How does this kind of serious injury occur in ice hockey?

Question: On 28th October 2023, an ice hockey player in England died after an incident in a game which resulted in

 his throat being slashed by a skate

A further description (but no images) of the accident are available in this Washington Post article.
As several of the people involved described it, this was a "freak accident", however, apparently such an injury is not nearly as uncommon as you'd hope. As the article cites, Clint Malarchuk in 1989 and Richard Zednik in 2008 both suffered and survived similar injuries. And furthermore, Will Borgen apparently had a near miss at some point during high school.
How does such an accident like this occur in hockey? The article offered no explanation on this and I'm struggling to imagine a scenario for such an act to occur that doesn't come off as being deliberate. At first I'd thought maybe if someone fell forwards onto another players skate as they were lifting their foot up, but from an image search nothing on the rear of the skate suggested something that would cause this injury, but maybe bludgeon the neck which while bad wouldn't be nearly as bad. Another thought I'd had was that another player gets checked on an angle with such force as to be launched into the air and spinning which might result in their legs/feet spinning at such a height to threaten to cause the injury; could that be what happened here?
Comment: Thank you for your consideration of the subject matter; I've made some further tweaks which I think are probably unnecessary but I would rather be overly conservative here. Anyone answering the question, please exercise discretion in your wording and extreme discretion if even considering any images.
Answer: Having seen a video of the incident1 it appears to be the latter of your two examples, where the Sheffield Steelers player is checked, seemingly causing his leg to rise towards Adam Johnson's neck area.
However, leaning towards your point of that sort of action being deliberate, there are rumblings as to if that sort of body check collision would cause a players leg to go so high, with some even going so far as calling for the Steelers player to be given a manslaughter charge from the police investigation.
Though, there is obviously a lot of emotion around the incident therefore objectivity might be hard to come by in these comments.
Countering these claims, Johnson's teammate has come out in support of the Steelers player posting on Twitter / X:

[...] I was at ice level on the bench closest to the accident, I saw both players moving fast.

The unintentional clip of the Panther player's leg by the Sheffield player caused the somersault. It's clear to me his actions were unintentional and anyone suggesting otherwise is mistaken.

Away from this incident itself, I guess it is possible also for two colliding players who fall in close proximity to each other, that neck and skate come into contact.
While ice skates are not razor sharp, when moving at speed, they can cause injury:

Hockey skate blades are sharp enough to cut someone when swung at high speeds but also dull enough that you could softly run your fingers across without even breaking the skin.
https://bshockey.com/how-sharp-are-hockey-skate-blades/

It could be possible that the dynamics of a fall, say an upturned skate in the path of another falling player and then the sudden stop as they hit the ice, could cause injury.

I won't post a link here for obvious reasons, but a video is available via a linked tweet on Marca Sports' article of the event on their site - though I'm not sure how long that will be available for.


Como manipular o local dos JLabels, tendo um papel de parede?

Question: Estou tentando fazer um app que tenha um papel de parede, mas não consigo mudar de posição os JButton ou JLabel. Só consigo se não tiver um plano de fundo.
Segue meu código:
public class teste extends JFrame{

public teste(){

JLabel titulo1 = new JLabel("Testes de local1");

JLabel titulo2 = new JLabel("Testes de local2");
//

ImageIcon imagem = new ImageIcon(getClass().getResource("/fotos/1.png"));

JLabel background = new JLabel(imagem);

//
setLayout(new BorderLayout());

background.add(BorderLayout.SOUTH,titulo2);

add(background);

background.setLayout(new FlowLayout());

background.add(titulo1);
//
setVisible(true);

setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setTitle("Teste");

}
}

Comment: Como assim? Pode editar e explicar melhor o problema?
Comment: Desculpe, não é JButton, são os dois JLabels que quero manipular
Comment: Veja essa resposta, ela te atende: https://pt.stackoverflow.com/a/205296/28595  se não entender algo, avisa ai que explico.
Comment: Eu percebi que encontro minha solução la, mas n consigo entender o código. O java ainda é muito novo para mim, agradeço se puder ajudar!
Comment: o background é pra ser aplicado a jframe ne? Sem se preocupar com redimensionamento nem nada? Essa é mais simples: https://pt.stackoverflow.com/a/158841/28595
Comment: Exatamente isso
Comment: Ainda assim, consigo fazer o comando, você pode pegar meu código e formata-lo para que funcione?
Answer: Evite utilizar JLabel para adicionar background em tela, pois ele é um componente comum e não vai permitir você sobrepor outros componentes sobre si.
A forma mais recomendada de se fazer isso é criar um componente do tipo Container como JPanel, ou que seja um container top level,  e sobrescrever o método paintComponent. Alem de preencher o fundo, ainda vai te permitir adicionar outros inúmeros componentes e posicioná-los como quiser:
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TesteBG extends JFrame {

    public TesteBG() {

        JLabel titulo1 = new JLabel("Testes de local1");

        JLabel titulo2 = new JLabel("Testes de local2");
        //
        BackgroundPanel bgPanel = new BackgroundPanel();
        //
        bgPanel.setLayout(new BorderLayout());

        bgPanel.add(titulo1, BorderLayout.NORTH);

        bgPanel.add(titulo2, BorderLayout.SOUTH);

        setContentPane(bgPanel);

        setSize(400, 400);

        setTitle("Teste");

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    class BackgroundPanel extends JPanel {

        Image imagem;

        public BackgroundPanel() {

            try {

                imagem = ImageIO.read(getClass().getResource("/fotos/1.png"));

            } catch (IOException e) {

                JOptionPane.showMessageDialog(null, "Não foi possivel ler a imagem !");

            }
        }

        @Override
        protected void paintComponent(Graphics g) {

            super.paintComponent(g);

            g.drawImage(imagem, 0, 0, this);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new TesteBG();
        });
    }
}

Perceba que também é recomendado configurar este painel como rootPane da tela através do método setContentPane(). A partir dai, tudo que você adicionar na tela deve ser adicionado ao painel e não diretamente na tela, para não ficar partes sem background.
Há uma forma mais complexa, porém mais efetiva de aplicar imagem de fundo a uma tela, sem ficar preso ao tamanho da tela ou da imagem, se quiser saber como, está bem explicado nesta resposta.
Comment: Ainda assim, dessa forma não consigo manipular da forma que gostaria, por exemplo: não é possível colocar os JLabels no canto inferior ou superior direito e nem mesmo no centro. Eu gostaria de ter controle total
Comment: @gui22222 isso é outro problema diferente do relatado na pergunta. A resposta atende ao problema de por um background e permitir que você adicione componentes com ele por baixo, esse problema ai é devido a layout manager. Você pode dar uma lida no link e ver qual melhor te atende: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Comment: @gui22222 da forma que expliquei, é possivel fazer qualquer coisa dentro do painel, pra isso, você precisa ter dominio de layouts, por isso é importante ver o link acima.
Comment: Entendi! Consegui resolver meu problema também, obrigado.


Remover linha do data frame com string dividida em várias colunas

Question: Possuo vários arquivos com dados armazenados em texto de largura fixa. Todos os arquivos possuem um cabeçalho com informações sobre a entidade dos dados e uma última linha no formato FINALIZADOR##########
Onde ########## corresponde ao total de registros do arquivos completados com zeros à esquerda (FINALIZADOR0000000037 teria 37 registros + a linha de cabeçalho + a linha com o FINALIZADOR).
Eu estou utilizando read.fwf("caminho do arquivo", widths = c(4,2,80), col.names = c("exercicio", "codigo", "nome"), strip.white = TRUE, skip = 1) da linguagem R e com isso consigo pular o cabeçalho, porém a linha do FINALIZADOR não estou conseguindo "pular".
Notem que widths e col.names são específicos de cada arquivo (são 27 arquivos no total).
Estou procurando uma forma de:
Ou não processar a linha que comece com "FINALIZADOR" antes de importar ou ao importar; ou
Excluir a linha que contenha FINALIZADOR mesmo que este esteja "dividido" em várias colunas. Por exemplo, no arquivo ORGAO.TXT, cujo primeiro campo tem 4 caracteres, o segundo tem 2 e o terceiro tem 80, FINALIZADOR estaria dividido em FIN, AL, IZADOR0000000037, nas três colunas.
Answer: Se o data frame se chamar dados e o objetivo for remover sempre a sua última linha, faça
dados.limpos <- head(dados, -1)

para criar o data frame dados.limpos, idêntico ao objeto dados, mas sem a sua última linha.
Answer: A seguinte função lê  o ficheiro com readLines como se fosse um ficheiro de texto, faz um pré-processamento, removendo a primeira e a última linhas e cria uma connection com o texto resultante, sob a forma de uma textConnection, tc. A leitura da tabela é feita por read.fwf a partir de tc.
Tanto o cabeçalho do ficheiro como a última linha são membros do valor da função, uma lista com os nomes

Cabecalho
Finalizador
Dados

Se pretender só a tabela de dados, este valor final é fácil de modificar.
lerFich <- function(con, widths, col.names){
  txt <- readLines(con = con)
  Header <- txt[1]
  n <- grep("FINALIZADOR", txt)
  Last <- txt[n]
  txt <- txt[-c(1, n)]
  tc <- textConnection(txt)
  dados <- read.fwf(file = tc, widths = widths, col.names = col.names, strip.white = TRUE)
  close(tc)
  list(Cabecalho = Header, Finalizador = Last, Dados = dados)
}

res <- lerFich("ORGAO.txt", widths = c(4, 10, 10), col.names = c("exercicio", "codigo", "nome"))

res
#$Cabecalho
#[1] "col1      col2      col3"
#
#$Finalizador
#[1] "FINALIZADOR0000000037"
#
#$Dados
#  exercicio     codigo       nome
#1      1234 abcdefghij 1234567890
#2      1234 abcdefghij 1234567890
#3      1234 abcdefghij 1234567890
#4      1234 abcdefghij 1234567890
#5      1234 abcdefghij 1234567890
#
#Warning message:
#In readLines(con = con) : incomplete final line found on 'ORGAO.txt'

A tabela será então
res$Dados

Ficheiro
O ficheiro criado para testes tem o seguinte conteúdo.
col1      col2      col3
1234abcdefghij1234567890
1234abcdefghij1234567890
1234abcdefghij1234567890
1234abcdefghij1234567890
1234abcdefghij1234567890
FINALIZADOR0000000037

Answer: Pode usar a opção nrows para ler só até a penúltima linha. Assim os dados serão carregados no formato apropriado e não necessita pré processar o arquivo. Só que deve primeiro determinar o número de linhas:
# Arquivo de exemplo
writeLines(
"Cabecalho
ABCD11Paulo
EFGH21Henrique
FINALIZADOR000000002",
"exemplo.txt")

nlinhas <- length(readLines("exemplo.txt")) # veja o comentário

dados <- read.fwf("exemplo.txt", widths = c(4,2,80),
                  col.names = c("exercicio", "codigo", "nome"),
                  skip = 1, nrows = nlinhas-2)

> dados
  exercicio codigo     nome
1      ABCD     11    Paulo
2      EFGH     21 Henrique

> str(dados)
'data.frame':   2 obs. of  3 variables:
$ exercicio: Factor w/ 2 levels "ABCD","EFGH": 1 2
$ codigo   : int  11 21
$ nome     : Factor w/ 2 levels "Henrique","Paulo": 2 1

