How to mock ResultSet.next() method using Mockito

Question: I am mocking java.sql.ResultSet like this
ResultSet rs = mock(ResultSet.class);
when(rs.next()).thenReturn(true); // this seems wrong appraoch

Test code is like this
while (rs.next()) {
  // doing stuff here
}

So problem is when I have mock rs.next() to true then while loop never terminates. I want to terminate while loop after 2 iteration. So how i can mock rs.next() method?
I have also tried
when(rs.next()).thenReturn(true, true, false); // always return false

Please help!
Answer: You can chain doReturn() method calls:
doReturn(true).doReturn(true).doReturn(false).when(rs).next();

Or, as mentioned in the comments, chain thenReturn method calls:
when(rs.next()).thenReturn(true).thenReturn(true).thenReturn(false);

Or, if you want to take things even further, you can use Mockito Answers:
when(rs.next()).thenAnswer(new Answer() {
    private int iterations = 2;

    Object answer(InvocationOnMock invocation) {
        return iterations-- > 0;
    }
});

Comment: You can also chain thenReturn: when(rs.next()).thenReturn(true).thenReturn(false)
Comment: Just tested locally using Mockito 1.10.19. My code works as expected.
Comment: Your both approaches are behaving same as  : when(rs.next()).thenReturn(true, true, false); which is not working case :(
Comment: it always takes last value as a resultant thenReturn ?
Comment: ok, your code technically looks fine to me as well but I was telling some how may be i am missing something and can't figure out :(
Answer: Try
when(rs.next()).thenReturn(true).thenReturn(true).thenReturn(false);

Comment: i am getting false on rs.next() every time :( not worked
Comment: Works for me with Mockito 2.0.2 beta. If you're still stuck, maybe you should edit your question to append the full test with your attempted fixes, and mention the version of Mockito in case someone knows about a bug.
Comment: I have used your approach in a different test it works fine but in this specific scenario it doesn't. I guess i am missing something! dont know what :(
Answer: While other answers are technically correct (if doesn't work in your code then maybe something else is in play and more code is needed). They all miss a vital point:
You should not mock JDBC classes but instead create an integration test with a real database behind. Also beware ResultSet is indeed an interface but drivers / DB may have some differences in behavior. Such test that are mocking those, makes developers blind to real production behaviors.
And if this code is just about handling data that is returned not the actual JDBC invocation code, then this code should be decoupled of JDBC classes in that ResultSet should not be imported. In the long run it helps to split technical code from business code.
Comment: hmm, i think u r right . I have used MockResultSet of mockrunner lib. its works fine but i cant do other major things with that.
Comment: I'm not disagreeing with the need for integration tests, but saying that you **only** need integration tests for cases like this is a bridge too far. It is completely possible that lower-level DAO-type code is expected to behave differently in case a different number of results is returned (e.g. throw an exception if multiple records are returned). Testing that behavior using a unit test makes complete sense.
Comment: @RobbyCornelissen Yes of course there's always some good reason to not follow such guidelines, but this is usually very narrow cases ; this doesn't appear to be one here. Anyway, even for the case you mention, implementors or different versions may fail differently and in unexpected ways, depending on the proper conditions. Testing such conditions may prove really challenging, additional mocking here with a DB behind may give a false sense of security. External systems are much more tricky to test correctly and securely than we use to think, and mocking is rarely if at all part of it.
Answer: when(rs.next()).thenReturn(true, true, false);

this should work.
i find an example from the javadoc of 'mockito-core:1.10.19'.
take a look at this:
org.mockito.Mockito.when


Wordpress: depois do redirecionamento os cookies desaparecem

Question: eu fiz um simples redirecionamento com
<code>wp_redirect(home_url());
exit();
</code>
E depois disso os cookies são limpos (a session também), o que não poderia acontecer, como persistir os cookies depois do redirecionamento?
Pelo que vi parece ser o exit() o problema, mas sem ele o direcionamento não acontece.
Obrigada.
Answer: O problema era que eu tinha páginas que estavam como localhost, e outras com o ip local, assim nessas trocas era identificado como diferentes domínios e limpado as variáveis de cookies e sessão. Padronizei as urls para usar todas o mesmo ip ("dominio") e as variáveis persistiram ao navegar pelas páginas.


Adicionar loader no ajax

Question: Como posso adicionar um loader na requisição do meu ajax?
<code>$(document).on('click', '#reg-discagem input[type="submit"]', function(e){

                  e.preventDefault();
var form = $('#reg-discagem');
            $.ajax({
                url: 'EnviarPedidoChamada.php',
                type: 'POST',
                data: form.serialize()
            })
            .done(function(data){
                $('#form-content_discagem').fadeOut('slow', function(){
                    $('#form-content_discagem').fadeIn('slow').html(data);
                });
            })
            .fail(function(){
                alert('Ajax Submit Failed ...');
            });
});
</code>
Comment: coloque o html do seu formulário. assim fica um pouco mais fácil responder a pergunta
Answer: Usando ajax é mais dificil mesmo, eu particulamente prefiro usar o jquery form
Esse é o link da documentação
https://github.com/jquery-form/form
O código para enviar, ficaria assim...
<code>$('#material_form').ajaxForm({

  beforeSend: function() {
     // $("#material_form").fadeOut(0);
     // $("#carregando_envio_material").fadeIn(0);
     // $("#progresso_envio_mateial").html("0%");
     //$("#msg_erro_envia_material").html("");
  },
  uploadProgress: function(event, position, total, percentComplete) {

  //aqui fica a % do load.... voce pode dar o fadin e fad outa nas divs para

  //aparecer so a partocentagem
  //$("#progresso_envio_mateial").html(percentComplete+"%");
  console.log(percentComplete);

  },
  success: function() {

  },
  complete: function(xhr) {

    //status.html(xhr.responseText);
    data = xhr.responseText;
    console.log(data);

    if(data == "sucesso"){

    }else{

    }
  }
});
</code>
qualquer coisa, se essa não for a documentação correta
esse é o link do meu escript
http://b1.alunoativo.com.br/publico/js/sistema/jquery.form.js
copia o codigo e cria a nos seus arquivos que vai fucionar
Answer: Boa tarde,
Consegui desta forma em minha aplicação.
http://blog.astraube.eti.br/2012/04/exibir-loading-nas-requisicoes-ajax/
Comment: O ideal seria responder a pergunta aqui mesmo. O link pode vir a quebrar.

Adicionar loader no ajax


Java game loop (painting) freezes my window

Question: I'm changing "views" with cardLayout (this class has a JFrame variable). When a user clicks a new game button this happens:
public class Views extends JFrame implements ActionListener {

    private JFrame frame;
    private CardLayout cl;
    private JPanel cards;
    private Game game;

    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if (command.equals("New game")) {
            cl.show(cards, "Game");

            game.init();
            this.revalidate();
            this.repaint();

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    game.loop();
                }
            });
        }
    }
}

Game's loop method and heading of class:
public class Game extends JPanel implements KeyListener {
    public void loop() {
        while (player.isAlive()) {
            try {
                this.update();
                this.repaint();
                // first class JFrame variable
                jframee.getFrame().repaint();
                // first class JFrame variable
                jframee.getFrame().revalidate();
                Thread.sleep(17);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void update() {
        System.out.println("updated");
    }
}

I'm painting using paintComponent()
public void paintComponent(Graphics g) {
    System.out.println("paint");
    ...
}

Actually it's not painting anything. When I do not call loop() method (so it paints it just once) all images are painted correctly. But when I call loop() method, just nothing is happening in the window. (Even close button on JFrame doesn't work.)
How to fix that? (When I was creating JFrame inside game class everything worked fine, but now I want to have more views so I need JFrame in other class.)
Thanks.
Comment: You either blocking the event dispatching thread or breaking the chain or both
Comment: well.. is player really alive? try changing it to `while(true)` for test
Comment: The main question is, what thread(s) is all this stuff running on? Are you launching separate worker threads to do some of this? Where are you calling `revalidate()` and `paint()` from? What thread is the main game loop running on? All AWT stuff needs to happen on the EDT, and the rest of your work needs to happen off it. Sounds like an AWT threading issue. Reviewing an AWT/Swing tutorial should help; they all cover the relevant threading stuff.
Comment: I added System.out.println(0) into game's paintComponent method and it wrotes 0 only once, but it didn't draw anything into jframe anyway
Comment: Still sounds like you're block the EDT
Comment: and what should I do? I'm kinda new in java
Comment: Well, consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses
Comment: Looks like the problem is in loop method. Can you post it?
Comment: I already did, second code block
Comment: I did, same result it writes 0 just once
Comment: well I'm not working with threads in any way, just in that loop I'm sleeping that thread. And revalidate and paint are called from class where I have card layout
Comment: What are you looking for in an answer that is not addressed by the existing accepted answer? And see also https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
Comment: @radiodef I can give that bounty in 8 hours, that's why it's still there
Answer: Precursor: The Event Dispatch Thread (EDT).
Swing is single-threaded. What does this mean?
All processing in a Swing program begins with an event. The EDT is a thread that processes these events in a loop along the following lines (but more complicated):
class EventDispatchThread extends Thread {
    Queue<AWTEvent> queue = ...;

    void postEvent(AWTEvent anEvent) {
        queue.add(anEvent);
    }

    @Override
    public void run() {
        while (true) {
            AWTEvent nextEvent = queue.poll();

            if (nextEvent != null) {
                processEvent(nextEvent);
            }
        }
    }

    void processEvent(AWTEvent theEvent) {
        // calls e.g.
        // ActionListener.actionPerformed,
        // JComponent.paintComponent,
        // Runnable.run,
        // etc...
    }
}

The dispatch thread is hidden from us through abstraction: we generally only write listener callbacks.

Clicking a button posts an event (in native code): when the event is processed, actionPerformed is called on the EDT.
Calling repaint posts an event: when the event is processed, paintComponent is called on the EDT.
Calling invokeLater posts an event: when the event is processed, run is called on the EDT.
Everything in Swing begins with an event.

Event tasks are processed in sequence, in the order they are posted.
The next event can only be processed when the current event task returns. This is why we cannot have an infinite loop on the EDT. actionPerformed (or run, as in your edit) never returns, so the calls to repaint post paint events but they are never processed and the program appears to freeze.
This is what it means to "block" the EDT.

There are basically two ways to do animation in a Swing program:

Use a Thread (or a SwingWorker).
The benefit to using a thread is that the processing is done off the EDT, so if there is intensive processing, the GUI can still update concurrently.
Use a javax.swing.Timer.
The benefit to using a timer is that the processing is done on the EDT, so there is no worry about synchronization, and it is safe to change the state of the GUI components.

Generally speaking, we should only use a thread in a Swing program if there's a reason to not use a timer.
To the user, there is no discernible difference between them.
Your call to revalidate indicates to me that you are modifying the state of the components in the loop (adding, removing, changing locations, etc.). This is not necessarily safe to do off the EDT. If you are modifying the state of the components, it is a compelling reason to use a timer, not a thread. Using a thread without proper synchronization can lead to subtle bugs that are difficult to diagnose. See Memory Consistency Errors.
In some cases, operations on a component are done under a tree lock (Swing makes sure they are thread-safe on their own), but in some cases they are not.

We can turn a loop of the following form:
while ( condition() ) {
    body();
    Thread.sleep( time );
}

in to a Timer of the following form:
new Timer(( time ), new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent evt) {
        if ( condition() ) {
            body();

        } else {
            Timer self = (Timer) evt.getSource();
            self.stop();
        }
    }
}).start();

