Teaching using the Piano Adventures series

Question: I am currently teaching five young piano students using the Piano Adventures curriculum (which is the method I learned by) and so far I am really in love with those books! However, two of my students have recently been causing me concern by developing the same exact problem. They have super slow sight-reading and often hit wrong notes without realizing it. Also, they pause for a long time at the end of each phrase and no matter how many weeks I assign- "Practice counting out loud and taking out all the pauses between measures", it never gets better.
They also seem to have no sense of note duration and pretty much never hold down a note longer than it takes to strike the key. I've explained to them many times about note duration, (demonstrating, counting, and then playing along with them, having them count out loud, etc.), but as soon as I leave them on their own it all goes out the window! They seem to have not sense of what music is at all and I am started to get very frazzled at the end of the teaching day.
Any help would be greatly appreciated! They are both in the red level (level 1) of PA, and I have them doing the lesson and theory book, and I have one reviewing with some of the later songs in Primer Performance.
Comment: Not expert advice but from my experience learning piano I wonder if it might help to reach out to other resources, like perhaps a Suzuki book, just for specific exercises. Suzuki has timing and rhythm exercises and also emphasizes listening to the same things that one is playing, so the student hears how it "should" be played. Suzuki does not help as much with sight reading, IME, though, but might be just the thing for note durations.
Comment: Depending on how young exactly your students are this behavior may be normal. If they are very young, group singing, rhythmic orchestra, and learning by example (as per the Susuki method like suggested by Todd), may be the most appropriate approach, not sight reading and counting.
Answer: Try playing a few tunes that they know well, but with different timings. Ask them to recogise the tunes - which will be impossible.That's the time to explain timing! Also, play long/short notes for recognition purposes, as a game. then introduce middle length notes and so on. Sight reading is NEVER going to be successful when done by students on their own. How can it? If no-one is around with some expertise when they 'try' to do it, it's a complete waste of playing time, so far. Later, when some skills are available, it takes on a different mantle, but for now, it's pointless.
What's worked well with my pupils on sightreading is to clap the rhythm out first (me counting). Also, use words for different note values - minim = walk, crotchet = jog, etc. With sightreading in the early stages, there are at least 3 things to do at once - read note on dots; find note on keys; hold down for appropriate length of time. It's all too much for a lot of youngsters, so split up the task.
Answer: When your students aren't "getting" something, then you need to devise other ways of explaining it.  If you're frazzled (and any teacher gets that way), take a step back and start working with your intuition and imagination.  How else could you explain?
Teaching is learning, and learning is teaching.  As you find new ways to get them to understand what you're trying to show them, you learn things about how their minds work.  You have to always be learning from your students, if you're to always be teaching them.  You'll want to keep that in mind as you deal with the frustration.
One suggestion comes to mind.  Think about how a child learns to read written words.  While there is some learning of the sounds that letters make ("sound it out," our teachers would say), there is also the process of learning to associate written words with spoken words by rote.  (Sounding out "rough", "cough", "dough" and "through" has limited value, for example.)  So, try taking a song from the book that they already know, and have them learn to play it by ear.  (Melody only perhaps.)  Work with them to get it correct.  Then show them the music in the book and ask them to play that, explaining that the music is a dressed up version of what they've already played.  This should help make the association between the written music and the actual music clearer.  As you relate the written score to the tune they know, things might begin to click for them.
Once they get the association between note values and rhythm, then you can begin challenging them more.  Sight reading requires this understanding, of course.  By the way, someone once said that the only way to get good at sight reading is to sight read!  So yes, they have to do it.  But they need to be able to read first.
One more thing.  Sell, don't tell.  :)
Comment: +1 for teaching is learning! Absolutely. I probably have learned more from teaching tham I ever learned by being taught!
Comment: It has been said that knowledge is gained in four phases: receive, learn, apply, teach.  :)
Comment: Yes, I've always thought that to teach something well, you need to understand it, so learn it better yourself. And if it's difficult, it'll give you empathy for the poor *** who has to learn it from you...
Comment: I've found teaching to be an endlessly creative process, where I constantly have to come up with variations on how to explain things.  There's some process of emotional connection that has to happen.  (cont)
Comment: One of my brothers teaches high school. If a cell phone rings or he catches someone texting in class, he confiscates the phone for the duration, explaining that it isn't the student's fault, but the cell phone's, and that the phone's punishment is to be put in "cell phone jail".  One student presented him with a wooden "cell phone jail", complete with cell-phone-sized cells, that now hangs on the wall of his classroom.  To me, that sort of goofiness is an example of connecting emotionally with the students.
Comment: Great! And the connection is often different for every student. It was finding a common denominator tha was the fun part when I had classes of 30 (and 46 in the early days!)
Comment: Just so. :) ...


How to send/broadcast ipv6-mac maping cache update request for IPv6 IP

Question: We can update IPv4 neighbors by using arping command. I have used arping -A -I -c  <interface_name> <IP_address_of_interface> with success.
what is the command to update mapping of IPv6 address and mac on router/gateway/nodes. we have observed when IPv6 address is removed from one node N1(RHEL-7.9 Node) and assigned to other node N2(RHEL-7.9 Node), mac address on router(Extreme Networks VDX 8770) dont get updated. It eventually gets updated but that time is not consistent. for this duration N2 is not reachable to gateway.
Comment: Please edit your question to add the operating system of relevant hosts and routers. You tagged this Linux, but your comments indicate something else.
Answer: For service addresses, implement a high availability protocol that can move IP addresses quickly. For example VRRP via keepalived.
To manipulate the neighbor cache on one Linux host, use a command like  ip neighbour flush to ${ADDRESS}  The kernel will do discovery when it encounters that IP again, do something like ping ${ADDRESS}  This does not affect other hosts' neighbor cache. Other platforms and IP stacks have different commands.
IPv6 neighbor advertisement is not using broadcast, it is using a targeted solicited multicast group. One way getting all hosts involved is playing with router advertisements and virtual MAC addresses.  In other words, VRRP.
Edit: ND spec allows for unsolicited advertisements to all nodes multicast. But it is an optional MAY, so you might want to trigger it manually. See also on Server Fault: Linux tool for IPv6 unsolicited neighbor advertisements.
Comment: This is not router or failover case or virtual ip, In this case when N1 who has IPv6-ip1 is shut off, and N2 is assigned with IPv6-ip1, mac table on router is still IPv6-ip1-mac-N1. it should be mac-n2. The router is not linux machine. question is from N2 - what can we do to update new mac on router. doing Ping is not working.
Comment: See edit adding a mention about unsolicited advertisements.  How fast do you need cutover to be?  ND should figure it out in a leisurely few minutes, but seems like that's not fast enough for you.
Comment: ndptool with -T is solution. thanks @John for pointer.


repeated measures ANOVA, crossover trial, R

Question: I am sorry for stating such a question. Unfortunatelly, it's very-very hard to go through all statistics.
I have a crossover study design with 3 treatments, 3 periods, and a baseline (covariate).
The data table looks like this:
SUBJECT     BASELINE   PERIOD1    PERIOD2    PERIOD3

subj_1      baseline   diet3      diet1      diet2
subj_2      baseline   diet2      diet3      diet1
subj_3      baseline   diet1      diet2      diet3
subj_4      baseline   diet1      diet3      diet2
...         ...        ...        ...        ...
subj_27     baseline   diet2      diet1      diet3

PERIOD1, PERIOD2, PERIOD3 correspond to the time (week5, week11, week17). In between there is wash-out period.
My question is how to perform repeated measures ANOVA to such a experimental design?
I was trying to search for some examples and code but what I found out at the end is that I can apply mixed effect linear model to such data. Unfortunatelly, I did not find enough examples describing similar studies and the theory behind is very hard (I need time to understand).
I'm trying to find solution in R but SAS is also good. As I understood, in R there is a package nlme and I can apply a function lme() to fit an ANOVA model.
In order to do so, I found out that I have to divide my data according to treatment sequences (I will have 6 sequences: diet1-diet2-diet3, diet1-diet3-diet2, diet2-diet1-diet3, diet2-diet3-diet1, diet3-diet1-diet2, diet3-diet2-diet1).
Then I have to create a mixed effect linear model:
I assume (according to what I read and found) that probably it should look like this:
output_value ~ period(fixed effect) + diet(fixed effect) + sequence(fixed_effect)
                   + subject(random_effect) + baseline_value(random_effect)

In R it probably looks something like:
lme( output_value ~ period + diet + sequence, random ~ 1 | subject + baseline_value )

Is it right?
Comment: If I understand your study correctly, this is not a repeated measure study, as your treatment changes in each period. It seems more like a cross-over design to me (as you have also pointed out).
Comment: @qoheleth, Unfortunatelly, I didn't know the right terms. But thanks for your comment.
Comment: @qoheleth As I understood, it does not matter whether it is a time factor or condition factor: it will be anyway repeated measures?
Comment: repeated measures are multiple measures taken on the same experimental unit. Your experimental unit here is a subject at a particular period, rather than just a subject. If it was the later then it would be a repeated measure design. But since treatment changes from period to period, the exp. unit is the former one so I think a crossover design is the correct description. Perhaps you can search for crossover design and see how people analyse it?
Comment: Yes, there are examples. They all are based on building mixed effect models. But I don't understand which parameters I should use as a fixed effect and which as a random effect and whether I should use 'sequence' parameter.
Answer: In a crossover design, the effects that usually need to take into account are fixed sequence effect, period effect, treatment effect, and random subject effect. Note that by design the subject factor is nested within sequence (meaning that different subjects go through different sequences).
Basically you might want to keep all the effects in the model, and test whether they are significant or not. Prior to build the model, you also might want to test the carryover effect.
I've not used R to perform this kind of data analysis. But I guess there are a lot of sample code illustrating how to write R for a mixed-effects model. As far as SAS code, here are two references I think that both explains the experiment design and the SAS code very well.
1. Crossover Designs and Proc Mixed In SAS
2. The 2-by-2 crossover study and Grizzle Model
Hope it helps.
Comment: Grizzle's approach to test for carry-over effects has been shown to introduce bias into the estimates of the coefficients. I can not recommend it.
Reference:
Freeman, P.R. (1989) The performance of the two-stage analysis of two-treatment, two-period crossover tirals. Statistics in medicine, 8: 1421-1432.
Answer: I am just suggesting following approach in R. I am not sure if it is the best way:
> ddf
  subject_id baseline period1 period2 period3