Se seus arquivos são muito grandes, usar readLines será pouco eficiente. Se está usando *nix, pode chamar wc -l:
nlinhas <- as.integer(sub("\\D.*", "", system("wc -l exemplo.txt", intern = TRUE)))


Is it possible to reduce a song written in chords into one with single notes

Question: Suppose that you want to practice the memorization of your repertoire by humming the notes while you drive.   You can only hum one note at a time, not chords.  I suppose you could just play the root note, but would you do in the case of dyads?

Update
Let me give a concrete example: this is from Stravinsky's Sonata for two pianos, 2nd movement, one of my favorite pieces.  Do you see the 6th note?  It's not a chord and if you ignore the G note, then it doesn't sound right.  Then again, you can't substitute those two notes for something else.
Comment: Transposing is a very understandable word, but it just happens to be culturally assigned to a completely unrelated concept. Maybe you meant "transform"?
Comment: So the question is more like "how to practice remembering harmonies with a non-chordal instrument"? Nothing to do with transposing.
Comment: Please provide some examples of the kind of music you are talking about.
Comment: BVW 114, Minuet in G major
Comment: I can't find any A note.
Comment: I meant G .....
Comment: I'm not aware that arranging music with chords or dyads into music with single notes has a name, so I used the word most understandable.
Comment: A few people have managed to teach themselves to hum one tune while simultaneously whistling a countermelody.  Not what I recommend here, but it is a fantastic ability!
Comment: Related, if closed, question: https://music.stackexchange.com/questions/77732/is-it-possible-there-are-beautiful-songs-that-take-more-than-two-hands-to-play/77737
Comment: This is going to depend _entirely_ on the kind of song. A Bach chorale? Probably. A Palestrina motet? Not gonna happen.
Answer: I think you can try to outline the chord with your humming like a walking bass. Like for a bar of C you could humm C - E - G - E. Thats what a walking bass is about: 'outlining the chords'.
If the chords change to fast for you to outline the full chords, you can try to omit some chord notes (humm only root/fifth or thrid/seventh)
Answer: This is a good method to practice the chords and train the ear!
If you mean to reduce a song written in chords to one single voice ... that's impossible.
But you can try this:
e.g.:We shall over come
singing two 16th (l.h. root and 3rd) and holding the melody  note (r.h.) as a quarter note or even a half note.
domiso__ domiso__ domila__ domila__ domiso_ domisofa  ....
The example of all examples is the prelude in C by Bach. You can sing the arpeggios like Arvo Paert plays it in a fast tempo. Try this out and then you can do it with a slow song always starting with the triad root or bass note.
You can download any piece or song in double speed and sing the lowest  pitch and the   highest pitch and imagine the middle parts of the chords. But you can also sing it slow ... as you like.
also this is an interesting exercice:

BWV 114 you can practice as following:

Play the bass line l.h. and sing the melody Play the melody r.h. and
sing the bass line
Sing the bass line and "listen" to your inner ear the melody and vice
versa
Sing the chord as triad domiso
You can also try to sing both lines skipping from the lower to the upper part, but this has to happen very slowly ...

BWV 114 is not so practicable like other pieces by Bach as e.g. BWV 999
Update:
The Largo of Stravinsky's  Sonata looks as a good example to try singing both parts as one skipping from the l.h. to the r.h.
Answer: It's not really transposing. What you're trying to do isn't going to be that productive if you keep changing bits round. How will that cement anything into memory, when it's not strictly what you eventually play (or sing).
Best bet is to get recordings, and you can play them in the car, and hum/sing along with them. That way, you are absorbing the whole thing, while singing along to any part you like. In key as well..!
Comment: I disagree, the point is to practice memorization.  Of course, I can listen to music, but that doesn't test whether or not you're able to reproduce it.
Comment: O.k. So how do you know if you're singing it right, and is being able to sing something the same as being able to play that same thing? I think not. It may help a little, and if that's o.k., fine, but it woudn't be enough for me.
Comment: When you're in your car what else are you going to do?
Comment: I would turn the volume down and up - that helps me keep in time as well. But I certainly don't do my practice while driving. My concentration is taken up with driving safely!
Comment: Turning the volume up or down is more dangerous than humming a tune since with the former your hand is on your musical device rather than on the wheel.  Further, in most states the law prohibits use of electronic devices while driving, but it certainly does not prohibit singing or humming.
Comment: No when the controls are on the wheel! But we'll agree to differ.
Comment: Just an FYI, the "transpose" remark has been removed from the question.
Answer: When talking about popular music, you probably won't have songs written in "chords". The majority of popular music is based on melody. Sure you have chords backing the melody, but if your plan is to memorize the song, you should be singing the melody and be sure to know what harmony comes with it.
But supposing you're playing something that is truly just chords like The Chord Catalogue, you could try singing the highest note in pitch for each chord. If that doesn't work (like chords changing by bass movement), sing the higher note that is moving from chord to chord.
Answer: A song written in chords tends to be homophonic and can therefore be reduced to single notes and a singable/hummable melody fairly easily. I know I've converted lots of music I've listened to this way by ear, including some with no published sheet music. I've almost always been satisfied with the results (although I do like singing accompaniment notes I can squeeze in). In fact, I tend to compose by humming a melody until it sticks, then harmonizing it.
What throws a wrench into this method is polyphony and counterpoint. The excerpt in the question/OP alludes to this: the lower displayed staff of its Bar 2 is a rough inversion of the contents of Bar 1. An astute listener likely wants both the new material and the rough inversion in Bar 2 to be heard, and they may not be satisfied with only one of them sounding at a time.
I've generally sung polyphonic pieces and pieces with strong and distinctive enough accompaniment by singing a different musical line in each repeat or the loudest musical line in all repeats. I'm often not satisfied with the singing results of any one repeat as a result. (I swear a recording of the slower Bach Well-Tempered Klavier fugue in F Minor I listened to several times when I was younger has forever messed up how I sing that piece and possibly all polyphonic pieces, simply because it kept emphasizing the topmost line.)
Answer: I haven't used this process to work on a instrument part before, however when I work up a harmony vocal, I sometimes record my vocal part played on an instrument and then use that to memorize the part by playing it back and singing along with it. I do this in my music room, but it might work for you if you have a music player in your vehicle. It can help you get used to recording yourself too.
Answer: Of course you can, Mr. Schenker!
Jokes aside, you can always simplify dense chordal passages to triads, intervals and even single notes, but why doing this? This may lead you to an incredible knowledge of the pieces form and important points of formal coherence or lead you to nonsense understanding of harmony and form.


Java - Searching table for an object with a matching String

Question: I'm searching through a table for a customer with a matching name, if found then I want to return that customer, otherwise return null. The problem is I'm getting null all the time, I think my problem is with the if in the inner for loop.
public class testter
{
    public Customer isCustomerInTable(Customer[][] table, String customerName) {
        for ( int r = 0; r < table.length; r++ ) {
            for ( int c = 0; c < table[r].length; c++ ) {
                if ( table[r][c].equals(customerName) ) {
                    return table[r][c];
                }
            }
        }
        return null;
    }
}

My customer class:
class Costumer {

    private String name;

    public Customer()  {
        name = "";
    }

    public void setCostumerName(String name) {
        this.name = name;
    }

    public String getCostumerName(){
        return name;
    }
}

Any ideas? Thanks
Answer: You if condition should be
if (table[r][c].getCostumerName().equals(customerName))

You need to compare the names, but in your case, you are comparing the Customer object with the String customerName.
Comment: As soon as I finished submitting the question I got the answer by my self, but since yours is exactly what I had in mind. I'm gonna give you credits, Thanks
Answer: You are checking Customer object with a string. That's the reason. You should do the following
if ( table[r][c].getCostumerName().equals(customerName) ) {
    return table[r][c];
}


Python3 - error installing jwt with pip3 on Ubuntu 14

Question: After know that jwt package is incompatible with python2, I am trying to install it with pip3:
sudo pip3 install jwt

I am getting the following output:

Exception:
    Traceback (most recent call last):
   File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2482, in
  _dep_map
     return self.dep_map
     File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2344, in
  __getattr
     raise AttributeError(attr) AttributeError: _DistInfoDistribution__dep_map
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
   File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main
      status = self.run(options, args)
   File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 278, in run
      requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
    File
  "/usr/lib/python3/dist-packages/pip/req.py", line 1266, in
  prepare_files
      req_to_install.extras):
  File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2291, in
  requires
      dm = self._dep_map   File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2484, in
  _dep_map
      self.__dep_map = self._compute_dependencies()
   File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2508, in
  _compute_dependencies
      parsed = next(parse_requirements(distvers))
   File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2605, in
  parse_requirements
      line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec")
   File "/usr/lib/python3/dist-packages/pkg_resources.py", line
  2583, in scan_list
      "Expected ',' or end-of-list in",line,"at",line[p:] ValueError: ("Expected ',' or end-of-list in", 'cryptography <2.,>=1.7.2', 'at',
  ',>=1.7.2')

Any help?
Answer: Solved problem. I had to upgrade pip3:
pip3 install --upgrade

After this, I am able to install jwt with the following:
pip3 install jwt


Manipulação de Consulta Sql em Select (Combo Multipla opção no Zend)

Question: Bom dia,
Tenho um "Select" que me lista como opção tudo que estiver na tabela "areas", seguido da palavra "TODAS",
Logo a baixo de cada opção "area", é listado aquelas subáreas que tem ligação com a área.
Quando clicar em "áreas - todas", então o select automaticamente entende como todas subáreas, e as seleciona corretamente.
Está funcionando,
O problema ocorre quando não há subáreas e então aparece o nome da área seguido de "- todas",
O usuario seleciona essa opção e não entende o por que não funciona, mas é por que não existe sub-áreas,
Eu preciso ocultar essa opção, para quando não existir sub-áreas, mas não sei em que parte do código fazer a modificação.
Por que na segunda parte, onde mostra as sub-areas dentro da área, então já listou a paavra "área - todas".
o código é
<code>private function getComboBoxGroup ()
{
    $group = [ ];

    foreach ( $this->getAreasTable ()->fetchAll () as $area ) {
        $group[$area->__get ( 'f_name' )] = [
            'label'     => $area->__get ( 'f_name' ),
            'data-area' => $area->__get ( 'f_id' ),
            'options'   => [ "ALL - {$area->__get ( 'f_name' )}" => "TODAS - {$area->__get ( 'f_name' )}" ]
        ];
    }

    foreach ( $this->getActionsTypesTable ()->fetchAll () as $action ) {

        if ( array_key_exists ( $action->__get ( 'f_area' ), $group ) ) {
            $group[$action->__get ( 'f_area' )]['options'][$action->__get ( 'f_id' )] =
                "[{$action->__get ( 'f_area' )}] " . $action->__get ( 'f_name' );

        }

    }

    return $group;
}
</code>
Answer: Tente verificar os dados
<code>'options'   => [ "ALL - " . !empty($area->__get('f_name')) ? $area->__get ( 'f_name' ) : "alguma coisa" => "TODAS - " . !empty($area->__get ( 'f_name' ))? $area->__get ( 'f_name' ) : "alguma coisa" ]
</code>


Does $\lim_{x \to 0}({z^2\over \overline z})$ exist? $(z\in \mathbb{C})$

