First sums of the Thue-Morse sequence

Question: Let $t_n$ denote the $n^{\rm th}$ element of the Thue-Morse sequence, i.e., $t_n$ begins
$$
0,1,1,0,1,0,0,1,\ldots
$$
The first differences of this series are present in the OEIS as entry A029883. This sequence begins
$$
1, 0, -1, 1, -1, 0, 1, 0,\ldots
$$
I am however interested in the first sums of the Thue-Morse sequence, i.e., the sequence $s_n$ such that $s_n=t_n+t_{n-1}$ for all $n\geq1$. I have found no reference to this sequence in the OEIS. For info, $s_n$ begins:
$$
1, 2, 1, 1, 1, 0, 1, 2, \ldots
$$
It is easy to find some ''basic'' properties of this sequence based on those of $t_n$, but I was wondering whether there have already been some more in-depth studies about it, like for the ''first differences'' sequence.
Comment: can you find info about $s_n$ based on binary representation of $n$?
Comment: @mathworker21 Can you elaborate?
Comment: The Thue-Morse sequence $t_n = digitsum_2(n) \mod 2$ where $digitsum_b(n)$ is the digital sum of integer $n$ in base $b$.

A property of digital sums is that
$$digitsum_b(x + y) = digitsum_b(digitsum_b(x) + digitsum_b(y))$$

Try using that.
Answer: Warning. I considered the sequence $t_n + t_{n+1}$ instead of $t_n + t_{n-1}$, which is not defined for $n = 0$, but it is easy to make the translation.
It is shown in $[1]$ that the shift of a $q$-automatic sequence is $q$-automatic and that the sum of two $q$-automatic sequences is $q$-automatic.
Since $t_n$ is $2$-automatic, it follows that $s_n$ is $2$-automatic.
In this specific case, it is not too difficult to obtain the corresponding automata. Here is the automaton for $t_n$
$\qquad$
and the one for the shifted sequence $t_{n+1}$ (the initial state is $1$)
$\qquad$
Combinining the two automata gives
$\qquad$
which leads to the automaton for $s_n$ by adding the outputs (the initial state is $1$)
$\qquad$
For instance, for $n = 21$, the binary expansion is $10101$, and since $1 \cdot 10101 = 4$, one gets $s_{21} = 2$. Indeed,
\begin{align}
t &= 01101001100101101001011001101001 \dotsm \\
s &= 121110121011121110111\color{red}{2}101211101 \dotsm
\end{align}
You can certainly find many properties of $s_n$ from the knowledge of this automaton.
EDIT. In particular, if $n$ is even, then $s_n = 1$. If you consider only the odd positions, that is, the sequence $s_{2k+1}$, you obtain the OEIS sequence A316826
$$
210201210120210201202101 \dotsm
$$
obtained by removing the initial $3$ in the image of $3$ by iteration of the morphism $0 \to 02$, $1 \to 1012$, $2 \to 102012$ and $3 \to 32$.
$[1]$ S. Lehr, Sums and rational multiples of $q$-automatic sequences are $q$-automatic. Theoret. Comput. Sci. 108 (1993), no. 2, 385--391.
Comment: Thanks for the detailed answer. Does this approach make it possible to get a recurrence relation for s_n? Note that for the first differences sequence a_n we have a_4n = a_n, a_{4n+1} = a_{2n+1}, a_{4n+2} = 0, and a_{4n+3} = - a_{2n+1}.
Answer: First of all, the Thue-Morse sequence $(t_n)_{n\ge0}$ is defined by the recurrence:

$t_0=0$;
$t_{2n}=t_n$; and
$t_{2n+1}=1-t_n$.

Thus, to calculate $s_n=t_n+t_{n-1}$ it is natural to separate the cases when $n$ is even and odd.
If $n=2k$ then $s_n=t_{2k}+t_{2k-1}=t_k+(1-t_{k-1})=1+(t_k-t_{k-1})$, so this is essentially the same as the first difference sequence.
If $n=2k+1$ then $s_n=t_{2k+1}+t_{2k}=(1-t_k)+t_k=1$ is constant, so this is uninteresting.
Thus, my guess is that studying the first sum sequence is essentially equivalent to studying the first difference sequence, which is why there isn't much literature on it.
Comment: Makes sense, thanks

First sums of the Thue-Morse sequence


Remove specific li element from list when parsing page with simple_html_dom

Question: I am pulling some page with simple_html_dom and on a page there is a list of ul li elements which I need to pull, but problem is that these are basically video tags, which are combined with other elements that I don't need in that.
Here is an example of original page source:

Uploader:

Sarasubmit.

Tagged:

makeup,

cosmetic,

liner,

fresh,

girls,

fashion,

more tags.

So when I pull the page I tried using this to get the tags.
 $get_tags = $video_page_url->find('ul[id="video-tags"]', 0);

$post_tags_arr = array();
foreach($get_tags->find('a') as $tag) {
$post_tags_arr[] = $tag->plaintext;
}
$post_tags = implode(', ', $post_tags_arr);

This way I get all the a elements inside li and output text, but since profile name is also link and more tags is also link I get that 2 also so I end up with this.
sarasubmit, makeup, cosmetic, liner, fresh, girls, fashion, tags

Is there a way that I can just strip out tags and remove other elements so I end up like this:
 makeup, cosmetic, liner, fresh, girls, fashion,

Edit: Just to mention, username is not constant so it's changing depending of who uploaded video, and also some videos don't have tags at all, and some have more or less tags. So things are dynamic.
Answer: You may try something like this:
foreach($get_tags->find('li[!class] a') as $tag) {
    if($tag->plaintext != 'tags') $post_tags_arr[] = $tag->plaintext;
}

Instead of this:
foreach($get_tags->find('a') as $tag)
    $post_tags_arr[] = $tag->plaintext;
}

Update: I've tested:
$htmlStr = '

Uploader:

Sarasubmit.

Tagged:

makeup,

cosmetic,

liner,

fresh,

girls,

fashion,

more tags.

';

$html = str_get_html($htmlStr);
foreach($html->find('li[!class] a') as $tag) {
    if($tag->plaintext != 'tags') $post_tags_arr[] = $tag->plaintext;
}
print_r($post_tags_arr);

Output:
Array
(
    [0] => makeup
    [1] => cosmetic
    [2] => liner
    [3] => fresh
    [4] => girls
    [5] => fashion
)

So, try this:
$html = file_get_html($url);
foreach($html->find('li[!class] a') as $tag) {
    if($tag->plaintext != 'tags') $post_tags_arr[] = $tag->plaintext;
}

Check the manual.
Comment: It doesn't work, for some reason it returns nothing.
Comment: Can you gimme the `link/url` of the page that you are scrapping ?
Comment: Yea i also tried that but it's the same, i read the manual and apparently ! should exclude that li element but it returns empty tags. And i would rather not share link because it's an adult website. And the html of site is as i posted, i just changed tag names from adult to safe. And when i try 'li a' or just 'a' it works fine but returns all li elements.'li[class!="profile_name"] a' returns empty.


Differentiable unbounded function $f: (a, b)\to \mathbb R$ must have unbounded derivatives

Question: For a function $f: (a, b) \to \mathbb{R}$ that is unbounded and differentiable, how can you show, using the Mean Value Theorem, that its derivative is also an unbounded function?
As far as I have gotten is basically just the definition of unboundedness being when the function is not bounded.
Bounded meaning that $\exists M \in \mathbb{R}:  |f(x)| \leq M, \forall x \in X$, where $X$ is the set the function is defined on.
And the Mean Value Theorem being $f'(c) = \frac{f(b) - f(a)}{b-a}$ for some interval $(a,b)$.
But I am unsure how this applies to the whole function, $f(x)$, not just at the point $c$, and how this can be used to show that the derivative is unbounded.
Comment: I think you have described the MVT inside out. You **start** with an interval $(a,b),$ and some conditions on it, and this implies the existence of a $c$ such that etc.
Comment: What have you tried ? What happens if you apply the definition of unboundedness ?
Comment: When I read $\exists M \in \mathbb{R}:  |f(x)| \leq M, \forall x \in X$, I wonder: does this notation technically mean $\exists M \in \mathbb{R}:  (|f(x)| \leq M, \forall x \in X)$ or does it mean $(\exists M \in \mathbb{R}:  |f(x)| \leq M), \forall x \in X$? Or maybe technically it doesn't mean anything. For the meaning I think you wanted to convey, I would write $\exists M \in \mathbb{R}. \forall x \in X. |f(x)| \leq M.$
Answer: Note that it is crucial the domain of the function be a bounded open interval, because if the domain is $\Bbb{R}$ then the claim is false ($f(x)=x$ is unbounded on $\Bbb{R}$ yet its derivative is constant hence trivially bounded).
One way of phrasing the argument is contrapositively, and I find that simpler. So, we suppose $f'$ is bounded on $(a,b)$, say by $B$, and we want to show $f$ itself is bounded. So, fix an $x_0\in(a,b)$ (for example $\frac{a+b}{2}$... it doesn't really matter, just pick a point and keep it fixed for the rest of the discussion), and let $x\in (a,b)$ be arbitrary. Then,
\begin{align}
|f(x)-f(x_0)|\leq B|x-x_0|.
\end{align}
(if $x=x_0$ this inequality is trivially true, if $x<x_0$ use the mean-value theorem on the interval $(x,x_0)$ while if $x_0<x$ then use the mean-value theorem on $(x_0,x)$). In particular, by the reverse triangle inequality,
\begin{align}
|f(x)|&\leq |f(x_0)|+B|x-x_0|\\
&\leq |f(x_0)|+B(b-a).
\end{align}
Since $x\in (a,b)$ is arbitrary, we have that $f$ is bounded by $M:=|f(x_0)|+B(b-a)$.
The crux of this argument is that if $f'$ is bounded, then $f$ satisfies a Lipschitz condition, and therefore is bounded on every bounded interval.
Answer: Hints:
Since f is unbounded there is point $x_0$ such that $ |f(x_0)| > M$ for any $M >0.$ Now choose another point $x,$ which is different from $x_0$ (WLOG, we can make it smaller than $x_0$) such that $f(x)= k$ for some finite $k.$ Then apply MVT on the interval $ (x, x_0).$
Comment: But this isn't exactly the definition of unboundedness: $f$ is unbounded iff for all positive numbers $M$ there is an $x_0\in(a,b)$ such that $|f(x_0)|>M$.  Hence one should start with a generic $M$ instead of $x_0$.
Comment: Thank you for the hints! I am still unsure how to make the connection between unboundedness and the MVT.
Answer: Fix $M\in(0,\infty)$. Since $f$ is unbounded, then there exists an $x_1\in (a,b)$ such that $|f(x_1)|>M$. There also exists an $x_2\in (a,b)$ such that $|f(x_2)|>|f(x_1)|+M(b-a)$. By the mean value theorem, there exists a $c$ between $x_1$ and $x_2$ such that $$f'(c)=\frac{f(x_2)-f(x_1)}{x_2-x_1}$$
Now we have
$$\begin{align*}|f'(c)|
&=\left|\frac{f(x_2)-f(x_1)}{x_2-x_1}\right|\\
&\geq \frac{|f(x_2)|-|f(x_1)|}{|x_2-x_1|}\\
&> M\frac{(b-a)}{|x_2-x_1|}\\
&>M \end{align*}$$
since we have $$b-a>|x_2-x_1|>0\Longrightarrow \frac{b-a}{|x_2-x_1|}>1 $$
Comment: Thank you for this! Can I just ask why |(2)|>|(1)|+(−) ? I am unsure why we multiply M(b-a).
Comment: @FISR I used the unboundedness of $f$ to get $|f(x_2)|>|f(x_1)|+M(b-a)$ so that $|f(x_2)|-|f(x_1)|>M(b-a)$. if we did not multiply $M$ by $(b-a)$, then we would have $|f(x_2)|-|f(x_1)|>M$  so $$\frac{|f(x_2)|-|f(x_1)|}{|x_2-x_1|}>\frac{M}{|x_2-x_1|}$$ and $M/|x_2-x_1|$ is not necessarily larger than $M$.
Answer: Let $c=(a+b)/2$ and let $d=(b-a)/2.$
For any $r>0,$ take some  $x\in (a,b)$ with $|f(x)|>|f(c)|+d\cdot r.$ Then $x\ne c$ because $|f(x)|\ne|f(c)|.$ So we have $$\frac {|f(x)-f(c)|}{|x-c|}\ge \frac {|f(x)|-|f(c)|}{|x-c|}>$$ $$>\frac {d\cdot r}{|x-c|}>$$ $$>\frac {d\cdot r}{d}=r.$$ And there exists $y$ between $x$ and $c$ with $\frac {|f(x)-f(c)|}{|x-c|}=|f'(y)|.$
Comment: BTW the converse is false: There exists a strictly increasing differentiable $f:\Bbb R\to \Bbb R$ such that $f'$ is  unbounded on the interval $(0,1)$ and such that $f'(x)$ is continuous except at the point $x=1$.


