Android nested library structure, access method in nested library from the main application

Question: Is it possible to access a library's dependencies through the main application.
I have the following library structure right now.

Main application:

Main library
LibA
LibB

Main library then have the following dependencies

Main library:

LibA
LibB

But i want the following structure instead

Main application:

Main library

Main library:

LibA
LibB

And then Main application should be able to access methods in LibA and LibB, so i only have to include Main library as a dependency in the main application.
I'm using gradle to build my application.
Comment: any progress? I have same problem and I'm searching but no result yet.
Answer: Depends on how you package up your main library.
Local dependencies (stuff in libs) get packaged up as part of the aar
Comment: Thanks for the quick answer, unfortunately there are no local dependencies, everything is retrieved through maven repositories. Is there any way to include it in the aar then? @MrChaz
Comment: If you can help me, please answer! :)
Comment: Hi, I don't know of a way to do it properly. It might be possible to do something that takes the contents of the exploded-aar directory in /build but that doesn't sounds like a good idea.


Relation between two problems of algebraic number theory

Question: Consider the following two problems of Number Theory.

For which prime $p, \Bbb Z[\omega]$ is a UFD, where $\omega$ is a $p$-th root of unity?
Does Unique Factorization occur for infinitely many $d>0$ in the ring of integers of $\Bbb Q\bigl(\sqrt{d}\mkern2mu\bigr)$?

Both these problems are not yet completely solved. My question is
As both of the problems are concerned with unique factorization in a ring, is there any relation between these two problems. Does solution of one imply the solution of other? Also, what are the best-known results on these problems?
Comment: 1. is solved: this is the case if $p\le19$. See Washington's book.
Answer:
It is a UFD for all primes $p\le 19$ and never again for any prime $p>19$.
The class number is conjecturally $1$ for infinitely many squarefree $d>0$ (Gauß), i.e., the ring of integers is a UFD for infinitely many $d>0$. This is still open.

Conclusion: The two statements are essentially not related. However, they are both part of the "class number one problem".
Remark to 1: The class numbers of $\Bbb Q(\zeta_p)$ grow rapidly with $p$:
\begin{array}{cc}
p & h_{\Bbb Q(\zeta_p)} \\
\hline
2 & 1 \\
3 & 1 \\
5 & 1 \\
7 & 1 \\
11 & 1 \\
13 & 1 \\
17 & 1 \\
19 & 1 \\
23 & 3 \\
29 & 8 \\
31 & 9 \\
37 & 37 \\
41 & 121 \\
43 & 211 \\
47 & 695 \\
53 & 4889 \\
59 & 41241 \\
61 & 76301 \\
67 & 853513 \\
71 & 3882809 \\
73 & 11957417 \\
79 & 100146415 \\
83 & 838216959 \\
89 & 13379363737 \\
97 & 411322824001 \\
101 & 3547404378125 \\
103 & 9069094643165 \\
107 & 63434933542623 \\
109 & 161784800122409 \\
113 & 1612072001362952 \\
127 & 2604529186263992195 \\
131 & 28496379729272136525 \\
137 & 646901570175200968153 \\
139 & 1753848916484925681747 \\
149 & 687887859687174720123201
\end{array}


Why include a time trend in a regression?

Question: I have a regression model of unemployment on vacancy over 20 years. The model also includes a time trend
time trend = 0, 1, 2 , 3 ,....
What's the reason for including a time trend?
Thank you
Answer: If both unemployment and vacancy have a trend in the long-run, then regressing one against the other would be very misleading. (Every time series with strong positive trend could be well regressed with practically anything that also has a strong positive trend!). That is a classical example of spurious regression; more generally speaking you should be cautious to think over whether time series in the regression are stationary.
Including time trend is essentially a form of de-trending. (If you include linear time trend, it means fitting and subtracting a linear trend.) Makes sense if the time series become stationary by de-trending.
Chapter 10 of the Wooldridge book discusses the basics of this question. Actually, Section 10.5 is dedicated to your very question.
Answer: Time is important in terms of inflation etc. Therefore, when dealing with economic situations (also many other situations) its effect should be controlled for. Good responses to your question are available from Time trend or time dummies in a panel


Gerar valor aleatório com formatação

Question: Como posso gerar uma string aleatória com uma determinada formatação? Estou fazendo com criptografia em PHP mas não consigo formatar os valores.
Queria que gerasse de acordo com o seguinte exemplo:
A9MDY3-X6S

Meu código está somente criando um md5 mas queria gerar um texto como no exemplo acima.
Meu código:
<?php md5(date("d/m/Y H:i:s")); ?>

Nota: Gostaria de realizar em JavaScript.
Answer: olá, você pode usar uma funcão como esta:
    function gerarCombinacao() {

        $combinacao = chr(rand(97,122));
        $combinacao .= chr(rand(97,122));
        $combinacao .= chr(rand(97,122));
        $combinacao .= "-";
        $combinacao .= rand(0,9);
        $combinacao .= rand(0,9);
        $combinacao .= rand(0,9);

        return $combinacao;
    }

O result da função a cima sera ex; asd-962
onde ela vai gerar string com numeros aleatorios de 0-9 e letras de a-z
Os tipos dos caracteres dentro do CHR pode ser verificado em https://www.ascii-code.com/
Answer: Com php:
<?php
$hash = strtoupper(md5(date("d/m/Y H:i:s")));
$hash = substr($hash,0,9); //Corta a string para 9 digitos;
$hash = substr_replace($hash, '-', 6, 0 ); //Insere o sinal na posicao indicada;
echo $hash;

Com JavaScript:

    function randomString() {
     var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
     var length = 9;
     var randomstring = '';
     for (var i=0; i < length; i++) {
      var rnum = Math.floor(Math.random() * chars.length);
      randomstring += chars.substring(rnum, rnum + 1);
     }
     var output = [randomstring.slice(0, 6), '-', randomstring.slice(6)].join('');
     document.randform.randomfield.value = output;
    }
<form name="randform">
<input type="button" value="Create Random String" onClick="randomString();">
<input type="text" name="randomfield" value="">
</form>

Fontes: How to Create Random Numbers & Characters, Inserting string at position x of another string.
Answer:

    function gerarNumeroAleatorio() {

      var texto = "";
      var valores= "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      var tamanho = 9;

      for (var i = 0; i < tamanho; i++)
        texto += valores.charAt(Math.floor(Math.random() * valores.length));

      console.log(texto.substr(0,6) + "-" + texto.substr(6,10));

      }

    <button onClick="gerarNumeroAleatorio();">GERAR</button>

Queria que gerasse de acordo com o seguinte exemplo: A9MDY3-X6S.