Question: I am trying to figure out if $\lim_{x \to 0}({z^2\over \overline z})$ exists or not. This is a way I though to show that this does not exist but I am not entirely sure.
 Let $a_n={1\over n}$ and $b_n={i\over n}$.
 $f(z)={z^2\over \overline z}={z^2\overline{z^2}\over \overline z^3}$=${|z|^2\over \overline z^3}$.
Thus, $f(a_n)=n$ and $f(b_n)=-{n\over i}$
$\lim_{n \to \infty}f(a_n) \rightarrow +\infty$ and $\lim_{n \to \infty}f(b_n) \rightarrow -\infty$. Thus the limit cannot exist. Is this correct? If someone has a better answer or any other method of solving this please do share. Thanks
Answer: you're mistaken. actually $z \bar{z} = |z|^2$ and not $|z|$ which is what you're using in your argument. The limit actually exists and is equal to $0$
oh, and if you're looking for a precise argument you can try the following: let $z_n \rightarrow 0$. Write $z_n = r_n e^{i \alpha_n}$ - in trigonometric form. You now know that $r_n \rightarrow 0$ and $\bar{z} = r_n e^{-i \alpha_n}$.
Comment: I was just stupid thanks for correcting!! How can you say it is 0?
Comment: So construct a general sequence and show that it all converge to 0?
Comment: yeah, you use the sequential definition of convergence


Android : maps from intent

Question: In my application : I have Find Home Tab..
On clicking it and after passing the co-ordinates from emulator control it should show the map...
If I use intent
<code>Uri uri = Uri.parse("http://maps.google.com/maps?saddr=42.35892,-71.05781&daddr=40.756054,-73.986951");
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
        startActivity(intent);
</code>
Its not showing the tabs of my application...
How do I associate intent with my application and make it show the map in my application..
Also is it possible to show textbox below the map displayed by this intent??
Please help..
Thanks.
Comment: Thanks for doing that! Unfortunately, I don't have an answer for you, but there are lots of other smart people here. I'm counting on them!
Answer: You will have to include the map in your Activity.
Here the infos by google:
http://developer.android.com/resources/tutorials/views/hello-mapview.html
Text below the Map:
How can I add a TextView below a MapView?
You can then set the tab to display the MapActivity you created the way explained int hose links above.
To draw the path in the Map do the same as the person here: android get duration from maps.google.com directions
Comment: thanks.. but in that case I have to draw the route myself on mapview overlay...  I want to use the intent and show the map displayed by intent on top of my application so that the buttons of my application and visible to user.. is this possible ??
Comment: i just tried it to put the browser or the google map app into a tab. is not working :( i can put my own activity in a tab, but not theirs. they just start the new app. seems you will have to display the path by yourself.
Comment: just found another post about showing the driving directions in the  own map.. added the link to my answer.
Comment: thanks patrick... I am already showing the path, but I wanted detailed directions to be shown to the user... adding map using intent works best but I wanted the controls in my application to be shown as well.. looks like its not possible :(

Android : maps from intent


Enabling a block to inherit the settings of a sub theme

Question: Being relatively new to Drupal, I apologize in advance if what I'm saying is unclear, but I'd imagine that a fix should be simple enough:
Basically, I'd like to add a header block that functions identically to the other block regions on my Drupal site. At the moment, the text of that header is not responsive to window size, unlike the rest of the site. How can I inherit the default settings of my theme when creating a new block?
Thanks in advance, a solution to this would help me tremendously.
Answer: You can style a block however you like - since it is going in the header, it sounds like a css issue for the header region. I would start by comparing the css for the content and/or footer regions with that of the header.  If all else fails, you can theme individual blocks - here is some info.


What is blocking my mysql connection?

Question: We run several docker images on a VM.
sudo iptables -S shows a lot of docker networking.
We try to connect to an external MySQL database in another net.
mysql --host=mysql.example.org --user=thisuser thatdatabase

We get error message:

ERROR 2002 (HY000): Can't connect to MySQL server on 'mysql.example.org' (115)

Network logs show that external firewall does not recognize a connect attempt.
We tried to shut down docker and try again with no avail.
sudo traceroute mysql.example.org
traceroute to mysql.example.org (111.222.333.444), 30 hops max, 60 byte packets
1  localvm.example.org (172.17.0.1)  3071.799 ms !H  3071.763 ms !H  3071.754 ms !H

The 172.17.0.1 is -not- the ip-address from the local system.
On another vanilla system we can connect to this instance.
We tried to use a explicit route with no avail.
ip route add 222.333.444.0/24 dev ens192

traceroute mysql.example.org
traceroute to mysql.example.org (correct external ip-address), 30 hops max, 60 byte packets
1  localvm.example.org (correct local ip-address)  3068.673 ms !H  3068.566 ms !H  3068.532 ms !H

Any suggestions how to narrow down errors?
Is it time to start wireshark?
VM is Debian 10, client is mysql Ver 15.1 Distrib 10.3.22-MariaDB
Comment: "VM is Debian 10".  What is the host OS?
Comment: I realized that docker services added IPTABLES-rules.  Now, how do i add iptables rule to allow TCP/3306 connection to mysql.example.org?
Comment: If i want to allow connections -from- foreign systems i should use
iptables -A INPUT -i eth0 -s aa.bb.cc.dd -p tcp --destination-port 3306 -j ACCEPT

But i have to allow connections -to- a foreign system.
Comment: @Gerard: Host is a well configured VMWare. VM client is Debian 10
Comment: The "external" database server has a private IP address?  Better add your routing info to the question, where you can format it properly.
Answer: Turned out that we had to tell docker not to use 172.17.0.0/24 network.
According to how-do-i-configure-the-default-bridge-docker0
we changed
/etc/docker/daemon.json
{
  "bip": "172.26.0.1/16"
}

systemctl restart docker;systemctl status docker

Old route entry was
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         ....            0.0.0.0         UG    100    0        0 ens192
...........     0.0.0.0         255.255.255.0   U     100    0        0 ens192
172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 docker0

route now shows different net:
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
172.26.0.0      0.0.0.0         255.255.0.0     U     0      0        0 docker0

Now its not conflicting with the existing server and connection is possible.
Thanks very much to all for your help!
Comment: If you have leftover routes you can delete them with:

route del -net 172.17.0.0 netmask 255.255.0.0
Answer: normally means that there is no MySQL server running on the system or that you are using an incorrect Unix socket file name or TCP/IP port number when trying to connect to the server. You should also check that the TCP/IP port you are using has not been blocked by a firewall or port blocking service.

What is blocking my mysql connection?


Microsoft azure para alojar website?

Question: Surgiu-me uma dúvida, eu tenho um domínio e um alojamento requisitados a uma empresa normal. Ouvi falar de Microsoft Azure que funciona através de cloud. Podiam-me explicar melhor como isto funciona para um website?
Se permite ser exatamente igual o site em php e as bases de dados tudo online como num outro alojamento qualquer. E este serviço torna mais rápida a navegação no website e claro existe alguma vantagem econômica?
E se trocar existe possibilidade de usar um domínio registrado noutra empresa? Obrigado pelo ajuda, peço desculpa pela chuva de perguntas mas estou muito curioso acerca deste sistema.
Comment: Pedro, te aconselho a [ler a documentação oficial](http://azure.microsoft.com/pt-br/) disponibilizada pela MS no site do Azure... Se eu não me engano o Azure também aceita sites em PHP. Entre em contato com o pessoal da MS pra saber mais também.
Comment: Só confirmando, suporta PHP sim e [algumas coisas legais a mais](https://azure.microsoft.com/blog/2015/04/15/supercharge-your-php-productivity-on-azure/) =)
Answer: O Azure tem algumas opções para o alojamento de websites. As mais comuns são as seguintes:

Máquinas virtuais: a opção de IaaS (Infrastructure as a Service) - você basicamente "aluga" um computador que está rodando no cloud, e é responsável por instalar tudo o que é necessário para rodar o seu website. O computador pode estar rodando Windows (várias versões) ou Linux (várias versões). Você tem o total controle sobre a máquina, inclusive sendo responsável por fazer atualizações necessárias.
Websites: a opção de PaaS (Platform as a Service) - você faz o upload dos arquivos que formam o seu website, que irão rodar em uma máquina gerenciada pelo Azure. Patches e outros updates são aplicados automaticamente, e você só precisa se preocupar com o website em si. Várias linguagens são suportadas, entre elas PHP (dá uma olhada nesse tutorial: criar o website ou nesse outro tutorial - mais completo, usando PHP e MySQL para mais informações).

As duas opções acima suportam domínios customizados, mesmo que estejam registrados em outras empresas (há um tempo atrás eu tinha um domínio registrado no GoDaddy.com que apontava para um website do Azure; não lembro como foi a configuração mas não era muito complicado).
Em relação a base de dados, no primeiro caso (máquina virtual) você pode instalar o BD na máquina (ela é "sua", e pode fazer o que quiser com ela). No segundo caso você pode ou usar algum BD no cloud (tanto no Azure quanto fora dele, contanto que você tenha algo tipo um connection string que aponte para onde a base de dados está armazenada), ou até mesmo ter uma base de dados local (na sua empresa), e acessá-la via "conexões híbridas".
Em relação à velocidade: provavelmente não vai ter muita diferença em relação a se você tiver o site rodando localmente. A vantagem do Azure (e de outros provedores de Cloud, como o AWS) é que eles têm vários data centers, então você pode ter o seu website redundante em vários locais e o cliente acessará o que tiver mais perto, reduzindo a latência das requisições.
Em relação ao preço - você paga o que você usa. Uma máquina virtual vai sair mais caro que um website simples, mas você tem mais controle. Com os websites também há vários modos (desde de gratuitos, com umas quotas relativamente baixas e pior performance, até os pagos que você paga dependendo do tamanho da máquina que está sendo usada e quantas cópias (replicação) estão rodando. Dá uma olhada na página da calculadora de preço que você pode ter uma ideia de quanto custa.
Comment: Obrigado pela sua ajuda
Answer: Se vc estiver pensando no contexto de uma máquina so, então, quase não existem vantagens. Digo quase, pq sempre da para se tirar proveito das ferramentas oferecidas nesses ambientes de cloud, mas, em contra partida, é um ambiente mais caro (proporcionalemente falando).
As vantagens, de ambientes como da Azure, irão aparecer em casos onde vc comece a necessitar de escalar o seu site.
Um exemplo seria o caso de vc ter uma máquina que rodará 100% do tempo (24 h/d e 7 d/s). E pode alugar outra máquina que só vai estar ligada em horários de pico.
Pq alguém vai querer isso? Pq não uma máquina só e mais "potente"?
Para explicar é necessário ter em mente que:
CLOUD (a da Azure, no caso) === Ambiente super gerenciado/controlado
Se é um ambiente "super gerenciado" eu posso alugar uma máquina bem pequena, pagar mais barato por ela e ligar outra máquina somente quando o meu site tiver a demanda para isso.
Só para explicar o que quis dizer com "super gerenciado"... É pq, em ambientes como o da Azure, existem varias variáveis que podemos configurar conforme a nossa demanda. Podemos configurar largura de banda, espaço em disco, memória, etc. (várias outras coisas). E uma vez configurado podemos criar imagens (cópias da máquina) e replicar de maneira muito fácil. E ainda decidir que hora ligar/desligar cada máquina. E o melhor de tudo... Isso pode ser, depois de configurado (é claro :]), automatizado.
E com isso, as empresas, quando encontram a equação correta, passam a economizar dinheiro.
Resumindo... Cloud (Azure, no caso) é o lugar para que tenhamos um ambiente sempre com 100% de uso dos recursos. Ou seja, nada de ociosidade, nada de pagar pelo que não está sendo utilizado.

Microsoft azure para alojar website?


Moving from internal raid to nas for video editing

Question: I've got a two drive raid 0 in my main desktop for 9tb of usable storage. I actively use premiere pro and the adobe suite to produce videos that I am paid for and I do web development.
I backup to cold stored hard drives pretty frequently and have about 20 tb of data stored that way.
I'm thinking about moving to a nas for these reasons.
1) I could have a 4 drive Raid 5 accessible from the network for my main machine
2) I could access that from other machines in the office.
3) I could have access via wifi from my laptop
4) I could free up space in my main desktop and move to ssds for all of my desktop needs, 1 to hold assets, 1 to hold working files, 1 for exporting.
5) The NAS could act as a plex server to serve video to our tvs and media players
I'm thinking of going to the synology 916+ for the fact that I have synology servers in other locations for clients and they work well and are reliable. Plus they have some other features that would be handy, like video surveillance server and asterisk server.
Does anyone see any problems with this? Am I going to run in to trouble with editing this way that I'm not seeing? I have 10 4tb drives that I use for cold storage that I would continue to back up to in addition to this server but the server would hold files that I am using actively and then also allow me to back up my desktop and workstations actively without really thinking about it.
Thanks
Comment: Moving to Super User I guess. Sometimes I wonder why I use these sites lol.
Answer: If you do not work directly from NAS, the only problem I am seeing is RAID 5. RAID 5 is deprecated. It has very slow write rates and for drives above 1 TB the resilvering takes so long that there is a good chance you are going to lose a second drive while the array is rebuilding. For this reason, go RAID 10 in your case, since you have cold storage anyway.
Reading speed will be limited by the network. If you build yourself a freeNAS for example, it would cost around the same, but you could put a 10 GBit card into it. A pair of 10 GBit cards has become very affordable.


