Como saber qual lista um objeto pertence?

Question: Estou com um problema, que não estou conseguindo saber a qual lista um objeto pertence.
Tenho que fazer um jogo de truco em java, tenho a classe jogador, e cada jogador tem uma lista com as cartas (a carta é o objeto), porém o jogo tem 4 jogadores. O problema é que para processar a jogada preciso saber a qual jogador a carta jogada pertence. Tenho a lista baralho, que contém as cartas criadas no construtor, e dou elas ao jogador dentro do loop.
public class Jogador {
private int id;
private String nome;
private List<LabelCarta> mao;

public Jogador() {
    mao = new ArrayList<>();
}

public void fazerJogada() {

}

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getNome() {
    return nome;
}
public void setNome(String nome) {
    this.nome = nome;
}
public List<LabelCarta> getMao() {
    return mao;
}
public void setMao(List<LabelCarta> mao) {
    this.mao = mao;
}

Classe que está rodando o jogo
Chamo esses dois métodos no construtor, após inicializar os demais componentes
private void gerarCartas() {
    for(int i = 1; i<=40;i++) {

        carta = new LabelCarta(i); //crio a carta pelo indice

        baralho.add(carta); //adiciono ela ao baralho principal
    }

    Collections.shuffle(baralho);//embaralhar

}

private void adicionarCartas() {

    for(int player = 0; player<=4;player++) {
        jogador = new Jogador();// crio 4 jogadores pelo loop
        jogador.setNome("Jogador "+(player+1));

        for(int cartaJogador = 0; cartaJogador<=2;cartaJogador++ ) {

            jogador.getMao().add(baralho.get(cartaJogador)); //da carta ao

            baralho.remove(cartaJogador); //depois de dar a carta ao jogador a removo do baralho principal

}
}
Answer: Talvez isso possa te ajudar, não sabia o que pertencia ao objeto LabelCarta, então surgeri um exemplo de atributo, se não der certo comenta aí que a gente chega lá.
    List<Jogador> jogadorList = new ArrayList<>();
    private void adicionarCartas() {

        for(int player = 0; player<=4;player++) {
            jogador = new Jogador();// crio 4 jogadores pelo loop
            jogador.setNome("Jogador "+(player+1));
            for(int cartaJogador = 0; cartaJogador<=2;cartaJogador++ ) {
                jogador.getMao().add(baralho.get(cartaJogador)); //da carta ao

                baralho.remove(cartaJogador);
            }
        jogadorList.add(jogador);
        }
    }

    private void donoDaCarta(LabelCarta labelCarta) {
        for(Jogador j:jogadorList) {
            for(LabelCarta lc: j.getMao) {
                if(labelCarta.getAlgumAtributoUnico == lc.getAlgumAtributoUnico) {
                        System.out.println("O dono da carta passada no parametro é "+j.getNome());
                    }
                }
            }
        }

Comment: Eu estou inscanciando o array vazio no construtor do jogador, não sei se precisa fazer isso de novo. Estou conseguindo adicionar as cartas à mao do jogador, verifiquei isso e está danco certo. O ponto é que existem 4 jogadores, cada um tem 3 cartas, e eu nao consigo saber a qual jogador pertence cada carta. Nao estou conseguindo pensar em uma maneira de descobrir isso
Comment: Tem como mostrar a classe Jogador e o array baralho pra ver se eu consigo visualizar sua dúvida
Comment: Porque aparentemente você está instanciando a classe jogador a cada vez que se cria um jogador é isso?se for isso, eu recomendo vc fazer arrylist ou um hashmap só para vincular a carta ao jogador. Diga se é isso q eu te ajudo.
Comment: Isso mesmo, vou colocar o código no post
Comment: Pronto, editei o post
Comment: editei a resposta
Comment: Funcionou, era isso mesmo. Não sabia que existia esse tipo de for.
Muito obrigado!!!
Comment: ele é chamado de foreach, criado a partir do java 5, que também é o mesmo que for(int i = 0; i < jogadorList.size(); i++) {
}
Comment: por nada cara, é sempre bom ajudar


Expected minimum absolute difference to a given point?

Question: I am trying to compute the expected absolute difference between $n$ iid uniformly between $[- \epsilon, \epsilon]$ sampled points to a given point $- \epsilon< c < \epsilon$:
$$
\mathrm{E}(\mathrm{min}(|x_1-c|,|x_2-c|,...,|x_n-c|))
$$
I know, that the expected minimum of n iid uniformly between $[0, \epsilon]$ sampled points is $\frac{\epsilon}{n+1}$.
How would I go about this problem though?
Answer: Since $\min|X_i - c|$ is non-negative and you want to compute its expectation, we can compute its survival function first. Consider the survival function of individual $|X_i - c|$:
$$ \begin{align}
S(x)&=\Pr\{|X_i - c| > x\}  \\
&= \Pr\{X_i > c + x\} + \Pr\{X_i < c - x\} \\
&= \begin{cases}
1 & \text {if} & x \leq 0 \\
\displaystyle 1 - \frac {x} {\epsilon} & \text{if} & 0 < x \leq \epsilon - |c|\\
\displaystyle \frac {\epsilon + |c| - x} {2\epsilon} & \text {if} & \epsilon - |c| < x < \epsilon + |c| \\
0 & \text{if} & x \geq \epsilon + |c|
\end{cases}
\end{align}$$
Then the survival function of $\min |X_i - c|$ will be $S(x)^n$ and thus
$$ \begin{align}
 E[\min|X_i - c|]
&= \int_0^{+\infty}S(x)^ndx \\
&= \int_0^{\epsilon - |c|} \left(1 - \frac {x} {\epsilon} \right)^n dx
+ \int_{\epsilon - |c|}^{\epsilon + |c|} \left(\frac {\epsilon + |c| - x} {2\epsilon} \right)^n dx  \\
&= \left. \frac {-\epsilon} {n+1}\left(1 - \frac {x} {\epsilon} \right)^{n+1} \right|_0^{\epsilon - |c|} + \left.\frac {-2\epsilon} {n+1} \left(\frac {\epsilon + |c| - x} {2\epsilon} \right)^{n+1} \right|_{\epsilon - |c|}^{\epsilon + |c|} \\
&= \frac {\epsilon} {n+1}\left(1 - \frac {|c|^{n+1}} {\epsilon^{n+1}} + 2\frac {|c|^{n+1}} {\epsilon^{n+1}}\right) \\
&= \frac {\epsilon} {n+1}\left(1 + \frac {|c|^{n+1}} {\epsilon^{n+1}} \right)
\end{align}$$
As you see, the answer is minimized when $c = 0$ and it reduced back to the previous solution.


Is there a great WYSIWYG html editor component that had Drag n' Drop *like* the Google Waves editor?

Question: Is there a component out there that can be used that provides some of the
great capabilities that the Google Waves editor provides (or Google Docs editor)?
If it only works on a certain browser, that is fine. If it is part
of GWT or some other framework, that is fine. I know that this will probably require Google Gears. I would prefer just a javascript library.
It must/should have:

Drag and Drop of images or files into
the area
The ability to have toggle for sections that were changes
(version history)
Basic support for PRE, Links, OL, LI. (Stack overflow editor, is close)
It must have auto-save support
It must have a sane API and system for uploading/communicating with server

It does not need:

Spell check
Real-time character by character
collaboration
Full playback of editor history

I have seen FCKEditor and tinyMce. These editors are way too clunky and complicated.
Answer: As noted here, Google Wave uses GWT, so you should be able to get those effects using GWT.
For direct confirmation of this, watch this video, where between 40 and 45 seconds in, a Google employee says about the Google Wave web client "it was built with the Google Web Toolkit".
(See also this search for "wave" and "gwt")
Comment: can anyone confirm that, however?
Answer: The drag and drop would require Gears as mentioned in the wave presentation, but they are working on getting an html 5 drag and drop api accepted. I don't know of any good solution to do all the other things. I know there are some simple rich text editors that can be used as plugins to mediawiki, so those combined could give you most of that functionality.


Singing what you're playing vs playing what you're singing

Question: I've heard the advice :- play what you sing as a means of practicing playing what you hear in your head.
I've realised that I tend to sing the stuff I play instead of playing what I sing.
I already know how some scale patterns, pentatonic runs and arpeggios sound, so I end up singing these patterns. I'm singing what I know my fingers are already going to do.
Ideally, I believe you want to be doing the opposite where you're playing what you're singing. So, how can I break this habit?
Answer: I know exactly what you're referring to and recall having this same problem myself. I discussed it with David Berkman in a lesson and here's the advice he gave me. This only works for pianists, but I'll describe a couple other techniques too.
When improvising on the piano, play the lines in both hands. Play through the form, and improvise such that your right hand is "leading" the left hand. When creating lines, let them flow from your right hand. Then switch the second time through the form. Let your left hand "lead" the right hand. When creating lines, think about your left hand and where it's moving, and let the left hand guide the right hand. This might seem strange or arbitrary, but there's an objective measure for whether we're doing it correctly. For most pianists, the right hand is stronger in improvising than the left hand. As a result, when my right hand was "leading," there were instances where my left hand couldn't keep up and missed the line. But when I switched and created lines using my left hand, I rarely had the opposite problem where my right hand couldn't keep up. This is a good gauge: if I am truly letting the left hand be the creator, then there are far fewer instances where the left hand struggles to keep up.
On guitar or another instrument, you can try something Jamey Aebersold once told me. Practice singing a solo without playing along on your instrument. After singing a lick or singing 8 bars, go back and replicate it on your instrument. This breaks the link between voice and finger. When I used this technique, I wasn't simply singing what my fingers already knew, because my fingers weren't moving.
But in addition to these techniques, which can be helpful, I realized that there was a deeper issue creating the problem you describe. My fingers had become so accustomed to certain movements (licks, patterns, etc.) that my brain turned on autopilot and just followed along. I played the same licks over and over and simply sang those licks which had become so rote. It turns out this was an issue of imbalance. The problem disappeared when I began learning new bebop heads systematically in all 12 keys at different tempos. By continually practicing new material and always focusing on all 12 keys (including those where I was much weaker), my fingers gained greater flexibility and freedom. Before, those licks were so entrenched in my muscle memory because they were so much easier to play. But with this practice, those licks lost that special status. I was strong enough in my technique that it was just as easy to play practiced licks as it was to play new licks I might come up with on the spot. It felt like I got out of the rut of my limited muscle memory by strengthening the areas where I was weaker.
I definitely recommend this routine. I would choose a new bebop head, start really slow (e.g., quarter note = 70 BPM), play the head in all 12 keys, the increase by 2-3 BPM, go through all 12 keys again, and continue until I reached ~220 BPM.
Comment: In regard to "all 12 keys" and "I wasn't simply singing what my fingers already knew, because my fingers weren't moving", a guitar-centric practice tip in the same vein is to use a different position on the neck or to use only one string. In both cases the point is to break out of your muscle memory whether it's for learning the notes, hearing intervals, getting out of melodic ruts, whatever...
Comment: Hey man, thank you so much for your detailed reply. I'm sorry but my knowledge of Jazz is poor and I do not know what a bebop head is. Do you mind explaining this briefly?
Comment: Sure! "Head" is just another term for melody, and bebop is just a style of jazz from the 1940s. I liked to practice melodies from bebop-style songs because they were notoriously complex (both melodically and rhythmically). So they did a great job of pushing me beyond what I was comfortable with. They were essentially high-quality licks to practice, which someone else had already created and written down.
Comment: When you say 'with both hands', I'm guessing you mean octave unison. Correct?
Comment: @Tim, almost always either octaves or double octaves. The farther apart the hands get, the harder it becomes.
Comment: @jdjazz would you be kind enough to name some tunes you used for practice? So that I can get into bebop lines as well.
Comment: @user37496, those are all awesome tips. karthik, I started with these bebop blues tunes: Blues for Alice, Billie's Bounce, Au Privave. [Here's a big list](https://www.jwpepper.com/50-Essential-Bebop-Bebop-Heads-for-Alto-Sax/5490503.item#/submit). Another tune I liked for some good fundamentals was Yardbird Suite, but it's not a blues. If you want to get into jazz, I definitely suggest this. If you're not trying to start playing jazz, I don't particularly recommend working with bebop tunes. Instead, you might transcribe one of your favorite guitar solos and learn that in all 12 keys.
Answer: I understand what you're saying but I'm not sure I totally agree with the premise.
It seems that you're assuming that everybody naturally has melodies in their head that come out of nowhere. But these melodies mostly come from listening to music, learning musical patterns like scales, arpeggios, intervals, and then making the connections between the two whether consciously or not. And the music that you're drawing inspiration from was made in the same way: based on patterns and the music that came before it. So playing scales and other patterns is about drilling that musicality into your head to the point where you can make use of it.
While I do completely endorse it, I think the benefit of singing, saying, or even thinking along with what you're playing is about making connections. Your fingers are learning the muscle memory, your brain is learning the theory—the note/degree names if that is in fact what you're singing—and your ears are learning how that sounds. And most importantly you're making the connections between those so that when you do have an idea in your head, you can more easily translate it to the correct musical context or fingering (or vice-versa).
It sounds like maybe you have a different problem that is pretty common. Your playing sounds too scale-like? Things come out sounding like an exercise rather than music? If so, here are some suggestions:

Don't just play up and down the pattern/scale. First of all, try defaulting to playing descending rather than ascending.
Play them in different intervals, for example 3rds, 4ths, 5ths, 6ths, etc. (or different inversions in the case of arpeggios)
Add in embellishments like appogiaturas, enclosures, chromatics, etc
Don't just play the patterns from beginning to end, mix them up too. Play a few notes in scalar fashion, then use an intervalic jump, then an embellishment, etc.
In other words, use the patterns as a jumping off point and as an underlying mental framework of what notes might fit. But quickly move on to experimentation and using what sounds good.
Learn some things other than just patterns. Learn some actual melodies. These still have patterns within them but you're skipping directly to something that already sounds melodic and drilling that into brain instead.
Steal from other music you like and dissect it. What are they doing that makes you like it?
Try using repeated sequences to establish a theme. That is, when you find a short melodic pattern that you like, try repeating it over the next chord change transposing as necessary. Playing it over a new harmonic context will add a new flavor but the repetition (the same/similar relative intervals) ties it all together.
Try repeating rhythms but varying the notes or vice versa. Again, use the repetition to establish a theme.
Learn about harmony and focus on that aspect more. Remember that you're not just playing melodies in a vacuum. Part of what makes a melody sound interesting at any given point is how that note fits in against the harmonic context. Simply focusing on the chord tones, extensions, and what notes can connect the chord changes will do wonders for your melodies.

Everybody has some basic sense of musicality just from hearing music their entire life. We hear consonance and dissonance. We hear tension and expect release, etc. So even non-musicians might be able to sing a melody but they are drawing from the underlying musical concepts that they've passively picked up over the years. As a musician, your goal is actively practice those things so that you can truly harness them.
So, in other words, it's not that you haven't found the trick to unlock the melodic creativity already in your brain. It's that you still need to train your brain to be melodically creative.
Comment: My point is that *everybody* is uncreative until you learn otherwise. It's a myth that musical creativity comes out of nowhere. And the problem with "playing what you sing or think" is that these musical thoughts can only come from your previous experiences with music. For non-musicians that's passive learning through listening, but for musicians it's that plus training. It's the *practice and understanding* of music that unlocks creativity past basic aural skill. That's where the "thoughts" come from *to begin with* so why not put your focus there? As that improves so will your "inner voice".
Comment: This is great advice, but I think there's a specific issue at the heart of this problem, which relates to muscle memory and an imbalanced in one's technical capability. @karthik's issue isn't necessarily that his brain is melodically uncreative--the problem is that there's a disconnect between his melodic creativity and his fingers. In my experience, this is a problem of muscle memory, technical capability, and strengthening one's weaknesses on the instrument. To that effect, your suggestions are helpful, but I think your diagnosis is slightly off.
Comment: I completely agree, and I think now this is the flip side of what I wrote. Maybe there's a disconnect as I suggest, & Karthik's playing *is* lagging behind the creativity he has already cultivated through listening. But maybe not--in which case more cultivating would do the trick, as you say. Interesting that, regardless of the root issue, we both have the same advice: practice with a greater variety. +1
Answer: My suggestion is to sing some songs that you know, any song.  For example,

Happy Birthday to You
Mary had a little lamb
When the saints go marching in
Pop goes the weasel
Hello Dolly

Really any song will do.  My guess is that you don't know the fingerings for all of these songs.
Now, take the same song and start on a different pitch/note and sing the song from the new starting pitch.  This will require different fingerings.
I'm a Jazz Trumpet player and what I've just described is one of the techniques I practice.
My goal when doing this is to be able to sing an improv lick and play it.
Another technique is to record what you sing and when playing it back also play your instrument.
For example, if there is a 16 bar improv/solo that I need to work on.  I might sing the entire improv and record it to my phone.  Then play the audio (from my phone) and try to match the pitches on my trumpet.  This is a form of transcribing.  This again requires hearing a pitch and then playing it.
Another technique is not recording but to sing a phrase and then play it.
For example, in the 16 bar solo, I might sing a two bar lick, and then play it back in the next two bars.  Then continue singing the next two bar lick and then playing what I just sang.  This is repeated until I finish the 16 bars.   I use iRealPro and Musescore to help with repeating the two bar phrases.
Hope this helps.


Ray-sphere intersection: t-value of the intersection points

Question: You have a sphere centered at [1,2,3] with radius 3, and a ray from [10,10,10] in the direction [-1,-1,-1]. Write the implicit equation for the sphere, the parametric equation for the ray, and compute the t-value of the intersection points.
I know that the equation of a sphere centered at $(x_{0}, y_{0}, z_{0})$ and with radius $r$ is $(x - x_{0})^{2} + (y - y_{0})^{2} + (z - z_{0})^{2} = 0$.
The implicit equation of this sphere is $(x - 1)^{2} + (y - 2)^{2} + (z - 3)^{2} = 3^{2} = 9$.
I also know that the parametric equation for a ray starting at the point $P(x_{0}, y_{0}, z_{0})$ and headed in the direction of the vector $\mathbb{v} = (v_{x}, y_{y}, y_{z})$ is given by $$x = x_{0} + v_{x}t$$ $$y = y_{0} + v_{y}t$$ $$z = z_{0} + v_{z}t$$
The parametric equation for this ray is $$x = 10 + (-1)t$$ $$y = 10 + (-1)t$$ $$z = 10 + (-1)t$$
How do I compute the $t$-value of the intersection points?
Comment: You have already done all the work! You just have to replace the parametric coordinates for the ray in the equation of the sphere, and you will have a equation of second order in $t$, which have 0, 1 or 2 solutions depending on the fact that the ray hits or not the sphere. You put back the roots in the parametric equation and you have the two points of intersection!
Comment: @Martigan Thank you for your help! I posted my work using your help in [an answer](http://math.stackexchange.com/questions/982611/ray-sphere-intersection-t-value-of-the-intersection-points/982671#982671).
Answer: From a comment from Martigan:

You have already done all the work! You just have to replace the parametric coordinates for the ray in the equation of the sphere, and you will have a equation of second order in t, which have 0, 1 or 2 solutions depending on the fact that the ray hits or not the sphere. You put back the roots in the parametric equation and you have the two points of intersection!

We know that for the ray, $x = y = z = 10 + (-1)t = 10 - t$.
The equation of the sphere is $$(x - 1)^{2} + (y - 2)^{2} + (z - 3)^{2} = 3^{2} = 9$$
Substitute the parametric coordinates for the ray into the equation of the sphere:
$\begin{align*}
((10 - t) - 1)^{2} + ((10 - t) - 2)^{2} + ((10 - t) - 3)^{2} &= 9 \\
(9 - t)^{2} + (8 - t)^{2} + (7 - t)^{2} &= 9 \\
(t^{2} - 18t + 81) + (t^{2} - 16t + 64) + (t^{2} - 14t + 49) &= 9 \\
3t^{2} - 48t + 194 &= 9 \\
t &= \dfrac{1}{3}\left(24 \pm \sqrt{21}\right) \\
&= 6.4725\text{ and }9.5275
\end{align*}$


Non-negative fractions summing to $1$

Question: Let $ d_1,\ldots, d_n \ge 2 $ be pairwise relatively prime. Are there any $ c_1,\ldots,c_n \in \mathbb{Z}_{\ge 0} $ with $ c_i \le d_i-1 $ for all $ i=1,\ldots,n $, such that $\displaystyle \sum_{i=1}^n \dfrac{c_i}{d_i} =1 $?
I see the answer is negative for all of the smaller cases I considered. But I have no proof. This is a conjecture given me by my friend, but probably this can be done with elementary tools, so I am posting it here instead of MO. I hope someone will help me.
Answer: Hint: Multiply both sides of the equation $\sum_{i=1}^n \frac{c_i}{d_i}=1$ by the product $d_2\cdots d_n$.
Comment: To the person who edited "product $d_2\cdots d_n$" to $d_1\cdots d_n$, the $d_2\cdots d_n$ is intended.
Answer: If it is the case $d_1\cdots d_n=c_1d_2\cdots d_n+$ a multiple of $d_1$, that is, $d_1$ divides $c_1d_2\cdots d_n$. Since $d_1$ is coprime with $d_i$, $2\leq i\leq n$, then $d_1$ divides $c_1$, but this is impossible.

Non-negative fractions summing to $1$


Como abrir link em uma parte específica de uma nova guia

Question: Quero que, quando a pessoa clicar em um link, abra uma nova guia em uma parte específica da nova guia.
Comment: Cara se vc tem uma pergunta nova, abra outra pergunta. Qual sua intenção em editar o conteúdo de uma pergunta que já foi respondida e fechada e ainda por cima era sobre outra coisa?
Answer: Para abrir a página em uma nova guia, adicione a propriedade target=_blank.
Se quiser que ela seja aberta em uma parte específica, coloque o id correspondente a este elemento no link, assim:
Abrir nova página

Neste exemplo, a nova página abre imediatamente no elemento com o id footer.
Comment: Obrigado, não estava dando certo porque eu estava colocando uma / no href
("novapagina.html/#footer")


Permission denied for gitweb.cgi on CentOS

Question: I've set up gitweb on my web server. I have created projects on the server. I can add commits to them and also clone them remotely.
The gitweb "homepage" does display and the static files like css, logo, favicon are loaded when I visit my git.website.
Issue is I only see the message:  No such projects found found..
Every time I refresh the webpage I see the following in my /var/log/httpd/error_log
[Wed Aug 04 00:39:32.321352 2021] [cgid:error] [pid 44346:tid 140132795492096] [client MY_HOME_IP:37700] fatal: mmap failed: Permission denied: /var/www/git/gitweb.cgi, referer: https://git.mydomain.abc/

I've confirmed httpd is running as the apache user and have the ownership of /var/www set to apache as well. The permissions are properly set up as well I believe:
[root@git ~]# ps auxw | grep httpd
root       44780  0.2  1.6 281804 13828 ?        Ss   00:48   0:00 /usr/sbin/httpd -DFOREGROUND
apache     44782  0.0  1.0 295684  8876 ?        S    00:48   0:00 /usr/sbin/httpd -DFOREGROUND
apache     44783  0.0  1.7 1484604 14712 ?       Sl   00:48   0:00 /usr/sbin/httpd -DFOREGROUND
apache     44784  0.0  2.2 1353476 18956 ?       Sl   00:48   0:00 /usr/sbin/httpd -DFOREGROUND
apache     44785  0.0  2.0 1353476 16760 ?       Sl   00:48   0:00 /usr/sbin/httpd -DFOREGROUND
apache     45019  0.0  1.7 1353476 14708 ?       Sl   00:48   0:00 /usr/sbin/httpd -DFOREGROUND
root       45141  0.0  0.1 221928  1140 pts/0    S+   00:48   0:00 grep --color=auto httpd
[root@git ~]# ls -ld /var/ /var/www/ /var/www/git/ ; ls -lZ /var/www/git/gitweb.cgi
drwxr-xr-x. 21 root   root   4096 Aug  2 18:16 /var/
drwxr-xr-x.  5 apache apache   44 Aug  2 18:23 /var/www/
drwxr-xr-x.  8 apache apache  179 Aug  4 00:18 /var/www/git/
-rwxr-xr-x. 1 apache apache system_u:object_r:git_script_exec_t:s0 253816 Jul 20  2020 /var/www/git/gitweb.cgi
[root@git ~]#

/etc/gitweb.conf
$projectroot = '/var/www/git/';
$git_temp = "/tmp";
$stylesheet = "static/gitweb.css";
$logo = "static/git-logo.png";
$favicon = "static/git-favicon.png";

/etc/httpd/conf.d/gitweb-le-ssl.conf
<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName git.mydomain.abc
    DocumentRoot /var/www/git
    <Directory /var/www/git>
        SetEnv  GITWEB_CONFIG  /etc/gitweb.conf
        Options +ExecCGI +FollowSymLinks +SymLinksIfOwnerMatch
        AllowOverride All
        order allow,deny
        Allow from all
        AddHandler cgi-script .cgi
        DirectoryIndex gitweb.cgi
    </Directory>
    <Files gitweb.cgi>
        SetHandler cgi-script
    </Files>
SSLCertificateFile /etc/letsencrypt/live/git.mydomain.abc/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/git.mydomain.abc/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

If anybody sees what I've done wrong I'll very much appreciate some guidance.. Thanks!
EDIT1:
And here is the audit.log
type=SYSCALL msg=audit(1628072069.412:134): arch=c000003e syscall=9 success=no exit=-13 a0=0 a1=b9 a2=1 a3=2 items=0 ppid=2911 pid=2917 auid=4294967295 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=4294967295 comm="git" exe="/usr/bin/git" subj=system_u:system_r:git_script_t:s0 key=(null)ARCH=x86_64 SYSCALL=mmap AUID="unset" UID="apache" GID="apache" EUID="apache" SUID="apache" FSUID="apache" EGID="apache" SGID="apache" FSGID="apache"
type=PROCTITLE msg=audit(1628072069.412:134): proctitle=2F7573722F62696E2F676974002D2D6769742D6469723D2F7661722F7777772F6769742F2F796F75747562652D646C2D62617463682E67697400666F722D656163682D726566002D2D666F726D61743D2528636F6D6D697474657229002D2D736F72743D2D636F6D6D697474657264617465002D2D636F756E743D3100726566
type=AVC msg=audit(1628072069.433:135): avc:  denied  { map } for  pid=2919 comm="git" path="/var/www/git/myrepo01.git/objects/1c/1c5ca1a07da5187a696cd1661d6b2a734ad98c" dev="vda1" ino=36639 scontext=system_u:system_r:git_script_t:s0 tcontext=unconfined_u:object_r:git_content_t:s0 tclass=file permissive=0

EDIT2
The issue boils down to SELinux which I am not an expert in. Changing the mode to Permissive I can now see all my repos..
However I have to figure out how to make it work with Enforced mode..
Comment: Check the audit log.
Comment: Hi Michael, I did check the audit log and it again points to a "denied" message.. from what I can see the persmissions are there but when trying to access my git repos it fails, I added it to the main post.
Comment: It seems to be SELinux preventing it but am still trying to figure out what options exactly I have to amend to allow the cgi script to be executed..
Answer: OK, so something I didn't know about were the audit2why and audit2allow commands..
After narrowing down the issues as per EDIT2 to SELinux, and passing the log over to audit2why it updated me that:
The boolean domain_can_mmap_files was set incorrectly.

and I have to:
Allow access by executing:
# setsebool -P domain_can_mmap_files 1

Ref: https://forums.centos.org/viewtopic.php?t=71917
This has now been resolved.
Thanks


An element of order $\phi(n)$ in $\mathbb{Z}/n\mathbb{Z}$ generates the multiplicative group

Question:
Suppose $x$ is an element of order $\phi(n)$ in $\mathbb{Z}/n\mathbb{Z}$. Then every invertible element of $\mathbb{Z}/n\mathbb{Z}$ is a power of $x$.

The lecture taught me that when this is the case, x is called a primitive element, and that I understood. But, how do I prove this theorem?
I know every invertible element has at least $a^{\phi(n)} = 1$, and that order(a) | $\phi(n)$
...but I wouldn't know how to put things together into a valid proof.
Comment: Welcome to MSE.. You are not supposed to write $\mathbb{Z}$/n$\mathbb{Z}$ but as $(\mathbb{Z}$/n$\mathbb{Z})^*$ by which you mean not all elements of $\mathbb{Z}$/n$\mathbb{Z}$ bu only invertible elements of $\mathbb{Z}$/n$\mathbb{Z}$.. Do you know what is definition of $\phi(n)$
Answer: Define $\phi(n)$ as
$$\phi(n)=\operatorname{Card}\{k,\;1\le k\le n\;| \gcd(k,n)=1\}$$
then it isn't hard to see that $\overline k$ is invertible in $\Bbb Z_n$ if and only if $\gcd(k,n)=1$ so $\phi(n)$ is the cardinal of the group of the invertible elements of $\Bbb Z_n$ and if there's $\overline x$ of order $\phi(n)$ then this group is cyclic generated by $\overline x$ and so every invertible element is a power of $\overline x$.
Answer: The number of invertible elements in $\mathbb{Z}/n\mathbb{Z}$ is $\phi(n)$.  So if you find an element, $x$ of order $\phi(n)$, this means that there are $\phi(n)$ distinct powers of $x$. This means these powers of $x$ must exhaust all the invertible elements of $\mathbb{Z}/n\mathbb{Z}$


Deserializar JSON

Question: Consigo fazer o POST desta informação:
{
    "Nritem": 1,
    "Cdprevenda": 3,
    "Cdproduto": 7,
    "Decomplitem": "",
    "Descricao": "Depilação",
    "Dtcadastro": "2015-11-27T13:53:35.120Z",
    "Flsituacao": 1,
    "Md5": "",
    "Qtproduto": 18,
    "Totalizador": "01T1700",
    "Unidade": "UN",
    "Vltabela": 50,
    "Vlunitario": 50,
}

Mas se colocar entre [] aparece esta mensagem:
"itemprevenda":[
  "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'PreVendaWebAPI.Models.Itemprevenda' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath '', line 1, position 1."]

API que faz o POST:
// POST: api/Itemprevendas
    [ResponseType(typeof(Itemprevenda))]
    public async Task<IHttpActionResult> PostItemprevenda(Itemprevenda itemprevenda)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        //  Implementar o Cditemprevenda e o Nritem automaticamente
        decimal cd = await GetMaiorCod();
        decimal nr = await GetMaiorNr(itemprevenda.Cdprevenda);

        itemprevenda.Cditemprevenda = cd;
        itemprevenda.Nritem = nr;
        //  *******************************************************

        db.Itemprevenda.Add(itemprevenda);

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (ItemprevendaExists(itemprevenda.Cditemprevenda))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtRoute("DefaultApi", new { id = itemprevenda.Cditemprevenda }, itemprevenda);
    }

Itemprevenda:
public partial class Itemprevenda
{
    public decimal Cditemprevenda { get; set; }
    public decimal Cdprevenda { get; set; }
    public decimal Cdproduto { get; set; }
    public decimal Nritem { get; set; }
    public decimal Qtproduto { get; set; }
    public decimal Vltabela { get; set; }
    public decimal Vldesconto { get; set; }
    public decimal Vlacrescimo { get; set; }
    public decimal Vlunitario { get; set; }
    public int Flsituacao { get; set; }
    public System.DateTime Dtcadastro { get; set; }
    public string Descricao { get; set; }
    public string Unidade { get; set; }
    public string Totalizador { get; set; }
    public byte[] Md5 { get; set; }
    public string Decomplitem { get; set; }
    public decimal Cdvendedor { get; set; }
    public decimal Vltotal { get; set; }
}

Como faço para deserializar este JSON?
Answer: Utilize o JavaScriptSerializer presente no namespace
System.Web.Script.Serialization;

O mesmo possui um método chamado Deserialize onde voce passa o objeto JSON e o tipo no qual o JSON será convertido.
Ex:
JavaScriptSerializer serializer = new JavaScriptSerializer();
meuTipo minhaVariavel = serializer.Deserialize(stringJson, meuTipo);

Comment: meuTipo seria o tipo que estou passando para deserializar: Itemprevenda? E stringJson é o formato que vai ser deserializado?
Comment: Exato, o meuTipo seria o Itemprevenda.

stringJson é a string que contem o json que voce quer deserializar.
Comment: Mas não tem uma _string_ com o JSON. O que eu tenho é Itemprevenda: `PostItemprevenda(Itemprevenda itemprevenda)`
Comment: Então voce quer serializar os dados? O que exatamente voce precisa?
Comment: Estou passando dados em JSON para a API e preciso descerializar para fazer o POST de objeto por objeto.
Comment: Mas o seu objeto já não está "deserializado" ? Me explica melhor o fluxo da sua lógica (passo a passo) e o objetivo final de todo o processo, por favor...
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/33593/discussion-between-andre-santarosa-and-leopiazzoli).
Answer: Bom, eu faria uma estrutura assim:
O JSON:
string seujson=
@"{""data"":[{""Cditemprevenda"":""1"",""Cdproduto"":""8""},{""Cditemprevenda"":""2"",""Cdproduto"":""9""}, {""Cditemprevenda"":""3"",""Cdproduto"":""10""}]}";

As classes:
public class Itemprevenda
{