O que levei em consideração foi gerar uma String com valores aleatórios misturando valores alfabéticos e numéricos.
A variável valores, possui toda diversidade dos possíveis valores aleatórios que devemos "sortear".
A variável tamanho(9) está referente à quantidade de caracteres que vamos ter no valor final(considere o ponto inicial como o índice 0).
E feito um loop e dentro dele os números/caractere aleatórios separados por um hífen na seguinte ordem: 6 dígitos(texto.substr(0,6) - 3 dígitos(texto.substr(6,10).

Gerar valor aleatório com formatação


Consulta PostgreSQL trazendo mais resultados do que esperado

Question: Olá, tenho uma situação em um sistema onde preciso encontrar quais as matriculas de alunos estão relacionados à um tutor em uma turma.
As tabelas que eu tenho são:

matricula que contém chave estrangeira com aluno (mat_aln_id) e com turma (mat_tur_id)
professor_turma que contém chave estrangeira com o tutor (prt_pes_id) e com a turma (prt_tur_id)
aluno_tutor que contém chave estrangeira com professor_turma (alt_prt_id) e com o aluno (alt_pes_id)

Em uma turma de 11 alunos, onde apenas 8 estão relacionados a um tutor específico, eu tento buscar as matrículas deles da seguinte forma:
SELECT DISTINCT(matricula.mat_id)
FROM matricula
INNER JOIN professor_turma ON prt_tur_id = mat_tur_id
INNER JOIN aluno_tutor ON prt_id = alt_prt_id
WHERE prt_tur_id = 92 AND prt_pes_id = 79

Esperando receber 8 resultados, mas recebo todos os 11 matriculados.
O exemplo no SQL Fiddle está aqui, para facilitar o entendimento na prática.
Alguém pode me ajudar?
Answer: Pelo que vi o erro está no segundo join, os campos selecionados não são os indicados.
Tenta assim:
SELECT DISTINCT(matricula.mat_id)
FROM matricula
INNER JOIN professor_turma ON prt_tur_id = mat_tur_id
INNER JOIN aluno_tutor ON at_pes_id = mat_aln_id
WHERE prt_tur_id = 92 AND prt_pes_id = 79

Comment: Muito obrigado. Estava batendo cabeça e não saia do lugar.


Diretório Raiz de Aplicação Java Desktop

Question: Estou com uma aplicação java desktop, sendo um jar executável e preciso sabre o diretório raiz onde o jar esta rodando. Ja pesquisei diversas forma e não encontrei o que preciso, sempre estou vendo modelos onde informo um arquivo X pra ele me retornar a localização do mesmo e o que preciso e pegar o Raiz do Jar Executável.
Agradeço.
Comment: Tente uma dessas: http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file
Comment: Obrigado pela indicação. Encontrei a resposta la.
Answer: Solução para o que preciso:

The only solution that works for me on Linux, Mac and Windows:

public static String getJarContainingFolder(Class aclass) throws Exception {
  CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();

  File jarFile;

  if (codeSource.getLocation() != null) {
    jarFile = new File(codeSource.getLocation().toURI());
  }
  else {
    String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
    String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
    jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
    jarFile = new File(jarFilePath);
  }
  return jarFile.getParentFile().getAbsolutePath();
}

encontrado no post: https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file
Answer: Você pode utilizar String path = new File(".").getCanonicalPath(); para isto.
Comment: Isso não responde a pergunta. Só retorna a pasta do usuario, não a que o jar está sendo executado.
Comment: Editado, realmente a resposta anterior retorna a pasta onde o usuário executou o jar.


Need to pass a value from PHP to Javascript

Question: I need to pass a value from PHP back to my javascript. I have tried so many things but can't get it to work. Here is my code.

I need to pass a specific value from the PHP file back to life.receiveResult and then add this to the redirection url.
Comment: you have an extra comma after susccess
Comment: possible duplicate of [how to pass these strings from php to javascript](http://stackoverflow.com/questions/3174092/how-to-pass-these-strings-from-php-to-javascript) and http://stackoverflow.com/questions/8626183/passing-values-from-php-to-javascript?rq=1
Comment: Can you search before posting questions. I've seen this question answered dozens of times on Stack Overflow.
Comment: Thanks for the help. I had seen answers as well, however, they did not seem to work for me. Got it working now though!
Answer: The biggest problem is probably that at the time when you assign life.receiveResult to success, life.receiveResult is undefined. You need to define it before you assign it to something else.
Answer: myurl.php needs to return a JSON result when it's called. Something like this:
<?php
header("Content-Type: text/json");
$mydata = "Hello";
echo json_encode(array('ok' => true, 'mydata' => $mydata));
?>

Have a look at the json_encode docs, the header docs and some of the other answers for more information.


A linear transformation $T$ from $V$ to $W$ is an isomorphism iff $\ker(T) = \{0\}$ and $im(T) = W$

Question: This is a result that's proven in my book, and I'm having trouble understanding some parts of the proof, so this is how it goes:

Suppose first that $T$ is an isomorphism. Then the kernel of $T$ is
  found by solving $T(f)=0$. If we apply $T^{-1}$ on both sides, we find
  that $f = T^{-1}(0)=0$, that the $\ker(T)=\{0\}$, as claimed.

My question here is why $T^{-1}(0)$ necessarily equals $0$. Is this a requirement of an invertible or linear transformation? Why does this show the kernel must be $0$?

To see that $im(T)=W$, note that any $g \in V$ can be written as $g =
 T(T^{-1}(g))$.

I don't quite get this either. How does this show that $im(T) = W$?
Answer: I hope you can follow this :
Given $T:V\to W$ is an Isomorphism. So T is invertible, which means that $\exists$ S $\ni$ $ST=TS=I$. Now by definition, a Linear Transformation maps $0$ to $0$, ie $T(0)=0$ and since T is invertible so $T^{-1}$ exists and hence $T^{-1}(0)=0$.
Now note that if $T$ is an isomorphism then so is $T^{-1}$.
$\therefore $ consider $T(f)=0$. Applying $T^{-1}$ both sides, we get
$T^{-1}(T(f))=T^{-1}(0)=0\implies f=0$ ,ie $Ker(T)={0}$.
Since $dim(V)=dim(Ker(T))+dim(Im(T))$
So $dim(V)=dim(Im(T))$. But since V and W are isomorphic, so $dim(V)=dim(W)$, and therefore $dim(Im(T))=dim(W)$ and hence $Im(T)=W$.
Converse is easy.
Suppose that $ker(T)=\{0\}$ and $Im(T)=W$. So T is one to one. This is easily followed by observing that
$T(u)=T(v) \implies T(u)-T(v)=0 \implies T(u-v)=0 \implies (u-v)\in Ker(T)$. But since $Ker(T)=\{0\}$, so $u=v$. It easily follows from here that $T$ is invertible. $\blacksquare$
Answer: First you can prove that $T^{-1}$ is linear. Once we have this
$$T^{-1}(0)=T^{-1}(0+0)=T^{-}(0)+T^{-1}(0)$$
which implies $T^{-1}(0)=0$.
For the second question. Notice that $T^{-1}(g)$ is an element $h$ of $V$. Then you are showing that (for every $g$) there is $h$ such that $T(h)=g$. This is the definition of being surjective.
Let's prove now the general result that if $T$ is linear then $T^{-1}$ is linear.
We have that for all vectors $u,v$ and all scalar $r,s$
$$T(ru+sv)=rT(u)+sT(v)$$
Let's use the particular case in which $u:=T^{-1}(w)$ and $v:=T^{-1}(x)$. We get
$$T(rT^{-1}(w)+sT^{-1}(x))=rT(T^{-1}(w))+sT(T^{-1}(x))=rw+sx$$
Take now $T^{-1}$ on both sides to get
$$rT^{-1}(w)+sT^{-1}(x)=T^{-1}(T(rT^{-1}(w)+sT^{-1}(x)))=T^{-1}(rw+sx)$$
i.e.
$$rT^{-1}(w)+sT^{-1}(x)=T^{-1}(rw+sx)$$
for all vectors $w,x$ and scalars $r,s$. This is the definition of $T^{-1}$ being linear.
Comment: Why is $T^{-1}(g)$ an element of $W$? What is $T(g)$ then?
Comment: $T^{-1}(g)$ is an element of V.


Assumptions behind Synthetic Control Methods

Question: I am trying to estimate the impact of a minimum wage policy in a given region and I was initially thinking of only using a DiD design. However, I came across this causal inference post on synthetic control methods SCM, and I am now considering but was curious if one method is "superior" to the other. Specifically, I want to know if I should pick my own control group based on institutional knowledge, as in the case of a DiD.
Or use SCM to create an artificial control group based on a dataset of all 8 regions in X country I am studying.
I have several macro variables/indicators at the region-level on both my treated and control regions, and both before and after treatment. These variables include:
<code>unemployment rate
Labor fore participation rate
employment rate
Gini coefficient
share of prime-age workers
median household income
median individual income
poverty rate
% of population on food stamps
% of workforce receiving unemployment insurance
</code>
Answer: The advantages over DID:

It relaxes the parallel trends assumption.
It can work with fewer treated units, often just one
Easier to explain compared to a table of regression coefficients.

You can select your potential donor group using institutional knowelede, and then let SC algorithm reweight those selected units. This is recommended in the SC literatuire. Personally I would pre-register the set of potential donors and then check "all regions" version for robustness.
Comment: Those are all the same papers I've read. I would take a look at Synth: An R package for synthetic control methods in comparative case studies
A Abadie, A Diamond, J Hainmueller - Journal of Statistical Software, 2011 and the code (or another implementation).
Comment: dimitriy, do you have a good recommendation for understanding the SC weighting algorithm? I think Abadie does too much abbreviation in the technical sections from the 2003, 2007, and 2021 articles on synthetic controls, and I would love to be able to learn it with enough depth to program the weights-estimations algorithm myself.


How do I create a link to the author's profile on the node that user created?

Question: I want a create a link on each node page, which redirects to the profile page of the user who created that particular node.
How can I achieve this?
Comment: Please don't edit question in a way that renders existing answers invalid. It's called [chameleon question](http://meta.stackexchange.com/q/43478/225745) and not liked. If you have another question, ask it as another question.
Comment: Once the question gets answers, its meaning cannot be changed, or the given answers would be invalidated. Furthermore, we like when questions show the OP tried to find the solution before asking the question.
Answer: Create a custom block with this:
<code>/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['author'] = array(
    'info' => t('author'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta='') {
  $block = array();

  switch($delta) {
    case 'author' :
      $block['title'] = NULL;

      ////////////////////////////////////////////
      $link = NULL;
      if (arg(0) == 'node' && is_numeric(arg(1)) {
        $node = arg(1);
        if (!empty($node->uid)) {
          $link = l('view all work', 'user/' $node->uid);
        }
      }
      //////////////////////////////////////////

      $block['content'] = $link;

      break;
  }

  return $block;
}
</code>
And set this block to nodes page with context, panels or native drupal blocks page.
Comment: i did'nt get you, but i tried this code it giving some error.Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\drupal\modules\php\php.module(80) : eval()'d code on line 2
Comment: Edited to show how to include on a custom block
Comment: i have insert this code in template.php but its showing error in line ' $block['content'] = l('view all work', 'user/' $node->uid);'
Comment: This code is for a custom module, if you want only the script to use on template.php assigning it to a variable use only the snipet
Comment: not working..please suggest some other alternative.
Answer: This is the default functionality available on Drupal. on detail pages author detail appears.
Just edit your content type display setting and check

"Display author and date information. Author username and publish date
  will be displayed."

See the screenshot
After that your can prepare link of author on theme preprocess or hook_node_view to make it clickable.
Answer: You can use the node--content-type.tpl.php node template file for showing the profile link of the user who created the node.
you can use $node->uid to find the user id and then use user_load() function to load the user OR profile2_load_by_user($account, $type_name = NULL) it will give you the profile url for the user if you are using the profile2 module and the you can create the link using the l() function.


Pegar registro no banco e se duplicado, mostrar somente um

Question: tenho uma tabela no banco chamada pedidos, onde o número do controle pode ser duplicado, pois o cliente no mesmo pedido pode comprar 2 itens, ou seja, cada linha vai inserir um produto comprado mas com o mesmo numero de controle, e eu queria que na hora de exibir os produtos comprados, mostrar apenas um, e ai quando eu clicar eu vou mostrar o resto, porém na exibição eu preciso que ele me traga apenas 1, pode ser o ultimo registro desse controle, e não duplicado como está vindo. não sei se fui claro.

                                                    Número pedido
                                                    Data
                                                    Valor
                                                    Situação

                                        <?
                                            $result = ("SELECT * FROM pedidos WHERE id_cliente = '".$usr_id."' ORDER BY id DESC");
                                            $execute = mysqli_query($conn, $result);

                                            if(mysqli_num_rows ($execute) > 0 )
                                            {
                                                while ($dados_cliente = mysqli_fetch_assoc($execute)){
                                                $data = $dados_cliente['data'];
                                                $controle = $dados_cliente['identificacao_pedido'];
                                                $valor_pedido = $dados_cliente['valor_pedido'];
                                                $valor_frete = $dados_cliente['valor_frete'];
                                                $situacao = $dados_cliente['situacao'];

                                              $total = $valor_pedido+$valor_frete;
                                              if ($situacao=='ag') {
                                                $exibir_situacao = 'Aguardando Pagamento';
                                              }
                                              elseif ($situacao=='ap') {
                                                $exibir_situacao = 'Pagamento Aprovado';
                                              }
                                              elseif ($situacao=='cn') {
                                                $exibir_situacao = 'Pagamento Cancelado';
                                              }
                                              elseif ($situacao=='sp') {
                                                $exibir_situacao = 'Em separação';
                                              }
                                              elseif ($situacao=='tr') {
                                                $exibir_situacao = 'Em transporte';
                                              }
                                              elseif ($situacao=='en') {
                                                $exibir_situacao = 'Pedido Entregue';
                                              }
                                            ?>

                                                    #<?=$controle;?>
                                                    <?=$data;?>
                                                    R$ <?=number_format($total,2,',','.');?>
                                                    <?=$exibir_situacao;?>

                                    <?}}else{?>

                                      Você não efetuou nenhum pedido ainda.

                                    <?}?>

Comment: Não poderia fazer uma consulta usando `DISTINCT` para listar apenas os valores, sem as repetições, e então ir para um outro elemento/página que mostra todos os itens independente de repetições?
Answer: Opa!
Faz um distinct na sua query como o exemplo abaixo, assim você só vai exibir um de cada vez, e coloca um link de detalhes em cada linha para exibir todos as linhas.

SELECT DISTINCT(CampoControle) FROM pedidos WHERE id_cliente = '".$usr_id."' ORDER BY id DESC

Espero que ajude.
Comment: então, funcionou, mas agora ele só ta exibindo campo controle e os valores e todo o resto nao ta mostrando
Comment: Coloca o restante dos campos no início da query após o select `SELECT DISTINCT(CampoControle), ColunaB, ColunaC FROM pedidos...`


emmeans contrasts of linear slope

Question: I apologise for no doubt a basic question that I am having difficulty intuiting. I have data with a time component that is measured at irregular intervals (but the same irregular intervals for everyone). In analysing this I could consider time as categorical (which I would normally do) but I have started using splines a little more, so am beginning to explore treating time more as continuous. As it turns out in this case, constraining the 'effect' of time to be linear fits better than using a spline.
My question is, why does emmeans give the same p value for every contrast of time - even though the magnitude of the estimates can be quite different? This is the p value for the slope, right (i.e. the same as the coefficient in the model), so is it a case that it doesn't matter what times you compare if you are treating time as linear, the p value is constrained to be the same?
Am I correct in thinking the only way to obtain contrasts that may differ in statistical significance is to freely estimate the adjusted outcome means by treating time as categorical?
Thanks.
<code>> emmeans(mod, ~ time, at = list(time = c(0, 1, 6, 12))) |>
+   regrid() |> pairs(reverse = T, adjust = "none") |>
+   summary(infer = T)
 contrast       estimate      SE   df lower.CL upper.CL t.ratio p.value
 time1 - time0  -0.00565 0.00925 30.1  -0.0245   0.0132  -0.611  0.5458
 time6 - time0  -0.03390 0.05548 30.0  -0.1472   0.0794  -0.611  0.5458
 time6 - time1  -0.02825 0.04623 30.0  -0.1227   0.0662  -0.611  0.5458
 time12 - time0 -0.06779 0.11096 30.3  -0.2943   0.1587  -0.611  0.5458
 time12 - time1 -0.06214 0.10171 30.1  -0.2698   0.1455  -0.611  0.5458
 time12 - time6 -0.03390 0.05548 30.0  -0.1472   0.0794  -0.611  0.5458
</code>
Answer: In your model, you've specified that the effect of time on the outcome is a linear function of time. It isn't the case that the creators of emmeans have constrained the p.value to be the same. The results follow from the fact that you have specified a linear effect in time.
I will outline below: for illustrative purposes, it is sufficient to treat the estimated coefficients as having an approximate normal distribution under the null since a $t_{30}$ is close to normal.
$$
\beta\sim N(\mu,\sigma^2)\rightarrow a\beta\sim N(a\mu,a^2\sigma^2)
$$
In your contrasts, you specify the contrasts of times, which has the following distribution.
$$
\beta_T 12 -\beta_T 1 \rightarrow 11\beta_T\sim N(11\mu,11^2\sigma^2)
$$
This will then lead to another normal distribution which is tested under a $N(0,1)$ null:
$$
\Delta_{12,1}\sim N(11\mu,11\sigma^2)\rightarrow \frac{11\mu}{\sqrt{11^2\sigma^2}}\ \sim N(0,1)
$$
In general, you are going to have:
$$
\Delta_{T_F,T_O}\sim N(\Delta_T\mu,(\Delta_T^2)\sigma^2)\rightarrow \frac{\Delta_T\mu}{\Delta_T\sigma}\sim N(0,1)
$$
From this it is clear, the differences only depend on the gap between the time intervals, and second, the test statistic will always be $\mu/\sigma$, which is what was used to compute the p-value in the original regression. The standard errors will change by some multiple of the gap in time. This can all be observed in the $T_6-T_0$ and $T_{12}-T_6$ results.
If it is the case that a linear form is better for the data, then so be it. You might not have enough data to estimate the differences in the time points themselves if you treated the time points as categorical predictors. I would not focus on trying to obtain significant results by further breaking down the data ... if you have substantive reason to believe that the linear relation does not hold between time points of your data, then it might be worth pursuing your idea of computing regressions in between each group.

emmeans contrasts of linear slope


Can I assess the relationship between a normally and non-normally distributed variable?

Question: My study is related to the visual attractiveness of route-plans in a logistics context. In practice, route-plans are rejected based on the fact that they "do not look nice". I have conducted an experiment where I showed participants of one group a route-plan with certain characteristics, while other groups were shown route-plans with different characteristics, however they both had the same quality ( in terms of total distance). Three main concepts I studied were: beauty 1=ugly - 10=beautiful), perceived quality (0 - 100% of shortest route-plan possible), and choice to accept a route-plan or not (yes/no).
I wanted to analyze the relationship between beauty (independent) and perceived quality (dependent), however the data for perceived quality is strongly skewed to the left. I tried several transformations, but I wasn't able to normalize the data for perceived quality. To be clear, multiple linear regression does not require the variables to be normally distributed, however the residuals should be. The residuals look normally distributed, but just not in the middle of the distribution.
Is there anything I can do or is it just not possible to test the relationship between those variables reliably? Perhaps non-parametric tests? If so, which ones?
Comment: Would you please post a link to the data?
Answer: I do not have enough reputation to add a comment, so I'll give my answer despite some question or remarks I have. And I'll add the questions and remarks at the end of my answer.
It is not really clear what you want to do. Do you want to check if there is a "relationship between beauty and perceived quality" or do you want to find what this relationship is?

If you want to check if there is a relationship
there are multiple options depending on what relation you expect. Since you were talking about linear regression, I'll assume that you at least expect some kind of strictly monotonic function (if not you'll have to give us more information about the data). Then I'd ineed suggest a non-parametric test, like Spearman's correlation coefficient (and test it's significance with a hypothesis test).
If, however, you want to know what the relationship is
you will have to come up with some possible models and test how they fit. If you want to us to help with suggestions for models, you'll have to show the data.
I would like to point out, though, that it is rather unlikely that you will find a good fit with linear regression (as your residuals probably show), since your dependent variable is strongly skewed, but your independent variable not (I infer from what you said). This would mean that both variables don't have the same type of distribution, and since any linear transformation will always preserve the type of distribution, both variables cannot be linearly related.

Questions/remarks:

Could you show us your data (at least their distributions)? It is difficult to help without
Do you want to know if there is a relationship or what it is?
Those residuals also don't seem normally distributed, they seem skewed.
This may be sound pedantic, but just so I understand your situation correctly, why do you want to do multiple linear regression when you have only one independent variable?


ScreenShot Not showing in testNg Report plugin

Question: I have an issue where the screenshots that i take dont show in the TestNg Report Plugin i am pretty sure that the probleme is the path i am giving them but i dont know what other path i can give is there a solution ?
My screenshot taking code :
public void ScreenShot() {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH_mm_ss");
    LocalDateTime now = LocalDateTime.now();
    String destDir = System.getProperty("user.dir") + "/" + "test-output/ScreenShots";
    String FileName = "SoftAssertScreenshot_" + dtf.format(now) + ".png";
    String DestFile = destDir + "/" + FileName;
    Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
    BufferedImage image = screenshot.getImage();
    try {
        ImageIO.write(image, "PNG", new File(DestFile));
        System.out.println("test");
    } catch (IOException e) {
        e.printStackTrace();
    }
    Reporter.log("
***************Screen Of the error****************");
    Reporter.log("
");
}

What shows in testng report :
[![Image of testng result][1]][1]
Html in testng :

Thanks for the help !
[1]: https://i.stack.imgur.com/5zp1Y.png
Answer: I tried the same code but seeing attached images.
Code:
String DestFile = System.getProperty("user.dir") + "/Data/SO.png";
Reporter.log("
***************Screen Of the error****************");
Reporter.log("
");

Output:

HTML:

There is nothing wrong with your Reporter.log code. Please try the below,

Check is the image really exists in location C:\Users\user\eclipse-workspace\07zr-aut\Demo_Automatisation/test-output/ScreenShots/SoftAssertScreenshot_2021-11-24 08_50_12.png

Put a debug point after line ImageIO.write(image, "PNG", new File(DestFile)); to confirm image is successfully written in the given location.

screenshot.getImage(); what is the purpose of getImage() method? Does it returning RenderedImage? If yes, where are you passing the file location? I am doing like below below and it is working. Are you following same approach?

String DestFile = System.getProperty("user.dir") + "/Data/"+imageName+".png";
Image image = ImageIO.read(new File(DestFile));
BufferedImage buffered = (BufferedImage) image;
ImageIO.write(buffered, "PNG", new File(DestFile));

This should help you. You need to find out the exact location of screenshots folder in Jenkins workspace and update String destDir
Comment: i didnt configure the testng it self i configured the Batch i put in Publish TestNG Results TestNG XML report pattern "**/testng-results.xml"
Comment: the problem with giving it the absolute path of jenkins i will have error images if i execute it from eclipse
Comment: The same code gives me a correct page if i check it in eclipse the photo are showing and all is good getimage() as i understood groupps the multiple part of my image in one big one and the file location is sent in DestFile the probleme is that the path when taken by jenkins isnt working btw i am using jenkins localy
Comment: Have you configured TestNG report plugin in Jenkins?
Comment: Am i just stupid and that s the problem if my fil exist in /test-output/screenShots and the Testng-results exist too in test-output that s why it will never work ?
Comment: No I guess. It should not happen even if both stays under `/test-output/`
Comment: i tried it still didnt work
Comment: I found similar problem here https://stackoverflow.com/questions/56484416/screenshot-is-not-getting-displayed-in-testngresults-under-jenkins
Comment: Yeah i saw it too but it doesnt have a solution
Comment: This should help you. https://stackoverflow.com/questions/54190259/unable-to-view-screenshots-in-jenkins-reports you need to find out the exact location of screenshots folder in jenkins workspace and update `String destDir `
Comment: In the question you have mentioned the screenshot location of local machine. See the location in Jenkins report and update it accordingly.


Double integral equivalent to single integral

Question: In Paul Nahin's book, Dr. Euler's Fabulous Formula Cures Many Mathematical Ills, he proves the irrationality of $\pi^2$ using the differentiation operator $\mathbf{D}$, its inverse $\mathbf{D}^{-1}$ and Euler's formula.
On page 98, he writes about $\mathbf{D}^{-2}$, letting $f(x) = \mathbf{D}^{-1} \phi(x) = \displaystyle \int_{0}^{x} \phi(s)ds$,
$$\mathbf{D}^{-2}\phi(x) = \mathbf{D}^{-1}\mathbf{D}^{-1}\phi(x) = \mathbf{D}^{-1}f(x) = \displaystyle \int_{0}^{x}\displaystyle \left\{\int_{0}^{t}\phi(s)ds\right\}dt$$
He explains how the region for integration is the following:

And so, he justifies that the double integral can be rewritten as,
$$\mathbf{D}^{-2}\phi(x) = \displaystyle \int_{0}^{x}\displaystyle \left\{\int_{s}^{x}\phi(s)dt\right\}ds = \displaystyle \int_{0}^{x} \phi(s)ds \displaystyle \int_{s}^{x} dt = \displaystyle \int_{0}^{x}\phi(s)(x-s)ds$$
I can't satisfactorily follow his explanation of the region of integration, and hence, the equivalence of the double and single integrals. Can somebody please explain it?
Note The pdf version of the book is available here.
Answer: This is just a change of order of integration. For simplification of integral draw the limits of integration $t=0,t=x,s=0$ and $s=t$ in $ts$ plane (which is your region of integration) and then change the order of integration. Actually firstly you are taking vertical strip $s=0$ to $s=t$ and then applying limits of $t$. But after change of order of integration you are taking horizontal strip $t=s$ to $t=x$ and then applying limits of s.


Multiplication and derivation of 3D matrix

Question: I have $A(q)=\begin{bmatrix}q_1 &q_2 & q_3\\ 2q_1 &3q_2 & 4q_3\\ 2q_1 &3q_1 & 10\\    \end{bmatrix}\tag 1$
$ q= {\left(\begin{array}{c}q_1\\q_2\\q_3\\q_4\\q_5\\q_6 \end{array}\right)}_{6\times1}\tag 2$
I am bit confused with the derivative matrix representation  related to above equations. Could you mention how I can do following operations mention in Question section below.
You can mention the method or procedure of how to do those issues than solving all   the problem step by step.
For example for  $\frac{\text{d}A(q)}{\text{d}q}$ ,you could mention, the result will be a matrix of dimension $3\times 3\times 6$ of 6, $3\times3$ slices where each slice i is defined by $slice _i=\frac{\text{d}A(q)}{\text{d}q_i}$. Each $slice_i$ tells you to take derivative of that $q_i$ on $A(q)$ elements individually and put back the result in the same location of the matrix
I am new to these sort of notations that is why I am requesting your help and it is very difficult to find proper martial for complex operations in this regard
Question

What is the content and matrix representation of $\frac{\text{d}A(q)}{\text{d}q}$ and $\frac{\text{d}^2A(q)}{\text{d}q^2}$? What is the content and matrix representation of $(\frac{\text{d}^2A(q)}{\text{d}q^2})^T$ and $(\frac{\text{d}A(q)}{\text{d}q})^T$?

How do we do multiplication of $q^T\frac{\text{d}^2A(q)}{\text{d}q^2}q$ and what will be the resultant matrix and its dimension ? or could you mention the order of multiplication I need to follow on slices

If $a.b=b^Ta$ what will be the content of a)$\frac{\text{d}A(q)}{\text{d}q} .\frac{\text{d}A(q)}{\text{d}q} $ b)$\frac{\text{d}A(q)}{\text{d}q} .(q^T\frac{\text{d}^2A(q)}{\text{d}q^2}q )$c)$\frac{\text{d}A(q)}{\text{d}q} .( \frac{\text{d}^2A(q)}{\text{d}q^2}  )$ or could you mention the order of multiplication I need to follow on slices

If I have a constant matrix $U_{3\times3}$  then what order should I multiply in order to get a)$U_{3\times3}\frac{\text{d}A(q)}{\text{d}q}$ b)$U_{3\times3}\frac{\text{d}^2A(q)}{\text{d}q^2}$. Bit confused with what row and column order to follow. What will be the resultant matrix and its dimension?

What order should I multiply in order to get a)$A(q)_{3\times3}\frac{\text{d}A(q)}{\text{d}q}$ b)$A(q)_{3\times3}\frac{\text{d}^2A(q)}{\text{d}q^2}$ .Bit confused with what row and column order to follow. What will be the resultant matrix and its dimension?

NB :: Remember here we deal with collection of slices in more than 2D. So it is not as straight as regular 2D case
Comment: How do you define $q^2$?
Comment: We dont have issue of $q^2$ here. It is not defined.. It is a vector..Thanks for the reply
Answer: The general definition is Frechet derivatie, or Gateaux derivative if a specific vector unit of differentiation is specified. If you applied the definition to the present question, the derivative is a tensor with elements $\Big[\frac{dA(q)}{dq}\Big]_{i,j,k}=\frac{[A(q)]_{i,j}}{dq_k}$.
Answer: Your matrix can be written as $A(q) = S\cdot q + B$ where $S$ is a very sparse third order tensor.
$B$ is also sparse, its only non-zero component is $B_{33} = 10$.
The only non-zero components of $S$ are seen by inspection to be
$$ \eqalign {
 S_{111} &= 1,\,\,\,S_{122} &= 1,\,\,\,S_{133} &= 1 \cr
 S_{211} &= 2,\,\,\,S_{222} &= 3,\,\,\,S_{233} &= 4 \cr
 S_{311} &= 2,\,\,\,S_{321} &= 3 \cr
} $$
Since $A(q)$ is linear, the first derivative is $\frac {\partial A} {\partial q} = S$, which is constant.  So the second, and higher derivatives are zero.


There are $2^n$ tickets in a jar.The frequency of the tickets of number $i$ is ${n \choose i}$

Question: There are $2^n$ tickets in a jar.The frequency of the tickets of number $i$ is ${n \choose i}$ where $i=0,1,2,..n$.
$m$ tickets are drawn randomly without replacement.
Let S be the sum of the numbers drawn.Find $E(S)$ and variance of S.
I can't find a way to approach this problem.
Comment: Is the drawing with or without replacement?
Comment: Without replacement
Comment: Similar: https://math.stackexchange.com/q/2813390/321264
Answer: This problem is  a type of coupon collector  without replacement where
there are  ${n\choose j}$  tickets of  type $j$ and  we ask  about the
expectation of  the sum of  the ticket  values after $m$  tickets have
been  drawn.  Using  the  methodology  from  the  following  two  MSE
links we find that
the EGF by multiplicity of a set of coupons of type $j$ is given by
$$\sum_{k=0}^{n\choose j}
{n\choose j}^{\underline{k}} \frac{z^k}{k!} =
(1+z)^{n\choose j}.$$
Distributing all $n$ types of coupons we get
$$\prod_{j=0}^n (1+z)^{n\choose j}
= (1+z)^{2^n}$$
for a total count according to multiplicity of
$$m! [z^m] (1+z)^{2^n} = m! \times {2^n\choose m}.$$
Marking the contribution of a ticket  of type $j$ with $u^j$ we obtain
the mixed generating function
$$G(z, u) = \prod_{j=0}^n (1+u^j z)^{n\choose j}.$$
Differentiate and evaluate at $u=1$ to obtain
$$\left.\frac{\partial}{\partial u} G(z, u)\right|_{u=1}
\\ = \left. \prod_{j=0}^n (1+u^j z)^{n\choose j}
\sum_{j=0}^n (1+u^j z)^{-{n\choose j}}
{n\choose j} (1+u^j z)^{{n\choose j}-1}
j u^{j-1} z \right|_{u=1}
\\ = (1+z)^{2^n}
\sum_{j=1}^n {n\choose j} \frac{jz}{1+z}
= z (1+z)^{2^n-1} \sum_{j=1}^n j {n\choose j}
\\ = z (1+z)^{2^n-1} \sum_{j=1}^n n {n-1\choose j-1}
= n 2^{n-1} z (1+z)^{2^n-1}.$$
Extracting coefficients we thus obtain for the expectation of the sum
$$\mathrm{E}[S] = {2^n\choose m}^{-1} n 2^{n-1} {2^n-1\choose m-1}
= n 2^{n-1} \frac{m}{2^n} = \frac{1}{2} nm.$$
Continuing with the variance we evidently require the second factorial
moment. Differentiating twice we get three components, the first is
$$\left. \prod_{j=0}^n (1+u^j z)^{n\choose j}
\sum_{j=0}^n (1+u^j z)^{-{n\choose j}}
{n\choose j} (1+u^j z)^{{n\choose j}-1}
j(j-1) u^{j-2} z \right|_{u=1}
\\ = z (1+z)^{2^n-1} \sum_{j=2}^n j(j-1) {n\choose j}
\\ = z (1+z)^{2^n-1} \sum_{j=2}^n n(n-1) {n-2\choose j-2}
= n(n-1) 2^{n-2} z (1+z)^{2^n-1}.$$
The second is
$$\left. \prod_{j=0}^n (1+u^j z)^{n\choose j}
\sum_{j=0}^n (1+u^j z)^{-{n\choose j}}
{n\choose j} \left({n\choose j}-1\right) (1+u^j z)^{{n\choose j}-2}
j^2 u^{2j-2} z^2 \right|_{u=1}
\\ = z^2 (1+z)^{2^n-2} \sum_{j=1}^n j^2
{n\choose j} \left({n\choose j}-1\right).$$
The third is
$$\left. 2\prod_{j=0}^n (1+u^j z)^{n\choose j}
\sum_{j=0}^n (1+u^j z)^{-{n\choose j}}
{n\choose j} (1+u^j z)^{{n\choose j}-1}
j u^{j-1} z
\\ \times
\sum_{k=j+1}^n (1+u^k z)^{-{n\choose k}}
{n\choose k} (1+u^k z)^{{n\choose k}-1}
k u^{k-1} z
\right|_{u=1}
\\ = 2 z^2 (1+z)^{2^n-2} \sum_{j=0}^n {n\choose j} j
\sum_{k=j+1}^n {n\choose k} k.$$
The coefficients on these last two may be joined and we get
$$-\sum_{j=1}^n j^2 {n\choose j}
+ \left(\sum_{j=1}^n j {n\choose j} \right)^2
\\ = -\sum_{j=1}^n j(j-1) {n\choose j} - \sum_{j=1}^n j {n\choose j}
+ \left(n \sum_{j=1}^n {n-1\choose j-1} \right)^2
\\ = - n(n-1)\sum_{j=2}^n  {n-2\choose j-2} - n \sum_{j=1}^n {n-1\choose j-1}
+ n^2 2^{2n-2}
\\ = - n(n-1) 2^{n-2} - n 2^{n-1} + n^2 2^{2n-2}
= n^2 2^{2n-2} - n(n+1) 2^{n-2}.$$
Extracting coefficients we get for the second factorial moment
$$\frac{1}{4} n(n-1)m
+ (n^2 2^{2n-2} - n(n+1) 2^{n-2}) \frac{m(m-1)}{2^n(2^n-1)}$$
or alternatively
$$\mathrm{E}[S(S-1)] =
\frac{1}{4} n(n-1)m  + \frac{1}{4} \frac{m(m-1)}{2^n-1}
(n^2 2^{n} - n(n+1)).$$
Finally recall that
$$\mathrm{Var}[S] = \mathrm{E}[S(S-1)] + \mathrm{E}[S] - \mathrm{E}[S]^2$$
so the answer to the problem posed by the OP is
$$\bbox[5px,border:2px solid #00A000]{
\mathrm{E}[S] = \frac{1}{2} nm}$$
and
$$\bbox[5px,border:2px solid #00A000]{
\mathrm{Var}[S] =
\frac{1}{4} n(n+1)m  + \frac{1}{4} \frac{m(m-1)}{2^n-1}
(n^2 2^{n} - n(n+1))
- \frac{1}{4} n^2 m^2.}$$
As a sanity check when $m=2^n$ and all coupons have been drawn we have
deterministically that
$$\mathrm{E}[S] = \sum_{j=0}^n j {n\choose j}
= n \sum_{j=1}^n {n-1\choose j-1} = n 2^{n-1} = \frac{1}{2} n m$$
and the check goes through.
With  this  problem  requiring  careful  algebra  I  also  coded  a
simulation of the coupon collector that  is featured here which was in
excellent agreement on all values  that were tested (outputs first
and second  factorial moment).  Some optimizations  are still possible
which is left as an exercise to the reader.

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <string.h>

int main(int argc, char **argv)
{
  int n = 4 , m = 2, trials = 1000;

  if(argc >= 2){
    n = atoi(argv[1]);
  }

  if(argc >= 3){
    m = atoi(argv[2]);
  }

  if(argc >= 4){
    trials = atoi(argv[3]);
  }

  assert(1 <= n);
  assert(1 <= m && m <= 1 << n);
  assert(1 <= trials);

  int all = 1 << n;
  int bincfs[n+1];

  bincfs[0] = 1;
  for(int k = 1; k <= n; k++)
    bincfs[k] = bincfs[k-1]*(n+1-k)/k;

  srand48(time(NULL));
  long long data = 0, dataV = 0;

  for(int tind = 0; tind < trials; tind++){
    int src[1 << n];

    int srcpos = 0;
    for(int k = 0; k <= n; k++)
      for(int r = 0; r < bincfs[k]; r++)
        src[srcpos++] = k;

    int steps = 0; int sum = 0;

    while(steps < m){
      int cpidx = drand48() * (double)(all-steps);
      int coupon = src[cpidx];

      for(int cind=cpidx; cind < all-steps-1; cind++)
        src[cind] = src[cind+1];

      steps++;
      sum += coupon;
    }

    data += sum;
    dataV += sum*(sum-1);
  }

  long double
    fm1 = (long double)data/(long double)trials,
    fm2 = (long double)dataV/(long double)trials;

  printf("[n = %d, m = %d, trials = %d]: %Le, %Le\n",
         n, m, trials, fm1, fm2);

  exit(0);
}
Comment: Congratulation on this very complete and useful answer =)
Comment: Thank you for the kind remark, it was a somewhat unusual problem.
Answer: Can you find the expectation of the value of one ticket?  Now use the linearity of expectation.  Can you find the variance of the value of one ticket?  Look up the definition.  What is the variance of a sum?
Answer: You can easily deduce that, with $X$ the ticket number variable : $$\forall i \in [0,n], P(X = i) = {{n\choose i}\over 2^n}$$
From there, you can apply the formula for expectation :
$$E(X) = \sum_{i=0}^n P(X=i)\cdot i=\sum_{i=0}^n {{n\choose i}\over 2^n}\cdot i$$
Then the formula for variance :
$$V(X) = E[(X-E(X))^2]$$
Comment: Since tickets are not replaced, this is expectation for the value of the first ticket only?
Comment: You're absolutely right @dEmigOd, and since the probability isn't equiprobable we can't just say $E(S)=m\cdot E(X)$.

Looks like I missed the point of the author's post :/
Comment: If $X_i$ denotes the number appearing on the $i$th ticket $(i=1,2,...,m)$, then sum of the numbers on the tickets drawn is $X=\sum_{i=1}^mX_i$. The probability distribution of $X_i$ is precisely what you have stated,i.e., $P(X_i=k)=\frac{1}{2^n}{\binom{n}{k}}$ for $k=0,1,...,n$. So the problem can be definitely solved using this.
Comment: My computation is right for the first draw but since it's without replacement and the tickets are not equiprobables I don't think we can conclude.
Answer: Without resorting to generating functions we can do the following:
Let $X_i$ denote the number on the $i$th ticket for $i=1,2,...,m$, so that $S=\sum\limits_{i=1}^mX_i$.
The pmf of $X_i$ for all $i=1,2,\ldots,m$ is then $$P(X_i=k)=\begin{cases}\frac{1}{2^n}\binom{n}{k}&,\text{ if } k=0,1,\ldots,n\\\\\quad0&,\text{ otherwise}\end{cases}$$
Since $\operatorname{E}(X_i)=\frac{n}{2}$, it follows that $$\operatorname{E}(S)=\frac{mn}{2}$$
Again $\operatorname{E}(X_i^2)=\frac{n(n+1)}{4}$, giving $$\operatorname{Var}(X_i)=\operatorname{E}(X_i^2)-(\operatorname{E}(X_i))^2=\frac{n}{4}$$
The calculation of variance of $S$ is a bit more involved.
\begin{align}
\operatorname{Var}(S)&=\sum_{i=1}^m\operatorname{Var}(X_i)+2\sum_{i<j}\operatorname{Cov}(X_i,X_j)
\\&=m\cdot\frac{n}{4}+2\binom{m}{2}\rho\cdot\frac{n}{4}\qquad,\small\rho\text{ is the correlation  between $X_i$ and $X_j$}
\\&=\frac{mn}{4}\left(1+(m-1)\rho\right)\tag{1}
\end{align}
Now observe that $$\operatorname{Var}\left(\sum_{i=1}^{\color\green{2^n}}X_i\right)=0\tag{2}$$, the sum within parentheses being a constant.
Moreover the joint distribution of $(X_i,X_j)$ for all $i\ne j$ is independent of $m$.
So we can replace $m$ by $2^n$ in $(1)$ to get from $(2)$:
$$\frac{n2^n}{4}(1+(2^n-1)\rho)=0$$
That is, $$\rho=\frac{1}{1-2^n}$$
Substituting the value of $\rho$ in $(1)$, we get $$\operatorname{Var}(S)=\frac{mn}{4}\left(1+\frac{m-1}{1-2^n}\right)$$


Find the number of non-negative integer solutions of the equation $x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 57$ where $x_1 \lt 3, x_3 \ge 4$

Question: Find the number of non-negative integers to
$$x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 57$$ where $$x_1 \lt 3, x_3 \ge 4$$
I first found the total number of solutions N=$57+6-1\choose57$=6471002, then the total number of equations for the restriction $x_1 \ge 3$, N(P1)=$54+6-1\choose54$=3425422, then for the restriction $x_3 \le 3$, N(P2)=$4+6-1\choose4$=126 and I have to find the number of solutions for both the restrictions N(P1P2), but I don't know the number I should plug in the combination formula or if my calculations are correct.
Comment: How did you get $54+6-1\choose54$? That's really all there is to it. Just do it to $x_3$ rather than $x_1$, and simplify the problem _before_ trying to use inclusion-exclusion.
Comment: The way you handled the $x_1\geq 3$ restriction you can also handle the $x_3\geq 3$ restriction. Which is to say, remove the restriction and say you want $x_1+x_2+x_3+x_4+x_5+x_6 = 54$ instead. That's one less thing to worry about.
Comment: Can you elaborate?
Comment: I see now that we have $x_3\geq 4$ rather than $x_3 \geq 3$. So apologies for the confusion there. Still, that's something I would suggest you take care of first, and _then_ set to find the number of solutions. Like was suggested in the naswer below.
Answer: This problem is equivalent to distribute $57$ candies to $6$ kids. To eliminate $x_3\ge4$ restriction, let's give $4$ candies to $x_3$. So problem is now
$x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 53$ with $x_1\le2$
I prefer Stars and Bars method see here.
$x_1=0:\quad$ $ x_2 + x_3 + x_4 + x_5 + x_6 = 53$. This implies we have $53$ stars and $4$ bars and we use Permutations with Repetition see here
$$\frac{57!}{53!4!}$$
$x_1=1:\quad$ $ x_2 + x_3 + x_4 + x_5 + x_6 = 52$
$$\frac{56!}{52!4!}$$
$x_1=2:\quad$ $ x_2 + x_3 + x_4 + x_5 + x_6 = 51$
$$\frac{55!}{51!4!}$$
So the answer is $$\frac{57!}{53!4!}+\frac{56!}{52!4!}+\frac{55!}{51!4!}$$
Comment: How did you get x1≤2?
Comment: Because $x_1<3$ and it is non-negative integer, $x_1<3\equiv 0\le x_1\le2$
Comment: This is a [combinations with repetition](https://en.wikipedia.org/wiki/Combination#Number_of_combinations_with_repetition) problem.
Answer: First eliminate the lower bound
x3>=4 ..lets take x3-4>=0 take x3-4 = y
so our equation gets reduced to
x1+x2+y3+x4+x5+x6=57-4=53
NO of solution of this equation can be obtained from stars and bars concept.
divide 53 identical balls in 6 distinct boxes.
C(53+6-1,6-1) = 58!/53!5! = 4582116
Now we have to eliminate all those cases where x1>=3
take y1=x1-3>=0
our equation gets reduced to
y1+x2+y3+x4+x5+x6=53-3=50
solution of this equation is
C(50+6-1,6-1) = 55!/5!50!=3478761.
We need to remove these solutions to satisfy our equation
Total number of solutions = 4582116-3478761= 1103355
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).


unable to remove 2nd instance of a value within a string

Question: i know that the str_replace( )  will remove an instance of a string.
but how do i remove just one instance of a string within a string.
below is the example of a URL address, i only want to remove the first instance of the  exampleDirecotry/`
www.example/exampleDirectory/exampleDirectory/index.php

i need to first test that there are two instance of exampleDirectory/ and if so, remove one of them.
$url  = www.example/exampleDirectory/exampleDirectory/index.php

if ($url ==  )
{
  $newURL  = str_replace($url, "", "exampleDirectory/");

}

Comment: `$newURL  = str_replace("e/exampleDirectory/", "e", $url);`  would be an option ?
Comment: You should have a look at `substr_replace()`, first you must find the offset and length of the string you would like to replace.
Comment: hi everyone. i only want to remove the first instance of exampleDirecotory/.
Answer: You have made very simple error, Paul. I do it from time to time as well.
The proper sequence of parameters is:
str_replace($search, $replace, $subject)

The easiest way:
$newURL = str_replace("/exampleDirectory/exampleDirectory",
                      "/exampleDirectory", $url);

Answer: You could do this by finding the offset and length of the first substring. To check so there are more than one instance you could use substr_count():
$search = "exampleDirectory/";
// check so the string exists more than once
if (substr_count($url, $search) > 1) {
  $length = strlen($search);
  $offset = strpos($url, $search);
  // replace the first occurance of the string
  $newURL = substr_replace($url, "", $offset, $length);
}


Windows Shares / NTFS permissions on folder redirection in Active Directory

Question: A client has folder redirection in AD setup on each user's Home Folder set to the Z:\ drive as \server\share\username. A Group Policy redirects the user's Documents to the user's Home Folder with the option 'Grant the user to exclusive rights to Documents' selected.
The share on the server has permissions for the relevant user security group with 'Full Control', but each user's folder only have NTFS permissions only for 'CREATOR OWNER' and 'Domain Admins'.
Why can the different users access other user's folders? I thought the most restrictive permissions applied effectively between the share and the NTFS permissions.
Also, this setup has been like this for years, and this client recently updated all client computers to Windows 7. What is the best way to setup this redirection now? I assume only in Group Policy, also Basic Redirection - to create a folder for each user under the root path?
Comment: What security principal is the owner of the folders?
Comment: The root folder as well as the subfolders' Owner is servername\administrators. And added to this group is Domain Admins and Power Users (Users who need local admin rights). I can access all folders with a non-Power User as well.
Answer: On one of the folders, Security tab > Advanced button, you can use the Effective Permissions tool to determine exactly what permissions are conferred to a particular security principal.
I would suspect that a user may have elevated permissions or rights that you are not aware of.  This may occur due to inadvertent or inappropriate rights assignment or group membership nesting.
gpresult may be used on a user's station where they are logged on to get a complete report of their actual group membership.  Or if you have access to a computer where one of the users has recently logged on, you can run gpresult /user domain\username /h gpresult.html to generate the rsop data from their local profile.


How to fetch data from database in mail template

Question: I'm desperatly trying to get data from the database using a custom module (which is based on ubercart funds) to send a costomized email.
Here is how it makes email :
drupal_mail('ubercart_funds', 'escrow_cancel_from', user_load($transaction['uid'])->mail, language_default(), array('transaction' => $transaction['transaction_id']));

Implementing the mail template :
function ubercart_funds_theme() {
  return array(
'escrow_cancel_from' => array(
          'variables' => array('transaction' => NULL),
          'template' => 'theme/emails/ubercart-escrow-cancel-from',
      ),
   )
}

Sending the email :
function ubercart_funds_mail($key, &$message, $params) {

  $message['headers']['MIME-Version'] = '1.0';
  $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
  $message['headers']['Content-Transfer-Encoding'] = '8Bit';

  if ($key == 'escrow_cancel_from') {
    $message['subject'] = token_replace('Escrow Payment at [site:name] was Cancelled');
    $message['body'][] = theme('escrow_cancel_from', array('transaction' => $params['transaction']));
  }
}

}
And in the template (ubercart-escrow-cancel-from.tpl) :
$transaction = db_query("SELECT * FROM {ubercart_funds_transactions} WHERE transaction_id=" . $variables['transaction']);

So actually I should have all the data from ubercart_funds_transactions which store the amount for example. But impossible to get any values. Moreover I would like to have the user name whereas I just have the user uid in ubercart_funds_transactions. So I tried to load it with user_load() but things seems to be protected ... Here is what I get if I do a print_r($transaction); :
DatabaseStatementBase Object ( [dbh] => DatabaseConnection_mysql Object ( [needsCleanup:protected] => [target:protected] => default [key:protected] => default [logger:protected] => [transactionLayers:protected] => Array ( ) [driverClasses:protected] => Array ( [SelectQuery] => SelectQuery [DatabaseSchema] => DatabaseSchema_mysql [UpdateQuery] => UpdateQuery ) [statementClass:protected] => DatabaseStatementBase [transactionSupport:protected] => 1 [transactionalDDLSupport:protected] => [temporaryNameIndex:protected] => 0 [connectionOptions:protected] => Array ( [database] => **** [username] => **** [password] => ****, [host] => localhost [port] => [driver] => mysql [prefix] => Array ( [default] => ) ) [schema:protected] => DatabaseSchema_mysql Object ( [connection:protected] => DatabaseConnection_mysql Object *RECURSION* [placeholder:protected] => 0 [defaultSchema:protected] => public [uniqueIdentifier:protected] => 5989e447343638.05601838 ) [prefixes:protected] => Array ( [default] => ) [prefixSearch:protected] => Array ( [0] => { [1] => } ) [prefixReplace:protected] => Array ( [0] => [1] => ) [escapedNames:protected] => Array ( [cache_bootstrap] => cache_bootstrap [registry] => registry [name] => name [filename] => filename [cache] => cache [base.uid] => base.uid [base] => base [uid] => uid [pass] => pass [mail] => mail [theme] => theme [signature] => signature [signature_format] => signature_format [created] => created [access] => access [login] => login [status] => status [timezone] => timezone [language] => language [picture] => picture [init] => init [data] => data [users] => users [base.fid] => base.fid [fid] => fid [uri] => uri [filemime] => filemime [filesize] => filesize [timestamp] => timestamp [file_managed] => file_managed [cache_field] => cache_field [m.entity_type] => m.entity_type [m.entity_id] => m.entity_id [m] => m [entity_id] => entity_id [revision_id] => revision_id [metatag] => metatag [cache_rules] => cache_rules [cache_form] => cache_form [ubercart_funds_user_funds] => ubercart_funds_user_funds [transaction_id] => transaction_id [ubercart_funds_transactions] => ubercart_funds_transactions [cache_token] => cache_token ) [escapedAliases:protected] => Array ( [name] => name [filename] => filename [uid] => uid [pass] => pass [mail] => mail [theme] => theme [signature] => signature [signature_format] => signature_format [created] => created [access] => access [login] => login [status] => status [timezone] => timezone [language] => language [picture] => picture [init] => init [data] => data [fid] => fid [uri] => uri [filemime] => filemime [filesize] => filesize [timestamp] => timestamp [entity_id] => entity_id [revision_id] => revision_id ) ) [queryString] => SELECT * FROM ubercart_funds_transactions WHERE transaction_id=39 )

How can I get the amount and user name ? What am I doing wrong ?
Answer: You're not getting the transaction data because you haven't executed the statement:
$transaction = db_query(...)->fetchObject();

A couple of other notes:

Don't run queries in the template, use a preprocess function to set up the vars and pass them in.
Don't concatenate parameters into an SQL string, you'll leave yourself wide open to injection attacks.

All-in-all, something like:
function mymodule_preprocess_escrow_cancel_from(&$vars) {
    $sql = 'SELECT * FROM {ubercart_funds_transactions} WHERE transaction_id = :id';
    $args = [':id' => $vars['transaction']];
    $vars['transaction'] = db_query($sql, $args)->fetchObject();

    $vars['user_name'] = $GLOBALS['user']->name;
}

That will convert the $transaction variable in your template into the object loaded from the DB, and give you the user name in $user_name too.
You'll need to clear cache after adding the preprocess function for the registry to pick it up.
Comment: Thanks ! It works perfectly and thank you for your security advises. I delete SQL call from my emails templates.
Comment: Just a little question, if I can avoid to create a new post. Why I can't fetch users data with `$from_user = user_load($transaction->reference)`;. When I print_r $transaction I get `stdClass Object ( [transaction_id] => 122 [uid] => 50 [reference] => 40 [created] => 1502362883 [amount] => 100 [type] => Cancelled Escrow Payment [notes] => #2 )` and so when I call the function using the website I get this error : `Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load()`


Send email with URL of same page as the email link?

Question: We have a page that displays a logged-in user's selections from a Flag Lists process. The page includes code to generate the specific URL of that page, so it can be copied and pasted elsewhere. (essentially a "share this" type of thing, but this is definitely not intended for social media) That code is:
    " onclick="this.select();" />
We want to provide an email link (ideally, a button) which sends a preformatted message including this URL, to a specific person's email address. (i.e. always to the same person) I am having trouble visualizing how this can be done, since the interface I am using for adding an email link (via CK Editor) isn't able to process the "current-page:url" PHP code and just displays it as code in the resulting message.
Any suggestions? -- Thanks! --
Answer: insert a Drupal token of the current page url into the WYSIWYG. This token is provided by drupal 7 core I believe.
See the Token Insert module.

This module allows you to insert tokens into a textarea. It supports
  both plain text and wysiwyg textareas. The format used for the insert
  is compatible with Token Filter.
This module contains three modules:

Token Insert UI: Allows you to select which tokens are available for
  the insert, by default all tokens are shown. This module doesn't have
  to be enabled to use the others.
Token Insert (text): Add a fieldset
  under each textarea, works for both plain text fields and wysiwyg
  fields.
Token Insert (wysiwyg): Adds an extra button to wysiwyg
  editors and opens a popup to select the token to insert.


Wrapping JSF components with DIV

Question: I have DIV element with a header style enclosing a h:outputText but when the page renders i see the HTML is formed in such a  way that my div doesnot contain the label generated by the h:outputText instead i see the label above my DIV . Am i doing it wrong? i tried f:verbatim but didn't help either
Comment: In future questions, please explicitly mention JSF version used.
Answer: Based on your question history you're using the ancient JSF 1.1. The <f:verbatim> way should work. Perhaps you've enclosed JSF components inside <f:verbatim>. You should not do that. It should only contain raw HTML.
<f:verbatim>
</f:verbatim>
    <h:outputText value="Some text." />
<f:verbatim>
</f:verbatim>

Since JSF 1.2 the <f:verbatim> is not necessary anymore. JSF 1.2 should work on all environments where JSF 1.1 is been used. I strongly recommend to upgrade.
See also:

Mix HTML and JSF in a JSF subview
What are the main disadvantages of Java Server Faces 2.0? (a bit of history)

Wrapping JSF components with DIV


top-bar button bad css positioning float right

Question: I have a bar with a title on the left and  buttons inline on the right, the buttons can be one, two or three added dinamically, and can be or link syled like a button or input button, if you see this code with firefox the buttons are overlapping, with chrome and explorer buttons alignment is wrong
CSS:
html, body {
height : 99%;
margin : 0;
padding : 0;
font-family : Arial, Helvetica, sans-serif;
font-size : 85%;
color : #333399;
}
h2 {
font-size : 170%;
margin : 0;
color : #333399;
}
#title {
position : relative;
width : 70%;
background-color : #BAB3D6;
padding : 10px 0 10px 16px;
margin-left : auto;
margin-right : auto;
margin-bottom : 3px;
-moz-border-radius-topleft: 10px;
-webkit-border-top-left-radius: 10px;
 border-top-left-radius: 10px;
-moz-border-radius-topright: 10px;
-webkit-border-top-right-radius: 10px;
border-top-right-radius: 10px;
}
#title a{
color: white;
text-decoration: none;
}
#title div {
float : right;
margin-top : -22px;
margin-right : 30px;
}
.button {
 background-color : #333399;
 border : 0;
 padding : 6px 20px;
 text-decoration : none;
  color : white;
cursor : pointer;
 border-radius : 10px;
 -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
 }
 .button:active {
  text-decoration: none;
  position : relative;
  top : 1px;
   }