1          1        5       6       7       5
2          2        6       8       7       5
3          3        8       9       9       7

> ddf$period1diff = ddf$period1 - ddf$baseline
    > ddf$period2diff = ddf$period2 - ddf$baseline
> ddf$period3diff = ddf$period3 - ddf$baseline
>
>
> ddf
  subject_id baseline period1 period2 period3 period1diff period2diff period3diff
1          1        5       6       7       5           1           2           0
2          2        6       8       7       5           2           1          -1
3          3        8       9       9       7           1           1          -1
>
> melt(ddf[,c(1,6:8)], id='subject_id')
  subject_id    variable value
1          1 period1diff     1
2          2 period1diff     2
3          3 period1diff     1
4          1 period2diff     2
5          2 period2diff     1
6          3 period2diff     1
7          1 period3diff     0
8          2 period3diff    -1
9          3 period3diff    -1
> mm = melt(ddf[,c(1,6:8)], id='subject_id')
> aov.out = aov(value ~ variable + Error(subject_id/variable), data=mm)
> summary(aov.out)

Error: subject_id
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  1 0.6667  0.6667

Error: subject_id:variable
         Df Sum Sq Mean Sq
variable  2  7.476   3.738

Error: Within
          Df Sum Sq Mean Sq F value Pr(>F)
variable   2 0.8571  0.4286   1.286  0.395
Residuals  3 1.0000  0.3333
>

Answer: Most of the terms are right. I wouldnt put the baseline value in the model though. Plus would add fixed effects for time (before vs after treatment) and time-treatment interaction, as well as a term for the data that you're modeling (say "x"). The following command should work fine in the nlme package: lme( output_value ~ period + diet + time + sequence + time * diet , random ~ 1 | subject, data=x)


How to get the revisions list of a node and delete them all?

Question: Revisions and how to delete them all. For Drupal 7, there're plenty of modules that do that or even limit the revisions that are kept or even delete everything that is older then x-days, but not for Drupal 8.
It seems there is nothing out there. Searching through the database is something I like not to do.
Any ideas?
Comment: do you got some advance?
Answer: Yes, as you says there is a list of modules that can do this in Drupal 7 like:
Node Revision Delete

The Node Revision Delete module lets you to track and prune old
  revisions of content types. Define the max amount of revisions to keep
  per content type. Run on Drush, cron run or on a different period
  (daily, weekly, etc).

Node Revision Restrict

The Node Revision Restrict module allows you to restrict revisions of
  node for each content type. This module has an admin interface to
  specify node revision threshold for each content type available. The
  possible setting include node type with corresponding revision limit,
  provided on the Node Revision Restrict configuration form. Note that
  this module does not and cannot delete the current revisions of a
  node.

Node Revision Cleanup

Node Revision Cleanup is designed for really big databases. And site
  administrators who are comfortable with Drush. The concept behind this
  module is to be able to run multiple invocations at the same time, via
  Drush to maximize the number of node revision deletions per second.

Revision Deletion

This modules enables the ability to mass delete aging node revisions.
  Possible settings include node type, the age of node revision before
  being deleted, along with a Cron frequency setting. The revisions may
  be deleted after review on an administer page as well. This module
  will NEVER delete the current revision of a node, nor will it allow
  you to do so.

And for Drupal 8, well at this moment there is not module for do that, but you can use:
To get the revision list of a node:
$vids = \Drupal::entityManager()->getStorage('node')->revisionIds($node);

See Nodes now have a storage controller; node_revision_list() removed.
To delete a revision revision you can use the node_revision_delete() function, but at the end see the function code:
function node_revision_delete($revision_id) {
  \Drupal::entityTypeManager()->getStorage('node')->deleteRevision($revision_id);
}

So, is better if you just use:
\Drupal::entityTypeManager()->getStorage('node')->deleteRevision($revision_id);
Comment: @KimberlyW Just change entityTypeManager() for entityManager() and should works.
Comment: You can find content revision while creating a new view. And you can have option for delete revision link there.
Comment: For getting the revision list, is there an alternative for `entityManager`? I think its deprecated.
Comment: Same for this answer:
entityTypeManager()->getStorage() return a EntityStorageInterface. It does not have "revisionIds" method.
You must explicitly inject NodeStorageInterface to have the method.
Comment: @ssibal just read: https://api.drupal.org/api/drupal/core%21modules%21node%21src%21NodeStorageInterface.php/interface/NodeStorageInterface/8.0.x
Comment: @ssibal have you tested the code?
Comment: @AdrianCidAlmaguer: you still don't get my point. Of course it's going to give you back NodeStroageInterface and you will have the method but this turns out only in runtime. This is why you should inject it via proper dependency injection:

  node_storage:
    class: Drupal\node\NodeStorage
    factory: entity_type.manager:getStorage
    arguments: ['node']
  my_service:
    class: Drupal\MyModule\MyService
    arguments: ['@node_storage']
Comment: @ssibal can you add another answer with your code?
Comment: @AdrianCidAlmaguer I just did!
Answer: The suggestions in here are correct, though a few things is worth mention.
$vids = \Drupal::entityManager()->getStorage('node')->revisionIds(node_load($nid));

But since this is marked as deprecated, it should be replaced by:
$vids = \Drupal::entityTypeManager()->getStorage('node')->revisionIds($node);

The example code in here also try delete the default revision and that will cause [error]  Default revision can not be deleted. To avoid that I suggest that you wrap the removal in something like:
  // If revision id is not default, remove it.
  if ($vid !== $node->getLoadedRevisionId()) {
    print 'Removing revision ' . $vid . PHP_EOL;
    \Drupal::entityTypeManager()->getStorage('node')->deleteRevision($vid);
  }

Comment: This is a completely false answer.
entityTypeManager()->getStorage() return a EntityStorageInterface.
It does not have "revisionIds" method.
Comment: @ssibal true, but since we're dealing with node storage, we will be getting NodeStorageInterface, which does.
Answer: Snippet to delete all but the latest revision of a specific node:
<?php
  try {
    $nid = 123; // Your node id
    $vids = \Drupal::entityManager()->getStorage('node')->revisionIds(node_load($nid));
    foreach($vids as $vid){
      \Drupal::entityTypeManager()->getStorage('node')->deleteRevision($vid);
    }
  } catch (Exception $e) {
    // Latest revision will not be deleted but throws an error
    return $e->getMessage();
  }
?>

Comment: brilliant Thomas. I found this a better option seeing that none of the modules in Adrian's answer actually work in D8. Yours actually works when added to MYTHEME.theme file.

Could you maybe add a loop to the start so that it runs through all of the nodes?  That would make this super for taking a dev site to production and dumping all the dev revisions to lean up and clean up.
Answer: There is a working module for Drupal 8: Node Revisions Autoclean.

This module allows to manage node's revisions store : according to
  admin's settings, older revisions are automatically deleted.
You may choose how many revisions you want to keep for each node type.
  Latest drafts coming after a published revision are never deleted. You
  may also choose to delete revisions by date.
For larger websites with many node, you may choose to delete revision
  by cron or a drush command (drush 9 only).

Do not expect it to run on normal cron runs, yet. But it can be set to run on updating nodes. Here is the issue for the cron, which I do not fully understand: https://www.drupal.org/project/node_revisions_autoclean/issues/2958655
Answer: Please inject always a storage in the proper way:
  # my_module.services.yml
  node_storage:
    class: Drupal\node\NodeStorage
    factory: entity_type.manager:getStorage
    arguments: ['node']
  my_service:
    class: Drupal\my_module\MyService
    arguments: ['@node_storage']

In this case you can already have in your class constructor the following:
class MyService {

  /**
   * @var \Drupal\node\NodeStorageInterface
   */
  private $storage;

  public function __construct(NodeStorageInterface $storage) {
    $this->storage = $storage;
  }

}

In this case your IDE will also easily list all of the available methods unlike with this solution:
\Drupal::entityManager()->getStorage('node')->revisionIds(node_load($nid));

Remember EntityTypeManager is in most of the case "too much" power: use only as much as you need but not more. Service configurations can help you with that.
Comment: I will test your answer, can you provide some references about this?
Comment: https://symfony.com/doc/current/service_container/factories.html


Como obter o objeto com o foco no Android

Question: Ola a todos Eu tenho o seguinte Listener a baixo que verifica se um editText foi alterado, o Listener será idêntico para vários editText então eu gostaria de obter o editText atual através da propriedade "v", para evitar a repetição de código e criar apenas um "onFocusChangeListener" e atribuir a vários editText.
        edtDescPer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            executeOnChange = false;
            v.focus

            if (hasFocus) {
                sTemp = edtDescPer.getText().toString();
                edtDescPer.setText("");
            } else {
                if (edtDescPer.getText().toString().equals(""))
                    edtDescPer.setText(sTemp);
            }

            executeOnChange = true;
        }
    });

Answer: Você pode obter o elemento obtendo o id da view, através do método getId() , por exemplo
public void onFocusChange(View v, boolean hasFocus) {

 switch (v.getId()) {
    case R.id.editText1:
        //caso for o editText1
        break;
    case R.id.editText2:
        //caso for o editText2
        break;
    }
}

Crie o OnFocusChangeListener, separado, não já como parâmetro do edittext, por exemplo:
View.OnFocusChangeListener exemplo = new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                 switch (v.getId()) {
                      case R.id.editText1:
                         //caso for o editText1
                         break;
                      case R.id.editText2:
                        //caso for o editText2
                         break;
                      }
            }
        } ;

e depois só atribuir ao edittext
editText1.setOnFocusChangeListener(exemplo);
editText2.setOnFocusChangeListener(exemplo);

Comment: Marco a sua sugestão foi fundamental para resolver meu problema. Vou por o código de como ficou a minha função em um resposta, mas vou marcar a sua como como correta
Answer: Segue a baixo a declaração da função onFocusChangeListener feita com a dica do Marco Giovanni:
    View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        executeOnChange = false;
        EditText et = (EditText) findViewById(v.getId());

        if (hasFocus) {
            sTemp = et.getText().toString();
            et.setText("");
        } else {
            if (et.getText().toString().equals(""))
                et.setText(sTemp);
        }

        executeOnChange = true;
    }
} ;

Atribuição da função no onCreate:
edtDescPer.setOnFocusChangeListener(onFocusChangeListener);

