What is considered a proper Cantus Firmus?

Question: I've recently begun on trying to compose a Cantus Firmus (it's an assignment given to me by my teacher).
I know some of the rules but there are some parts I guess I don't understand:
Could it be in any key signature? What about clefs? I've searched online but I've mostly seen the style written in Alto clef.

this is what I've done so far for the Alto version. After the climax is went down a 4ths instead of going down in step wise motion.
As for the treble clef version, I've done the same as well after the climax. Are there any rules I would be breaking?
Comment: A cantus firmus is, at root, just a melody, so clef is according to who should sing that part, and key signature is up to you -- unless your teacher specified otherwise in the assignment.
Comment: @Aaron is the way I noted this correct in a sense? Now that I understand that there is no limit in terms of clefs and key signatures.
Comment: They seem okay to me, but this is not my expertise.
Comment: Looks like you replaced the wrong c.f. There are two treble clefs (both without the q=150) but no alto.
Answer: It's hard to believe you would be given an assignment to write a cantus firmus but not have a text book or syllabus for procedures. The whole point of species counterpoint is to learn about rigorous compositional procedures. How can you do that without the procedures? If you did get that, ask for it.
Here is an example syllabus for a counterpoint class and it gives a list of rules for the cantus firmus.
You can also get similar stuff from other counterpoint books. Look for Fux's Gradus that's the classic text. Goetschius' Applied Counterpoint has a detailed intro for melody rules, although it isn't specifically labeled cantus firmus.
Some of the rules I've seen in various sources:

start and end on the tonic
use a modest range like an octave or tenth (it should be easily singable, that's the real goal of the cantus)
move by step, diatonically (except the penultimate note may be a raised leading tone like C# in D dorian ... and some others like a lowered subdominant in lydian, etc.)
keep leaps small, generally the max is a perfect fifth (an octave is acceptable too)
resolve leaps by step in opposite direction
melodic contour-wise place the climax, highest note around middle or slightly after middle of the melody

Some avoids:

avoid chromatic, augmented, diminished, or tritone melodic intervals
avoid repeating a note too many times, max of three
avoid repeating figures or melodic sequence
avoid outlining a triad (I think I have seen this somewhere, but can't quote it)

You cantus seems fine to me, but the opening outlines a triad, and mm. 7, 8 and 9, 10 are a melodic sequence.
Clef and key don't matter.
One final point: don't get too hung up on the "rules." The cantus firmi that Fux presents in the Gradus include example of consecutive leaps, leaps resolve with leaps, etc. Try to stick to the rules for the sake a rigorous study, but understand they aren't inviolable.
Answer: I see a couple of mistakes here, compared to the cantus firmi taught by Fux. Is your teacher using the Fux? Observations below:

2nd species counterpoint typically given the unit pulse so much counterpoint is written in cut time.
The range of your treble cantus firmus exceeds a perfect fifth.
Both of your examples have spots where there are two skips ("skip" defined as movement by a 3rd; "leaps" are for intervals a 4th or greater) in a row; double skips must immediately proceed by step in the opposite direction.

In two-part counterpoint the cantus firmus is traditionally the lower voice as its rhythm is static and therefore serves to ground the composition. In three-part counterpoint it's traditionally a low or middle voice, more commonly a middle voice as the middle is the easiest way to ground a composition without becoming obtrusive.
Keep in mind my comments are with respect to strict 17th century technique. Counterpoint practices evolved with each century.
That said, you should pick up "gradus ad parnassum" by Fux if you're serious at all about counterpoint.
Also, as an aside, many classical musicians would not take the 150 tempo mark seriously, as many tempo indications in the classical tradition revolve around analog metronome speeds.
Comment: This doesn't fully jibe with my understanding of Fux. Are they specific to the rules for the c.f.? For counterpoint voices, the rule about a skip being followed by a step in the other direction is specific to skips of a fourth or larger. Fux also makes a point of placing the c.f. both above and below the counterpoint in two-part exercises. And as I recall, counterpoint voices are not restricted to the range of a perfect fifth.
Comment: BTW, nice to see you posting again. I joined since you last posted, and until now, I'd only encountered your entries from "long ago" in MP&T terms. Good stuff, and I look forward to reading more.
Comment: I'll look into more of what you've just mentioned... As for the tempo of 150 I have accidentally placed that there. Forgot to mention not to pay attention to it. But I've edited it now.
Comment: Since your first bullet point has nothing to do with Fux (the metronome having come into common use roughly 90 years after Gradus ad Parnassum was published), the answer would probably be improved if that were mentioned somewhere else.  (Since that is a relatively minor point, I have upvoted.)
Comment: @phoog - valid point; was still groggy after waking up and was maybe a little salty too. Yep I'll change it.
Comment: @Aaron - yes, there are some rules specific to c.f. that counterpoint doesn't follow; the range of a 5th being one of them. You're correct about the 4th but you should double-check your usage of double skips. I haven't done any Fux-style counterpoint in probably six years and would need to bother to get my book. Yes, c.f. can go above, I just said it *usually* takes the lower voice. Also thanks. I don't post much anymore because I was tired of folks not listening to me / arguing with incorrect information.
Comment: @Leffles - take what I say with a grain of salt - they are mostly specific to 17th century counterpoint, and a lot of those considerations break down in other traditions of counterpoint. Personally I don't care that much about metronome speeds. So many metronomes are digital nowadays that tempi of fractional indications are possible and used!
Comment: @jjmusicnotes That clarifies. Thanks kindly. An edit to the double-skip part of your post might be worthwhile just to clarify that "any skip" doesn't mean individual skips of a third. But the double-skip -- definitely needs to return by step. (I hear you 100% about the ... resistance, shall we say? ... to discussion.)
Comment: @Aaron - yup, I've amended to clarify. Mmm more like resistance to factual information...anyway, I look forward to reading your answers :)
Comment: @jjmusicnotes I think you've found our new motto: "Music Practice & Theory: New home of alternative facts."
Comment: @jjmusicnotes I know this has no relation to music theory at all but thank you for your share of wisdom. This is just my opinion- but I believe that music isn't something we all should just continuously argue over about. I believe it's about respecting each other's information and understanding, and changing that into insight. But I guess people are people.
Comment: @Leffles - I appreciate that and hope that you find my information useful.
Comment: @Aaron – that is probably the truest statement I've ever seen here.
Answer: Canto fermo is simply put, any piece of melody taken as a basis for composition. Italian for 'fixed song'.
So, any basic melody (often initially secular) usually used in ecclesiastical ways could be termed canto fermo. Also known as 'vox principalis' it formed the basis for a song. That melody line was then used to produce a 'harmony' a fourth or fifth away, in a sort of doubling effect. Maybe that's what your teacher is looking for, but basically any melody can be canto fermo.
Comment: While this answer is correct to a certain degree (and, in general, it is a point well worth making), it ignores the fact that historical composition treatises developed rules governing cantus firmus composition.  In the context of a composition class, therefore, which is the context of this question, the student will want to understand how to apply those rules.  This answer isn't particularly helpful for that purpose.
Comment: "Canto fermo" is Italian for "I stop singing". "Cantus firmus" is Latin for "fixed song." Britannica has a [nice definition of Cantus Firmus](https://www.britannica.com/art/cantus-firmus) the includes some additional historical detail regarding the evolution from "vox principalis" to "cantus firmus".


Find a constant (a class) scoped to a specific namespace (a module)

Question: I'm trying to programmatically fetch a constant (e.g. a class), but want to only look at the constants defined in a specific namespace. However, const_get will bubble up to higher namespaces while searching for the constant. For instance:
module Foo
  class Bar
  end
end

class Quux
end

If you then ask Foo to return the constant "Bar", it'll return the correct class.
Foo.const_get('Bar')
#=> Foo::Bar

However, if you ask it for "Quux", it'll bubble up it's search path and find the top-level Quux:
Foo.const_get('Quux')
#=> Quux

Is there any way to make it only search in the module that const_get is called on?
Comment: *+1* for creating good and clear question.
Answer: Module#const_get says:

Checks for a constant with the given name in mod If inherit is set, the lookup will also search the ancestors (and Object if mod is a Module.)
The value of the constant is returned if a definition is found, otherwise a NameError is raised.

You can then do as below:
module Foo
  class Bar
  end
end

class Quux
end

Foo.const_get('Quux',false) rescue NameError
# >> NameError
Foo.const_get('Bar',false) rescue NameError
# >> Foo::Bar


What can I do to "stress test" an ASA5505?

Question: Just wondering there is any kind of stress test I can put the ASA through. I'm asking this not to help with a problem but just for reference.
I know I could use iperf to send a bunch of traffic through it but was thinking there might be something more I could do.
Comment: Piss off someone on 4chan.  See how long it is before your firewall catches fire?
Answer: For a firewall device It is quite common to stress test the throughput capacity and simultaneous connections (and in some scenarios even the maximum size of the NAT translation table).
Then there is the amount of new connections per unit of time the firewall device can establish (rate of new connections).
This parameter is of huge significance in a firewall and in my experience, not many people talks about it and as a consequence, not many people do test it.
In fact, a couple of times I have seen firewalls fell on their knees under a DDoS that is well under the maximum advertised throughput of the firewall but which has a very high connection rate (last I remember above ~100Kconns/sec).
When this happens the explaining is not always easy to do:
"What do you mean with a 100Mbps DDoS our firewall fell???, isn't it supposed to handle Zillions of Gbps of throughput??? I want to talk with the sales engineer right know dammit!"
Comment: Personally I don't see the value in stress testing a firewall for it's ability to handle situations that don't reflect real usage. What's the value in testing it's ability to handle a DDOS attack? Do you want it to continue handling normal traffic while under a DDOS attack? I don't crash my car into a wall to stress test it's airbag. Why the need to stress test it at all? Do you stress test the fire retardent material in your house by lighting a fire in the living room? I'm trying to understand the logic here. Stress testing it's ability to handle your projected traffic load is valid though.
Comment: @joeqerty: "how can you stress test it before the attack .. without knowig the volumne and scope.."  Well, that's kind of what stress tests are for.  To determine the volume and scope of what can be handled by a product BEFORE failure.  In other words the stress test should STRESS the product to find the point of failure.
Comment: @joeqwerty: The thing is, someone actually did crash the car in question in a wall to make those safety ratings. Usually they do 7 of them just to be sure. Regarding computer products it's buyer beware and you can't trust anything a manufacturer says.  NIC manufacturers advertise 1GB/s, but you'll never actually see that rate. HD Manufactures tout the new 6 GB/s interface, but there isn't a single drive on the planet that can transfer that fast.  I could go on, point is it's called stress testing for a reason.
Comment: In addition, how can you stress test it for a situation you have no ability to quantify. If the firewall comes under attack how can you stress test it before the attack for it's ability to withstand the attack without knowing the volume and scope of the attack?
Comment: @Chris: Good points. My point being that you should purchase a device based on it's documented (from the device specifications) ability to handle the load that you expect it to handle and for your projected usage of said device. I don't crash my car into a wall just to prove that the manufacturer's safety ratings hold true. I also don't drive my car at 120MPH to see how far I can push my 80MPH rated tires. Maybe "load testing" or "usage testing" are better terms than "stress testing".
Comment: @Chris: Again, good points. Of course the manufacturer puts the product through stress tests, so that the consumer doesn't have to. When you purchase a product it's already been determined (by the manufacturer) what said device can and can't do and what it's limitations and capabilities are. You shouldn't have to stress test a device, that's what device specifications are for, so you as the consumer know before making a purchase whether or not the device suits your needs and usage. If you have to stress test it you probably haven't done enough to determine what your needs and usage are.
Comment: Do you stress test hard drives, NIC's, memory sticks, and CPU's when you purchase them? Maybe I'm hung up on semantics here. Load testing is valid but I see no point in stress testing. Stress testing implies that you're going to push a device to and beyond it's rated limits, which is pointless in my opinion. The manufacturer has already done that. Load testing to determine how well a device operates at the projected usage is valid.
Comment: @joeqwerty: Actually that testing is done by the government (NTSB).  The vendors might crash their own cars, but the NTSB performs their own crash tests on behalf of the people.  In other words, the words of the vendor arent' trusted and instead are independently verified.
Comment: @joeqwerty: With regards to stress testing components: we absolutely do that along with load and performance testing. There is a HUGE difference in how a given product fails between manufacturers. Further the manufacturers I see that advertsise the results for this are for hard drives; it's used to come up with a MTBF rating. That said, Intel and others have started stress testing full servers in order to determine the real cooling requirements for data centers. It's interesting to see how the actual numbers are different from what's been advertised.
Comment: @joeqwerty: One last thought.  In this particular case I would want to know what happens when the device was completely overloaded.  Does it simply stop accepting new connections or is it worse.  For example: does it drop current connections, shut down, lose the magic smoke, or worse, simply pass through all connections.  15 years ago you could overload the Cisco PIX and it would stop protecting your network and pass all connections through.  We found this by stress testing the device.  Cisco sure wasn't going to give us this info.
Comment: @Chris: Thanks for the well thought out comments. I'll respectfully agree to disagree with you, but I appreciate your point of view on the issue and the time you've taken to state your position.
Answer: Kudos for even thinking about stress testing.  In my experience you really have to break down the components of the firewall and design your tests for specific circumstances depending on your policies and configuration.  @jliendo pointed out some good items for consideration.  Connections per second instead of merely throughput is important to think about and you could try a real-world test of that by downloading a heavily seeded torrent.  Your device could also have the IPS card installed so if it did, you'd want to thoroughly test stress any policies that you setup for packet inspection with the sensor.  Did you setup Antivirus scanning?  You would want to test throughput of that policy to see if it can keep up.  In general, the goal of a stress test would be to test your policies more so than the raw power of the hardware; since the policies can significantly impact the performance levels of the hardware.
With the above in mind, you would find a collection of tools such as iperf to help you analyze specific cases.  Iperf can help you test your storm control policies.  Seagull is a useful traffic generator that can test most of your other policies.  (Remember to test whether or not it works as intended, AND whether it blocks traffic as intended)  Depending on your environment you may also want to test latency and poor network connections (perhaps the 5505 is a branch-office firewall?) to help you adjust your timeouts.  The trial version of Netlimiter is very helpful in this regard.
In summary I would re-approach your question from the view of your configuration.  If you have configured the box to allow or deny traffic in a certain situation, then ask yourself how to test whether or not that works as intended.  Once you tested at this level, then try to test multiple policies (such as HTTP through the AV Scan to a secondary subnet on a VLAN).  Then bomb the device to death with a traffic generator, find weak points in the flow, and setup quality of service to protect yourself in the case of extreme situations.


Inform the user what page of the pager it is -- on top of the page as well

Question: When we create a View of pages we can give it a pager. That pager typically appears underneath the view. This can cause an accessibility problem of a user mistakenly clicking to go to a next page without understanding what the current page is, especially if the page is very long and the the fold of the new page doesn't indicate what is the current page on the pager series.
The pager is rendered as in the following screenshots.

How can I show the user the current page above the view as well?
Comment: Welcome to Drupal Answers! The pager shown in a view already shows the current page, even when the mini pager is used. For example, with Drupal 10 and its default theme, it appears like [this](https://i.stack.imgur.com/2KX2q.png). Probably, the used theme is not showing correctly the pager.
Comment: @apaderno my theme is olivero and the pager is shown fine underneath the main content but I want to somehow show the current page above the main content as well, perhaps even duplicating the pager to the top part of the page. I can duplicate it with JavaScript in a `cloneNode(true);` but I doubt it's a good way to go.
Comment: Go for JavaScript. Because whatever top of the page means and depending of how the view is built, it can become quite difficult to retrieve the pager states outside of the context of the view.
Comment: My comment was for *This can cause an accessibility problem of a user mistakenly clicking to go to a next page **without understanding what the current page is**.* The current page is shown near the link to go to the next page. If users do not notice that, they would not notice that if the page number is placed on the top of the page. I could understand if the problem is that users do not understand what those numbers are, but in that case it should be sufficient to change how the pager is rendered to add more explicit labels, for example *Current page:* near the current page number.
Comment: @leymannx I guess the main problem is not where the pager is shown, but for the users to understand that the numbers shown on the pager are page numbers, and the highlighted one is the current page.
Comment: May you add a screenshot that shows the pager in that view? This would allow to give a more helpful answer.
Comment: @apaderno it's a standard all-regular full pager of 5 items per page (in a simple blog View). I think I'll just clone it with JavaScript perhaps, or clone the `pager__item pager__item--active pager__item--number` with JavaScript and add some text near it like "You are here in this page `PAGE_NUMBER`".
Comment: Even if it is standard, the theme could change how the pager is rendered. For example, with the Seven theme, it would be rendered like *‹‹ Page 2 Next page ››*, while the Claro theme would not show *Page* near the page number. Modules can alter how a pager is rendered. That is why I asked for a screenshot.
Comment: @apaderno I have added two screenshots.
Answer: You can use template_preprocess_views_view() hook to get current page number
<code>function Mymodule_preprocess_views_view(&$vars){
  $view = $vars['view'];
  $id = $view->storage->id();
  if($id == 'view_name'){
   $pager_number = $view->pager->current_page;
   // current page key value start from 0 so add by 1
   // set current_page variable that can access in view twig
   $vars['current_page'] = $pager_number + 1;
  }
}
</code>
Note: Now you can use the "current_page" in views-view.html.twig by rendering like this:
{{ current_page }}
Make sure override view twig by view name displayed by theme suggestion
To override view twig can follow naming convention like this:
views-view--machine_name.html.twig
Answer: In the View add a Header: Global: Text area and fill in the text:
<code>[view:current-page]
</code>
There is a list with more pager variables in the section Available global token replacements.


How to find a function with several bifurcations of specified type

Question: Suppose I want to construct a function $h(x,r)$ such that it exhibits a bifurcation of type $a$ at the point $(x_{1},r_{1})$ and bifurcation of type $b$ at the point  $(x_{2},r_{2})$.
One alogirhtm to find this is to set all the relevant derivatives equal to zero, using the two taylor expansions, and go from there. This gets complicated quite fast, specially when done by hand.
As a first attempt, I tried doing the following:
let $f$ have a bifurcation of type $(a)$ at point $(x_{1},r_{1})$, and $g$ have a bifurcation of type $(b)$ at point $(x_{2},r_{2})$. Then if $h = f+g$, we might be in luck, since locally $h$ behaves like $g$ at $(x_{1},r_{1})$ and similarly for $f$. But this turned out not to work:

This plot shows that we don't get the desired bifurcation.
Experimentally, I tried $fg$ instead.
And at least in the one example I tried, this seemed to work. There are the bifurcations of the desired type in the desired positions.
How can I generalize this result, and what is the theoretical justification of $fg$ exhibiting the desired bifurcation behavior?
Answer: This is essentially due to the fact that bifurcations are determined by the zeros of the RHS function in an ODE $x'=f(x)$. It's not easy to relate the zeros of the sum of polynomials (or any other kinds of functions) to the sum of the zeros of the polynomials (e.g. consider $p(x)=x-1, q(x)=x$. Then $x=1$ is the unique zero of $p$ and $0$ is the unique zero of $q$, but $p+q=1$ has no zero.); while any zero of a product ought to be a zero of one component.
For completeness here is an alternative implementation of a combination of a saddle-node bifurcation and pitchfork bifurcation, which also records the stability properties:

(Here is the link to the interactive graph: https://www.desmos.com/calculator/0fb2kpdner)


Cliente Servidor erro no envio de mensagens

Question: Tenho o seguinte codigo porem quando corro o Servidor e o cliente e tento enviar mensagens a partir do cliente (Frame janelaUtilizador) da me erro! Alguem consegue me ajudar?
Supostamente o erro esta a classe Painel mensagens no botaoEnviar no actionlistener
public class PainelMensagens extends JPanel{
private static final long serialVersionUID = 1L;

private EstadoMensagem estadoMensagem = null;
private JButton botaoEnviar;
private JTextField zonaEscreverMensagens;
private JTextArea zonaReceberMensagens;
private JanelaUtilizador janelaUtilizador;

private Mensagem mensagem;
private SocketCliente socketCliente;

public PainelMensagens(JanelaUtilizador janelaUtilizador) {
    this.janelaUtilizador = janelaUtilizador;

    setLayout(new BorderLayout());
    criarPainelEscrita();
    criarPainelLeitura();
}

private void criarPainelEscrita(){
    JPanel painelEscrita = new JPanel();
    painelEscrita.setLayout(new BorderLayout());

    zonaEscreverMensagens = new JTextField();

    botaoEnviar = new JButton("Enviar");
    botaoEnviar.addActionListener(e->{
        String texto = this.zonaEscreverMensagens.getText();
        String nome = this.mensagem.getNome();

        if(!texto.isEmpty()){
        this.mensagem = new Mensagem();
        this.mensagem.setNome(nome);
        this.mensagem.setMensagem(texto);
        this.mensagem.setAccao(Accao.ENVIAR_TODOS);

        this.socketCliente.enviar(this.mensagem);
        }
        this.zonaEscreverMensagens.setText("");
    });

    painelEscrita.add(zonaEscreverMensagens, BorderLayout.CENTER);
    painelEscrita.add(botaoEnviar, BorderLayout.EAST);

    add(painelEscrita, BorderLayout.SOUTH);
}

private void criarPainelLeitura(){
    zonaReceberMensagens = new JTextArea();
    zonaReceberMensagens.setEditable(false);

    add(zonaReceberMensagens, BorderLayout.CENTER);
}

public EstadoMensagem getEstadoMensagem() {
    return estadoMensagem;
}

public JTextField getZonaEscreverMensagens() {
    return zonaEscreverMensagens;
}

public JTextArea getZonaReceberMensagens() {
    return zonaReceberMensagens;
}

public JanelaUtilizador getJanelaUtilizador() {
    return janelaUtilizador;
}

public JButton getBotaoEnviar() {
    return botaoEnviar;
}
}

public class PainelEstadoContacto extends JPanel{

private static final long serialVersionUID = 1L;

private JanelaUtilizador janelaUtilizador;
private JButton botaoOnline;
private JButton botaoOffline;
private JTextField nomeUtilizador;

private Socket socket;
private Mensagem mensagem;
private SocketCliente socketCliente;

public PainelEstadoContacto(JanelaUtilizador janelaUtilizador) {
    this.janelaUtilizador=janelaUtilizador;

    botaoOnline= new JButton("ONLINE");
    botaoOnline.addActionListener(e -> {
        String nome = nomeUtilizador.getText();

        if(!nome.isEmpty()){
            this.mensagem = new Mensagem();
            this.mensagem.setAccao(Accao.ONLINE);
            this.mensagem.setNome(nome);

            this.socketCliente = new SocketCliente();
            this.socket = this.socketCliente.conectar();

            //Criar thread para iniciar processo
            new Thread(new ListenerSocket(this.socket)).start();
        }
        this.socketCliente.enviar(mensagem);

    });

    botaoOffline=new JButton("OFFLINE");
    botaoOffline.addActionListener(e->{
        this.mensagem.setAccao(Accao.OFFLINE);
        this.socketCliente.enviar(this.mensagem);
        desconectar(mensagem);
    });

    setLayout(new GridLayout(1,3));

    JPanel painel = new JPanel();
    painel.setLayout(new BorderLayout());

    JLabel utilizador = new JLabel("Utilizador:");
    nomeUtilizador = new JTextField();

    painel.add(utilizador, BorderLayout.NORTH);
    painel.add(nomeUtilizador, BorderLayout.SOUTH);

    add(painel);

    add(botaoOnline);
    add(botaoOffline);
}

public JanelaUtilizador getJanelaUtilizador() {
    return janelaUtilizador;
}

private class ListenerSocket implements Runnable {
    private ObjectInputStream input ;

    public ListenerSocket(Socket socket) {
        try {
            this.input = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        Mensagem mensagem = null;

        try {
            while((mensagem = (Mensagem) input.readObject()) != null){
                Accao accao =  mensagem.getAccao();                 //receber accao por parte do servidor

                if(accao.equals(accao.ONLINE)){
                    conectado(mensagem);
                }else if(accao.equals(accao.OFFLINE)){
                    desconectar(mensagem);
                    socket.close();
                }else if(accao.equals(accao.ENVIAR_UM)){
                    receberMensagem(mensagem);
                }else if(accao.equals(accao.CONTACTOS_ONLINE)){
                    atualizarLista(mensagem);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void conectado(Mensagem mensagem){
    if(mensagem.getMensagem().equals("Não conectado!")){
        this.nomeUtilizador.setText("");
        JOptionPane.showMessageDialog(this, "Conexão sem sucesso \n Introduzir outro nome");
        return ;
    }
    this.mensagem = mensagem;
    //      this.botaoOnline.setEnabled(false);
    //      this.nomeUtilizador.setEditable(false);
    //
    //      this.botaoOffline.setEnabled(true);
    //
    //      //this.textoEnviado.setEditable(true);
    //      this.janelaUtilizador.getPainelMensagens().getZonaEscreverMensagens().setEditable(true);
    //
    //      //this.botaoEnviar.setEnabled(true);
    //      this.janelaUtilizador.getPainelMensagens().getBotaoEnviar().setEnabled(true);
    //      //this.botaoAtualizarLista.setEnabled(true);
    //      this.janelaUtilizador.getPainelMensagens()

    //this.textoRecebido.append(mensagem.getNome() + "\n");
    this.janelaUtilizador.getPainelMensagens().getZonaReceberMensagens().append(mensagem.getNome() + "\n");

    JOptionPane.showMessageDialog(this, "Conectado ao QuequeAPP");
}

private void desconectar(Mensagem mensagem){

    this.botaoOnline.setEnabled(true);
    this.nomeUtilizador.setEditable(true);

    this.botaoOffline.setEnabled(false);
    //      this.textoEnviado.setEditable(false);
    //      this.botaoEnviar.setEnabled(false);
    //      this.botaoApagar.setEnabled(false);
    //      this.botaoAtualizarLista.setEnabled(false);

    JOptionPane.showMessageDialog(this, "OFFLINE");
}

private void receberMensagem(Mensagem mensagem){
    //      this.textoRecebido.append(mensagem.getNome() + " diz:" + mensagem.getMensagem() + "\n");
    this.janelaUtilizador.getPainelMensagens().getZonaReceberMensagens().append(mensagem.getNome() + " diz: " + mensagem.getMensagem() + "\n");
}

private void atualizarLista(Mensagem mensagem) {

}
}

public class JanelaUtilizador {

private PainelContactos painelContactos;
private PainelMensagens painelMensagens;
private PainelEstadoContacto painelEstadoContacto;
private JFrame janela;
private Cliente cliente;

public JanelaUtilizador(Cliente cliente){
    this.cliente = cliente;

    painelContactos = new PainelContactos(this);
    painelMensagens = new PainelMensagens(this);
    painelEstadoContacto = new PainelEstadoContacto(this);

    criarJanela();
    janela.validate();
    janela.setVisible(true);
}

public void criarJanela(){
    janela = new JFrame("QuequeApp");

    janela.setLayout(new BorderLayout());

    janela.setLocation(400,100);
    janela.setSize(500, 500);

    janela.add(painelContactos, BorderLayout.WEST);
    janela.add(painelMensagens, BorderLayout.CENTER);
    janela.add(painelEstadoContacto, BorderLayout.NORTH);

    janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public Cliente getCliente() {
    return cliente;
}

public JFrame getJanela() {
    return janela;
}

public PainelContactos getPainelContactos() {
    return painelContactos;
}

public PainelMensagens getPainelMensagens() {
    return painelMensagens;
}
}

Mensagem de erro
Comment: Você postou código demais. Mas creio que dentro da classe PainelMensagens o objeto private SocketCliente socketCliente está nulo. Assim, quando vc chama ele dentro do seu  botaoEnviar.addActionListener dá o erro de NPE (Null Pointer Exception).
Comment: Possível duplicata de [Cliente Servidor erro a enviar mensagens](http://pt.stackoverflow.com/questions/102482/cliente-servidor-erro-a-enviar-mensagens)
Comment: Então por que apagou, se não era duplicata?
Comment: So agora e que percebi! Consegue me ajudar?
Comment: então e que valor e que tem de assumir? sabe?
Comment: Não tem que assumir valor. Tem que ser instanciado em algum lugar, de acordo com a sua lógica. Algo assim: this.socketCliente = new SocketCliente(). Exatamente como você faz com o campo mensagem.
Answer: Dentro da classe PainelMensagens, método criarPainelEscrita, existe o código abaixo:
botaoEnviar.addActionListener(e->{
    String texto = this.zonaEscreverMensagens.getText();
    String nome = this.mensagem.getNome();

    if(!texto.isEmpty()){
    this.mensagem = new Mensagem();
    this.mensagem.setNome(nome);
    this.mensagem.setMensagem(texto);
    this.mensagem.setAccao(Accao.ENVIAR_TODOS);

    this.socketCliente.enviar(this.mensagem);
    }
    this.zonaEscreverMensagens.setText("");
});

Neste código, está sendo referenciado o objeto socketCliente, assim:
this.socketCliente.enviar(this.mensagem);

Entretanto, este campo não está sendo instanciado em nenhum lugar. Portanto, muito provavelmente, o seu NPE está sendo gerado por causa disso.
Para resolver, esse objeto precisa ser instanciado, da mesma maneira que você fez com o campo mensagem, algo assim:
this.socketCliente = new SocketCliente();

Note que estou omitindo qualquer parametros do construtor, se o mesmo existir.
Um outro erro pode ser visto na mesma rotina acima, porém no campo mensagem.
O seguinte trecho de código está sendo executado antes de instanciar o objeto mensagem, veja:
String nome = this.mensagem.getNome();

Comment: acho que entendi, então como faço para resolver isso?
Comment: eu meto esse this.socketCliente = new Cliente em cima do this.socketCliente.enviar(this.mensagem) e mesmo assim quando tento enviar uma mensagem da me o mesmo erro
Comment: NPE é um erro causado pelo programador. Portanto, você está deixando de instanciar algo e tentando referenciá-lo. Como a referência é nula, acontece isso. Se não tem relação com o que falei, faça um Debug que você encontrará facilmente.
Comment: sim tem razão essa parte eu entendi. Mas não consigo resolver o erro e é mesmo importante porque falta me este passo para o meu projecto estar completo, so tenho esse erro que não consigo mesmo resolver e sei que é fácil para vocês
Comment: vc tentou debugar o seu código? Coloca um breakpoint dentro do addActionListener e veja passo-a-passo em qual ponto desse trecho está dando o erro. Não temos como ajudar mais do que isso. Precisaríamos do código rodando e ainda entender a sua lógica. Por isso, as dúvidas precisam ter escopo muito bem delimitado.
Comment: Sim ja tentei eu sei que o erro e simples e que me consegue ajudar num minuto não consigo e explicar melhor
Comment: nao me pode dar o seu mail para me ajudar?
Comment: ultima dica: eu vi que no construtor da PainelEstadoContacto voce instancia um socketCliente assim: this.socketCliente = new SocketCliente(); this.socket = this.socketCliente.conectar(); Porque você não faz o mesmo na PainelMensagens?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/32641/discussion-between-cantoni-and-java).


iCell.Value takes too long

Question: I have this simple code that loops through 400 rows.
It works but it takes 30 secs.
The problem comes from the   iCell.Value = stringaDecriptata line
Is there any way to speed up the code?
Sub Decr()

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False

Dim counter As Integer
Dim stringaCriptata As String
Dim stringaDecriptata As String
Dim carattere_da_decriptare As String
Dim carattere_da_sostituire As String
Dim iCell As Range

For Each iCell In Range("A1:BK460")
    stringaDecriptata = ""
    lunghezza = Len(iCell.Value)
    indirizzo = iCell.Address

    For counter = 1 To lunghezza
        stringaCriptata = iCell.Value
        carattere_da_decriptare = Mid(iCell.Value, counter, 1)
        carattere_da_sostituire = Chr(Asc(carattere_da_decriptare) - 10)

        stringaDecriptata = stringaDecriptata & carattere_da_sostituire
    Next

    iCell.Value = stringaDecriptata
Next iCell

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True

End Sub

Comment: I tried your code in new workbook with A1:BK460 filled with ten letters each. It ran in under 2 secs. I think you should try this yourself. If it's faster in a clean workbook, I think your problem is elsewhere in the original workbook.
Comment: There are 28980 cells in that range, which is almost 30.000. This means that 1000 cells are handled per second. Is that so bad?
Comment: `stringaCriptata = iCell.Value` Is this line needed ?
Answer: Please, try the next adapted code. It places the range to be processed in an array and all process is done in memory. Only at the code end it drops the processed result, at once:
Sub Decr()
 Dim sh As Worksheet, i As Long, j As Long, rng As Range, arr As Variant, counter As Integer
 Dim stringaCriptata As String, stringaDecriptata As String, carattere_da_decriptare As String
 Dim carattere_da_sostituire As String, lunghezza As Long

 Set sh = ActiveSheet
 Set rng = sh.Range("A1:BK460")
 arr = rng.Value2  'place the range in an array for faster processing

 For i = 1 To UBound(arr)        'iterate between the array rows
    For j = 1 To UBound(arr, 2)  'iterate between the array columns
         stringaDecriptata = ""
         lunghezza = Len(arr(i, j))
         For counter = 1 To lunghezza
            stringaCriptata = arr(i, j)
            carattere_da_decriptare = Mid(arr(i, j), counter, 1)
            carattere_da_sostituire = Chr(Asc(carattere_da_decriptare) - 10)

            stringaDecriptata = stringaDecriptata & carattere_da_sostituire
        Next counter
        arr(i, j) = stringaDecriptata 'place the decrypted string back in the array element
    Next j
 Next i

 'drop the processed array result, at once:
 rng.Value2 = arr
End Sub

Iterating between each range cell takes time, and even more time to place back the processed value, one at a time.
Then, it is good to make the habit to declare all involved variables. To let VBA helping you if forgot it, you should place  Option Explicit on top of the module...
I did not test the code, but I think it should work and be faster. I am just curious how much it takes to process your range...
Comment: It takes 1 msec!! Thanks!

iCell.Value takes too long


I'm starting to feel depressed playing by myself

Question: I've recently graduated from college and started playing guitar again with my spare time with the full intention of playing with others. It's fun, I'm progressing decently, and I'd like nothing better than to find somebody else to play with and liven up my usual routine of sitting in my bedroom for two hours practicing scales.
The problem is, I have never, ever, not once met somebody who's interested in playing an instrument, let alone with another person. I was led to believe by the internet that just playing an instrument in public or moving around different groups of friends and family would magically reveal people that would want to start a garage band or something, but so far nothing. This was a problem in highschool, it was a problem in college, and it's a problem now.
And to be honest, it's really depressing to practice with the understanding that I could learn how to play like Hendrix and still be practicing by myself in my bedroom for potentially the rest of my life. It's gotten to the point that this feeling of loneliness is starting to cut into my drive to practice regularly.
My question is twofold:
Firstly, is it natural to feel lonely when practicing to the point that it starts to make practicing unpleasant?
Secondly, what kind of techniques or tools can I employ to find people to play with if my existing friends, family, and neighbors aren't interested? The questions I can get ahold of on this site just stop at looking for preexisting friends that would want to play with you or hoping to find people through playing publicly. Eight years later and that hasn't worked for me.
Comment: And please don't learn too hard to become another Jimi Hendrix, one is enough!
Comment: Hi there, welcome. I know the search engine on SE isn't the most intuitive, but we have a number of questions on this topic. I have linked to the best duplicate. The psychology bit of your question is off topic, I'm afraid - it's just human psychology.
Comment: Record and upload on youtube, you will find guitar enthusiasts alike, or by all means be criticized, which is good. It also gives you a sense that your effort is eternally perserved into a certain extent, and this may be a solace.
Answer: I understand you. I've this problem a lot, not due to the lack of people who would want to play together though, but due to the fact that all those people that, here in my city, gather into groups, mostly play shitty music and are very poor in music both theoreticaly and practicaly.
Considering your first question:
You always only do scales and enhance your technique? If so you are really put in a corner there. Try composing a bit, try playing some songs or pieces. Scales, arpeggios, different exercises are good but if do them only all of your time, that's very boring. I often did 50/50. And even when I hadn't an instrument at hand, i still composed, but in my head.
If you make a few of your own songs, especially with vocals, you might have a better chance of starting your own band where you'd be the leader.
Important notice: Try to find people who are technically as good as you are or at least close to that. With people who are not it's hard to work together, you have problems all time through.
Imagine you want your bass player to play some wonderful lick that fits into your piece and he can't, that'll be a problem until he learns that. Or you'll have to simplify.
If you have a city forum try looking for musicians there. Try Facebook or Instagram or Twitter or any other social network.


If $A+B \mid A^5$ and $A+B \mid B^5$, what can be concluded?

Question: Assume $A+B \mid A^5$  and $A+B \mid B^5$, while all the variables are integers expect zero.
Can we prove that $A=B$?
This is my idea of the proof:

For every prime $p$ that $p\mid A+B$ there is $p \mid A$ and $p \mid B$.

Let $\gcd(A,B)=P$, so $A=Pw$ and $B=Pv$ such that $w$ and $v$ have no common factors with $P$. Then if $q\ne 1$, such that $q$ and $P$ are coprime, and $q\mid A+B$ then $q\mid w+v$, and hence $q$ divides both $A$ and $B$, and this is not possible.

Hence $A=P$ and $B=P$.

In this proof, I did not use the exponent $5$ at all. So I feel there is something wrong with the proof.
Is there any thoerem that can be used here?
Comment: It's not necessarily true; $A = 3, B = 6$ satisfies these conditions.
Comment: $(A+B) \mid (A^5+B^5)$ is always true. In fact $A^5+B^5 = (A+B)(A^4-A^3B+A^2B^2-AB^3+B^4)$.
Comment: Well, I am 15 and I have not much sense to talk the kind of talks you people are having now, so I may be a bit incapable in understanding the whole topic.
Comment: @Spectre age is not important, at least in math
Comment: @paulinho good point. I should think about this.
Comment: Another nice example is $A=12$, $B=15$.
Comment: The two assumptions are redundant: $A + B \mid A^5$ is equivalent to $A + B \mid B^5$.
Comment: @WhatsUp can you elaborate please?
Comment: @DietrichBurde here the assumption is that "A+B divides A^5 and also divides B^5" so here this sentence should be correct.
Comment: There's something that I felt - $B$ could be $0$ while $A$ could be something else (or vice versa).
Comment: @player3236 but here the assumption is $A+B | A^5$ and $A+B | B^5$ which is not always true. It is true only due to an assumption here.
Comment: I was elaborating on WhatsUp's argument.
Comment: @Spectre true. Zeros should be excluded. I will edit the question.
Comment: Good then ! I felt we required Mr Zero to come into the question.....
Comment: The aforementioned counterexample holds since $3 \mid 1+2$ ($p \mid w+v$). This possibility was not (and cannot be) accounted for in your proof.
Comment: If $A +B | A^5$ or $A +B | B^5$, can't $A +B $ be a prime factor of either of the two ?
Comment: Or say, $A^5 $ or $B^5$ can be factorised and any of the factors of those could be cancelled out (I mean, divided off) using $A + B$, right?
Comment: @Spectre  but is not it a case of v+w in the second bullet point? The idea is that if A and B have a factor other than A + B, then that factor is common between them. So what ever factors A has, B has the exact same factors. Thus A and B are the same. Makes sense do you think?
Comment: I will try to put up a few inferences I made as an answer.
Comment: Thanks for the encouragement, sir !
Comment: I have put up my answer... please check if that works.
Comment: @Optima, I have also added a few other opinions of mine in the comments below my answer.
Comment: @JaapScherphuis , you said it right.
Answer: As mentioned there are easy counterexamples. We can characterize the solutions as follows. By the gcd Universal Property & Freshman's Dream we have
$\begin{align} A+B\mid A^5,B^5\!\iff\! A+B&\mid (A^5,B^5)=(A,B)^5\\[.2em]
\iff a\ +\ b&\mid\, c^4\ \ \text{by dividing prior by }\,c := (A,B), \ {\rm  with }\,\ a,b = \frac{A}c,\frac{B}c
\end{align}$
So let $\,c\,$ and coprime $\,a,b\,$ be solutions of $\,a+b = c^4.\,$ Then $\,A\!+\!B\mid A^5,B^5$ for  $\,A,B = ac,bc$.
e.g. let's view the first counterexample in the comments this way
$$\begin{align}
1+2&\mid 3^4\\[.2em]
\iff\ 3+6&\mid 3^5 = (3,6)^5 = (3^6,6^5)\\[.2em]
\iff\  3+6&\mid 3^5,6^5\\[.3em]
\text{for a bigger example }\ \ \
40\ +\ 41\ &\mid\ 3^4\\[.2em]
\iff\  120+123&\mid 120^5, 123^5
\end{align}\qquad\qquad\qquad\qquad\quad $$
Comment: You are better than me.... I bow down, sire ! :)
Comment: What about my answer ?
Comment: Is there anything worth understanding from it ?
Comment: @Spectre I haven't had a chance to read it, but you may find it interesting to view your examples from the above viewpoint.
Comment: I'll try it... thanks for the advice...
Comment: But was my answer sensible, @BillDubuque ?
Answer:
NB : I'll be using $(x,y)$ to denote the values of $A$ and $B$ as $(A,B)$.

"Suppose $A$ and $B$ are integers other than $0$, such that $A + B|A^5$ and $A + B|B^5$, what inferences can be drawn from this ?" - this is what has been asked.
If the above conditions have to be satisfied, $A^5$ and $B^5$ should have $A + B$ as a factor (or some other number divisible by that sum) . This means that $A = 0$ or $B = 0$ , which is invalid as per the question. Therefore, we can consider values like $(3, 6)$ (as @paulinho suggested) , but at the same time, we have exceptions : $(2,9) [\because 11 \nmid2^5 , 11 \nmid 9^5]$ and such values. So, maybe, $A +B$ should be some power of primes to satisfy the condition (as in the example $(3,6) : 3 + 6 = 9 = 3^2$; or even $(2,6):2 + 6 = 8 = 2^3$).
On the whole, if $p$ is a prime, a pair of integers $(p, pn)$ [for some $n$ such that $p \mid (n + 1)$ and $(n + 1) = p^m$ for some $m <  5$] satisfies the conditions.

PS : For a better answer, look for the one written by @BillDubuque. I think that his answer is more sensible and more understandable than mine.
Comment: I believe that I am clear enough to you ...
Comment: Note : the above condition that you have to take a prime needn't be followed. I wrote what I had ended up in. You may find counterexamples and add that to the answer to make it more OK ....
Comment: @BillDubuque, I hope you'll edit your comment.. a few typos came up, I guess..
Comment: Never mind... I have put my comments beneath your answer, @BillDubuque ...


Google Drive access without user login

Question: I am making an app for the iPhone were all the users have access to the same google drive folder for uploading files. This google drive account is managed by the company and not by the users. There for I want to skip the google login form and just give the user access. Ideal the user does not even know he/she is using google drive.
I looked at the drEdit example and looked at oauth documentation. Is it possible to use one refresh_token for all the users to grand access? So I login once, grand access, somehow store the refresh_token and hard code that in the app for future use, so that all the users use that refresh_token for access. Or are there better ideas to do this?
Kind regards,
Stijn
Comment: There may be efficient solution to this.One possibility is to have a web service that provides the secure information(refresh token or any other info that is needed to log in to service). Every time application can access from the web service. Once retrieved information can also be stored in user keychain.
Answer: Thought there was a similar question to this, but can't find the one I'm looking for. Short answer is you need to be very careful how you do this. Embedding the refresh token in your app like that is inviting abuse, particularly if it is authorized for write access. Once a clever user or attacker finds that value, they can use that token to call the API however they want. If authorized for the full drive scope, that means that can also maliciously modify or delete files, secretly store their own content, etc...
If you really need to have anonymous or shared access to content stored in Drive, you're better off proxying requests through your own servers so you can control the interaction with Drive.

Google Drive access without user login


Pegar rows que não sejam do usuário logado

Question: Possuo uma tabela com colunas para e de onde eu insiro IDs diferentes em cada uma, porém eu preciso obter o ID do usuário que ENVIOU o pedido para mim, ou seja o ID que não seja igual ao do usuário logado.
SELECT `username` FROM all, users WHERE (`de` = 'ID DO USUARIO LOGADO' OR `para` = 'ID DO USUARIO LOGADO') AND (users.idu = chat.from NOT IN (ID DO USUARIO LOGADO) OR users.idu = chat.to NOT IN (ID DO USUARIO LOGADO)) GROUP BY `c_id` order by id desc

Dai criei este código, porém ele continua a me retornar o ID do usuário logado e não do que enviou, que esta a ocorrer?
Usei o NOT IN para impedir que fosse o ID do usuário logado, mesmo assim não funcionou.
Exemplo:

Tabela ALL

-------------
| de | para |
-------------
|  2 |  1   |
-------------

TABELA USERS

------------------
| idu | username |
------------------
|  1  |  MARCOS  |
------------------
|  2  |  MANUEL  |
------------------

SELECIONA O ROW ONDE (para = USUARIO LOGADO or de = USUARIO LOGADO) e depois vai na tabela USERS e seleciona o usuário que não seja o usuário logado dentre `para` e `de`.

Ou Seja, retornaria -> Manuel

Comment: Quais as estruturas de suas tabelas? Seria bom também uns dados de exemplo. Estou com um pouco de dificuldade em entender sua *query*, essa coluna `username` está em qual tabela?
Comment: @mgibsonbr Atualizei, está claro espero.
Answer: Pelo que eu entendi, um dos ids (de ou para) deve ser o do usuário logado, e o outro não, e você quer o outro em qualquer uma das duas situações, certo? Há diversas maneiras de fazer isso, mas a mais semanticamente correta na minha opinião seria usando um union:
select username
from users
where idu in (
    select de from `all` where para = 'ID DO USUARIO LOGADO'
    union
    select para from `all` where de = 'ID DO USUARIO LOGADO'
);

Exemplo no SQLFiddle. Ou seja, selecione o conjunto onde o usuário logado é o para, e faça a união com o conjunto onde o usuário logado é o de. Em cada caso, o id que te interessa é o outro. Busque na tabela users quem tem esse id.
Atualização: uma forma alternativa, sem envolver subquery, seria simplesmente trocar a ordem das suas condições; em vez de uma conjunção de disjunções (i.e. AND de ORs) você fazer o contrário. Isso exigiria no entanto um join a mais além do uso de case:
select case
           when u1.idu = 'ID DO USUARIO LOGADO' then u2.username
           else u1.username
       end as username
from users u1
    join `all` a  on u1.idu = a.de
    join users u2 on u2.idu = a.para
where
    (a.de = 'ID DO USUARIO LOGADO' AND a.para != 'ID DO USUARIO LOGADO') OR
    (a.de != 'ID DO USUARIO LOGADO' AND a.para = 'ID DO USUARIO LOGADO');

Exemplo.
Comment: Eu devo ter me expressado mal, está tudo certo menos "e o outro não, e você quer qualquer um dos dois, certo?" é exatamente o oposto eu desejo pegar o username do usuario oposto ao logado.
Comment: @user3163662 E é exatamente isso que esse código está fazendo! No exemplo, o usuário logado é o "Manuel", então ele retorna "Marcos". Quando eu disse "qualquer um dos dois" eu me referi a qualquer uma das duas situações: onde o usuário logado é o remetente e onde o usuário logado é o destinatário. Mas o que é retornado é sempre o outro usuário, o que não está logado.


Conditional probability and independence

Question: Suppose A and Y are discrete dichotomous variables $(A=0,1; Y=0,1)$
If $Pr[Y=1|A=1] = Pr[Y=1|A=0]$, why can we conclude that $$Pr[Y=1|A=1] = Pr[Y=1|A=0] = Pr[Y = 1],$$ without knowing beforehand whether $A$ and $Y$ are independent?
Comment: If it is a homework, you should use the `[self-study]` tag and check https://stats.stackexchange.com/tags/self-study/info
Answer: By the law of total probability,
\begin{align}
Pr(Y=1) &= Pr(Y=1|A=1)Pr(A=1) + Pr(Y=1|A=0)Pr(A=0) \\
&=Pr(Y=1|A=1)Pr(A=1) + Pr(Y=1|A=1)(1-Pr(A=1))\\
\end{align}
Can you simplify the equations above?
Edit:
In the second equation, I have used the fact that we are given $$Pr(Y=1|A=0)=Pr(Y=1|A=1)$$
Comment: Let me add a remark there. Thanks for the feedback.
Comment: If you, in your equation, are only using the law of total probability, and not an indepedence property, the last part of the equation should read $Pr(Y=1\mid A=0)(1-Pr(A=1))$ and not $Pr(Y=1\mid A=1)(1-Pr(A=1))$. Otherwise the equivalence does not hold.
Comment: We are told $Pr(Y=1|A=0)=Pr(Y=1|A=0)$ isn't it?
Comment: I am assuming that you mean $Pr(Y=1\mid A=1) = Pr(Y=1 \mid A=0)$. Yes, we are. But my point is that we are using external information for that part of the calculation, and not just relying on the law of total probability. I would thus add somewhere in the writing that "where the last equality holds because, here,  $Pr(Y=1\mid A=1) = Pr(Y=1 \mid A=0)$" or something along those lines.


MailChimp API 2.0 python new subscriber to groupings

Question: How does one add new subscribers to a grouping using the MailChimp API 2.0 in python? Let's say the group_id for two groups are 123 and 456. I'm able to set the email, first and last name for a subscriber, however, the groupings are ignored. What am I missing or doing incorrectly?
mailchimp_api = mailchimp.Mailchimp(mailchimp_api_key)
mailchimp_api.lists.subscribe(list_id, {
        'email': email
    }, {
        'FNAME': first_name,
        'LNAME': last_name,
        'GROUPINGS': [
            {'id': 123},
            {'id': 456}
        ]
    }
)

EDIT -
The correct way is:
mailchimp_api = mailchimp.Mailchimp(mailchimp_api_key)
mailchimp_api.lists.subscribe(list_id, {
        'email': email
    }, {
        'FNAME': first_name,
        'LNAME': last_name,
        'GROUPINGS': [{
            'id': grouping_id,
            'groups': ('group name 1', 'group name 2',)
        }]
    }
)

Comment: So, the way it works - A confirmation email is sent to the intended recipient. Once the user confirms, then the email is added to the groups.
Comment: Do you mean to say the email is not added to the groups on mailchimp ?
Comment: Yes, the email isn't added to the groups.
Comment: How long after the users confirms will they be added to the groups? In testing, after the user confirms another email is sent to them and doesn't list them as added to any group. Also, in MailChimp I'm not seeing the user added to the groups, which makes me think the code is incorrect.
Comment: i have personally not used the mailchimp api. I use mailsnake, and it works like a charm.
Comment: mailsnake uses the mailchip 1.3 api, which is deprecated. I rather not use a deprecated api.
Comment: hey could you tell me if there is a way to retrieve groups in a list using the api?
Answer: This piece of code may help you:
m = mailchimp.Mailchimp(mailchimp_id)
groupings = [{'name': 'your-group-name', 'groups': ['opt1', 'opt2']}]
merge_vars = {
    'fname': 'first_name',
    'lname': 'last_name',
    'groupings': groupings,
    'GROUPINGS': groupings,
}
m.lists.subscribe(list_id, email, merge_vars=merge_vars, double_optin=False, update_existing=True, replace_interests=True)

Comment: Thanks for the answer, this was helpful.


How do I only render the main content without wrapping it with the theme or side blocks and menus?

Question: I want to output a google map div with a side panel in my drupal 8 moodule. So no need for blocks surrounding my main content.
The question is how do I tell Drupal to only render main content using a Twig template of my module without outputting the entire Drupal theme stuff a long with the menus and the blocks?
All online materials I found so far talks about concepts behind Drupal rendering mechanism and render arrays but none really tell something about their implementation.
Take for instance, the concept of page variants in the following link. HTMLRenderer fires an event to determine which type of page will be used to wrap the main content around:
RenderEvents::SELECT_PAGE_DISPLAY_VARIANT. Its also says the SimplePageVariant, which will only output the main content, is suppose to be used by default but in case the Block module is enabled like my case, the BlockPageVariant kicks in to allow the placement of blocks in the regions around the main content. It continues, if you want, you can subscribe to this event in your own module and provide your own variant. However, I couldn't figure out how to do this subscribing.
I feel what I want is simpler than creating my own Page variant. I just want to output simple html with two divs in the Twig template of my own module.
Anyone has an idea what to do?
Edit
So there are two ways to do this as mentioned in the answer below, I will just summarize them and add a little more clarification of naming convention in drupal 8:
Return a basic Symfony response  with out any drupal specific rendering:
$element['#title'] = 'Title';
$html = \Drupal::service('renderer')->renderRoot($element);
$response = new Response();
$response->setContent($html);
return $response;

Doing so, you will not be able to attach css or js libraries with render arrays. However, if you want to do that you can override the page.html.twig by following dupral 8 template naming conventions link with out returning "pure symfony" response and hindering drupal from finishing its theming.
Answer: There are two similar questions.
Problems creating a custom blank page with my custom module
How to output from custom module without rest of theme
You can use a symfony response or replace the page template with a blank twig in hook_theme().
Comment: Ran into another problem

Using a pure symfony response it seems doesn't allow you to attach assets - JS or CSS files to the render array. Doing so: $build['#attached']['library'] = 'mymodule/my-lib'; with the render array  should output an html head tag and js/css files with the page but the attached library gets neglected for some reason. Then what is inside the twig template only gets printed out, even  is not present.

Tried many things but none worked. My fear is that I might need to use {% block javascripts %} in the twig template, how to reference my js files then?
Any idea?
Comment: By using a pure symfony response there is no html template. From your comment it seems, that you want to keep the html template and only override the page template. Did you try the code in the second question, I mean the question itself, because the OP has updated the code in the question with what was discussed in the comments.
Comment: Thanks for your reply 4k4, but I don't understand what is the difference between the html template and page template. Are you referring to the website general theme vs the module twig template?  In your previous answer what do you mean by: Override page.html.twig and html.html.twig, remove anything out of this templates and put only that in what you want. Where are both files?
Comment: What is really daunting is when using pure symfony response you could still use the twig template of your module and outputting  stuff such as {{ name }} still works but when using {{  attach_library() }} function directly from twig, it gets totally bypassed...
Comment: ... bypassing the theme is why you would use a symfony response. And without a theme you don't have attach_library, but also hundreds of other things. Perhaps you only want to override `page.html.twig`. Normally you do this in the theme. I would start with this, because it is straightforward. To get a feeling for it, remove anything from `page.html.twig`, so you have no menu, no blocks, nothing and put back step by step parts of the original twig. When you have the result you want you can try to move the twig to the module. But you only need this, if you want to distribute it with the module.
Comment: btw. this all has nothing to do with the fact, how you generate your specific html for the google map, this can be twig, php or any other source.
Comment: This is rather a late reply but I had to dig more into template naming convention of drupal 8[ Link ](https://www.drupal.org/node/2354645) to override the page.html.twig template of the current theme. Then I did as mentioned in question 2 in your answer and it worked like magic. Also I was able to attach css and js files. I will edit my question to reflect that but now I cant pass variables to Twig template, really strange!! Any idea. Tried to put the variables ('#name', '#address') in different hierarchical places in the array but still not passing to twig template.
Comment: It seems like you where successful with replacing the page template. In this template your content will show up in the region content by default. How you theme this specific content is up to you. You could simply provide a markup in `array('#markup' => '...')` or build a more complicated render array. This can but must not have a twig template of your own, more often you use the render elements that are already in drupal.
Answer: If you need to render a piece of content with no regions or blocks, but just the piece of content, wrapped in valid HTML, with the ability to attach CSS/JS or whatnot you can do the following. In this example, I am going to wrap a field of a node in proper HTML (HTML tag, head tag, body tag etc), with nothing else at all. This content will be accessible at a route/path, so that it can be used in an iframe.
Situation

Node has: field_description - a textfield that needs to be rendered in a stand alone page
Goal is to render the description, alone as a stand-alone, valid HTML page.

Step 1: Create a route
Create a route that will be used for the description
node.description_raw:
  path: '/node/{node}/description'
  defaults:
    _controller: '\Drupal\example\Controller\Controller::descriptionRaw'
    _title: 'Description'
  requirements:
    _permission: 'access content'
    node: \d+
  options:
    parameters:
      node:
        type: entity:node

This route calls \Drupal\example\Controller\Controller::descriptionRaw() to generate the page response.
Step 2: Build the Controller Response
The next step is to build the controller response:
public function descriptionRaw(NodeInterface $node) {
  $page = [
    // Note - the view mode here is `standalone_description` - a
    // custom view mode (More to come later in the tutorial)
    'description' => $node->field_description->view('standalone_description'),
    // If you need CSS/JS, you can attach the library
    '#attached' => [
      'library' => 'example/description_raw',
    ],
  ];

  return $page;
}

At this point, the page will be rendered with all the regions/content etc, so the requirements aren't yet met.
Step 3: Create a New Page Template for the Standalone Description
The next thing is to create a theme suggestion for the audio player page, that will override the default page.html.twig template. This is done by implementing hook_theme_suggestions_page():
function HOOK_theme_suggestions_page(array $variables) {
  $suggestions = [];
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name == 'node.description_raw') {
    $suggestions[] = 'page__description_raw';
  }

  return $suggestions;
}

Now when accessing the route defined in step 1, the system will look for the template page--description-raw.html.twig in the active theme, and if it exists, it will use that template to render the page, rather than the default page.html.twig.
Step 4: Create the template to render the content
The next step is to create the template used to render the content, as defined in the theme suggestions in the last step. The content of this template is very simple. page--description-raw.html.twig:
{{ page.content }}

This is very simple, as only the content of the page should be rendered, and nothing else. In this case, the content of the page is the description field that was set in the controller.
Step 5: Adjust settings using view modes
There is still likely a lot of unwanted markup around the description from labels. In the controller, the field was set to use the view mode standalone_description. The first step is to create this view mode:

Navigate to Admin -> Structure -> Display modes -> View modes -> Add view mode
Click Content (for nodes)
Enter Standalone Description (machine name standalone_description)
Save

Next, the new view mode must be configured:

Navigate to Admin -> Content types -> [Content Type] -> Manage Display
Scroll to the bottom and expand 'Custom display modes'
Check Standalone Description (the view mode just created)
Save.
Click on the newly created Standalone Description tab
Hide all fields other than the description
Set the label to be 'visually-hidden' (For the sight-impaired)
Set the format to your desired settings
Save

When this is all said and done, the field on the node  is rendered in a stand-alone HTML page, and is customizable through the newly created view mode.


How to get a joint distribution from two conditional distributions?

Question: I have given two conditional distributions $p$ (assuming a conditional deterministic relationship):
$$p(y_1|y_3)=\mathcal{N}(K_{N_1M}K_{MM}^{-1}y_3,0),$$
$$p(y_2|y_3)=\mathcal{N}(K_{N_2M}K_{MM}^{-1}y_3,0),$$
where $y_1\in \mathbb{R}^{N_1}$, $y_2\in \mathbb{R}^{N_2}$, $y_3\in \mathbb{R}^{M}$ and kernel matrices $K_{N_1M}\in \mathbb{R}^{N_1\times M}$, $K_{N_2M}\in \mathbb{R}^{N_2\times M}$, $K_{MM}\in \mathbb{R}^{M\times M}$, where each entry of the kernel matrices is a squared-exponential covariance function. $y$ are function values and e.g. the covariance matrix $K_{MM}$ corresponds to the input values $x_3$ belonging to the output $y_3$
Furthermore, we know $p(y_3)=\mathcal{N}(0,K_{MM})$.
The question now is how to get the joint distribution $p(y_1,y_2)$ under the assumption that we have conditional independence of $y_1,y_2$ given $y_3$.
What I know so far is that I can write:
$$p(y_1,y_2)=\int p(y_1,y_2|y_3)p(y_3)dy_3 =\int p(y_1|y_3)p(y_2|_3)p(y_3)dy_3$$
where the second equation holds due to the additional assumption of conditional independence.
The solution (and here is the missing step I don't understand) should be
$$p(y_1,y_2)=\mathcal{N}(0,\begin{bmatrix}
    K_{N_1M}K_{MM}^{-1}K_{MN_1} & K_{N_1M}K_{MM}^{-1}K_{MN_2}  \\
    K_{N_2M}K_{MM}^{-1}K_{MN_1} & K_{N_2M}K_{MM}^{-1}K_{MN_2}
    \end{bmatrix}).$$
I tried to solve the integral by plugging in the density functions of the normal distributions, but since the two deterministic probabilities don't have a density I don't know how to solve it.
Thanks a lot in advance!
Answer: It's a lot easier to think about the random vectors $y_i$ directly than about their density functions.  You have $y_1=Ay_3$, $y_2=By_3$, and  $y_3\sim N(0,M)$, for certain matrices $A$, $B$, and $M$. So $y_1$ and $y_2$ are jointly normal. The expectations of $y_1$ and $y_2$ are $AEy_3 = 0$ and $BEy_3= 0$, respectively. The covariance matrix of $y_1$ is $AMA^T$, that of $y_2$ is $BMB^T$ and the cross covariance matrix of $y_1$ and $y_2$ is $AMB^T$.  In more detail, it is the expectation of $y_1 y_2^T $, that is, of $Ay_3 (By_3)^T = Ay_3 y_3^T B^T$.  Since the covariance matrix of $y_3$ is $M$, $E y_3 y_3^T=M$, and thus the cross covariance matrix is $AMB^T$.  So your big  covariance matrix is $$\pmatrix{AMA^T&AMB^T\\BMA^T&BMB^T},$$ which is your expression when written out in full.
Comment: Great, thanks a lot! It's much easier like this. But it's not working anymore if I don't have the assumption of deterministic conditional probabilities, right? If e.g. the Covariance of $p(y_1|y_3)=F$ for a matrix F. How could I manage this?
Comment: More generally you could model $y_1 = Ay_3 + z$ where multivariate gaussian $z$ is conditionally independent of $y_3$ .  Then the covariance of $y_1$ and $y_3$ is (in my notation) $AM$ which is your $F$, and so on, and the variance of $y_1$ is then  $AMA^T+S$ where $S$ is the covariance of $y_3$, etc.


Fazer lâmpada acender e apagar

Question: eu estou estudando javascript e fiz um exercício onde tenho uma imagem de uma lâmpada apagada onde ao clicar ele troca a lâmpada colocando uma acesa, como se estivesse acendendo uma lâmpada, porém estou na dúvida não sei como fazer a mesma trocar a imagem para fazer o efeito de apagar novamente. Segue o código abaixo de como implementei.

Comment: Por favor, marque uma das resposta com ✓. Não deixe a pergunta em aberto. MArque ✓ na resposta que resolveu seu problema.
Answer: Você pode fazer desta forma

function ligarDesliga(){

    var imagem = document.getElementById('lamp').src;
    var imagem_ligado = 'https://www.w3schools.com/js/pic_bulbon.gif';
    var imagem_desligado = 'https://www.w3schools.com/js/pic_bulboff.gif';

    if(imagem == imagem_ligado){
     document.getElementById('lamp').src = imagem_desligado;
    }else{
     document.getElementById('lamp').src = imagem_ligado;
    }
}
document.getElementById("lamp").addEventListener("click", ligarDesliga);
#lamp{
  cursor: pointer;
  cursor: hand;
}

HTML

JavaScript
Isso é só para deixar o cursor da mesma forma de um link "maozinha", para o usuário entender que é possível clicar naquela imagem.
#lamp{
  cursor: pointer;
  cursor: hand;
}

JavaScript
function ligarDesliga(){

    var imagem = document.getElementById('lamp').src;
    var imagem_ligado = 'images/lampada-on.jpg';
    var imagem_desligado = 'images/lampada-off.jpg';

    if(imagem == imagem_ligado){
        document.getElementById('lamp').src = imagem_desligado;
    }else{
        document.getElementById('lamp').src = imagem_ligado;
    }
}
document.getElementById("lamp").addEventListener("click", ligarDesliga);

Criei um evento click para o id "lamp" e a função "ligarDesliga" verifica qual imagem esta presente na tag e a altera, fazendo o efeito de liga e desliga.
Update

Outro exemplo do w3 Tryjs Intro Lightbuld
Comment: Obrigado @VirgilioNovic, eu não sabia que este recurso se chamava Snippet, quando o "Jefferson" me falou isso, pesquisei aqui no google o significado e entendi que era outra coisa.
Comment: Eu acho que fica melhor por como snippet do que referência externa...
Comment: Agora a lampada esta feia, mas é a mesma rsrs.
Comment: Eu coloquei no próprio Snippet !!!
Comment: Aproveitando, os soquetes das lâmpadas apagada e ligada são distintos xD Pode me chamar de louco, mas me chamou a atenção imediatamente quando eu vi
Comment: Fiz exatamente como você fez ai nesse código, porém ao trocar o endereço das imagens para as minhas que estão no diretório ele mostra um erro no console e não dá certo. Clico para acender a lâmpada e ela acende, porém quando clico novamente para apagar, não funciona e aparece um erro.
Comment: Qual é o erro que aparece?
Answer:
Let`s Go!

$('.cube-switch .switch').click(function() {
    if ($('.cube-switch').hasClass('active')) {
        $('.cube-switch').removeClass('active');
        $('#light-bulb2').css({'opacity': '0'});
    } else {
        $('.cube-switch').addClass('active');
        $('#light-bulb2').css({'opacity': '1'});
    }
});
body {
  background: rgb(70, 72, 75);
}

/* SWITCH */
.cube-switch {
    border-radius:10px;
    border:1px solid rgba(0,0,0,0.4);
    box-shadow: 0 0 8px rgba(0,0,0,0.6), inset 0 100px 50px rgba(255,255,255,0.1);
    /* Prevents clics on the back */
    cursor:default;
    display: block;
    height: 100px;
    position: relative;
    margin: 5% 0px 0px 10%;
    overflow:hidden;
    /* Prevents clics on the back */
    pointer-events:none;
    width: 100px;
    white-space: nowrap;
    background:#333;
}

/* The switch */
.cube-switch .switch {
    border:1px solid rgba(0,0,0,0.6);
    border-radius:0.7em;
    box-shadow:
    inset 0 1px 0 rgba(255,255,255,0.3),
    inset 0 -7px 0 rgba(0,0,0,0.2),
    inset 0 50px 10px rgba(0,0,0,0.2),
    0 1px 0 rgba(255,255,255,0.2);
    display:block;
    width: 60px;
    height: 60px;
    margin-left:-30px;
    margin-top:-30px;
    position:absolute;
    top: 50%;
    left: 50%;
    width: 60px;

    background:#666;
    transition: all 0.2s ease-out;

    /* Allows click */
    cursor:pointer;
    pointer-events:auto;
}

/* SWITCH Active State */
.cube-switch.active {
    /*background:#222;
    box-shadow:
    0 0 5px rgba(0,0,0,0.5),
    inset 0 50px 50px rgba(55,55,55,0.1);*/
}

.cube-switch.active .switch {
    background:#333;
    box-shadow:
    inset 0 6px 0 rgba(255,255,255,0.1),
    inset 0 7px 0 rgba(0,0,0,0.2),
    inset 0 -50px 10px rgba(0,0,0,0.1),
    0 1px 0 rgba(205,205,205,0.1);
}

.cube-switch.active:after,
.cube-switch.active:before {
    background:#333;
    box-shadow:
    0 1px 0 rgba(255,255,255,0.1),
    inset 1px 2px 1px rgba(0,0,0,0.5),
    inset 3px 6px 2px rgba(200,200,200,0.1),
    inset -1px -2px 1px rgba(0,0,0,0.3);
}

.cube-switch.active .switch:after,
.cube-switch.active .switch:before {
    background:#222;
    border:none;
    margin-top:0;
    height:1px;
}

.cube-switch .switch-state {
    display: block;
    position: absolute;
    left: 40%;
    color: #FFF;

    font-size: .5em;
    text-align: center;
}

/* SWITCH On State */
.cube-switch .switch-state.on {
    bottom: 15%;
}

/* SWITCH Off State */
.cube-switch .switch-state.off {
    top: 15%;
}

#light-bulb2 {
width: 150px;
height: 150px;
background: url(https://lh4.googleusercontent.com/-katLGTSCm2Q/UJC0_N7XCrI/AAAAAAAABq0/6GxNfNW-Ra4/s300/lightbulb.png) no-repeat 0 0;
}

#light-bulb {
position: absolute;
width: 150px;
height: 150px;
top: 5%;
left: 40%;
background: url(https://lh4.googleusercontent.com/-katLGTSCm2Q/UJC0_N7XCrI/AAAAAAAABq0/6GxNfNW-Ra4/s300/lightbulb.png) no-repeat -150px 0;
cursor: move;
z-index: 800;
}

            Off
            On

Answer: Acredito que isso faça o que você precisa:
function liga_desliga(){

    const lamp = document.querySelector('#lamp');

    var src = ['lampada-on.jpg','lampada-off.jpg']
        .filter((value) => {
            var a = lamp.src.match(/\/(lampada-.+)/i)[1];
            return value != a;
        })[0];
    lamp.src = `images/${src}`;

}

Comment: Fazer só com CSS é uma opção para vc ou como vc está estudando tem que ser com Script mesmo?
Comment: Eu estou estudando javascript mesmo puro e não jQuery
Answer: Você pode fazer um código parecido com o meu para alterar a imagem da lâmpada.

<button onclick="ligaDesliga()"></button>

Answer: Uma forma bem simples e enxuta de fazer isso:

function ligarApagar(e){
   e.src = "images/lampada-"+( ~e.src.indexOf("-on") ? "off" : "on" )+".jpg";

   // daqui pra baixo é apenas exemplo para mostrar o texto
   // pode apagar
   document.querySelector("b").textContent = e.src;

}

 https://stacksnippets.net/images/lampada-on.jpg

<button type="button" id="controle" onclick="ligarApagar(document.getElementById('lamp'))">Ligar/Apagar</button>

Fazer lâmpada acender e apagar


Showing infimum of distance is attained

Question: I have a continuous map $f: X \to X$ on a compact metric space and I am trying to show that $inf \{ d(x,f(x)) : x \in X \}$ is attained.
My thoughts so far are to use sequential compactness to obtain a sequence of points $x_n$ so that $d(x_n, f(x_n))$ tends to the infimum, but I'm struggling to make anything of this.
Thanks for any help
Answer: Hint: $x \mapsto d(x,f(x))$ is continuous.
Comment: Oh and a continuous function on a compact set is bounded and attains its bounds, thanks!

Showing infimum of distance is attained


Increasing game's system compatibility

Question: I wrote this game on my windows 8, in visual studio 2013, C#. I am now trying to get it to run on an older system that can only run up to .net framework 3.5. I wrote it using a monogame template, and i don't mind if i have to change the code.
so far i've tried lowering the target .net framework to 3.5. The compiler didn't like that, and wouldn't let me use the xna framework 22.214.171.124, so I found an old dll of xna framework 220.127.116.11 and used that. the compiler accepted it, but so many of the classes that I was using before don't exist in that version.
I have been unable to find any version of the xna framework that runs with .net framework 3.5, or think of any solution that doesn't involve changing the xna framework. If someone could point me in the right direction, or give me access to the newest version of the xna framework that works with .net framework 3.5, that would be great.
Answer: Why not install .NET framework on that system? In most cases you need to make your game ship with .NET 4.0 or above to use xna on that old system. Since MonoGame is cross-platform you can also spread it across Linux and Mac OSX.
A side note: XNA has been discontinued in favour of DirectX. I used it before, but now I see at as a lost clause.
Either go Mono framework all the way or choose from other frameworks, such as ANX, OpenTK. Although i'm not a huge fan of it, I can also suggest trying Unity.
Comment: Seeing as even Windows XP is able to run .NET Framework 4.0, what could this system possibly be running that would be able to play your game?
Comment: that system is unable to run anything higher than 3.5, so i have to resort back to a low version of xna.

Increasing game's system compatibility


Ember.js + socket.io

Question: I really could use some pointers in the right direction.
I'm new to Ember.js, but I'm eager to use it for my game.
Background: I'm creating a multiplayer html5 (mostly textbased) game in Node.JS + Socket.io.
What I want to achieve:

Application wide: load and keep the player data updated
On the "homepage" (index view): load and keep a list of active games

On the backend I'm emitting two things:

the player data: socket.emit('player data', data);
a list with active games: socket.emit('available games', data);

Displaying the player data was easy. My template has a {{userName}} and {{balance}} placeholder.
I'm using the following code to display the actual userName and balance:
App.ApplicationRoute = Ember.Route.extend({
    setupController: function (controller) {
        var socket;

        socket = io.connect();

        controller.set('socket', socket);
    }
});

App.ApplicationController = Ember.Controller.extend({
    userName: null,
    balance: null,
    playerDataChanged: function () {
        var socket, self;

        socket = this.get('socket');
        self = this;

        socket.on('player data', function (player) {
            console.log(player);
            self.set('userName', player.username);
            self.set('balance', satoshiToMBTC(player.balance));
        });
    }.observes('socket')
});

This works fine. I'm now trying to the same for the list with actual games. But I honestly have no clue how I would do this.
If I create a games model it keeps trying to do: GET  127.0.0.1:5555/games 404 (Not Found). Of course this won't work since I don't have a REST api, but I'm emitting live data.
So to recap:
My server is emitting an array with game objects containing information on those games. I want to loop over those games and display them to the user.
Can anyone point me in the right direction? I looked at the first 5 pages on Google for "ember.js + socket.io" but I just can't seem to get it work.
Comment: Have you tried EmberSockets? (https://github.com/Wildhoney/EmberSockets)  It allows you to bind a controller function to a socket.io channel.  Anytime an event is received on a specific channel a function in your controller is called and is passed the socket.io data.  You could then take that data and add it to your ArrayController model to display all the games.
Comment: The short short version of what I need to say is: this paradigm won't really work. Ember.js displays certain data at certain times, and there's no guarantee that it will be displaying your data when your socket.io event is happening. You need to make the data available to Ember.js _when it requests the data_. I think that if you start with an Ember-Data model and the Ember-Data fixture adapter (without your socket.io server), the way Ember.js works will become a bit more clear to you.
Answer: There's a good example of sockets and ember.js in this EmberConf 2015 talk, it uses a new approach of using services
Answer: There is a good enough package: ember-websockets
Step by step:
1. Install:
ember install ember-websockets

2. init socket-io:
ember g socket-io

3. write route/component/controller:
import Ember from 'ember';
export default Ember.Route.extend({
    socketio: Ember.inject.service('socket-io'),

    myThisActivationHandler() {
        const socket = this.get('socketio').socketFor('http://localhost:7000/');
        socket.on('connect', this.onConnect, this);
        socket.on('message', this.onMessage, this);
    },

    onConnect(data) {
        const socket = this.get('socketio').socketFor('http://localhost:7000/');
        socket.send('Hello World');
    },

    onMessage(data) {
        // This is executed within the ember run loop
        this.set('messageTextOrSomethingElse', data);
    },

    myThisDestroyHandler() {
        const socket = this.get('socketio').socketFor('http://localhost:7000/');
        socket.off('connect', this.onConnect);
        socket.off('message', this.onMessage);
    }
})

Ember.js + socket.io


PHP redirect when URL is not requested through ajax (when on a wordpress page)

Question: I have a Wordpress website with Domain: Hello.com which is "ajaxified".
what I want to know is how to redirect user back to Hello.com if they visit Hello.com/ask,  Hello.com/cake or anything deeper using the browser address bar.
Even if they go 2 degrees deeper like Hello.com/cake/make, I want them to stay at the root of my website.
I am using Wordpress and my first Idea was to put redirect script at header, but ended up making an infinite redirect loop.
How can I redirect users to homepage without redirecting my ajax requests to the homepage as well?

[If you ask why I would disallow them to go deeper, the answer is: I
  am using ajax to load deeper pages and everything else into a div]
Comment: Look into htacess http://stackoverflow.com/tags/.htaccess/info
Comment: @Stefan that's what robots.txt is for.
Comment: It might be admin interfaces or another type of web application which isn't supposed to be searchable by SE.
Comment: @user2128576 htaccess also has exclude rules.
Comment: As far as I know, the least effort is to use rewrite rules in htaccess.  Otherwise you could put a redirect into each index.xyz page, using one of various ways: meta refresh, javascript window.location, php Header('Location: ') etc. Then rename the pages you load via ajax so that they aren't named index.xyz
Comment: @raam86 Yes, that works too, but it's not quite what I was looking for since wordpress works differently, if I use htaccess, I migh not even be able to access the backend.

I'd like to do this the wordpress-friendly way :)
Comment: @Ohgodwhy I was responding to a now deleted comment which said that the OP is building a SE unfriendly site.
Comment: @Stefan Yes I am aware, thanks. I will add robots.txt for it, but the question is how do I redirect?
Comment: possible duplicate of [.htaccess redirect in wordpress](http://stackoverflow.com/questions/16596775/htaccess-redirect-in-wordpress)
Comment: @raam86 You're probably right. Thought of it after reading your comment. True, htaccess would be a good choice for doing it, but I remember having static pages that aren't part of wordpress which I would allow users to go to, and some pdf files viewable on browser. >__> The hell, it's getting really complex. I'd have to list it all, isn't there any other way to do this dynamically and apply it to wordpress pages only?
Comment: I think, if you have are using Apache and have access to httpd.conf, you can also specify redirects there.
Comment: The question has been modified to be more helpful to site visitors. Some comments may no longer make sense, and I am sorry for the ambiguity in my question. (I was new and unprofessional back then.)
Answer: By adding a short PHP script somewhere before everything else, I was able to check how my pages were loaded using the condition below.
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')

It allowed me to check through PHP if it was through Ajax or not.
The value of $_SERVER['HTTP_X_REQUESTED_WITH'] is xmlhttprequest when the request was an ajax request.
For my case, this is how I used it:
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    header("Location: http://". $_SERVER['HTTP_HOST']."/");
}

Which would check if the request was done through ajax, and redirect to the homepage/Main Screen of the website/web App if not.
I got the idea after reading this post

Note: Usage of HTTP_X_REQUESTED_WITH depends on the JavaScript framework you are using, if it sets that header. I am using jQuery and it does it for you.
Also $_SERVER is not entirely a part of PHP so it also depends if your server passes that variable to PHP.
If you are on a Nginx Server and it doesn't work for you, you can try this:
Passing HTTP_X_REQUESTED_WITH from nginx to php
Hope this helps others!


IIS 7.5 not logging

Question: I have a strange issue with a Windows Server 2008 R2 running IIS: HTTP logging stopped a few months ago (I just found out), and I cannot seem to get it to start logging again.
I have both HTTP Logging and Logging Tools installed (under Web Server/ Health and Diagnostics) and under IIS Manager > Logging, it is enabled (One log per: Site, Format: W3C, Directory: "%SystemDrive%\inetpub\logs\LogFiles", etc. - all default stuff).
Yet under C:\inetpub\logs\LogFiles\W3SVC1 / W3SVC2avalanche, etc., all files are months old.
I have also restarted the server, to no avail.
I tried to disable logging and then enable it again (in IIS Manager), but that did not help.
Lastly, I tried to enable via command-line (even though already enabled):
C:\Windows\System32\inetsrv>appcmd set config /section:httpLogging /dontLog:False /selectiveLogging:LogAll

Applied configuration changes to section "system.webServer/httpLogging" for "MACHINE/WEBROOT/APPHOST" at configuration commit path "MACHINE/WEBROOT/APPHOST"

What I am missing??
Comment: I got this working.  In the event log, I found this: "Owner of the log file or directory C:\inetpub\logs\LogFiles\W3SVC2\u_ex140606.log is invalid. This could be because another user has already created the log file or the directory."  So I checked the owner of the logs folder, etc., and for some reason it was set to "Trusted Installer" instead of what it should have been: C:\inetpub\logs should be owned by SYSTEM and its sub folders owned by the Administrators group.  After fixing this, it started working.
Comment: Have you verified that permissions are still good? How about the file system space?
Comment: @kce Disk space is fine.  Re. folder permissions, I am not 100%:  I just gave IIS_IUSRS Full Control to C:\inetpub\logs and restarted the site, but that did not help.  What should the permissions be (and on what specific folders are you supposed to set them - just the logs folder?)?
Comment: @JimBalo it would be good to convert this to an answer to make it easier to see.
Answer: I know this is an old post (I'm a necromancer)! I found my way here in desperation via Google, and I believe that, at least on our server, the problem was that the "W3C Logging Service" in services.msc was stopped. Upon restarting it, the service worked fine (provided the proper folder permissions were in place, as described above). It appears that the problem our GMT -08:00 server ran into was this one:
https://support.microsoft.com/en-us/help/2982169/w3c-logging-service-crashes-in-iis-8.5-on-a-server-in-windows-8.1-or-windows-server-2012-r2
There is an update able to be downloaded within. Hope this helps someone.
Answer: Check you permission on log file folders.  IIS will not write to folders owned by certain groups, such as users.
The folder should be owned by "Administrators" or "SYSTEM".
Answer: The Logging feature is managed in IIS UI on 3 levels: machine, site, application.
I had it enabled on the machine level, disabled on the site level (Default Web Site) level, and enabled on the the application level.
Once I enabled it (in the Actions pane on the right side) for the site, it started working.
Answer: When I come across the issue I delete the W3SVC1 folder and browse to the site so that IIS creates a new W3SVC1 folder with the correct SYSTEM owner and permissions.
Comment: This is basically the answer @Zamicol has but another solution. If you do not wish to delete the current folder(s), simply edit the owner by right-clicking the folder-> Properties->Security->Advanced, click change next to owner, and enter "system" as the object name.

IIS 7.5 not logging


Average of a game of dice best of three

Question: In a game of dice, I throw a 20 sided dice (values from 1 to 20) three times. My result is the best of three.
For example, if I get the values 4, 16, and 7, my result is 16. If I get the values 14, 1, and 3, my result is 14.
What is the average result (or "payoff" if I understand the notation correctly) of the game?
An explanation would be appreciated.
Answer: The probability that $n$ is the largest of three rolls is the probability that each roll doesn't contain numbers greater than $n$ multiplied by the probability $n$ has been selected at least once given there are no larger numbers:
$$P(\text{max}(\{N_1,N_2,N_3\}) \leq n)
=P\left(\left(N_1\leq n\right)
\land \left(N_2\leq n\right)
\land \left(N_3\leq n\right)\right)
\times P\left(\left(N_1 = n\right)
\lor \left(N_2 = n\right)
\lor \left(N_3 = n\right)
|\left(N_1\leq n\right)
\land \left(N_2\leq n\right)
\land \left(N_3\leq n\right)\right)$$
$$\begin{align}P_1&=P\left(\left(N_1\leq n\right)
\land \left(N_2\leq n\right)
\land \left(N_3\leq n\right)\right) \\
&= \left(\frac{n}{20}\right)^3\end{align}$$
$$\begin{align}
P_2 &= P\left(\left(N_1 = n\right)
\lor \left(N_2 = n\right)
\lor \left(N_3 = n\right)
|\left(N_1\leq n\right)
\land \left(N_2\leq n\right)
\land \left(N_3\leq n\right)\right)\\
&= 1 - \left(\frac{n-1}{n}\right)^3
\end{align}$$
so for dice with $m$ sides,
$$\begin{align}E(\text{max}(\{N_1,N_2,N_3\}) &= \sum_{x=1}^{m}x\times\left(\frac{x}{m}\right)^3\left(1 - \left(\frac{x-1}{x}\right)^3\right)\\
&= \frac{(m+1) ( 3 m -1)}{4 m}, (\text{according to WolframAlpha})\\
\end{align}$$
for $m=20$,
$$\begin{align}E(\text{max}(\{N_1,N_2,N_3\})&=\frac{1239}{80}\\
&=15.4875\end{align}$$
Disclaimer: I'm not 100% sure if this is correct, perhaps someone could correct me if it isn't.
Answer: A slightly different way to solve, but essentially the same result:
Using the Layer Cake theorem, $E[X] = \sum_{x=1}^{max(X)} P(X\geq x)$. Thus, we need to find $P(X \geq x)$. By the Principle of Inclusion and Exclusion, this is: $$\begin{align}P(X \geq x) &= P(X_1\geq x) + P(X_2\geq x) + P(X_3\geq x) \\&\quad- P(X_1\geq x)P(X_2\geq x) - P(X_1\geq x)P(X_3\geq x)-P(X_2\geq x)P(X_3\geq x) \\&\quad +P(X_1\geq x)P(X_2\geq x)P(X_3\geq x)\\
&= 3*\frac{21-x}{20}-3*\left(\frac{21-x}{20}\right)^2+\left(\frac{21-x}{20}\right)^3\\
&=3*\frac{21-x}{20}*\left(1-\frac{21-x}{20}\right)+\left(\frac{21-x}{20}\right)^3\\
&=3*\frac{21-x}{20}*\left(\frac{x-1}{20}\right)+\left(\frac{21-x}{20}\right)^3\end{align}$$
, where $X_i$ is the $i^{th}$ throw. Thus $E[X] = \sum_{x=1}^{20}3*\frac{21-x}{20}*\left(\frac{x-1}{20}\right)+\left(\frac{21-x}{20}\right)^3 = 15.4875$

Average of a game of dice best of three


Install Logcheck / Logtail in Rocky Linux 8

Question: I need to install logtail / logcheck in Rocky Linux 8. We have an application that uses it and we are migrating that from Centos 7 to Rocky 8.
Yum doesn't find it.
<code>[root@myserver ~]# yum provides logtail
Last metadata expiration check: 0:37:59 ago on Mon 15 Nov 2021 12:43:04 PM CET.
Error: No Matches found

[root@myserver ~]# yum repolist
repo id                                          repo name
appstream                                        Rocky Linux 8 - AppStream
baseos                                           Rocky Linux 8 - BaseOS
epel                                             Extra Packages for Enterprise Linux 8 - x86_64
epel-modular                                     Extra Packages for Enterprise Linux Modular 8 - x86_64
extras                                           Rocky Linux 8 - Extras
powertools                                       Rocky Linux 8 - PowerTools
virtualmin                                       RHEL/CentOS 8 - x86_64 - Virtualmin
virtualmin-universal                             Virtualmin Distribution Neutral Packages
</code>
I can see EPEL is already added. Any help will be much appreciated.
Answer: I downloaded from source and compiled it to run on Rocky Linux 8.


Erro ao utilizar o método File.Delete dentro da Controller

Question: Estou com problemas em minha controller no momento em que inicio uma rotina de exclusão de arquivos.
Eu estou utilizando o método File.Delete(), porem ele simplesmente não reconhece e me retorna a seguinte advertência:

Cannot choose method from method group. Did you intend to invoke the method?

Segue o código também:
public void Delete(String id)
{
    //Função que busca o meu arquivo de delete
    var modelArquivo = BuscaArquivo(id);

    //Aqui se atribue o nome completo do arquivo
    var nomeArquivo = modelArquivo.NomeArquivoCompleto;

    //Aqui da-se a advertência citada acima
    File.Delete(nomeArquivo);
}

Alguma ideia sobre o que está a acontecer?
Answer: Já tentou usar no lugar de
//Aqui da-se a advertência citada acima
File.Delete(nomeArquivo);

Usar
System.IO.File.Delete(nomeArquivo)

Answer: Está me parecendo conflito de namespace. Você poderia testar com:
System.IO.File.Delete(nomeArquivo)


how to collapse my div panel in jquery

Question: When I click on outside my expanded div this div should be close.
I have html code like

Welcome to jquery demo

Welcome to jquery demo

Welcome to jquery demo

Welcome to jquery demo

Welcome to jquery demo

            <button class="sc-button g-opacity-transition sc-button-large loginButton" tabindex="0">Log in</button>

Hello Guest!

|

                More Info
                Close Panel

js code
$(document).ready(function() {

    // Expand Panel
    $("#open").click(function(){
        $("div#panel").slideDown("slow");

    });

    // Collapse Panel
    $("#close").click(function(){
        $("div#panel").slideUp("slow");
    });

    // Switch buttons from "Log In | Register" to "Close Panel" on click
    $("#toggle a").click(function () {
        $("#toggle a").toggle();
    });

});

how can i also close that expanded div when i clicked outside area also.
Comment: Where is panel div HTML?
Answer: You can add a handler to the document since the click event is not a "flooding" one ...
=> Test whether the event.target was '.close'
$(document).on('click','.close', function(eventObject){
  $('#panel').slideUp("slow"); // useful if you want to put several buttons all over the your content
});

=> Or simply is the event.target outside your panel
Jsfiddle here
(Try not to attach too many greedy handlers to the document to keep your browser reacting fast.)
Answer: You can use focusout()
 $("div#panel").focusout(function(){
        $(this).slideUp("slow");
    });

Bind an event handler to the "focusout" JavaScript event.
See fiddle here
Answer: How about handling the event at the document level:
$(document).click(function(e){
    if (event.target.id == "open") {
        $("div#panel").slideDown("slow");
    }
    else if (event.target.id == "close") {
        $("div#panel").slideUp("slow");
    }
    else {
        $("div#panel").slideUp("slow");
    }
});

Working fiddle: http://jsfiddle.net/VC9eT/
Answer: I have used the following:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

HTML Area:

Section 1

    Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
    ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
    amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
    odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

Section 2

    Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
    purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
    velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
    suscipit faucibus urna.

Section 3

    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.

List item one

List item two

List item three

Section 4

    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.

    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.

jQuery documentation link:
https://jqueryui.com/accordion/

how to collapse my div panel in jquery