HTML:

title

add

edit

<input class="button" type="submit" name="delete_button" value="delete" />

jsfiddle : http://jsfiddle.net/zL4P6/
Comment: "buttons alignment is wrong" is not helpful. you need to explain both what is happening AND what you want to happen instead. Instead of reposting your code above, I suggest photoshopping an image that shows what you want.
Comment: maybe if you see the jsfiddle with different browser you know what I want..
Answer: You have to change your HTML markup at some aspect to achieve whatever you want. See i've implemented the desired layout. Hope it will help you
HTML

title

add

edit

            <input class="button" type="submit" name="delete_button" value="delete" />

 // Added clearfix to floats

CSS
html, body {
    height: 99 %;
    margin: 0;
    padding: 0;
    font - family: Arial, Helvetica, sans - serif;
    font - size: 85 %;
    color: #333399;
}

h2 {
    font-size: 170%;
    margin: 0;
    color: # 333399;
    float: left; /* New property added */
}

#title {
    position: relative;
    width: 70 %;
    background - color: #BAB3D6;
    padding: 10px 0 10px 16px;
    margin - left: auto;
    margin - right: auto;
    margin - bottom: 3px;
    - moz - border - radius - topleft: 10px;
    - webkit - border - top - left - radius: 10px;
    border - top - left - radius: 10px;
    - moz - border - radius - topright: 10px;
    - webkit - border - top - right - radius: 10px;
    border - top - right - radius: 10px;
}

    #title a {
        color: white;
        text - decoration: none;
    }