Comment: Você não precisa fazer um `findViewById(v.getId())`, basta fazer um cast na `view` que você recebe como parâmetro, `EditText et = (EditText)v`
Answer: Você pode fazer com que sua classe implemente o OnFocusChangeListener, dessa forma:
public class MainActivity extends Activity implements OnFocusChangeListener {
    private EditText editText1, editText2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText1 = (EditText) findViewById(R.id.editText1);
        editText1.setOnFocusChangeListener(this);
        editText2 = (EditText) findViewById(R.id.editText2);
        editText2.setOnFocusChangeListener(this);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        String liganame = editText1.getText().toString();
        String liganame2 = editText2.getText().toString();

        if(liganame.length() == 0) {
            if(editText1.requestFocus()) {
                //primeiro
            }
        }

        if(liganame2.length() == 0) {
            if(editText2.requestFocus()) {
                //segundo
            }
        }

    }
}


Jsoup parece nao estar a funcionar

Question: Ola tenho este bocado de código que da um link e que vai a net com o jsoup tira alguma informação e depois mete essa informação numa ArrayList usada numa ListView. Mas o problema é que não sei porque a Array cursos não fica cheia , o site muda consoante a letra no url por isso e que faço este código . Não percebo porque e que ele não enche a variável cursos das .lin-area-c2 que estão no site.
Aqui esta o código :
<code>  public class Chose_curso extends AppCompatActivity {

private TextView pickLetraText;
private ListView cursoList;
private Spinner letraPicker;

private ArrayList<String> letras = new ArrayList<String>();
private ArrayList<String> cursos = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chose_curso);

    pickLetraText = (TextView) findViewById(R.id.pickLetraText);
    cursoList = (ListView) findViewById(R.id.cursoList);
    letraPicker = (Spinner) findViewById(R.id.letraPicker);

    letras.add("A");
    letras.add("B");
    letras.add("C");
    letras.add("D");
    letras.add("E");
    letras.add("F");
    letras.add("G");
    letras.add("H");
    letras.add("I");
    letras.add("J");
    letras.add("L");
    letras.add("M");
    letras.add("N");
    letras.add("O");
    letras.add("P");
    letras.add("Q");
    letras.add("R");
    letras.add("S");
    letras.add("T");
    letras.add("U");
    letras.add("V");

    ArrayAdapter<String> adapterLetras = new ArrayAdapter<String>(Chose_curso.this,android.R.layout.simple_spinner_item,letras);

    adapterLetras.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    letraPicker.setAdapter(
            new NothingSelectedSpinnerAdapter(
                    adapterLetras,
                    R.layout.contact_spinner_row_nothing_selected,
                    // R.layout.contact_spinner_nothing_selected_dropdown, // Optional
                    this));

    Document document = null;

    letraPicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            setCursoList();
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }

        });}

public void setCursoList(){
            try  {
                if(letraPicker.getSelectedItem()!=null){
                    cursos.clear();
                    Document document = null;

                    String site ="http://www.dges.gov.pt/guias/indcurso.asp?letra="+(letraPicker.getSelectedItem().toString());

                    document = Jsoup.connect(site).get();
                    for(int contador=0;contador<document.select(".lin-area-c2").size();contador++){
                        cursos.add(String.valueOf((document.select(".lin-area-c2").get(contador).text())));}}
            } catch (Exception e) {
                e.printStackTrace();
            }

    ArrayAdapter<String> cursosAdapter = new ArrayAdapter<String>(Chose_curso.this,android.R.layout.simple_spinner_item,cursos);

    cursoList.setAdapter(cursosAdapter);

}
</code>
}
Link do site http://www.dges.gov.pt/guias/indcurso.asp?letra=B neste caso com a letra B selecionada . O que eu estou a fazer e basicamente dar ao user a oportunidade de escolher qual letra e que eles querem no url quando vou buscar a informação!
Para resolver fiz desta maneira como me indicado :
<code>  public List<String> buscarCursos(final String letra) throws IOException {

    final List<String> cursos1 = new ArrayList<>();

    final ArrayAdapter<String> cursosAdapter = new ArrayAdapter<String>(Chose_curso.this,android.R.layout.simple_spinner_item,cursos1);

    cursoList.setAdapter(cursosAdapter);

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            try  {
                String site = "http://www.dges.gov.pt/guias/indcurso.asp?letra=";
                Document document;

                Elements lista;

                document = Jsoup.connect(site +letra).get();

                lista = document.select(".lin-area-c2");

                for (Element elemento: lista) {
                    cursos1.add(elemento.text());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();

    return cursos1;

}
</code>
Usei o buscar cursos para retirar todos os cursos para cada letra como a resposta que me foi indicada.
Answer: Você pode utilizar o seguinte método para buscar todas as descrições de cursos:
<code>public List<String> buscarCursos(String letra) throws IOException {
  String site = "http://www.dges.gov.pt/guias/indcurso.asp?letra=";
  List<String> cursos = new ArrayList<>();
  Document document;

  Elements lista;

  document = Jsoup.connect(site + letra).get();

  lista = document.select(".lin-area-c2");

  for (Element elemento: lista) {
    cursos.add(elemento.text());
  }

  return cursos;
}
</code>
Comment: Fiz como estavas a dizer mas como me estava so a dar o erro android.os.NetworkOnMainThreadException tive que meter um thread , fiz Log.d(tag,buscarCursos(letraPicker.getSelectedItem.toString())) e deu me return de uma ArrayList vazia
Comment: Fiz thread.start
Comment: Dei upVote pelo seu tempo , se me conseguisse ajudar com a informação que lhe dei ficaria muito agradecido
Comment: Ja fiz com que funciona-se obrigado
Comment: @EmanuelSobreiro conte-nos como resolveu
Comment: Ja fiz mas tenho um problema , quando seleciono a letra aquilo não faz upgrade , so faz quando eu clico nessa letra duas vezes seguidas

Jsoup parece nao estar a funcionar


Area below probabilities

Question: Let $p$ be probabilities and $D$ is the real
How can I proof that the areas
$$\int p \; d F_{p}(p|D=1) = \int (1-p) \; d F_{1-p}(1-p|D=1)$$
are equal. Where $F_{p}$ is the empirical distribution function of $p$.
Illustration:
<code>par(mfrow=c(1,2))
set.seed(123)
predRisk <- plogis(runif(1000,-1,10))
plot(ecdf(1-predRisk))
plot(ecdf(predRisk))
</code>
Answer: Just use the change of variable $p=1-q$ (don't forget the Jacobian and the use of the correct integration range). Maybe this should be a comment.
Comment: Welcome to the site. Why not expand this a little--it does seem like a potential answer.

Area below probabilities


Can a lower-semi continuous function be convex?

Question: In an image processing paper I was reading about a class of functions:
$\Gamma(\mathbb{R}^N)$ is the class of proper, convex, lower semi-continuous functions from $\mathbb{R}^N \rightarrow \left] -\infty, +\infty \right]$.
Then I was drawing a function similar to this (but quadratic, without the tailes).

Then I noticed that this function cannot be convex. Then I questioned whether even semi-continuous function can be convex?

Can anyone say something about this? Thank you.
Answer: For example, the following is a convex l.s.c. function from $\mathbb R$ to $]-\infty, \infty]$:
$$ f(x) = \cases{0 & if $|x| \le 1$ \cr
                 +\infty & otherwise}
$$
Comment: More examples: continuous convex functions.


Lemma regarding constructible universe

Question: How does $\alpha \subset L_{\alpha}$ follow from the lemma : whenever $\alpha < \beta ,\alpha , L_{\alpha} \in L_{\beta}$ ?
Answer: If $\gamma\in\alpha$, then $\gamma<\alpha$, so $\gamma\in L_\alpha$ (replacing $\alpha$ and $\beta$ in your lemma by $\gamma$ and $\alpha$, respectively).

Lemma regarding constructible universe


ospfd over an OpenVPN link - strange error in logs

Question: I am trying to set up Quagga ospfd on two hosts connected by an OpenVPN link. These hosts have VPN IPs 10.31.0.1 and 10.31.0.13. ospfd config is pretty simple:
hostname bizon
password xxxxxxxxx
enable password xxxxxxxxx
!
log file /var/log/quagga/ospfd.log
!
interface lo
!
interface tun0
ip ospf network point-to-point
ip ospf mtu-ignore
ip ospf cost 10
interface tun1
ip ospf network point-to-point
ip ospf mtu-ignore
ip ospf cost 10
interface tun2
ip ospf network point-to-point
ip ospf mtu-ignore
ip ospf cost 10
!
router ospf
ospf router-id 10.31.0.1
network 10.31.0.0/16 area 0.0.0.0
network 10.119.2.0/24 area 0.0.0.0
redistribute connected
area 0.0.0.0 range 10.0.0.0/8
!
line vty
!
debug ospf event
debug ospf packet all

I am getting the following error in the ospfd.log (the log is from 10.31.0.13):
2012/10/05 01:25:28 OSPF: ip_v 4
2012/10/05 01:25:28 OSPF: ip_hl 5
2012/10/05 01:25:28 OSPF: ip_tos 192
2012/10/05 01:25:28 OSPF: ip_len 64
2012/10/05 01:25:28 OSPF: ip_id 64666
2012/10/05 01:25:28 OSPF: ip_off 0
2012/10/05 01:25:28 OSPF: ip_ttl 1
2012/10/05 01:25:28 OSPF: ip_p 89
2012/10/05 01:25:28 OSPF: ip_sum 0xe5d1
2012/10/05 01:25:28 OSPF: ip_src 10.31.0.1
2012/10/05 01:25:28 OSPF: ip_dst 18.104.22.168
2012/10/05 01:25:28 OSPF: Packet from [10.31.0.1] received on link tun1 but no ospf_interface

I'm not sure what to do next. I have set up ospfd over OpenVPN several times but I used Debian and I am on CentOS 6 now. Quagga version is 0.99.15. Should I try to get more recent version?
tun1      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:10.31.0.13  P-t-P:10.31.0.14  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:19888 errors:0 dropped:0 overruns:0 frame:0
          TX packets:859 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:1207870 (1.1 MiB)  TX bytes:70797 (69.1 KiB)