Average treatment effect on the treated

Question: There is something conceptual I don't understand with average treatment effect on the treated. Say you have two binary outcomes $Y_i(W_i)$ in which $W_i$ is either 0 or 1 (treatment). So I either observe $Y_i(1)$ or $Y_i(0)$.
What I am not sure I understand is what is $E(Y_i(0)|W_i=1)$. Since $Y_i(0)$ is a random draw from the population who did not receive a treatment, I am not sure what the expectation of this given treatment means. In other words conditioning on treatment while drawing outcomes from the population who didn't receive treatment doesn't make sense to me.
I guess I am missing something important here.
Answer: Rubin explains in his great free book, Basic Concepts of Statistical Inference for Causal Effects in Experiments and Observational Studies (pdf), what's called "The fundamental problem of causal inference" (see, e.g., p. 4). I'd suggest starting form there.
In short: the only way to truly assess a causal effect is to compare things that don't really exist - potential outcomes. The observed and the unobserved (usually, the mean is used as a representative statistic).

Average treatment effect on the treated


SELECT em uma RELAÇÃO com AUTO-RELACIONAMENTO(Verificando Occorrências)

Question: Estou com dificuldade em fazer uma consulta.
A situação é a seguinte, preciso que o banco retorne todos os nomes das disciplinas que não tenham pré-requisitos e que não sejam pré-requisitos.
A relação é esta:
/* Create a table */
CREATE TABLE DISCIPLINA(CodD char(2) PRIMARY KEY,
NomeD varchar(60),
CargaD int,
AreaD varchar(60),
PreReqD char(2),
FOREIGN KEY (PreReqD) REFERENCES DISCIPLINA(CodD));

/* Create few records in this table */
INSERT INTO DISCIPLINA VALUES('D1','TLP1',          2,  'Computação',   'D2');
INSERT INTO DISCIPLINA VALUES('D2','Cálculo 1',     4,  'Matemática',   NULL);
INSERT INTO DISCIPLINA VALUES('D3','Inglês',        2,  'Humanas',      NULL);
INSERT INTO DISCIPLINA VALUES('D4','Ed Física',     3,  'Saúde',        NULL);
INSERT INTO DISCIPLINA VALUES('D5','G Analítica',   5,  'Matemática',   'D2');
INSERT INTO DISCIPLINA VALUES('D6','Projeto Final', 6,   NULL,          'D1');

Eu tentei desta forma e também com LEFT JOIN, mas não obtive exito.
SELECT DISTINCT D1.NomeD
FROM DISCIPLINA D1, DISCIPLINA D2
WHERE D1.CodD != D2.PreReqD AND D2.PreReqD IS NULL;

Comment: Então só é preciso retornar o que tiver NULL, certo?
Comment: Olá Lúcio, no caso não. Pois Cálculo 1 é pré-requisito de outra matéria, então não poderia retorná-la.
Answer: Voce pode fazer com LEFT JOIN mais DISTINCT
SELECT DISTINCT D.NomeD
  FROM Disciplina D
  LEFT JOIN Disciplina DPai ON DPai.PreReqD = D.CodD
 WHERE D.PreReqD IS NULL AND DPai.CodD IS NULL

UPDATE:
Seleciona de forma distinta apenas nomes de disciplinas
SELECT DISTINCT D.NomeD

Da tabelas de disciplinas
  FROM Disciplina D

Que possua (JOIN) ou não (LEFT) relação com outras disciplinas (PAI) que tem a disciplina principal (FILHA) como PréRequesito ( DPai.PreReqD = D.CodD )
  LEFT JOIN Disciplina DPai ON DPai.PreReqD = D.CodD

Onde a disciplina não possua pré requisitos, e não seja pré requisito de nenhuma outra disciplina
 WHERE D.PreReqD IS NULL AND DPai.CodD IS NULL

Ajudou? :)
Veja funcionando no SqlFiddle
Comment: Olá Thiago, funcionou perfeitamente. Você poderia dar uma explicação da lógica dessa Query? Muito obrigado pela ajuda.
Comment: @WellingtonPerez, fiz um update com mais explicações.
Comment: Obrigado Thiago, cheguei até antes do where. Obrigado pela explicação!!!
Answer: Tente:
 SELECT NomeD
FROM DISCIPLINA d
WHERE d.PreReqD IS NULL
  AND NOT EXISTS
    (SELECT 1
     FROM DISCIPLINA d1
     WHERE d1.PreReqD = d.CodD)

Veja funcionando no SqlFiddle.
Comment: @ThiagoLunardi verdade, eu fiz até uma pergunta aqui no SO que explica isso .http://pt.stackoverflow.com/questions/62925/not-in-ou-not-exists-qual-usar. Pergunta editada, Obrigado.
Comment: Funciona, mas subquery no `WHERE` faz com que a subquery seja executada a cada registro de cada tabela referenciada em `FROM`. Se mesmo assim quiser, substitua `NOT IN` por `NOT EXISTS`, será mais performático.
Comment: Olá Merconi, obrigado pela resposta. Funcionou aqui também!
Comment: @WellingtonPerez que bom que tenha ajudado. :)
Answer:   SELECT D1.NomeD,  D2.NomeD
    FROM disciplina D1, disciplina D2
      WHERE  D2.codD = D1.PrereqD ;


How to get a pattern into a written text via CSS?

Question: some days ago I saw a website where a written text had a background-image in.
Is it already possible with CSS to get a background-image into a text?
I do not want a background-image behind the text. I have no idea to achieve this. :(
Thanks gago!
http://img221.imageshack.us/img221/232/examplewf.png
Comment: get a background-image into a text? what do you mean?
Comment: It could be a custom font too.
Comment: I think he wants the text to go around (probably either side of) the image, rather than having it as a background image and the text going over the top of it.
Answer: @gago; you can use css3 background clip proprty.
for example
css:
p {
   color: white;
   background: url(images/fire.jpg) no-repeat;
   -webkit-background-clip: text;
   -webkit-text-fill-color: transparent;
}

check this link for more http://css-tricks.com/7850-image-under-text/
Comment: I would still restrain myself from this due to bad browser support. Not only that but if i recall it right, this fails horribly in ie9.
Comment: you have to explain it's in your question at least which browser you want to support .this property support by moz & webkit browsers.
Comment: When it is not specified i usually asume that cross browser support is wanted cause it just makes sense. And if not.. then he would mention it. And im not the OP.
Comment: check your tags man you give  css3 on it
Comment: Either way, i would not use non-crossbrowser solution myself and I dont recommend them to others unless they ask for them directly. And im still not the OP.
Comment: This does not work for chrome right?
Comment: It works for both Chrome and Safari.
Answer: -webkit-background-clip does the job

HTML

BBrainz:: An   Amazing Touch

CSS
    header span:first-child
    {
     font-size: 7em;
     color: white;
     background: url("strip.png") repeat center center;
     background-size: 6px 6px;
      background-clip: content-box;
     -webkit-text-fill-color: transparent;
     -webkit-background-clip: text;
    }

View result

This method is only supported by webkit browsers which means you must set a color property and background-clip as content-box incase it fails in a non-webkit browser
Answer: The example image that you have Could be achieved with a font that has such a pattern in it. For that you would need to use css @font-face or some other way of using custom fonts.

Aside from that I'd say that your only option is to make image of a text with a specific background/styling.


How to execute scrapy python in a javascript file?

Question: I have a python script that I launched with the command scrapy crawl mynamefile.
I would like to run the python cli command scrapy crawl from a js file in my node js application, then display it in the console.
The problem is that I don't how to import the scrapy python library in node.
Thanks for your help!
Comment: Please, provide your code examples for both js/python, but anyway, you can check this guide https://medium.com/@HolmesLaurence/integrating-node-and-python-6b8454bfc272
Answer: I don't think it is a good idea to run Python code from NodeJS. If you are for some reason forced to do that, you probably need to call Python script in a child process (see for example this article).
Alternatively, you might use something like Scrapyrt, which exposes HTTP API for your Scrapy project and provides on-demand scraping ability.
Yet the best option seems to be using some native JavaScript scraping solution, like Apify.


Anexar uma foto ao email

Question: Bom dia a todos, a duvida é a seguinte.
Tenho alguns campos básicos(nome, telefone etc), e uma opção para tirar fotos. Eu já tenho funcionando o envio de e-mail e o botão para tirar foto, consigo pegar os valores de todos os campos e tirar a foto inclusive, porem quero saber como que eu faço para anexar a foto neste e-mail...
Esses são os métodos para tirar a foto e salva-la no cartão de memoria do celular.
public void abrirCamera(){
        File picsDir =       Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File imageFile = new File(picsDir, "foto.jpg");
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
        startActivity(i);
    }

public void takePhoto(View view)
{
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    File photo = new File(Environment.getExternalStoragePublicDirectory
            (Environment.DIRECTORY_PICTURES), "Pic.jpg");

    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    imageUri = Uri.fromFile(photo);

    startActivityForResult(intent, TAKE_PICTURE);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {

        case TAKE_PICTURE:
            if (resultCode == Activity.RESULT_OK) {

                Uri selectedImage = imageUri;
                getActivity().getContentResolver().notifyChange(selectedImage, null);

                ImageView imageView = (ImageView)  getActivity().findViewById(R.id.ImageView);

                ContentResolver cr = getActivity().getContentResolver();
                Bitmap bitmap;

                try {
                    bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);

                    imageView.setImageBitmap(bitmap);
                    fotoCart.setText("");
                    //Toast.makeText(getActivity(), selectedImage.toString(), Toast.LENGTH_LONG).show();

                } catch (Exception e) {
                    //Toast.makeText(getActivity(), "Failed to load", Toast.LENGTH_SHORT).show();
                    Log.e("Camera", e.toString());
                }
            }
    }

Comment: Pode adicionar algum trecho de código para ajudarmos a evolui-lo?
Comment: Esses métodos são vinculados a uma outra classe chamada Camera. Mas acho que é possível obter a foto sem ter de acessar essa outra classe...
Comment: E com Javamail? Tenho uma aplicação que fiz com Javamail!
Answer: Você irá precisar ciar uma Intent colocando a Uri de sua foto como EXTRA_STREAM.
Tente algo parecido:
private void enviaEmail(Uri uriDaSuaFoto) {
    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

    //Definindo que o conteúdo sera uma imagem
    emailIntent.setType("application/image");

    //Qual e-mail a ser enviado
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, "email@example.com");

    //Titulo do e-mail
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Titulo");

    //Corpo do e-mail
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Corpo do email");

    //Aqui você coloca a uri da sua imagem
    emailIntent.putExtra(Intent.EXTRA_STREAM, uriDaSuaFoto);

    //Criando um dialog para o usuário poder escolher qual aplicação enviar o e-mail
    startActivity(Intent.createChooser(emailIntent, "Enviar e-mail com"));
}