.buttons { /*  New class added */
    float: right;
}

    .buttons div {
        display: inline - block;
    }

.button {
    background - color: #333399;
    border: 0;
    padding: 6px 20px;
    text-decoration: none;
    color: white;
    cursor: pointer;
    border-radius: 10px;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
}

    .button:active {
        text-decoration: none;
        position: relative;
        top: 1px;
    }

.clear { /* new class added */
    clear: both;
}

Fiddle
See i have mentioned changes with comments in above code
Answer: There is a much cleaner, more logical way of implementing this, please see the below HTML/CSS.
Demo Fiddle
HTML

Title

Delete

<button>Edit</button>

<input type='submit' value='Add'/>

CSS
body {
    width:100%;
    text-align:center;
}
div {
    background:#BAB3D6;
    display:inline-block;
    border-radius:10px 10px 0 0;
    padding:10px;
    font-weight:bold;
    font-size:18px;
    color:#333399;
    font-family:arial;
}
ul {
    list-style:none;
    margin:0;
    padding:0;
    display:inline-block;
    margin-left:300px;
}
ul li a, ul li button, ul li input[type=submit]{
    color:white;
    text-decoration:none;
    background:none;
    border:none;
    display:inline-block;
    margin:0;
    padding:0;
    cursor:pointer;
    line-height:15px;
    font-size:12px;
    font-weight:bold;
}
ul li {
    display:inline-block;
    color:white;
    font-size:12px;
    background:#333399;
    border-radius:10px;
    padding:5px 10px;
    margin:0 5px;
}