Here is a simple example demonstrating animation both with a thread and a timer. The green bar moves cyclically across the black panel.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class SwingAnimation implements Runnable{
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new SwingAnimation());
    }

    JToggleButton play;
    AnimationPanel animation;

    @Override
    public void run() {
        JFrame frame = new JFrame("Simple Animation");
        JPanel content = new JPanel(new BorderLayout());

        play = new JToggleButton("Play");
        content.add(play, BorderLayout.NORTH);

        animation = new AnimationPanel(500, 50);
        content.add(animation, BorderLayout.CENTER);

        // 'true' to use a Thread
        // 'false' to use a Timer
        if (false) {
            play.addActionListener(new ThreadAnimator());
        } else {
            play.addActionListener(new TimerAnimator());
        }

        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    abstract class Animator implements ActionListener {
        final int period = ( 1000 / 60 );

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (play.isSelected()) {
                start();
            } else {
                stop();
            }
        }

        abstract void start();
        abstract void stop();

        void animate() {
            int workingPos = animation.barPosition;

            ++workingPos;

            if (workingPos >= animation.getWidth()) {
                workingPos = 0;
            }

            animation.barPosition = workingPos;

            animation.repaint();
        }
    }

    class ThreadAnimator extends Animator {
        volatile boolean isRunning;

        Runnable loop = new Runnable() {
            @Override
            public void run() {
                try {
                    while (isRunning) {
                        animate();
                        Thread.sleep(period);
                    }
                } catch (InterruptedException e) {
                    throw new AssertionError(e);
                }
            }
        };

        @Override
        void start() {
            isRunning = true;

            new Thread(loop).start();
        }

        @Override
        void stop() {
            isRunning = false;
        }
    }

    class TimerAnimator extends Animator {
        Timer timer = new Timer(period, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                animate();
            }
        });

        @Override
        void start() {
            timer.start();
        }

        @Override
        void stop() {
            timer.stop();
        }
    }

    static class AnimationPanel extends JPanel {
        final int barWidth = 10;

        volatile int barPosition;

        AnimationPanel(int width, int height) {
            setPreferredSize(new Dimension(width, height));
            setBackground(Color.BLACK);

            barPosition = ( width / 2 ) - ( barWidth / 2 );
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            int width = getWidth();
            int height = getHeight();

            int currentPos = barPosition;

            g.setColor(Color.GREEN);
            g.fillRect(currentPos, 0, barWidth, height);

            if ( (currentPos + barWidth) >= width ) {
                g.fillRect(currentPos - width, 0, barWidth, height);
            }
        }
    }
}

Answer: What does update do? You probably shouldnt call game.loop() on the EDT. You are running a loop on EDT, your repaint wont ever be invoked since repaint queues an event on EDT and it seems kind busy. Try moving game.loop() to another thread
new Thread(new Runnable() {
    @override
    public void run() {
        game.loop();
    }
}).start();

This way you wont block the EDT while the repaint still gets to be executed on the EDT.
Comment: update is just updating coordinates of items, but finally it works, I appreciate your help, thanks.
Answer: Move game.loop() method invocation to something like:
SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    game.loop()
                }
            });

Thanks.
Comment: I did, now it's showing me images(game screen) and game's method update() is looping(so coordinates of objects are updating) but it's not rendering this update(it's not calling paint() method), so it looks like its freezen
Comment: Well my dear, the rest of your logic is a black box to me, so I can't help you unless you provide full relevant source code. Thanks.
Comment: do you think I can send you whole code to you to take a look at it? (threw email or something)
Comment: You can just post it here just like @MadProgrammer instructed you above, so everyone can take a look at it including myself. Thanks.
Comment: I edited questions, I change card in cardlayout(so it's called loop method) it writes me twice "paint" and xxxxx times "updated", so loop is working but it's not calling paint()


How to check for correlation between 5 classes (Likert ratings) and continous variable?

Question: Apologies if the question seems basic or technical terms are used incorrectly, but I am not very experienced in statistics.
I have collected data concerning different properties of objects, let's say animals, that are classified into 5 classes. The classes are equidistant and ordered Likert ratings 1-5 (for example representing weight, so 1 = low weight, 5 = high weight). Each object (animal) belongs to a class 1-5, and the properties are all numerical and continous. So the data looks something like this:

Animal (unique ID)
Class
Property1
Property2
Property3
...

Fish
1
0.5
2
2.2
...

Cat
3
0.2
1
1.3
...

Horse
4
1.2
4
3
...

Dog
3
0.8
2.5
1
...

...
...
...
...
...
...

How do I test whether there is a correlation between the classification into the 5 classes and a certain property? For example, if property 1 was volume, then surely low volume would correlate to lower classes/lower weight, and high volume would correlate to higher classes/higher weight.
What I'm actually trying to do is to build a program that analyses these objects, and then uses their properties to predict a class. So I need to compare the properties to find out which work best as class predictors.
I could obviously just get the averages for each property per class and then compare, to see if there is a trend from 1-5, but that doesn't seem statistically sound. Especially if I need to compare the "degree of correlation" with the classes for different properties.
Answer: Your assumptions are very straightforward, and there are no problems with what you envision.  While correlation can be used to understand the informativeness of each property feature in terms of linear association (covariance) with class, regression is better since it can actually determine what property features are the most optimal predictors of class.
Obviously, you're supposed to have, in terms of sampling, a lot of values for property1, e.g. $n=30$ for fish in class 1, $n=30$ for cats in class 2, and $n=30$ for horses, plus a lot of values for the other two classes of mammals. In other words, you need sampling variation based on measurements of all the property features from many different animals in the same class.
Then, you can easily determine correlation between class and each property, since class is already ordinal, since it's in the Likert scale with a gradient-based definition --> lower is low weight, higher is high weight.  Linear regression and polytomous (polychotomous) logistic regression are easy classifiers to use as well.  Correlation is not really used for class prediction, at least not nearly as much as various regression models are used.
Once you can apply logistic regression or linear (it would have to be multivariate normal regression), you can then branch out to classification analysis using by K-nearest neighbor (KNN), naive Bayes classifier (NBC), discriminant analysis (LDA), quadratic discriminant analysis (QDA), Fisher discriminant analysis (FDA), decision tree classification (DTC), supervised random forests (SRF), learning vector quantization (LVQ), gradient ascent support vector machines (SVMGA), least squares support vector machines (SVMLS), supervised artificial neural networks (SANN), kernel regression (KREG), particle swarm optimization, supervised neural gas (SNG), and mixture of experts (MOE).
Answer: For $n = 50$ subjects, suppose you have Likert variable x1 and numerical variable x2 with a positive association between categorical values of x1 and values x2. Perhaps they are
somewhat similar to the fictitious variables sampled in R and summarized below:
summary(x1)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  1.000   3.000   3.000   3.356   4.000   5.000
summary(x2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  9.919  10.301  10.409  10.408  10.525  10.892

The plot below shows a clear positive association:
plot(x1,x2, pch=20)

You could find the Pearson correlation $r = 0.756$ between
the two variables.
cor(x1,x2)
[1]  0.7562872

Because x1 is ordinal categorical and because the relationship may not be exactly linear, it may make more sense
to look at Spearman correlation $r_S = 0.750,$ which is the Pearson correlation of the ranks of the two variables.
cor(x1,x2, meth="s")
[1] 0.7496384
cor(rank(x1), rank(x2))
[1] 0.7496384

Once you see that there are associations among some of your variables, you can explore their consequences using various kinds of regression.


Updated taxonomy terms do not save

Question: I am using the taxonomy module (D7) to list Continents, Countries, and Cities. Continents is the 1st level, Countries is the second level, Cities is the third. Or, in other words, Countries and Cities are children to Continents.
That's quite a number of terms.
All has been going well for a while but it seems I have reached some kind of a limit. Indeed, I can save new terms on the root level but when I move them to be children (at the 3rd level) the update no longer saves. There is no error message and no confirmation that the new configuration was saved. Indeed, the new terms are back to the root level after that.
I have added "max_input_vars = 1500" to my php.ini file but it didn't help.
The server generates no error.
Any idea or suggestion on how to fix this?
Thanks. :)
Update: If I move a term from the root directory to become the child of another term, the (new) automatic URL is not written in the database. I have to delete some existing terms to be able to save new terms (by the same number.) This tells me there is an imposed limit somewhere.
Answer: The fix is as follows:
In your php.ini file, increase the max_input_vars to 2000. That should fix the issue with taxonomy terms and blocks too.

Updated taxonomy terms do not save


What conventions are used with accidentals and tied notes?

Question: If I have a tied note across a bar line, say 2 whole G notes, and I have an accidental, say a sharp, on the first G, my assumption is that the accidental applies as well to the second G because it is tied. If I wanted it to not apply, what would be the convention?  Would it be simply to not have a tie note in the first place and have two separate notes, a sharped G and a G itself?
Comment: If the second note is not augmented, then you can't have a tie at all, since it doesn't connect equal pitches. (However, if you use a *slur* for phrasing or legato, which looks similar and can be confused with a tie, then you should definitely include a complementary cancellation sign.)
Answer: An accidental does apply across the bar line, but would need to be reapplied to any applicable notes after the second note under the tie. Ties don't apply to different notes. (You'd use a slur instead if you wanted the 1st note held until the 2nd note is attacked.)
If, say, you sharp a G and tie it across the bar line, then follow the second note under the tie with G♮, you may want to use a cautionary accidental to show that the sharp has come off. If the sharp wasn't part of the key signature, this isn't absolutely necessary, but it usually saves a bit of confusion.
The following example should make this clear.
Comment: Great answer! I would always use a cautionary accidental. If I saw that measure without it, I would almost surely play G# again.
Comment: Well, yeah, @NickB. The rule says that the accidental only applies in the bar in which it is added, but, in cases like this, it can look a lot like a proofreading error if the cautionary isn't there.
Comment: Yeah, it can be hard to distinguish between ties and slurs on old sheet music.  Even some new stuff.  I'd probably default to assuming it's a tie if the note doesn't change -- it's on the arranger to make it explicit if not.
Comment: @Speldosa, might be a good question. I can think of a few instruments where it would be possible to re-attack a note (i.e., distinct attack) without a break - that's makes for a good slur but an incorrect tie. From point of view of _notating_ multi-voice music, though, slurs and ties are placed differently.
Comment: Could you expand on the the engraving difference between a tie and a slur? I saw in your example that they don't look the same, but I had never noticed. Very interesting!
Comment: @Gauthier, my notation software is a bit old, or the differences would be even more obvious. Ties tend to be more "in between" the note heads than slurs, usually with less curvature: they rarely extend more than 1 to 1-1/2 lines or spaces in depth past the line or space the note is occupying. When flipped (because the note is in the upper voice of a multi-voice stave), they remain between the note heads. Slurs will migrate to the ends of the stems in a multi-voice setting.
Comment: Does it really matter whether you got a tie or a slur though? A slur for two notes that were the same would, if anything, reduce down to a tie (what does two consecutive notes at the same pitch sound like when played in legato mode?); and you can't have a tie between two notes with different pitches. It almost feels easier to think of the slur and tie as the same thing.
Comment: @Speldosa, put more than one voice on the stave. Are ties and slurs the same then?
Comment: @Patrx2 Hmm... I can't think of an example with several voices on the same staff where it would be necessary to make a distinction between the two. Maybe I should turn this into a new question instead of discussing it in the comment field :)
Comment: @Patrx2 Good point! I created a question about this: http://music.stackexchange.com/questions/33611/are-there-any-situations-when-one-needs-to-make-a-distinction-between-slurs-and
Comment: @Speldosa, I see that. user21166 has done a good job of amplifying my point here. Main thing is that ties really denote a _single_ note.
Comment: I've more often heard a "cautionary accidental" called a "courtesy accidental" instead.
Answer: Tied notes are, by definition, the same note carried across a bar line. When the second note is different, even though it may be the same letter name, but altered with a #, b or natural, then that note will have to be played as a separate note in the new bar. Then, the 'tie' line becomes a slur. Yes, if it's the same note, there's no need to put the # in your case. There would certainly not be a tie - there couldn't be.
This answer is direct to your question, as you stated the second G (G natural)lasted the whole bar, Which takes a different slant from Patrx2's answer, which correctly states what happens to SUBSEQUENT notes of the same name in a second bar.
Comment: I don't understand the part "there would certainly not be a tie." It sounds like you are agreeing with Patrx2's answer, but if it's the same note and there's no need for the #, doesn't that make it in essence a tie of G#'s spanning the two measures?
Comment: If the 1st bar was G#, and the 2nd, G natural, there could be a slur, but not a tie. It's not possible to tie dissimilar notes. This is how I interpreted the question. If the two notes were the same, then yes, they could be tied, and would not need the 2nd accidental, as you said.
Answer: Others have already stated that a tied note does not call for a repeat accidental but any following notes will.  This is correct with one exception: if the tie is broken across lines, the tied note after the line break will require a repeat accidental which then counts for following notes as well.
This is one of the rare cases where line breaks affect details of notation inside of the lines.
Comment: FWIW, this rule doesn't seem to be consistent across scores. Looking through my scores from various publishers/editors, I see many follow it (e.g. Urtext, Mandyczewski Brahms, IMC) but some don't (e.g. Paderewski Chopin). Dorico, usually so scrupulous about these sorts of rules, does not follow this one. I wonder if it's a regional thing, or just a matter of taste?


