MLE of fourth moment of normal distribution

Question: Take $X\sim N(0,\theta)$, and let $\phi = E(X^4)$, the fourth moment. What is its MLE, $\hat{\phi}$, and what is the asymptotic distribution of $\sqrt{n}(\hat{\phi} - \phi) $ as $n\to \infty$? Any help with this question would be appreciated, as I really can't think of where to start!! Many thanks.
I have integrated the expression for $E(X^4)$ by parts three times to get $\phi = 6\theta^3$, which gives $\hat{\phi} = 6\hat{\theta}^3$ as the function is continuous (is this correct?). However, I am not sure what the MLE of $\theta$ should be, and what that makes the asymptotic distribution $\sqrt{n}(\hat{\phi} - \phi) $.
Comment: Welcome to Math.SE! Please, consider updating your question to include what you have tried and where you are getting stuck. That way, people on this site will know exactly what help you need.
Comment: Sure, I have done so. Thanks for your comment, this is my first time on the site.
Comment: Whoever voted to close this should exercise some common sense and rescind that vote.  It's just newbie-biting.
Answer: I assume you mean $\theta=\operatorname E(X^2)$.
The fourth moment is
$$
\operatorname E(X^4) = 3\theta^2.
$$
If you can find the MLE $\hat\theta$ for $\theta$, then the MLE for $3\theta^2$ is just $3\hat\theta^2$.  Something useful to know about MLEs is that if $g$ is a function, and which function $g$ is does not depend on any parameters being estimated, then the MLE of $g(\alpha)$ is $g(\hat\alpha)$ where $\hat\alpha$ is the MLE of $\alpha$.
(The asymptotic distribution is something I'll look at later.  Probably the delta method will work.)
PS: I see you're saying you got $6\theta^3$.  Having a third power there doesn't make sense.  Let $\varphi$ be the standard normal density, so the standard distribution is
$\varphi(x)\,dx$.  Then the $N(0,\theta)$ distribution (assuming you mean by that that the variance, not the standard deviation, is $\theta$, is
$$
\varphi\left(\frac{x}{\sqrt{\theta}}\right)\,\frac{dx}{\sqrt{\theta}}.
$$
So
\begin{align}
\operatorname E(X^4) & = \int_{-\infty}^\infty x^4 \varphi\left(\frac{x}{\sqrt{\theta}}\right)\,\frac{dx}{\sqrt{\theta}} = \theta^2 \int_{-\infty}^\infty \frac{x^4}{\theta^2} \varphi\left(\frac{x}{\sqrt{\theta}}\right)\,\frac{dx}{\sqrt{\theta}} \\[10pt]
& = \theta^2 \int_{-\infty}^\infty u^4 \varphi(u)\,du = \theta^2 \operatorname E (Z^4)
\end{align}
where $Z\sim N(0,1)$.  So it has to be proportional to $\theta^2$.
PPS:  OK, let's look at the integral
\begin{align}
& \phantom{={}}\int_{-\infty}^\infty z^4\varphi(z)\,dz = 2\int_0^\infty z^4\varphi(z)\,dz \\[8pt]
& = \frac{2}{\sqrt{2\pi}}\int_0^\infty z^3 \exp(-z^2/2)\Big(z\,dz\Big) \\[8pt]
& = \frac{2}{\sqrt{2\pi}} \int_0^\infty \sqrt{2w\,{}}^3 \exp(-w)\,dw \\[8pt]
& = \frac{2}{\sqrt{2\pi}}\sqrt{2}^3\Gamma(5/2) = \frac{1}{\sqrt{2\pi}}\sqrt{2}^3\cdot\frac12\cdot\frac32\cdot\Gamma(1/2) \\[8pt]
& = \frac{2}{\sqrt{2\pi}}\cdot\sqrt{2}^3\cdot\frac12\cdot\frac32\cdot\sqrt{\pi} \\[10pt]
& = 3.
\end{align}
Comment: Thank you, I see where I went wrong in the integral, and your reasoning that it has to be proportional to $\theta^2$ makes sense too.


Java adding ImageIcon to JLabel

Question: I am trying to make a very basic game with Java and I am having trouble displaying an image on a JFrame. It has worked in the past for me and now is not, i can't see what I did wrong.
I have tried printing the current working directory and changing where I get my image to match that. It is likely that the problem is not getting the image, since my (filefinder or filereader or something like that) can find it without problems, but I cannot correctly add it (the ImageIcon) to the JLabel, or that to the JFrame.
This is my code...
JFrame frame = new JFrame("no image");
ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
JLabel imagelabel = new JLabel(image);
frame.add(imagelabel);

The JFrame has been setVisible(true) and pack().
Could someone please help me understand what is wrong.
Comment: Please have a look at this example, [How to add images to your Project](http://stackoverflow.com/questions/9864267/load-icon-image-exception/9866659#9866659) or Please follow these [steps](http://gagandeepbali.uk.to/gaganisonline/webpages/makejareclipse.html)
Comment: I looked at those examples, they did not help
Comment: Simply place your image next to your .class file, and use it like this ImageIcon image = new ImageIcon(getClass().getResource("yourImage.extension"));. That link has to work, since it's the right way to put your images in your project. I hope you had walked through all the steps mentioned in that !!
Comment: Simply copy the nicely idented code from your notepad to the question area, then select all the code and press CTL + K, to format it. You don't really have to press space bar eight times for each line.
Comment: that throws a nullpointer exception
Comment: I made it work myself, the solution was to name the images "New Bitmap Image". I think that for some reason it thought i didn't specify a file name, and was looking for the default filename.
Comment: Glad you got it sorted, KEEP UP the GOOD WORK :-)
Comment: how to i close this question now that i have solution?
Answer: Your problem lies here:
   ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
   JLabel imagelabel = new JLabel(character);

You create an ImageIcon "image" but you create your JLabel with "character".
It should be:
JLabel imagelabel = new JLabel(image);

Comment: sorry, in my actual code they are the same, I forgot to replace character with image.
Answer: Try,
ImageIcon image = new ImageIcon("c:\\path\\image.png");
imagelabel = new JLabel(character, image, JLabel.CENTER);
frame.add(imagelabel);

Take a look at Tutorial - How to use Icons
Comment: I have looked at the tutorial many times, I don't see what i did wrong.
Answer: import javax.awt.*;
import java.awt.*;
import java.awt.event*;

//class name image
class image {
    image()
    //constructor {
        Frame f=new Frame("Image");
        //Frame
        f.setSize(500,500);
        f.setVisible(true);
        Panel p =new Panel();
        //Panel
        f.add(p);
        p.addLayout(null);
        ImageIcon ii=new ImageIcon("set your image path");
        //ImageIcon is used to image Display .
        Label l =new Label(ii);
        p.add(ii);
        p.setBounds(set you bounds);
        //Like that(20,20,500,40);
    }

    public static void main(String [] args) {
        image obj = new
    }
}

Comment: Please add some explanations about your code and about that why OP needs your code ;).

Java adding ImageIcon to JLabel


How to log a given instance of a scaled service with docker-compose?

Question: I have a docker-compose.yml file which contains, among others, an application service app.
When I start this service using the up --scale app=N option (with N>1) I can monitor what's happening in the service using docker-compose logs app but this list all the instances of the app service, namely, app_1, app_2, ..., app_N.
Let's say I'd like to only see the logs of the app_4. How could I achieve that?
The help doesn't help me much on that:
ubuntu-host-machine$ docker-compose logs --help
View output from containers.

Usage: logs [options] [--] [SERVICE...]

Options:
    --no-color          Produce monochrome output.
    -f, --follow        Follow log output.
    -t, --timestamps    Show timestamps.
    --tail="all"        Number of lines to show from the end of the logs
                        for each container.

I naturally tried docker-compose logs app_4 but without much success, as it says:
ERROR: No such service: app_4

The same error appears if I want, e.g. to stop the app_4 using docker-compose stop app_4 and will probably for other similar commands. So the question may also apply to these similar situations.
Versioning information:
ubuntu-host-machine$ docker-compose --version
docker-compose version 1.27.4, build 40524192

ubuntu-host-machine$ docker --version
Docker version 20.10.8, build 3967b7d

ubuntu-host-machine$ uname -mor
5.4.0-81-generic x86_64 GNU/Linux

Comment: You could upvote https://github.com/docker/compose/issues/8636 where the request is tracked
Answer: Since there is still no official option for this, I'm writing an obvious solution that might not come in mind: using grep
If you do
docker compose logs app | grep app_2

You will get the logs for a specific instance of the scaled service


Exactly how do you derive Riemann's explicit formula correctly?