how can i retrieve the text data from sqlite datadase in objective-c?

Question: i am using this
  -(void) Data

  {
   databaseName = @"List.sqlite";

  NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
      NSUserDomainMask, YES);
  NSString *documentsDir = [documentPaths objectAtIndex:0];
  databasePath =[documentsDir stringByAppendingPathComponent:databaseName];

  [self checkAndCreateDatabase];

  sqlite3 *database;
  if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
  {
    if(detailStmt == nil)
    {
        const char *sql = "Select item from list";
        if(sqlite3_prepare_v2(database, sql, -1, &detailStmt, NULL) == SQLITE_OK)
        {
            NSLog(@"Hiiiiiii");

            while(sqlite3_step(detailStmt) == SQLITE_ROW)
            {
                NSLog(@"Helllloooooo");
                NSString *item= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 0)];

                //item1=item;
                NSLog(@"%@",item);

            }
            sqlite3_reset(detailStmt);
        }
        sqlite3_finalize(detailStmt);
        sqlite3_clear_bindings(detailStmt);
    }
}
detailStmt = nil;
sqlite3_close(database);
}

Comment: @uttam: Please provide more specific details about what you want.
Comment: Why not just use Core Data?  The sqlite API is actually quite thoroughly difficult to use correctly. Core Data has better introductory documentation and better support.
Answer: You should have a look at this tutorial. It always helped me when I used sqlite in ios. For me it looks like you should structure your code a little bit, you shouldn't load any path's inside a query method.
Maybe the problem occurs because of
sqlite3_reset(detailStmt);
sqlite3_clear_bindings(detailStmt);


Post Fedora Server upgrade to FC38, Apache httpd server no longer honors Lets Encrypt keys

Question: The environment has twins of virtually everything, including two web server / firewall / gateway systems, and they were getting long-in-the-tooth version wise, so I decided to upgrade from Fedora Server 30 to 38 on one of them.
My timing was curious because at the very same time I began the upgrade, without even touching (physically or electronically) the other server, it decided to fail! So, now I have a "server down" scenario. -ugh-
The update DID NOT involve crossing Apache's HTTPD's change in handling SSL keys, I don't think, because both before and after versions are sub-versions of 2.4 - the older was 2.4.41 and the younger 2.4.57, which is the present youngest version, which coincides with Fedora Core 38. (This is Fedora Server 38, of course.)
However, when starting, Apache's HTTPD (hereafter just called httpd), complains about the lines pertaining to the encryption keys provided by LetsEncrypt.
The keys are all current, of course, as LetsEncrypt doesn't let you get keys that last more than 3 months, I think.
The errors are like this example:
May 20 17:09:24 host2 httpd[3180]: AH00526: Syntax error on line 76 of /etc/httpd/conf.d/virtualhosts.conf:
May 20 17:09:24 host2 httpd[3180]: Invalid command 'SSLCertificateFile', perhaps misspelled or defined by a module not included in the server configuration

However, a VERY basic check of the documentation yields this link, which provides a template example which is virtually identical to what's in the virtualhosts.conf file - namely:
LoadModule ssl_module modules/mod_ssl.so
Listen 443
<VirtualHost *:443>
ServerName www.example.com
SSLEngine on
SSLCertificateFile "/path/to/www.example.com.cert"
SSLCertificateKeyFile "/path/to/www.example.com.key"

Rather than me come up with a version of my own config that likewise removes the exact domains the server hosts.
I did a thorough listing of the packages that WERE installed and then that are NOW installed and don't see anything but mod_http2-1.15.3-2.fc30.x86_64 on the old system and mod_http2-2.0.11-2.fc38.x86_64 on the new one, and there are some 106 modules installed so...
Given all this focus on security and encryption, what gives?
Answer: It turns out that the silly people who now run the show, all the while screaming about security, don't deign to include the module; not only is it NOT in the httpd software package, it's not in the mod_http2-2.0.11-2.fc38x86_64 package EITHER!
Instead, you have to:
dnf install mod_ssl

in order to get this - and then INSTANTLY it all works.
Ya know, I think this is a BUG - I see it as a packaging bug but it's surely a documentation bug at the very least, as I actually looked. And no, buried deep in the documentation is not OK! Hence my wasted time - hope this saves someone some time.


New Relic warning: the Xdebug extension prevents the New Relic agent from gathering errors. No errors will be recorded

Question: In /var/log/newrelic/php_agent.log on my servers I see lines like this:

2013-08-30 16:05:01.444 (15615/child) warning: the Xdebug extension prevents the New Relic agent from gathering errors. No errors will be recorded.

Yet, I still see [at least some] PHP errors in New Relic. What's going on? Is this warning a bug in New Relic?
I also found this which says:

If you are using xdebug, you will have a warning about this. So you could turn off Xdebug , or write your own handler and call New Relic API to allow errors report into New Relic properly. See the comments of Kris Weltz for more information.

The words "Kris Weltz" link to a missing document.
Here's what I've got installed:
# rpm -qa | grep relic
newrelic-php5-common-22.214.171.124-1.noarch
newrelic-php5-184.108.40.206-1.x86_64
newrelic-repo-5-3.noarch
newrelic-daemon-22.214.171.124-1.x86_64
newrelic-sysmond-188.8.131.527-1.x86_64

Answer: I got help from New Relic support.
Their response was basically that Xdebug indeed conflicts with New Relic, and they should not be used simultaneously. Uninstalling the Xdebug PHP extension made the warning go away.
It may be possible to disable stack traces in Xdebug and continue to use other Xdebug features, but New Relic support didn't comment on this.
Answer: Instead of uninstalling extension you can also disable xdebug extension loading in the .ini files.
I use docker, so in the docker container where docker agent runs.
In

In /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini comment following line: zend_extension=xdebug
Also, in /usr/local/etc/php/conf.d/xdebug.ini comment following line: zend_extension=xdebug.so
Restart PHP service or docker container.

If the .ini paths does not match to yours, running php --ini command will list all the .ini files that it uses.
This solution worked for me.


differences-in-differences regression with peer effects

Question: I am interested in running a differences-in-differences regression that exploits the passage of a law at the state-level. I am also interested in understanding not only what happens to the treated units in those states, but also to peers of those units in other states. For instance, if the units are families, and a law is passed in California, I would like to study the effect of these laws on families outside California that are linked to families in California (such as having a family tie or a social tie). Therefore, the treatment group are not the treated families, but rather their peers.
If someone knows of useful literature on something along these lines, I would very much appreciate it!
Answer: I'm a newbie but off the top off my head - no literature.
Peer State would be another level of treatment, socially tied individuals would need a new variable identifying them as a cluster.  Use cluster as random effect.


What is the definition of a chord?