Comment: the buttons can be link button styled but also input type


How to rename machines after image install

Question: Today I am deploying 20 brand new Dell workstations.  These will all be for public use at a local library and will be replacing 20 older workstations, which will be moved to another branch of the library, all today and by me alone.
Once deployed, I have a new image for all 40 machines.  Immediately after imaging, I need to change the name of each machine to a name that will be determined shortly before deployment.
Is there a script that I could work into a batch file or wmi which can be run from the desktop and will prompt me to enter a new name and workgroup for the machine?  Is this the easiest way to change the name and workgroup of 40 machines?  I have to visit each desktop anyway to configure Windows SteadyState Disk Protection.
I'm not a stranger to WMI and batch files and I usually wouldn't ask for help writing one, but it's late and I am running out of time and haven't been able to come up with anything that will suffice.
Any other info would be appreciated also.  I have been doing this for years, but could always use some help.  Thanks in advance.
Answer: You can (and you should!) run sysprep before capturing the master image, and then customize the installation using sysprep.inf, leaving the fields for computer name and domain blank; this way, all other installation steps will be automated, but computer name and domain will be asked during setup.
Comment: you need to run sysprep anyway otherwise your machines will have the same SID which is bad
Comment: Duplicate SIDs are actually a non-issue, contrary to conventional wisdom... http://blogs.technet.com/markrussinovich/archive/2009/11/03/3291024.aspx
Comment: Thanks for the info...I have read about this in the past and the SteadyState manual refers to and recommends it, but I am not sure what advantage over a quick batch file it has.  It looks like it takes 6-10 additional minutes per machine of my time.
Comment: Nice blog post, but what if a domain computer needs to authenticate against another one *as itself*? Wouldn't the computer SID get involved here?
Answer: As has been mentioned, You should use sysprep on the master computer that you're generating the image from. Not only does sysprep handle the generation of a new, unique SID for each machine but it also allows mini-setup to run on each machine so that the hardware can be detected and the correct drivers installed. Using an image without sysprep may lead to hardware issues. For instance, each NIC in the computer has a unique GUID, without sysprep each cloned machine will have the same GUID for the NIC which can lead to flaky network functionallity.
Answer: You should check out the following link. This is a software tool to change your sid and computer name.
http://technet.microsoft.com/en-us/sysinternals/bb897418.aspx
To use NewSID's auto-run option, specify "/a" on the command line. You can also direct it to automatically change the computer's name by including the new name after the "/a" switch. For example:
newsid /a [newname]
Comment: newsid has been retired: http://blogs.technet.com/markrussinovich/archive/2009/11/03/3291024.aspx
Answer: Thanks for the advice guys.  I really wasnt interested in sysprep, so I didnt use it...and after reading this post I was pretty comfortable with NOT using it.
What I was looking for was a script to change the name of the machine, which I did eventually find.
As always, I appreciate everyones time here.
Thanks again.
Answer: I agree with Bob.  I have always used newSid.  It doesn't have the option to add to a domain, so I have to call it in a script the will run NewSid without a reboot, add it to the Domain, the reboot.  I love this tool.
Answer: And the author of NewSID disagrees with Bob in his The Machine SID Duplication Myth