     public List<Item> Items {get;set;}
}

public class Item
{
    public string Cditemprevenda {get;set;}
    public string Cdproduto {get;set;}
}
Itemprevenda item = new JavaScriptSerializer().Deserialize<Itemprevenda>(seujson);

Para recuperar:
foreach(var json in item.Items)
{
   Console.WriteLine("CdItem: {0}, CdProduto: {1}",json.Cditemprevenda ,json.Cdproduto );
}

Comment: Só que o JSON vai vir através da URL do navegador, eu não vou defini-la no escopo do código com `string seujson=
@...`. Como faço pra passar esta informação para a classe, dentro do **seujson**.
Answer: EDIÇÃO
Não tinha me atendado ao fato da deserialização ser implícita. para receber mais de um objeto do tipo Itemprevenda você deverá modificar a assinatura do seu método de public async Task<IHttpActionResult> PostItemprevenda(Itemprevenda itemprevenda) para public async Task<IHttpActionResult> PostItemprevenda(Itemprevenda[] itemprevenda). Note que foi adicionado [] após o tipo Itemprevenda.
Fazendo esta modificação o seu JSON deverá ser enviado da seguinte forma para a sua API:
"[{
        "Nritem": 1,
        "Cdprevenda": 3,
        "Cdproduto": 7,
        "Decomplitem": "",
        "Descricao": "Depilação",
        "Dtcadastro": "2015-11-27T13:53:35.120Z",
        "Flsituacao": 1,
        "Md5": "",
        "Qtproduto": 18,
        "Totalizador": "01T1700",
        "Unidade": "UN",
        "Vltabela": 50,
        "Vlunitario": 50,
    }, {
        "Nritem": 2,
        "Cdprevenda": 4,
        "Cdproduto": 8,
        "Decomplitem": "",
        "Descricao": "Depilação 2",
        "Dtcadastro": "2015-11-27T13:53:35.120Z",
        "Flsituacao": 1,
        "Md5": "",
        "Qtproduto": 18,
        "Totalizador": "01T1700",
        "Unidade": "UN",
        "Vltabela": 50,
        "Vlunitario": 50,
    }]";