Is the subset relation on the powerset of a set, with qualification, reflexive?

Question: I was wondering if the subset relation is reflexive?
$R = \{(X, Y ) \in P(A)^2\mid X\subseteq Y \text{ and } X \neq Y \}$
I assumed they it was reflexive since for all $X \in P(A), X \subseteq X$ is true. So does that mean the relation is reflexive? Or do I need to add additional proof?
Comment: **Note:** While $X\subseteq X$ is true, however $X\neq X$ is false, so $(X,X)\not\in R$.
Comment: That's a confused use of the phrase "a subset of a powerset." It seems you mean, "Is the subset relation on the pwoerset a reflexive relation?" At least, that is what the rest of your question appears to be asking. But then you start using $S1$ and later reference $R$, which is nowhere defined. $S1$ explicitly forbids $(X,X)\in S1$. Not sure what $R$ is meant to be.
Comment: sorry will make edit.
Comment: If  X ⊆ X that means X = X? or are you referring to the condition in the relation that X != Y?
Comment: You've also got an odd arrow - you are trying to prove that $(X,X\in R$, so what you seem to want to say is that $X\subseteq X\rightarrow (X,X)\in R$. The other direction doesn't get you anything. $X+2=Y$ implies $Y<X$, but $Y<X$ does not imply that $Y=X+2$.
Answer: The relation cannot be reflexive. $(X, X)\in R$ if and only if both the following statements are true:
$$X\subseteq X\tag{1}$$ $$X \neq X\tag{2}$$
$(1)$ is true for all $X \in \mathcal P(A)$. $(2)$ is false for all $X \in \mathcal P(A)$.
Hence, for all $X \in \mathcal P(A)$, $(X, X) \notin R$.


Python - "unexpected EOF while parsing"

Question: I've watched some videos by Socratica and now I tried stuff out, but it keeps saying  "unexpected EOF while parsing" when I try to save. Here's my code (just to try out stuff)
<code>    dir() # Short for "directory"

    print(dir())
    print(dir(__builtins__))

    print(help(pow))

    #pow(x, y [, z])
    pow(2,10) #2^10
    2**10 #2^10
    print(pow(2, 10, 3))

    print(help(hex))
    hex(10)
    #0x start of hexadecimals
    print(0xa)

    print(help(modules))

    import math
    print(dir())
    print(dir(math))

    help(math.radians)
    #180 degrees=pi radians
    math.radians(180)

    #boolean values: True, False
    True
    print(True)

    a=3
    b=5
    print(a == b)
    print(a != b) # ! means not
    print(a > b)
    print(a < b)
    print(type(True))

    #every number except 0 bool-->True
    print(bool(28))
    print(bool(-2.71828))
    print(bool(0))

    #strings True except ""
    print(bool("Hello World"))
    print(bool("   "))
    print(bool("")

    #print(int(True))
    #print(2 + True)
</code>
btw I made
<code>    print(int(True))
</code>
and
<code>    print(2 + True)
</code>
notes because for some reason it saidd there's a syntax error even though Socratica said that this would say 1 and add 2+1 :/
I use python 3.7
Comment: Duplicate of many, many questions: https://stackoverflow.com/search?q=%E2%80%9Cunexpected+EOF+while+parsing%E2%80%9D
Comment: Oh now I see, thanks
Comment: Missing parenthesis on `print(bool("")`.
Comment: BTW I use IDLE 3.7
Comment: Um I got another question about hex(10), in the shell it says     >>> hex(12648430)
    '0xc0ffee'
Answer: <code>...
#strings True except ""
print(bool("Hello World"))
print(bool("   "))
# missing parenthesis in this line -> print(bool("")
print(bool(""))

#print(int(True))
#print(2 + True)
</code>
Answer: Those examples are meant to be tested in a python REPL - Read Eval Print Loop, which is a prompt where you type commands and see the results. You are not supposed to save anything. The lines are not a complete program you should save, just some experimentation commands you should run and try to make sense.
Go to https://www.python.org/downloads/ download python and install it. Then run python
You will see a prompt like this:
<code>>>>
</code>
Then type each command one by one, don't paste all commands. The point is to experiment and see. Try changing the commands and see the results.
<code>>>> dir()
['__builtins__', '__cached__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'atexit']

>>> print(dir(__builtins__))
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
...
'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
</code>
etc etc...

Python - "unexpected EOF while parsing"


Self invoking functions no PHP 7. Quais as vantagens?

Question: Eu sei que no javascript é muito útil a utilização de self invoking functions, principalmente quando se trata da proteção do escopo de variáveis.
Eu estava fazendo testes no PHP 7 e vejo que temos a mesma possibilidade de usar a Self Invoking Function - funções que podem ser chamadas ao mesmo tempo que são declaradas.
Exemplo:
$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})()

foreach ($gen as $number) {
    echo $number;
}

A saída é:
1
2
3

Nesse caso do uso do Generator, vejo muita utilidade.
Quais são outras possíveis vantagens na utilização do Self Invoking Function em PHP7?
Answer: O recurso vai na direção do que chamamos, em outras linguagens, de delegate functions. Há até uma proposta para o PHP 7 em que o conceito está até melhor desenvolvido.
A vantagem deste tipo de função (que até podemos chamar de função anônima) é a possibilidade de definir a função dinamicamente. Este exemplo que você colocou não é exatamente bom, então vou montar outro. Suponha uma função que realize soma de quadrados:
$squares = (function($meu_array) {
    foreach ($meu_array as $elemento)
    {
        yield $elemento * $elemento;
    }
})()

Você pode usar assim:
foreach ($squares(array(1, 2, 3, 4, 5)) as $number) {
    echo $number;
}

A saída deve ser:
1
4
9
16
25

Agora, suponha que você quer a soma dos quadrados até um determinado número, e esse número só é conhecido em tempo de execução:
$squares = (function($meu_array, $limite) {
    foreach ($meu_array as $elemento)
    {
        var $numero = $elemento * $elemento;
        if ($numero <= $limite ) yield $numero;
    }
})()

Podemos usar assim:
var $limite = 20;
foreach ($squares(array(1, 2, 3, 4, 5), $limite) as $number) {
    echo $number;
}

Saída:
1
4
9
16

Comment: Eu era programador PHP. Acho que já te falei.
Comment: Acho que vai rolar um "mortar" desse jeito
Comment: Olha, esse exemplo foi fino, hein.
Comment: Melhorei ele. Agora sim está adequado.
Comment: Pra quem não gosta de PHP, até que está sabendo muita coisa, hein.