Comment: Do you know what the problem was with OpenVPN? For the future, if you get stuck on how to look at setting up OSPF holistically. this is an excellent OSPF overview http://www.certificationkits.com/cisco-certification/Cisco-CCNP-ROUTE-Implementing-OSPF.html as it is very similar to the type of study guide you will get when you go to one of the CCNP boot camps. It has a slide at the top of each page with a detailed explanation below it to help you troubleshoot issues.
Comment: Packets destined to a multicast address suggests the other side may not be configured as a point-to-point interface.  It's also interesting that the ospfd process isn't seeing tu1 as a valid interface.  How is the IP of the interface being configured?
Comment: I added `tun1` configuration to the question. Basically this address is assigned by the OpenVPN client.
Answer: I gave up struggling with OpenVPN in tun mode and set up a tap-based OpenVPN. Everything started to work as expected.
Answer: Try specifying OSPF neighbors explicitly (like here http://www.freeccnaworkbook.com/workbooks/ccna/configuring-ospf-static-neighbors/ )
Comment: I'm not sure how to do it in Quagga, there is nothing relevant in the manual.


Cross-validation and model selection of ANN

Question: I have a neural network that I use to classify data into a number of classes; in my particular case, the classes are imbalanced, but I am trying to understand this for the general case. I am using F1 score as the metric for evaluating the network. I also would like to perform K-fold cross-validation.
So, let's say I have 1000 data points and I split them into 900 training and 100 test set, which I will use for evaluation only.
I then run a K-fold cross-validation; for simplicity let's assume K=3.
I take the training set (900 elements), use the first 600 elements for training and the other 300 for validation. I then take the middle 300 elements for validation and, finally the last 300.
At each fold, I will

Save the best-performing model (according to the validation set)
Evaluate this best-performing model on the test set.

Ok, so let's say I get these F1 scores

fold
train F1
val F1
test F1

1
0.93
0.88
0.87

2
0.95
0.93
0.86

3
0.94
0.91
0.92

Average
0.94
0.91
0.88

SD
0.01
0.03
0.03

I have a few questions.

Is the procedure above correct?
When reporting the model accuracy, is it OK to just report the average, so for example, $F1 = 0.88 \pm 0.03$?
Now, let's say I am happy with the model and I want to use it to classify some new data. Which model should I use? Should I pick the model trained in fold 3, since it has the highest score on the test data? But the one trained in fold 2, had a higher score on the validation data, so am I not biasing my choice based on the arbitrarily-picked characteristic of my test set?
Finally, let's say that now I decide I want to change some hyperparameter or change the network structure etc. I repeat the steps above and get a "better" model, based on the evaluation on the same test set. How can I be confident that this new model is really better on a new dataset and I am not just seeing a fluke in how the test set was picked?
Answer: 1 and 2 look good!
For 3, you should choose the model based off of validation set results. Since you've done multiple folds, you can take the hyper parameters that returned the highest average validation accuracy as best. The test set should be a complete hold out as an estimate to see how it will do when deployed. Another common practice is once you have run cross-validation, you would retrain the neural network (with the best hyperparameters) on the training+validation data, since the more data fed into these models, the better.
For 4, You would do the same process as above, and only use the test set as a gauge, rather than using it to choose a better model.
Comment: Thank you very much, this makes a lot of sense!


Can you use an opponent for leverage in basketball?

Question: If an attacking player sees a defender slip for example and fall to one knee. Can the offensive player use the defenders knee as a platform to jump, like running up and jumping off the defender?
Or a similar example of the same type thing, an attacker has the ball, jumps to attack the rim, but pushes their hand down on top of an opponents head generate more height, is this a foul?
Answer: The Block-Charge section under Comments on the Rules in the NBA rulebook (p.59) states

An offensive foul shall be assessed if the player initiates contact in a non-basketball
  manner (leads with his foot, an unnatural extended knee, etc.).

Which more than likely puts an offensive player springboarding off of an opponent who is not even taking a defensive position, or a player intentionally using his free hand to push down on his opponent's head as charging foul situations, as neither the head or the knees are natural contact points between an offensive player and a defender.
Comment: Note that although Michael Jordan was not called for an offensive foul when he [used one of the MonStars as a launching pad](https://www.youtube.com/watch?v=-S9W9xZikkA), Marvin the Martian's performance as referee in that game leads one to suspect that his knowledge of the rules was incomplete, at best. (He could for instance have also called a defensive foul on the play, since neither of the MonStars that attempted to tackle Jordan were set before Jordan was in the air.)
Answer: The way a referee in the NBA would likely rule this would be that if the contact was accidental, it may be a no call if the contact was minor. If it was apparent that the offensive player intentionally chose to initiate this contact, then a foul would be called.
If a player's well-being was in jeopardy because of such of a play, and their knee or head was at risk, this could even result in a flagrant foul being called.
A lot of basketball rules, as many rules in life, are based on common sense. Basketball is a contact sport in which all players are not supposed to hurt the opposing players. In the event that a player performs an action that could injure another player, it's quite likely that it will be called a foul. This is especially the case if the action was intentional.
Comment: Contact is contact.   There is no "accidental" contact unless you are reviewing something being a regular foul vs. an intentional/technical foul.   Nothing in this answer is right.
Answer: It is a "push": if you push off of someone you are pushing someone which is a foul.
Here are the types of fouls in basketball (ALL OF THEM):

Blocking
Holding
Hand Check
Push (Charging)
Illegal use of hand (not really called because the foul usually hits another category)
Player control.

Those are all the foul categories a player can commit.   If you commit a foul you have to do one or more of these.   If you didn't do one of these it isn't a foul.  So in this case you are pushing off on a player.   So it is a push.  It clearly isn't a hold, a block, a hand check, illegal use of hands, and since the player was deemed to do it on purpose it couldn't be a player control foul.   So in essence if what the OP said is true it is a "push" foul but probably also an intentional or technical foul type.   See chart below to reference foul types.


How to align the title in the middle?

Question: I'm working with codepen.io and I am creating a paragraph.
The graph has a title.
The problem is that I want the title center-aligned.It should automatically set the title in the middle, not about editing the value of "x". I can't use CSS to do this, and I believe javascript would do the job.
Here are the one functions I am using to draw the title and the link to my project goes bellow.
var text = document.createElementNS(svgNS,"text");
    text.setAttributeNS(null, 'x', 100);
    text.setAttributeNS(null, 'y', 15);
    text.textContent = (titel);
document.getElementById("bargraph").appendChild(text);

Full code:
codepen.io/Cleanwater/pen/LWQyJm?editors=0010
Comment: "Schieberöffnung" ..  should be vertically and horizontally aligned ?
Comment: It's a word in another language. It should be horinzontally aligned.
Comment: Isn't it ?
it looks like it is
Comment: what browser are you using ?
Comment: Now it is in the middle, but if I change the title than it's not in the middle anymore. It should automatically be placed in the center, like when you use in CSS text-align: center;
Comment: I'm using firefox
Comment: please explain the difference between middle and horizontal align
Comment: If you do not understand what I want, just ask direct. I just want the title be in the center/middle
Comment: so you do indeed mean vertically and horizontally aligned ?
Comment: if it helps me than yes
Comment: it was really helpful
Answer: var text = document.createElementNS(svgNS,"text");
    text.setAttributeNS(null, 'y', 15);
    text.textContent = (titel);
document.getElementById("bargraph").appendChild(text);
    text.setAttributeNS(null, 'x', 300 / 2 - text.getBBox().width /2);

How to align the title in the middle?


What process does certbot run as on Linux?

Question: I'm guessing certbot must operate as a continual running service on Linux however using ps on a server that uses Let's Encrypt certificate auto-renewal, I'm not seeing any obvious process for certbot. If it's running successfully, is there a central process for certbot, and if so, what is it?
I can find the version with apt-cache policy certbot | grep Installed - in my case 0.25.0-1~bpo9+1
Answer: Certbot is a Python program. So it runs as some version of python3 (currently minimum version supported is 3.6).
And, notice it doesn't run for most of the time. It is started periodically by cron or systemd-timers (whichever is used on your system), checks and renews certficates and stops.
Comment: Indeed, it doesn't need to run continually, and that would be slightly wasteful of system resources. Certificates can be renewed before they expire, so it's enough to just check every now and again if there are any that the system knows about which need to be renewed.


Modeling quesion, linear regression or survival analysis

Question: I am analyzing a dataset where the outcome variable is "teenagers' recreational drug use in weeks." This is continuous and highly skewed outcome variable. While the range spans from 2 weeks to 100 weeks, most teenagers reported experimenting with drugs for durations between 2 and 25 weeks, with very few values beyond 25 weeks.
This dataset comprises around 2000 children, each with a single row of data. There are no repeated measures; each child enters the study at a different time.
The exposure of interest is a single event: the abolition of a drug counselor position by the federal government in 2020.
The goal of the analysis is to examine changes in drug use duration before 2020, prior to the abolition of drug counselors, compared to after 2020, following the abolition.
My question is what is a appropriate model to analyze such outcome. Should I apply simple linear model or survival analysis ? I welcome any advice on this topic. Thanks in advance.
Comment: *"This dataset comprises around 2000 children, each with a single row of data"* Each child has a row of data? Like what data?
Comment: @SextusEmpiricus, age, sex, education, parent's income, BMI, city, state, `before/after 2020`
Answer: If there are no repeated measures, I suppose it means that you are not following the children in time, i.e. weeks of recreational drug use is an endpoint measure.
A survival analysis would not be appropriate, because your outcome variable is not the occurrence of an event. It would work if it were time to drug use for example.
I would first check that the time spent in the study does not differ between the 2 conditions (before the suppression of the counselor position and after). Then I would analyse it with a GLM, probably for a binomial distribution since it is skewed count data, but this depends how skewed the distribution of the outcome variable is.


How do I get atonal melody by ear?

Question: It's pretty common to transcribe tonal music by ear, but not atonal music. Also, for me, and a lot of mates, it's much easier to get tonal music by ear than atonal. I'd like to know how can I get atonal melodies by ear. A person said that the way to get the atonal melodies is to use trichords, but I don't know what they are and how to use them.
Comment: IMPORTANT POINT, there's a technical difference between "atonal" and "dissonant." People often use "atonal" simply to mean "dissonant," especially if they have encountered the terms but not learned a lot about the details. But music that contains tritones, minor 2nds, major 7ths, etc. can still be tonal. I suggest starting by practicing transcribing and sight-singing these types of works, so you have a good command of all intervals, not just triadic ones.
Comment: (Also, I guess I should explain in detail. Truly "atonal" music doesn't just mean "it sounds clashy." It means it isn't trying to organize around a tonal center—that is, it's not "in a key." It often uses some other organizing system, like serialism. But Stravinsky, Shostakovich, Bartok, etc. are still (usually) tonal even while using dissonances.)
Comment: @AndyBonner more than "it isn't trying to organize around a tonal center": it's often seeking deliberately to avoid organizing around a tonal center.
Answer: If you are able to transcribe tonal music I'm sure you should be able to start transcribing atonal music but it will be much slower process at the beginning. If you're not sure if your transcriptions are correct start from transcribing the pieces for which you can access existing transcriptions, do your own, compare to find mistakes and then analyze what sort of mistakes you tend to make. Typically certain intervals might be more difficult to discern and be confident about. Then you might try one of these apps or software tools for practicing ear training to practice recognition of intervals. Many of these apps can be configured to drill only particular intervals. Practicing singing atonal melodies should be a great help as well.
Answer: When we transcribe tonal music, we can relate what we hear to known patterns, major and minor chords perhaps, major or minor scales.   Or maybe we'll recognize other patterns, a Mixolydian or Lydian scale, a whole-tone scale, a diminished chord...   So why not recognize ANY note of the chromatic scale, without having to relate to a subset of that scale?  There's only 12 pitch classes after all!    Listen to C - F♯.  Do you REALLY need to hear that as a modified perfect 4th or perfect 5th?  No, you KNOW those pitches!  Just extend that idea.
When I was at college, we had to transcribe short passages of 'atonal' 4-part harmony.   The pure classicists found this hard.  But those of us with some jazz background too often found that a seemingly random set of 4 notes actually formed a familiar 'jazz chord'!
Answer: If you're not lucky enough to have absolute/"perfect" pitch, be prepared to rely a lot more on detecting intervals between adjacent notes to confirm or even do your transcribing work when transcribing atonal melodies. If your previous favoured transcribing method was indeed detecting a (local) key and melody notes' positions/intervals from the tonic, that will have to go out the window.
Answer: I think it's important to note that the difference between tonal and atonal music requires a different approach.  Transcribing tonal music is often easier because the notes are connected to a larger sense of harmony and traditional form.  With a little practice, musicians get really good at remembering patterns and melodies that tend to fit with a certain progression.  In atonal music, though, this harmonic and tonal "guide" is absent.  Unless I'm very much mistaken, the only real way to get better at transcribing atonal melodies is to go one note at a time.
Start by relentlessly practicing interval training with two-note patterns.  There are likely many ear-training software options that will do this for you.  You may discover that you are good at picking out some intervals, like the tritone or major and minor seconds, but others like sixths you are likely to miss.  Then, practice 3-note patterns (but only when you are rock-solid on two-note patterns).  You will, with good practice and lots of time, get better at it.
I'll also say that you might find it hard to locate good resources to help you.  There are a ton of examples where being able to play tonal music by ear can be helpful.  Think joining in on a saxophone with a pickup band at open mic night, jamming with others and having them play a tune you don't know, picking up a guitar and strumming along with a sing-along around the campfire, etc.  But there aren't lots of times where we are called upon to transcribe atonal music by ear.  In my experience this is largely a written form (unless there are secret "twelve tone row clubs" somewhere).
One resource I have found helpful is a book called Modus Novus, which is a systematic approach to improving this skill.  It might help to have a buddy play things for you and take turns transcribing.

Book PDF.

How do I get atonal melody by ear?


Is this data from machine votes or human votes? Opinions appreciated!

Question: A friend recently entered (but lost) an online competition where the winner was chosen based on total votes. Only one vote would register per IP address so as to discourage multiple votes coming from one person. The only contest rule was that "machine or automated voting" was not allowed. The following data is a small snapshot of the vote activity for the eventual winner:
Time    Total Votes

11:22   3765

11:24   3770

11:26   3773

11:28   3775

11:30   3780

11:32   3781

11:34   3784

11:36   3787

11:38   3791

11:40   3799

11:42   3803

11:44   3805

11:46   3808

11:48   3810

11:50   3813

11:52   3817

11:54   3819

11:58   3827

12:00   3829

12:02   3834

12:14   3852

12:56   3990

13:06   4014

13:08   4022

13:12   4029

16:00   4341     Final vote count

Note that the beginning data was collected at 2 minute intervals, but later there are gaps before a large gap when the final vote count is presented.
When I put the contiguous data (11:22 - 11:54) into excel and then "fill down" for a prediction, I get a predicted final vote count = 4246... less than 100 votes from the actual count. In addition, the arrival of votes just doesn't look as random as I'd expect if independent human voting was happening. I'm pretty sure there is some degree of human voting, but I'm speculating that there is a strong machine element at play as well.
I'd sure appreciate any opinions / analysis / advice that the community can offer. Do you believe there is machine voting going on here? How strongly do you believe this?
Comment: What is the standard error of that prediction?
Comment: Not sure what you mean... if you mean the std deviation, the real data vs the excel "back-filled" straight-line values in the 11:22 - 11:54 range have a std of 1.66. Slope for the fitted line is about 3.4559 votes per 2 minutes.
Comment: No, I do not mean the standard deviation of your data. I mean that when you make a prediction you can get some [prediction intervals](http://en.wikipedia.org/wiki/Prediction_interval) about it. Anyway, I think that @BenKuhn gave you a really nice answer (+1 to him).
Answer: One statistical test you can do is see whether the arrival time of past votes influences the arrival time of future votes. If it does, that would strongly suggest that the votes were orchestrated in some way (e.g., a machine issuing one vote per minute, or issuing 100 votes in one minute and none for the next).
This suggests to a good null hypothesis, which is that the data are drawn from a Poisson distribution. That's our benchmark for random, independent voting patterns, where the time of one vote doesn't tell you anything about the timing of the next vote. So how do we figure out whether the data we have is Poisson-distributed?
We can try to falsify this null hypothesis--convince ourselves the data are not Poisson-distributed--by testing a statistic called index of dispersion. Basically, this measures whether the standard deviation of the data is larger or smaller than you would expect if it were a Poisson variable.
The index of dispersion is the variance (square of the standard deviation) divided by the mean. For a Poisson distribution--where voting events are independent--this ratio is always 1. If the votes are too regular and machine-like, then the variance of the vote counts, and hence the index of dispersion, will be lower. If the votes are too irregular (because they happen all at once), the index of dispersion will be higher.
We'll use just the 2-minute windows to simplify things; that means that, under the null hypothesis that the data is Poisson distributed, the number of votes in each 2-minute window comes from a Poisson distribution with the same rate parameter. We just have to find out what that rate parameter is. Our best guess is just the mean of the count in each window. I'm going to do this in Python since that's what I'm most familiar with:
In [16]: import numpy as np

In [17]: votes_per_time = [5, 3, 2, 5, 1, 3, 3, 4, 8, 4, 2, 3, 2, 3, 4, 2, ]

In [18]: np.mean(votes_per_time)
Out[18]: 3.375

So the average number of votes per window is 3.375. We can start by comparing a histogram of the plots to a true Poisson variable:

Hmm. It looks like it's a little bit underdispersed--concentrated towards the center, and away from the tails, compared to a Poisson distribution. But there's no smoking gun, so let's go on with the statistics. What's the index of dispersion?
In [19]: np.std(votes_per_time)**2 / np.mean(votes_per_time)
Out[19]: 0.77314814814814814

So these votes are slightly more regular (less variable) than we would expect from a Poisson distribution.
But we can't stop there. Even if the votes were really random, a sample of them wouldn't necessarily have an index of dispersion of exactly one. Instead, we need to figure out how likely it would be that, if the data were really Poisson, the index of dispersion would be as low as the one we saw. To do this, we'll create a ton of fake data that we know is from a Poisson distribution, and see how its index of dispersion goes.
In [22]: np.random.seed(1234)

In [23]: samples = [np.random.poisson(np.mean(votes_per_time), size=len(votes_per_time))
   ....:            for i in xrange(1000)]

In [24]: indices = [np.std(sample) ** 2 / np.mean(sample) for sample in samples]

Here's a density plot of that distribution:

You can already probably see that 0.77 (the dashed line) is fairly close to the peak of this distribution; it doesn't look implausible that we'd see a value like that from truly Poisson data. We can quantify this by producing a confidence interval for the dispersion index under the null hypothesis--basically, if the data were truly Poisson, what's an interval we would be 90% sure the dispersion index would fall inside? We find this by calculating the 2.5th and 97.5th percentiles of how it would be distributed:
In [25]: np.percentile(indices, [2.5, 97.5])
Out[25]: array([ 0.38584454,  1.6878125 ])

So the index of dispersion of 0.77 that we saw above is well within the realm of possibility for truly Poisson-distributed data.
This doesn't necessarily mean that the data actually is Poisson-distributed! It might be that we just don't have a large enough sample to tell. For instance, if we saw the same index of dispersion over a sample of 1,000 2-minute windows...
In [27]: samples2 = [np.random.poisson(np.mean(evts), size=1000) for i in xrange(1000)]

In [28]: indices2 = [np.std(sample) ** 2 / np.mean(sample) for sample in samples2]

In [29]: np.percentile(indices2, [2.5, 97.5])
Out[29]: array([ 0.91544624,  1.0890494 ])

...then we could much more confidently reject the hypothesis that our data was Poisson. But since our confidence interval with the smaller number of buckets is a lot wider, we don't have as much power to detect deviations from Poisson-ness.
To sum up: if the votes are actually different from how a bunch of independent humans would make them, we don't have enough data to tell.
Comment: Wow @Ben ... I can't believe how awesome your answer is. Thank you for your expertise and quick reply. I think I understand most of it, but I still wonder whether it should be expected that the little bit of data collected could be extrapolated so accurately.
Comment: If the average rate extended over the duration, I guess the accurate prediction is expected. But I imagine with human voters, the "ebb and flow" of the day would result in the average rate changing, and thus the final total. Granted, the rate could go up and down in amounts that end up giving you the average, but that sounds less likely than a machine-driven constant average.
Comment: I have a request to a polling / survey company for a larger set of data, but it won't be from this particular vote. I was planning to look for this "ebb and flow", take short chunks of data, and see how accurately it predicts the outcome. If the company is kind enough to provide the data, I'll post my findings.
Comment: @HonestLee: if the votes are constant with rate 3.375 per 2 minutes--i.e., 1.16875 per minute--then I get that on average 278 * 1.16875 ~= 325 votes should have come in over the rest of the study, with standard deviation sqrt(325) ~= 20. So a discrepancy of 100 votes (per your calculation) or 200 (per mine) would actually be hard to explain *without* some degree of human "ebb and flow" to the voting rate.


How do I enter Segno, Coda, D.S. al Coda into TuxGuitar?

Question: I've figured out TuxGuitar for the most part, and although I can do simple repeats, I can't find where "D.S. al Coda", "To Coda", and the symbol buttons are.
How do I enter Segno, Coda, D.S. al Coda into TuxGuitar?
Comment: This question seems like it would be better suited to the TuxGuitar support forum / chat / technical support.
Answer: Unfortunately, TuxGuitar does not currently have this capability. Posts on their forum have been suggesting such an implementation for years, but it has not yet been acted upon.
If you need software that can provide such markings, I recommend free/open-source programs like MuseScore or LilyPond (my personal favorite). Finale, Sibelius, and Dorico also have these capabilities, but you'll need to pay for the software.


Amazon Pinpoint for Android - AWSMobileClient not found in the SDK jar file

Question: I was trying to implement an easy sample Android app to illustrate how to integrate Amazon Pinpoint - targeted Push Notifications for Mobile Apps. So I was reading and following this documentation below for integration:
Initializing the Amazon Pinpoint Client - Amazon Pinpoint
Then I realized that AWSMobileClient is not found inside the SDK jar file. (Other classes such as PinpointManager or CognitoCachingCredentialsProvider are available.) If you have imported and read the sample Android project for receiving test Push Notification for Amazon Pinpoint, you may have noticed that this AWSMobileClient IS there inside com.amazonaws.mobile package.
I'd like to know if I am missing something, this is intended and documented somewhere else, etc.
I have added the following jars:
aws-android-sdk-core-2.3.5.jar
aws-android-sdk-pinpoint-2.3.5.jar

and the cognito dependency:
compile 'com.amazonaws:aws-android-sdk-cognito:2.3.5'

(AWSMobileClient is required for registering and handling tokens, refer this for more info.)
Answer: Alternatively, you can add this dependency in the app's build.gradle
compile ('com.amazonaws:aws-android-sdk-mobile-client:2.6.+@aar') { transitive = true; }
Answer: I have found out the sentence in the doc:

In the following example, the AWSMobileClient class is provided in the AWS Mobile Hub sample code to reference the Amazon Pinpoint object.

So it seems like AWSMobileClient is not a part of the SDK but defined for sample project.
[UPDATED]
If you finish adding your app on Mobile Hub and get ready to integrate SDK, you will see Android Setup Steps section and there it also says,

Copy the Mobile Hub Helper and Custom Code
  Copy the contents of the java/com/amazonaws folder from the helper code you downloaded into the java/com folder of your Android Studio project.
This folder contains a set of helper classes that have been custom generated for you. These were generated based on your project configuration and on the AWS cloud resources and identifiers that were created for you when you configured the project. These classes simplify the use of all the SDKs that are required to support your project.
Answer: I have found that
implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.+@aar') { transitive = true }

worked when the following two options didn't:
compile ('com.amazonaws:aws-android-sdk-mobile-client:2.6.+@aar') { transitive = true; }

and
implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.6.+@aar') { transitive = true; }


Exception when we want to share image and text via Facebook sdk

Question: I have problem that When we want to share a product with its image and text on facebook with the help of facebook sdk (Fb Dialog) then it gives an error message as following:
Error Stack:
*
08-20 12:26:06.002: ERROR/AndroidRuntime(1776): FATAL EXCEPTION: main
08-20 12:26:06.002: ERROR/AndroidRuntime(1776): java.lang.ArrayIndexOutOfBoundsException
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at com.facebook.android.Util.decodeUrl(Util.java:96)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at com.facebook.android.Util.parseUrl(Util.java:115)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at com.facebook.android.FbDialog$FbWebViewClient.shouldOverrideUrlLoading(FbDialog.java:125)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:224)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:349)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at android.os.Looper.loop(Looper.java:123)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at java.lang.reflect.Method.invokeNative(Native Method)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at java.lang.reflect.Method.invoke(Method.java:521)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
08-20 12:26:06.002: ERROR/AndroidRuntime(1776):     at dalvik.system.NativeStart.main(Native Method)*

The code of Fb Dialog is as follows:
package com.shopzilla.android.listener;

import android.app.Activity;
import android.os.Bundle;
import com.shopzilla.android.client.model.BaseInventoryItem;
import com.shopzilla.android.moretab.SettingActivity;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

/**
 * A facebook dialog listener.
 *
 * @author Rod Barlow
 * @since 7/21/11
 */
public class FacebookDialogListener implements DialogListener {

    final BaseInventoryItem item;
    final Activity activity;

    public FacebookDialogListener(BaseInventoryItem item, Activity activity) {
        this.item = item;
        this.activity = activity;
    }

    @Override
    public void onComplete(Bundle values) {
        if (values.isEmpty()) {
            //"skip" clicked ?
            return;
        }
        if (!values.containsKey("post_id")) {
            try {
                Bundle parameters = new Bundle();
                parameters.putString("attachment", "{\"name\":\"" + item.getTitle() + "\",\"href\":\"" + item.getUrl() + "\",\"description\":\" \", \"media\":[{\"type\":\"image\",\"src\":\"" + item.getImageUrl() + "\",\"href\":\"" + item.getUrl() + "\"}]}");
                SettingActivity.mFacebook.dialog(activity, "stream.publish", parameters, new FacebookLoginDialogListener());
            } catch (Exception e) {

                System.out.println(e.getMessage());
            }
        }
    }

    @Override
    public void onFacebookError(FacebookError e) {
        System.out.println("Error: " + e.getMessage());
    }

    @Override
    public void onError(DialogError e) {
        System.out.println("Error: " + e.getMessage());
    }

    @Override
    public void onCancel() {
    }

}

Please Help me out about This problem.
Answer: This Is Solved by a very easy Code as following:
In Util.java You must add this Line in a decode method:
if(v.length == 2)
{
param= /*as mentioned previous*/
}

And Issue Solved.
Answer: See the following page..
https://github.com/wrapp/facebook-android-sdk/commit/f226c110ff49b75b8a15d486a74e0295e05b8bd5
Comment: Thanx for this, but the problem with me is that I am building my app with Maven. and I want to create the apklib of facebook sdk but when we access it from Maven Repository it returns this error. So, it will resolve?
Answer: I had the same issue and i think i solved it.
Have a look at this:

https://stackoverflow.com/questions/7158224/another-problem-with-facebook-integration

Hope it helps!
Answer: I'd suggest you use Graph API instead of REST. Changing to that may solve your problems. And it's much easier and more clear.
Also, I remember I had to do some fixes in Facebook SDK in order to work correctly - I had similar problems with Util class.
You may want to try out my fixed Facebook SDK implementation:
http://www.2shared.com/file/0DFYym3f/facebookSDK.html
At some point you may get into trouble when trying to login to Facebook.
For example if you have Facebook application on your phone and you try to login in your app, you will be forwarded to that Facebook app and your callback will never be called. I fixed that in this implementation too so you don't depend on existing Facebook App, but you need to track access token for yourself.
Example to do that would be something like this:
This should be put in some kind of 'Facebook manager'
public boolean restoreSession(Context context) {
        if (preferences == null) {
            preferences = PreferenceReader.getInstance(context);
        }
        return preferences.restoreFacebookSession(facebook, context);
    }

    public boolean saveSession(Context context) {
        if (preferences == null) {
            preferences = PreferenceReader.getInstance(context);
        }
        return preferences.saveFacebookSession(facebook, context);
    }

And SharedPreferences should hold something like:
public boolean saveFacebookSession(Facebook facebook, Context context) {
    editor.putString(TOKEN, facebook.getAccessToken());
    editor.putLong(EXPIRES, facebook.getAccessExpires());
    return editor.commit();
}

public boolean restoreFacebookSession(Facebook facebook, Context context) {
    facebook.setAccessToken(preferences.getString(TOKEN, null));
    facebook.setAccessExpires(preferences.getLong(EXPIRES, 0));
    return facebook.isSessionValid();
}

Now when you receive false from restoreFacebookSession, you need to authorize and call saveFacebookSession. That's it :)
Hope that helps to find a right way to use Facebook SDK \o/
Comment: Hi Kostas, the problem behind to implement this is; we are using facebook sdk in through Maven Repository in apklib format then how to change it in desired format as metioned by You? and One thing more, where should I write these functions as restoreSession, SaveSession and many more.
Comment: Hi, as I mentioned above, you should handle session saving/restoring in your SharedPreferences. If you cannot manipulate what's inside your Facebook SDK library then my solution will not be of any help.


How to change error message of the webform

Question:
Possible Duplicate:
preprocess_node_webform is not working

How can I change the default error message of the webform ? For example "The name field is required"  to  "Please enter your name". Where should I make changes to achieve this ?
Answer: You can use drupal_set_message().


Closed under equality

Question: In the Wikipedia article on "Peano axioms" I read this (source):

For all $a$ and $b$, if $a$ is a natural number and $a = b$, then $b$ is also a natural number. That is, the natural numbers are closed under equality.

Seems legit (to a computer scientist such as me, anyway, maybe not to a mathematician). But then in the Wikipedia article on "Closure" I read this (source):

A set has closure under an operation if performance of that operation on members of the set always produces a member of the same set.

I think the two above statements contradict each other. The first statement basically says: if an element of a set is operated on by a certain operator, the operator will not allow for elements of a different set to be the other operand, this set is considered closed under that operation. But the second statement says that the result of that operation is supposed to be of the same type (for lack of a better term). So one natural number added to another produces another natural number, so the natural numbers are closed under addition. But the equality operator produces a Boolean/truth value, not a natural number.
Question:
What's the deal with equality and closure? I take it that the natural numbers are closed under equality, but how exactly? Which of the above statements is flawed?
Comment: I didn't find your statement "if a is a natural number and a=b, then b is a natural number" anywhere in the wiki article. Maybe you could copy the whole area around where you found the statement, so someone could find it. In my opinion, such a statement should *not* appear (as you have quoted it) in any serious article about Peano arithmetic. The statement is really redundant!
Comment: weird, it's the fifth numbered item under the paragraph "The axioms".
Comment: The axioms you are looking at were probably from Peano's original paper in Latin. The axiom in question seems redundant to us today. The most commonly used modern version of Peano's axioms does not given the axioms of equality. They define only 0 (or 1), the successor function  and sometimes addition and multiplication. The axioms of equality are now subsumed in the rules and axioms of logic.
Answer: There are two ways to approach understanding this.

Closure refers to two different things: the idea that elements in a set are only related to other elements of the set (for relations), or are only mapped to other elements of the set (for functions of one or more arguments). Using the same word for different concepts is not too harmful if the meaning is clear from context. In fact, there are more meanings from topology and algebra: a set is closed under limits if all convergent sequences in the set have their limit also contained in the set (although "taking limits" isn't an operation or a relationship on elements of a set); and a field is algebraically closed if all polynomials over that field factor as a product of linear polynomials (which could be formulated as a relation from polynomials to sets of polynomials, but isn't usually). We think these ideas have something in common — a sort of family resemblance — so we give them similar names.
In the case of closure under an operation or under a relation, we can unify the concepts somewhat by recognising that functions are relations. A function $F: X \to Y$  is often described as a relation $F \subseteq X \times Y$ such that $$\forall x \in X \, \exists! y \in Y : (x,y) \in F$$ (where $\exists!$ denotes unique existence). We may say that a set $Y$ is closed under a relation $R$ between $X$ and $Y$, where $\mathcal P(Y) \subseteq X$ or  $Y^n \subseteq X$ forsome $n \geqslant  0$, if every element of $X \cap \mathcal P(Y)$ or $X \cap Y^n$ as appropriate is related only to elements in $Y$. In the special case of binary relations such as equality, and binary operations such as addition — or considering the set of points in a converging sequence, for that matter — we then recover the usual meanings. (The "family resemblance" of the definitions might be capturable in a single, more general definition.)
Answer: What is said about equality, is a (or in fact the) general property of identity: If $a=b$ then $\Phi(a)\iff\Phi(b)$ holds for any predicate (if one rejects strange things like "... is the first letter of the alphabet").
The term closure refers to operations, not equality. With natural numbers, you have the successor function, addition, multiplication, under which the set of naturals is closed (as opposed to subtraction).
Comment: this is known as [the identity of indiscernibles](http://en.wikipedia.org/wiki/Identity_of_indiscernibles)
Comment: If you're working in a logic without $=$, then such silly kinds of axioms can be necessary.

Closed under equality


Is a Cadential 6/4 tonic or dominant function?

Question: A cadential 64 would normally occur before a V, and after an IV, ii, V/V, viio/V, It. 6, Fr. 6, or Ger. 6.  Does a cadential 64 have tonic or dominant function?  (Or... maybe... subdominant function...?)
Answer: It is a decoration of the dominant by a double appoggiatura, which resolves to V:

It is traditionally seen as a voice leading event rather than a distinct harmony. As such, it has a dominant function.


How to use compression option for ssh with the ProxyCommand?

Question: I want to establish a ssh tunnel for transferring data from my computer to a remote machine through a gateway machine.
I want to copy large amount of data, thus I use blowfish for encryption and enable the compression.
Which of the following commands is correctly setup the encryption and compression:

Define the compression and encryption within ProxyCommand:
ssh -L 5555:127.0.0.1:555  -o ProxyCommand="ssh -c blowfish -C user@gateway nc -q0 target  2222" user2@target -v
Define the compression and encryption within the main ssh command:
ssh -L 5555:127.0.0.1:555 -c blowfish -o ProxyCommand="ssh user@gateway nc -q0 target  2222" -C user2@target -v
Define the compression and encryption both in the ProxyCommand and ssh command:
ssh -L 5555:127.0.0.1:555 -c blowfish -o ProxyCommand="ssh -c blowfish -C user@gateway nc -q0 target 2222" -C user2@target -v

The debug message (-v) informs me that the compression is enabled.
Does the option 3 make ssh to compress the data two times?
Answer: Command 1 will compress data between the client and gateway, but not between the gateway and target. Option 2 will compress data between the client and target (at the expense of not compressing some protocol level data, which won't be significant). Option 3 will compress data between the client and target, and double compress data between the client and gateway (which you definitely don't want).
If the bandwidth between the gateway and target is high (e.g. LAN speed) then go with option 1. If not, go with option 2.


How can I set the graphical diff tool for ClearCase on Linux, as non-root?

Question: I want to replace the GUI tool ClearCase brings up when I use cleartool diff. I've read:
Any way to use a custom diff tool with cleartool/clearcase?
but the answers there are either about Windows, or they show me shell scripts which I don't know how to  use. Or there are kludges like this one.
On the other hand, I do know that ClearCase uses a symlink, e.g. /opt/rational/clearcase/lib/mgrs/directory/xcompare, for the graphical diff'ing. Except that this symlink is owned by root, and I'm not root. Also, I don't want to replace everybody's diff tool, just mine.
So, what can I do to have ClearCase use the tool I want it to?
Note: I'm using GNU/Linux (Devuan 3.0).
Answer:
Also, I don't want to replace everybody's diff tool, just mine

That points out to a Unix client, where you want to open a Unix diff tool different from xcompare (without using the command-line tool cleardiff or cleartool diff).
You would still need to modify the ccase-home-dir/lib/mgrs/manager-name , with ccase-home-dir refering to both the Rational ClearCase installation directory).
The goal is to replace the executable of the line text_file_delta   xcompare         ../../bin/cleardiffmrg by the graphical tool of your choice (kdiff3 for instance)
So that would still affect all users of the ClearCase client on that machine (as opposed to Windows, where you are generally the only user).
Comment: So, there are no user-specific overrides for these links?
Comment: @einpoklum Not to my knowledge.


How to override breadcrumbs defined by a module using a custom module?

Question: Is it possible, using a module, to override a breadcrumd definition defined in another module's hook_node_view()?

Module property_bc sets a custom breadcrumb for nodes of type Property.
Module property_bc_plus wants to override that behaviour.

property_bc implementation of hook_node_view would be:
<?php
/**
 * Implementation of hook_node_view().
 */
function property_bc_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'property') {
    $breadcrumb = array();
    $breadcrumb[] = l(t('Home'), NULL);
    $breadcrumb[] = l(check_plain($node->name), "user/$node->uid");
    $breadcrumb[] = l(t('Properties'), "user/$node->uid/properties");
    drupal_set_breadcrumb($breadcrumb);
  }
}