Question: I know the functional equation etc and I have seen a complete proof of von Mangoldt's version of the formula via a free paper online but I would like to read a direct proof.
You know, the formula that says
$$J(x)=li(x)-\sum\limits_{\rho} li(x^{\rho})-\log(2)+\int\limits_x^{\infty}\frac{1}{t(t^2-1)\log t}dt$$
Please give links that are free or at least free to read online or something like that.
Comment: This is not a research-level question, you'd better ask it on Math.SE.
Comment: it might also help if you explain a bit more what precisely you are looking for, for example with reference to [these notes](http://www-users.math.umn.edu/~garrett/m/mfms/notes_c/mfms_notes_02.pdf)
Comment: Sorry for the WolframAlpha-like math syntax, I'm not used to the syntax used here.
Answer: Let $\Lambda(n) = \log p$ if $n=p^k$ is a prime power, $\Lambda(n)=0$ otherwise. Then $$\frac{-\zeta'(s)}{\zeta(s)} = \sum_{n=1}^\infty \Lambda(n) n^{-s} = s \int_1^\infty (\sum_{n \le x} \Lambda(n)) x^{-s-1}dx, \qquad \Re(s) > 1$$
Thus, by inverse Mellin/Laplace/Fourier transform
$$\sum_{n \le x} \Lambda(n) = \frac{1}{2i \pi} \int_{\sigma-i\infty}^{\sigma+i\infty} \frac{-\zeta'(s)}{\zeta(s)} \frac{x^s}{s}ds, \qquad \Re(s) > 1$$
Then the Riemann explicit formula follows by applying the residue theorem
$$\frac{1}{2i \pi} \int_{\sigma-iT}^{\sigma+iT}+\int_{\sigma+iT}^{-\infty+iT}+\int_{-\infty+iT}^{-\infty-iT}+\int_{-\infty-iT}^{\sigma-iT} \frac{-\zeta'(s)}{\zeta(s)} \frac{x^s}{s}ds $$
$$=\sum_\beta Res(\frac{-\zeta'(s)x^s}{\zeta(s)s},\beta) = x-\log2\pi -\sum_{k=1}^\infty \frac{x^{-2k}}{-2k}-\sum_{|\Im(\rho)|< T} \frac{x^\rho}{\rho}$$
And carefully letting $T \to \infty$,  using the density of zeros to show that $\int_{\sigma+iT}^{-\infty+iT}+\int_{-\infty+iT}^{-\infty-iT}+\int_{-\infty-iT}^{\sigma-iT} \frac{-\zeta'(s)}{\zeta(s)} \frac{x^s}{s}ds  \to 0$ and hence
$$\sum_{n \le x} \Lambda(n) = x-\log2\pi -\sum_{k=1}^\infty \frac{x^{-2k}}{-2k}-\sum_{\rho} \frac{x^\rho}{\rho}$$
Finally the explicit formula for $J(x)= \sum_{n \le x} \frac{\Lambda(n)}{\log n}$ follows by differentiating, multiplying by $\frac{1_{x \ge 2}}{\log x}$ and integrating, transferring the formula for $\frac{\zeta'(s)}{\zeta(s)}$ to $\log \zeta(s)$.
Comment: How do you "use the density of zeros" to show that whatever you're calculating is zero? I think -zeta'(s)/zeta(s) oscillates without bound as s-> -inf...
Comment: @JustSomeNerdyTeen Use the functional equation to show the only problematic term is $\int_{\sigma+iT}^{-1+iT}\frac{\zeta'(s)}{\zeta(s)}\frac{x^s}{s}ds$. With the density of zeros (which follows from the functional equation) show there is a sequence $t_n\to \infty $ such that $\frac{\zeta'(a+it_n)}{\zeta(a+it_n)} = o(t_n)$


How to deal with non-comparable elements in the partial order set in the formal proof

Question: If $X$ is any partially ordered set and $f,g\in i\mathbb{R}^X$, then
$\alpha f+\beta g\in i\mathbb{R}^X$ whenever $\alpha,\beta\geqslant 0$

$i\mathbb{R}^X$ is the set of increasing functions, and increasing function $f\in\mathbb{R}^X$ is defined as $x,x'\in X$, $x\preceq x'\implies f(x)\leq f(x')$

This is a somewhat trivial question; below is my attempt.
However, there is a flaw in my argument about how I should reason the non-comparable elements in the poset, not every pair of elements needs to be comparable in the poset. My proof already presumes every element is comparable so as can be indexed by $n,n-1$
Given $f,g\in i\mathbb{R}^X$, then $f_{n-1}\leqslant f_n$ and $g_{n-1}\leqslant g_n$ for all $n\in X$, then any $\alpha,\beta\geqslant 0$ maintains $\alpha f_{n-1}\leqslant\alpha f_n$ and $\beta g_{n-1}\leqslant\beta g_n$. Then $$\alpha f_{n-1}+\beta g_{n-1}\leqslant\alpha f_n+\beta g_n$$ for all $n\in X$. Hence, $\alpha f+\beta g\in i\mathbb{R}^X$
Thank you for any help.
Comment: could you please define the notation you use, what is $i\mathbb{R}^X$? presumably some poset with an underlying set of functions, but a precise definition is needed
Comment: @Carlyle my bad, the question edited.
Answer: You would argue directly from definition of $i\mathbb{R}^X$ and work with arbitrary elements $x, x' \in X$ with $x \preceq x'$, instead of trying to place a total order on $X$. Here's a very slight modification of your proof which works:
Let $f,g \colon X \to \mathbb{R}$ be increasing functions with respect to the partial order on $X$ and the usual order on $\mathbb{R}$, and let $\alpha,\beta \geq 0$. Suppose $x,x'\in X$ are such that $x \preceq x'$. Then $f(x) \leq f(x')$ and $g(x) \leq g(x')$ since $f$ and $g$ are increasing. Also, since $\alpha,\beta \geq 0$, we have $\alpha f(x) \leq \alpha f(x')$ and $\beta g(x) \leq \beta g(x')$. Adding the inequalities to each other, we obtain
$$\alpha f(x) + \beta g(x) \leq \alpha f(x') + \beta g(x').$$
So $\alpha f + \beta g$ is also an increasing function.


Remover comentários JavaScript da tag script de um HTML, ignorando conteúdo de outras tags (ex: imagens em base 64)

Question: Preciso ignorar as tags img pois algumas imagens vem em base64 e contêm // que são reconhecidas como comentários e são removidas, quebrando todo o código HTML.
function limpa_html($html){
    $pattern = '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/';
    $html = preg_replace($pattern, '', $html); //apaga comentarios em js
    return $html;
}

Esta é a função me atende super bem, porém imagens como
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgAAQABAAD/2wBDAAQgHBwcJCQg// quebram o HTML. A ideia seria ignorar as tags img ou limitar o código apenas nas tags script, porém não entendo de regex a esse ponto.
Aqui uma simulação do que acontece:

No exemplo acima, o trecho final da tag img (//ejhdbjkebdklebdklenbdknedklnekdlelde) também é removido.
Comment: Dá uma olhada aqui https://www.php.net/manual/pt_BR/class.domxpath.php#87645
Answer: Em vez de usar a regex em todo o HTML, você pode usar DOMDocument para pegar somente as tags script, e aplicar a regex somente nelas.
Assim você garante que fará a substituição somente no código JavaScript, sem precisar se preocupar com as demais tags. Exemplo:
$text = <<<TEXTO

TEXTO;

// mudar o nome da função e do parâmetro para deixar bem claro o que ela faz
function limpa_comentarios($jsCode) {
    $pattern = '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/';
    return preg_replace($pattern, '', $jsCode); // apaga comentários em js
}

// carrega o HTML
$dom = new DOMDocument;
$dom->loadHtml($text); // $text é uma string contendo o HTML
$xpath = new DOMXPath($dom);
// procura as tags script e aplica a regex somente nelas
foreach ($xpath->query("//script") as $script) {
    $newContent = limpa_comentarios($script->nodeValue);
    // substitui o conteúdo do script
    $script->nodeValue = '';
    $script->appendChild($dom->createTextNode($newContent));
}
echo $dom->saveHTML();

Mas se a ideia é minificar o HTML/JS, talvez seja melhor procurar por libs dedicadas, em vez de tentar fazer tudo manualmente.
Comment: Entendi o seu posicionamento porem uso um template que monta todo o HTML monta variáveis em diversas partes do HTML, por isso seria interessante incluir isso la no template, senão teria que pegar a saida do template e usar essa sua solução ai.. Na verdade a função limpa todo o HTML, deixei so a parte que esta de fato prejudicando o arquivo final..
Comment: @ThiagoCondé Então a solução ideal seria modificar o template para que ele já gerasse o código sem comentários. Se não é possível modificar o template, não tem jeito, tem que processar o HTML depois (ou então modifique a função `limpa_html` para usar `DOMDocument` e só remover o comentário das tags `script`, pelo que entendi dá na mesma) - tentar fazer uma regex que processa todo o HTML é bem mais complicado do que parece (sem contar que a regex atual já está complicada o bastante)
Comment: Valeu pela ajuda!! acho que resolvi sem querer porem terei que revisar todos comentarios a solução é adicionar um espaço entre as duas barras e os comentarios //espaçoComentario é uma solução. Mas valeu pela sua ajuda eu nem conhecia esse DOMDocument do php. Ele pode ser muito util daqui pra frente!! de qualquer forma muito obrigado!!
Comment: [RESOLVIDO] $pattern = '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\s\/\/.*))/';


COLMAP camera pose reconstruction for NeRF

Question: I am currently playing around with mesh reconstruction from NeRF models and I noticed that most NeRF implementations provide a python script for the extraction of camera poses from images via COLMAP.
It is my understanding that those scripts use sparse reconstruction or at least the feature extraction methods from COLMAP to determine camera poses and information.
The COLMAP Tutorial for feature extraction states that intrinsic parameters can be manually specified and now I can't help but wonder if there is a more efficient way to extract camera poses from images (because the quality of the NeRF often depends heavily on accurate camera poses).
Has anyone here ever tried to mess with the intrinsic parameters? Are there any more parameters to tweak to achieve better results in camera pose detection? Has anyone tried to create their own script for NeRF purposes?
I am thankful for all tips and tricks or nudges in the right direction. If you think the idea to try and mess with parameters is stupid in the first place please also feel free to let me know!
Also: If someone knows what parameters are really needed or most important for NeRF models (parmeters that can be reconstructed from a set of images) please let me know!
I have so far tried to understand the provided python scripts and read the COLMAP tutorial section. I have not tried to extract camera poses myself using COLMAP because at this point I am not entirely what parameters are really needed for good results in NeRF modelling.
Please excuse the tags I couldn't find any that better suited the question in the suggestions.
Answer: If you're working with NeRF and encountering issues where Colmap is preventing you from obtaining camera positions, I also faced a similar problem for several months as running NeRF you need the camera positions that is ditected by Colmap. I'm using TEM images to train with the NeRF model, but Colmap couldn't detect the camera positions.
I found a helpful workaround that saved me from this predicament. You can check out NerfMM. This tool works without the need for camera parameters. Give it a try; it might assist you in resolving your problem.
Answer: You can use other KIRI Engine app for example to get position when you take a photo. It gave me much better training results.
Comment: Isn't Kiri an App for photogrammetry? How can I use camera positions from Kiri for my NeRF model?
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: You can find developer mode in KIRI. If you turn it on,  you will see position options.
https://docs.nerf.studio/en/latest/quickstart/custom_dataset.html#kiri-engine-capture
you can have a look on that site. search kiri


What's the difference between Fréchet-differentiation and complex differentiation "intuitively"?

Question: Let $G$ be open in $\mathbb{C}$ and $f:G\rightarrow \mathbb{C}$ be a funtion.
Define $H\triangleq \{(x,y)\in\mathbb{R}^2: x+iy\in G\}$.
Define $u(x,y)=Re(f(x+iy))$ and $v(x,y)=Im(f(x+iy))$ for all $(x,y)\in H$.
Assume that $u,v$ are Fréchet differentiable at a point $(X,Y)$ and they do not satisfy Cauchy-Riemann equation

Is there a case $f$ is not complex-differentiable in this case? And why this is possible intuitively?

Set $T=Du(X,Y)+ i Dv(X,Y)$. Then,we have $T(a,b)=au_x(X,Y) + bu_y(X,Y) + i( av_x(X,Y) + bv_y(X,Y))$.
Thus, $|f(X+iY + (h+ik)) - f(X+iY) - hu_x(X,Y) - ku_y(X,Y) - i hv_x(X,Y) -ikv_y(X,Y))|= o(h+ik) \cdots (1)$
Also,note that $|f(X+iY + (h+ik)) - f(X+iY) - (h+ik)f'(X+iY)|=o(h+ik) \cdots (2)$ if $f$ is differentiable.
So both expressions are approximations of $f(z)$ near $X+iY$. But $(1)$ is $\mathbb{R}^2$ approximation and $(2)$ is $\mathbb{C}$ approximation.
But if $u,v$ do not satisfy Cauchy-Riemann equation, what kind of approxnation is $(1)$? I tried to draw a diagram to compare, but I cannot figure out how they are different.
(Note: "If $f$ is differentiable, then $u,v$ satisfy Cauchy-Riemann equation. Hence $u,v$ must satisfy Cauchy-Riemann equation to have $f$ differentiable." I know this! But I'm not asking this analytically. )
Thank you in advance.
Answer: Think of the function $\mathbb C\ni z\mapsto \bar z\in\mathbb C$.
Comment: Hint: this is a $\mathbb R$-linear operator on $\mathbb R^2$, but not a $\mathbb C$-linear operator on $\mathbb C$ (which is $\mathbb R$-linearly isomorphic to, but more structured than, $\mathbb R^2$.)
Answer: More generally, $\mathbb C$-differentiable is a more stringent requirement than $\mathbb R^2$-differentiable.  Note that they are both Fréchet, except the latter uses all linear operators on $\mathbb R^2$ as candidates for the derivative (in the Taylor expansion that you've written above) wheras the first one uses only linear operators on $\mathbb R^2$ that represent complex numbers, i.e., linear conformal transformations, i.e., angle preserving, i.e., matrices of the form $$\begin{bmatrix}\phantom-a&b\\-b&a\end{bmatrix}\text{ with }a,b\in\mathbb R.$$


Busca em php com UNION - erro mysql_num_rows

Question: estou fazendo um simples sistema de busca que traga somente as quantidades de resultados das tabelas especificadas O problema é que está ocasionando um erro devido as tabelas serem diferentes e suas linhas. Vejam meu script.
$q = $_GET['busca'];

$query= '
        SELECT * FROM noticia WHERE noticia_title LIKE "%'.$q.'% or noticia_content LIKE "%'.$q.'%"
    UNION
        SELECT * FROM eventos WHERE evento_nome LIKE "%'.$q.'% or evento_content LIKE "%'.$q.'%"
        UNION
    SELECT * FROM albuns WHERE album_name LIKE "%'.$q.'%" or album_descricao LIKE "%'.$q.'%"
    ';

    $result = mysql_query($query);
    $count = mysql_num_rows($result);

    if ($count == 0) {
        echo "Nenhum resultado!";
} else {
    if ($count == 1) {
        echo "1 resultado encontrado!";
}
        if ($count > 1) {
        echo "$count resultados encontrados!";
    }
        while ($dados = mysql_fetch_array($query)) {
        echo "";
    }
    }

O erro que está sendo ocasionado é:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in
Alguém pode me ajudar?
Comment: Você está esquecendo de fechar aspas em dois pontos... 1) SELECT * FROM noticia WHERE noticia_title LIKE "%'.$q.'%"   2) SELECT * FROM eventos WHERE evento_nome LIKE "%'.$q.'%"
Comment: @FernandoSouza Fiz a correção, não havia nem percebido. Mais o error persiste. Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource
Comment: tenta fazer assim: mysql_query($query) or die(mysql_error()); e vê o que aparece
Comment: Deu o seguinte erro: The used SELECT statements have a different number of columns
Comment: As tabelas [noticia , eventos e albuns] tem a quantidade de colunas diferentes.. se você puder editar sua pergunta e colocar a estrutura dessas tabelas, ajudará bastante.
Comment: Olá, coloquei, veja !
Comment: Então... o erro que você está tendo é por que você não consegue fazer um select * from nessas tabelas usando union por que a quantidade de colunas é diferente..
Comment: O que posso fazer para resolver essa seleção e resultados. Tem como ajudar?
Answer: Conforme conversado nos comentários:
1) Faltavam aspas duplas nos dois primeiros selects
SELECT * FROM noticia WHERE noticia_title LIKE "%'.$q.'%"
SELECT * FROM eventos WHERE evento_nome LIKE "%'.$q.'%"

2) Após adicionar mysql_query($query) or die(mysql_error()); foi identificado o seguinte erro:

The used SELECT statements have a different number of columns

3) Para resolver este problema você deve fazer um SELECT com a mesma quantidade de colunas. Exemplo:
$query= '
        SELECT noticia_id FROM noticia WHERE noticia_title LIKE "%'.$q.'%" or noticia_content LIKE "%'.$q.'%"
    UNION
        SELECT evento_id FROM eventos WHERE evento_nome LIKE "%'.$q.'%" or evento_content LIKE "%'.$q.'%"
    UNION
        SELECT album_id FROM albuns WHERE album_name LIKE "%'.$q.'%" or album_descricao LIKE "%'.$q.'%"
    ';

Comment: Olá companheiro! Deu certo agora! Show de bola! Poderia me explicar porque foi necessário colocar a primeira coluna da tabela em cada SELECT?
Comment: Quando você utiliza o operador UNION em um SELECT você tem que se atentar a alguns detalhes como: 1) A quantidade de colunas devem ser iguais.. 2) O Tipo dos dados devem ser similares... 3) As colunas devem estar na mesma ordem...    Veja este [Link](https://www.w3schools.com/sql/sql_union.asp) onde fala um pouco mais sobre isto.  Ah! e se possível aceite a minha resposta como a correta.
Comment: Ah entendi! Muito obrigado pelo apoio!


What is the correct way of using angular 2 partially in an application?

Question: Every single example I have come across with angular 2, expects the Angular 2 to be used on every single page and expects the AppComponent to exist on the page. If an AppComponent is missing, there is a following error:
Error in :0:0 caused by: The selector "my-app" did not match any elements

What is the correct and preferred way of using angular 2 partially within an application, whereas rest of the app is rendered on the server side?
In Angular 1, you could just not include ng-app directive, if a specific page did not require angular. What is the angular 2's equivalent of not having ng-app directive?
Answer: You can actually learn how angular2 bootstraps itself. Look at the transpiled code in the main file to see how it's done and add your own logic to the page to determine whether or not to run it.
Comment: Angular2 is designed to load on any page it's included in. I'm just giving a suggestion that goes against the way its designed; the better way is to just not load it in the pages it's not used.
Comment: I thought the point of using Angular was to avoid having to do this. Angular1's elegance is that you don't have to conditionally bootstrap if such directive didn't exist.
Comment: I see, thanks for your suggestion. I wasn't meaning to be rude or anything, I'm just trying to wrap my head around this.
Comment: Oh no worries... I learned a lot from questioning stuff just as you had :)
Answer: If the app that is rendered on the server side can include scripts and tags required for bootstrapping Angular2 application. Other parts of the application would render HTML as usual without Angular 2 tags and directives. The only difference is that the same links require href attribute instead of routerLink.
Answer: Expanding on @Paul Jerome Bordallo's answer, we can change the bootstrap script to look like this:
const elemExists = document.getElementById("load-angular");

if(elemExists) {
    platformBrowserDynamic().bootstrapModule(AppModule);
}

So on your html, we could have something like:
<my-app id="load-angular"></my-app>

to get the functionally we want.
Comment: The part that used to control  if `elemExists` could be done on server side.


Criar um algoritmo, em JS, para listar todos os números primos menores ou igual a N

Question: Preciso criar um algoritmo em Javascript, para listar todos os números primos menores ou igual a um determinado número.
function primeNumber (num){
    var num = 0;
    for (var i = 0; i <= num; i++){
        if ((num % 1 === 0) && (num % num === 0)){
            return (primeNumber(i));
        }
    }
}
console.log(primeNumber(num));

Onde estou errando?
Comment: O resto da divisão de um número por 1, ou o resto dadivisão por ele mesmo, sempre será zero. Reveja a definição de número primo e seu algoritmo.
Answer: A definição mais comum é que "um número é primo se for divisível por 1 e por ele mesmo" ou então "é todo o número com dois e somente dois divisores, ele próprio e a unidade". Sendo assim, por exemplo, o número 7 é primo por ser divisível apenas por 1 e por 7.

Por definição o número 2 é um número primo portanto devemos testar a partir do divisor 2.
Se na função primeNumber houver algum divisor que o resto da divisão seja igual a 0 ele não é primo e podemos parar com a verificação.

function primeNumber(num) {
    for (var divisor = 2; divisor < num; divisor++)
    if (num % divisor == 0) return false;
    return true;
}

var determinadoNumero = 50;

for (var i = 2; i < determinadoNumero; i++) if (primeNumber(i)) console.log(i);

o número 2 é o único número primo que é par.
Answer: Conceito:
Para identificar um número primo devemos dividi-lo sucessivamente por números primos como: 2, 3, 5. . . e verificar se a divisão é exata (em que o resto é zero) ou não exata (onde o resto é diferente de zero).

Se o resto da divisão for zero o número não é primo.
Se nenhum resto for zero, o número é primo.

Exemplo simples em código onde a função primeNumbers vai interar de 0 até a quantidade de números e os isPrime vai verificar se o mesmo realmente é número primo:

function primeNumbers(num) {
  let numbers = new Array();
  for (var i = 0; i <= num; i++) {
    if (isPrime(i)){
      numbers.push(i);
    }
  }
  return numbers;
}
function isPrime(num) {
  for(let i = 2; i <num; i++)
    if(num % i === 0) {
        return false
    };
  return num > 1;
}
console.log(primeNumbers(13));

onde a operação trará todos os números entre o número informado.
Comment: Este seu programa lista os número ímpares e não primos.
Comment: realmente eu vou arrumar @anonimo
Comment: @anonimo obrigado foi arrumado agora!
Answer: Criar função para mostrar numeros primos

exibirNumerosPrimos(25);

function exibirNumerosPrimos(limite){
    for(let numero = 2; numero <= limite; numero++){
        if(NumerosPrimo(numero)) console.log(numero);
    }
}

function NumerosPrimo(numero){
    for(let divisor =2; divisor < numero; divisor++){
        if(numero % divisor === 0){
            return false;
        }
    }
    return true;
}


Página é carregada antes dos dados do firebase retornarem.

Question: Galera estou com um controller, onde eu busco dados do firebase, porém ao fazer essa busca o código sofre um delay e a página é carregada antes com dados vazios antes da consulta de fato acabar.
Meu controller :
function DashboardController($http, $scope){

    var vm = this;
    vm.searchJedi = searchJedi;
    vm.obj = [];
    vm.jedi = {
        master: '',
        name: '',
        planet: '',
        status
    }
    vm.teste = [];

   vm.searchJedi();

    function searchJedi(){
        db.collection("jedi").get().then((querySnapshot) => {
            querySnapshot.forEach((doc) => {
                vm.jedi = doc.data();
                vm.obj.push(vm.jedi);
            });
            console.log(vm.obj); //objeto com valor
        });

        console.log(vm.obj); //objeto vazio
    }
}

O que acontece  é que esse último console sempre está vazio enquanto o console que está dentro do db.collection vem preenchido após a busca sofrendo um delay. Dessa forma na página HTML os dados não são mostrados.
Alguma dica?
Answer: O db.collection("jedi").get() retorna para você uma Promise que é um dado assíncrono e que realmente não irá aparecer de imediato. Através do .then você consegue o valor e enquanto ele está sendo executado o resto do código externo a ele também está seguindo, como o seu console.log que está vazio e a renderização do seu HTML. Minha sugestão é que você crie uma animação de loading pro HTML que comece antes de buscar o dado com o db.collection e termine após a sua inclusão no vm.obj.push(vm.jedi). Exemplo:
var loading;
function searchJedi(){
    loading = true;
    db.collection("jedi").get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            vm.jedi = doc.data();
            vm.obj.push(vm.jedi);
        });
        loading = false;
    });
}