Delete LVM and anything related to it

Question: I want to delete /dev/sdb disk from the server. Before doing that I guess I should remove lvm and anything related to it. I don't care about /dev/sdb1 data.
I'm trying to follow this article https://www.golinuxhub.com/2014/03/how-to-remove-logical-and-physical.html
lvremove /dev/mapper/VolGroup01-LogVol00

but during the second command I get the following error
vgreduce VolGroup01 /dev/sdb1
Can't remove final physical volume "/dev/sdb1" from volume group "VolGroup01"

Also tried vgchange -an VolGroup01
and then  vgreduce VolGroup01 /dev/sdb1 but still same error.
Answer: You are trying to "reduce" a volume group to nothing. Instead, to delete it, use vgremove.
vgremove VolGroup01

Now you can remove the LVM volume label from the physical volume with pvremove.
pvremove /dev/sdb1

And now you can remove or repurpose the disk.
Comment: @user Yes, that removes the logical volume.
Comment: okay thanks. Makes sense
Answer: FWIW, I had given myself a headache from aborting in the middle of pvmove operation and vgremove was getting a "busy" error. The solution was to use pvremove --force --force (yes, the --force flag twice).
In your situation:
pvremove /dev/sdb1 --force --force

Then, I could finally use:
vgremove VolGroup01