Answer: Different solution depending of your context.

Change the module order by changing their weight: http://drupal.org/node/110238
Use an other hook than is called later like hook_node_view_alter
Add a flag in your node and test against it

First module
 <?php
 function property_bc_node_view($node, $view_mode, $langcode) {
      if ($node->type == 'property') {
        $breadcrumb = array();
        $breadcrumb[] = l(t('Home'), NULL);
        $breadcrumb[] = l(check_plain($node->name), "user/$node->uid");
        $breadcrumb[] = l(t('Properties'), "user/$node->uid/properties");
        $node->custom_bredcrumb_is_set = TRUE;
        drupal_set_breadcrumb($breadcrumb);
      }
    }

In your other module
    <?php
    function property_bc_plus_node_view($node, $view_mode, $langcode) {
      if ($node->type == 'property' && isset($node->custom_bredcrumb_is_set) && $node->custom_bredcrumb_is_set != TRUE) {
        $breadcrumb = array();
        $node->custom_bredcrumb_is_set = TRUE;
        drupal_set_breadcrumb($breadcrumb);
      }

}

Comment: You solution is great. Just a note here, I didn't modify the first module since this is what I wanted to avoid in the first place.


Track the lifetime of a CPython object from C extension

Question: I have some C++ code that delivers events to Python objects. Observers are kept as weak_ptrs, so they don't have to deregister.
This works in C++, but bridging weak pointers and Python weak references is troublesome (I also want Python event handlers not being kept alive by subscriptions, same as in C++ code). In order to have a live observer, something needs to have a shared pointer to it while the object is alive, so it boils down to having an observer in Python land control the lifetime of a C++ observer object.
The approaches I've come up with so far involve a fair amount of boilerplate and intermediate objects (e.g. creating another PyTypeObject for a type that keeps a C++ observer and a weak reference to the Python observer and setting it as a member of Python observer, so it dies with it).
The question is, is there any obvious way to do it?
Answer: I would write a python wrapper over the C++ module and dispatch to python observers in the python wrapper. Would that be enough?
When you mention that something needs to have a shared pointer, would it be enough if that shared pointer is on the stack until given observer returns?