O seu JSON deve ser enviado sem um label para o array, pois caso contrário o ocorrerá um erro na deserialização do JSON.
Antigo:
A questão é que você utilizando sem o [] ele considera somente um item e colocando o [] ele considera um vetor, array de itens.
Para fazer isso o seu modelo deveria conter um array itemprevenda com os mesmos atributos que o seu JSON.
Tente deixar a sua classe modelo semelhante à isso:
///Essa classe será a classe que conterá a sua lista de itens
///de pré venda.
public class Modelo {
    public Itemprevenda[] itemprevenda { get; set; }
}

public partial class Itemprevenda
{
    public decimal Cditemprevenda { get; set; }
    public decimal Cdprevenda { get; set; }
    public decimal Cdproduto { get; set; }
    public decimal Nritem { get; set; }
    public decimal Qtproduto { get; set; }
    public decimal Vltabela { get; set; }
    public decimal Vldesconto { get; set; }
    public decimal Vlacrescimo { get; set; }
    public decimal Vlunitario { get; set; }
    public int Flsituacao { get; set; }
    public System.DateTime Dtcadastro { get; set; }
    public string Descricao { get; set; }
    public string Unidade { get; set; }
    public string Totalizador { get; set; }
    public byte[] Md5 { get; set; }
    public string Decomplitem { get; set; }
    public decimal Cdvendedor { get; set; }
    public decimal Vltotal { get; set; }
}