Of course, everything on sdb1 was lost, but I was able to remove the LVM and start over.

Delete LVM and anything related to it


Prime numbers of the form $ n^{34} -9$

Question: For what positive integer values of $n$ where $n^{34}-9$ is a prime.
I am not getting how to approach this one.
Any help will be truly appreciated.
Comment: Note that $x^2-y^2 = (x+y)(x-y)$.  So, $n^{34}-9 = (n^{17})^2-3^2=\dots$ and this is definitely *not* prime for...
Comment: sorry it was very trivial
Answer: $n^{34}-9=(n^{17}+3)(n^{17}-3)$ so it is never prime as there is no value of $n$ that makes one of the factors $1$.

Prime numbers of the form $ n^{34} -9$


Kubernetes, Docker and vm.max_map_count

Question: While attempting to run ElasticSearch on K8 I ran into an error that would kill the container:
max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
Fortunately this is pretty well documented and I was able to figure out a configuration setting for the container that got it stable. This question isn't about that.
The question that arises for me is why does this happen on K8 versus Docker? I'm using the same image (The official ES image) in both cases so what are some of the reasons why the value would be different? Is there a way I could configure K8 or the machines I'm running it on so that this situation wouldn't arise?
Answer: The setting for vm.max_map_count can be changed on the host level. Your can read the current value like this: sysctl vm.max_map_count. To change it run: sudo sysctl -w vm.max_map_count=262144. This will be reverted by the next boot. To set it permanently add vm.max_map_count=262144 to /etc/sysctl.conf.
Most Elasticsearch setups for Kubernetes use an Init Container to make sure this value is set like required. The drawback here is that it needs to in privileged mode: Elasticsearch Helm Chart
It is also possible to set sysctls in the securityContext of a Pod. But for now virtual memory settings are considered unsafe and need some more tweaking on your Kubernetes setup.
Comment: So if I'm understanding you, this value is persisted from the host itself. So it's less about Docker vs. K8 and more that the OS on my bare metal machine has vm.max_map_count set higher so when I load up Docker it provides that value to the containers. And it's likely the OS running the instances of K8 I'm connecting to have a different vm.max_map_count value.
Comment: Yes, I would guess so. Can you maybe read out the values with `sysctl vm.max_map_count`?
Comment: @WillNilges No, this is a Kernel setting and the Kernel is shared by all containers. Specific settings for containers are possible via [control groups](https://en.wikipedia.org/wiki/Cgroups).
Comment: I don't have access to do this on the K8 hosts so I'm trying to make sure I'm using the correct language when I ask the people who do.
Comment: Apologies for dragging this out, but is there a way to set this value for one container only? Perhaps this can be discussed in chat.

Kubernetes, Docker and vm.max_map_count


Prove that $f(x,y) = \sqrt{x^2 + y^2}$ is continuous at $a=(3,\frac{1}{2})$

Question: I'm seriously struggling with understanding how to do these problems.
I start with the theorem:

$\forall\,\epsilon >0,\ \exists\,\delta>0$ s.t.
$d[(x,y),(c,d)] < \delta$ $\implies$ $d(f(x,y), f(c,d)) < \epsilon$

I know the above is just the general theorem but I think it's good to have visible.
Thank you in advance for your help.
Comment: What does $a = (3,{1 \over 2})$ have to do with anything?
Comment: One moment. I made a mistake. I had moved to a diferent problem and copied my work from that down. My apologies.
Comment: So then fix it!!!
Comment: There I have fixed it.
Comment: No you haven't.  In the title you're saying that $a$ is a two-dimensional point  but in the body it is a scalar.  And why do you need that point in the title anyway?  It is arbitrary and doesn't help anyone find or solve your problem.  Also, the title itself is vague and unclear otherwise.
Comment: I am given exactly, "Prove that the functions are continuous at a. Then I am given the function as in the title and I am given a as in the title. Is what I have in this comment not clearly expressed in my title? If so please let me know. I'm not trying to be confusing.
Comment: Oh I see where the confusion came from. I meant the theorem I added as a general theorem and not for the a provided. I will change it so it's not as confusing. I just meant that this was the definition I felt was correct to use.
Answer: The so-called "theorem" is indeed a definition which goes as follows:
$f:\mathbb{R}^2 \to \mathbb{R}$ is continuous in $(a,b)\in\mathbb{R}^2$ if there for any $\epsilon>0$ exists a $\delta>0$ such that for any $(x,y)\in\mathbb{R}^2$ with  $d((x,y),(a,b))<\delta$ then $d(f(x,y),f(a,b))<\epsilon$.
Now to show that $f(x,y)=\sqrt{x^2+y^2}$ is indeed continuous everywhere on $\mathbb{R}^2$, we first fix an arbitrary $(a,b)$ and $\epsilon>0$. Note that $f$ is indeed the Euclidean norm on $\mathbb{R}^2$, so we can use the reverse triangle inequality. For any $(x,y)\in\mathbb{R}^2$ with $|(x,y)-(a,b)|<\delta=\epsilon$ \begin{align}
d(f(x,y),f(a,b))&=|f(x,y)-f(a,b)| \\
&= |\sqrt{x^2+y^2}-\sqrt{a^2+b^2}|\\
&= |\, |(x,y)| - |(a,b)|\, | \\
&\leq |(x,y)-(a,b)| \\
&< \epsilon,
\end{align}
proving that $f$ is continuous in $(a,b)$ and since this was arbitrarily chosen we conclude that $f$ is everywhere continuous. This obviously assumes that both domain and co-domain of $f$ are equipped with the corresponding Euclidean metrics.
Comment: Thank you for your reply. My only question is, how do you go from $\sqrt{x^2 + y^2}$ to $|(x,y)|$?
Comment: @Nicklovn The norm of $(x,y)$, denoted here by $|(x,y)|$ is by definition $\sqrt{x^2+y^2}$, so your function is just the norm itself that we use to measure Euclidean distance.
Comment: I assumed that you have been introduced to the euclidean norm on $\mathbb{R}^2$ before talking about continuity of mappings from $\mathbb{R}^2$ to $\mathbb{R}$. Usually when we talk about continuity on Euclidean spaces we equip them with the Euclidean norm given by $|(x_1,...,x_n)| = \sqrt{x_1^2 + \cdots + x_n^2}$ for $(x_1,...,x_n)\in\mathbb{R}^n$.
Comment: Oh I understand. Thank you. Yes I am a little behind on this material. I'm a stats major and skipped the 200-level real analysis course so I'm just trying to stay up there with everyone else :)


Stopping memcached: [FAILED]. Why?

Question: My application seems to be having issues with memcached not stopping.
I'm using php, and have specific keys expiring after every hour. However those keys & values are not repopulating anymore.
When I run:
/etc/init.d/memcached restart

I get the following:
Stopping memcached:                                        [FAILED]
Starting memcached:                                        [  OK  ]

I have to run a killall memcached for memcached to stop. I then run a restart and everything is fine.
I'm not exactly sure what is causing this, but I need memcached to be restarting every hour.  Where should I be looking to find out what is causing this?
Comment: Inelegance is not the question there... but expiring all of a cache at one point in time is a good way to stampede the application under heavy load.
Comment: You need memcached to restart once an hour? Sounds like you've got some other problem you're trying to inelegantly solve, too. You can set an expiration time for memcached keys when you set them...
Comment: I won't comment on the why, but have a look at the PID recorded in /var/run/memcached (or similar) then compare it to the running PID of memcached.
Comment: Perhaps I was unclear, but the expirations are set once an hour in the php code. But the keys aren't being reset is the issue I'm trying to solve. Memcached doesn't need to be reset, just the keys/values.
Comment: Thank you for responding to the question Nick. That is one thing I've noticed. The memcached.pid is empty, I'm assuming it shouldn't be.
Comment: No, it shouldn't be. Is there some other process monitoring, or restarting memcached?
Comment: No, there isn't.
Answer: For me it was because I initially ran memcached -d manually.
Then later when I tried to run service memcached restart/stop, the stop command would fail. After killing the process manually service memcached restart/stop worked as expected.
Answer: On face value, I would suggest that something is making memcached crash. And if memcached isn't running when you try to stop it, it will fail (because it's stopped already). So that would explain why /etc/init.d/memcached stop (or the first part of /etc/init.d/memcached restart) is failing.
But then you go on to say that you need to run killall memcached to get it to stop. That would suggest to me an issue with your init system losing track of the process. As I don't know what init system you are using, it's hard to be sure.
Most distros these days use SystemD and I've had some edge case issues with Debian because of problems caused by the backwards compatibility with the old SysVinit scripts.
Looking at the commands you are using to control your service, you are directly calling the SysVinit script, so I'll assume that either you're using SysVinit, or SystemD with SysVinit compatability.
If you don't have any SystemD, then it's almost certainly something wrong with your initscript and/or memcached config.
If you do have SystemD, then it's likely being caused by some communication issues between your initscript and SystemD (and there could still be memcached config issues too). IMO, the best path forward there, would be to write a proper SystemD service file and use SystemD commands directly; i.e. systemctl COMMAND SERVICE_NAME.service. They're super easy to write, google will help you out (try something like "how to write systemd service file")

Stopping memcached: [FAILED]. Why?


Getting PHPStorm working with XDebug