Lilypond – ties across staves

Question: Is there a way in Lilypond to tie notes across two staves?
I have this fragment of an organ piece:
<code>\version "2.18.2"
\language "deutsch"

global = {
  \key c \major
  \numericTimeSignature
  \time 3/4
  \set Timing.beamExceptions = #'()
}

right = \relative c'' {
  \global
  <h dis>2 (<cis e>4~<cis e>~<e, cis'>2~<cis e cis'>)r4
}

left = \relative c' {
  \global
  dis2 (e4~e cis2) gis'8(fis e dis e fis)
}
</code>

And I need to add the red tie between the two notes. (It is an organ piece and I need to let the organist know, that he is supposed to silently exchange fingers on the note and not to hit the tone twice.)
Comment: One solution may involve writing the `cis` in the lower voice and moving it to the upper staff. See also https://music.stackexchange.com/questions/71562/how-to-cross-staff-slurs-in-lilypond
Comment: I don't have Lilypond (so apologies if this doesn't work), but in my programme you can easily place a 'slur' between two staves, which would mimic a tie visually, but not audibly. See if that does the job.
Answer: I do not pretend that this is an optimal answer, nor even a desired one. But here is one possible solution. Notice that I've moved some things around into multiple voices in a few spots. You can tweak the tie as you desire.
<code>\version "2.18.2"
\language "deutsch"