string seujson = "{
    "itemprevenda": [{
        "Nritem": 1,
        "Cdprevenda": 3,
        "Cdproduto": 7,
        "Decomplitem": "",
        "Descricao": "Depilação",
        "Dtcadastro": "2015-11-27T13:53:35.120Z",
        "Flsituacao": 1,
        "Md5": "",
        "Qtproduto": 18,
        "Totalizador": "01T1700",
        "Unidade": "UN",
        "Vltabela": 50,
        "Vlunitario": 50,
    }]
}";

/*
  Realiza a deserialização do JSON para um objeto do tipo "Modelo"
  que contém o array de Itemprevenda. Modelo com 'M' maiúsculo é a
  classe e com 'm' minúsculo é a variável.
*/
Modelo modelo = new JavaScriptSerializer().Deserialize<Modelo>(seujson);

Como você deseja receber uma série, array, de objetos Itemprevenda você deve ter uma classe, nesse exemplo a classe Modelo, para conter esse array.
Isso deverá solucionar o seu problema.
Comment: @leopiazzoli modifiquei a resposta para tentar esclarecer
Comment: Pode explicar o que está sendo feito nesta implementação? O que seria **Modelo** e **modelo**? E o que tenho que passar em **seujson**?
Comment: Tem que passar uma _string_ para **seujson** certo? Mas as informações que são passadas para a API são do tipo Itemprevenda. `PostItemprevenda(Itemprevenda itemprevenda)`.
Comment: Não tinha me antedado para isso. Já modifiquei a resposta.
Answer: Forma correta:
public async Task<IHttpActionResult> PostItemprevenda(Itemprevenda itemprevenda){}

Quando o Json está entre [ ] a API entende que é uma lista de objetos, então tem que dizer que Itemprevenda é List desta forma List<Itemprevenda>.
E agora só fazer um foreach e percorrer a lista.

Deserializar JSON


Related to matrix

Question: Find the values of $a$ and $b$ for which the equations are consistent
$$\begin{cases}
X+aY+Z=3 \\
X+2Y+2Z =b \\
X+5Y+3Z=9 \\
\end{cases}$$
I tried solving it although my phone is not uploading the snap of attempt I made.  But I get to a point where I have to apply
$R_3-(R_2+\lambda)$
Is this valid?
Comment: Is the answer , $a\neq(-1) $ and $b\neq3$
Comment: There are three Sol.. given . First yours is correct . Second is a=-1 and b is not equal to 6. The third is a=-1 and b=6
Answer: Consider equations$$(1)\qquad x+ay+z=3\\(2)\qquad x+2y+2z=b\\(3)\qquad x+5y+3z=9$$$(2)$ and $(3)$ are obviously linearly independent. Here we have two different cases:
Case 1: $(1)$ is independent from $(2)$ and $(3)$
At this case the determinant of $\begin{pmatrix} 1 & a &1 \\ 1 & 2 &2 \\1 & 5 &3 \\\end{pmatrix}$ is nonzero and the equations are consistent with unique solution for any $b$. The determinant is $-a-1$ so for $a\ne -1$ and $b$ free Case 1 would be achieved.
Case 2: $(1)$ is dependent to $(2)$ and $(3)$.
This happens when $a=-1$ therefore we have $$(1)=2*(2)-(3)$$ and it is consistent iff $$3=2b-9$$ or $b=6$.
In other words for $a\ne -1$, $b$ is free and for $a=-1$, $b=6$
Alternative way (using elementary row transformations):
Consider the matrix $\begin{pmatrix} 1 & a &1&3 \\ 1 & 2 &2&b \\1 & 5 &3&9 \\\end{pmatrix}$ and the following steps:$$\begin{pmatrix} 1 & a &1&3 \\ 1 & 2 &2&b \\1 & 5 &3&9 \\\end{pmatrix}$$$R_2-R_1\to R_2\\R_3-R_1\to R_3$$$\begin{pmatrix} 1 & a &1&3 \\ 0 & 2-a &1&b-3 \\0 & 5-a &2&6 \\\end{pmatrix}$$$R_1-R_2\to R_1\\R_3-2R_2\to R_3$ $$\begin{pmatrix} 1 & 2a-2 &0&6-b \\ 0 & 2-a &1&b-3 \\0 & 1+a &0&12-2b \\\end{pmatrix}$$Look at $R_3$. If $a+1\ne 0$ then there exists an answer and if $a+1=0$ there should forcibly be that $12-2b=0$ or $b=6$
Comment: Stack exchange is super cool now I get it
Comment: Can you tell this using elementary row transformation cause I used it to solve this.
Comment: Sure! Just hold on a couple!

Related to matrix


How to use a BASH variable as a variable on a Javascript file function

Question: I have test.js file and a test.command file.
test.js:
  module.exports.init = function (a) {
      console.log(a);
  };

test.command
    FOO="$(node -e 'require("/test.js").init("Hello")')"

    echo ${FOO}

If I manually type "Hello", the programs works as it should and echo ${FOO} prints "hello".
However, if I do this
    BAR="hello"

    FOO="$(node -e 'require("/test.js").init("${BAR}")')"

    echo ${FOO}

it prints "${BAR}"
How do I let the shell script know that part is a variable, and should be read as such? If I remove the quotes from the ("${BAR}") part it gives me this error
    [eval]:1
    require("/test.js").init(${BAR})
                             ^

    SyntaxError: missing ) after argument list