Comment: Cara, muuuito obrigado me ajudou pra caramba... Deu tudo certo, vaaleu mesmo.

Anexar uma foto ao email


Solving systems of mods (Chinese Remainder Theorem)

Question:
Solve the following system of mods for $x$.
$3x$ $\equiv$ $5\ (mod \ 7)$
  $7x$ $\equiv$ $5\ (mod \ 15)$

This is my current work, but am stuck about 75% of the way through:
1) Find multiplicative inverse of $7\  mod\  15 $
$7b$ ($mod$ 15) = 1
  so $b$ = $13$.
$13$ * $7x$ $\equiv$ $5$ * $13$ ($mod \ 15$)
$91x$ $\equiv$ $65$ $ mod \ 15$
$x$ $\equiv$ $5$ $ mod\ 15$
2) Find multiplicative inverse of $3\ mod\ 7%$
$3b$ ($mod$ 7) = 1
  so $b$ = $5$.
$5$ * $3x$ $\equiv$ $5$ * $5$ ($mod \ 7$)
$15x$ $\equiv$ $25$ $ mod \ 7$
$x$ $\equiv$ $4$ $ mod\ 7$
3)  Substitution method to solve for $x$
$x$ $\equiv$ $4$ $ mod\ 7$
$x$ =  $7a+4 $  $ \equiv$ $5 \ (mod \ 15)$
The answer to this problem, according to my textbook, is $x \equiv 95 (mod \ 105)$. The $105$ makes sense since its the LCM of 15 and 7. But what do I do now? Find the multiplicative inverse of 7 mod 15, so let the coefficient of $a$ be 1 and then solve for $x$?
Comment: https://en.m.wikipedia.org/wiki/Chinese_remainder_theorem
Answer: You're on the right track. Now just compute the value of $a$ modulo $15$ from $7a + 4 \equiv 5 \pmod{15}$ and the you would get that $a$ is of the form $15k + b$ and now just substitute in $x = 7a + 4$.
Comment: @JohnLocke $b$ is some value, which you should find. The form follows from the condition. In fact you have that $7a \equiv 1 \pmod{15}$, so you get that $a \equiv 1 \pmod{15} \iff a = 15k + 13$, now just substitute in $x = 7a + 4$
Comment: Why would we get that $a$ is of the form $15k+b$?
Answer: The inverse of $3 \ (mod \ 7)$ is $5$ since $3\cdot5 = 15$ and $15 \ (mod \ 7) \equiv 1 \ (mod \ 7)$, therefore the first equation is equivalent to $$x \ \equiv \ 25 \ (mod \ 7) \ \equiv \ 4 \ (mod \ 7)$$
and this can be seen as $x$ is of the form $4 + 7k, \ k \in \mathbb{Z}$. With this, we go to the other equation.
Now, we have $$ 7x \ \equiv \ 5 \ (mod \ 15) \iff 28 + 49k \ \equiv \ 5 \ (mod \ 15)$$
Reducing the actual equation: $$k \ \equiv \ 13 \ (mod \ 15)$$
hence $k$ is of the form $13 + 15q, \ q \in \mathbb{Z}$. So, $$x = 4 + 7k = 95 + 105q$$ and this is equivalent to $x \ \equiv \ 95 \ (mod \ 105)$.


How to generate cowboy SSL certificates?

Question: In cowboy's ssl directory I see 3 files
cowboy-ca.crt,  server.crt and  server.key.
Probably somewhere the directory they have the cowboy-ca.key which is not needed.
I can guess that cowboy-ca.crt is the public key of some default CA, and that is being used to sign the server.crt using csr file for server's key pair, and when the client connects to cowboy it downloads and installs the server.crt file to establish secure connections to server, am I correct?
The question is how do I generate all these there files using openssl and my own CA?
Comment: Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask. Also see [Where do I post questions about Dev Ops?](http://meta.stackexchange.com/q/134306).
Answer: There are tutorials on the net for this, but I happen to have a record from doing it before. It has quite a bit more than you need, but will show you how to achieve the basics of creating your own CA and certificates signed from it. My record, pasted below, creates a CA, creates an intermediate CA signed by the CA, and finally creates a certificate that can be used on a server. You don't need the intermediate CA obviously, so you should skip the middle bit and sign your final / end certificate with your root CA instead of the intermediate CA, so for example, when creating end.crt, instead of signing with ../inter_ca/inter.key, use ../root_ca/rootca.key, etc.
I'm assuming you are asking the right correct question here, and that a self signed certificate really is what you want.
After the creation of the certificates and keys, there is also guidance on configuring Apache, and a description of how to use the OpenSSL tools to verify that it is working correctly (on any SSL TCP connection, so that's applicable to Cowboy or anything else too). This will show you the trust chain, though yours will be depth 1 instead of depth 2 because you'll omit the intermediate CA.
Create some directories to work with:
mkdir inter_ca_demo
cd inter_ca_demo
mkdir root_ca inter_ca end_cert
cd root_ca

Create a key:
openssl genrsa -out rootca.key 2048

Output will be something like:
Generating RSA private key, 2048 bit long modulus
...........................................................+++
.............................+++
e is 65537 (0x10001)

Self sign it to create your root CA certificate (you will have to enter various information that will be encoded into the certificate):
openssl req -x509 -new -nodes -key rootca.key -days 1024 -out rootca.pem

It should look something like (here you can see what I entered):
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:GB
State or Province Name (full name) [Some-State]:London
Locality Name (eg, city) []:London
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Method Analysis Ltd
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:methodanalysis.com
Email Address []:firstname.lastname@example.com

Before moving on to the intermediate you must rename, copy or create a link to the root certificate so that it can be found by way of a hash algorithm. This is to make sure performance isn't degraded if there are a lot of trusted certificates in your CA path. To do this you must find out what the hash is with the following command:
openssl x509 -noout -hash -in rootca.pem

The output should be something like:
03ed4e37

Then create the link, adding a .0 to YOUR HASH (as output from the previous command):
ln -s rootca.pem 03ed4e37.0

Now create the intermediate CA key and a CSR (Certificate Signing Request) (you will have to enter various information that will be encoded into the certificate):
cd ../inter_ca
openssl genrsa -out inter.key 2048
openssl req -new -key inter.key -out inter.csr

It should look something like this:
$ openssl genrsa -out inter.key 2048
Generating RSA private key, 2048 bit long modulus
.........................................+++
..............................................................+++
e is 65537 (0x10001)
$ openssl req -new -key inter.key -out inter.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:GB
State or Province Name (full name) [Some-State]:London
Locality Name (eg, city) []:London
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Intermediate certificates R US Ltd
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:intermediatecasrus.com
Email Address []:email@example.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Now create a file (v3x509extensions.txt) which includes data that indicates this should be an intermediate CA, then generate the intermediate certificate, signing with your root CA:
echo 'basicConstraints=CA:TRUE' > v3x509extensions.txt
openssl x509 -req -extfile v3x509extensions.txt -in inter.csr -CA ../root_ca/rootca.pem -CAkey ../root_ca/rootca.key -CAcreateserial -out inter.crt -days 200

It should look something like this:
Signature ok
subject=/C=GB/ST=London/L=London/O=Intermediate certificates R US firstname.lastname@example.com
Getting CA Private Key

Now create your final key (that you are going to use for an SSL website (for example)), create a CSR from it, and sign it with your intermediate certificate, generating a new certificate:
cd ../end_cert
openssl genrsa -out end.key 2048
openssl req -new -key end.key -out end.csr
openssl x509 -req -in end.csr -CA ../inter_ca/inter.crt -CAkey ../inter_ca/inter.key -CAcreateserial -out end.crt -days 500

It should look something like this:
$ openssl genrsa -out end.key 2048
Generating RSA private key, 2048 bit long modulus
................................................+++
.....................................................+++
e is 65537 (0x10001)
$ openssl req -new -key end.key -out end.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:GB
State or Province Name (full name) [Some-State]:London
Locality Name (eg, city) []:London
Organization Name (eg, company) [Internet Widgits Pty Ltd]:End User Ltd
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:intermediatecademo-enduser.com
Email Address []:firstname.lastname@example.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
$ openssl x509 -req -in end.csr -CA ../inter_ca/inter.crt -CAkey ../inter_ca/inter.key -CAcreateserial -out end.crt -days 500
Signature ok
subject=/C=GB/ST=London/L=London/O=End User firstname.lastname@example.com
Getting CA Private Key

At this point, you can check things look ok by verifying the trust chains, here I concat the intermediate and the 'end' certificates, and then verify them using only the root CA path (remember the 'end' certificate can't be verified without the intermediate CA, so it must be given with the 'end' certificate):
cat ../inter_ca/inter.crt end.crt | openssl verify -CApath ../root_ca

The output should be:
stdin: OK

If you used these keys with apache for example, you could configure them like this:
SSLCertificateFile       FULL_PATH_TO/inter_ca_demo/end_cert/end.crt
SSLCertificateKeyFile    FULL_PATH_TO/inter_ca_demo/end_cert/end.key

SSLCertificateChainFile  FULL_PATH_TO/inter_ca_demo/inter_ca/inter.crt

SSLCACertificatePath     FULL_PATH_TO/inter_ca_demo/root_ca

Apache will now provide the intermediate certificate along with its own, which allows a web client to perform the same sort of verification (along with other checks) as above using 'openssl verify'.
If you did use these certificates with apache, and you create a website with a name 'intermediatecademo-enduser.com' in keeping with the 'end' certificate you created, you can also use openssl to verify the certificates from a clients perspective:
openssl s_client -connect intermediatecademo-enduser.com:443 -CApath root_ca -verify 5

Output should be something like this:
verify depth is 5
CONNECTED(00000004)
depth=2 C = GB, ST = London, L = London, O = Method Analysis Ltd, CN = methodanalysis.com, emailAddress = firstname.lastname@example.com
verify return:1
depth=1 C = GB, ST = London, L = London, O = Intermediate certificates R US Ltd, CN = intermediatecasrus.com, emailAddress = email@example.com
verify return:1
depth=0 C = GB, ST = London, L = London, O = End User Ltd, CN = intermediatecademo-enduser.com, emailAddress = firstname.lastname@example.com
verify return:1
---
Certificate chain
 0 s:/C=GB/ST=London/L=London/O=End User firstname.lastname@example.com
   i:/C=GB/ST=London/L=London/O=Intermediate certificates R US email@example.com
 1 s:/C=GB/ST=London/L=London/O=Intermediate certificates R US email@example.com
   i:/C=GB/ST=London/L=London/O=Method Analysis email@example.com
---
Server certificate

...
...
...

    Start Time: 1445696823
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---

It will hang now, waiting for data to be sent. You can just CTRL+C to quit.
Answer: You're basically right about the certificate relationship; there's a server certificate and private key, and a CA certificate.
Since they're only intended for test purposes, I assume that the author of cowboy didn't bother including the CA private key that he used to generate the server certificate.
There's nothing special about cowboy when it comes to SSL certificates. Assuming that you're looking at the ssl_hello_world example, you can see the certificates being used in ssl_hello_world_app.erl.
From there, those SSL options are passed to the Erlang SSL application, which is documented here.
The documentation states (though it's not totally obvious) that these are standard PEM-encoded certificate and key files. You can generate them by using OpenSSL, for example.


Java Thread Start-Stop-Start on same button click

Question: I am creating a simple java program with a GUI built with the help of window builder. The GUI consists of just a button.
On button click,start a thread that will print to the random number infinitely until it is stopped by clicking the same button again.
Here is my code
LoopTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoopTest extends JFrame implements ActionListener {//******
    private JButton startB, stopB;
    private JTextArea oa;
    Start sta;

    public LoopTest(){
        super("Final Exam: Question ");

        Container c = getContentPane();
        c.setLayout(new FlowLayout());

        startB = new JButton("START"); c.add(startB);

        stopB = new JButton("STOP"); c.add(stopB);

        oa = new JTextArea(5,20); c.add(oa);
        c.add(new JScrollPane(oa));

        registerEvents();
        sta = new Start("Loop", oa);

    }
    public void registerEvents(){
        startB.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent ae){
                        if(startB.isEnabled() == true )
                            sta.setLoopFlag(true);
                        if(!sta.isAlive())
                            sta.start();
                        startB.setEnabled(false);

                    }
                }
        );

        stopB.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent ae){
                        if(stopB.isEnabled()==true){
                            sta.setLoopFlag(false);

                        }

                    }

        }

        );
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }
    public static void main(String[] args){
        LoopTest app = new LoopTest();
        app.setSize(300,300);
        app.setLocationRelativeTo(null);
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.setVisible(true);
    }

}