global = {
  \key c \major
  \numericTimeSignature
  \time 3/4
  \set Timing.beamExceptions = #'()
}

right = \relative c'' {
  \global
  <h dis>2 (<cis e>4~ |
  <cis e>~ <e,^~ cis'~>2 |
  <e cis'>) r4
}

left = \relative c' {
  \global
  <<
    {
      \slurNeutral
      dis2 (e4~ |
      e \shape #'((0.5 . -10) (3 . -9) (1 . -5) (0 . -3)) Tie
        cis2)~ |
      \change Staff = "right"
      cis?
    }
    \\
    {
      s2. |
      s |
      \stemNeutral
      gis'8(fis e dis e fis)
    }
  >>
}

\score {
  \new PianoStaff <<
    \new Staff = "right" \right
    \new Staff = "left" { \clef treble \left }
  >>
  \layout { }
}
</code>

Lilypond – ties across staves


Android Studio projects are having an error "Missing Permission"

Question: Note: I was working on the project and building it from time to time. It was working fine, until recently all of my projects started showing a "missing permission error" but I've mentioned permission in the AndroidManifest file already for the projects.
Project 1 :
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.firstproject">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        ////other code

</manifest>

missing permission error in first project
Why I need permission / permission check:
error-at(1)
error-at(2)
error-at(3)
error-at(4)
missing permission error
build.gradle (:app) (first project):
dependencies {
implementation platform('com.google.firebase:firebase-bom:28.1.0')
implementation "androidx.cardview:cardview:1.0.0"
implementation "com.google.android.material:material:1.3.0"
implementation 'com.google.android.gms:play-services-auth:19.0.0'
implementation 'com.firebaseui:firebase-ui-database:6.2.1'
implementation 'com.google.firebase:firebase-auth'
implementation 'com.google.firebase:firebase-analytics'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.google.firebase:firebase-database:20.0.0'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.navigation:navigation-fragment:2.3.5'
implementation 'androidx.navigation:navigation-ui:2.3.5'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.vectordrawable:vectordrawable:1.1.0'
implementation 'com.google.android.gms:play-services-maps:17.0.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.karumi:dexter:6.1.2'
implementation 'com.google.android.gms:play-services-location:18.0.0'
implementation 'com.google.android.gms:play-services-places:17.0.0'
implementation 'com.firebase:geofire-android:3.0.0'
}