Less permissions for a Foursquare app

Question: We would like to develop a survey in which consenting participants would have to give us access to their list of checkins on Foursquare. Currently, we do so via a Foursquare app, but I do not seem to find a way to specify which permissions our application needs.
Whenever a user is asked to grant access to our app, he is informed that we will be able to post checkins on his behalf and do a bunch of other things. This will raise concerns and will likely lower the number of willing participants.
The question would be whether there is a way to restrict the permissions of our app to what we actually need, i.e. the full list of checkins.
As an alternative, we are considering befriending the user from a special account instead. However, does friendship guarantee that we can see all of his checkins?
Answer: The Foursquare API currently doesn't support scoped permissions (e.g., seeing check-ins only). You will have to make it clear to your users that you won't post to their accounts.
The only way to see a person's entire history of check-ins is if you have an access token for them, so unfortunately the befriending method won't work.

Less permissions for a Foursquare app


Looking for a way to write to a file the name of the step and the scenario

Question: I'm writing the error/failures of my steps to a file with this function:
def addToErrorFile(errorName)
    open('error.txt', 'a') { |f| f.puts"#{errorName}"}
end

This function is located in a lot of places in my test flow.
To make it easier to read it in the end, I would like to add the step name (Then /I go to…) and also the scenario (Scenario: login to..).
Is there a way to copy those into the function?
Comment: This might help - http://stackoverflow.com/questions/31864767/accessing-the-scenario-title-and-example-in-a-cucumber-after-hook
Answer: You could put some code in your before and after scenario hooks that writes to the error log.  That should break it up a bit and make it easier to read.  Something like this.
Before do |scenario|
  your_logging_method(scenario.name)
end

After do |scenario|
    your_logging_method(scenario.name)
end

And there is an AfterStep hook too, though I haven't used it.
AfterStep do |step|
  another_logging_method(step)
end

You may have to call some methods on the step variable to get it in a useful format.
Here's a link to the cucumber hooks documentatioon - https://github.com/cucumber/cucumber/wiki/Hooks
Comment: Thank you! I will give it a try
Answer: it wouldn't be better to use ruby (begin rescue ensure ) and put the code in there. You save your test session and you can progress your test to next steps, where you can put line of code to save name of next step to file


bond0:0 + define virtual IP

Question: in my linux server I have the follwoing:
Linux Version - RedHat-Linux- 188.8.131.52
(this linux server only only one LAN)
<code>   more /etc/sysconfig/network-scripts/ifcfg-bond0:0

   DEVICE=bond0:0
   ONBOOT=yes
   BOOTPROTO=static
   IPADDR=10.10.10.12
   NETMASK=255.255.255.0

 ifconfig -a
           bond0     Link encap:Ethernet  HWaddr 00:00:00:00:00:00
           UP BROADCAST MASTER MULTICAST  MTU:1500  Metric:1
           RX packets:0 errors:0 dropped:0 overruns:0 frame:0
           TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:0
           RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

           bond0:0   Link encap:Ethernet  HWaddr 00:00:00:00:00:00
           inet addr:10.10.10.12  Bcast:184.108.40.206  Mask:255.255.255.0
           UP BROADCAST MASTER MULTICAST  MTU:1500  Metric:1

           eth0      Link encap:Ethernet  HWaddr 00:0E:0C:C7:F8:92
           inet addr:188.8.131.52  Bcast:126.96.36.199  Mask:255.255.255.0
           inet6 addr: fe80::20e:cff:fec7:f892/64 Scope:Link
           UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
           RX packets:8600 errors:0 dropped:0 overruns:0 frame:0
           TX packets:4764 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:1000
           RX bytes:717979 (701.1 KiB)  TX bytes:598620 (584.5 KiB)
           Memory:b8820000-b8840000
</code>
my problems:

why I get HWaddr 00:00:00:00:00:00 and not the real MAC address
I cant ping to other server with 10.10.10.11 from my server
is it posible to define bond0:0 when I have only one LAN (eth0)

other info:
more /etc/modprobe.conf
<code> alias eth0 e1000e
 alias eth1 e1000e
 alias eth2 e1000e
 alias eth3 e1000e
 alias scsi_hostadapter mptbase
 alias scsi_hostadapter1 mptsas
 alias scsi_hostadapter2 ata_piix
 alias bond0 bonding
 alias bond1 bonding
</code>
Answer:
Is your bond associated with eth0?
(see 1)
Theoretically: yes but it makes no sense to do so. (see below)

A bonded interface is for taking two physical interfaces and combining the bandwidth. If you have 2x1Gbps ports, you can configure the switch to treat them as 1x2Gbps port.
It sounds like what you want is an IP Aliases or Range
UPDATE
If you really do want to set up a bond, then Red Hat's documentation may help.
Comment: yes I want to add to eth0 the bond0:0 is it wrong?
Comment: @yael "not 'wrong' per se; it's just a bit of unnecessary complexity". If you really want a bond set up, I added a link to Red Hat's documentation on it. However, it really sounds as though you want IP Aliases.
Answer: A bond interface will show the all-zeros MAC until it has at least one member (slave) interface added to it (via the ifenslave command).
On RedHat (and similar), you'll add two lines to the physical interface's sysconfig script:
'MASTER=bond0' and 'SLAVE=yes'. Then set the IP in a new sysconfig script for the bond0 interface.
You can have as many alias subinterfaces (:0, :1, etc) as you want, regardless of the number of physical interfaces the machine has.
A bond group with only 1 physical interface is a little unusual, but not 'wrong' per se; it's just a bit of unnecessary complexity. When you do get more interfaces, be sure to set the 'mode' parameter for the bonding module -- the modes work in very different ways, depending on your intended application.
Answer: Why are you trying to use a bonded connection with one interface?
I'm pretty sure creating a bonded device generally requires two or more interfaces.
I think what you're trying to do will require either an alias interface (eth0:N) or a VLAN configuration.
Comment: hi I need two diffrent ip's , this is the reson for that
Comment: I return on my question , I have only one LAN , but I need to define the second IP 10.10.10.12 as CHB (cluster hart bit) because I want to add this server as second cluster machine,
Comment: See my answer below
Answer:
I return on my question , I have only one LAN , but I need to define the second IP 10.10.10.12 as CHB (cluster hart bit) because I want to add this server as second cluster machine,  – yael yesterday

A bonded connection is not the solution you need in this situation.
What you need is an aliased connection.
With RedHat based systems, this is very easy to do.
copy /etc/sysconfig/network-scripts/ifcfg-eth0 file to /etc/sysconfig/network-scripts/ifcfg-eth0:0
Edit the ifcfg-eth0:0 so that you remove the HWADDR section and obviously change the IP to the second IP you want on the same interface.
Also change the DEVICE to read eth0:0
Restart networking and you should see the new IP address on your network.

bond0:0 + define virtual IP


Two-Dimensional Gaussian integral in complex coordinates.

Question:
(4) A two-dimensional Gaussian integral in complex coordinates:
$$
\begin{aligned}
&\frac{1}{\pi} \int \exp \left(-\mu \alpha^{2}-\nu \alpha^{* 2}-z^{*} \alpha+z \alpha^{*}-|\alpha|^{2}\right) \mathrm{d}^{2} \alpha \\
&\quad=\frac{1}{\tau} \exp \left[-\left(\mu z^{2}+\nu z^{* 2}+z z^{*}\right) / \tau^{2}\right], \quad \tau=\sqrt{1-4 \mu \nu}, \quad \mu+\nu<1 .
\end{aligned}
$$