Start.java
public class Start extends Thread {

private JTextArea ta;
    private boolean loopFlag;

    public Start(String name, JTextArea ta){
        super(name);
        this.ta = ta;
        ta.setText("");
        loopFlag = true;
    }
    public void run(){
        int num=0;
        while(true)
            while(loopFlag){
                num = 1+ (int)(Math.random()*100);
                ta.append(num + "\n");
            }
    }

    public void setLoopFlag(boolean value){
        loopFlag = value;
    }

}

Stop.java
public class Stop extends Thread {
    public Stop( String name ){
        super(name);
    }
    public void run(){

    }
}

Thanks in advance.
Comment: What is your question? You cannot stop a thread by simply "replacing your reference to it". `Start` never stops due to the external (useless) loop. Please, make a self-explanatory question, possibly an [mvce].
Answer: Your code breaks Swing threading rules as you're making mutational changes to Swing components off of the Swing event thread.
Suggestions:

Never extend Thread. It's almost always better to implement Runnable and use the Runnable in a Thread.
Avoid making Swing calls, other than repaint() off of the Swing event thread.
Your while (true) is a "tight" loop -- it has no Thread.sleep within it, and that means that it risks typing up the CPU in its tight loop, something that can hamper your program and your computer.
Best to avoid using direct background threading altogether here as your code issue can be solved much more easily and cleanly by using a Swing Timer. Please check the Swing Timer Tutorial
You can easily start and stop this Timer by calling its start() and stop() methods.
I would also use a JList preferentially over a JTextArea since it can more easily handle large amounts of data.
I also like using AbstractActions rather than ActionListeners for my JButton, and this problem lends itself nicely to their use. You can create an Action for start and one for stop and simply swap out the button's actions.

For example:
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class StartStop extends JPanel {
    private static final int TIMER_DELAY = 300;
    private StartAction startAction = new StartAction();
    private StopAction stopAction = new StopAction();
    private JButton button = new JButton(startAction);
    private DefaultListModel<Integer> model = new DefaultListModel<>();
    private JList<Integer> jList = new JList<>(model);
    private Timer timer = new Timer(TIMER_DELAY, new TimerListener());

    public StartStop() {
        JPanel btnPanel = new JPanel();
        btnPanel.add(button);

        jList.setFocusable(false);
        jList.setVisibleRowCount(10);
        jList.setPrototypeCellValue(100000);
        JScrollPane scrollPane = new JScrollPane(jList);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.PAGE_END);
    }

    private class TimerListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            int num = 1 + (int) (Math.random() * 100);
            model.addElement(num);
        }
    }

    private class StartAction extends AbstractAction {
        public StartAction() {
            super("Start");
            putValue(MNEMONIC_KEY, KeyEvent.VK_S);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            timer.start();
            button.setAction(stopAction);
        }
    }

    private class StopAction extends AbstractAction {
        public StopAction() {
            super("Stop");
            putValue(MNEMONIC_KEY, KeyEvent.VK_S);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            timer.stop();
            button.setAction(startAction);
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Start Stop");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new StartStop());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}


Remove Shadow From AutoCompleteTextView Dropdown

Question: I am trying to create a full width auto complete text field.
So far, I think I have the text field itself looking right. The problem is with the auto complete popup. It has this very bold shadow all around it and I just can't get rid of it.
 Don't get me wrong, I still want the shadow, but a subtle shadow, only on the bottom of the popup, not all around it (especially not at the top, that's really weird).
Something like this:

Here's what mine looks like (sorry for giant image):

The Code
activity_main.xml:
<AutoCompleteTextView
    android:id="@+id/actvSearch"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="8dp"
    android:background="@drawable/full_width_input"
    android:completionThreshold="1"
    android:hint="Search a movie..."
    android:textColorHint="#BDBDBD"
    android:elevation="0dp"
    android:popupBackground="@android:color/white" />

full_width_input.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-1dp" android:right="-1dp" android:left="-1dp">
        <shape android:shape="rectangle">
            <padding android:bottom="20dp" android:top="20dp" android:left="16dp" android:right="16dp" />
            <solid android:color="@android:color/white" />
            <stroke android:width="1dp" android:color="#E0E0E0" />
        </shape>
    </item>
</selector>

Answer: use android:popupElevation="0"
<AutoCompleteTextView
    android:id="@+id/actvSearch"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="8dp"
    android:background="@drawable/full_width_input"
    android:completionThreshold="1"
    android:hint="Search a movie..."
    android:textColorHint="#BDBDBD"
    android:popupElevation="0dp"
    android:popupBackground="@android:color/white" />

Answer: This question is a bit old already, but anyways. I just crossed through this problem. I was using android:popupBackground="@null" for my autocomplete, but it DOES NOT WORK PROPERLY ON ANDROID 6 (I just tested it).
Instead of using android:popupBackground="@null", use android:popupBackground="@android:color/transparent" (it will also work for the Android 4.4 and 5.0).
Answer: If we set android:popupBackground="@null" in AutoCompleteTextView and set background for the adapter row as white, we can achieve this. Hope it will help you.
Comment: Thanks for the answer! I tried your solution and it's almost there. There is no shadow, but it seems like the white background for each row doesn't affect the actual background of items. Right now, it's like the list has a transparent background.
Answer: What I ended up doing is manually creating the auto complete using a ListView.
It took a bit of hacking around but now I have the exact design I had in mind.


how to call View controller of MainStoryBoard from UI cellView xib

Question: The problem i want to call view controller of MainStoryBoard.
i have created UIcellView in xib file and on that have button so  i want to move on AddLocationVC viewController when i pressed the button.
I have written some code
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:Nil];

AddLocationVC *view = [storyBoard instantiateViewControllerWithIdentifier:@"AddLocation"];

its not worked when i pressed the button its does not redirect me on view controller AddLocationVC but controller is coming in this section of code.
Comment: Tell your exact problem.You did not ask correctly which you want.
Answer: The most efficient way of doing this would be to use protocols or blocks. With delegate protocol the steps would be:

Define a DelegateProtocol in your custom cell class
In cellForItem/RowAtIndexPath: make your ViewController the delegate of your cell and implement the protocol in it. Here you'll instantiate the new ViewController and present/push it
On button tap call the delegate method


Selenium RC htmlsuite error

Question: I am trying to use Selenium RC but i keep getting this error whenever i start the server.
The command i use is
java -jar selenium-server.jar -multiwindow -htmlsuite *iexplore http://localhost/app testsuite.html testsuiteoutfile.html

<code>    Starting Selenium Server....
    18:14:29.086 INFO - Java: Sun Microsystems Inc. 10.0-b23
    18:14:29.086 INFO - OS: Windows XP 5.1 x86
    18:14:29.102 INFO - v2.0 [a2], with Core v2.0 [a2]
    18:14:29.227 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
    18:14:29.227 INFO - Version Jetty/5.1.x
    18:14:29.242 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver]
    18:14:29.242 INFO - Started HttpContext[/selenium-server,/selenium-server]
    18:14:29.242 INFO - Started HttpContext[/,/]
    18:14:29.336 INFO - Started org.openqa.jetty.jetty.servlet.ServletHandler@2bbd86
    18:14:29.352 INFO - Started HttpContext[/wd,/wd]
    18:14:29.367 INFO - Started SocketListener on 0.0.0.0:4444
    18:14:29.367 INFO - Started org.openqa.jetty.jetty.Server@14ed9ff
    HTML suite exception seen:
    java.lang.RuntimeException: sessionId 69367 doesn't exist; perhaps this session was already stopped?
            at org.openqa.selenium.server.FrameGroupCommandQueueSet.getQueueSet(FrameGroupCommandQueueSet.java:220)
            at org.openqa.selenium.server.browserlaunchers.HTABrowserLauncher.writeSessionExtensionJs(HTABrowserLauncher.java:117)
            at org.openqa.selenium.server.browserlaunchers.HTABrowserLauncher.createHTAFiles(HTABrowserLauncher.java:102)
            at org.openqa.selenium.server.browserlaunchers.HTABrowserLauncher.launch(HTABrowserLauncher.java:63)
            at org.openqa.selenium.server.browserlaunchers.HTABrowserLauncher.launchHTMLSuite(HTABrowserLauncher.java:155)
            at org.openqa.selenium.server.htmlrunner.HTMLLauncher.runHTMLSuite(HTMLLauncher.java:121)
            at org.openqa.selenium.server.htmlrunner.HTMLLauncher.runHTMLSuite(HTMLLauncher.java:166)
            at org.openqa.selenium.server.SeleniumServer.runHtmlSuite(SeleniumServer.java:545)
            at org.openqa.selenium.server.SeleniumServer.boot(SeleniumServer.java:239)
            at org.openqa.selenium.server.SeleniumServer.main(SeleniumServer.java:198)
    18:14:30.320 INFO - Shutting down...