Sendo esse loading tratado no HTML para aparecer assim por exemplo:
Carregando...


GLM: Sigmoid link with MSE for linear regression?

Question: I have a relatively simple regression problem where I wanted to model y given x. X is continuous and is bounded [0,inf); y is bounded (0,1).
My question is, is it appropriate for me to insert a sigmoid link function into my linear regression model?
Predicted values of y should never exceed 1 or go short of 0. The sigmoid function should enforce this.
However, the loss function with be mean squared error.
I think that this is an acceptable GLM, however, I'd like community consensus
Answer: It's no longer a linear model, but it's fine to use a nonlinear link function with mean squared error loss. Mean squared error loss corresponds to maximum likelihood estimation of a Gaussian likelihood, and the link function does not change that. I have not heard of the nonlinear link function being sigmoid, but I have heard of using a $\log$ link with a Gaussian likelihood (so mean squared error as the loss).
I have my doubts that you really want a Gaussian conditional distribution if you want your $\hat y$ bounded between $0$ and $1$, but that is a separate matter.
Comment: I see. To make things more complicated, I'll be using a Bayesian paradigm, so the likelihood is a bit ambiguous here. Perhaps Gaussian is the way to go, as would be for linear regression.


Moonlight Sonata vs K.331 Andante Grazioso