(Transcribed from picture)
Can anyone suggest some text reference where I can get to learn about the result and about Two-dimensional Gaussian integral in complex coordinates in general? Any Mathematical Physics text reference is preferred. I am having problems dealing with them in my study of Quantum Optics.
Comment: Welcome to math.SE: Please write equations in latex formatting instead of attaching images, this will help your question get better answers and avoid it being closed.
Comment: Difficult to understand the connection with Fourier Transform. Is there a connection with quaternions like here https://arxiv.org/pdf/1406.1014.pdf ?
Comment: I am not aware of the connection with quaternions, so I cannot comment on that. The kernel of the transformation here is $${e^{z\alpha^{*}-z^{*}\alpha}}$$ which transforms a function $$Q({\alpha},\alpha^{*})$$ to, lets say, $$P(z,z^{*})$$ which is the expression on the right side of the equation.
Comment: I understand. I have never seen this. As it deals with a function of 2 complex variables, the usual notation for the differential element should have been $dz d\overline{z}$. It is a detail but it is interesting to know it if you are looking into maths books about "functions of several complex variables" like [this one](https://www.amazon.com/Fourier-Analysis-Several-Variables-Mathematics/dp/0486449750)
Comment: I too haven't seen this before. Can you give the source for this?
Comment: Its from this book Quantum Optics by Girish Saran Agarwal page-22. This page is available in the preview here. https://books.google.co.in/books/about/Quantum_Optics.html?id=InUgAwAAQBAJ&printsec=frontcover&source=kp_read_button&hl=en&newbks=1&newbks_redir=1&redir_esc=y
Comment: Crossposted from https://physics.stackexchange.com/q/678465/2451
Answer:
It follows from my Phys.SE answer here that OP's Gaussian integral becomes
$$ \begin{align} I~:=~&\int_{\mathbb{R}^2} \!  \frac{\mathrm{d}{\rm Re}\alpha \wedge \mathrm{d}{\rm Im}\alpha}{\pi}~
\exp\left\{-\mu \alpha^{2}-\nu \alpha^{* 2}-z^{*} \alpha+z \alpha^{*}-|\alpha|^{2}\right\}\cr
~=~&\int_{\mathbb{C}} \!  \frac{\mathrm{d}\alpha^{\ast} \wedge \mathrm{d}\alpha}{2\pi i}~
\exp\left\{ -\frac{1}{2}A^TSA +Z^TA\right\}\cr
~=~&\sqrt{\frac{-1}{\det(S)}}\exp\left\{\frac{1}{2}Z^TS^{-1}Z \right\}\cr
~=~&\frac{1}{\tau} \exp \left\{-\frac{\mu z^2+\nu z^{* 2}+z z^{*}}{\tau^2}\right\}.
\end{align}$$

Here we have defined
$$ \begin{align}
A~:=~&\begin{pmatrix} \alpha   \cr \alpha^{\ast} \end{pmatrix}, \cr
Z~:=~&\begin{pmatrix} -z^{\ast}   \cr z \end{pmatrix}, \cr
J~:=~&\begin{pmatrix} 1 & i \cr 1 & -i \end{pmatrix}, \cr
S~:=~&\begin{pmatrix} 2\mu & 1 \cr 1 & 2\nu \end{pmatrix}, \cr
\tau^2~:=~&-\det(S), \cr
S^{-1}~=~&\frac{1}{\tau^2}\begin{pmatrix} -2\nu & 1 \cr 1 & -2\mu \end{pmatrix},
\end{align}$$

Moreover, the Gaussian integral $I$ is convergent if ${\rm Re}(J^TSJ)>0$ is positive definite.


Area under the curve - Integrals (Antiderivatives)

Question: I have a question regarding antiderivatives and area under the curve.
I've learned that first, you must to a graph to see if the area is above or below the curve. If it is above the $x$-axis the area is "positive" and I must use $A=\int f(x) dx $. If it is below the $x$-axis the area is "negative" and I must use $A=-\int f(x) dx $. In this last one, I've understood that negative outside the integral is because the integration alone will be negative because is under $x$-axis, but an area can't be negative so that's why is multiply by that negative. I've also seen this with absolute value $A=|\int f(x) dx| $ that I think have the same purpose.
This is an example of an exercise:
Determine the area of the region bounded by the curve of the function $f(x)=4x^3-16x$ the $x$-axis and the lines $x=-2$ y $x=2$.
Ok. I'll show you my work.
I first do the graph.

I see that between $-2$ and $0$ the region bounded is above the $x$-axis so is positive, and that between $0$ and $2$ the region bounded is below the $x$-axis so is negative. So I'll call the first one $A_1$ and the second $A_2$.
$$A_{total}=\int_{-2}^2 (4x^3-16x) dx$$
$$A_{total}=A_1+A_2$$
$$A_{total}=\int_{-2}^0 f(x) dx+(-\int_0^2 f(x) dx)$$
$$A_{total}=\int_{-2}^0 (4x^3-16x) dx+(-\int_0^2 (4x^3-16x) dx)$$
$$A_{total}=[\frac{4x^4}{4}-\frac{16x^2}{2}]|^{0}_{-2} - [\frac{4x^4}{4}-\frac{16x^2}{2}]|^{2}_{0} $$
$$A_{total}=[x^4-8x^2]|^{0}_{-2} - [x^4-8x^2]|^{2}_{0} $$
$$A_{total}=[((0)^4-8(0)^2)-((-2)^4-8(-2)^2)]-[((2)^4-8(2)^2)-((0)^4-8(0)^2)]$$
$$A_{total}=[-(16-32)]-[16-32]$$
$$A_{total}=[-(-16)]-[-16]$$
$$A_{total}=16+16$$
$$A_{total}=32u^2$$
So I got that the total area is 32 square units. But I was wondering why is this different from doing the integration of $\int_{-2}^2 (4x^3-16x) dx$. This gives $0$.
$$\int_{-2}^2 (4x^3-16x) dx$$
$$=[\frac{4x^4}{4}-\frac{16x^2}{2}]|^{2}_{-2}$$
$$=[x^4-8x^2]|^{2}_{-2}$$
$$=[(2)^4-8(2)^2]-[(-2)^4-8(-2)^2]$$
$$=[16-32]-[16-32]$$
$$=-16-[-16]$$
$$=-16+16$$
$$=0$$
So I'm a bit confused. Which is one correct?
Please help.
Comment: Note that $|\int f(x)dx|\ne \int |f(x)|dx$
Answer: Ok, so here's the cause of your confusion: the meaning of the word "area" depends on the context of the problem. Indeed your calculation
$$\int_{-2}^{2} (4x^3-16x)\,dx = 0$$
is correct. (A shortcut is to notice that you are integrating an odd function over a domain which is symmetric about the origin). However, in this particular question, the "area between the curves and the x-axis" really means to compute
$$\int_{-2}^{2} |4x^3-16x| \,dx$$
So yes, in the geometric sense, area generally must be positive. But when evaluating definite integrals, we sometimes think of the area above the x-axis as being "positive area" and the area below the x-axis as "negative area."
As to getting the answer to your problem, use symmetry to make your life easier:
$$\int_{-2}^{2} |4x^3-16x|\,dx = 2 \cdot \int_{-2}^{0} (4x^3-16x)\,dx = 2 \big[x^4 - 8x^2\big] \big|_{-2}^{0} = 32.$$
Comment: (+1) A very good answer for a new contributor! Welcome to MSE!
Answer: In such cases , you must create the partial intervals and integrate over them.
The integral without considering whether the function is negative or positive counts the areas above the $x$-axis positive and the areas below the $x$-axis negative.
Hence, the solution $0$ is not correct (anyway area $0$ cannot be the result here).
You need the roots of the function to find the necessary intervals , exactly what you did in the first (correct) approach.
Answer: In your first approach, you are taking the absolute value of the "signed areas" (so the areas will be positive whether above or below the $x$-axis). Hence, $A_1 = \vert 16\vert = 16$ and $A_2 = \vert -16\vert = 16$, so $A_1+A_2 = 32$.
When taking the definite integral, you are taking the signs into account, so $A_1 = 16$ while $A_2 = -16$, which means $\int_{-2}^2 f(x)dx = 0$. (The areas above and below the $x$-axis are equal and cancel out.)
The first approach is correct because the question is asking for the area bounded by $f(x)$ and the $x$-axis (in which case, a non-positive area makes no sense), not for the definite integral of $f(x)$ between $-2$ and $2$.


Using NOT in Excel Advanced Filter

Question: I am just asking whether it is at all possible using Advanced Filter with NOT and unique records? To explain my logic, this is what I am trying to achieve, I have a column called option codes, in this column there are duplicate values and values that have the word "NULL". Now, what I want to do is to filter on this column all unique values but I also want to keep all rows that have the word NULL in that column, too. I want to do this in one filter rather than having to go back and forth.
Is there away to do this?
Example output would be:
AA
BB
CC
NULL
NULL
.
.
.
.
.

Answer: This is how you get advance filter http://support.microsoft.com/kb/214324
For not equal you can do something like this; for example
=if( F5<>35,"Failed","Passed")

Comment: Can I ask whether this can be added into the criteria range? My point is that I wish to record the advanced filter as a macro and adding another column is not possible
Comment: Yes, I think you can. Try once.
Comment: I had a go but it said invalid reference

Using NOT in Excel Advanced Filter


w-score vs. z-score with covariates

Question: I want to predict GM volume in a group of patients based on their degree of cognitive impairment, corrected for age and sex. To have a more 'disease specific' measure of cognition, I use cognitive performance-scores in a large group (N=500) of healthy controls (HC) as a reference.
Me and my supervisor discussed two methods for doing this (the w-score vs. the z-score method):
1.    w-score method:
a.  calculate the effect of age and sex on cognitive score in the HC group (cognition = a + (b * age) + (c * sex))
b.  predict cognitive score in the patient group based on the regression coefficients we found in the HC group
c.  for each patient, subtract this predicted score from his actual score, and divide by the SD of the HC's residuals
(w-score = (cognition.obs – cognition.pred)/SDres)
d.  perform a regression in which w-score predicts GM volume
(GM volume = a + (b * w-score))
2.    z-score method:
a.  calculate the mean and SD of cognitive score in the HC group
b.  for each patient, subtract the HC's mean from his actual cognitive score, and divide by the HC's SD (z-score = (cognition.obs – cognition.mean)/SD)
c.  perform a regression in which z-score predicts GM volume, using age and sex as covariates (GM volume = a + (b * z-score) + (c * age) + (d * sex))
My supervisor wants to use the w-score method (because it is similar to the use of 'norm tables' which are based on a HC group and have corrections for age/sex). I actually prefer the z-score method, because the effect of age/sex on cognition in my patient group is different from the age/sex effect in the HC group.
If the logic behind correcting for age and sex is that they are a covariate/confounder in my regression (i.e. they directly relate to GM volume and might not be evenly distributed over cognitive scores), wouldn't it make more sense to use the z-score method? In that way, you correct for the actual effect of age/sex that exists in the patient group (instead of a different effect that only exists in the HC group).
I'm very curious about your opinions, thank you in advance.
Anita
Comment: Do you have data on GM volume for the HC group, or just the cognitive-performance scores?
Comment: I only have cognitive performance-data from my HC group, no GM volume data.
Answer: IMHO this is not based on statistical principles, and such manipulations cause observations to be correlated even if they started out independent.  You are also making the strong assumption that the standard deviation is an appropriate normalizing statistic and that you have estimated the SDs very tightly.  SD is useful for smooth symmetric distributions with non-heavy tails.  This may not apply to your data.
The best approach to statistical modeling is to spend a lot of time formulating a comprehensive model that takes into account all known sources of variability that you can measure.  This model uses the raw data and leads to comparisons of real interest.
Answer: In addition to the severe problems in using SDs to normalize, as noted in the answer from @FrankHarrell, both proposed methods have additional problems and seem to address different underlying hypotheses. They tend to mix up (in different ways) the contributions of the age/sex covariates to cognition and to GM volume.
In method 1 the only predictor variable for GM (presumably gray-matter volume) is the difference between observed COG score and the COG score predicted based on age and sex. Thus it ignores any direct effects of age or sex on GM. I would be very surprised if age and sex were unrelated to GM on their own, for individuals having normal COG scores, yet method 1 does not allow for that possibility.
In method 2, you model GM as a function of the difference between the individual's COG score and the mean COG score of your entire HC group (among all values of age and sex), along with age and sex as separate variables. If you ignore the normalization by SD, method 2 examines

GM ~ a + b * (COG-COG.mean) + c * age + d * sex

Note that the mean COG score of the HC group, COG.mean, is a constant and its inclusion just changes the intercept of the model:

GM ~ (a - b * COG.mean)+ b * COG + c * age + d * sex

So subtracting the mean HC COG score doesn't add anything useful, and the information from the COG scores of the HC group about relations of age and sex to COG is effectively thrown out in method 2. This method combines the contributions of age and sex to COG score with any influences they may have on GM independent of their effects via COG.
So neither of these methods addresses a clean hypothesis.
If your interest is purely prediction, then a model including COG, age and sex (and potentially many other variables, as indicated by @FrankHarrell) would seem the simplest, and is effectively related to method 2 (without the troubling SD normalization).
It seems, however, that you want to test whether there is a relation of GM to some measure of deviation from predicted cognitive function. But method 1 ignore effects of age and sex other than through the predicted COG score, and method 2 ignores the information about predicted COG scores based on age and sex. (And, on reflection, I wonder why you are modeling GM as a function of COG score rather than the other way around.) You have to specify very clearly the hypothesis you want to test, then devise a model that tests it.
Added in response to comment
Including other scores that evaluate memory or attention, which is certainly in keeping with both answers here, raises the same issues with respect to normalization by sample-estimated SDs. All variables are best entered into the model as their original scores. Keeping the variables in the original scales is not just more convenient, it is also much more reliable. If you try to normalize them into z-type scores before regression, dividing them by sample estimates of their SDs, you are making your results harder to interpret and harder to reproduce. There can be a large error in any sample-based estimate of SD, so you are adding extra variability to your coefficients. Anyone trying to reproduce your results will probably find different sample-estimated SDs and thus different z-scores even on retesting the same individual with the same instrument.
There is no problem with including variables having different scales in this type of analysis. You already are doing this in your model with age, COG score, and sex. Your comment on "varying scales" suggests that you are interested in comparing different domain scores for some type of relative importance. If so, do that afterward. For example, you could examine the difference in predicted values between, say, the 25th and 75th percentiles of your sample for each of your domain scores. But be warned that measures of relative importance of variables are highly sample-dependent. You can learn that for yourself by comparing results of the same evaluation of relative importance on bootstrapped re-samples of your data set.
Comment: Thanks a lot FrankHarrel and EdM for investing your time in my question, I very much appreciate it! I understand that transforming the COG score into a z-/w-score seems unnecesary and actually harmfull to the data, and that using the 'raw' COG score is more convenient. However, one of the reasons for not using the raw COG-score is that we want to have 'domain scores' (e.g. memory, attention) which are based on multiple cognitive tests with varying scales. Is there an alternative to the above described methods, e.g. not using the HC group and just calculating z-scores within the patient group?

w-score vs. z-score with covariates


Specifying Taxonomy Term Filter in View from Page Editor

Question: I'm currently using a view to display content teasers and I want my users who are making pages to be able to incorporate these views, however I want them to be able to specify a taxonomy term to show that content. I tried doing this with a Contextual Filter, however I need some way to allow the user to specify the term in the page editor, not on the page preview itself. Is this something that Views allows you to do? Do I need to install a module, or do this programatically?
Hopefully I'm not being too confusing with that description, if so just let me know and I can try and clarify.
Comment: To clarify - you want users to create nodes, and on those nodes they will select one taxonomy term. Then when they save the node, besides the usual node content you also want to show View of Content teasers you have created, but only for the content that shares the same taxonomy term as the one the user selected on the node. Is this true?
Comment: @prkos Yes exactly. Without creating individual views for each term. I just want one view that will filter based on a term they provide somewhere on the page.
Answer: There are two parts to this question - one is to have creators of nodes to choose a Taxonomy term, the other is to have a Views Display show up on Node View based on the Taxonomy term set inside the node.
Taxonomy term reference
As you've already worked out, the easiest way to allow for users to influence what content list to display on their nodes is to allow them to choose a Taxonomy term.
You can do that by creating an Entity reference field referencing Taxonomy terms. The way you worded your question suggests you will only allow one term to be selected (limit number of values to 1).
When the node is saved, the information about the chosen Taxonomy term will be displayed when viewing the node. If you don't want this to be visible, if you only want this field to serve as a way to influence Views in the following steps, you can hide the field from showing up on node view by changing Manage Display settings. The info from the field will still be available for Views to read "on the sly".
Views Block listing content sensitive to the Taxonomy of the page they're on
Creating Views that display related content is probably the most common request in Views. With such a Views Block you don't have to have any additional interface for node creators to choose what to display on their nodes. Simply having a Taxonomy term reference is enough (already covered above).
First you create a Views Block listing your desired Content (set up all the regular Filters and Fields).
Then add a Contextual Filter of type Content: Has taxonomy term ID, and configure it to Load filter from node page (NOT taxonomy term page). Take a look at screenshots from this answer: display lists of related content that share the same Taxonomy term.
In the end place the Block in a region, and configure the block settings (to display only on node page where you want).
When your content creators save a new node, that Block will automagically show only Teasers of content tagged with the term they chose when creating the node.
If the content type of the created node is the same as the content type of teasers in the Block, the newly created node will also be displayed on the Teaser list. If you don't want the node you're currently viewing to be listed there you can exclude it with an additional Contextual Filter Content: ID (Provide default value: Content Id from URL, More (at the bottom): Exclude).
Comment: THANK YOU! We've been trying to do this for 24 hours at work! This was exactly what we needed! Thanks again for your help.
Comment: I'm glad to help :)


How to fix "Object reference not set to an instance of an object" - when calling RequestClientCredentialsTokenAsync?

Question: When I'm trying to send a request to:
 var client = new HttpClient();
 var resp = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = "http://localhost:5000/connect/token",
                ClientId = clientId.AsString(),
                ClientSecret = clientSecret,
                GrantType = grantType,
                Scope = scopes
            });