</code>
I tried to use a different port number and in debug mode and the output is shown here
No there are no other tests or applications running on port 4444. I even tried restarting my machine just to confirm.
Here is the error again when i tried to start it using port 6565 and in debug mode
<code>    C:\workarea\wip\SeleniumSuite>runenssuite all
    Starting Selenium Server....
    18:35:06.088 INFO - Java: Sun Microsystems Inc. 10.0-b23
    18:35:06.104 INFO - OS: Windows XP 5.1 x86
    18:35:06.104 INFO - v2.0 [a2], with Core v2.0 [a2]
    18:35:06.119 INFO - Selenium server running in debug mode.
    18:35:06.135 DEBUG - add component: firstname.lastname@example.com:6565
    18:35:06.166 DEBUG - add component: org.openqa.jetty.http.ResourceCache@18a47e0
    18:35:06.182 DEBUG - add component: org.openqa.selenium.server.ProxyHandler in HttpContext[/,/]
    18:35:06.182 DEBUG - add component: HttpContext[/,/]
    18:35:06.182 DEBUG - Added HttpContext[/,/] for host *
    18:35:06.182 DEBUG - add component: org.openqa.jetty.http.ResourceCache@89fbe3
    18:35:06.197 DEBUG - added SC{BASIC,null,user,CONFIDENTIAL} at /tests/html/basicAuth/*
    18:35:06.213 DEBUG - add component: org.openqa.jetty.http.handler.SecurityHandler in HttpContext[/selenium-server,/selenium-server]
    18:35:06.213 DEBUG - add component: org.openqa.selenium.server.StaticContentHandler in HttpContext[/selenium-server,/selenium-server]
    18:35:06.229 DEBUG - add component: org.openqa.selenium.server.SessionExtensionJsHandler in HttpContext[/selenium-server,/selenium-server]
    18:35:06.229 DEBUG - add component: org.openqa.selenium.server.htmlrunner.SingleTestSuiteResourceHandler in HttpContext[/selenium-server,/selenium-ser
    ver]
    18:35:06.229 DEBUG - add component: org.openqa.selenium.server.htmlrunner.SeleniumHTMLRunnerResultsHandler@1bf6770
    18:35:06.244 DEBUG - add component: org.openqa.selenium.server.CachedContentTestHandler@94948a
    18:35:06.244 DEBUG - add component: HttpContext[/selenium-server,/selenium-server]
    18:35:06.244 DEBUG - Added HttpContext[/selenium-server,/selenium-server] for host *
    18:35:06.260 DEBUG - add component: org.openqa.jetty.http.ResourceCache@c51355
    18:35:06.276 DEBUG - add component: org.openqa.selenium.server.SeleniumDriverResourceHandler in HttpContext[/selenium-server,/selenium-server]
    18:35:06.276 DEBUG - add component: HttpContext[/selenium-server/driver,/selenium-server/driver]
    18:35:06.291 DEBUG - Added HttpContext[/selenium-server/driver,/selenium-server/driver] for host *
    18:35:06.291 DEBUG - add component: org.openqa.jetty.http.ResourceCache@253498
    18:35:06.307 DEBUG - add component: WebDriver remote server
    18:35:06.322 DEBUG - add component: org.openqa.jetty.jetty.servlet.HashSessionManager@16930e2
    18:35:06.322 DEBUG - add component: org.openqa.jetty.jetty.servlet.ServletHandler@108786b
    18:35:06.354 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:6565/wd/hub
    18:35:06.354 DEBUG - add component: HttpContext[/wd,/wd]
    18:35:06.354 DEBUG - Added HttpContext[/wd,/wd] for host *
    18:35:06.369 DEBUG - Starting org.openqa.jetty.jetty.Server@18eb9e6
    18:35:06.369 INFO - Version Jetty/5.1.x
    18:35:06.369 DEBUG - LISTENERS: [email@example.com:6565]
    18:35:06.385 DEBUG - HANDLER: {null={/selenium-server/driver/*=[HttpContext[/selenium-server/driver,/selenium-server/driver]], /selenium-server/*=[Htt
    pContext[/selenium-server,/selenium-server]], /=[HttpContext[/,/]], /wd/*=[HttpContext[/wd,/wd]]}}
    18:35:06.385 DEBUG - Starting HttpContext[/selenium-server/driver,/selenium-server/driver]
    18:35:06.385 DEBUG - Init classloader from null, sun.misc.Launcher$AppClassLoader@11b86e7 for HttpContext[/selenium-server/driver,/selenium-server/dri
    ver]
    18:35:06.401 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver]
    18:35:06.401 DEBUG - Starting HttpContext[/selenium-server,/selenium-server]
    18:35:06.401 DEBUG - Init classloader from null, sun.misc.Launcher$AppClassLoader@11b86e7 for HttpContext[/selenium-server,/selenium-server]
    18:35:06.416 DEBUG - Started org.openqa.jetty.http.handler.SecurityHandler in HttpContext[/selenium-server,/selenium-server]
    18:35:06.416 DEBUG - Started org.openqa.selenium.server.StaticContentHandler in HttpContext[/selenium-server,/selenium-server]
    18:35:06.416 DEBUG - Started org.openqa.selenium.server.SessionExtensionJsHandler in HttpContext[/selenium-server,/selenium-server]
    18:35:06.416 DEBUG - Started org.openqa.selenium.server.htmlrunner.SingleTestSuiteResourceHandler in HttpContext[/selenium-server,/selenium-server]
    18:35:06.432 DEBUG - Started org.openqa.selenium.server.SeleniumDriverResourceHandler in HttpContext[/selenium-server,/selenium-server]
    18:35:06.432 INFO - Started HttpContext[/selenium-server,/selenium-server]
    18:35:06.432 DEBUG - Starting HttpContext[/,/]
    18:35:06.432 DEBUG - Init classloader from null, sun.misc.Launcher$AppClassLoader@11b86e7 for HttpContext[/,/]
    18:35:06.447 DEBUG - Started org.openqa.selenium.server.ProxyHandler in HttpContext[/,/]
    18:35:06.447 INFO - Started HttpContext[/,/]
    18:35:06.447 DEBUG - Starting HttpContext[/wd,/wd]
    18:35:06.447 DEBUG - Init classloader from null, sun.misc.Launcher$AppClassLoader@11b86e7 for HttpContext[/wd,/wd]
    18:35:06.463 DEBUG - Starting org.openqa.jetty.jetty.servlet.ServletHandler@108786b
    18:35:06.463 DEBUG - New random session seed
    18:35:06.557 DEBUG - Started holder of class org.openqa.selenium.remote.server.DriverServlet
    18:35:06.557 INFO - Started org.openqa.jetty.jetty.servlet.ServletHandler@108786b
    18:35:06.572 INFO - Started HttpContext[/wd,/wd]
    18:35:06.572 DEBUG - Session scavenger period = 30s
    18:35:06.588 INFO - Started SocketListener on 0.0.0.0:6565
    18:35:06.588 INFO - Started org.openqa.jetty.jetty.Server@18eb9e6
    18:35:06.604 DEBUG - Requested browser string '*iehta' matches *iehta
    18:35:06.697 DEBUG - Extracting /core to c:\DOCUME~1\702723~1\LOCALS~1\Temp\customProfileDir306604\core
    HTML suite exception seen:
    java.lang.RuntimeException: sessionId 306604 doesn't exist; perhaps this session was already stopped?
            at org.openqa.selenium.server.FrameGroupCommandQueueSet.getQueueSet(FrameGroupCommandQueueSet.java:220)
            at org.openqa.selenium.server.browserlaunchers.HTABrowserLauncher.writeSessionExtensionJs(HTABrowserLauncher.java:117)
            at org.openqa.selenium.server.browserlaunchers.HTABrowserLauncher.createHTAFiles(HTABrowserLauncher.java:102)
            at org.openqa.selenium.server.browserlaunchers.HTABrowserLauncher.launch(HTABrowserLauncher.java:63)
            at org.openqa.selenium.server.browserlaunchers.HTABrowserLauncher.launchHTMLSuite(HTABrowserLauncher.java:155)
            at org.openqa.selenium.server.htmlrunner.HTMLLauncher.runHTMLSuite(HTMLLauncher.java:121)
            at org.openqa.selenium.server.htmlrunner.HTMLLauncher.runHTMLSuite(HTMLLauncher.java:166)
            at org.openqa.selenium.server.SeleniumServer.runHtmlSuite(SeleniumServer.java:545)
            at org.openqa.selenium.server.SeleniumServer.boot(SeleniumServer.java:239)
            at org.openqa.selenium.server.SeleniumServer.main(SeleniumServer.java:198)
    C:\workarea\wip\SeleniumSuite>
</code>
Update #19:37
OK another update - if i change the browser from *iexplore to *iexploreproxy it seems to work. Is there any reason for this?
Update #21:45
I tried to donwload an older version of Selenium RC and the older version (0.9.2) works fine. Its possible that this is something that affects just the new version.
Answer: An observation is noted in the command used to run your html suite: can you try the following command:
<code>java -jar selenium-server.jar -htmlSuite *iexplore "http://localhost/app" "testsuite.html" "testsuiteoutfile.html"
</code>
Note1: make sure you are referring to the correct path where your 'testsuite.html' is located. Eg: "C:\testsuite.html"
Note2: Same applies for the output file too, make sure you refer to the specific directory where you want to save your result.

Selenium RC htmlsuite error


Ho can I show the first tab

Question: I am having trouble with showing the first tab by default. Right now it's showing the second tab by default. Please help. Thanks
What I want to do is present the first tab automatically when someone opens the page.
Here is the code:

                        <?php _e('Detalii','language');?>

                        <?php _e('Features','language');?>

                        <?php $video_source = get_post_meta($post->ID, 'video_meta_box_source', true);
                                    $video_id = get_post_meta($post->ID, 'video_meta_box_videoid', true);
                                    if(($video_source == "vimeo") && !empty($video_id)){ ?>
                                    <?php _e('Video','language');?>
                                                                        <?php } elseif(( $video_source == "youtube") && !empty($video_id)){ ?>
                                    <?php _e('Video','language');?>
                                    <?php  } ?>

                                <?php   $trim_length = 200;
                                        $values = get_post_meta($post->ID, 'mod3', true);
                                        if (is_array($values))
                                        {
                                        foreach($values as $value) {
                                        add_filter( 'custom_filter', 'wpautop' );
                                        echo '
'.apply_filters( 'custom_filter', $value ).'
';}
                                        }
                                        ?>

                                <?php   if (get_the_terms($post->ID, 'features')) {
                                    $taxonomy = get_the_terms($post->ID, 'features');
                                    foreach ($taxonomy as $taxonomy_term) {
                                    ?>
<?php echo $taxonomy_term->name;?>
<?php }

                                    }
                                    ?>

<?php $video_source = get_post_meta($post->ID, 'video_meta_box_source', true);
                                    $video_id = get_post_meta($post->ID, 'video_meta_box_videoid', true);
                                    if(($video_source == "vimeo") && !empty($video_id)){ ?>
                                    <iframe src="http://player.vimeo.com/video/<?php echo $video_id; ?>?title=0&portrait=0&color=e275c7" width="478" height="310" frameborder="0" webkitAllowFullScreen allowFullScreen>
                                    <?php } elseif(( $video_source == "youtube") && !empty($video_id)){ ?>
                                    <iframe src="http://www.youtube.com/embed/<?php echo $video_id; ?>"  width="478" height="310" frameborder="0" allowfullscreen>
                                    <?php  } ?>

Answer: As a guess, without seeing the Javascript doing the show/hide mechanics, I'd suggest putting the "active" class on the first tab in the HTML and reloading the page.
Comment: thank you so much, that was useful, I can see the tab first, but to see the content within it I still need to click on the name of the tab, I'd like it to display the content automatically (now it's still showing the content from the other tab, the features one) [link](http://brateauto.ro/brate-auto/kit-brate-bmw-e34/)
Comment: Can you share the Javascript you're using?

Ho can I show the first tab


Trouble with Android Facebook SDK on Java, Android

Question: I create app for working with facebook. I download Android Facebook SDK from GitHub, than I create a new Android project for sdk in Eclipse (when I'm creating a new project for sdk, i selected "create from existing source"). Than I added to my project this facebook project ("build path", etc). But when I want to create a new Facebook object, I got unhandled error. It is code:
<code>Facebook fb=new Facebook(APP_ID);
</code>
Where have I do mistake?
Error log:
<code> - 09-29 05:23:21.295: ERROR/AndroidRuntime(1256):
   java.lang.NoClassDefFoundError: com.facebook.android.Facebook 09-29
   05:23:21.295: ERROR/AndroidRuntime(1256):     at
   com.nda.mailinglist.SimpleAndroidMailingListActivity.onContextItemSelected(SimpleAndroidMailingListActivity.java:80)
   09-29 05:23:21.295: ERROR/AndroidRuntime(1256):     at
   android.app.Activity.onMenuItemSelected(Activity.java:2174) 09-29
   05:23:21.295: ERROR/AndroidRuntime(1256):     at
   com.android.internal.policy.impl.PhoneWindow$ContextMenuCallback.onMenuItemSelected(PhoneWindow.java:2731)
   09-29 05:23:21.295: ERROR/AndroidRuntime(1256):     at
   com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:139)
   09-29 05:23:21.295: ERROR/AndroidRuntime(1256):     at
   com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
   09-29 05:23:21.295: ERROR/AndroidRuntime(1256):     at
   com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:129)
   09-29 05:23:21.295: ERROR/AndroidRuntime(1256):     at
   com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:884)
   09-29 05:23:21.295: ERROR/AndroidRuntime(1256):     at
   android.widget.AdapterView.performItemClick(AdapterView.java:284)
   09-29 05:23:21.295: ERROR/AndroidRuntime(1256):     at
   android.widget.ListView.performItemClick(ListView.java:3285) 09-29
   05:23:21.295: ERROR/AndroidRuntime(1256):     at
   android.widget.AbsListView$PerformClick.run(AbsListView.java:1640)
   09-29 05:23:21.295: ERROR/AndroidRuntime(1256):     at
   android.os.Handler.handleCallback(Handler.java:587) 09-29
   05:23:21.295: ERROR/AndroidRuntime(1256):     at
   android.os.Handler.dispatchMessage(Handler.java:92) 09-29
   05:23:21.295: ERROR/AndroidRuntime(1256):     at
   android.os.Looper.loop(Looper.java:123) 09-29 05:23:21.295:
   ERROR/AndroidRuntime(1256):     at
   android.app.ActivityThread.main(ActivityThread.java:4363) 09-29
   05:23:21.295: ERROR/AndroidRuntime(1256):     at
   java.lang.reflect.Method.invokeNative(Native Method) 09-29
   05:23:21.295: ERROR/AndroidRuntime(1256):     at
   java.lang.reflect.Method.invoke(Method.java:521) 09-29 05:23:21.295:
   ERROR/AndroidRuntime(1256):     at
   com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
   09-29 05:23:21.295: ERROR/AndroidRuntime(1256):     at
   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 09-29
   05:23:21.295: ERROR/AndroidRuntime(1256):     at
   dalvik.system.NativeStart.main(Native Method)
</code>
Comment: What was error? Please post here.
Comment: So you are making library project from that facebook sdk and adding that sdk project as library project to your code? Try removing and re-adding that libraray project and then cleaning project and see if thats solve the problem.
Comment: I succesfully maked library project, but i can't add this project as library - when I close window for it operation and will returned, therefore I see that project isn't library.
Comment: So you are saying you made Facebook sdk code as library project but when you want to add this as library project you don't see it there in list of library projects?
Comment: I added it and I see a green daw, but than, when I closed the window, I reopen properties and see red cross.
Comment: Also make sure facebook sdk project should be on same drive in which you have your project. For example if you have your project code in C: drive but you have placed facebook sdk in D: drive then it wont work. Both should be in same drive.
Comment: I love you man, thank you very much. I moved android facebook sdk and it works! Thank you
Comment: Great to hear my post helped you. Can you please up my comment.
Answer: Facebook sdk project should be on same drive in which you have your project. For example if you have your project code in C: drive but you have placed facebook sdk in D: drive then it wont work. Both should be in same drive.


Spliting into even and odd $n$ sum

Question: In this site, on proof 1 section there is a line where the expression is split into even and odd $n$, I don't understand how this was done, could someone explain it for me?
Comment: Write out the entire sum, then pretend each pair of terms is one term of another sum.
Answer: What it did was that it changed this original sequence
$$\sum_{m=0}^{\infty}a_m=a_0+a_1+a_2+...$$
into
$$\sum_{n=0}^{\infty}(a_{2n}+a_{2n+1})=(a_0+a_1)+(a_2+a_3)+...$$
by showing two adjacent terms at the same time.
So $n=0$ in the new sequence would correspond to $m=0$ & $1$ in the old sequence, and $n=1$ corresponds to $m=2$ & $3$, and $n=2$ to $m=4$ & $5$, and so on.
This way, $(-1)^m$ can be split into two cases - $m$ is even and $m$ is odd, and can be explicitly calculated.
Comment: Thank you. I didn't think it was so simple

Spliting into even and odd $n$ sum


Interpretation of Residuals vs Fitted [Regression]

Question:
Hi there,
I tried to interpret and evaluate the given plot. Most statistic-books say that if homoscedasticity in regression models is present, it would be recognizable through a triangle-shape in a residual vs fitted plot. For me, there is no clear triangle-shape present.
What I find more complex to interpret is that most of the residuals are in the very beginning. What does that tell me regarding the regression-assumptions? I could neither find such an example in a statistic book, nor online.
Answer: If the predictions are reasonably accurate, then the fact that most of the predictions are lower values implies also that most of your dependent variable's values are also lower values.  (I.e., there is a positive skew in the marginal distribution of the DV.)
Your assessment of heteroscedasticity seems reasonable.
The diagonal lines are evidence of discreteness, which means that many observations on the dependent variable take the same numeric value. This is evidence of non-normality, but it's not a gross deviation.


What points in the complex plane satisfy $|z|=arg(z)$.

Question: Question: What points in the complex plane satisfies $|z|=arg(z)$.
Work thus far: Let $z=a+bi$ and $arg(z)$ is the angle between the vector $z$ and the axis. So $|z|=\sqrt{a^2+b^2}$ and $a=|z|\cos(\theta),b=|z|\sin(\theta)$. I would expect from intuition that the shape traced out by the points is a spiral. From here I don't how to proceed. Any hints would be appreciated.
Answer: Try thinking the other way:
Fix some $\theta_0$ and imagine a line starting at the origin and making an angle $\theta_0$ with the real axis. How many points $z $, in that line, have modulus $|z|$ equal to $\theta_0$? Can you write an expression for it/them?
Answer: Let's take a parametric approach: suppose $|z|=\arg(z)=t\ge 0$. Then using polar form and Euler's formula, we can write $z=t\exp(it)$. This traces out the curve

Depending on your perspective, you may choose to only consider $0\le t < 2\pi$.
Comment: (Such curve is an Archimedean spiral.)
Answer: If you use polar coordinates $z = re^{i\theta}$ so the question is which points are $z = re^{ir}; r\in [0,\infty)$ which is it's own answer.
To convert back to rectangular coordinates we have $z = r\cos r + ir\sin r; r\in [0,\infty)$.
To continue what you started:
$a=|z|\cos(\theta)=|z|\cos(|z|),b=|z|\sin(\theta)= |z|\sin(|z|)$.
As $|z|$ may be any non-negative real value the solution is all $z = r\cos r + ir\sin r; r\in [0,\infty)$


RadDataControl. Hide add new logical opearor button

Question: Is there a way to hide the add logical operator button?
The green one with three white dots at the end of each filter descriptor
Answer: You can modify the control template with Blend to achieve your goal.
Answer: Adding this attribute to the component does it
CanUserCreateCompositeFilters="False"


Find $\lim_{x\rightarrow\infty}\sin^2(x^2)$

Question: $$\lim_{x\rightarrow\infty}\sin^2(x^2)$$
I assume the limit doesn't exist but how do I show it?
Do I use sequences somehow?
Comment: Look at the function at $x=\sqrt{2n\pi}$ and $\sqrt{(2n+1)\pi/2}$.
Comment: the limit dont exist.
Answer: As $x$ marches on toward infinity, it is reasonable to guess that the function $\sin^2(x^2)$ visits both 0 and 1 infinitely often. Can you construct an infinite sequence of values such that $\sin^2(x^2)$ evaluates to 0 for each term in the sequence? What about a similar sequence for which it evaluates to 1?
Comment: if i take a_n = root(2npi) and b_n = root((2n+1)pi/2), then both of these sequences tend to infinity as n tends to infinity, but f(a_n) tends to 0 as n tends to infinity, and f(b_n) tends to 1 as n tends to infinity, so because they are not equal, the limit does not exist. Does this work?
Comment: @bws It sounds great, but I would add that $f(a_n)$ does not just tend toward 0, it is *equal* to 0 for all $n$. Similarly for $f(b_n)$.
Comment: oh, yes, my bad, thank you :)
Answer: Note that the function $\sin^2 x$ never approaches a value as $x\to\infty$, it oscillates.
Comment: A real function taking on the value $\;-1\;$ is highly unlikely.
Comment: @TravisJ Why the strange edit?
Comment: @Did, the $-1$ was my mistake (as I was thinking $\sin(x)$ not $\sin^{2}(x)$.  I removed the "never approaches a value" since that is false as $\lim_{x\to a}\sin^{2}(x)=\sin^{2}(a)$ for any $a\in \mathbb{R}$.
Comment: @Did, oscillates seems fine (as long as the $a$ is $\infty$)... as $x\to \infty$ the value of $\sin^{2}(x)$ oscillates between $0$ and $1$.  Unless you feel like that asserts that it only takes on the values $0$ and $1$?
Answer: If a function $f$ admits a limit, say $L$, as $x$ tends to $+\infty$ then for any sequence $(x_n)$ which tends to $\infty$, the sequence $(f(x_n))$ converges to $L$ too. However, if you take the two sequences $(x_n)$ and $(y_n)$ given by André Nicolas above, you will find that the two sequences $(f(x_n))$ and $(f(y_n))$ do not have the same limit. It follows that the limit do not exists, our function $f$ do not have a limit as tends to $+\infty$.
Answer: One can even show the set of values of $\sin^2 n^2$ ($n$ is an integer) is dense in the interval $[0,1]$ (not trivial!).
Comment: Actually more or less trivial, by continuity of the sine function.
Comment: @Did: Actually, I was thinking of a nearby problem: when $x$ is  a integer.
Comment: Actually you might want to modify your post.
Comment: @Did:  done (pun intended :o)).


Can I clone a view but keep it independent of it's content?

Question: I'm looking to duplicate(clone) of a view, so that I may reuse it on other pages and have it will not pull through the same content.
I'm using Views 7.x-3.8 on Drupal 7.34 this will be updated later when the site goes live.
Comment: Yes, you can edit a view after you've cloned it and change what you need to. Depending on your use case a single view with a contextual filter might make more sense though
Answer: Yes it is possible to duplicate a views as much as you need and edit them independently. It saves a lot of work and time.


Undefined value for input fill

Question: Follow my previous article Built method time is not a function, I managed to successfully implement the functions with an appropriate wait time by following a combination of @ggorlen's comment and @Konrad Linkowski answer, additionally, this article puppeteer: wait N seconds before continuing to the next line that @ggorlen answered in, this comment especially helped: -

Something else? Run an evaluate block and add your own code to wait for a DOM mutation or poll with setInterval or requestAnimationFrame and effectively reimplement waitForFunction as fits your needs.

Instead I incorporated waitForSelector, produces the following script:
const puppeteer = require('puppeteer')

const EXTENSION = '/Users/usr/Library/Application Support/Google/Chrome/Profile 1/Extensions/gidnphnamcemailggkemcgclnjeeokaa/1.14.4_0'

class Agent {
  constructor(extension) {
    this._extension = extension
  }

  async runBrowser() {
    const browser = await puppeteer.launch({
      headless:false,
      devtools:true,
      args:[`--disable-extensions-except=${this._extension}`,
            `--load-extension=${this._extension}`,
            '--enable-automation']
    })
    return browser
  }

  async getPage(twitch) {
    const page = await (await this.runBrowser()).newPage()

    await page.goto('chrome-extension://gidnphnamcemailggkemcgclnjeeokaa/popup.html')

    const nextEvent = await  page.evaluate(async () => {
      document.getElementById('launch-trace').click()
    })
    const waitSelector = await page.waitForSelector('.popup-body')
    const finalEvent = (twitch) => new Promise(async (twitch) => page.evaluate(async (twitch) => {
      const input = document.getElementById('user-trace-id')
      input.focus()
      input.value = twitch

    }))
    await finalEvent(twitch)
  }
}
const test = new Agent(EXTENSION)

test.getPage('test')

However, my webpage produces undefined rather than test, I am a little confused by the parameters twich and k, and how to properly assert the parameter twitch so its entered inside the function finalEvent.
Alternatively, I have also tried wrapping finalEvent into a Promise so I can assert the parameter twitch into it as a function, but this does not fill any value:
    const finalEvent = (val) => new Promise(async () => await page.evaluate(async () => {
      const nextTime = () => new Promise(async () => setInterval(async () => {
        const input = document.getElementById('user-trace-id')

        input.focus()
        input.value = val
      }, 3000))
      //await nextTime(k)
    }))
    await finalEvent(twitch)

Answer: There are a few issues here. First,
const page = await (await this.runBrowser()).newPage()

hangs the browser handle and leaks memory which keeps the process alive. Always close the browser when you finish using it:
const browser = await this.runBrowser();
const page = await browser.newPage();
// ... do your work ...
await browser.close();

Or use await page.browser().close() if you lose track of the browser variable.
Here, though, Puppeteer can throw, again leaking the browser and preventing your app from cleanly exiting, so I suggest adding a try/catch block with a finally block that closes the browser.
Generally speaking, try to get the logic working first, then do a refactor to break code into functions and classes. Writing abstractions and thinking about design while you're still battling bugs and logical problems winds up making both tasks harder.
Secondly, there's no need to async a function if you never use await in it, as in:
const nextEvent = await  page.evaluate(async () => {
  document.getElementById('launch-trace').click()
})

Here, nextEvent is undefined because evaluate()'s callback returned nothing. Luckily, you didn't attempt to use it. You also have const waitSelector = await page.waitForSelector('.popup-body') which does return the element, but it goes unused. I suggest enabling eslint no-unused-vars, because these unused variables make a confusing situation worse and often indicate typos and bugs.

On to the main problem,
const finalEvent = (twitch) => new Promise(async (twitch) => page.evaluate(async (twitch) => {
  const input = document.getElementById('user-trace-id')
  input.focus()
  input.value = twitch

}))
await finalEvent(twitch)

There are a number of misunderstandings here.
The first is the age-old Puppeteer gotcha, confusing which code executes in the browser process and which code executes in the Node process. Everything in an evaluate() callback (or any of its family, $eval, evaluateHandle, etc) executes in the browser, so Node variables that look like they should be in scope won't be. You have to pass and return serializable data or element handles to and from these callbacks. In this case, twitch isn't in scope of the evaluate callback. See the canonical How can I pass a variable into an evaluate function? for details.
The second misunderstanding is technically cosmetic in that you can make the code work with it, but it's a serious code smell that indicates significant confusion and should be fixed. See What is the explicit promise construction antipattern and how do I avoid it? for details, but the gist is that when you're working with a promise-based API like Puppeteer, you should never need to use new Promise(). Puppeteer's methods already return promises, so it's superfluous at best to wrap more promises on top of the them, and at worst, introduces bugs and messes up error handling.
A third issue is that the first parameter to new Promise((resolve, reject) => {}) is always a resolve function, so twitch is a confusing mislabel. Luckily, it won't matter as we'll be dispensing with the new Promise idiom when using Puppeteer 99.9% of the time.
So let's fix the code, keeping these points in mind:
await page.evaluate(twitch => {
    const input = document.getElementById('user-trace-id');
    input.focus();
    input.value = twitch;
  },
  twitch
);

Note that I'm not assigning the return value to anything because there's nothing being returned by the evaluate() callback.
"Selecting, then doing something with the selected element" is such a common pattern that Puppeteer provides a handy method to shorten the above code:
await page.$eval("#user-trace-id", (input, twitch) => {
    input.focus();
    input.value = twitch;
  },
  twitch
);

Now, I can't run or reproduce your code as I don't have your extension, and I'm not sure what goal you're trying to achieve, but even the above code looks potentially problematic.
Usually, you want to use Puppeteer's page.type() method rather than a raw DOM input.value = ..., which doesn't fire any event handlers that might be attached to the input. Many inputs won't register such a change, and it's an untrusted event.
Also, it's weird that you'd have to .focus() on the input before setting its value. Usually focus is irrelevant to setting a value property, and the value will be set either way.
So there may be more work to do, but hopefully this will point you in the right direction by resolving the first layer of immediate issues at hand. If you're still stuck, I suggest taking a step back and providing context in your next question of what you're really trying to accomplish here in order to avoid an xy problem. There's a strong chance that there's a fundamentally better approach than this.

Undefined value for input fill


Working with a subtheme

Question: I am customizing my sub-theme and looking to see where to place styling rules. My web inspector is not showing me the specific files where the base theme rules are, it just show that all the rules are in foundation_subtheme.css.  I don't believe that I have any aggregation turned on, what do I need to do to see the specific files that the styling rules are inside of?
For example, how do I fine this rule?
.top-bar input, .top-bar select, .top-bar .button, .top-bar #contact-btn, .top-bar .button-ghost, .top-bar button {
    font-size: 0.875rem;
    height: 1.75rem;
    position: relative;
    top: 0.53125rem;
}

Even when I add a rule to _header.scss the web inspector doesn't show me that its there it only shows the main css file.
Comment: I overlooked your question. You are asking about sass file....
Comment: Rules? CSS? I feel confused. Do the rules mean the content of css files?
Comment: Yes - like .top-bar input, .top-bar select, .top-bar .button, .top-bar #contact-btn, .top-bar .button-ghost, .top-bar button {
    font-size: 0.875rem;
    height: 1.75rem;
    position: relative;
    top: 0.53125rem;
}
Comment: I never see people describing it as 'rules', I ask this because I want to sync our understandings :)
Comment: And which base theme you are using? You can check which CSS files has been loaded on **Network** tabs in the Chrome developer tools. In Firefox, the tab is **Net**.
Comment: I am using zurb foundation theme.
Answer: scss isn't parsed by the browser- it needs to be compiled to css... ,Assuming you have already installed ruby and sass, open a terminal window and navigate to your theme's root directory. Then sass --update to compile the styles once or sass --watch to continue compiling as you work.
Comment: Yes - I am doing that.  But shouldn't I still be able to see which sass file its compiling from?
Comment: In `config.rb` you'll find the sass parameters- change the output style to 'expanded'

Working with a subtheme


multiple vhosts on amazon ec2 instance: cannot access any other vhost than default

Question: I have an Amazon EC2 instance running Ubuntu 14.04 with Apache 2.4.
I have configured Apache with 3 virtual hosts, all for HTTPS only.
The problem is, when I try access the web server from the internet, the host name somehow gets lost and apache tries to serve the page from the default host, no matter by which hostname I accessed it.
/etc/apache2/sites-enabled/default-ssl.conf:
<VirtualHost *:80>
    ServerName monitor.mydomain.net
    Redirect / https://monitor.mydomain.net
</VirtualHost>

<VirtualHost *:443>
    ServerAdmin webmaster@localhost
    ServerName monitor.mydomain.net
    DocumentRoot /usr/share/nagios3/htdocs
    <Directory />
            Options FollowSymLinks
            AllowOverride None
            allow from all
    </Directory>
    <Directory /usr/share/nagios3/htdocs>
            Options Indexes FollowSymLinks MultiViews
            Options +ExecCGI
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>
    ScriptAlias /cgi-bin/nagios3 /usr/lib/cgi-bin/nagios3
    ScriptAlias /nagios3/cgi-bin /usr/lib/cgi-bin/nagios3
    Alias /stylesheets /etc/nagios3/stylesheets
    <DirectoryMatch (/usr/share/nagios3/htdocs|/usr/lib/cgi-bin/nagios3|/etc/nagios3/stylesheets)>
            Options FollowSymLinks
            DirectoryIndex index.php index.html
            AllowOverride AuthConfig
                <IfVersion < 2.3>
                    Order Allow,Deny
                    Allow From All
                </IfVersion>
                <IfVersion >= 2.3>
                    Require all denied
                </IfVersion>
                AuthName "Nagios Access"
            AuthType Basic
            AuthUserFile /etc/nagios3/htpasswd.users
            <RequireAny>
                    Require valid-user
            </RequireAny>
    </DirectoryMatch>
    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/nagios_error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/nagios_access.log combined
    SSLEngine on

    SSLCertificateKeyFile /etc/ssl/private/a-wildcard.key
    SSLCertificateFile /etc/ssl/certs/a-wildcard+dhparam.pem
    SSLCertificateChainFile /etc/ssl/certs/gd_bundle-g2-g1.crt

    <FilesMatch "\.(cgi|shtml|phtml|php)$">
            SSLOptions +StdEnvVars
    </FilesMatch>
    <Directory /usr/lib/cgi-bin>
            SSLOptions +StdEnvVars
    </Directory>
    BrowserMatch "MSIE [2-6]" \
            nokeepalive ssl-unclean-shutdown \
            downgrade-1.0 force-response-1.0
    BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
</VirtualHost>

/etc/apache2/sites-enabled/timetracker.conf:
<VirtualHost timetracker.mydomain.net:80>
    ServerName timetracker.mydomain.net
    Redirect / https://timetracker.mydomain.net
</VirtualHost>
<VirtualHost timetracker.mydomain.net:443>

    ServerAdmin email@example.com
    ServerName timetracker.mydomain.net

    DocumentRoot /var/www/kimai
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/kimai>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/timetracker_error.log

    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/timetracker_access.log combined

    SSLEngine on

    SSLCertificateKeyFile /etc/ssl/private/a-wildcard.key
    SSLCertificateFile /etc/ssl/certs/a-wildcard+dhparam.pem
    SSLCertificateChainFile /etc/ssl/certs/gd_bundle-g2-g1.crt

    <FilesMatch "\.(cgi|shtml|phtml|php)$">
            SSLOptions +StdEnvVars
    </FilesMatch>
    <Directory /usr/lib/cgi-bin>
            SSLOptions +StdEnvVars
    </Directory>

    # MSIE 7 and newer should be able to use keepalive
    BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown

</VirtualHost>

The domain has been anonymized, of course.
Testing the URLs in the browser gives me:
monitor.mydomain.net -> Nagios page from monitor.mydomain.net
timetracker.mydomain.net -> ALSO the Nagios page from monitor.mydomain.net, while it is supposed to serve the Kimai page from timetracker.mydomain.net.
This is the log file nagios_acces.log after I access the page through monitor.mydomain.net:
 220.127.116.11 - nagiosadmin [10/Oct/2016:19:08:35 +0000] "GET / HTTP/1.1" 200 6389 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.2.0"
 22.214.171.124 - nagiosadmin [10/Oct/2016:19:08:36 +0000] "GET /side.php HTTP/1.1" 200 1429 "https://monitor.mydomain.net/" "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.2.0"
 18.104.22.168 - nagiosadmin [10/Oct/2016:19:08:36 +0000] "GET /main.php HTTP/1.1" 200 1917 "https://monitor.mydomain.net/" "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.2.0"

When I access the site through timetracker.mydomain.com, I get these lines in the same logfile:
220.127.116.11 - nagiosadmin [10/Oct/2016:19:12:19 +0000] "GET / HTTP/1.1" 200 1018 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.2.0"
220.127.116.11 - nagiosadmin [10/Oct/2016:19:12:20 +0000] "GET /side.php HTTP/1.1" 200 1429 "https://timetracker.mydomain.net/" "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.2.0"
220.127.116.11 - nagiosadmin [10/Oct/2016:19:12:20 +0000] "GET /main.php HTTP/1.1" 200 1917 "https://timetracker.mydomain.net/" "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.2.0"
220.127.116.11 - nagiosadmin [10/Oct/2016:19:12:20 +0000] "GET /images/favicon.ico HTTP/1.1" 200 1178 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.2.0"

Note that these lines also appear in the logfile for monitor; the actual logfile for timetracker stays empty.
Somebody suggested to me that Amazon EC2 instances might be behind a reverse proxy that somehow drops the host name to which the original HTTP request was made.
Is this true and if so, how can I work around it?
Thanks a lot in advance!
EDIT: This whole configuration has been migrated from another server where it was working perfectly as expected. The /etc/apache2 directories on both servers are completely identical, except for the 2nd level domain name of course. The only other difference is that the original server is Debian Jessie while the new server is Ubuntu 14.04.
Comment: Individual AWS EC2 instances are more than capable of serving as many domains as you like, I have on small t2.micro instance that services a half dozen domains / websites. There is no reverse proxy between the internet and the instance unless you configure one yourself. This issue is almost certainly Apache misconfiguration.
Comment: You have only shown us the config for 2 vhosts. Unless you configured a reverse proxy it is not that. Did you restart httpd after configuring your vhosts ?
Comment: @Hangin on in quiet desperation: Of course I restarted apache. I've also temporarily disabled the other vhost configs to rule out that they're interfering.
Answer: It's because of network environment of AWS. Your EC2 instance looks like it has 2 IPs assigned (private one ane public one) but in reality EC2 has assigned only private ip. Public IP points into some huge NAT device which is in front of VPC and which knows how to map public IP to your EC2 instance. This is one of weirdness of AWS.
And this is root cause of your problem. As you can see, your default virtual host is declared as <VirtualHost *:80> or <VirtualHost *:443> which means for apache something like "scan requests on every interfaces where apache is listening and look for request with Host header equal of monitor.mydomain.net (as set in ServerName directive)". This is ok, your requests are comming thru your private IP (due that NAT device) and everything is working.
But in your second virtualhost, you have declared is as <VirtualHost timetracker.mydomain.net:80> resp. as <VirtualHost timetracker.mydomain.net:443>, which means in apache language "scan all requests comming thru interface with IP timetracker.mydomain.net and looks for Host header timetracker.mydomain.net". Problem is that your EC2 has no interface with IP of timetracker.mydomain.net because that IP points to AWS NAT device, not your EC2 instance, so this rule is never used.
You have to reconfigure all of your VirtualHosts to listen on *:80 and *:443 and just define your sites with ServerName directive. Unfortunatelly there is no way how you can have your public IP directly on your EC2. AWS has this because they want to dynamically change mapping of IPs and EC2 instances.
Comment: :děkuji! That was it. I removed the host name from the VirtualHost directive, now it works! Thanks a log!
Comment: i mean "a lot" :-))


Summing up Fourier coefficients $\hat{f}({\bf m})$ of $f\in L^1({\bf T}^n)$ for ${\bf m}=(m,\ldots,m), m \in {\bf Z}$

Question: Say $f\in L^1({\bf T}^n)$ a function on the real n-torus ${\bf T}^n$ with $\sum_{{\bf m}\in {\bf Z}^n} \mid \hat{f}({\bf m})\mid<\infty$ where
$\hat{f}({\bf m})=\int_{{\bf T}^n} f({\bf x}) e^{-2\pi i {\bf m}\cdot {\bf x}} dx$ is the m-th Fourier coefficient. Then by Fourier inversion
$f({\bf x})= \sum_{{\bf m}\in {\bf Z}^n}\hat{f}({\bf m})e^{2\pi i {\bf m}\cdot {\bf x}}$
almost everywhere. Now set $\Delta: {\bf Z}\rightarrow {\bf Z}^n, m \mapsto (m,\ldots,m)^t$. In this setting  what (if anything non-trivial) can one say about
$\sum_{{\bf m}\in \Delta({\bf Z})}\hat{f}({\bf m})e^{2\pi i {\bf m}\cdot {\bf x}}$
or
$\sum_{{\bf m}\in \Delta({\bf Z})} \mid \hat{f}({\bf m})\mid$?
What I mean is, are there theorems (with perhaps additional assumptions) making any interesting statements about these sums?
Comment: This might help:https://en.wikipedia.org/wiki/Convergence_of_Fourier_series#Absolute_convergence
Answer: For simplicity,  take $n=2$ and $f \in C^\infty$.
As usual $$\sum_{m=-M}^M e^{2i \pi m(x+y)} = \frac{\sin( 2\pi (m+1/2) (x+y))}{\sin(\pi(x+y))}$$ so that $$\sum_{m=-\infty}^\infty c_m e^{2i \pi m(x+y)} = \lim_{M \to \infty} \int_0^1 \int_0^1 f(x-u,y-v) \frac{\sin( 2\pi (m+1/2) (u+v))}{\sin(\pi(u+v))}dudv \\ = \int_0^1 \int_0^1 f(x-u,y-v) \delta(u+v) du dv = \int_0^1 f(x+v,y-v)dv$$
Answer: There's a lot to say if you care about asking in a certain direction. I don't know what level of math you're asking from: this answer is going to be about current research, so there's a chance this flies over your head if you were asking from a less advanced motivation.
This question could be classified under the category of discrete Fourier restriction, which (to simplify things a bit) studies what happens when a Fourier series is restricted to a specific subset $E$ of frequency space. Researchers in this field are concerned with questions like finding the best constant $A_{p,N}$ in the inequality
$$
\left(\sum_{|\mathbf{m}|\leq N, \mathbf{m}\in E} |\hat{f}(\mathbf{m})|^q\right)^{1/q} \leq A_{p,q,N}\left( \int_{\mathbf{T}^n} |f(\mathbf{x})|^p dx\right)^{1/p}.
$$
Specific cases of $E$ are often of particular interest: for example, $E = \{(\mathbf{m},|m|^2): \mathbf{m}\in\mathbf{Z}^n\} \subset \mathbf{Z}^{n+1}$ is associated to counting the number of solutions to certain systems of quadratic Diophantine equation (see Vinogradov's mean-value theorem), which has further consequences for PDEs (in this case, the Schrodinger equation). There has been much recent research progress in this area: for instance, many reasonably general polynomial relations defining $E$ have been studied.
That said, $E$ is usually taken to be a hypersurface of one dimension lower than the ambient space, as cutting away more than one dimension's worth of Fourier data tends to lead to noninteresting conclusions. In your case, $E$ is a straight line through the origin in the direction $(1,1,\ldots,1)^t$, hence one-dimensional: therefore the nontrivial case in Fourier restriction arises in the case $n=2$. In this case you have the discrete Fourier restriction problem for a 1-dimensional hyperplane in a 2-dimensional ambient space. Unfortunately, this is also not a particularly interesting problem: it is well-known that curvature of the hypersurface is required for interesting norm bounds, while on a flat hypersurface there are no restriction inequalities because you can construct functions that are well-behaved in the physical domain while blowing up on any subset of a hyperplane in Fourier space.
However, you would arrive at a very interesting problem if you instead considered $E = \{(\mathbf{m},|\mathbf{m}|)\in\mathbf{Z}^n\times\mathbf{Z}\}$. This set is the cone in $n+1$-dimensional Fourier space, and corresponds to the discrete Fourier restriction problem for the cone, which is also related to the wave equation. For $n=1$ this matches your original problem, except that the anti-diagonal $(-m,m)$ is also included. Although the problem is still not interesting in this dimension (two straight lines through the origin are not any better than just one), in higher dimensions the cone is a genuine curved surface, albeit with one direction of zero principal curvature. This direction of zero principal curvature makes the cone problem one of the more difficult restriction problems, and indeed it is connected to some of the most notable problems in harmonic analysis and PDEs today, including the Kakeya conjecture, Bochner-Riesz conjecture, and the local smoothing conjecture. Again, there has been very recent progress on this problem as well.


Retornar Ids buscando pelo valor de um array multidimensional

Question: Existe alguma forma sem utilizar foreach, utilizando apenas funçoes nativas do PHP para retornar um array com os ids buscando todos que estao com o value 'a' ?
Exemplo:
$lista = array(
    array(
        'id' => '100',
        'name' => 'Sandra Shush',
        'value' => 'a'
    ),
    array(
        'id' => '5465',
        'name' => 'Stefanie Mcmohn',
        'value' => 'a'
    ),
    array(
        'id' => '40489',
        'name' => 'Michael',
        'value' => 'b'
    )
);

Retornar um array com os ids que tem o value 'a'
$lista_ids = array(100,5465);

Answer: Não vejo porque não usar o foreach, pois quando se trata de arrays com índice ele é uma mão na roda. Foreach é nativo do PHP.
Mas vamos ao que interessa:
<?php

$lista = array(
    array(
        'id' => '100',
        'name' => 'Sandra Shush',
        'value' => 'a'
    ),
    array(
        'id' => '5465',
        'name' => 'Stefanie Mcmohn',
        'value' => 'a'
    ),
    array(
        'id' => '40489',
        'name' => 'Michael',
        'value' => 'b'
    )
);
$ids = [];
for($i = 0; $i < count($lista); $i++) {
    if( $lista[$i]['value'] == 'a' ) {
        $ids[] = $lista[$i]['id'];
    }
}

var_dump($ids);

Simplificando a sintaxe de array, e fazendo com o foreach:
<?php

$lista = [
    [
        'id' => '100',
        'name' => 'Sandra Shush',
        'value' => 'a'
    ],
    [
        'id' => '5465',
        'name' => 'Stefanie Mcmohn',
        'value' => 'a'
    ],
    [
        'id' => '40489',
        'name' => 'Michael',
        'value' => 'b'
    ]
];
$ids = [];
foreach($lista as $item) {
    if ( $item['value'] == 'a' ) {
        $ids[] = $item['id'];
    }
}
var_dump($ids);

Você também pode fazer com o array_map dessa forma:
<?php
function teste($item) {
    if($item['value'] == 'a') {
        return $item['id'];
    }
}

$lista = [
    [
        'id' => '100',
        'name' => 'Sandra Shush',
        'value' => 'a'
    ],
    [
        'id' => '5465',
        'name' => 'Stefanie Mcmohn',
        'value' => 'a'
    ],
    [
        'id' => '40489',
        'name' => 'Michael',
        'value' => 'b'
    ]
];
$b = array_map("teste", $lista);
echo '
';
var_dump($b);
echo '
';

O array_map ele vai deixar null os que não entrarem na condição.
Comment: Obrigado, a ideia de nao precisar usar o foreach era no caso de já existir algo que eu escrevesse menos sem precisar fazer um loop.
Comment: Mas a ideia dos laços de repetições é exatamente essa.