Question: I learned the first part of K.331 "Andante Grazioso", and I was moving to the first variation. However, I am finding very huge difficulties in learning it, especially when I compare it with Moonlight Sonata (first movement).
Why am I finding Beethoven's sonata easier than Mozart's?
I really thought it would be the other way, so is there any technical reason? I am not referring to the expressiveness of the piece, just the technical part.
Answer: Why did you think the Mozart should be technically easier than the Beethoven?
The Beethoven has simpler rhythm, slower tempo, and the left hand plays almost nothing.
The Mozart is faster, the way the different rhythms in each hand interlock with each other is more complicated, and the right hand is using a very different finger technique than the simple chord patterns in the Beethoven.
(But be warned, the Mozart doesn't get really difficult till variations 4 and 6...)
Comment: Well, maybe just heard this and thought it was also technically more difficult. Would you compare Moonlight Sonata's difficultly with K.331 Theme being "on par"? I'm trying to see if Moonlight is something I can try technically.
Answer:
Why am I finding Beethoven's sonata easier than Mozart's?

Well, this isn't a very fair statement, given that you're actually referring to just the first movement of a sonata, and one which lays almost all the difficulty in the musical interpretation. If your question is about why it's easier to you from the technical point of view, I don't think you should think that you 'can play a Beethoven sonata while having huge difficulties with a Mozart one'.
Comment: The OP is indeed referring to the higher technical difficulty of that part of the Mozart sonata, not the expressive difficulty. While you say that almost all of that Mozart sonata movement's difficulty is expressive, please touch more on the technical difficulty it does have.
Comment: 'While you say that almost all of that Mozart sonata movement's difficulty is expressive...'. That's the point: I'm not, I was writing about Beethoven's; hence the lack of point for comparison.
Comment: Darn, I though you were referring to the Mozart sonata movement as the expressively difficult one because both movements in question are first movements. Please be less ambiguous when referring to the sonata movements.
Answer: There are different kinds of difficulty. The Moonlight sonata first movement is technically quite easy to play. But to play it well, with the touch absolutely calibrated right for every note, is actually quite demanding. The third movement is technically much, much harder. This is the basis for a joke in the E F Benson books: the wannabe pianist heroine can play the first movement but the third is totally beyond her, so she gets out of playing it in an evening recital by saying it's more suited to the afternoon.
Andante Grazioso is somewhere between the two. There are some nasty little finger twisters in there for sure! Listen to Periaha play the trills in var 2, or the consecutive octaves that need to be smooth as glass, or the final movements light semiquavers and you'll see what I mean.


Consumir web api com varios models

Question: Nessa minha pergunta Duvida verb GET WebApi eu enfrente algum erro por conta dos relacionamentos. Mas agora pegando ela como base por conta dos meus models, como eu poderia consumir esse serviço? Porque o model Tabela1 tem relacionamentos e eu precisava traze-los para o MVC que eu estou usando para consumir... Mas o que acontece é que os relacionamentos, os models, não vem preenchidos, vem nulos...
Meu controller no asp.net mvc:
    public ActionResult Index()
    {
        //Varialvel resposável por receber os dados que estão no banco de dados para mostrar na tela
        HttpResponseMessage resposta = cliente.GetAsync("http://meuservico/api/servico").Result;

        //Se der tudo certo, é porque trouxe os dados retornando código 200
        if (resposta.IsSuccessStatusCode)
        {
            //Formata o json para mostrar na tela
            var result = resposta.Content.ReadAsAsync<IEnumerable<Tabela1>>().Result;

            //retorna para a tela os json formatado
            return View(result);
        }

        //Caso tenha dado errado, retorna somente a tela sem dado algum
        return View();
    }

A variavel result traz o model Tabela1 preechido, mas os seus relacionamentos não... O que poderia estar acontecendo?
Answer: De acordo com o código da resposta do link:
public IQueryable GetVerb()
{
    var dados = from d in db.Tabela1
                join a in db.Tabela2 on d.Tabela1_Tabela2Id equals a.Tabela2Id
                select new
                {
                    nome = d.Nome,
                    cnpj = d.CNPJ,
                    endereco = a.Endereco,
                    cidade = a.Cidade,
                    cep = a.CEP,
                };

    return (dados);
}

O método GetVerb() retorna uma lista de um genérico que foi criado no select. Então, se vc está restringindo de retornar todos os registros de Tabela1 junto com seus relacionamentos Tabela2, não tem como os consumidores de sua API receberem esses dados.
public IQueryable GetVerb()
{
    var dados = from d in db.Tabela1
                join a in db.Tabela2 on d.Tabela1_Tabela2Id equals a.Tabela2Id
                select new
                {
                    nome = d.Nome,
                    cnpj = d.CNPJ,
                    endereco = a.Endereco,
                    cidade = a.Cidade,
                    cep = a.CEP,
                    tabela2 = a // <====
                };

    return (dados);
}

Por último, torne todo seu fluxo assíncrono:
public async Task<ActionResult> Index()
{
    var response = await cliente.GetAsync("http://meuservico/api/servico");
    if (!response.IsSuccessStatusCode) return View();

    var list = await response.Content.ReadAsAsync<IEnumerable<Table1>>();
    return View(list);
}

Comment: E no caso de usar um Include? Digo Tabela1.Include(x => x.Tabela2); Funciona dá mesma forma?
Comment: Mas daí vc estará usando `Lambda Expressions` com `Fluent API` e não apenas `Linq to SQL`. O que eu acho muito melhor, e bem mais simples. Bastaria fazer algo como `db.Tabela1.Include(t => t.Tabela2)`. Mas não esqueça de [definir os relacionamentos](https://msdn.microsoft.com/pt-br/library/jj591620(v=vs.113).aspx)  antes.
Comment: Então, no web api fiz assim e funcionou... Mas é no ASP.net MVC... Como posso consumir dessa forma? Já tem todos os relacionamentos...
Comment: Linq, Lambda expressions, fluent api, nenhum tem dependência com System.Web. Vc pode usalos até com console app.
Comment: Poderia incrementar a resposta dessa forma que me mostrou então?

Consumir web api com varios models


Algebraic function field of one variable as a scheme

Question: Let $F|K$ be an algebraic function field of one variable. How can it be considered as a scheme? And how can one define geometric and arithmetic genus for it?!
Answer: There exists $t\in F$ transcendental over $K$ such that $F/K(t)$ is finite. Let $A$ (resp. $B$) be the integral closure of $K[t]$ (resp. $K[1/t]$) in $F$. Note that $B_{1/t}$ and $A_t$ are equal, so we can glue the spectra of $A$ and $B$ along $D(t) = D(1/t)$, where the LHS is an open subset of the spectrum of $A$ and the latter is an open subset of the spectrum of $B$.
The scheme $X$ which is obtained is naturally an integral $K$-scheme with function field $F$ and even has a natural morphism to $\mathbb{P}^1$ corresponding to the rational function $t$. Usual scheme theory applies to define a genus.
When $F/K(t)$ is separable, $A$ and $B$ are Dedekind rings and finitely generated modules over $K[t]$ and $K[1/t]$, which entails that $X$ is a noetherian Dedekind scheme hence is regular. So you may easily enough define a notion of arithmetic and geometric genus.
Comment: $F/K(t)$ needs being separable? I read that the inseparable mess appears in dimension $2$
Comment: @reuns: I'm not sure to be honest. Basically I use separability to explain that the normalization is finitely generated over $K[t]$ (I use a nondegenerate trace map), and in particular is a Noetherian ring. It's possible that I don't actually need it, but I'll err on the side of caution.


Differential of $x \sin x$

Question: Finding the differential of $x \sin(x)$
\begin{align}
d(x \sin x) &= (dx) sinx + x (d(\sin x)) &&\text{using the product rule}\\
&= \sin x\,dx + x \cos x\,dx
\end{align}
My question is why is the differential of $\sin x$ equal to $(\cos x) (dx)$ and not just $\cos x$ (which is the derivative of $\sin x$.)
A similar question is, why is the differential of $x^2$ equal to $2x(dx)$? Why is there an additional $dx$ in both cases?
Comment: For purposes of a calculus class, you should just take this as a definition: $dy = \frac{dy}{dx} dx$. The notation is motivated by the fact that if $\Delta x$ is small, $\Delta y = \frac{\Delta y}{\Delta x} \Delta x \approx \frac{dy}{dx} \Delta x$.
Comment: If you believe in using differentials as algebraic symbols, then yeah, you can go from $\frac{dy}{dx} = \frac{dy}{dx}$ to $dy = \frac{dy}{dx} dx$ by multiplying both sides by $dx$. I think it is probably better for calculus students to not get confused by this, and just take $dy = \frac{dy}{dx} dx$ as a formal, symbolic definition.
Comment: just divide by $dx$
Comment: Do you mean that because d/dx (sin x) = cos x, d(sin x) = cos x(dx)?
Answer: in short: $f'(x) = \frac{d f(x)}{dx}$. In your case $f(x) = x \sin x$.
Answer: You have a function $f(x)$ and are looking for the differential $df(x)$. In the case $f(x)=x\sin(x)$:
$$\begin{align}
f'(x) &= \frac{df(x)}{dx}\\
df(x) &= f'(x)dx\\
df(x) &= \left( \frac{df(x)}{dx} \right) dx \\
d\left( x \sin (x) \right) &=\left( x \cos(x) + \sin(x) \right)dx
\end{align}
$$
Similarly, for $f(x)=x^2$:
$$\begin{align}
f'(x) &= \frac{df(x)}{dx}\\
df(x) &= f'(x)dx\\
df(x) &= \left( \frac{df(x)}{dx} \right) dx \\
d(x^2) &= (2x)dx
\end{align}
$$
Answer: Here we have to do with infinitesimals.
What is the derivative? We all know the formula: $$\frac{\Delta f(x)}{\Delta x}=f'(x).$$ This means that derivative is a value that tells us the ratio between the change of the function and the change of its variable. If you have a knowledge in numerical analysis, roughly speaking this is similar to relative error.
But what if we want to know the value of change for the function f(x)? Then, from the last formula we may write: $$\Delta f(x)=f'(x) \Delta x.$$ So this tells us that the change of $f(x)$ is equal to the product of $f'(x)$ and the change of the variable corresponding to the change of the function. In 'numerical analysis language' this is a kind of absolute error of the function $f(x)$.
In the end, we write $d$ instead of $\Delta$ when we deal with the limit.
Answer: It's precisely because you're asking for the differential, rather than asking for the derivative with respect to $x$. In general,
$$ \mathrm{d}(f(x)) = f'(x) \mathrm{d} x$$
One interpretation of taking "the derivative with respect to $x$" is to first compute the differential, and then substitute $\mathrm{d} x = 1$. I imagine your confusion is because you are so used to that final substitution that you don't even realize it's a thing. But here, we're specifically asking for the differential, so you don't make that substitution.
(this interpretation is more like taking a partial derivative than taking a total derivative, if you know what those phrases mean)
This is something that is useful, because we may not yet have decided that $\mathrm{d} x = 1$ is what we want. Maybe we will want to substitute $x = g(t)$ and eventually substitute $\mathrm{d} t = 1$.
Or maybe you simply want to explicitly record how the function varies.
Notation with differential is especially useful when you have more than one variable (even if you only have one independent variable).
Comment: We do not substitute dx=1 when we deal with the derivative. In that case we have a 'fraction' of infinitesimals df(x) and dx.
Comment: @Emin: It depends on whether you're thinking of a derivative as being like a partial derivative but just with one variable. (I usually don't -- I usually think of it as a ratio of differentials) And the interpretation of substituting $\mathrm{d}x$ with something *is* directly relevant to various applications, such as differential approximation.
Comment: Partial derivative? I don't understand what do you mean with partial derivative! We are dealing with functions with one variable.

Differential of $x \sin x$


How to paginate subsections of an array property in Vue.js?

Question: When displaying list data, one can iterate through the items using v-for. I have some filter controls which increase or decrease the number of visible items (size, type, name - stuff like that).
Regardless of this, I'd like to limit the amount visible on page to, say, 10 items.
In other words, if the filter hides 50 out of 100 result items (which are still stored in Vuex) I still want to be able to paginate through 5 pages (10 at a time only).
There's a few plugins such as this one which seem to help with that.
However, I'd like to try to do it manually to understand how it's done, though I'm a bit stumped.
Comment: What have you tried so far? can you share your code and explain the what errors you are getting ?
Comment: You'd basically want to `slice` whatever you're iterating through. `results.slice(start, start + itemsPerPage)` and increase and decrease `start`.
Comment: By the way, **vuejs-paginator** pages the http.get() calls (so that memory footprint in minimized). Is this a feature you want?
Answer: Since you have Vuex on board, a getter seems easiest.
export const getters = {
  pagedItems: state => {
    return pageNo => {
      const pageSize = state.pageSize || 10
      const items = state.items || []
      return items.slice(pageNo * pageSize, pageSize)
    }
  }
}

Default values (e.g state.items || []) are there to stop the calculation erroring before initial load completes.
Use it on the component in a computed property, which will make it reactive when pageNo changes,
computed: {
  pagedItems() {
    return this.$store.getters['pagedItems'](this.pageNo)
  },
},

It just occurred to me that if you are filtering, you probably want to apply that before the pagination otherwise the display may not be be consistent in size (e.g page 1 filters to 4 items, page 2 to 6 items).
Depends on your exact filter, should be easy to add a getter for filteredItems  and use that as source for pagedItems.
Comment: Thanks for the answer. Barely tangientially related: if I have a set of multiple filters including a fuzzy search, how would one conceptually go about figuring out the ORDER in which they are applied / pick and choose which ones are applied to reduce potential memory and processing loads?
Comment: Interesting, that seems problematic with the getter solution. Let me have a think about it.
Comment: Wouldn't filtering simply alter the contents of the array in Vuex? That's kind of my initial instinct
Comment: My concern is that with an initial results array of 100,000,000 items this could start causing issues. This won't be the case ever, but you know what I mean.
Comment: I'm not sure how much of a problem that would be. See [Array.prototype.slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) which says 'The slice() method returns a shallow copy' and 'For object references (and not the actual object), slice copies object references into the new array'. So each filter makes a subset copy of the object reference list and leaves the original array as-is.
Comment: Great. Just dotting all the i's. Thanks again for your answer.
Answer: well, i would just divide the number of items by the number of data i want to display per page with the rest operator and create number of pages + 1, of course with some validations to empty data and so on.
Imagine you recieve an object that contains lists, this lists represent all the arrays with your data, each array is a row.
Just get the length, divide it with module operator and add one more, in your case, if you have 52 items, and want to have 10 per page:
52 % 10 = 2
52 / 10 = 5
you need 5 pages + 1 for the 2 items.
so i would do something like this:
const NUMBER_ITEMS_PER_PAGE = 10;

const numberItems = list.length;
const pages = numberItems / NUMBER_ITEMS_PER_PAGE

if(numberItems % NUMBER_ITEMS_PER_PAGE > 0) {
  pages++;
}

function buildPages(numberPages) {
  const pageObj = {}
  for(var i = 0; i < pages; i++) {
    pageObj.page[i+1]
    const arr = []
    for(var j = 0; j < (NUMBER_ITEMS_PER_PAGE) * (i + 1); j++) {
      arr.push(lists[i])
    }
   pageObj.page[i+1] = arr;
  }
}

of course this is just one possible solution, but i think this can let you start in some way, the code is just to help. good luck


Como faço para contabilizar valores de um array?

Question: parece ser uma pergunta meio boba, mas como faço para contabilizar os valores do array e mostrar a fração de numeros positivos, negativos e zeros existentes, por exemplo: [1,3,0, -1] e retorna [0.50,0.25,0.25]?
Eu fiz um for e if, mas ainda continuo com essa dúvida.
Obrigado
Comment: Podes explicar melhor o que pretendes e com exemplos? Qual é a relação entre essas arrays?
Comment: kd seu código? poste pra tentarmos melhorá-lo ;)
Comment: @Sergio eu tenho uma função na qual vou receber x array e nele eu preciso contabilizar a quantidade de numero positivos, negativos e 0 que possui, e com isso retornar um outro array com a porcentagem de numeros, por exemplo, numerosX([1, 2, 0, -1]) deveria retornar [0.5, 0.25, 0.25], devido a que há 50% de positivos, 25% de zeros, e 25% de negativos.
Answer: Viva!
Penso que seja isto que você quer:

function percentagens(arrayNumeros) {
  var countPositivos = 0,
      countNegativos = 0,
      countNeutros = 0;

  for (var i = 0; i < arrayNumeros.length; i++) {
    if (arrayNumeros[i] > 0) {
      countPositivos++;
    } else if (numeros[i] < 0) {
      countNegativos++;
    } else {
      countNeutros++;
    }
  }

  return [(countPositivos / arrayNumeros.length),(countNegativos / arrayNumeros.length),(countNeutros / arrayNumeros.length)];
}

var numeros = [1,3,0, -1];
alert(percentagens(numeros));


CI pipeline run only when Merge Request has new push commit and to specific branch

Question: I want to create a pipeline that only run when have merge request to specific branch and also it can run every time working branch has new push commit.
this is my example but it wont work properly:
unit_test:
stage: test
script:
 - echo "unit test running"
only:
 - merge_requests
 - develop
 - push

Answer: When working with merge requests, you need to use workflow and rule to control how the runner should trigger the pipelines. You can read more about them on Gitlab's official documentation: Gitab CI workflow and Gitlab CI rules
Using workflow, you can control the execution of stages generally, and using rules you can control the execution of a specific stage. You can use Predefined Variables or even custom variables to write some rules.
For instance, in the following sample, the runner will trigger the pipeline if there is a push over branches and when a merge request is created. It will also disable branch pipeline when you push to a branch when there is an open merge request.
image: ...

workflow:
  rules:
    - if: '$CI_COMMIT_BRANCH' # All branches
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' # Merge requests
    - if: '$CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS' # Fix detached merge request pipelines
      when: never

And in the following example, you can limit the execution of a stage by the name of the source and destination branches in the merge request.
job:
  script: echo "Hello, Rules!"
  rules:
    - if: '$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/ && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH'
      when: always
    - if: '$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/'
      when: manual
      allow_failure: true

Comment: Thank you for your answer I have now idea how to do what I want.
but sadly our devops team is maintaining an old gitlab version that not support workflow keyword and other.
but this will be useful in future thanks for the help.
Answer: using Gitlab CI workflow and Gitlab CI rules make what i want to do.
image: ...

workflow:
  rules:
    - if: '$CI_COMMIT_BRANCH' # All branches
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' # Merge requests
    - if: '$CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS' # Fix detached merge request pipelines
      when: never


How to view work item xml ids in azure ticket

Question: I have an azure devops work item with some custom fields:

I can set some of these fields using the azure api python package, like so for 'RTCID':
jpo.path = "/fields/Custom.RTCID"

But when I try to set the targeted release, I can't find what the field path is for this variable, I've tried
jpo.path = "/fields/Custom.TargetedRelease"

But that results in an error.
I know my organization id, is there any way I can list all the variable path IDs in a ticket?
I tried going to https://dev.azure.com/{organization}/{project}/_apis/wit/workitemtypes/Epic/fields to see all the fields, but ctrl+f searching for 'targeted' brings up no results
Answer: To save the response time when calling a Azure DevOps REST API, many times it will not load the complete properties to the request body.
If you want to view more properties, you can try to use the parameter $expand to expand the complete properties.
GET https://dev.azure.com/{organization}/{project}/_apis/wit/workitemtypes/{type}/fields?$expand=all&api-version=7.1-preview.3

In addition, you also can use the API "Work Items - Get Work Item" to get a work item that is the work item type you require, and use the parameter $expand to expand all the fields.
GET https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}?$expand=fields&api-version=7.1-preview.3

This also can list all the fields on the work item type.


FreeBSD 9 - default file system?