Question: I'm self-studying music. I'm trying to learn about chord but I'm currently stuck on its definition. I've read that a "chord" is like a triad, which is 3 notes comprised of a root, a third, and a fifth. But in other definitions, a chord can be any combination of notes, as long as it is 3 OR MORE notes. So what is a chord, then, how many notes is it comprised of
Answer: Basically, a chord is comprised of 3 or more notes. Some disagree and say a chord can be made up using only 2, although that's usually called a dyad. Anyone marking this answer down due to that statement has a perfect right to explain why.
Those 3 notes together get called a triad, and can be any 3 notes at all. Obviously, some combinatios won't sound so good, and the most common combinations are 1, 3 and 5 of a major or minor scale.
Chords of more than 4 notes are often termed extensions, as they can contain extra notes, usually in what we call stacked thirds. As in C E G B D - each a third apart from the next note - 1 3 5 7 9. That will be called Cmaj9. Often, in chords that have several extensions, specific notes are omitted, partly due to clashes in sound, partly due to the fact that on some instruments - guitar, for example - all the relevant notes can't physically be played simultaneously.
So, a chord has anything from 3 to many notes in its make-up. There is no maximum number.
Comment: "There is no maximum number." Someone might argue that C1 - C2 - C3 - C4 - C5 - C6 - C7 - C8 is not a chord in all meanings of the word, despite having eight notes. Or how about overtones ... lots of different frequencies. :) White noise? Chord with all possible notes at the same time.
Comment: CFG could be Fsus2/C, Caus4, G7sus4(no5)/C. And that's just three notes. Every fully diminished 7th chord has three names. And something like CDGBE has lots of possible names.
Comment: @piiperiReinstateMonica - I should have probably stated 3 **different** note names. I guess theoretically, one note *could* constitute a chord, as overtones/harmonics are often audible, thus making 'several notes'. Food for thought?
Comment: @piiperiReinstateMonica Let me introduce yo to the [sUpEr UlTrA hYpEr MeGa MeTa LyDiAn](https://www.youtube.com/watch?v=HeTygKpi6pI&list=LLSCnPN56BRVSDBacr5oeTag&t=289s)
Comment: IMHO the best answer would clarify that there is not one single widely agreed upon definition of *chord* among musicians, but that it most often is 3+ notes, sometimes 2+ notes, sometimes must be 3+ different note names (i.e., octaves don't count), might include clusters or might not, etc.
Comment: I'd also note that anyone downvoting this answer has a perfect right to **not** explain why.
Comment: @ToddWilcox - merely hoping someone may have the reasoning they used. Naming dyads is simple - they're intervals. Naming chords is fairly simple. I've asked similarly previously - how would one name the 'chord' C and F?
Comment: @ToddWilcox - the reason I keep banging on about unexplained downvotes is simple. As a teacher, merely saying something is wrong is pretty well no help to a student. An explanation as to *why* it's wrong makes a lot more sense - there is usually some learning going on. As a teacher yourself, that must be apparent. I learn very little from a dv anonymously given. Thus my encouragement for explanations. 2+2=5. No, it's wrong. But so are millions of other answers to that. Let's try some of them...
Comment: How would one name the chord composed of C and F? Context. Seems like you're implying that for something to be a chord, it must be possible to "name" it. It might clarify your answer to include that. I'd like to suggest that asserting that chord must have one clear name might muddy the waters. Pretty much every chord could have multiple names and we need the context to be able name them. C E G? That's just E-6/C of course.
Comment: One reason why defining "chord" as requiring three notes is that there is **wildly** popular usage of the phrase "power chord" which comprise only two notes. Someone coming away convinced that it's only a chord if it has three or more notes might easily get confused in their search for how to play "power chords". Then again, some music theory teachers might object to calling two simultaneous notes a "chord", so I don't think we can offer a single definition that works in every situation.
Comment: @ToddWilcox - I'd be surprised if any chord had more than two sensible names - C6=Am7, Fm6=Dm7b5 are two that spring to mind. Have you honestly ever seen written and had to play Em6/C? Doubtful... Responding to the last comment - the *only* (*recognised*) two note chord seems to be that ubiquitous - as far as guitarists are concerned - the 'power chord' (5).
Comment: @ToddWilcox - CFG is Csus4 or Fsus2.(Although you prbably know my feelings about sus2. Ret2 is politicallyy correct. Unsure about Caus4 etc. But when music is written, it's supposed to be for ease of playing while being read. That's it for now!
Comment: @ToddWilcox - fair point about naming chords! Dyads will always have one name only. I guess with my rhythm guitar hat on, I'm used to seeing chords named, and thus playing them. Incidentally, fully dim7 chords have more names - for instance, Co=Ebo=Gbo=Bbbo=Ao at least!

What is the definition of a chord?


MongoDB nested group by query

Question: I want to count correct, incorrect and unattempted question count. I am getting zero values.
Query -
db.studentreports.aggregate([
{ $match: { 'groupId': 314 } },
{ $unwind: '$questions' },
{ $group:
    {
      _id: {
       dateTimeStamp: '$dateTimeStamp',
       customerId: '$customerId'
      },
      questions : { $push: '$questions' },
      unttempted : { $sum : { $eq: ['$questions.status',0]}},
      correct : { $sum : { $eq: ['$questions.status',1]}},
      incorrect : { $sum : { $eq: ['$questions.status',2]}},
      Total: { $sum: 1 }
    }
}
])

Schema structure -
{
    "_id" : ObjectId("59fb46ed560e1a2fd5b6fbf4"),
    "customerId" : 2863318,
    "groupId" : 309,
    "questions" : [
        {
            "questionId" : 567,
            "status" : 0,
            "_id" : ObjectId("59fb46ee560e1a2fd5b700a4"),
        },
        {
            "questionId" : 711,
            "status" : 0,
            "_id" : ObjectId("59fb46ee560e1a2fd5b700a3")
        },
....

values unttempted, correct and incorrect are getting wrong -
"unttempted" : 0,
 "correct" : 0,
 "incorrect" : 0,
 "Total" : 7558.0
Group by is required based on datetime and customerId.
Can some one correct query ?
Thanks.
Answer: You want to sum these fields only if a certain condition is met.
You just have to rewrite your group statement like this:
{ $group:
    {
      _id: {
       dateTimeStamp: '$dateTimeStamp',
       customerId: '$customerId'
      },
      questions : { $push: '$questions' },
      unttempted : { $sum : {$cond:[{ $eq: ['$questions.status',0]}, 1, 0]}},
      correct : { $sum : {$cond:[{ $eq: ['$questions.status',1]}, 1, 0]}},
      incorrect : { $sum : {$cond:[{ $eq: ['$questions.status',2]}, 1, 0]}},
      Total: { $sum: 1 }
    }
}

Check out the documentation $eq. $eq compares and returns true or false. So then your $sum cannot do anything with that result

MongoDB nested group by query


NODE.JS - Error: Route.get() requires a callback function but got a [object Undefined]

Question: Em meus roters crio:
    var express = require('express');
var router = express.Router();
var service = require('./../services/users');

router.get('/login', service.login);
router.get('/register', service.register);
router.get('/edit/:id', service.edit);

module.exports = router;

Onde tem o service:
exports.login = function(req, res) {
    res.render('login');
};

exports.register = function(req, res) {
    res.render('register');
};

mas quando rodo o npm start dá a mensagem de erro:
\node_modules\express\lib\router\route.js:202
        throw new Error(msg);
        ^

Error: Route.get() requires a callback function but got a [object Undefined]
    at Route.(anonymous function) [as get] (C:\mean\parking\node_modules\express\lib\router\route.js:202:15)
    at Function.proto.(anonymous function) [as get] (C:\mean\parking\node_modules\express\lib\router\index.js:510:19)
    at Object.<anonymous> (C:\mean\parking\routes\users.js:7:8)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\mean\parking\app.js:9:19)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! firstname.lastname@example.com start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the email@example.com start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Ramos\AppData\Roaming\npm-cache\_logs\2018-11-03T16_02_53_765Z-debug.log

** EDITADO - MEU APP.JS **
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var connection = require('./models');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cars = require('./routes/cars');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/cars', cars);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Meu Packarge:
{
  "name": "parking",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "bootstrap": "^4.1.3",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "~4.16.0",
    "express-session": "^1.15.6",
    "hbs": "~4.0.1",
    "http-errors": "~1.6.2",
    "mongoose": "^5.3.9",
    "morgan": "~1.9.0"
  }
}

O que posso estar fazendo de errado?
Answer: Troque
exports.login
exports.register

Por
module.exports.login
module.exports.register

Comment: Coloque o resto do código desse arquivo, outra coisa pode estar interferindo
Comment: Havia tentado isso de uma dúvida anteriror aqui mesmo do Stack, mas dá o mesmo erro.
Comment: Vou editar com mais detalhes.
Comment: Coloque todo o código do serviço de usuários! Verifique se o caminho do arquivo está correto e coloque o resultado de `console.log(service)`
Comment: Vi que estava faltando um exports.... erro meu. a sua resposta estava correnta @Guilherme.


javascript scope issue

Question: Code snippet as follows:
$(this).parents('td:first').next().find('option').customizeMenu('myMenu2');

This works,but :
var listener = function(){
 $(this).parents('td:first').next().find('option').customizeMenu('myMenu2');
};
listener();

is not working,why and how to fix it?
Answer: 'this' does not point to the same object when put in a function, it points to the current function (in your case 'listener'). Take it as a parameter instead, if that is an option (it depends on how you call your function).
var listener = function(obj){
 $(obj).parents('td:first').next().find('option').customizeMenu('myMenu2');
};

listener(this);

Answer: this is the function.  Try:
var listener = function(element){
  $(element).parents('td:first').next().find('option').customizeMenu('myMenu2');
};
listener(this);

javascript scope issue


Is there a way to show a Push Notification like an iOS banner?

Question: I want to show a Push Notification as a banner in my Cordova-based app. When the app is in background by default on Android 5.0.1 when a Push Notification is received it gets added to the notification area. But is there any way to show it as a banner like Facebook or Whatsapp notifications?
Comment: Thanks Idan for the edit
Comment: are you talking about in-app messaging?
Comment: No I am talking about the banner notification that is displayed when there is a new Facebook notification e.g when someone comments on any of your Facebook posts.
Comment: It seems like a native feature as it seems to be there for all my android applications but doesnt happen when I receive a push notification from my mobilefirst server.
Comment: Maybe a Android Lock Screen Widget? you would like to display the contents of the notification in your lock screen?
Comment: Can you attach a sample image of what you are trying to achieve?
Answer: There is library you can use TSnackBar in this place
Actually this is modified SnackBar found in support-design. It comes from top you can make it look like iOS banner notification.
Hope this will look and feel the same.
For Lollipop and above read this


How can I use an IF statement within a view to display a table depending on the result received?

Question: At the moment I have created two tables within my view, each table is different. One contains a summary of information and the other a detailed view. I have passed a variable in called 'Report Type'. If it is type 1, I would like it to display the summary table. If it is type 2, I would like it to display the detailed table. My question is, how would I go about doing this? My code is below, you can see both tables and also how the Report Type will be passed in. Thank you.
 <% Using Html.BeginForm("ReportCriteria", "Reports", Nothing, FormMethod.Post, New With {.id = "formReportCriteria"})%>

    <%: MasterPageHelpers.ContainerStart("wid1", "Results", 16)%>

        Date From: <%: Model.DateFrom%>

        Date To: <%: Model.DateTo%>

        Report Type: <%: Model.ReportType%>

                    Client
                    Tickets Created
                    Tickets Resolved

               <%
                   Dim oResult As Object
                   For Each oResult In Model.ReportResults
                       Response.Write("
")
                       Response.Write("" & oResult.ClientName & "	")
                       Response.Write("" & oResult.CreatedCount & "	")
                       Response.Write("" & oResult.ResolvedCount & "	")
                       Response.Write("
")
                   Next

                %>

                        Client
                        Classification
                        Tickets Created
                        Tickets Resolved

                <%
                    For Each oResult In Model.ReportResults
                        Response.Write("<tr")
                        Response.Write("" & oResult.ClientName & "	")
                        Response.Write("" & oResult.ClassificationDesc & "	")
                        Response.Write("" & oResult.CreatedCount & "	")
                        Response.Write("" & oResult.ResolvedCount & "	")
                    Next
                %>

    <% End Using%>

    <%: MasterPageHelpers.ContainerEnd%>

Answer: You need to use something along the following lines
@Code
   If Model.ReportType == 1 Then
      @

  Else
      @

  End If
End Code

See this post
Update - code for aspx as per your comments
  <% If Model.ReportType == 1 Then %>

 ...
  <% Else %>

 ...
  <% End If %>

Comment: I'm sorry, I don't quite understand. I already have called in my Model which allows me to use my passed in variables. I am using ASP. Sorry for not specifying that. What does this part mean? '@'. Sorry, I am new to this and find it difficult.
Comment: Sorry, I edited my earlier post as I noticed you had already passed the ReportType in as part of the model. Are you not using asp.net-mvc?  If so the syntax for your views will be razor.  The `@` is just showing you where to put the table. you need to put the @ before if you are combining html in code.  If you read through the article I have linked to it gives some good examples of the syntax you need to use in your views
Comment: Thanks for replying Pete, I am using ASPX, not Razor. Thanks for clearing it up. I'll take a look now thanks
Comment: Ah ok that link is for Razor, for aspx it is a bit simpler - you just need to do your if statement in a code block and then close the code block, I have edit my above
Comment: Thank you! It works, you have been a great help and very kind by keeping your answer updated. I've learnt something new today. The problem was that I did not realise that at the end of every statement there must me the %>. I thought that I could have one at the start of the IF and one at the End.
Comment: Ah, yeah you need to break out of the vb code block to start doing the html again - unless you do a vb way of writing the html (something like a response.write)


Como criar validação em campos diferentes no formulário ReactJS?

Question: Como faço a validação do formulário criado com ReactJS de acordo com o que usuário informa nos campos?
Exemplo:
<form>
  Escolha uma opção:

  <select name="tipo_requisicao" id="tipo_requisicao">
    <option value="Aumento">Aumento de Quadro</option>
    <option value="Substituição">Substituíção</option>
  </select>

  <textarea id="story" name="story" rows="5" cols="33"></textarea>
</form>

Eu estou usando o React-Hook-Form para os meus formulários em ReactJS, mas pode ser qualquer exemplo ou dica de como fazer isso, seja via YUP com Formik, ou outro.
Comment: [Assista o vídeo](https://react-hook-form.com/), veja a documentação, está tudo lá que você precisa saber.
Comment: Agradeço a dica, mas não tinha na documentação a forma de fazer isso. Consegui usando a Renderização Condicional do ReactJS.
Answer: Consegui fazer o que eu queria usando a Renderização Condicional .
Ficou assim:
<form>
  Escolha uma opção:

  <select name="tipo_requisicao" id="tipo_requisicao" ref={register({ required: true})}>
    <option value="Aumento">Aumento de Quadro</option>
    <option value="Substituição">Substituíção</option>
  </select>

  {tipo_requisicao === "Aumento" &&
    <textarea id="story" name="story" rows="5" cols="33" ref={register({ required: true})}></textarea>
  }
</form>

Devido o campo textarea ser renderizado apenas se o valor do campo tipo_requisicao for igual ao valor "Aumento", ele vai ser obrigatório apenas depois dele ser renderizado.


/admin/modules and Views Edit pages take forever to load

Question: I recently noticed that two specific sections of my site are taking forever to load, /admin/modules and /admin/structure/views/view/{any-view}/edit. Before I disabled the PHP max_execution_time (only temporarily), it kept timing out at 5 minutes.
Now that the timeout is disabled, the mysql server is going away. I've seen a lot of suggestions that max_allowed_packet should be 100M+, so I set it to 500M for some ridiculously high value. Last time I hit that page had to have been ~15-20 minutes ago, and it's still just sitting there.
The only thing I have done recently to it was moving a TON of images into sites/default/files from another web server. (~ 25Gb)
Does anyone know why admin/modules and the View Edit pages are taking forever? It's only those two sections. The public side of the site is fine, the other admin parts are fine, it's just those two places.
Answer: I found more information on this and have fixed it.
I guess that when Drupal has enabled modules that are missing from the filesystem (this happened as we're using Capistrano to deploy and I didn't sync the two sites correctly), it recursively keeps calling file_scan_directory() trying to find the missing modules, and that causes the site to timeout.
References:
Avoid re-scanning module directory when multiple modules are missing
Drupal 7 speed issue: file_scan_directory called > 1000 times per page load
Used XHProf to see what the call stack looked like over the course of loading /admin/modules and found over 5,000,000 function calls. By contrast, any other page had about 30,000 ~ 50,000 function calls.


application failed to find Chromium-edge browser

Question: I created a sample application to open a webpage on microsoft edge, by following below URL guidance.
https://learn.microsoft.com/en-us/microsoft-edge/webview2/gettingstarted/win32
I installed packages using NuGet packet manager as instructed. Everything worked fine on development machine.
Then I copied the exe of my sample application and the library "WebView2Loader.dll" into testing machine, which has Microsoft edge Version 83.0.478.50 (Official build) (64-bit). I got "ERROR_FILE_NOT_FOUND" error, means "Either it failed find the edge installation or version is Not compatible with SDK version". This error is on call CreateCoreWebView2Environment(), which supposed to find browser.
I am trying to find out why it is not working when it has higher version of than minimum required version. As per documentation, minimum required version of edge is 82 I have 83.0.478.50.
Let me know what I am missing on test environment? should I set any environment variables? I tried find online if there any environment variables required, couldn't find any.
Edit:
The current version Microsoft.web.webview2 SDK is 0.9.488. The testing box has edge version 83.0.478.50. I understand that I need to update my edge version on Testing machine.
Comment: I agree with the suggestion given by @Nic Champagne Williamson. Please check whether you are using the correct version of the MS Edge browser as per your SDK version. If the error still persists then please try to provide more information about your SDK version that may help to narrow down this issue.
Comment: @ Deepak-MSFT Edited my original post with details
Answer: What version of the SDK package are you using?
The way to find out the minimum version of the browser for a given SDK package is to look at the build numbers. For example:
SDK version 0.9.538 requires Edge n.n.538.n+
More details can be found here:
https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/versioning
Answer: CreateCoreWebView2Environment or CreateCoreWebView2EnvironmentWithOptions returns 'FILE_NOT_FIND'?
You need webview2 runtime. You should download WebView2 Runtime installer (Preview) and then run it.
Separate webview2 runtime is not necessary if there is a fully functional Microsoft edge(Chromium). But the stable channel Microsoft edge(Chromium) is not supported by now, as the webview2 is in its preview stage.


Rails: has_many with condition on self

Question: I'm trying to have a condition on a has_many clause referencing to the current model but I'm getting an error:
PG::Error: ERROR:  missing FROM-clause entry for table "badges"

This is my model:
class Badge < ActiveRecord::Base

  has_many :user_badges, :dependent => :destroy
  has_many :users, :through => :user_badges, :conditions => ["(user_badges.era_id =? and badges.seasonal =?)", GAME_CONFIG["current_era"], true, GAME_CONFIG["current_era"], false]
end

Can you point me in the right direction?
Thanks!
Answer: has_many :users, -> { select(badges.*, users.*).where("user_badges.era_id =? and badges.seasonal =?", GAME_CONFIG["current_era"], GAME_CONFIG["current_era"]) }, through: :user_badges

Comment: Thanks Rick but something seems missing before "-> { select(badges.", also I haven't seen before the "->" operation.  BTW on this app I'm still using Rails 2.3.
Comment: Oh jesus I didn't know it was Rails 2.3 `->` is a Rails 4 function [Check this post](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html) & search for "Customizing The Query"
Comment: I believe my syntax is correct for Rails 4, but since you're on Rails 2.3, it won't work. The key is to use the `select()` to help it load the badges data
Comment: Thanks Rick, I'll try this way!
Comment: I cannot find much about using select() in a Rails 2.3 association.  Do you think it is possible in someway?

Rails: has_many with condition on self


XenServer and VMware ESXi, scalability and budget considerations?

Question: In my organization, we are looking to virtualize servers (a dozen of Linux and Windows servers or so).
I am looking for a solution what would scale over the years and that would allow us maximum flexibility (i.e., moving virtual machines from one physical machine to another one when the old hardware becomes obsolete for example).
Which solution would you recommend in the short run and in the long run?
Answer: Citrix Xenserver Free is free.  Note that this is a commercialised version of Xen, with management tools around it. It is not the same as installing your favourite distribution and adding Xen to it.
Citrix Xenserver Free gives you central multi-host management, no limit on physical hosts, resource pooling, SAN (iSCSI, FC, SAS) and NAS (NFS) shared storage, live migration between hosts (if using shared storage), P2V and V2V conversion, and so on. And it's free - no limits whatsoever. You can start with a couple of servers, and scale up and out as you grow.
Once you start needing more complicated infrastructure, you can upgrade to one of the pay-for solutions, which gets you high availability, VM provisioning, workload management, etc. It's not free, however :)
Answer: My experience with ESXi has been great. I'm currently using ESXi 4 on Core 2 Quad and Core i7 machines. The free license seems to support only 1 x 6-core physical CPU so if you have dual Xeon's you may want to investigate other free solutions.
Positive:
ESXi seems to run everything. I've run 32-bit and 64-bit versions of Linux, FreeBSD, Windows and even Mac OS X tiger successfully.
Memory overcommitment is a very pain reducing feature. Without this feature you have to micro-manage each VM's memory footprint or else the machine would not start. Most of the time the actual memory in use is far below the physical threshold and you can fire up more and more VM's. ESXi seems to scale to about 4 VM's per core as long as they are not all busy.
Scaling up to the enterprise is as easy as adding an ESXi host to a vCenter Server cluster. Enterprise features of vSphere are currently unmatched by competitors, e.g. vCenter can run two VM's in virtual lockstep allowing instantaneous failover without missing a cycle if a host dies. Another new feature is the automatic powering down of hosts during idle times. The running VM's on these hosts are moved off to other hosts.
Negative:
We did not have good experiences with VMware support. We ended up solving most problems ourselves. Maybe it's just because they're new in South Africa.
You have to be careful with cheap hardware. It's certainly possible to get it to work on hardware not on the HCL list, but you'll have to do some homework. The most important to look out for is NIC, SATA and 64-bit guest support. For 64-bit guest support your host must have hardware virtualization. Note that installing ESXi on the hard drive does not guarantee that you're going to be able to create VM's on it.
Windows Vista and Server 2008 caches very aggressively. This does not work well with overcommitment of memory because Vista will use all memory assigned increasing memory pressure. This does not affect Microsoft's Hyper-V since Hyper-V does not offer overcommitment. Vista and Server 2008's behaviour will probably change in the next version of Hyper-V since overcommitment is on the road map for Hyper-V.
Microsoft support will probably require reproducing the error on physical hardware before they will look at it. The good thing is that those Microsoft products that are supported on Hyper-V are usually also supported on ESX.
Comment: Free ESXi supports dual quad core Xeon in my machines. (I'm not sure about more socket)
Comment: The free license I installed says 1 x 6-core CPU, which says to me that two or more processors are not free.
Comment: Aha, I think vSphere Client is somewhat misleading.
On my 1-CPU machine, it says "License: ESXi 4 Single Server, Licensed for 1 physical CPUs (1-6 cores per CPU)".
Using same License Code, on my 2-CPUs machine, it says "License: ESXi 4 Single Server, Licensed for 2 physical CPUs (1-6 cores per CPU)".
Comment: Thanks for the insight, I'll look into the licensing since I have a dual socket Xeon available.
Answer: Given the small number of servers you are considering managing I would go with the VMware vSphere Essentials bundle. At only $995 it would give you the ability to scale to 3 physical ESX/ESXi servers (which could easily support dozens of VMs depending on the HW you select) and provide you with a best-in-class central management solution (VirtualCenter now called vCenter) to manage all of your ESX hosts and virtual machines from a single console.
Should you decide you require high-availability and an integrated backup solution for your virtual machines you can upgrade to the Essentials Plus bundle with no re-installation (you just enter a new license key). It even gives you a simple migration path to VMware's Enteprise feature sets should your needs change in a few years.
Here's a link on VMware's site with more information about the SMB targeted bundles:
www.vmware.com/vmwarestore/vsphere_smbpurchaseoptions.html
Answer: I prefer Xen over VMware, as it's less of a black box and is, as a result, far more flexible.  That does result in it having a reputation for being harder to manage, but given the fun I'm seeing with trying to "manage" some ESX servers at work, I'm not sure that's all that justified.
The other nice thing about Xen is that the way you run VMs is quite similar to how you run VMs under KVM, so as that project matures, if you decide to move there the migration will be trivial.
Comment: Just a note that "XenServer" typically refers to Citrix Xenserver, which is a specific Xen distribution. It's not at all the same as installing your favourite OS and then running Xen on top of it.  Migration to KVM will not be trivial from a XenServer system, to the extent that you don't just change how you run the VM. You can, of course, still do a V2V migration to move your VM into your KVM system.
Comment: Also XenServer advanced editions are much much cheaper then VMWare :-)
Answer: Having run numerous virtualization farms, both for big business and personal use, I'm of one singular camp.  VMware.  The VMware tools support is currently unparalleled, between Lab Manager, LifeCycle manager, etc.  Citrix XenServer is coming up, but it has 10 years of makeup work to do to catch up with the mature VMware products.
And as a general rule I've found that even though you start at a dozen or so, you need to plan for 50.  Once you start virtualizing, you never stop.
At the moment, though the Citrix offerings are promising, VMware is your best choice for the near future.  If you're willing to live with the growing pains Citrix offers (immature tools support), I don't think you could lose with either open.
And both have Free-as-in-beer versions you can try-before-you-buy.
Answer: The one downside of Xen that we picked up on a few months ago was that Xen cannot overcommit memory, so you end up with less memory if you're trying to achieve high density.
VMWare can single instance some memory objects, which allows VMWare to overcommit memory to virtual machines. On the other hand, VMWare gives me the same annoying feeling the EMC and NetApp do -- all of those cool features require yet another license.
Clarification: You end up with less memory allocated per VM. We were looking at Xen in the context of desktop virtualization. The Citrix model is to allocate very small (256MB) Windows XP VMs, then use XenApp (aka Citrix Presentation Server) to actually deliver applications. VMWare will lie to the desktop and tell it that 1GB is available, and run applications in the VMs compute space
Answer: I currently run ESXi 3.5 U2.  I've been hesitant to go to 4.0 because the licensing appears to hint at a timeout for the free version, but isnt clear.  Plus when I installed version 3.5 U4 I got a purple screen due to a CPU versioning issue in my Opterons.  I run 4 quadcore opterons on ESXi FREE.  (16cores x 64bits).  With 16gb of physical memory I am running 24 VMs on the one box.  This is a self contained box with 20 SataII Hds.  The Largest array is a RAID60 of 1.8TB.  The servers are running great.  Mostly Ubuntu, 5 Solaris, and one Windows.  I use the "unsupported" SSH and SCP and VMCLI from Windows with perl scripting to run backups - very slow.  Working on a datastore to datastore copy process with hotswapping the drive for backup or secondary streaming via SCP as a faster process..
I tried Xen, and now wish I have given it a better chance as my Adaptec ICP needs on board Java powered application to manage the array.  ESXi does not support this, Xen does.
So, I must rely on the autofailover features of the controller and the hot spares for recovery.  Two days ago, the server took a power surge.  UPS fried.  The surge broke the array. I had to use BIOs tools to recover... Somehow this was successful...
Currently running a new set of backups for the VMs.
Still considering Hyper-V.  But Xen has moved up on my list and I plan to build a test server soon to try to migrate some VMs to.
Being that none of my projects are bringing anything in that comes close to paying the internet bill or datacenter fees, I would be hard pressed to put the kind of money VMWare wants out there..
But in answer to the question above about number of procs/cores.  Yes, 4 procs, 4 cores each. no problem.  But this is not vSphere 4 either and there did appear to be some licensign changes.
Comment: There's no time limit on the free ESXi licensing. What you do have is a 'full features' trial period that expires after 30/60 days. Once that's over, you're down onto the freebie version and lose some of the shiny extras.
Answer: I have 2 x 32 cores with 128 Go RAM on it and running on Citrix Xen. We enxperienced too muchs stability problems, licensing problems with version ugrade, no good support and multipath is working bad.
I'd like to go through another solution like vmware, but i wonder if virtualisation is enough mature for Production.
Answer: @Hans (since I can't comment yet) - When you get your license key from VMWare you can specify how many physical CPU sockets to get it for.  If you only said 1 when you obtained the key that may be why it doesn't see your other CPU.  I believe the limit is 2 sockets though.  I also have a dual quad-core box with ESXi 3.5 and that is what I had to do.
Answer: The question may be decided for you depending on what Linux distributions you are planning to run. If they are supported by XenServer I'd recommend that. You can start with the free version, which supports various shared storage types, live migration, snapshots, backup & restore, and work you way up as needed. It would probably cost less in the long run since VMware's prices are astronomical once you grow past the essentials. Want cool features in VMware? You're gonna pay for them! ;)
That being said, if your Linux distributions are not supported by XenServer I'd recommend VMware...non-Xen guests running in Xen perform terribly. VMware has been around the longest and is the most mature. As such it has the largest list of supported guest OSs.
If you're a Windows shop you might want to look at Hyper-V as well. Though it has a small list of supported Linux guests, they seem to run faster than in XenServer. If you run Hyper-V Server on a domain management is fairly easy, but I wouldn't recommend it if you aren't on a domain. It should run on just about any hardware with Windows drivers, and the upcoming R2 supports clustering and live migration even down to the free Hyper-V Server!
Answer: To be honest, both of these are very viable platforms over both short and long term, currently the two best technology leaders and the like.
We've gone with VMWare and we're very happy with it but at the end of the day it's subjective imho.


Amazon GameCircle on Generic Android Device?

Question: I've read Jeff's documentation inside and out. I'm still not able to log into GameCircle on my Samsung S3.
<code>(31429): Unable to initialise AmazonGamesClient - service not ready. Status=CANNOT_INITIALIZE
</code>
I have the right security profile, app signature, api_key.txt. Is there anything I'm missing? Is there a GameCircle app I need to download or something? How would GameCircle even know I have an Amazon account?
I did download the Amazon Underground App Store app but that hasn't made a difference.
Answer: After talking to the company that makes my engine (GameMaker Studio) it seems like they have bugs with the Amazon compile target.  So not my end afterall.
Answer: QUOTE "When testing your GameCircle integration, if CANNOT_INITIALIZE AmazonGamesStatus is returned to your callback function by initialize(), you may not have correctly registered the package name and signature of the game build. Review the steps in Setting Up Your GameCircle Configuration, and then try again."
https://developer.amazon.com/public/apis/engage/gamecircle/docs/initialize-android


Root CA's: Is there an agreed upon standard of CA's?

Question: I know that the Root CA bundles differ between OS/browsers/applications. However, it seems like Verisign is always included.
How did this become the case? Is there some sort of standard?
I'm just curious since SSL has become a big topic lately at my place of work.
Answer: There is no standard set of certificate authorities, and the list of trusted authorities may vary from one application to another.  Linux Weekly News had an interesting article about this last August.
Answer: Verisign has a very large customer base and has been around for a long time.   Omitting it would cause problems for a large percentage sites.  This would be a problem for users, and consequently would cause them to change to different tool.
Most tools allow you to check the trust chain so you can verify what your experience would be like if Verisign was not in the CA bundle.  I sometime clean the bundle of CAs that I am unlikely to trust, but always keep Verisign.
Some tools such a VPNs allow users to specify their own trusted authorities.  With a private CA this can greatly simplify trust relationships.


Question related to Polya urn model

Question: Just in case I will remind what is called Polya urn: Suppose you have an urn containing one red and one blue ball. You draw one at random. Then if the ball is red, put it back in the urn with an additional red ball, otherwise put it back and add a blue ball.
Now denote by $N$ number of balls drawn before first appearance of a blue one. What will be $\operatorname{E}(N+2)^{-1}$?
I can find a mean for the $N$ itself just by
$$\operatorname{E}(N) = \left(\frac 1 2 \cdot\frac 1 3 \right)\cdot1+ \left( \frac 1 2 \cdot \frac 2 3 \cdot\frac 1 4  \right)\cdot2+\cdots = \sum_{i=1}^\infty \left( \prod_{k=1}^i \frac{k}{k+1}\cdot\frac{1}{i+2}\right)\cdot i$$
but get stuck what to do with $\operatorname{E}(N+2)^{-1}$. Can anyone explain it?
Answer: Applying the martingale optimal stopping theorem one can show that $\mathbb{E}(T+2)^{-1} = \frac{1}{4}$ (here $T$ stands for the number of balls drawn until the first blue ball appears)
Theorem (Optimal Stopping theorem)
Let $Y_{n}$ be a martingale adapted to filtration $\{ \mathcal{F_{n}} \}$ and let $T$ be the stopping time. Then if
(1) $Y_{n}$ is uniformly integrable.
(2) $\mathbb{P}(T < \infty) = 1$
(3) $\mathbb{E}(|Y_{T}|) < \infty$
then $\mathbb{E}(Y_{n}) = \mathbb{E}(Y_{0})$
So, since $Y_{n}$ is uniformly integrable it suffcies to check the second condition, indeed $$P(T < \infty) = \frac{1}{2}  \cdot \frac{2}{3} \ldots \cdot \frac{n-1}{n} = \frac{1}{n} \to 0$$ as $n \to \infty$.
By the optimal stopping theorem, which is to say that $$\mathbb{E}(\frac{T}{T+2}) = \frac{1}{2}$$ the result follows.
Answer: Let $X_k$ be the number of red balls in the $k$th trial, so that $X_k = 0 \text{ or } 1.$
Here's a useful lemma:

Let $R$ be uniformly distributed in the interval $(0,1)$ and let the conditional distribution of $Y_k$, for $k=1,2,3,\ldots$ be given by
  $$
\Pr(Y_k = 1\mid R) = R \text{ and } \Pr(Y_k = 0 \mid R) = 1-R
$$
  and $Y_1,Y_2,Y_3,\ldots$ are conditionally independent given $R.$
  Then the marginal (i.e. "unconditional") distribution of the sequence $Y_1,Y_2,Y_3,\ldots$ is the same as that of $X_1,X_2,X_3,\ldots\ $.

Thus we can regard $N$ as the number of indices $k$ for which $Y_k=1$ before the first index $k$ for which $Y_k=0.$ Thus we have
\begin{align}
\Pr(N=n) & = \operatorname{E}(\Pr(N=n \mid R)) = \operatorname{E}( R^n(1-R) ) = \int_0^1 r^n (1-r)\,dr = \int_0^1 (r^n - r^{n+1})\,dr.
\end{align}
Then the expected value:
\begin{align}
\operatorname{E} \left( \frac 1 {N+2} \right) & = \sum_{n=0}^\infty \frac 1 {n+2} \Pr(N=n) = \sum_{n=0}^\infty \frac 1 {n+2} \left( \frac 1 {n+1} - \frac 1 {n+2} \right) \\[10pt]
& = \sum_{n=0}^\infty \left( \frac 1 {(n+1)(n+2)} - \frac 1 {(n+2)^2} \right) \\[10pt]
& = \sum_{n=0}^\infty \left( \frac 1 {n+1} - \frac 1 {n+2} \right) - \sum_{n=0}^\infty \frac 1 {(n+2)^2} \text{ (partial fractions)} \\[10pt]
& = 1 - \left( \frac {\pi^2} 6 - 1 \right) = \cdots
\end{align}
The first term, $1,$ comes from telesciping. The fraction $\pi^2/6$ is not easy to derive from scratch but is widely known.
And you still have the problem of proving the lemma.
Answer: Let $N$ represents the first time that a white ball being drawn, we have
$$\{N=n\}=\left\{R_0=1, R_1=2,R_2=3,\dots,R_{n-1}=n,R_{n}=n\right\}$$
which is finite. So, $N$ is a stopping time. Then,
\begin{align*}
            E\left[\frac{1}{N+2}\right]&=\sum_{n=1}^{\infty}\left(\frac{1}{n+2}\right)P(N=n)\\
            &=\sum_{n=1}^{\infty}\left(\frac{1}{n+2}\right)\left(\frac{1}{n(n+1)}\right)\\
            &=\sum_{n=1}^{\infty}\frac{1}{2}\left(\frac{1}{n+1}\right)\left(\frac{1}{n}-\frac{1}{n+2}\right)\\
            &=\frac{1}{4}
        \end{align*}

Question related to Polya urn model


R: Automatically Creating Graphs from Dataframes

Question: I am working with the R programming language.
I have the following data set (route_1):
 route_1

  id      long      lat
1  1 -74.56048 40.07051
3  3 -72.44129 41.71506
4  4 -77.53908 41.55434
2  2 -74.23018 40.12929
6  6 -78.68685 42.35981
5  5 -79.26506 43.22408

Based on this data, I want to make a directed network graph in which each row is only linked to the row that comes right after. Using the "igraph" library, I was able to do this manually:
library(igraph)

my_data <- data.frame(

"node_a" = c("1", "3", "4", "2", "6"),
"node_b" = c("3", "4", "2", "6", "5")
)

graph <- graph.data.frame(my_data, directed=TRUE)
graph <- simplify(graph)

plot(graph)

My Question: Is it possible to make this above network graph directly using the "route_1" dataset, and without manually creating a new data set that contains information on which node is connected to what node?
Thanks!
Answer: Is the dataset always going to be ordered correctly, so the plot will go from row 1->2->3 etc in a single line? If so, we can make the node info dataframe by simply subsetting the ID column. If we put the steps in a function, it becomes a simple 1-liner:
plot_nodes <- function(x) {
    id = x$id
    a = id[1:length(id)-1]
    b = id[2:length(id)]
    graph.data.frame(data.frame(a,b), directed=TRUE)
}

graph <- plot_nodes(route_1)
plot(simplify(graph))


Problem on the Fitting ideal

Question: I am trying to solve Dummit Foote, Abstract Algebra, 15.1 Exercise 40. It reads,
Suppose $R$ and $S$ are commutative rings, $\phi:R \to S$ is a ring homomorphism, $M$ is a finitely generated $R$-module, and $M'=S\otimes_R M$ is the $S$-module obtained by extending scalars from $R$ to $S$. Prove that the Fitting ideal $\mathcal{F}_S(M')$ for $M'$ over $S$ is the extension to $S$ of the Fitting ideal $\mathcal{F}_R(M)$ for $M$ over $R$.
Below is my attempt: The previous exercise implies that the Fitting ideal is actually the image of $\wedge^n\ker f$ in to $R$ where $f$ is a surjection $f:R^n\to M$. In other word, I have a surjection $\wedge^n\ker f\to \mathcal F_R(M)$. Tensoring $S$, since tensoring is right exact functor, we have the following commutative diagram:
$\require{AMScd}$
$$
\begin{CD}
\wedge^n \ker f @>>> \mathcal{F}_R(M) @>>> 0 \\
@VVV @VVV \\
S\otimes \wedge^n \ker f @>>> S\otimes \mathcal{F}_R(M) @>>> 0 \\
@VVV @VVV \\
\wedge^n(\ker f_S)  @>>> \mathcal{F}_S(M') @>>> 0
\end{CD}
$$
where $f_s$ is $f\otimes \textrm{Id}_S: S\otimes R^n=S^n \to S\otimes M = M'$.
Now I am stuck here. I don't see why $S\otimes \mathcal{F}_R(M) \to \mathcal{F}_S(M')$ should be an isomorphism.
Thanks in advance.
Answer: I don't know this is right or wrong, but anyway I dealt with it myself.
$S$ is an $R$-algebra in which the multiplication $r\cdot s$ for $r\in R$ and $s\in S$ is defined to be
$$
r\cdot s := \phi(r)s.
$$
Our goal is to prove that $\mathcal F_R(M) S = \mathcal F_S(M')$. First we prove that $\mathcal F_R(M)S \subseteq \mathcal F_S(M')$. By the definition, the generators of $\mathcal{F}_R(M)$ are of the form
$$
\det\begin{pmatrix}
r_{11} & r_{12} & \cdots & r_{1n} \\
r_{21} & r_{22} & \cdots & r_{2n} \\
\vdots & \vdots & \ddots & \vdots \\
r_{n1} & r_{n2} & \cdots & r_{nn}
\end{pmatrix}
$$
where $r_{i1}m_1 + r_{i2} m_2 + \cdots + r_{in} m_n = 0$. Hence the extension of $\mathcal F_R(M)$ to $S$ is generated by the elements of the form
$$
\phi \det\begin{pmatrix}
r_{11} & r_{12} & \cdots & r_{1n} \\
r_{21} & r_{22} & \cdots & r_{2n} \\
\vdots & \vdots & \ddots & \vdots \\
r_{n1} & r_{n2} & \cdots & r_{nn}
\end{pmatrix}.
$$
Since $\phi$ is the ring homomorphism, and the determinant is just a polynomial of $n\times n$ variables, $\phi$ and $\det$ commutes. Thus,
$$
\phi \det\begin{pmatrix}
r_{11} & r_{12} & \cdots & r_{1n} \\
r_{21} & r_{22} & \cdots & r_{2n} \\
\vdots & \vdots & \ddots & \vdots \\
r_{n1} & r_{n2} & \cdots & r_{nn}
\end{pmatrix}=\det\begin{pmatrix}
\phi(r_{11}) & \phi(r_{12}) & \cdots & \phi(r_{1n}) \\
\phi(r_{21}) & \phi(r_{22}) & \cdots & \phi(r_{2n}) \\
\vdots & \vdots & \ddots & \vdots \\
\phi(r_{n1}) & \phi(r_{n2}) & \cdots & \phi(r_{nn})
\end{pmatrix}
$$
However, the right hand side is an element of $\mathcal F_S(M')$ since
$$
\phi(r_{i1})1\otimes m_1+\phi(r_{i2})1\otimes m_2+\cdots+\phi(r_{in})1\otimes m_n = 1\otimes (r_{i1}m_1+ \cdots r_{in}m_n) = 0
$$
for all $i=1,2,\cdots,n$. Remind that since $R^n \to M$ is a surjection, and tensoring is right exact, so $S^n \to M'$ is still surjection. Thus $1\otimes m_1, \cdots , 1\otimes m_n$ generate $M'$. Hence we have the natural injection
$$
\mathcal{F}_R(M)S \to \mathcal{F}_S(M').
$$
Now our goal is to prove that this is actually a surjection. There are two preceding lemmas.
(i) $f:A\to B$ and $g:C\to D$ are surjections, then so is $f\wedge g:A\wedge C \to B\wedge D$. This is obvious since for every $b\wedge d\in B\wedge D$, there are $a\in A$ and $c\in C$ such that $f(a)=b$, $g(c)=d$, so $f\wedge g (a\wedge c) = b\wedge d$. Hence by the corollary, when $f:M \to N$ is a surjection between two $R$-modules, then so is $\det f: \wedge^n M \to \wedge^n N$ for every $n=1,2,\cdots$.
(ii) Suppose $L$ is an $R$-module and $S$ is an $R$-algebra. Then there is a cannonical $S$-module isomorphism
$$
\bigwedge_S^n ( S\otimes L) \cong S \otimes \left(\bigwedge^n_R L\right).
$$
The isomorphism is defined as
$$
(s_1\otimes_R a_1) \wedge_S \cdots \wedge_S (s_n \otimes a_n) \mapsto s_1 \cdots s_n \otimes_R a_1 \wedge_R \cdots \wedge_R a_n
$$
$$
(s\otimes_R a_1) \wedge_S (1\otimes_R a_2) \wedge_S \cdots \wedge_S (1\otimes a_n) \leftarrow s\otimes a_1 \wedge_R \cdots \wedge_R a_n
$$
It is obvious that those two maps are homormophisms, and they are inverse to each other. This is actually just the commutativity of the tensor product.
Now we are ready to prove the original problem. First, we let $f_S:S^n \to M'$ the surjection given by tensoring $S$ to the surjection $f:R^n \to M$. Then we have the following commutative diagram

The first horizontal line is given by tensoring $S$ to the exact sequence
$$
0 \to \textrm{Ker} f \to R^n \to M \to 0.
$$
The second horizontal sequence is obviously exact. For every $x\in \textrm{Ker} f_S$, it is actually in $S^n$, and is mapped to $0$ by $S^n \to M'$. Since the first horizontal sequence is exact, there should be $y\in S\otimes \textrm{Ker} f$ such that $y$ is mapped to $x$ by $S\otimes \textrm{Ker}f \to S^n$. This means $S\otimes \textrm{Ker}f \to \textrm{Ker}f_S$ is the surjection. By the first lemma, the following homomorphism
$$
\bigwedge^n S\otimes \textrm{Ker}f \to \bigwedge^n \textrm{Ker}f_S
$$
is surjection. And by the second lemma, $\bigwedge^n S\otimes \textrm{Ker}f$ is isomorphic to $S\otimes \bigwedge^n(\textrm{Ker}f)$. By the result of the previous exercise,
$$
\bigwedge^n(\textrm{Ker}f) \to \mathcal F_R(M)
$$
is a surjection. By tensoring $S$, we have another homomorphism
$$
S\otimes \bigwedge^n(\textrm{Ker}f) \to S\otimes \mathcal F_R(M).
$$
Also, there is a canonical homomorphism
$$
S\otimes \mathcal F_R(M) \to \mathcal F_R(M)S.
$$
Now we have the following diagram

If the diagram commutes, then $\mathcal F_R(M)S \to \mathcal{F}_S (M')$ is the surjection, so the proof ends. It is enough to observe how the element is mapped in the diagram to show that the diagram actually commutes. For every $s_1,\cdots, s_n \in S$ and $r_1,\cdots, r_n \in \mathrm{Ker}f$, let $s=s_1\cdots s_n$. First, along
$$
\bigwedge^n (S\otimes \mathrm{Ker} f) \to S\otimes \bigwedge^n \mathrm{Ker} f \to S\otimes \mathcal F_R(M) \to \mathcal F_R(M)S \to \mathcal{F}_S (M')
$$
we have
\begin{align*}
    (s_1\otimes r_1)\wedge \cdots \wedge (s_n\otimes r_n) &\mapsto s \otimes r_1 \wedge \cdots \wedge r_n  \\
    &\mapsto s\otimes \det(r_1 \wedge \cdots \wedge r_n) \\
    &\mapsto \det(r_1 \wedge \cdots \wedge r_n)\cdot s = \phi(\det(r_1 \wedge \cdots \wedge r_n)) s
\end{align*}
Next, along
$$
\bigwedge^n (S\otimes \mathrm{Ker} f) \to \bigwedge^n \mathrm{Ker} f_S \to \mathcal{F}_S (M')
$$
we have
\begin{align*}
    (s_1\otimes r_1)\wedge \cdots \wedge (s_n\otimes r_n) &\mapsto s\phi(r_1) \wedge \cdots \wedge \phi(r_n) \\
    &\mapsto \det(s\phi(r_1) \wedge \cdots \wedge \phi(r_n)) = \det(\phi(r_1) \wedge \cdots \wedge \phi(r_n))s
\end{align*}
Hence the diagram commutes decause $\det$ and $\phi$ commutes.

Problem on the Fitting ideal