I'm catching an exception: System.NullReferenceException: 'Object reference not set to an instance of an object:
crit: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Unhandled exception: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
   at IdentityServer4.Validation.DefaultClientConfigurationValidator.ValidateUriSchemesAsync(ClientConfigurationValidationContext context) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Validation\Default\DefaultClientConfigurationValidator.cs:line 148
   at IdentityServer4.Validation.DefaultClientConfigurationValidator.ValidateAsync(ClientConfigurationValidationContext context) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Validation\Default\DefaultClientConfigurationValidator.cs:line 52
   at IdentityServer4.Stores.ValidatingClientStore`1.FindClientByIdAsync(String clientId) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Stores\ValidatingClientStore.cs:line 61
   at IdentityServer4.Stores.IClientStoreExtensions.FindEnabledClientByIdAsync(IClientStore store, String clientId) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Extensions\IClientStoreExtensions.cs:line 23
   at IdentityServer4.Validation.ClientSecretValidator.ValidateAsync(HttpContext context) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Validation\Default\ClientSecretValidator.cs:line 67
   at IdentityServer4.Endpoints.TokenEndpoint.ProcessTokenRequestAsync(HttpContext context) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Endpoints\TokenEndpoint.cs:line 78
   at IdentityServer4.Endpoints.TokenEndpoint.ProcessAsync(HttpContext context) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Endpoints\TokenEndpoint.cs:line 70
   at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Hosting\IdentityServerMiddleware.cs:line 54

It's a really "good" describing about error... I'm trying to debug identity code from the library by using resharper. When I'm stepped the line 58 of ValidatingClientStore.cs file which represented by this code:
 var context = new ClientConfigurationValidationContext(client)

I'm getting the error I've mentioned above. It's just redirected me to
C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Validation\Default\DefaultClientConfigurationValidator.cs:line 148

for the method signature... That's all. I can't understand what I'm doing wrong...I'm trying to override the identity components and I'm stuck with that error.

My Startup.cs configuration:
 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var scope = Configuration["Authentication:Scope:Name"];

            services.AddCors(options =>
            {
                // this defines a CORS policy called "default"
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins("http://localhost:4300")
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });

            services.AddAuth(options =>
            {
                options.Security = new SecurityOptions
                {
                    RequiredScope = scope,
                    IntrospectionOptions = new OAuth2IntrospectionOptions
                    {
                        Authority = Configuration["Authentication:Settings:Authority"],
                        ClientId = Configuration["Authentication:Settings:ApiName"],
                        ClientSecret = Configuration["Authentication:Settings:ApiSecret"],
                        SaveToken = bool.Parse(Configuration["Authentication:Settings:SaveToken"]),
                        NameClaimType = Configuration["Authentication:Settings:NameClaimType"],
                        RoleClaimType = Configuration["Authentication:Settings:RoleClaimType"]
                    }
                };
            });

            services.Configure<List<ApiResourceOption>>(Configuration.GetSection("ApiResources"));
            services.Configure<List<ClientOption>>(Configuration.GetSection("Clients"));
            services.Configure<IdentityServerAuthenticationOptions>(Configuration.GetSection("Authentication:Settings"));

            //register main stores for identity
            services.AddIdentityCore<ApplicationUser>()
                .AddRoles<ApplicationRole>()
                .AddUserStore<ApplicationUserStore>()
                .AddRoleStore<ApplicationRoleStore>()
                .AddUserManager<ApplicationUserManager>()
                .AddUserValidator<CustomUserValidator<ApplicationUser>>()
                .AddDefaultTokenProviders();

            //register identity server
            services.AddIdentityServer(c =>
                {
                    c.Caching.ClientStoreExpiration = TimeSpan.FromDays(1);
                    c.Caching.ResourceStoreExpiration = TimeSpan.FromDays(1);
                })
                .AddAspNetIdentity<ApplicationUser>()
                .AddClientStore<ApplicationClientStore>()
                .AddResourceStore<ApplicationResourceStore>()
                .AddProfileService<ProfileService<ApplicationUser>>()
                .AddResourceOwnerValidator<CustomResourceOwnerEmailValidator<ApplicationUser>>()
                .AddDeveloperSigningCredential();

            services.AddScoped<IPasswordHasher<ApplicationUser>, IdentityHasherService<ApplicationUser>>();
            services.AddScoped<IPersistedGrantStore, ApplicationPersistedGrantStore>();

            services.TryAddScoped<IPasswordValidator<ApplicationUser>, PasswordValidator<ApplicationUser>>();
            services.TryAddScoped<IPasswordHasher<ApplicationUser>, PasswordHasher<ApplicationUser>>();
            services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
            services.TryAddScoped<IRoleValidator<ApplicationRole>, RoleValidator<ApplicationRole>>();
            services.TryAddScoped<IdentityErrorDescriber>();
            services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<ApplicationUser>>();
            services.TryAddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, UserClaimsPrincipalFactory<ApplicationUser, ApplicationRole>>();
            services.TryAddScoped<UserManager<ApplicationUser>, UserManager<ApplicationUser>>();
            services.TryAddScoped<SignInManager<ApplicationUser>, SignInManager<ApplicationUser>>();
            services.TryAddScoped<RoleManager<ApplicationRole>, AspNetRoleManager<ApplicationRole>>();

            services.Configure<AuthSettings>(Configuration.GetSection("Authentication:Settings"));

            string connection = Configuration.GetConnectionString("Default");
            services.AddDbContext<IdentityContext>(options =>
                options.UseSqlServer(connection));

            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

            services.AddMvcCore().AddJsonFormatters();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors("default");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseIdentityServer();
            app.UseMvc();
        }
    }

resp.Value has a html page with error description:
Comment: This is not a duplication question about NullReferenceExceptions in general. This is a question about how to use IdentityServer4, as per the tag.
Answer: According to the stack trace above, the exception occurs in ValidateUriSchemesAsync() code, so most likely there is a null value in RedirectUris or PostLogoutRedirectUris in one of the client configurations object.


Expiring Inactive User Accounts

Question: I want to have some method of determining which user accounts have remained unused for a certain period of time, lock the accounts, and then after a further period, delete the accounts (notifying the user at each step).
These user accounts (in my case) can be used for ssh, ftp, pop3, and webmin/usermin - so any activity of any type should mark the account as active
How can I determine simply which accounts have been unused (for anything) for a certain period of time?
I have written a custom script that parses several logfiles (one for each type of login) every day to determine who has had any activity that day. But I suspect this is not the best way to do this.
Is this the best way to do this, or is there a simpler way (or perhaps a standard utility) to accomplish this?
Answer: I have written a script that scans all the relevent logs daily, makes a list of people that have had any activity that day, and maintains database (just a text file) of users and the last time they logged in.
Then I have a second script that examines the database for dates more than x days ago, an notifies the user and administrator 2 weeks prior to locking the account.  And if there are any dates more than x+y days ago, deletes the account altogether.
This seems to be working for me - but I would like to use a non-proprietary solution if one is available.

Expiring Inactive User Accounts


Cannot load github.com/open-policy-agent/opa/capabilities: no Go source files

Question: I was trying to install the OPA library using command
go get github.com/open-policy-agent/opa/rego
but installation is getting stuck with message
build github.com/open-policy-agent/opa/capabilities: cannot load github.com/open-policy-agent/opa/capabilities: no Go source files

Below is the o/p of command:
-bash-4.2$ go get github.com/open-policy-agent/opa/rego
go: finding github.com/open-policy-agent/opa/rego latest
go: finding github.com/open-policy-agent/opa v0.53.1
go: downloading github.com/open-policy-agent/opa v0.53.1
go: extracting github.com/open-policy-agent/opa v0.53.1
go: downloading github.com/gorilla/mux v1.8.0
go: downloading github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0
go: downloading github.com/sirupsen/logrus v1.9.2
go: downloading github.com/go-ini/ini v1.67.0
go: downloading go.opentelemetry.io/otel v1.14.0
go: extracting github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0
go: downloading github.com/prometheus/client_golang v1.15.1
go: downloading github.com/OneOfOne/xxhash v1.2.8
go: downloading gopkg.in/yaml.v2 v2.4.0
go: downloading github.com/gobwas/glob v0.2.3
go: extracting github.com/gorilla/mux v1.8.0
go: downloading github.com/tchap/go-patricia v2.2.6+incompatible
go: extracting github.com/prometheus/client_golang v1.15.1
go: extracting gopkg.in/yaml.v2 v2.4.0
go: extracting github.com/sirupsen/logrus v1.9.2
go: extracting github.com/OneOfOne/xxhash v1.2.8
go: extracting go.opentelemetry.io/otel v1.14.0
go: extracting github.com/tchap/go-patricia v2.2.6+incompatible
go: extracting github.com/go-ini/ini v1.67.0
go: downloading github.com/yashtewari/glob-intersection v0.1.0
go: downloading github.com/tchap/go-patricia/v2 v2.3.1
go: downloading github.com/ghodss/yaml v1.0.0
go: downloading github.com/agnivade/levenshtein v1.1.1
go: extracting github.com/tchap/go-patricia/v2 v2.3.1
go: downloading github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415
go: extracting github.com/yashtewari/glob-intersection v0.1.0
go: extracting github.com/ghodss/yaml v1.0.0
go: extracting github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415
go: extracting github.com/gobwas/glob v0.2.3
go: downloading github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb
go: downloading golang.org/x/sys v0.8.0
go: extracting github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb
go: extracting golang.org/x/sys v0.8.0
go: downloading google.golang.org/protobuf v1.30.0
go: downloading github.com/prometheus/client_model v0.3.0
go: downloading github.com/prometheus/common v0.42.0
go: downloading github.com/beorn7/perks v1.0.1
go: downloading github.com/cespare/xxhash v1.1.0
go: extracting github.com/agnivade/levenshtein v1.1.1
go: extracting github.com/prometheus/common v0.42.0
go: extracting github.com/beorn7/perks v1.0.1
go: extracting github.com/prometheus/client_model v0.3.0
go: extracting github.com/cespare/xxhash v1.1.0
go: downloading github.com/prometheus/procfs v0.9.0
go: downloading github.com/cespare/xxhash/v2 v2.2.0
go: extracting google.golang.org/protobuf v1.30.0
go: downloading github.com/golang/protobuf v1.5.3
go: extracting github.com/cespare/xxhash/v2 v2.2.0
go: extracting github.com/golang/protobuf v1.5.3
go: extracting github.com/prometheus/procfs v0.9.0
go: downloading go.opentelemetry.io/otel/sdk v1.14.0
go: extracting go.opentelemetry.io/otel/sdk v1.14.0
go: downloading github.com/go-logr/logr v1.2.4
go: extracting github.com/go-logr/logr v1.2.4
go: downloading github.com/go-logr/stdr v1.2.2
go: extracting github.com/go-logr/stdr v1.2.2
go: downloading github.com/matttproud/golang_protobuf_extensions v1.0.4
go: extracting github.com/matttproud/golang_protobuf_extensions v1.0.4
go: downloading go.opentelemetry.io/otel/trace v1.14.0
go: extracting go.opentelemetry.io/otel/trace v1.14.0
go: finding github.com/OneOfOne/xxhash v1.2.8
build github.com/open-policy-agent/opa/capabilities: cannot load github.com/open-policy-agent/opa/capabilities: no Go source files

Is there any pre-requisite before installation of OPA? or am I missing something during installation?
-bash-4.2$ uname -a
Linux dev-rh72-tas-1.in.intinfra.com 3.10.0-327.el7.x86_64 #1 SMP Thu Oct 29 17:29:29 EDT 2015 x86_64 x86_64 x86_64 GNU/Linux

Comment: What do you mean or expect from "to install the OPA library using command go get github.com/open-policy-agent/opa/rego"? Do you want to add package rego as a dependency to your module? You cannot "install" libraries. You can "install" commands/executables (via `go install`).
Answer: Your Go version is outdated since several years. Opa requires at least Go 1.16
Comment: After installing go version "go version go1.20.2 linux/amd64" now issue is resolved. Thanks
Comment: on Ubuntu 20.04, installing apt package `golang-go` gives you old version 1.13. Prefer installing package `golang-1.21-go`


Storage access automatically granted for tracker "https://duckduckgo.com"

Question: I hope I didn't miss something somewhere, but I can't get to understand what is exactly happening with what I'm doing.
I'm programming a webapp and in my app I open programmatically a new page to search something in duckduckgo. I'm using the following code window.open("https://duckduckgo.com/?q=something") which is good for me.
This all works fine, but I noticed that when this code is executed, in my console, the following is logged:

Storage access automatically granted for tracker "https://duckduckgo.com" on "http://localhost:8000".

I'm wondering what this means.
I'm aware that it's probably not something related to duckduckgo itself, maybe just that they are nice enough to actually log something and be transparent.
What information is exactly shared with an external website when using window.open? What does this "granting access to the tracker" mean? Where is this log in my console coming from? Can an external site actually execute some javascript code in my current page? This seem strange to me and would sound disastrous for privacy.
Comment: Documented [here](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Privacy/Storage_access_policy).  I'm thinking you were automatically granted access because you've interacted with DDG before.
Answer: So from what I understand from this firefox documentation page (plus a bit of experimenting with window.open):
When window.open is ran to open https://duckduckgo.com, this allow any tracker from https://duckduckgo.com that would be loaded from localhost now or in the next 30 days, to have access to it's own domain storage (and not only the one of localhost).
The message is logged by firefox itself to inform that you just granted this right to https://duckduckgo.com.
(Thanks a lot Amy for the link that allowed me to learn and answer myself :))
Comment: I don't clearly understand what you mean when you say "and not only the one of localhost". Is duckduckgo being granted any access to anything other than duckduckgo's data? That's the main concern; can they track your page's data? For example, can they see any private data that may be in the script that calls `window.open`, or any data that the calling script stores in local storage?
Comment: @LonnieBest Would also be curious about details on this, this is what the article I mention says about this: "The restrictions applied by the policy will not prevent third-party scripts classified as tracking resources from accessing storage in the main context of the page. These scripts can continue to use storage scoped to the top-level origin."


Definition of Galois representation unramified at a prime.

Question: In J. Weinstein's note: Reciprocity laws and Galois representations: recent breakthroughs, section 3.3, a Galois representation that is unramified at a prime $\mathfrak{p}$ is defined in a different way.
Suppose $K$ is a number field with absolute Galois group $\text{Gal}(\bar{K}/K)$, and $F$ is a topological field, a Galois representation $\rho$ is a continous homomorphism
\begin{equation}
\rho:~\text{Gal}(\bar{K}/K) \rightarrow\text{GL}_n(F)
\end{equation}
$\rho$ is unramified at a prime $\mathfrak{p}$ of $K$ if it factors through $\text{Gal}(L/K)$, where $L/K$ is some (possibly infinite) algebraic extension which is unramified at $\mathfrak{p}$. The common definition in literature is that $\rho(I_{\mathfrak{p}})$ is trivial, where $I_{\mathfrak{p}}$ is the initial group at $\mathfrak{p}$.
Anyone knows how to show their equivalences?
Comment: Usually, for an infinite extension, one *defines* a prime to be unramified if its inertia group is trivial. For finite extensions, the equivalence follows by proving that the order of the inertia group is exactly the ramification index. Notice that the inertia group of $L/K$ is exactly the image of $I_\mathfrak p$
Answer: $\require{AMScd}$
If $\rho$ factors through some $\overline{\rho}\colon \mathrm{Gal}(L/K) \to \mathrm{GL}_n(F)$ with $L/K$ unramified at $\mathfrak{p}$, then the image of $I_{\mathfrak{p}}$ under $\rho$ is
\begin{equation*}
\rho(I_{\mathfrak{p}}) = \overline{\rho}\circ \pi(I_{\mathfrak{p}}) = \overline{\rho}(I_{\mathfrak{p}}(L/K)) = \overline{\rho}(1)=1
\end{equation*}
because $\mathfrak{p}$ is unramified in $L/K$ so it must have trivial inertia group there, and the image of the absolute inertia group in some intermediate extension is the inertia group of that extension.
Conversely, if $I_{\mathfrak{p}}$ is trivial then the statement is trivial as well. If on the contrary $I_{\mathfrak{p}}\neq 1$ then $\rho$ factors through $\mathrm{Gal}(L/K)$ where $K\subseteq L\subseteq \overline{K}$ is the maximal extension where $\mathfrak{p}$ is unramified. Indeed, the kernel of the projection is exactly $I_{\mathfrak{p}}$ which lies in the kernel of $\rho$.
Comment: Thank you! I forget about the largest unramified extension!
Comment: @Alessandro, why $ \overline{\rho}\circ \pi(I_{\mathfrak{p}}) = \overline{\rho}(I_{\mathfrak{p}}(L/K))$ ? How it is obtianed? Can you explain it shortly please? I am beginner


how to install flake8 in atom on windows

Question: I have follow, these steps, but
"apm install linter
Next, we're going to install a Python Linter package, to help us detect errors in our Python code.
This package is called linter-flake8 and it's an interface to flake8. To install it, you need to run:
pip install flake8
pip install flake8-docstrings
apm install linter-flake8
You must restart Atom to see the changes"
I have followed those steps and every package with PIP and APM were installed, however, corrections are not made on my python code in ATOM. Is there something else i need to configure or to do appart from steps i mentioned?
2
3
Answer: It could be your Environment Variable paths, especially if you have two concurrent versions of Python installed. Check to see which one is at the top of the list and ahead of the one your not currently developing within.
Answer: I'll try to give you an example of my installation
Installation path of python in my computer is
C:\Python36-32

So in control panel in system settings in advanced settings in path i add the following paths
C:\Python36-32
C:\Python36-32\Scripts

Now i reopen the cmd and i enter python if it worked you will see the python interpreter line.
To install flake8 system wide run the command
pip install flake8

In atom editor install  the package linter-flake8.When package is installed in settings of package in package path add the full path of package for example in my configuration i have in path
C:\Python36-32\Scripts\flake8   without the .exe

Answer: Maybe you got installed flake8 on C:\Users\myuser\AppData\Roaming\Python\Python3X\Scripts just like me. If that is the case you only need to add that location to the PATH.


Augmented Dickey-Fuller test performed regression in package urca. Problem with lags

Question: I'm having troubles in understanding the steps performed by the ur.df function in R. I'm performing an Augmented Dickey-Fuller Test with drift to assess if my series has a unit root or not. The first time i chose to set maximum lags equal to 9 and the second time i set the maximum lag equal to 5. The function should select the best lag order through the AIC. I don't know why the statistics of the test where i set the maximum lag=9 is different from the test where i set the maximum lag equal to five. They both should derive from the regression with just two lags because the regression with two lags is the best one according to the AIC. Why are they different? I'm missing something.

These are the code and the results of the test:
<code>    test=ur.df(myseries,type="drift",lags=9,selectlags = "AIC")
    summary(test)
###############################################
# Augmented Dickey-Fuller Test Unit Root Test #
###############################################

Test regression drift

Call:
lm(formula = z.diff ~ z.lag.1 + 1 + z.diff.lag)

Residuals:
    Min      1Q  Median      3Q     Max
-5.6558 -0.8559 -0.1850  0.9438  3.3900

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   0.3351     0.4166   0.804   0.4282
z.lag.1      -0.3662     0.2171  -1.687   0.1032
z.diff.lag1  -0.1267     0.2032  -0.624   0.5381
z.diff.lag2  -0.3465     0.1834  -1.890   0.0696 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.744 on 27 degrees of freedom
Multiple R-squared:  0.3679,    Adjusted R-squared:  0.2976
F-statistic: 5.238 on 3 and 27 DF,  p-value: 0.005583

Value of test-statistic is: -1.6868 1.5055
</code>
It seems that the program set the best lag to 2 according to the AIC. If i set the maximum lag equal to 5 it chooses again the lag 2 as the best one but now the p-value is different. Here are the results
<code>    test=ur.df(myseries,type="drift",lags=5,selectlags = "AIC")

###############################################
# Augmented Dickey-Fuller Test Unit Root Test #
###############################################

Test regression drift

Call:
lm(formula = z.diff ~ z.lag.1 + 1 + z.diff.lag)

Residuals:
    Min      1Q  Median      3Q     Max
-5.5543 -0.9269 -0.2216  0.9126  3.4027

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.44241    0.39802   1.112   0.2749
z.lag.1     -0.45811    0.19678  -2.328   0.0266 *
z.diff.lag1 -0.01737    0.17767  -0.098   0.9227
z.diff.lag2 -0.29120    0.16638  -1.750   0.0900 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.7 on 31 degrees of freedom
Multiple R-squared:  0.3694,    Adjusted R-squared:  0.3083
F-statistic: 6.052 on 3 and 31 DF,  p-value: 0.002287

Value of test-statistic is: -2.3281 2.9333
</code>
Comment: What is your question?
Comment: I don't know why the statistics of the test where i set the maximum lag=9 is different from the test where i set the maximum lag equal to five. They both should derive from the regression with just two lags because the regression with two lags is the best one according to the AIC and so the best regression should provide one test statistic wich should be independent from the maximum lag chosen
Comment: Maybe when setting the maximum lag to $k$, all models are estimated on a sample where $k$ initial observations are discarded, even though it is technically possible to estimate models with non-maximum $k$ on samples longer than that. (But you need the same sample to be able to compare AIC values.) So probably the underlying data set gets truncated to a different degree for different maximum $k$, and thus the estimates and the test statistics change even if the selected model remains the same.
Comment: You're right. If i look at the degree of freedom in the output they are different. Thank you, i'll try to replicate these regression manually to check if it's true
Comment: @RichardHardy Of course!your answer was exactly  what I was looking for!
Answer: Perhaps when setting the maximum lag to $k$, all models are estimated on a sample where $k$ initial observations are not considered (but they are used when lags of the original time series are formed), even though it is technically possible to estimate models with non-maximum $k$ on samples longer than that. (Recall that you need the exact same sample to be able to compare AIC values.)
So the underlying data set gets truncated to a different degree for different maximum $k$, and thus the estimates and the test statistics change even if the selected model remains the same.
Comment: This is correct, and also the reason why you should not pick an unreasonably large maximum lag order and just hope that the the IC will select a low order for you anyway (especially if you have a very short series).


Is It a Bad Idea to Install the OS GUI on a Server That Will Host Asterisk?

Question: We have a server onto which we plan to install CentOS 6.2.  The server will host Asterisk for our office, but is not a webserver.
If we install the minimal installation for CentOS - that is, no GUI for the OS, then that means that Asterisk will also not be able to be interfaced with a GUI such as FreePBX or Elastix.
I found this thread useful in the consideration:
Should I use an Asterisk GUI?
My thinking is to provide the GUI for folks who may have to succeed me and who do not know Asterisk so well as to manually maintain the configuration files.
Now, I understand that it is better for a server to run without a GUI. But if it is only meant to host Asterisk, then is it still a bad idea to install the GUI?
Answer: Generally speaking, the more extraneous software you run results in two problems:

Reduced memory availability for the software you actually care about
A greater likelihood that your server will be vulnerable due to an unpatched security vulnerability.

If your application is not memory intensive, or under particular memory pressure for your hardware, you don't really need to worry about (1). If you can completely isolate the environment your server runs in (hint: you probably can't), then you don't need to worry about (2).
Aren't the GUIs of popular applinces like FreePBX and Elastix web-based anyway? Not sure why you think the OS on your server requires a window manager for a web-based user interface. You say it's not a webserver - what does this mean? You're not allowed to / don't want to install a webserver?
Comment: By _not a webserver_ I mean that it won't be used to serve up any public websites.  Honestly, though, I didn't realize that FreePBX and Elastix were web-based - (I am in new territory, and there is soooo much to be known and read, I dispair of making any progress on my deadline) - I imagined them to use OS-based GUI's instead.  However, if they are web-based, then I wouldn't need the OS GUI to support them anyway.
Answer:
My thinking is to provide the GUI for folks who may have to succeed me and who do not know Asterisk so well as to manually maintain the configuration files.

This seems like a silly assumption from the start. For one thing, virtually all of the documentation available for asterisk is in the form of config files, someone approaching your setup from no prior knowledge is more likely to find instructions to deal with those very configs, not a GUI tool.
On the other hand; someone who already knows how to use a particular config tool can probably also sort out how to install it.

In general, I'm very reluctant to install anything that might affect the performance of asterisk (or freeswitch, which we've mostly migrated to).  unlike most other services, media switches are highly sensitive to disturbances of load, which may be reflected in poor call quality.  Except for things that are actively used, we meticulously police the set of start-up services that run on the switch; and offload absolutely everything we possibly can (within practical reason, of course).
Comment: Maybe it seems silly to you, but you don't know the people I am working with!  I have been writing my own directions anyway for doing the manual editing.  I was thinking that since I am installing everything anew, I might want a GUI interface for Asterisk.  Problem with that is, that *I* don't want to use the GUI! I *want* to edit manually, but leave a way for others to maintain the system in case I am not available.
Comment: Oh... well if you have people that want to use it *now*, that's another matter.  It's perfectly reasonable to support actual users with needs today.   That said, If it's practical to run those tools on a second box, that's just what I'd do.
Answer: I generally do not recommend it. Even more so if you plan on installing telephony hardware. Certain video card / driver combinations can take a not-insignificant amount of time scrolling the video display which will cause some cards to miss their deadlines or increase jitter on RTP streams.  I've seen it work, and I've seen it cause problems.
Comment: Right, and many Zaptel cards, in order to minimize the amount of latency they introduce into conversations are designed to service their interrupts at 1 ms intervals. Many video drivers run processing with interrupts locked for longer than 1ms, which can cause issues with the audio.
Comment: the only hardware I would install for serving up Asterisk is a zaptel card.  The phones are all external, you know.
Comment: Hmmm.  That is very interesting!  Would it be enough to install the OS GUI but to set the system to boot using runlevel 3?