Question: What will the default file system be in FreeBSD 9?
Answer: It's still UFS. The installer (bsdinstall as of 9.0) cannot install to a ZFS filesystem.
If you want ZFS for your root filesystem you need to do a fully manual install.
Comment: Not to be offensive, but if you don't know how to install on ZFS manually it's probably a good idea not to be using it as the root FS. ZFS is quite different from UFS in many important administrative ways and the switch should not be taken lightly.
Comment: That's frustrating that ZFS doesn't work by using the installer. Thanks for the info.
Comment: Do you know if there is plan (when) to have ZFS work using the bsdinstaller?
Comment: I don't believe there is a firm plan yet. You're better off asking on the current@ or stable@ mailing list. For now if you want ZFS the wiki has [several good guides](http://wiki.freebsd.org/RootOnZFS). I've used this successfully on several servers.
Comment: http://mfsbsd.vx.sk also has a script that automates installation of FreeBSD 9 with ZFS as the root filesystem.
Answer: PC-BSD installer can install FreeBSD on ZFS. As soon as the installation start, you may choose you want to install FreeBSD (instead of PC-BSD) and then the installer lets you partition your disk using ZFS.

FreeBSD 9 - default file system?


Intellisense doesn't work for MVVM light toolkit

Question: I began to use MVVM pattern yesterday.But for working with events i needed to install MVVM light toolkit.I did that,and added library to references.At UserControl i announced that library,but  when i want to use toolkit whatever i write it doesnt show any suggestions and doesnt accept what i want to write and shows this error "A value of type 'EventToCommand' cannot be added to a collection or dictionary of type 'TriggerActionCollection' "
<EventTrigger RoutedEvent="TextChanged">
   <mvvm:EventToCommand Command="{Binding Test}"/>
</EventTrigger>

`
Answer: You have to use it like this ..
Namespace to add :
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

        <mvvm:EventToCommand Command="{Binding Path=UserControlLoadedCommand}" />

Dont forget to add a reference to System.Windows.Interactivity to your project
You need To Use PassEventArgsToCommand="True" in

        <mvvm:EventToCommand Command="{Binding Path=UserControlLoadedCommand}" PassEventArgsToCommand="True" />

And then you can get that at ViewModel ..... you Might Need to use Generic RelayCommand as
RelayCommand<KeyEventArgs> myCommand= new RelayCommand<KeyEventArgs>(Execute,CanExecute)

Comment: @JavidanGuliyev se Edited answer
Comment: now i tested it.but it is doesnt raise event(command) when it must rise.I couldnt understand what the problem
Comment: which dll you use?i use GalaSoft.MvvmLight.Extras.WPF4
Comment: well,i could solve this,but there is another problem now.I bind preview key down event,because of that it must return keyEventArgs but it returns null


Lilypond: Putting left hand notes on treble clef - one more question

Question: Similar to my earlier question -
How to put Left hand notes on the treble clef
But this still has me stumped -
This is what I am trying to achieve:

This is what I am getting:

My right hand is:
    \repeat volta 2 {
      \time 4/4
      r4^"8. Cartwheels" c4 e4 g4|
      \hideStaffSwitch
      \change Staff = "left"
      R1
      \change Staff = "right"
      |
      r4 c,4 e4 g4 |
      s2 c,2 | R1 \bar "|."
    }

My left hand is:
    \repeat volta 2 {
      \stemUp
      \showStaffSwitch
      c'4_5 r4 r2
      \change Staff = "right"
      c''1_2
      \change Staff = "left"
      |
      c,,4_5 r4 r2
      \change Staff = "right"
      \stemDown
      c''2
      \change Staff = "left"
      r1
      c,,1-5
    }

My questions are:

How can we get those nicely curved-dashed staff change lines in lilypond?

How can the staff change be shown to begin immediately after the c4 note on the bass clef in measure one - instead of the r2? If I do the switch starting after the c4 - the c1 full note comes on to the treble clef right in the middle of measure 1!

How should the second measure be written - Where should the rest in the second measure be placed? In the left hand part after switching back having played the c1 OR do a staff switch in the right hand part->go to the bass clef and put in an R1 and switch back to the right hand staff ... I tried the former, but it did not look right and I got some warnings, I tried the latter and now it looks OK as in the picture - but it does not feel OK :-) (why should the right hand do a rest on the bass clef)

Why are we getting an extra measure at the end of the left hand part?
Comment: Something you may want to decide for yourself is whether you want to follow the top notation exactly or offer a more "correct" way of doing things. As I see it, the top option is notated for beginners and treats some rests idiosyncratically; a more correct notation is what you can see in Elements in Space's answer.
Comment: @Richard I would not say it's more correct. This thing does not really specify a staff switch, but rather taking notes from one hand into the other hand. So the high c is not actually part of the lower voice, which would be implied the other way. Rather it is very common in piano music to simply annotate notes that should be taking into the other hand by m.s. or m.d. (or like here L.H., R.H.).
Answer: The extra measure come from you specifying r1 in the left hand after the second cross staff c. You have an extra half note everything starting at this point is shifted.
To get the cross-staff c and the rest you can simply create a new Voice in the left hand containing the rest.
For the curved lines I'd suggest using tweaked Phrasing slurs, something like
#(define right-arrow-and-lh-over-to-slur
   (grob-transformer 'stencil (lambda (grob orig)
     (let* ((cpts (ly:grob-property grob 'control-points))
            (middle-left-coord (cadr cpts))
            (middle-right-coord (caddr cpts))
            (right-coord (cadddr cpts))
            (raw-arrow (grob-interpret-markup grob (markup #:arrow-head Y DOWN #t)))
            (arr-ext (ly:stencil-extent raw-arrow Y))
            (arr-neg-height (- (car arr-ext) (cdr arr-ext)))
            (corrected-arrow (ly:stencil-translate-axis raw-arrow arr-neg-height Y))
            (arrow (ly:stencil-translate corrected-arrow right-coord))
            (lh-raw (grob-interpret-markup grob (markup #:fontsize -2 #:italic "L.H. over")))
            (lh-cent (ly:stencil-aligned-to (ly:stencil-aligned-to lh-raw X CENTER) Y DOWN))
            (middle-coord (cons (/ (+ (car middle-left-coord) (car middle-right-coord)) 2) (/ (+ (cdr middle-left-coord) (cdr middle-right-coord)) 2)))
            (lh (ly:stencil-translate lh-cent middle-coord)))
       (display middle-coord)
     (ly:stencil-add
       orig arrow lh)))))

right = \repeat volta 2 {
      \time 4/4
      r4 c'4-1 e'4 g'4|
      \change Staff = "left"
      R1
      \change Staff = "right"
      |
      r4 c'4 e'4 g'4 |
      s2 c'2-\tweak parent-alignment-X #CENTER ^\markup\smaller\smaller\italic\center-align "R.H." | R1 \bar "|."
    }

left = \repeat volta 2 {
  \clef bass
      \phrasingSlurDashed
      \override PhrasingSlur.thickness = #0.6
      \override PhrasingSlur.stencil = #right-arrow-and-lh-over-to-slur
      \shape #'((-0.4 . 3) (-1 . 9) (0 . 4) (0.3 . 1.7)) PhrasingSlur
      c4_5^\( r4 r2
      \change Staff = "right"
      c''1-\tweak Y-offset -1.5 -\tweak whiteout 1 _2\)-\tweak parent-alignment-X #CENTER _\markup\smaller\smaller\italic\center-align "L.H."
      \change Staff = "left"
      |
      \shape #'((-0.4 . 3) (-1 . 9) (0 . 4) (0.3 . 1.7)) PhrasingSlur
      c4_5\( r4 r2
      <<
        { \change Staff = "right"
          c''2\)-\tweak Y-offset -1.5 -\tweak whiteout 1 _2-\tweak parent-alignment-X #0.6 _\markup\smaller\smaller\italic\center-align "L.H."
          \change Staff = "left"
        }
        \new Voice R1
      >>
      c1-5
    }

\new PianoStaff <<
  \new Staff = "right" \right
  \new Staff = "left" \left
>>

which then results in something like this:
Comment: @saraf Guile is basically the GNU implementation of scheme (hence the name). That being said, you more or less only need some basic knowledge of scheme/guile here. Rather you'd need some understanding how Lilypond and the scheme interface to lilypond works. Helpful resources are http://lilypond.org/doc/v2.23/Documentation/internals/scheme-functions the documentation of available scheme functions, and of course https://extending-lilypond.readthedocs.io/en/latest/ the documentation on extending lilypond. Also asking questions on the user mailing list email@example.com is a good idea.
Comment: @saraf Also of course all changes to the PhrasingSlur can be applied to specific Phrasing Slurs by using \once\override (or \temporary\override and \revert) or \tweak.
Comment: Thanks for this! :-) Looks like I'm going to have to learn Guile programming! Which book would be a good start?
Answer: I don't know how to make the staff-switch voice follower line to be curves, but I think I can answer some of your other questions:

The rest in the second measure should stay in the treble clef, but go down a bit to accommodate the high note of the left-hand voice.  This can be achieved by getting rid of the staff switches in the right hand and placing \once\voiceTwo before this rest instead. Similarly, the s2 in the fourth bar of the right-hand should be a visible rest r2 with a \once\voiceTwo before it, to move it down a little.

The r1 in the second last bar of the left-hand should be an r2, this is causing the extra half bar at the end.

To make the staff-switch line dashed, use:
\override VoiceFollower #'style  = #'dashed-line

You should get something like this:

As mentioned, I am not sure how to make the staff-switch lines to be curves, but if you can figure out how to get curves, it should prevent the line from colliding with the rest in the second bar.
I don't really understand your question 2.
You could just move the staff switch to before the rests in the first bar of the left-hand (so the rest go into up the top of the treble clef), this doesn't look great.  But having the staff-switch line before the rests just seems confusing — the rests belong to the voice.
Alternative Approach:
For this particular piece of music, I think it is worth considering an interpretation that there is only one voice.  This voice crosses staves and is played by both hands.
Thinking about the music this way warrants the use of \autoChange (or \autochange if you are using a version older that 2.21).  This makes the score much cleaner; eliminating the need for rests. The coding is much simpler too, and the dashed lines are easy to implement with a phrasing slur.
\new PianoStaff
    <<
        \new Staff = "up" {
            \clef "treble"
        }
        \new Staff = "down" {
            \clef "bass"
            \phrasingSlurDashed
            \autoChange b {
                \repeat volta 2 {
                    c4\(_5 c'-1 e'-3 g'-5 |
                    c''1\)_2^\markup{\italic"L.H."} |
                    c4\( c' e' g' |
                    c''2\)^\markup{\italic"L.H."} c' |
                    c1 |
                }
            }
        }
    >>

Comment: thank you! ... one question - the rest in the second measure is visible in the bass clef in the original picture ... but you mentioned in the beginning of the answer that it should stay in the treble clef - did you mean the other way around?
Comment: Also, in measure four, the original shows just one R1 in the bass clef - does that belong to RH or LH? In the picture that you posted - there are two R2s - one in between the two staves, and one in the bass clef. Logically - what you have posted seems correct, is the fourth measure of the original picture incorrect? Okay - this one is answered by Richard's comment on the question, I think.
Comment: @saraf  —  Oh, I didn't really look much at the original image this time.  I got my image as I intended, but it just doesn't agree with the image you provided.  I was thinking of each _hand_ as a voice, that must have note (or rest) at all times (which is reflected in your code structure).  But your original image appears to be thinking each _clef_ as a voice.
Comment: @saraf (I don't know why it's organised differently to your previous question.)
If you do want to get the same thing as the original image, it is much easier to code, (just do one staff at a time and don't use and staff switches at all) but then I don't know how you'll be able to get switch lines.
Comment: Okay ... got the answer to the first comment of mine ... "the rest in the second measure is visible in the bass clef in the original picture ... but you mentioned in the beginning of the answer that it should stay in the treble clef - did you mean the other way around?" ... the answer is that logically - the rest ACTUALLY IS for the treble hand, but for unknown/stylistic reasons - the original author has put it in the bass clef.
Comment: just for information - the examples are from this book - https://www.amazon.com/dp/0877180237」
Comment: Thanks! This alternative method looks really clean and simple. However, I am also generating MIDI from the samples, it just occurred to me, will the right hand notes also turn into legato - as they will be under the slurs?


Default Integration server in Node is not showing IIB 10?

Question: I have downloaded "10.0.0.14-IIB-WIN64-DEVELOPER.exe" and installed it after opening it default user node is showing but default integration server is not showing. When deploying any integration service "No Integeration server available found" error is coming. when I tried to make new integration server it is giving following error .
<code>Integration node rejected the request BIP1123E: The integration server already exists. The utility was asked to create integration server 'default2' on integration node 'TESTNODE_JA', but it already exists. Check that the names of the integration server and integration node are correct and reissue the command. or or No response from broker

Check that, 1. The integration node is running. 2. The TCP/IP port used by the integration node's web user interface is active. 3. The integration node name provided in the connection details matches the name of the integration node if the node is remote.
</code>
When I started it through command line following error came.
mqsicreateexecutiongroup.bat abc -e xyz BIP1124I: Creating integration server 'xyz' on integration node 'abc'... BIP1047E: The operation timed out waiting for a response. The utility did not receive an expected response from the integration node withi n a designated amount of time. The operation might have completed successfully, even though the response was not received.Ensure that the integration node is running and that the correct connection parameters have been supplied to the utility. Use the -w flag to increase the amount of time to wait for responses.
kindly help as i m new to IIB.
Comment: You should click edit and add more details to your question not try to add them in a comment where you can not format them.
Comment: Restart your toolkit. In windows run your toolkit as administrator.
Comment: restarted many times even installed and uninstalled it many times but integration server which is default is not coming
Answer: You should check real status of your installation
Try to use command via IBM Integration Console 10.0.0.14 (you can find it in your Windows Start Menu), not a cmd.exe
type mqsilist - it should display all your integration nodes
<code> C:\Program Files\IBM\IIB\10.0.0.15>mqsilist
BIP1325I: Integration node 'TESTNODE_abc' with administration URI 'http://localhost:4414' is running.
BIP8071I: Successful command completion.
</code>
if you type mqsilist again with the name of integration node you should get the list of all integration servers within your integration node
<code>  C:\Program Files\IBM\IIB\10.0.0.15>mqsilist TESTNODE_abc
-----------------------------------
BIP1286I: Integration server 'default' on integration node 'TESTNODE_abc' is running.
BIP8071I: Successful command completion.
</code>
It is possible to use web admin interface which is on URL listed in first mqsilist.
If there is nothing in your output, you can try to create integration server again and look into windows event viewer as is described in IBM Infocenter, there could be more information
https://www.ibm.com/support/knowledgecenter/en/SSMKHH_10.0.0/com.ibm.etools.mft.doc/an04090_.html


Are multilevel model and random effect model the same concept?

Question: I saw from their Wikipedia page, and my impression is that both are developed when the data is nested. Are multilevel model and random effect model the same concept? If they are not, what are their differences and relations?  Thanks!
Comment: Random effect is a very vague term, that means different things to different people. But yes, they can be the same.
Answer: Yes, to quote the Wikipedia page on multilevel model:

Multilevel models (also hierarchical linear models, nested models, mixed models, random coefficient, random-effects models, random parameter models, or split-plot designs) are statistical models of parameters that vary at more than one level.1

It naturally arises from observing the hierarchical and the clustered structure of the collected data typical found in treatment comparisons in clinical trials. It allows modelling residuals at different level, in other words, between-groups and within-group components for a two-level model.
I just re-iterated something that I learnt in my course, I could expand a bit on this if needed :)


Get the order id in woocommerce_new_order hook

Question: why don't can get id order in new order ?
This code don't work
add_action( 'woocommerce_new_order', 'get_order_details_woo',  1, 1  );
function get_order_details_woo ($order_id)
{

    $order = wc_get_order( $order_id );

    foreach ($order->get_items() as $item_key => $item_values):

        $item_id = $item_values->get_id();

        $item_data = $item_values->get_data();

        $product_name = $item_data['name'];

        //echo $product_name;
    endforeach;

}

But this code is work
 add_action( 'woocommerce_new_order', 'get_order_details_woo',  1, 1  );

    function get_order_details_woo ()
    {

        $order = wc_get_order( 100);

        foreach ($order->get_items() as $item_key => $item_values):

            $item_data = $item_values->get_data();

            $product_name = $item_data['name'];

            //echo $product_name;
endforeach;

    }

How get id in new order ?
Get new order details if i don't have order id ?
Comment: If you look [**to the source code**](https://docs.woocommerce.com/wc-apidocs/source-class-WC_Order_Data_Store_CPT.html#88), the `$order_id` **is included in the hooked function as an argument**, just like in **your first code**. So the problem is something else… **Why are you using this code? and for what?**
Answer: You get the order ID with this hook, but it seems that the order is just created at this moment with no product items yet. You can check this with var_dump.
try another hook:
add_action( 'woocommerce_checkout_create_order', 'get_order_details_woo',  1, 1  );

this one is fired just after the order object gets it's data and before it is saved to the database. You don't have to retrieve the order ID here, because you get the order object directly.
Answer: add_action( 'woocommerce_checkout_update_order_meta', 'get_order_details_woo', 10, 2 );
function get_order_details_woo($order_id, $data) {
}


Show that there is no vector field with curl $x \hat i + y \hat j + z \hat k$.

Question: I have no idea how to prove this. By assuming the field has the curl I get these 3 equations:
$$x = \frac{\partial F_{3}}{\partial y} - \frac{\partial F_{2}}{\partial z}$$
$$y = \frac{\partial F_{1}}{\partial z} - \frac{\partial F_{3}}{\partial x}$$
$$z = \frac{\partial F_{2}}{\partial z} - \frac{\partial F_{1}}{\partial y}$$
I cant't see how to get a contradiction from here.
Comment: [Vector calculus identities.](http://en.wikipedia.org/wiki/Vector_calculus_identities)
Answer: Hint: If one vector field is the curl of another, what is its divergence?
Answer: Divergence of every curl field must be zero.
In your case it is 3, so it is not a curl.


Left join query with EF 6

Question: First, here is the simplified EF model I'm using :
public partial class MaterielRoulant : IKeyed<int>
{
    public MaterielRoulant()
    {
        this.RelationsMaterielRoulantEquipement = new List<RelationMaterielRoulantEquipement>();
    }

    public int Id
    {
        get;
        set;
    }

    public virtual ICollection<RelationMaterielRoulantEquipement> RelationsMaterielRoulantEquipement
    {
        get;
        private set;
    }
}

public partial class RelationMaterielRoulantEquipement : IKeyed<int>
{
    public int EquipementId
    {
        get;
        set;
    }

    public int Id
    {
        get;
        set;
    }

    public int MaterielRoulantId
    {
        get;
        set;
    }

}

public partial class Equipement : IKeyed<int>, IEditable, IArchivable, IAuditable
{
    public int Id
    {
        get;
        set;
    }
}

public partial class Filiation : IKeyed<int>
{
    public int EquipementFilsId
    {
        get;
        set;
    }

    public int EquipementPereId
    {
        get;
        set;
    }

    public int Id
    {
        get;
        set;
    }
}

I have a MaterielRoulan item which is linked to 0 or 1 Equipement. In turn this equipement might have 1 son (another equipement) or not. The SQL query I previously used is :
select * from MaterielRoulant mr
left outer join RelationMaterielRoulantEquipement rmre on mr.Id = rmre.MaterielRoulantId
left outer join Equipement e1 on rmre.EquipementId = e1.Id
left outer join Filiation f1 on e1.Id = f1.EquipementPereId
left outer join Equipement e2 on f1.EquipementFilsId = e2.Id

So my EF6 translation of this query, which doesn't work, is :
var query = DataContext.Set<MaterielRoulant>()
    .Join(DataContext.Set<RelationMaterielRoulantEquipement>().DefaultIfEmpty(), x => x.Id, x => x.MaterielRoulantId, (mr, rmre) => new { mr, rmre })
    .Join(DataContext.Set<Equipement>().DefaultIfEmpty(), x => x.rmre.EquipementId, x => x.Id, (x, e1) => new { x.mr, x.rmre, e1 })
    .Join(DataContext.Set<Filiation>().DefaultIfEmpty(), x => x.e1.Id, e => e.EquipementPereId, (x, f1) => new { x.mr, x.rmre, x.e1, f1 })
    .Join(DataContext.Set<Equipement>().DefaultIfEmpty(), x => x.f1.EquipementFilsId, x => x.Id, (x, e2) => new { x.mr, x.rmre, e2 })

When I start SQL Server Profiler, I see that my query is translated like this :
SELECT
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT
        COUNT(1) AS [A1]
        FROM     [dbo].[MaterielRoulant] AS [Extent1]
        INNER JOIN  (SELECT [Extent2].[EquipementId] AS [EquipementId], [Extent2].[MaterielRoulantId] AS [MaterielRoulantId]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable1]
            LEFT OUTER JOIN [dbo].[RelationMaterielRoulantEquipement] AS [Extent2] ON 1 = 1 ) AS [Join1] ON [Extent1].[Id] = [Join1].[MaterielRoulantId]
        INNER JOIN  (SELECT [Extent3].[Id] AS [Id]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable2]
            LEFT OUTER JOIN [dbo].[Equipement] AS [Extent3] ON 1 = 1 ) AS [Join3] ON ([Join1].[EquipementId] = [Join3].[Id]) OR (([Join1].[EquipementId] IS NULL) AND ([Join3].[Id] IS NULL))
        INNER JOIN  (SELECT [Extent4].[EquipementFilsId] AS [EquipementFilsId], [Extent4].[EquipementPereId] AS [EquipementPereId]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable3]
            LEFT OUTER JOIN [dbo].[Filiation] AS [Extent4] ON 1 = 1 ) AS [Join5] ON ([Join3].[Id] = [Join5].[EquipementPereId]) OR (([Join3].[Id] IS NULL) AND ([Join5].[EquipementPereId] IS NULL))
        INNER JOIN  (SELECT [Extent5].[Id] AS [Id]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable4]
            LEFT OUTER JOIN [dbo].[Equipement] AS [Extent5] ON 1 = 1 ) AS [Join7] ON ([Join5].[EquipementFilsId] = [Join7].[Id]) OR (([Join5].[EquipementFilsId] IS NULL) AND ([Join7].[Id] IS NULL))
    )  AS [GroupBy1]

Where it should be :
SELECT
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT
        COUNT(1) AS [A1]
        FROM     [dbo].[MaterielRoulant] AS [Extent1]
        LEFT OUTER JOIN  (SELECT [Extent2].[EquipementId] AS [EquipementId], [Extent2].[MaterielRoulantId] AS [MaterielRoulantId]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable1]
            LEFT OUTER JOIN [dbo].[RelationMaterielRoulantEquipement] AS [Extent2] ON 1 = 1 ) AS [Join1] ON [Extent1].[Id] = [Join1].[MaterielRoulantId]
        LEFT OUTER JOIN  (SELECT [Extent3].[Id] AS [Id]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable2]
            LEFT OUTER JOIN [dbo].[Equipement] AS [Extent3] ON 1 = 1 ) AS [Join3] ON ([Join1].[EquipementId] = [Join3].[Id]) OR (([Join1].[EquipementId] IS NULL) AND ([Join3].[Id] IS NULL))
        LEFT OUTER JOIN  (SELECT [Extent4].[EquipementFilsId] AS [EquipementFilsId], [Extent4].[EquipementPereId] AS [EquipementPereId]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable3]
            LEFT OUTER JOIN [dbo].[Filiation] AS [Extent4] ON 1 = 1 ) AS [Join5] ON ([Join3].[Id] = [Join5].[EquipementPereId]) OR (([Join3].[Id] IS NULL) AND ([Join5].[EquipementPereId] IS NULL))
        LEFT OUTER JOIN  (SELECT [Extent5].[Id] AS [Id]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable4]
            LEFT OUTER JOIN [dbo].[Equipement] AS [Extent5] ON 1 = 1 ) AS [Join7] ON ([Join5].[EquipementFilsId] = [Join7].[Id]) OR (([Join5].[EquipementFilsId] IS NULL) AND ([Join7].[Id] IS NULL))
    )  AS [GroupBy1]

Inner join replaced by outer join.
I have tried using GroupJoin, which still give me the wrong answer with a much more complicated query. I would like to keep the lambda writing as it's used everywhere in my application but at this point any working solution would be great.
Thanks in advance
Answer: You can write it like this:
var q =
    from mr in db.MaterielRoulant
    from rmre in db.RelationMaterielRoulantEquipement.Where(x => mr.Id == x.MaterielRoulantId).DefaultIfEmpty()
    from e1 in db.Equipement.Where(x => rmre.EquipementId == x.Id).DefaultIfEmpty()
    from f1 in db.Filiation.Where(x => e1.Id == x.EquipementPereId).DefaultIfEmpty()
    from e2 in db.Equipement.Where(x => f1.EquipementFilsId == x.Id).DefaultIfEmpty()
    select new {...}

For expression syntax it'll look like this (for the first 2 joins)
db.MaterielRoulant
   .SelectMany(
      mr =>
         db.RelationMaterielRoulantEquipement
            .Where (x => mr.Id == x.MaterielRoulantId)
            .DefaultIfEmpty(),
      (mr, rmre) =>
         new
         {
            mr = mr,
            rmre = rmre
         }
   )
   .SelectMany(
      temp =>
         db.Equipement
            .Where (x => rmre.EquipementId == x.Id)
            .DefaultIfEmpty(),
      (temp, e1) =>
        new
        {
          mr = temp.mr,
          rmre = temp.rmre,
          e1 = e1
       }
   )...

Comment: @BrandonSeydel Just because it looks more complicated and is more difficult to maintain does not make it more professional. (In my opinion)
Especially if you need a tool to create it for you.
Comment: Thanks man it's working fine. But i don't get why I can't have the same result using Lambda Expression...Is lambda a beta feature or something ?
Comment: No, this can be written entirely with lambda expressions but that makes it more complicated and difficult to read. I think ReSharper can translate it for you.
Comment: Yea resharper will get rid of linq and turn it into method chaining.  Just set ur cursor on the from in the line statement and have it convert to a method chain.  I think method chaining is much more professional than linq.

Left join query with EF 6


Arithmetic modulo of negative number

Question: According to Modulo of a negative number

"In arithmetic modulo , we seek to express any $$ as $+$,
  where $$ must be a non-negative integer."

This makes sense to me as we are trying to group numbers into classes from $0$ to $n$.
E.g. If $n = 4$, then one of the following holds:
$$a \equiv b \pmod 4 \iff \begin{cases} a, b \in [0] = \{4k + 0\mid k\in \mathbb Z\} = \{\cdots, -8, -4, 0, 4, 8, 12,\cdots\} \\ \\
a, b \in [1] = \{4k + 1\mid k \in \mathbb Z\} = \{\cdots, -7, -3, 1, 5, 9, 13,\cdots\} \\ \\
a ,b \in [2] = \{4k + 2\mid k \in \mathbb Z\} = \{\cdots, -6, -2, 2, 6, 10, 14,\cdots\} \\ \\
a, b \in [3] = \{4k + 3\mid k \in \mathbb Z\} = \{\cdots, -5, -1, 3, 7, 11, 15, \cdots\}
\end{cases}
$$
But according to Shall remainder always be positive?
For example:
$$-48\bmod{5} = 2$$
and
$$-48 \bmod{5} = -3$$
are both true because

"2 and −3 are just two names for the same element" (Means they are the same name for same class I assume)

Hence $r$ can be a non-negative integer which disproves the original statement? I am confused.
Comment: You should ignore the 2nd linked answer and instead read the other answers there (the highest voted answer is often not  the best).
Comment: @mathguy No, operations are (single-valued) functions. The most common  definition used for the operation is $\, a\bmod n\,$ is the least natural $\,r\equiv a\pmod n,\,$ which is the remainder $r$ left by $ a\div n.\ $  Then we have $\ a\equiv b\pmod{n}\iff  a\bmod n = b\bmod n.\ $
Comment: To be honest I do not know why the first citation says we seek where $r$ must be non-negative.  I do not think we do any such thing and we can certainly have negative expressions of residues.  The *remainder* is by convention non negative but is is also strictly less than the modulus.  But the remainder isn't the residue class.  It is a specific element with in the class.
Comment: You are confusing some things. $-48\pmod 5 = 2$ as $2$ is in the range $[0,5)$. But, $$-48\equiv -3\equiv 2\pmod 5$$The point is, if one forms the group $\mathbb Z/5\mathbb Z$, the group of integers modulo $5$, $-48,\;-3,$ and $2$ all describe the same number in this group. Often, to distinguish a number in $\mathbb Z$ from one in $\mathbb Z/n\mathbb Z$, we write $k\in\mathbb Z$, $\overline{k}\in\mathbb Z/n\mathbb Z$.
Comment: @Don Wrong notation, it should be $\ {-}48\bmod 5 = 2\ $ (use \bmod in TeX)
Comment: @BillDubuque I think Mark Bennet's answer provides more clarity for me
Comment: Do you understand the difference between $\bmod$ the binary operation vs. equivalence relation?
Comment: @BillDubuque Is it correct to say that $-48 mod 5$ when used as a binary operation can represent any number in the set $[2]$ and when mod is used to show equivalence relation we find a nonnegative integer $r$ from [0,5) which indicates which set $a$ is in?
Comment: @BillDubuque That was a typo lol, my bad. I don't think the rest of the comment is incorrect.
Answer: In mathematics, one usually writes "$a\equiv b\pmod m$", and that means precisely that $b-a$ is a multiple (an integral multiple, more specifically) of $m$. With this definition and this notation, $m$ can be any integer, positive, negative, or zero.
Answer: The division with remainder is usualy defined from left to right.
As has been said by  other posters.
If $n\ mod\  m\neq 0$ with $m>0$ one asks for the largest integer multiple
$mq$ which is less than n and the remainder is the difference $r=n-mq$
Hence r is always $>0$
A way to get negative remainders would be to consider division from right to left
instead.
For a given modulo $m>0$ we have  remainders $\{-m+1,\dots,-1,0\}$ instead
of $\{0,1,\dots,m-1\}$ and $mq$ is the least integer multiple of m larger than n
.
Both definitions are equivalent,
$n=r\ mod\ m$ for some $r\in \{0,\dots,m-1\}$ according to left right division iff $n=m-r\ mod\ m$  which is $n=-m+r\ mod\ m$ according right left division.
In the second system one would get the result of OP's example
$-48=-3\ mod\ 5$ and respectivly $48=-2\ mod\ 5$.
If one wants negative remainders for $n<0$ and positive remainders $n>0$ one can
introduce a shift function which assigns remainder $-m+r=-(m-r)$ to n whenever n is negative
and r otherwise,where r is defined for n and m in the canonical way
Where i have seen negative remainders being used is when considering quadratic congruences
like $x^2=-1\ mod\ m$ which is the same with asking  for $x^2=m-1\ mod\ m$
Answer: Operations are (single-valued) functions. The most common definition used for the operation is $ mod $ is the least natural $≡(mod)$, which is the remainder $$ left by $÷$.  Then we have  $≡(mod)⟺mod=mod$.

Arithmetic modulo of negative number


python-semantic-release doesn't recognise gitlab

Question: I tried to set up my repo to automatically trigger versioning increase based on commit.
But it doesn't seem to recognise that it's on Gitlab.
Here's the logs of the latest run:
semantic-release -vv publish
[05:17:10] DEBUG    [semantic_release.cli.commands.main] DEBUG       main.py:105
                    main.main: logging level set to: DEBUG
           DEBUG    [semantic_release.cli.commands.main] DEBUG       main.py:123
                    main.main: global cli options:
                    GlobalCommandLineOptions(noop=False,
                    verbosity=2, config_file='pyproject.toml',
                    strict=False)
           INFO     [semantic_release.cli.util] INFO                  util.py:78
                    util.load_raw_config_file: Loading configuration
                    from pyproject.toml
           DEBUG    [semantic_release.cli.util] DEBUG                 util.py:81
                    util.load_raw_config_file: Trying to parse
                    configuration pyproject.toml in TOML format
           INFO     [semantic_release.cli.config] INFO             config.py:261
                    config.select_branch_options: Using group
                    'develop' options, as 'develop' matches
                    'develop'
           WARNING  [semantic_release.cli.config] WARNING          config.py:380
                    config.from_raw_config: the token for the
                    remote VCS is configured as stored in the
                    GH_TOKEN environment variable, but it is empty
           DEBUG    [semantic_release.changelog.template] DEBUG   template.py:55
                    template.environment: {'template_dir':
                    'templates', 'block_start_string': '{%',
                    'block_end_string': '%}',
                    'variable_start_string': '{{',
                    'variable_end_string': '}}',
                    'comment_start_string': '{#',
                    'comment_end_string': '#}',
                    'line_statement_prefix': None,
                    'line_comment_prefix': None, 'trim_blocks':
                    False, 'lstrip_blocks': False,
                    'newline_sequence': '\n',
                    'keep_trailing_newline': False, 'extensions':
                    (), 'autoescape': True, 'autoescape_value':
                    True}
           DEBUG    [semantic_release.version.translator] DEBUG translator.py:40
                    translator._invert_tag_format_to_re:
                    inverted tag_format 'v{version}' to
                    'v(?P<version>.*)'
           DEBUG    [semantic_release.version.version] DEBUG      version.py:121
                    version.parse: attempting to parse string
                    '1.4.0' as Version
           DEBUG    [semantic_release.version.version] DEBUG      version.py:145
                    version.parse: version string 1.4.0 parsed as
                    a non-prerelease
           DEBUG    [semantic_release.version.version] DEBUG      version.py:148
                    version.parse: parsed build metadata '' from
                    version string 1.4.0
           INFO     [semantic_release.version.algorithm] INFO    algorithm.py:60
                    algorithm.tags_and_versions: found 1
                    previous tags
           INFO     [semantic_release.cli.commands.publish] INFO   publish.py:48
                    publish.publish: Uploading distributions to
                    release
           DEBUG    [semantic_release.hvcs.github] DEBUG           helpers.py:45
                    helpers._wrapper:
                    upload_dists(<semantic_release.hvcs.github.Git
                    hub object at 0x7efc0b7b1390>, tag='v1.4.0',
                    dist_glob='dist/*')
           DEBUG    [semantic_release.hvcs.github] DEBUG           helpers.py:45
                    helpers._wrapper:
                    get_release_id_by_tag(<semantic_release.hvcs.g
                    ithub.Github object at 0x7efc0b7b1390>,
                    tag='v1.4.0')
           DEBUG    [semantic_release.helpers] DEBUG              helpers.py:112
                    helpers.parse_git_url: Parsing git url
                    'https://gitlab-ci-token:***@gitlab.com/test/custom/projects/app/backend.
                    git'
           DEBUG    [urllib3.connectionpool] DEBUG        connectionpool.py:1055
                    connectionpool._new_conn: Starting
                    new HTTPS connection (1):
                    api.github.com:443
           DEBUG    [urllib3.connectionpool] DEBUG         connectionpool.py:549
                    connectionpool._make_request:
                    https://api.github.com:443 "GET
                    /repos/test/custom/projects/app/backend/releases/tags/v1.4.0 HTTP/1.1" 404 91
           DEBUG    [semantic_release.hvcs.github] DEBUG           helpers.py:56
                    helpers._wrapper: Github.get_release_id_by_tag
                    -> None
           WARNING  [semantic_release.hvcs.github] WARNING         github.py:252
                    github.upload_dists: No release corresponds to
                    tag v1.4.0, can't upload dists
           DEBUG    [semantic_release.hvcs.github] DEBUG           helpers.py:56
                    helpers._wrapper: Github.upload_dists -> 0

Cleaning up project directory and file based variables

And this is the config files to set that up:
[tool.semantic_release]
version_variable = "lambda/__init__.py:__version__" # --> version = "1.4.0"

[tool.semantic_release.branches.develop]
match = "develop"
prerelease = true

As you can see from the logs, it tries to interact with GitHub which is not suppose to do so? I couldn't find a way on the docs to force is on a particular VCS, it supposedly detects it automatically from environment variables. But I don't know which one is triggering this.
Anyone ever had this issue? Or if you know a better way to do the same thing?
Answer: What you need to do is to add remote type setting for Gitlab as described in the documentation here
Add something like this for a start:
[tool.semantic_release.remote]
type = "gitlab"