Question: I am trying to get PHPStorm to talk to Xdebug, and am having very little luck.
Here is my setup:
I have a VM which shares my php files from my local machine
I am trying to follow this:
http://blog.jetbrains.com/webide/2011/02/zero-configuration-debugging-with-xdebug-and-phpstorm-2-0/
I put the following in my php.ini
<code>zend_extension = /usr/lib64/php/modules/xdebug.so
xdebug.remote_connect_back = 1
xdebug.remote_enable = 1
xdebug.remote_handler = dbgp
xdebug.remote_mode = req
xdebug.remote_port = 9000
xdebug.remote_host = <my ip address>
xdebug.remote_log = /tmp/xdebug_remote.log
</code>
It appears I successfully got xdebug running according to phpinfo().
I open my script, turn on the listener.  But when I get to the "Activate debugger on server" portion of the tutorial, things fall apart.  I download the firefox addon to start the debugger(this one: https://addons.mozilla.org/en-US/firefox/addon/easy-xdebug/), click the icon to start the debugger, reload the page, but phpstorm does not find it.  I also tried adding XDEBUG_SESSION_START=1 as a POST value yet still no luck.
What am I doing wrong?
Comment: Edited, changed IP address to my localhost IP address.  In addition I tried to debug on my VM via vim, and nothing.  I don't know whats wrong anymore.
Comment: can you ssh from your host into your vm?  Can you open a webpage using http://ip.of.vm?  What happens is that the xdebug will connect back to your ide at the ip address and port# (9000) you have specified.  If it cannot make a connection to port 9k for some reason, it will not work.
Comment: Full guide here: [How to debug code on a remote server (or in vagrant box) with PHPStorm](http://www.dev-metal.com/debug-code-remote-server-vagrant-box-phpstorm/)
Answer: You want your remote_host to be the ip address that the vm sees on your localhost.  It's not the IP address you get from your ISP.
Comment: Fixed that and still no luck :(
Comment: found the issue, this was part of it, the other issue was my httpd conf still have the incorrect port value in it.
Comment: With vagrant, I've had luck leaving `remote_host` empty and just using `remote_connect_back=1`.

Getting PHPStorm working with XDebug


List of GPO's for Windows Admins

Question: I am hoping we can get a list together of usful/must use GPOs for Windows Admins.
Maybe explain how to set them up and why they are helpful?
Comment: I would say that this is a duplicate of http://serverfault.com/questions/66049/what-group-policies-have-you-applied
Comment: I would say you are right.
Answer: check out http://www.microsoft.com/downloads/details.aspx?FamilyID=18c90c80-8b0a-4906-a4f5-ff24cc2030fb&displaylang=en
thanks,
mark
Answer: why would you need to apply GPO's spefically to Domain admins? Your question is a bit vague, can you explain what you are trying to achieve?
Comment: I was asking for a list of useful/common GPOs that Domain admins use on their domains, not on themselves.
Answer: There are so many things that you can do with GPO's. There aren't any specific templates only best practice. Look up the threats and countermeasures guide on Microsoft.com

List of GPO's for Windows Admins


Javax.validation - how to validate a Date attribute with a specifies date

Question: I have been trying validate a date attribute with java.util.Date class be means of javax.validation annotations.
I have found some annotation to do it, for instance: @Past, @PastOrPresent, @Future, @FutureOrPresent; however I need the validation will be with a specific date.
I am searching something like this:
<code>@Future("01/01/2019")
</code>
Does someone know how can I do it?. I would like to do it with annotation existing (I don't like to do it with custom annotations).
Regards.
Comment: You can use Hibernate validation framework to create an annotation like @Future and you can validate.
Comment: Hibernate validator framework provides simple way to create custom annotations.
Comment: ok, but of this way I should create a custom annotation right? or Does HIbernate's @Future annotation have attributes for doing that?
Answer: I was able to create the annotation of this way:
FutureCustom annotation
Interface:
<code>@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = FutureCustom.class)
public @interface FutureCustom {
    public abstract String max() default "";
    public abstract String message() default "Message";
    public abstract Class<?>[] groups() default {};
    public abstract Class<? extends Payload>[] payload() default {};
}
</code>
Class:
<code>public class FutureCustomImpl  implements ConstraintValidator<FutureCustom, Date> {

    private String max;

    @Override
    public void initialize(FutureCustom constraintAnnotation) {
        this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(Date value, ConstraintValidatorContext context) {
        //Validation using value and max like parameter in annotation
            // The max attribute will always be a String, you have to convert it to Date.
    }

}
</code>
Of this Way the annotation will be:
<code>@FutureCustom(max="10/10/2010")
</code>


Why does the mixture dependencies exist between variables?

Question: Sorry if my question is clear to most of you. As a mathematics background, I really just start working with the mixture and would like to understand it in a clear way. Mixture dependencies are when the dependencies structures between two variables come from different distribution. For example, if I have an air pollution data and would like to model the relationship between air pollution within cities in one state of a country and the cities over the country.  Then, this data will be a mixture since we have two different type of dependencies. If not, could someone help me with this using an example?
many thanks.
Answer:
Mixture dependencies are when the dependencies structures between two
  variables come from different distribution.

No. The finite mixture distribution is a distribution of a single random variable, that is defined in terms of a "mixture" of other distributions. The mixture probability density function $g$ is called a mixture of distributions $f_1,\dots,f_m$ when
$$
g(x) = \sum_{k=1}^m \pi_k \, f_k(x; \theta_k)
$$
where $\theta_1,\dots,\theta_m$ are the parameters and $\pi_1,\dots,\pi_m$ such that $0 \le \pi_k \le 1$ and $\sum_k \pi_k = 1$ are mixing proportions.
To give a real-life example, say that you are looking at the distribution of heights of teenagers. The distribution is a mixture of distributions of heights of boys and girls (that differ). If you knew who are the boys and girls in your data, you could model the distributions of their heights separately, or preferably in a hierarchical model, but if you are given the unlabeled data, then possibly two-component mixture would fit your data better, then "single", unimodal distribution.
Your air pollution example sounds rather like an example of mixed effects model.


Excel nested IF's

Question: I have found several sites that talk about work arounds but they all talk about doing some kind of mathematical equation, so this is the nested if's I am trying to fix.
<code>=IF((COUNTIF($A$137:$A$146,$C173)=1), 9203, IF((COUNTIF($A$161:$A$196,$C173)=1), 9202, IF((COUNTIF($A$199:$A$228,$C173)=1),9216, IF((COUNTIF($A$231:$A$255,$C173)=1),9222, IF((COUNTIF($A$258:$A$295,$C173)=1),9202, IF((COUNTIF($A$199:$A$228,$C173)=1),9216, IF((COUNTIF($A$298:$A$312,$C173)=1),9203, IF((COUNTIF($A$327:$A$361,$C173)=1),9202, IF((COUNTIF(A364:A383,$C173)=1),9219, Error)))))))))
</code>
Any tips?
Comment: The only obvious error is the use of the name 'Error' (without quotes). The word Error is seen here as a function, which is illegal. Try replacing it with quoted "Error". Alternatively, we will need more detail to go on...
Comment: As you've been a member of Stack Overflow for more than a month, never voted, never answered a question, and never accepted an anwer, let me post my welcome message (see below)
Comment: HuX, when editing a cell formula, you can use alt+enter to trigger a page break.  This can be very useful for debugging your code and making it easier to read.
Answer: The problem is in the last word Error. It's not a valid name in Excel. Replace for example with "Error"
Comment: @Kevin You posted your observation as a comment while I was elaborating my answer. So far, so good, but when you decide to post something as a comment it's just because you understand it's not an answer, or you are not sure about it, so you're not exposing neither to downvotes nor upvotes. Anyway, I saw your posting after posting mine.
Comment: You are correct, and no harm done.  I actually just expected the problem might be something more elaborate.  Perhaps not afterall.
Comment: @Kevin Me too. That's why I actually reviewed all those nested IFs and parens (a rather unpleasant job, I might say) :D
Comment: The problem isn't the Error... Excel doesn't allow over 7 nested if's so I need to find an alternate way
Comment: @Huxu7 that is version dependent. What version are you working on?

Excel nested IF's


Resolving chordal 7th, Counterpoint question

Question: This is the second episode of a fugue I have completed.  Here is the link to the full thing: https://musescore.com/williamjegertiii/g-major-fugue-adagietto-synth-and-beat
At any rate, I've been reviewing it and there is a musical problem that I can't seem to find the answer to.
Combining counterpoint theory and chord theory can prove difficult sometimes, because it's difficult to find "correct" answers.  Any answers that are "correct" in my mind are ones that are justifiable to me, not simply based on conventions.
I will paste a few measures.

The root chords are in the middle,  the annotations at the top are my own key analysis shorthand.  Link to my site where I explain this: https://musicofbach.com/locating-the-tonal-center-shorthand-understanding/
In short, any chord I post in the middle of the grand staff necessarily relates to the key I notated at the top.
Anyway, now the problem:
The episode begins on the 3rd measure of my pasted example.  In each measure from then on out, the phrase ends with a 7th chord.  Each of the 7th chords are in 6/5 inversion, yet do not resolve "conventionally" where the 3rd of the chord rises by step to the root of the next chord.  I opted not to do this because I like the descending bass line in each measure.
The problem, so to speak, is that the chordal 7th of the chord resolves up each time, whereas conventional thought says the 7th must resolve down.
Now, from a counterpoint perspective, dissonant 7ths must resolve by step to consonants.  Yet a 6/5 chord technically contains no dissonance, not with the bass at all.  The chordal 7th does indeed resolve by step to a consonant, just not down like conventional thought encourages.
I know counterpoint deals mainly with consonance/dissonance in relation to the bass itself, and this issue really only deals with the chord's 7th.

The episode ends in the first measure of the next pasted example, before entering into the final entry of the subject.
You will notice that in this measure, I include a 7th chord where the chordal 7th does indeed resolve down, and the 3rd of the chord does indeed resolve up to the root of the next.  In my mind, this somewhat rectified the problem.
However!
I'm looking for some outside opinions on the this matter.  I am grateful to any answer I receive.
Thank you!
Answer: I think the root of the problem (bad pun) is not so much that the 7th resolves upwards, but that the progression in the bass and treble after the fifth at the end of the bar isn't convincing.
If the treble goes from G to A, the bass can't make the obvious strong progression from C to D because of the parallel 5ths, but making the it go from C to F# (an augmented fourth) leaves the first beat of the following bar sounding weak.
I can't see a way out of that issue that doesn't involve a "complete rewrite" of the parts.
Answer: My opinion:
If I had a composition that sounds fine I wouldn't care about rules that are 200 years old.
Or I would add new rules or exceptions of rules like:
the rules resolving  the 3rd and 7th are only concerning the dominant 7 chord.
or:
in certain cases it is allowed to resolve  the 3rd of a 7th chord downwards,
the 3rd of a minor 7 chord has no leading tone tension so there's no need to resolve it upwards.
Answer: It is too busy, your motif has no chance to develop because you have to many non-chordal notes. You also make the habit  of having non chord notes on strong parts of the beat and then the return to  the chord on the weak part, this although not necessarily bad, is going to make it harder to get it convincing. That type of reimagaining will take a master to do well.  Let's do baby steps first.
You also only seem to have non chordal notes in two of the voices, I don't know why you would do that, that takes away from the piece.
Comment: In this piece, the strong beats are all on the count: 1, 2, 3 and 4.  In between these, I view it as all generally weak.  The business is subjective.  It depends on the instrument you play it on.  if you have a better transcription of what I have pasted post it up.  Thanks.
Comment: My question was about the 7ths.  We can split hairs all day about the nitty gritty details of what's happening in between every strong beat, or you can simply show me your version of my episode, and justify why your's is better.
Comment: Bach's chorales are all very busy.  He broke rules all the time but is still held as a master.  I urge you also, that if you are going to rewrite the episode to your definition of rightness, that you view/listen to my entire piece so you are able to give your answer in context.


how to return a number from UIAlertView

Question: I have a function like
I want getResponse to return the index of the button pressed.
-(NSNumber*)getResponse
        {
        ...
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title"
                                                    message:@"Message"
                                                   delegate:self
                                          cancelButtonTitle:@"No"
                                          otherButtonTitles:@"Si",nil];
        [alert show];
        return """Index of button Pressed"""
    }

getResponse looks prefUser data in order to return a number 0 or 1 but there are some combinations that are to be asked to the user in order to know what to return.
User may check allways save data (so it returns 1)
Or may check never save data (...returns 0)
Ask me every time:
It's like:

¿do you want to save the data? (YES/NO)
Comment: Do you know about delegation??? How to implement it?? Go through it http://code.tutsplus.com/tutorials/ios-sdk-working-with-uialertview-and-uialertviewdelegate--mobile-3159
Comment: How does your `alertView:clickedButtonAtIndex:` look like?
Comment: You should know that UIAlertView is deprecated starting with iOS 8. You should use UIAlertController instead.
Answer: You can use delegate method, first set up view controller as UIAlertViewDelegate:
@interface YourClass : UIViewController <UIAlertViewDelegate>

and add that delegate method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    // button index it what you are looking for
}

how to return a number from UIAlertView