Answer: Bash treats ' and " differently
no variable substitution is performed inside '
So, do this instead (since javascript treats ' and " identically)
BAR="hello"
FOO="$(node -e "require('./test.js').init('${BAR}')")"
echo ${FOO}

Comment: Thanks! I'm new to bash scripting so coming from javascript I thought " and ' would be treated the same.


jQuery Mobile images auto-resizing

Question: I'm new to this community: I'm trying to use jQuery Mobile to create a simple GUI in Windows Phone style.
I want to create some tiles with images and then I must adjust them to the screen width: I tried to do this with the style rule " style="width: 100%;" " but the border of the image is too heavy.
Here is my code:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Tiles Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, height=device-height">

    <link rel="stylesheet" href="Framework\Theme\Metro.css" />
    <link rel="stylesheet" href="Framework\JQM\S-1.3.0.css" />

                Menu

But the result is: http://img801.imageshack.us/img801/9474/6aoq.png
How can I fit the image to the screen size? (Something like this; http://img19.imageshack.us/img19/1305/f1y4.png)
Answer: I would try using css instead of jquery. You can accomplish what you're looking for with that. For example, you are using two images. You could set each one to a width of about 45% of the screen and add a border all in css. You can even have it dynamically scale based on screen size. It would probably be best to use div containers to organize it but this example should be enough to get you started.
I would try something like this:

Comment: Oh thank you for the answer, I have solved with this code

jQuery Mobile images auto-resizing


How to create a bijection from the union of the set natural numbers and square root 2 to the set of natural numbers?

Question: Since $\Bbb N$ and ${\sqrt2}$ are each countable sets, I see that the union is also countable. From this and the fact that $\Bbb N$ union ${\sqrt2}$ is infinite we know there exists a bijection to $\Bbb N$
I understand why such a bijection exists, but i'm not sure how to create the actual bijection itself?
If we let an element in the union be the smallest element we can show that it is impossible for two elements to be the smallest element in that set so that it would be one to one. and then because it is infinite, it is also onto. Is this correct?
Comment: The two sets are indeed countably infinite. But I think you are being asked to give an *explicit* bijection.  Suppose we decide to let $f(\sqrt{2})=1$. Then we could let $f(1)=2$, $f(2)=3$, and so on.
Answer: Define
$$f:\Bbb N\cup\{\sqrt{2}\}\to\Bbb N$$
by $f(\sqrt{2})=1$ and $f(n)=n+1$ for all $n\in\Bbb N$.
Its inverse is the map
$$g:\Bbb N\to\Bbb N\cup\{\sqrt{2}\}$$
defined by $g(n)=n-1$ for $n\geq 2$ and $g(1)=\sqrt{2}$.
Comment: Define $f:\Bbb N\to\Bbb N-\{2\}$ by $f(1)=1$, $f(2)=3$, $f(3)=4$, $f(4)=5$, and so on.
Comment: Define $f:\Bbb N\to\Bbb N-\Bbb N_{odd}$ by $f(n)=2n$.
Comment: Okay, then if I had something similar but the union was between the set of natural numbers and the set containing $\sqrt2$ and$\pi$ would I let $f(\sqrt2)=1$ and $f(\pi)=2$ and $f(n)=n+2$ ?
Comment: @user319635 Yes, that would work.
Comment: Awesome, thank you. If it were the other way around and I was to go from the set of natural numbers to the set of natural numbers excluding some values how would I go about this?
Comment: Is it different if instead of $N$ union $\sqrt2$ is is $N$ excluding $\sqrt2$?
Comment: @user319635 Since $\sqrt{2}\notin\Bbb N$ I am not sure to understand what you mean.
Comment: Oh exactly, I should have thought of a different example. Let me change that, If it was $N$ excluding some value in $N$, like 2?
Comment: Or even better, what if it was $N$ excluding all the odd numbers?


Median of an array? Best solution to keep track of median

Question: Numbers are randomly generated and stored into an expanding array. How do you keep track of the median?
Ideas:
Array
Binary Tree
Heap
Comment: I wonder you accepted an answer written for Javascript, but removed the [tag:javascrippt] tag!
Comment: https://www.reddit.com/r/ProgrammerHumor/comments/731n4x/java_vs_javascript/
Comment: Most efficient is using two heaps (min and max).
Answer: There's a wide variety of options for programming in general, but since we're working with JS the straightforward way is to simply keep an array and insert elements in sorted order, something like:

class Median {
  arr = []
  insert(i) {
    let l = 0,
      r = this.arr.length
    while (l < r) {
      const m = (l + r) >>> 1
      if (this.arr[m] < i) l = m + 1
      else r = m
    }
    this.arr.splice(l, 0, i)
  }
  get median() {
    const mid = (this.arr.length / 2) | 0
    return this.arr.length ?
      this.arr[mid] : (this.arr[mid - 1] + this.arr[mid]) / 2
  }
}

const m = new Median;
[2, 8, 8, -2, 19].forEach(m.insert.bind(m))
console.log(m.median)


Calculate the operator norm defined on L2

Question: For $f \in L^2([0, 1]) $ and $x \in [0, 1]$ we have the following
$$
A(f)(x) = \int_0^1 (x - y) f(y)dy
$$
In this particular exercise I have to calculate the operator norm $\| A \|$.
We know that from a theorem that if $A$ is compact and self-adjoint then either $\|A\|$ or $-\| A \|$ is an eigenvalue to the operator $A$.
My attempt:
We know that $A$ is indeed compact, but it is not self-adjoint. However, by some inspection, we have that $iA$ is self-adjoint (and compact). So we just have to calculate $\|iA\| = \|A\| = |\lambda|$ where $\lambda$ is an eigenvalue satisfying $A(f)(x) = \lambda f(x)$, for some eigenfunction $f$. Now setting $f(x) = a + bx$ we get by calculation that
$$\lambda(a + bx) = \int_0^1 (x - y) (a + by) dy = -\frac a 2 - \frac b 3 + (a + \frac b 2)x.$$
But from this I'm not sure how to solve for $\lambda$. Maybe there is an another way to solve this?
Comment: It should be $-\frac{a}{2}$.
Answer: First, deal with the simpler cases $a = 0$ or $b = 0$. Second, if $a, b \neq 0$, then you can factor out $\frac{1}{b}$ to instead apply the operator to $\frac{a}{b} + x = c + x$.
The more general case, if you would want to do it, is to identify the constant terms of both sides and the coefficient of $x$ on both sides, getting two equations involving $x, a$ and $b$. Then you want to maximize $|\lambda|$ by choosing $a$ and $b$ appropriately.
Answer: Your operator has finite range (its range is generated by $\{f_0(x)=1,f_1(x)=x\}$. For $f(x)=a+bx$ as eigenfunction, the values
$a=0$ or $b=0$ gives $a=b=0$. Thus $ab\neq0$. From your derivation we have
\begin{aligned}
\lambda a&=-\big(\frac{a}{2}+\frac{b}{3}\big)\\
\lambda b&=\big(a+\frac{b}{2}\Big)
\end{aligned}
Let $r=b/a$. Then,
\begin{aligned}
\lambda=-\Big(\frac12+\frac{r}{3}\Big)=\Big(\frac{1}{r}+\frac{1}{2}\Big)
\end{aligned}
This gives $r_1=\frac{1}{2}\big(-3+i\sqrt{3}\big)$ and $r_2=\frac{1}{2}\big(-3-i\sqrt{3}\big)$. Then you get
$\lambda=\pm i\frac{\sqrt{3}}{6}$. The norm of your operator is then $\sqrt{3}/6$.


Find the sign of $a,b,c$ in $ax^2+bx+c$ given the graph and a coordinate on it.

Question:

So my first approach was that, we see that there are $2$ roots. And one is negative and one is positive. $a$ would be evidently positive. The positive one's modulus is bigger than the negative one's. So the sum of roots would be $+ve$, that is $\frac{-b}a$. So if $a$ is positive and  sum of roots is positive, then $b$ has to be negative. And similarly, product of the roots will be $-ve$, that is $\frac ca$, so $c$ will be negative. Which gives the option $b)$ as correct.
But if we see, point $A$ will be the minimum point. And at the minimum point value of function is $\frac{-D}{4a}$. But generally the value is $\frac{-D^2}{4a}$ , because
[Edit] let $y=ax^2+bx+c$. Now let $a$ be positive. So minimum will be at $x=\frac{-b}{2a}$. Substitute. $y=a(\frac{b^2}{4a^2})-\frac{-b^2}{2a}+c$
$y=\frac{b^2-2b^2+4ac}{4a}=\frac{-(b^2-4ac)}{4a}=\frac{-D^2}{4a}$
 This means that $b^2=4ac$. Which is completely different and unsupportive of the graph. So where did I do it wrong.
Comment: As the question never menstion $D$ is the discriminant of quadratic equation, it is safer to assume it isn't. Also discriminant is $=b^2-4ac$.
Comment: Should we conclude that the $A$'s ordinate is misprinted and $-D$ should have been $-D^2$?
Comment: Can i ask why you want $-D$ to be $-D^2$?
Comment: See the edit....
Comment: Did I miss anything from the question that said $D= \cdots$? Why you need to let $D^2=b^2-4ac$? In my point of view $D$ is just a dummy in the question.
Comment: Why is it a capital $D$ only then? $D$ means discriminant in quadratics, which I assumed here. And if you are saying it was a dummy, what was the need of putting a minus in front of it and what was the need of ordinate of $A$?
Answer: a is positive and c is negative are pretty much clear by looking at the shape and y-intercept of the graph. b is negative since the x coordinate of the turning point is positive. As a is positive you need b to be a negative valune to change the sign.
Comment: But what is the use of the coordinate $A$ then?
Comment: Point A is the turning point since $x=-b/2a$ at A. So if you know a is positive, point A will tell you b is negative.
Comment: I know that. See my comment under question.
Comment: http://www.wolframalpha.com/input/?i=a%28%28b%5E2%29%2F%284a%5E2%29%29-%28b%5E2%29%2F%282a%29%2Bc%3D-sqrt%28b%5E2-4ac%29%2F%284a%29
Comment: Oh yes! D is the expression under the radical not the expression with radical!
Answer: Assuming that you understand some Calculus!
Let $f(x) = ax^2 + bx + c$ (a second degree polynomial in the single variable $x$) where $a,\ b,\ c$ and $x$ denote real numbers where $a \neq 0$.
Using the Calculus: We can see where some of the given information is coming from and then using it to determine the answer to the questions
$f^\prime(x) = 2ax + b = 0$ exactly when $x = -\frac{b}{2a}$ which is the $x$-coordinate of the point where the graph of $f(x)$ as a single turning point given as $A$. The corresponding $y$-coordinate of $A$ is $f(-\frac{b}{2a}) = \frac{4ab-b^2}{4a} = - \frac{b^2-4ac}{4a}$.  Hence the coordinates of the turning point (known as the vertex) is then $(-\frac{b}{2a},\ -\frac{b^2-4ac}{4a})$.  Hence, we can see that in the given problem $D\equiv b^2-4ac$ (known as the Discriminant and is commonly used to determine whether or not $f(x)$ has real roots---$D\geq 0$ tell us "Yes, real roots exists" and $D < 0$ tell us "No real roots exist".)
Recall the quadratic formula (the roots of $f(x)$) $$x\equiv -\frac{b}{2a}\ \pm\ \frac{\sqrt{D}}{2a} = -\frac{b}{2a}\pm \frac{\sqrt{b^2-4ac}}{2a}$$ Consider the sum and product of the roots!
Next, using the second derivative $f^{\prime\prime}(x)$ tell us the concavity (upwards or downwards) of the graph of $f(x)$.
$$f^{\prime\prime}(x) = (2ax + b)^{\prime} = 2a$$Now if $f^{\prime\prime}(x) > 0$ then the graph of $f(x)$ is concaved upwards and if $f^{\prime\prime}(x) < 0$, the graph of $f(x)$ is concaved downwards.
Now the $y$-intercept (given as $P$) is the point where the graph of $f(x)$ intersects the $y$-axis and has the form $(0,\ f(0))$ (or $(0,\  c)$).
Let's determine the sign of the coefficents $a,\ b$ and $c$ of $f(x)$ from the given graph.

The given graph is concaved upwards, so $f^{\prime\prime}(x) = 2a > 0$ exactly when $a > 0$; that is, the coefficient $a$ is positive.

The turning point given as $A$ lies in the fourth quadrant of the coordinate system and, so the point $A$ has a positive $x$-coordinate and a negative $y$-coordinate; that is,
$$-\frac{b}{2a} > 0\ \ \ \hbox{and}\ \ -\frac{b^2-4ac}{4a} < 0$$From the first inequality together with the fact that $2a > 0$ we easily deduce that $-b > 0$ or equivalently that $b < 0$; that is, the coefficent $b$ is negative.

The $y$-intercept of the given graph lies directly below the origin $O$ and as such must have a negative $y$-coordinate. In this case, $f(0) = c < 0$ which means that the coefficient $c$ is negative.

In summary, this comes down to choice (B) in the question.


Não consigo capturar regex do fim da string com o método replace do Java

Question: Tentei esse código mas o $ não é entendido como final da string e sim como caractere a ser capturado mesmo, fiz algo errado ou é um bug?
String s = "gabriel";
System.out.println(s.replace("iel$", ""));

Answer: Segundo a documentação, o método replace não funciona com expressões regulares.
O que você quer é o método replaceAll. Esse sim trabalha com regex:
String s = "gabriel";
System.out.println(s.replaceAll("iel$", "")); // gabr

Se bem que nesse caso específico não precisa de regex:
String s = "gabriel";
System.out.println(s.replace("iel", ""));

Comment: MEU HERÓI VLWWW


Node.js array empty in import() file

Question: I am trying to build an array path where when I call Router.group, the first parameter is pushed onto the end of the this.groupPath array, and this works. However, when I dump the data of the array within an import() the array is empty. What is causing this?
export class Router {
  // The current path
  private static groupPath: string[] = []

  // A grouping of routes
  public static group(path: string, callback: Function) {
    this.groupPath.push(path)
    callback()
    this.groupPath.pop()
  }

  // Add a post route
  public static post(routePath: string, callback: string | ((client: Client, mongo: Mongo) => void | Response)) {
    let r = new route(path.join(...this.groupPath, routePath), 'post', callback)
    this.routes.push(r)
    return r
  }
}

I am then trying to call group like this, and my Router.groupPath outputs the correct array:
import { Router } from '../util';

Router.group('/api', () => {
  console.log('before', Router['groupPath']) // outputs: ['/api']
  import('./api')
  console.log('after', Router['groupPath']) // outputs: ['/api']
})

However, within the file ./api, I have this where they array is now empty:
import { Router } from '../util'

console.log('in', Router['groupPath']) // outputs: []
Router.post('/install', 'install@install')
Router.post('/install/testMongoConnection', 'install@testConnection')

Why is this static property empty?
Edit:
I noticed that the outputs are out of order:
before [ '/api' ]
after [ '/api' ]
in []

Which to me indicates that the import isn't running synchronously. I was expecting this to be the output:
before [ '/api' ]
in ['/api']
after [ '/api' ]

Comment: The `Router` you import in `./api` is a different instance. Have you tried passing `Router` in?
Comment: It should be a cached instance of the Router....
Comment: Why are you using dynamic import in the first place? It isn't desirable in such cases exactly because of the way it works.
Comment: @estus What else would I use?
Comment: Regular imports for static imports like `./api`. `require` for dynamic imports, since TS type safety isn't reachable for the latter any way.
Answer: So, it looks like that import() returns a promise. To solve the issue, I need to do 2 things:

In the group callback prefix async to the function

await the import to look like await import('./api')

In Router.group make it async as well

await the callback() to look like await callback()

So now the callback looks like this:
Router.group('/api', async () => {
  await import('./api')
})

The group method now looks like this:
public static async group(path: string, callback: Function) {
  this.groupPath.push(path)
  await callback()
  this.groupPath.pop()
}

Node.js array empty in import() file


What changed in the way to implement a block?

Question: The documentation for Drupal 8 lists the following hooks as the ones necessary to implement a block.

hook_block_access() controls which users have access to a block
hook_block_view_alter() is used to alter how a block implemented by other modules is rendered
hook_block_view_BASE_BLOCK_ID_alter() is a specialization of the previous hook, similarly to what hook_form_FORM_ID_alter() is for hook_form_alter()

What I don't find is hook_block_info(), which in Drupal 7 allowed to expose the blocks defined from modules, and hook_block_view(), which was invoked when a block defined from a module was rendered in a page.
How do modules expose blocks, in Drupal 8? How are the blocks rendered?
Comment: This question is part of a series of questions whose purpose is highlighting the differences between Drupal 7 and Drupal 8.
Answer: Using the "Powered by Drupal" block as an example:
Drupal 7
modules/system/system.module
/**
 * Implements hook_block_info().
 */
function system_block_info() {
  $blocks['powered-by'] = array(
    'info' => t('Powered by Drupal'),
    'weight' => '10',
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function system_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'powered-by':
      $block['subject'] = NULL;
      $block['content'] = theme('system_powered_by');
      return $block;
  }
}

Drupal 8
core/modules/system/src/Plugin/Block/SystemPoweredByBlock.php
<?php

/**
 * @file
 * Contains \Drupal\system\Plugin\Block\SystemPoweredByBlock.
 */

namespace Drupal\system\Plugin\Block;

use Drupal\block\BlockBase;
use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;

/**
 * Provides a 'Powered by Drupal' block.
 *
 * @Plugin(
 *   id = "system_powered_by_block",
 *   admin_label = @Translation("Powered by Drupal"),
 *   module = "system"
 * )
 */
class SystemPoweredByBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#children' => theme('system_powered_by'),
    );
  }
}