Same error occurs in my second project.
Second Project:
missing permission error in second project
AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.driver">
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
//other stuff

The Project builds log:
Starting Gradle Daemon...
Gradle Daemon started in 3 s 90 ms

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/7.0.2/userguid/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 34s

What happens if I run this project with the error:
It doesn't asks for my permission but shows the permission in the Setting -> Apps
permission showing in the setting
What I already tried:

Rebuilding the project
Cleaning the project
Upgrading the Gradle
Deleting the project and building the backup version(one commit revert as I use github)
Comment: You need to request permission

https://developer.android.com/training/permissions/requesting
Answer: After many hours of research and trying new things out, I found out that my AndroidManifest.xml was not merging files and it was happening for all of my projects.
I can't find the answer to why it was happening but it was the reason why the permission inside the AndroidManifest.xml was not working.
The things I did to solve that issue

Delete the Android Studio directory at E:/Android Studio (custom)
Delete the .android directory at C:/Users/UserName/.android (default)
Delete the .gradle directory at C:/Users/UserName/.gradle (default)
Install new Android Studio

After that all the previous projects were working fine
Note:
To view the Directory (e.g .android) make sure that "show hidden files/folders" is enabled
Comment: You right; This Manifest merger was unable to merge all manifests. I had to fix my manifests inside modules. Thanks
Answer: It's an easy fix, Android studio will automatically generate some code with return statement. Which will check the permission if  granted then, the next line of code will be executed else you ask permission at runtime  if granted and rerun the same yourgetLocationmethod();
This link will be helpful
Comment: This question is about Android Studio giving the warning even if the permission is already in the manifest.


Remove 3 blank lines and two lines with text below them in Notepad++

Question: I ran a sql script that uses a cursor to execute sp_table_privileges on each table in a database.
If you run the script and save the output to a file you get this after each iteration:
data,data,data,data,data,data,data

(x row(s) affected)

next_table_name
TABLE_QUALIFIER,TABLE_OWNER,TABLE_NAME,GRANTOR,GRANTEE,PRIVILEGE,IS_GRANTABLE

I was able to remove the (x row(s) affected) in Notepad++ by using the regular expression replace with (\(.*\)) but it replaced it with a blank line.
So now I have 3 blank lines, the next tables name and the columns.
I know you can remove blank lines in Notepad++.
But, can I use a regular expression to find 3 blank lines, remove them and two lines below them?
If not is there a better way to do this?
Answer: If I understood you correcly.
Find
(\r\n){4}.*\r\n.*

replace with (Replace All)
leave empty

Box ".matches newline" leave unchecked
And if you want to delete everything beneath the three empty lines find
(\r\n){3}.*

replace with (Replace All)
leave empty

In this case Box ".matches newline" has to be checked
Comment: That works like a charm on my example, I think you answered correctly. +1
Answer: Just to clarify :
So you get something like in my screenshot once you applied your regular expression ? correct ? And then you delete the 3 blank lines like I do here ?

And you get :
> data,data,data,data,data,data,data
> next_table_name
> TABLE_QUALIFIER,TABLE_OWNER,TABLE_NAME,GRANTOR,GRANTEE,PRIVILEGE,IS_GRANTABLE

And now you want to remove "next.." and "TABLE_QUALIFIER"...etc automatically so you just keep the data,data,data etc ?
[Editing with Placido's solution for the Author of the question]
Have a look, that's what you wanted, correct ?

And then :
Comment: Yes...I want to get rid of 'next_table_name' and the line after it: TABLE_QUALIFIER, ...    Is this possible?
Comment: Yes, have a look at Placido's solution.


Prove that $\left\{u\in W_0^{1,2}(\Omega):\int_\Omega|u|^{p+1}\;d\lambda^n=1\right\}$ is well-defined and closed

Question: Let

$\Omega\subseteq\mathbb{R}^n$ be a domain with a smooth boundary
$H:=W_0^{1,2}(\Omega)$ be the Sobolev space
$p>1$ such that $$p<\begin{cases}\infty&\text{, if }n=2\\\frac{n+2}{n-2}&\text{, if }n> 2\end{cases}$$

How can we prove, that $$S:=\left\{u\in H:\int_\Omega|u|^{p+1}\;d\lambda^n=1\right\}$$ is a well-defined and closed set? Moreover, why is there a non-negative $v\in S$, such that $$\int_\Omega|\nabla v|^2\;d\lambda^n\le \int_\Omega|\nabla u|^2\;d\lambda^n\;\;\;\text{for all }u\in S\;?$$ I suppose we need to use the smoothness of the boundary $\partial\Omega$, but I absolutely don't get how I need to process in detail.
Comment: By the continuity and compactness of the Sobolev embedding.
Comment: Sorry, what do you mean by $\lambda^n$ here? It is not a standard notation for integration.
Answer: I think here you probability need $\Omega$ to be bounded as well. (however since $u\in W_0^{1,2}(\Omega)$, you do not need smooth boundary condition) And I will assume by $d\lambda^n$ you just mean $x\in \mathbb R^n$, the standard integration notation.
For your first question, since $u\in W_0^{1,2}(\Omega)$, by Sobolev embedding you have $u\in L^{p^*}$ where $p^*\leq \frac{2n}{n-2}$ and clearly $p^*> p+1$. So at least $S$ is well-defined. To show closeness, you again use the fact that $p^*> p+1$ and call compact embedding. (suppose a sequence convergence in $S$ and there is a subsequence convergence to...)
For your second question, it is known as minimizing problem. It is a big topic in calculus of variation. I would suggest you to read Evans PDE book chapter 8 for more details. I will give you a start on second question and the rest would be the compact embedding again.
Notice that the number $m\geq 0$ defined as
$$
m:=\inf_{u\in S} \left\{\int_\Omega |\nabla u|^2dx\right\}
$$
exists. So you could have a sequence $(u_n)\subset S$ such that $\|\nabla u_n\|_{L^2}\to m$. Notice that you actually have the norm of $\nabla u_n$ is bounded and hence by compact embedding...
Comment: To prove closedness of $S$ boundedness of $\Omega$ and compact embedding is not needed (only continuity of the embedding).


Impressão em 2 vias Jaspersoft Studio

Question:
Tenho um report Master que possui duas "Detail Band", com uma altura definida, que não deve ser modificada.
Meu SubRelatorio também possui uma "Detail Band", com um JRBeanCollectionDataSource, os parâmetros estão sendo passados sem maiores problemas, PORÉM, não está sendo feita a paginação da forma como eu gostaria.
Preciso que fique DUAS vias na mesma página, como um canhoto, quando são poucos itens funciona, mas existem casos em que podem ter até 200 itens, e eles precisam estar paginados, mantendo a altura fixa.

No momento, quando existem muitos itens, ele simplesmente mostra de forma contínua. Já tentei várias combinações com Stretch e No Stretch, Split Type da Band, realmente não consegui chegar a uma solução.
Eu consegui fazer um Exemplo Mínimo Verificável como o próprio StackOverFlow recomenda... segue o link do repositório - https://github.com/Sibelly/jasper-subrelatorios
Comment: E se você determinasse um detail band apenas que tive o tamanho de meia folha A4, já que os dois são iguais automaticamente ele colocaria dois em uma folha
Comment: Então, eu lembro que tinha tentado na época, porém a detail band não ficava com a altura truncada sabe.
Answer: Eu consegui resolver esse problema truncando a quantidade de itens por página no próprio código. Criei um método com a lógica responsável por quebrar os itens. Basicamente é o trecho de código a seguir:
<code>       while (quantidadeDeItens > 0) {
            if (quantidadeDeItens <= quantidadeDeItensPorPagina) {
                itensPaginados.addAll(produtos.subList(i, produtos.size()));

                // Workaround para deixar o layout sempre do mesmo tamanho
                if (itensPaginados.size() < quantidadeDeItensPorPagina) {
                    while (itensPaginados.size() < quantidadeDeItensPorPagina) {
                        Produto item = new Produto();
                        itensPaginados.add(item);
                    }
                }
            } else {
                itensPaginados.addAll(produtos.subList(i, j));
            }

            paginaCorrente = paginaCorrente + 1;

            JasperPrint printReport = setarParametrosParaImpressao(itensPaginados, cliente, totalPaginas, paginaCorrente);
            listaDeProdutosParaImpressao.add(printReport);

            i = i + quantidadeDeItensPorPagina;
            j = j + quantidadeDeItensPorPagina;
            quantidadeDeItens = quantidadeDeItens - quantidadeDeItensPorPagina;
            itensPaginados = new ArrayList<>();

        }
</code>
Porém eu tive que modificar a maneira como é gerado o JasperPrint. Não colocarei aqui pois ficaria muito extenso, para quem tiver interesse só verificar nesse repositório.
Esqueci de responder antes, mas espero que ajude alguém um dia. ;)

Impressão em 2 vias Jaspersoft Studio