The hook_block_info() is replaced by an annotation, containing all of the necessary metadata within the @Plugin portion of the docblock. hook_block_view() is replaced by the BlockPluginInterface::build() method.
The directory structure is the key here. All blocks must be placed into a specific directory within their module folder (src/Plugin/Block).


json.decode to List> issue in flutter

Question: snap shot from the code
Hello
I am trying to get Data from API
And put it inside List<Map<String,dynamic>>
I use a several ways but they doesn't work
In the image the data saved in the variable but when i use foreach it ignore the index 0
I try to print index 0 and it is ignore it and ignore print (extracted data [0]) and i can't print the length of that list it ignore the print
Their is no errors
Snapshot of the console
I am using flutter 2.8.0
And dart 2.15.0
Answer: This is your UI code
class ApiExample extends StatefulWidget {
  const ApiExample({Key? key}) : super(key: key);

  @override
  _ApiExampleState createState() => _ApiExampleState();
}

class _ApiExampleState extends State<ApiExample> {
  final items = initAndSet();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<StackHelp>>(
        future: items,
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Center(child: Text(snapshot.data.toString()));
          }
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) => ListTile(
                leading: CircleAvatar(
                  backgroundImage: NetworkImage(snapshot.data![index].logo!),
                ),
                title: Text(snapshot.data![index].name!),
              ),
            );
          }
          return Center(
            child: Text("Waiting..."),
          );
        },
      ),
    );
  }
}

This is your API code
import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:stackoverflow/model/stackHelp.dart';

Future<List<StackHelp>> initAndSet() async {
  const url = "http://muhammeddevxd.pythonanywhere.com/api/ecommerce";
  final response = await http.get(Uri.parse(url));
  if (response.statusCode == 200) {
    final Iterable decodeJson = jsonDecode(response.body);
    return decodeJson.map((item) => StackHelp.fromJson(item)).toList();
  } else {
    throw SocketException("No Internet Connection");
  }
}

This is your model class
class StackHelp {
  int? id;
  String? name;
  String? logo;

  StackHelp({this.id, this.name, this.logo});

  StackHelp.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    logo = json['logo'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['logo'] = this.logo;
    return data;
  }
}

final result is this
Answer: Whenever flutter is acting strange, I recommend running the following commands (close the debug session first):
Command 1
flutter clean

Command 2
flutter pub get

If it's still acting strange, it means that the problem is in the code.
Now, your code runs perfectly on my computer, so I'm not sure what the problem is. Although we can try another aproach with it:
Future<void> initAndSet() async {
    var url = 'http://muhammeddevxd.pythonanywhere.com/api/ecommerce';
    final response = await http.get(Uri.parse(url));
    var extractedData =
        List<Map<String, dynamic>>.from(jsonDecode(response.body));
    extractedData.forEach((element) {
      print(element);
    });
  }

!! Don't forget to import 'dart:convert' and 'package:http/http.dart' as http.

json.decode to List> issue in flutter


Error: Missing binding "binding.node" after merge to main branch

Question: I tried to configure automated code coverage in CI/CD in one of my branches in GitLab, and the pipeline passed perfectly within the branch, but when the admin merged the changes into the main branch, the pipeline failed due to a missing binding.
I used gitlab-ci.yml to configure my jobs in. I didn't have any experience working with pipelines, so this was pretty much a trial and error task for me.
Finally I got the configuration that was working for me that didn't break anything and produced the coverage as required. However, since it was showing a no space error prior to a successful build, I had to force clear the cache to get the jobs to run properly. Within my branch, the pipeline passed without any errors and I double checked by re-running it several times. But once the admin merged the branch it suddenly started producing the following error:
ERROR in Module build failed: Error: Missing binding /builds/internal/employee_portal/node_modules/node-sass/vendor/linux-x64-64/binding.node
Node Sass could not find a binding for your current environment: Linux 64-bit with Node.js 10.x

Found bindings for the following environments:
  - Linux 64-bit with Node.js 11.x

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to download the binding for your current environment.
    at module.exports (/builds/internal/employee_portal/node_modules/node-sass/lib/binding.js:15:13)
    at Object.<anonymous> (/builds/internal/employee_portal/node_modules/node-sass/lib/index.js:14:35)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.sassLoader (/builds/internal/employee_portal/node_modules/sass-loader/lib/loader.js:46:72)
ERROR in ./src/styles.scss
Module build failed: ModuleBuildError: Module build failed: Error: Missing binding /builds/internal/employee_portal/node_modules/node-sass/vendor/linux-x64-64/binding.node
Node Sass could not find a binding for your current environment: Linux 64-bit with Node.js 10.x

Found bindings for the following environments:
  - Linux 64-bit with Node.js 11.x

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to download the binding for your current environment.
    at module.exports (/builds/internal/employee_portal/node_modules/node-sass/lib/binding.js:15:13)
    at Object.<anonymous> (/builds/internal/employee_portal/node_modules/node-sass/lib/index.js:14:35)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.sassLoader (/builds/internal/employee_portal/node_modules/sass-loader/lib/loader.js:46:72)
    at runLoaders (/builds/internal/employee_portal/node_modules/webpack/lib/NormalModule.js:244:20)
    at /builds/internal/employee_portal/node_modules/loader-runner/lib/LoaderRunner.js:364:11
    at /builds/internal/employee_portal/node_modules/loader-runner/lib/LoaderRunner.js:230:18
    at runSyncOrAsync (/builds/internal/employee_portal/node_modules/loader-runner/lib/LoaderRunner.js:143:3)
    at iterateNormalLoaders (/builds/internal/employee_portal/node_modules/loader-runner/lib/LoaderRunner.js:229:2)
    at Array.<anonymous> (/builds/internal/employee_portal/node_modules/loader-runner/lib/LoaderRunner.js:202:4)
    at Storage.finished (/builds/internal/employee_portal/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:43:16)
    at provider (/builds/internal/employee_portal/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:79:9)
    at /builds/internal/employee_portal/node_modules/graceful-fs/graceful-fs.js:90:16
    at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)
ERROR: Job failed: exit code 1

side note: The branch I was working on had been checked out from the main branch, no changes from other branches had been included into this one.
I wanted to know:

what part of my code caused this error (i suspect force clearing the cache, but just a hunch)
why this error did not appear in the pipeline of the branch I was working in?
why is the runner giving an error when it has bindings for an updated version of Node? Shouldn't it be backward compatible?

I've looked at this link, but I'm curious as to why this error never occurred before merge and even if it did, why is it giving me an error because I have an updated version installed.
Here is my gitlab-ci.yml file:
image: trion/ng-cli-karma

cache:
  paths:
  - node_modules/

build:
  stage: build
  script:
   - npm cache clear --force
   - npm i @angular/cli
   - npm install
   - npm run generate-docs
   - ./node_modules/.bin/ng build --prod --base-href . --output-path www/
  artifacts:
    paths:
      -  www/
      -  documentation/
  variables:
    DOCKER_DRIVER: overlay

test:
  stage: test
  script:
    - ./node_modules/.bin/ng test --code-coverage=true
  artifacts:
    paths:
      - coverage/
  coverage: '/(\d*.?\d+)%/'

pages:
  stage: deploy
  dependencies:
    - build
    - test
  script:
    - ls
    - mv documentation www/
    - mv coverage/ www/
    - mv www/ public
    - ls public/
  artifacts:
    paths:
      - public
    expire_in: 30 days

Comment: Why are you installing the ng-cli, it is part of the docker image already?
Answer: I had the same problem and npm rebuild node-sass command didn't work for me. The reason was the npm cache. If you clear the cache, issue would be resolved.
Steps followed:

Remove node modules rm -rf node_modules/
Remove cache npm cache clean --force
Verify cache removed npm cache verify
npm install


I Have 5GB Free RAM and 70-130 Apache Processes - Improvements?

Question: I want to tune my httpd.conf. I have constantly about 60-130 Apache processes (all 20+MB). However my server only needs like 3GB and I have 8GB overall.
My settings:
<code>Timeout 10
FileETag None
StartServers 15
<IfModule prefork.c>
MinSpareServers 20
MaxSpareServers 30
</IfModule>
ServerLimit 500
MaxClients 300
MaxRequestsPerChild 8000
KeepAlive On
KeepAliveTimeout 15
MaxKeepAliveRequests 1000
</code>
What can I increase to server my page faster? I want to go for speed! Well, I guess I could change MaxRequestsPerChild to 0 and KeepAliveTimeout to 50 but what else? Is it worthwile to up the MaxClients value?
Any tips?
Thanks,
Oliver
Comment: Without knowing what the current bottleneck is, it's impossible to say how to improve things.
Answer: The only boost you might get there is eliminating the time it takes to start up a new server - boost the StartServers directive [if you are sure there are always 60 running at any given time!]
Otherwise your performance bottleneck may be elsewhere:

test your applications to be sure it not them that are slow
test your database[s]
make sure you are not loading any unnecessary apache modules
use caching wherever possible
check your disk and processor

-sean
Answer: Right - tuning the webserver (Apache) is the place where you'll get some of the least performance gains.
You have extra resources available, so you're on the right track - you need to put them to use. It's time to use your memory much more aggressively to speed up your side - this is where you're going to get the most performance gains. Reduce CPU usage, increase memory usage (through caching), minimise disk access.
You don't mention what OS you're running on, or what programming language you're using. My area of expertise is Linux and PHP, so I'll go with some advice for that and if its wrong you might be able to adapt it for other stacks.
PHP - are you using something like APC or xCache? If not, get on it! Make sure you allocate enough memory in the config to contain your whole application.
Start building in caching into your application - make use of things like memcached (you can also probably use xcache/APC variable storage).
Do some analysis of the database usage. Increase the buffers and caches to keep more stuff in memory => less disk access.
Many people concentrate on minimising your memory usage, but what use is a server with 8gbs of RAM if you're only using 3. Obviously minimise any memory usage that is unncessary or not actually serving a purpose, but other than that, use your resources!
Comment: Thank you for the advice. I am already using APC but it's only using about 300MB and doesn't go over that even thou I assigned 1GB to APC. I am running CentOS and using a lot of PHP code (Wordpress) but I already have W3 Total Cache, ObjectCache, Database Cache, SQL Query Cache, CDN, etc. - problem is I am not so satisfied with First-Byte time and would like to cache even more requests. Maybe I should try that Varnish cache.


Solving linearised least squares using statsmodels

Question: I'm trying to translate a simple linearised least squares problem to statsmodels, in order to learn how to use it for iterative least squares:
The (contrived) data comprise measurements of the time it takes for a ball to drop a given distance.
distance    time
10          1.430
20          2.035
30          2.460
40          2.855

Using these measurements, I want to determine the acceleration due to gravity, using:
t = sqrt(2s/g)
This is (obviously) non-linear, but I can linearise it (F(x- + x) = l0 + v, where x- is a provisional value), then use a provisional value for g (10) to calculate F(g), and iterate if necessary:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

measurements = pd.DataFrame({
    'distance': [10, 20, 30, 40],
    'time': [1.430, 2.035, 2.460, 2.855]
})

prov_g = 10
measurements['fg'] = measurements['distance'].apply(
    lambda d: ((2 * d) ** 0.5) * (prov_g ** -0.5))
measurements['A_matrix'] = measurements['distance'].apply(
    lambda d: -np.sqrt(d / 2) * (prov_g ** -1.5))
measurements['b'] = measurements['time'] - measurements['fg']
ATA = np.dot(measurements['A_matrix'], measurements['A_matrix'].T)
ATb = np.dot(measurements['A_matrix'].T, measurements['b'])
x = np.dot(ATA ** -1, ATb)
updated_g = prov_g + x
updated_g

>>> 9.807

What I can't figure out from the examples is how I can use solve statsmodels to do what I've just done manually (linearising the problem, then solving using matrix multiplication)
Answer: statsmodels is not directly of any help here, at least not yet.
I think your linearized non-linear least square optimization is essentially what scipy.optimize.leastsq does internally. It has several more user friendly or extended wrappers, for example scipy.optimize.curve_fit or the lmfit package.
Statsmodels currently does not have a generic version of an equivalent iterative solver.
Statsmodels uses iteratively reweighted least squares as optimizer in several models like GLM and RLM. However, those are model specific implementations. In those cases statsmodels uses WLS (weighted least square) to calculate the equivalent of your solution for the linear model in calculating the next step.


After upgrade Rails 3 .0. to 7.0 I am getting retrieve_connection': No connection pool for 'ActiveRecord::Base' found

Question: Traceback (most recent call last):
    31: from script/rails:6:in `'
    30: from script/rails:6:in `require'
    29: from /var/lib/gems/2.7.0/gems/railties-7.0.3/lib/rails/commands.rb:18:in `<top (required)>'
    28: from /var/lib/gems/2.7.0/gems/railties-7.0.3/lib/rails/command.rb:48:in `invoke'
    27: from /var/lib/gems/2.7.0/gems/railties-7.0.3/lib/rails/command/base.rb:87:in `perform'
    26: from /var/lib/gems/2.7.0/gems/thor-1.2.1/lib/thor.rb:392:in `dispatch'
    25: from /var/lib/gems/2.7.0/gems/thor-1.2.1/lib/thor/invocation.rb:127:in `invoke_command'
    24: from /var/lib/gems/2.7.0/gems/thor-1.2.1/lib/thor/command.rb:27:in `run'
    23: from /var/lib/gems/2.7.0/gems/railties-7.0.3/lib/rails/commands/server/server_command.rb:134:in `perform'
    22: from /var/lib/gems/2.7.0/gems/railties-7.0.3/lib/rails/commands/server/server_command.rb:134:in `tap'
    21: from /var/lib/gems/2.7.0/gems/railties-7.0.3/lib/rails/commands/server/server_command.rb:137:in `block in perform'
    20: from /var/lib/gems/2.7.0/gems/railties-7.0.3/lib/rails/commands/server/server_command.rb:137:in `require'
    19: from /home/sharique/Desktop/CodeSlash/config/application.rb:21:in `<top (required)>'
    18: from /usr/lib/ruby/2.7.0/bundler.rb:174:in `require'
    17: from /usr/lib/ruby/2.7.0/bundler/runtime.rb:58:in `require'
    16: from /usr/lib/ruby/2.7.0/bundler/runtime.rb:58:in `each'
    15: from /usr/lib/ruby/2.7.0/bundler/runtime.rb:69:in `block in require'
    14: from /usr/lib/ruby/2.7.0/bundler/runtime.rb:69:in `each'
    13: from /usr/lib/ruby/2.7.0/bundler/runtime.rb:74:in `block (2 levels) in require'
    12: from /usr/lib/ruby/2.7.0/bundler/runtime.rb:74:in `require'
    11: from /var/lib/gems/2.7.0/gems/acts_as_audited-2.0.0/lib/acts_as_audited.rb:36:in `<top (required)>'
    10: from /var/lib/gems/2.7.0/gems/acts_as_audited-2.0.0/lib/acts_as_audited.rb:36:in `require'
     9: from /var/lib/gems/2.7.0/gems/acts_as_audited-2.0.0/lib/acts_as_audited/audit.rb:12:in `<top (required)>'
     8: from /var/lib/gems/2.7.0/gems/acts_as_audited-2.0.0/lib/acts_as_audited/audit.rb:25:in `<class:Audit>'
     7: from /var/lib/gems/2.7.0/gems/activerecord-7.0.3/lib/active_record/querying.rb:22:in `order'
     6: from /var/lib/gems/2.7.0/gems/activerecord-7.0.3/lib/active_record/relation/query_methods.rb:429:in `order'
     5: from /var/lib/gems/2.7.0/gems/activerecord-7.0.3/lib/active_record/relation/query_methods.rb:434:in `order!'
     4: from /var/lib/gems/2.7.0/gems/activerecord-7.0.3/lib/active_record/relation/query_methods.rb:1591:in `preprocess_order_args'
     3: from /var/lib/gems/2.7.0/gems/activerecord-7.0.3/lib/active_record/relation/delegation.rb:93:in `connection'
     2: from /var/lib/gems/2.7.0/gems/activerecord-7.0.3/lib/active_record/connection_handling.rb:280:in `connection'
     1: from /var/lib/gems/2.7.0/gems/activerecord-7.0.3/lib/active_record/connection_handling.rb:313:in `retrieve_connection'
/var/lib/gems/2.7.0/gems/activerecord-7.0.3/lib/active_record/connection_adapters/abstract/connection_handler.rb:208:in `retrieve_connection': No connection pool for 'ActiveRecord::Base' found. (ActiveRecord::ConnectionNotEstablished)

Answer: Rails 3 -> 7 is not going to be a smooth upgrade, there's a LOT of work involved.  I mean script/rails doesn't even exist anymore.
Honestly, 3 is so old there's no "right way" to upgrade from 3 to 7.  I think the easiest option is to create a blank Rails 3 project, and a blank Rails 7 project, and then use diff to look at the differences and apply those differences to your project.  Then you'll still need to upgrade most of the gems in the project.
Just to put you in the ballpark, I've done these sorts of upgrades professionally, and the time required is around the 40-80 hour mark.


Create an array/vector of objects

Question: I'm trying to create an array or vector of objects. Most other stuff that I've found online has been about dynamically creating this, but I know the size that I need. I say vector or arrays because I believe either one will work for my situation (I'm comparing start and stop points) but any input onto which one will work better would be gladly welcomed as I'm pretty new to C++. My code below is my header followed by my main where I attempt to declare an array of objects, then I get this error: Variable length array of non-POD element type "Window." posWsize is a const int declared
#ifndef __Compare_Data_C____comp_fns__
#define __Compare_Data_C____comp_fns__

#include <iostream>
using namespace std;

class Window {
    int start, stop, length;
    double average;
    string strandID;

public:
    void setValues(int a, int b, string strand, int length, double avg);
};
#endif

int main()
{
    int posWsize = getSize(fwdWindowInput, "+", windowHeader);
    Window posWindow[posWsize];

    return 0;
}

getSize gets the size of my array. Any help would be greatly appreciated! If I can't do it this specific way that's ok, I just want to know how to properly create this array (or vector if appropriate) of objects. Thanks
Comment: What's wrong with `std::vector posWindow(posWsize);`? See this [`std::vector` reference](http://en.cppreference.com/w/cpp/container/vector).
Answer: Use an std::vector:
std::vector<Window> posWindow(posWsize);

Answer: As a general rule in C++, unless you have a compelling reason not to, use a vector.

Create an array/vector of objects


Does hearing fatigue?

Question: Sometimes everything sounds terrible to my ears. Lacking of high end or ear piercing (or both a same time). After few days after stopping practicing everything goes back to normal. Does my hearing fatigue or it is something wrong with my ears?
Comment: Revealing what instrument in what circumstances will help provide more meaningful answers. World of difference practising clarinet in a sound absorbing room to practising on electric guitar, with other band members who haven't learned the benefits of playing quietly.
Comment: I focus on guitar. But when  I have this issue any music sounds wrong
Comment: Getting closer! Classical guitar or loud electric? It would be easy to assume the latter is the cause.
Comment: Both. And I also listen rock music more than classical
Comment: So, is it extreme volume that's causing the problem?
Comment: I'm not sure what is extreme volume. I tend to listen music louder than people that don't play any instrument. I don't use distortion from amp because it is too loud. I don't have tinnitus. It looks more like be related with amount of music I listen than loudness overall.
Comment: Distortion doesn't necessarily equal loudness. It used to, when the only way to achieve it was to turn up to 11.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/50521/discussion-between-teodozjan-and-tim).
Answer: Wow, this is a big subject - & one I'm not fully qualified to answer, but I'm going to try anyway...
Hearing fatigue is a very real phenomenon, though it takes many forms, of which I shall just skirt the main aspects...

You get bored.
Your brain, rather than your ears, stops hearing anything other than what you are concentrating on.
This is a "mix killer" & a sign you ought to quit for the day & come back tomorrow... it's also one of the hardest to self-identify
Actual 'volume fatigue'
This is a 'compression' of the mix that occurs if you have been listening too long at too high volume
...again, the 'fix' is to come back tomorrow.
You need to blow your nose.
The worst - once you do, your entire day's work is suddenly invalidated. Everything sounds wrong
Fix, again, is 'come back tomorrow'
'Check it in the car' syndrome
If you cannot make a portable mix; one that sounds good everywhere - car, iTunes, walkman [if anyone still has one], friend's stereo...
then you may need to re-evaluate your studio listening environment - test for resonance in your mix room. Also poor monitoring or headphones [Aaaarrrgh, you cannot mix on headphones] may be responsible for the discrepancy.

There are others, I hope someone else will fill my gaps...
Answer: In short: you can, yes. Just like with any kind of information, you might be experiencing some sort of fatigue. From what you describe, though, it may be that you have some sort of lesion, and the inflamation gets worse when you are exposed to certain sounds for an extended period of time. Solutions might be a) take breaks often, 2) go see a doctor, make sure they examine your tympanus, 3) low your decibels :-)

Does hearing fatigue?


Appropriate distribution for simulating a random walk between two known points, with known min/max values

Question: I have a 1-D random walker. It starts at a value of x at time t=0. It ends with a value of y at time t=1. Along the way, it hits a low of w, and a high of z. I know nothing about its path except the endpoints and the min/max values achieved.
Suppose I want to simulate the behavior of this random walker. So at any given time t between 0 and 1, I need to be able to sample from a realistic distribution with the described endpoint and extremes. What would be an appropriate distribution for this task?
Properties of distribution function f(t)

f(0)=x
f(1)=y
The central tendency should be weighted towards x at values close to t=0, and should lean more and more towards y as t approaches 1.
The variance should scale according to w and z, should be greatest at t=0.5, and should go to zero at t=0 and t=1.
The the tails of the probability distributions should go to zero at w and z, without abrupt discontinuity (i.e. it shouldn't be truncated).

Possible options?

A beta distribution visually looks like it has the right properties, but I'm not entirely sure how to interpret its parameters as a random walk scenario.
I understand that Rayleigh distributions describe random walks, but I'm not sure how one might incorporate the concept of knowing the bounds and final value of the walk.
Answer: A friend helpfully suggested that this is similar to a Brownian Bridge, and I was able to use that to derive an analytical solution.
Conditions: $w$ = min boundary, $x$ = starting value, $y$ = final value, $z$ = max boundary
1. Incorporating the x and y conditions using a Brownian Bridge
The generalized Brownian Bridge is a specific Wiener Process, defined as a time-dependent normal distribution:
$$B(t)=N(\mu_t,\sigma^2_t)$$
that is tethered at either end by the conditions:
$$B(t_1)=x,\;  B(t_2)=y$$
The mean and variance for this distribution are:
$$\mu_t=x+\frac{t-t_1}{t_2-t_1}(y-x)$$
$$\sigma^2_t=\frac{(t_2-t)(t-t_1)}{t_2-t_1}$$
When our time interval is $[0,1]$, these reduce to:
$$\mu_t=x(1-t) + yt$$
$$\sigma^2_t=t(1-t)$$
But then we have to condition our distribution on the observed min and max values, $w$ and $z$.
2. Min/Max Conditional
The total distribution of points observed across the entire $t\in[0,1]$, $B_T$ will also be normal (Brownian Bridges are proven to be normally distributed at all scales). We want to find the normal distribution that would be expected to have $w$ and $z$ as its min and max observed values.
It can be proven using the joint cumulative distribution functions (CDFs) that $B_T$ has a mean $\mu_T=\frac{1}2(w+z)$ halfway between the endpoints, and a standard deviation $\sigma_T=k(n)*(z-w)$ that depends on the sample size $n$.
For example, a well-known result derived from the normal CDFs is that 99.73% of the normal probability distribution lies within $3\sigma$ on either side of the mean. If we assume that $w$ and $z$ are the only two values observed outside this range, then $0.0027 = \frac{2}n$, giving $n=741$. Since this is the case where $2*3\sigma_T=z-w$, we can use this in our previous standard deviation equation to find $k(741)=\frac{1}6$.
Generalizing, where $p$ is the tail of the normal distribution containing a single extremum, and $z_p$ is the quantile:
$$2(1-p) = \frac{2}n$$
$$p=\frac{n-1}n$$
$$2*z_p\sigma_T=z-w$$
$$\sigma_T=\frac{z-w}{2z_p}$$
We can use the quantile function of the normal distribution to find $\sigma_T$ as a function of $n$:
$$z_p=\sqrt2\text{erf}^{-1}(2p-1)$$
$$z_p=\sqrt2\text{erf}^{-1}\left(\frac{n-2}n\right)$$
$$\sigma_T=\frac{z-w}{2\sqrt2\text{erf}^{-1}\left(\frac{n-2}n\right)}$$
Or, we can just use quantile tables that give us $z_p$ for values of $p\approx p(n)$.
3. Bringing it all together
Our solution will be a particular Wiener Process distribution that behaves like the Brownian Bridge, but also adds up over time to the total distribution described in Part 2:
$$W(t)\sim B(t)$$
$$B_T=\int_{0}^{1}W(t)dt$$
A helpful property is that the product of two independent normal distributions is another normal distribution. So, we can decompose our desired model into the joint probability of $B(t)$ and an independent, time-invariant normal distribution $N_C$:
$$W(t)\ = N_CB(t)$$
$$B_T=N_C\int_{0}^{1}B(t)dt$$
The time-integral of a Brownian or Wiener process is another specific normal distribution:
$$B_T=N_CN(0,\tfrac13)$$
In general, the product of two normal distributions is the normal distribution with mean and variance as:
$$\mu=\frac{\mu_1\sigma^2_2+\mu_2\sigma^2_1}{\sigma^2_1+\sigma^2_2}$$
$$\sigma^2=\frac{\sigma^2_1\sigma^2_2}{\sigma^2_1+\sigma^2_2}$$
So then $N_C$ is fully specified by:
$$\sigma^2_T=\frac{\sigma^2_C\tfrac13}{\sigma^2_C+\tfrac13}$$
$$\sigma^2_C=\frac{\sigma^2_T}{1-3\sigma^2_T}$$
and
$$\mu_T=\frac{\tfrac13\mu_C+0}{\sigma^2_C+\tfrac13}$$
$$\mu_C=\mu_T(3\sigma^2_C+1)$$
$$\mu_C=\frac{\mu_T}{1-3\sigma^2_T}$$
Finally, we can use the same property to fully specify our model $W(t)=N_CB(t)=N(\mu_W,\sigma_W^2)$ in terms of the values solved for in Parts 1 and 2:
$$\mu_W=\frac{\mu_C\sigma^2_t+\mu_t\sigma^2_C}{\sigma^2_C+\sigma^2_t}$$
$$\sigma_W^2=\frac{\sigma^2_C\sigma^2_t}{\sigma^2_C+\sigma^2_t}$$
Comment: Thanks for documenting your work on your own question here!
Answer: After a couple of days hammering away at this, I think I have a workable solution, reparameterizing a beta distribution. The key insight (from this answer) was to solve for the beta distribution parameters $\alpha$ and $\beta$ as functions of the mean $\mu$ and variance $\sigma^2$. Then, I just had to decide how $\mu$ and $\sigma^2$ should vary with $t$ on the interval $[0,1]$.
As a reminder:
$w$ = min boundary,
$x$ = starting value,
$y$ = final value,
$z$ = max boundary
So then from $t=0$ to $t=1$, $\mu$ can travel linearly from $x$ to $y$. The simplest form of this would be:
$$\mu = x (1 - t) + yt$$
Next is the variance and standard deviation. At $t=0$ and $t=1$, the function value is exactly known (equivalent to the starting or end point mean), so $\sigma=0$. The simplest version of this would be:
$$\sigma=C*t(1-t)$$
In the middle ($t=0.5$), where the time is furthest from the two endpoints, we have the least information about the location of the random walker, so then the distribution should be approximately normal, spread across the entire interval. Thus, the min and max should each be about 3 standard deviations from the mean at that time:
$$z-w=6*\sigma(t=0.5)$$
rearranges to:
$$\sigma(t=0.5)=(\frac{z-w}6)$$
Solve the previous equation for $C$ in this scenario:
$$\sigma(t=0.5)=C*0.5(1-0.5)$$
$$C=4*\sigma(t=0.5)$$
$$C=4(\frac{z-w}6)$$
Finally:
$$\sigma=4(\frac{z-w}6)*t(1-t)$$
But the beta distribution is only defined on the interval $[0,1]$, so we can just set $w$ and $z$ to $0$ and $1$ respectively, and rescale everything later:
$$\sigma=4(\frac{1}6)*t(1-t)$$
$$\sigma=\frac{2}3t(1-t)$$
Hence, keeping in mind that $x$ and $y$ are predefined (and should be between $w$ and $z$ on the $[0,1]$ interval, to be rescaled later), these 4 equations fully determine the $\alpha$ and $\beta$ parameters of the beta distribution based on $t$, with all of the desired behaviors and constraints of a 1-D random walk from $x$ to $y$:
$$\mu = x (1 - t) + yt$$
$$\sigma=\frac{2}3t(1-t)$$
$$\alpha=\left(\frac{1-\mu}{\sigma^2}-\frac{1}{\mu}\right)\mu^2$$
$$\beta=\alpha\left(\frac{1}{\mu}-1\right)$$
Plugging in some values of $x$, $y$, and $t$, the plots of these beta distributions give a very convincing simulation!
Comment: Actually, some edge cases (e.g. when x=y=0.2) don't look great, because when the mean is very close to one of the boundaries, too much probability density is squeezed into that small space. The random walker shouldn't actually be spending equal time on either side of x and y if x and y are skewed away from the center of the distribution.

I think I can fix this by reformulating the equations in terms of the mode and variance, instead of the mean and variance.


Block direct IP connections to Apache web server

Question: I need to figure out how to block direct IP access to my website.
Example: I want it so that when people type my IP address 184.108.40.206 into the browser it doesn't work, but when they type www.example.com it does work.
I am using Apache 2.4.9, and my website is run using WampServer.
I have tried other solutions from some old questions on here, but none of them have worked for me. I have tried pasting virtual host stuff into the vhosts.conf, but I couldn't get it right, and I tried doing rewrite stuff with the htaccess file, but that didn't work either.
Comment: The duplicate question is not quite the same, but the answer works for your situation as well.
Answer: Generally the first virtual host entry also acts as the default, so make your first virtual host entry point to a folder with an access denied page.
Comment: In addition to preventing use of the default virtual host for any other purpose (_if_ a user should have one), this approach also prevents serving localized error pages to the browser accessing by IP address
Answer: One way to do this is to set a rewrite condition within the global server context that disallows IP based requests by requiring an HTTP header similar to
the example shown below:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteCond %{REQUEST_URI} !^/error [NC]
RewriteRule ^.(.*) - [L,F]

NOTE: This example requires that you enable mod_rewrite.
NOTE ALSO: If you have multiple virtual hosts, you can modify the RewriteCond to check more broadly or use multiple RewriteCond statements to accommodate the different domains.
An alternative configuration is:
<If req('Host') != 'www.example.com'">
  <Location "/">
    Require all denied
  </Location>
</If>

Comment: This just gave me a error on all my web pages when visiting anything.
I think I have mod_rewrite enabled. I am very confused. I am a noob at apache.
Comment: It is hard to know why without digging through all of your configuration files, but added an alternative configuration that can work if inserted in the right place.


Find the absolute maximum and minimum values of $f(x,y)=(x-y)(1-x^2-y^2)$ for $x^2+y^2\le1$

Question: Find the absolute maximum and minimum values of
f
on the set D:
$f(x,y)=(x-y)(1-x^2-y^2)$
$D=\left\{(x,y) \mid x^2+y^2\le1\right \}$
Can someone help me resolving the system of partial derivatives???
Answer: $f_x(x, y) = 1 - x^2 - y^2 - 2x(x - y) = 1 - 3x^2 - y^2 + 2xy$
$f_y(x, y) = x^2 + y^2 - 1 - 2y(x - y) = x^2 + 3y^2 - 2xy - 1$
Set these both equal to 0, and then simplify and you will get:
$1 = 3x^2 + y^2 - 2xy$ and $x^2 + 3y^2 - 2xy = 1$, so we can set these equal to each other, since they are both equal to 1:
$3x^2 + y^2 - 2xy = x^2 + 3y^2 - 2xy$. Simplify and you get $2(x^2 - y^2) = 0$, which you can factor and get that $x = \pm y$.
Notice what happens to $f(x,y)$ when $x = y$. If $x = -y$, then $f(x, -x) = 2x (1 - 2x^2)$, and now you have a function of a single variable which you want to maximize or minimize.