Vb picture box (n)

Question:  Dim x As String
    Dim zombies As List(Of Zombie)
    Dim n As Integer
    Dim boxes As List(Of PictureBox)

    x = diceRoll(4)
    RichTextBox2.Text &= "You rolled a " + x & vbCrLf
    RichTextBox1.Text &= "There are " + x + " Zombies attacking" & vbCrLf
    zombies = makeZombies(Val(x), 4)' x zom w/ 4 max health

    n = 0

    boxes.Add(PictureBox1)
    boxes.Add(PictureBox2)
    boxes.Add(PictureBox3)
    boxes.Add(PictureBox4)

    For i = 1 To Val(x)
        n = n + 1
        boxes(n).Image = My.Resources.zombie

    Next

    fight(zombies)
End Sub

I have 4 picture boxes, I am trying to get it so when a number is rolled on a dice ( diceroll(4) )  depending on what your rolled the image of the picture boxes will change. If a 3 is rolled 3 out of the 4 picture boxes will change to the picture, other wise they are clear pictureboxes. The image is in my resources called zombie.png.
Can anyone help ?
Comment: does `diceRoll()` return a string? That seems like an odd choice... but if not, why do you keep using `Val()`?
Comment: joel the diceroll is a function which just rolls a dice., val Is used to turn x into a value it would not work without it.
Comment: If you don't even know if it returns a String or an Integer, you need to find that out. You will continue to struggle as a programmer until you develop of sense for the **types** resulting from each variable, value, and expression you're dealing with in your code. This especially holds in a strongly-typed platform like .Net, but will even trip you up in dynamically typed platforms like javascript or python.
Answer: I can see a couple problems. One is array/List indices start at 0 rather than 1, but the n variable increments to 1 before it is used as an index for the first time. Also, you don't initialize the boxes collection... it's a null reference/Nothing when you try to use it.
This code fixes those issues and does some other cleanup:
Dim x As Integer = diceRoll(4) 'If this function returns a string, fix it to use Integer instead
Dim zombies As List(Of Zombie) = makeZombies(x, 4)' x zom w/ 4 max health

Dim boxes As New List(Of PictureBox) From {PictureBox1, PictureBox2, PictureBox3, PictureBox4}
boxes = boxes.Take(x).ToList()

RichTextBox2.Text &= "You rolled a " + x.ToString() & vbCrLf
RichTextBox1.Text &= "There are " + x.ToString() + " Zombies attacking" & vbCrLf

For Each box As PictureBox in boxes
    box.Image = My.Resources.zombie
Next

fight(zombies)

Vb picture box (n)


Lista Encadeada em Linguagem C imprimir lista inversa

Question: Eu preciso criar uma lista que receba n nós e imprima esses nós normalmente e em ordem inversa, ou seja, 1,2,3 para 3,2,1. Sou novo na área de programação e seria muito grato pela ajuda. Estou usando o Dev C ++. Eu não estou conseguindo inverter os números.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

struct no       //cria uma estrutura do tipo no
{
    int num;
    struct no *prox;
    struct no *ant;
    } *node;

int main (){
    setlocale (LC_ALL, "Portuguese");

    void criar_lista (int n);   //mostra que foi criado uma função criar_lista
    void imprimir_lista ();     //mostra que foi criado uma função imprimir_lista
    void imprimir_lista_inverso ();

    int n;                      //declaração de variável n

    printf ("Quantidade de nós: ");
    scanf ("%d", &n);
    criar_lista (n);            //chama a função criar_lista
    printf ("\nDados inseridos na lista: \n");
    imprimir_lista ();          //chama a função imprimir_lista
    printf ("\nDados inversos: \n");
    imprimir_lista_inverso ();
    return 0;
}

void criar_lista (int n)        //função criar lista que puxa um valor do tipo inteiro 'n'
{
    struct no *fim_no, *aux;    //declaração da estrutura no com ponteiro para fim_no e aux
    int num, i;
    node = (struct no *) malloc (sizeof (struct no));
    if (node == NULL)
    {
        printf ("Erro no 'if'em criar lista !!");
    }
    else
    {
        node -> num = num;      //estrutura node na variável num recebe o valor de num
        node -> ant = NULL;     //estrutura node na variável ant recebe o valor de NULL
        node -> prox = NULL;    //estrutura node na variável prox recebe o valor de NULL
    }
    printf ("Digite dados para nó 1: ");
        scanf (" %d", &num);
        node -> num = num;      //estrutura node na variável num recebe o valor de num
        node -> ant = aux;      //estrutura node na variável prox recebe o valor de NULL
        node -> prox = NULL;    //estrutura node na variável prox recebe o valor de NULL
        aux = node;

    for (i = 2; i <= n; ++i)
    {
        fim_no = (struct no *) malloc (sizeof (struct no));
        if (fim_no == NULL)
        {
            printf ("Erro no 'for' em criar lista ");
            break;
        }
        else
        {
            printf ("Digite dados para nó %d: ", i);
            scanf (" %d", &num);

            fim_no -> num = num;
            fim_no -> prox = NULL;
            aux -> prox = fim_no;
            aux = aux -> prox;
        }
    }
}

void imprimir_lista ()
{
    struct no *aux;
    int ant, prox;
    if (node == NULL)
    {
        printf ("Erro no 'if' de imprimir lista");
    }
    else
    {
        aux = node;
        while (aux != NULL)
        {
            printf ("Dado = %d\n", aux -> num);
            aux = aux -> prox;
        }
    }
}

void imprimir_lista_inverso ()
{
    struct no *aux;
    int ant, prox;
    if (node == NULL)
    {
        printf ("Erro no 'if' de imprimir lista");
    }
    else
    {
        aux = node;
        while (aux != NULL)
        {

            printf ("Dado = %d\n", aux -> num);
            aux = aux -> prox;
        }
    }
}

Desde já agradeço pelo ajuda.
Comment: Como é uma lista duplamente encadeada é só percorrê-la de trás para a frente. Creio que seria muito útil você ter ponteiros tanto para o primeiro quanto para o último nó da lista.
Answer:
Alterei um pouco o exemplo original porque eu tinha postado errado e
para mostrar a falta que faz Lista não ser uma estrutura completa,
mas apenas um nó.
Vou deixar um exemplo ao final com seu código e que cria de fato uma
lista com alguns elementos e mostra na tela. Mas acho que deve incorporar o
que estou escrevendo a seguir antes de continuar com seu programa - @arfneto

struct no       //cria uma estrutura do tipo no
{
    int num;
    struct no *prox;
    struct no *ant;
    } *node;

Escreva seu programa em torno dos dados. Sempre. E tudo fica mais simples.
Entenda que uma lista ligada NÃO é um nó e sempre que programar uma lista como se fosse um nó vai ter mais trabalho sem necessidade.
Imagine essa estrutura:
typedef struct
{
    unsigned        size;
    unsigned        limit;
    Node*           inicio;
    Node*           fim;

}   Lista;

Ao declarar algo como Lista já vai ter um tamanho, um limite, um ponteiro para o fim e outro para o início. E assim mesmo que tenha 25 listas no mesmo programa cada uma vai ter seus valores preservados DENTRO da estrutura. Esse é o conceito de encapsulamento.
Entenda que os protótipos devem ficar FORA de main()
E quem sabe em um arquivo de cabeçalhos --- o tal .h por exemplo --- separado. Do modo como escreveu está errado.
É legal usar comentários em seu código, mas talvez pudesse evitar esses assim óbvios:
void criar_lista(int n);   //mostra que foi criado uma função criar_lista
void imprimir_lista();     //mostra que foi criado uma função imprimir_lista
void imprimir_lista_inverso();

E como inverter uma lista?
É você que está criando a lista.
Você pode inserir sempre no início, sempre no fim ou em alguma ordem.
Vamos imaginar que vai inserir sempre no início:
Então ao percorrer a lista para imprimir os valores vão aparecer em ordem cronológica inversa, claro: o último inserido será o primeiro.
Quando você listar o último cara, ele estará apontando para NULL. E esse será o ponteiro para o fim da lista. Acho que já imaginou que deveria ter um ponteiro atualizado para o fim da lista, certo? E então fazer exatamente a mesma coisa que fez para listar os elementos, mas apenas mostre o último elemento, aponte para o anterior dele e continue até ele não ter um anterior e terá listado os elementos na ordem inversa, a ordem de inserção.
Essas classificações são genericamente chamadas de LIFO e FIFO na literatura, de Last In First Out e First In First Out.
criar_lista()
Criar lista deveria retornar o endereço de uma Lista. Evite retornar void: em geral é um desperdício e muitas vezes um erro. Nesse caso aqui os dois. mas o que importa é o erro: o endereço de sua nova lista vai morrer lá dentro da função.
Faça o simples e crie uma função também que insere um valor na lista e retorna o endereço dela, pelo mesmo motivo. Algo simples como
    Lista*    insere( int item, node lista);

Não precisa de uma função para criar a lista
evite criar tipos ponteiros
Isso é muito problemático e sempre vai cair na sua cabeça. No seu exemplo, qual o tipo de node? struct no*. Para que isso? Como vai saber ao ler o programa daqui um mês?
Talvez deva usar uma convenção, como mostrei no exemplo, escrevendo os tipos que define com uma inicial maiúscula, ou todas maiúsculas, ou um underline na frente, no fim, um prefixo, um sufixo, qualquer coisa mas alguma.
Entenda que só declara variáveis, então se um nó da lista é Node um ponteiro para ele SEMPRE é Node*, um ponteiro para um ponteiro para ele é Node** e por aí vai. O asterisco fala por si só em C. No seu exemplo node não. Vai ter que se lembrar sempre de que node é um ponteiro e isso não é bom: é ruim. Bem ruim.
Não leia nada do teclado
Enquanto seu programa não estiver pronto em termos de lista não leia nada do teclado. Só vai te atrasar e não será pouco. Além de dificultar a repetição de testes com os mesmos dados.
Leia sempre de arquivo. É muito mais fácil. Pode digitar arquivos no próprio IDE. Ler do teclado é um inferno e só vai te atrasar...
E ante de ler de um arquivo use constantes em seu programa e teste um pouco.
Um exemplo com seu código
Como te disse, acho que deve escrever melhor a estrutura lista.
Considere que não precisa de fato de uma rotina para criar a lista. E que imprimir_lista() deve ser a primeira rotina a rodar em seu programa. Veja essa versão de main()
int main(void)
{
    setlocale(LC_ALL, "Portuguese");

    Node* teste = NULL;
    imprimir_lista(teste);

    for (int i = 1; i <= 10; i += 1)
        teste = inserir_no_inicio(i, teste);

    Node* ultimo = imprimir_lista(teste);
    Node* primeiro = imprimir_lista_inverso(ultimo);
    // so para fechar o circulo
    ultimo = imprimir_lista(primeiro);

    return 0;
}

Talvez concorde que é muito mais simples de ler. E testar. Já que seus dados são apenas um int. Chamar imprimir_lista() no início é um teste óbvio porque tem que funcionar com o ponteiro NULL.
Depois um for insere uns elementos e imprimir_lista() deve mostrar os mesmos
Como eu disse no início, essa não é uma boa representação de uma lista. O simples é ter uma estrutura com metadados para controlar a lista, como te mostrei. É muito mais fácil.
De todo modo, eu alterei as rotinas que imprimem a lista para serem mais cooperativas: você pode chamar as rotinas a partir de qualquer ponto da lista, e imprimir_lista() imprime até o fim e retorna o endereço do último. E imprimir_lista_inverso() imprime da posiçào até o começo, mas retorna o endereço do primeiro.
Assim pode chamar uma depois da outra e o círculo se completa :D
mostra o esperado
imprimir_lista()
imprimir_lista()
Dado = 10
Dado = 9
Dado = 8
Dado = 7
Dado = 6
Dado = 5
Dado = 4
Dado = 3
Dado = 2
Dado = 1
imprimir_lista_inverso()
Dado = 1
Dado = 2
Dado = 3
Dado = 4
Dado = 5
Dado = 6
Dado = 7
Dado = 8
Dado = 9
Dado = 10
imprimir_lista()
Dado = 10
Dado = 9
Dado = 8
Dado = 7
Dado = 6
Dado = 5
Dado = 4
Dado = 3
Dado = 2
Dado = 1

O programa, quase o mesmo
Rode e compare o programa. Sugiro colocar o ponteiro para o fim e fazer todas as mudanças como listei. Se tiver mais dúvidas escreva e eu completo o exemplo com algo...
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

struct no
{
    int num;
    struct no* prox;
    struct no* ant;

} *node;

typedef struct no Node;

typedef struct
{
    unsigned        size;
    unsigned        limit;
    Node* inicio;
    Node* fim;

}   Lista;

Node*       criar_lista(int n);   //mostra que foi criado uma função criar_lista
Node*       imprimir_lista(Node*);
Node*       imprimir_lista_inverso(Node*);
Node*       inserir_no_inicio(int, Node*);

int main(void)
{
    setlocale(LC_ALL, "Portuguese");

    Node* teste = NULL;
    imprimir_lista(teste);

    for (int i = 1; i <= 10; i += 1)
        teste = inserir_no_inicio(i, teste);

    Node* ultimo = imprimir_lista(teste);
    Node* primeiro = imprimir_lista_inverso(ultimo);
    // so para fechar o circulo
    ultimo = imprimir_lista(primeiro);

    return 0;
}

Node* criar_lista(int n)        //função criar lista que puxa um valor do tipo inteiro 'n'
{
    /*
    Node* novo = (Node*) malloc ( sizeof(Node) );
    if (node == NULL) return NULL;
    node->num = num;
        node->ant = NULL;     //estrutura node na variável ant recebe o valor de NULL
        node->prox = NULL;    //estrutura node na variável prox recebe o valor de NULL
    }
    printf("Digite dados para nó 1: ");
    scanf(" %d", &num);
    node->num = num;      //estrutura node na variável num recebe o valor de num
    node->ant = aux;      //estrutura node na variável prox recebe o valor de NULL
    node->prox = NULL;    //estrutura node na variável prox recebe o valor de NULL
    aux = node;

    for (i = 2; i <= n; ++i)
    {
        fim_no = (struct no*)malloc(sizeof(struct no));
        if (fim_no == NULL)
        {
            printf("Erro no 'for' em criar lista ");
            break;
        }
        else
        {
            printf("Digite dados para nó %d: ", i);
            scanf(" %d", &num);

            fim_no->num = num;
            fim_no->prox = NULL;
            aux->prox = fim_no;
            aux = aux->prox;
        }
    }
    */
    return NULL;
};

Node*       imprimir_lista(Node* L)
{
    // imprime a lista a partir de L
    // e retorna o endereco do ultimo cara
    printf("imprimir_lista()\n");
    if (L == NULL) return NULL;
    Node* p = L;
    Node* ultimo = NULL;
    while (p != NULL)
    {
        printf("Dado = %d\n", p->num);
        ultimo = p;
        p = p->prox;
    };
    return ultimo; // retorna o total de itens
};

Node*       imprimir_lista_inverso(Node* L)
{
    // imprime a lista a partir de L, para tras,
    // e retorna o endereco do primeiro cara
    printf("imprimir_lista_inverso()\n");
    if (L == NULL) return NULL;
    Node* p = L;
    Node* primeiro = NULL;
    while (p != NULL)
    {
        printf("Dado = %d\n", p->num);
        primeiro = p;
        p = p->ant;
    };
    return primeiro; // retorna o total de itens
}

Node* inserir_no_inicio(int n, Node* L)
{
    // a lista existe, mas pode estar vazia
    // vai inserir sempre no inicio nesse exemplo
    Node* novo = (Node*)malloc(sizeof(Node));
    novo->num = n;
    novo->ant = NULL; // vai ficar no inicio
    novo->prox = L; // vai apontar para o que estava na frente
    if (L != NULL) L->ant = novo;
    return novo;
};

// fim

Comment: Tentei rodar esse código, mas ele dá erro no imprimir_lista (teste), sabe me dizer por que?
Comment: @RenanPereira me desculpe: eu tinha escrito usando a estrutura `Lista` como te mostrei, mas aí achei que eu devia postar um exemplo usando sua própria estrutura e esqueci de passar o parâmetro para `imprime_lista()` e por isso não rodava. Digitei direto no SO :( my bad. Agora aproveitei para mudar as rotinas de impressão para você ver como faz falta não ter os ponteiros atualizados DENTRO da estrutura. Desculpe.
Answer: Se você utilizar recursividade seu código pode ficar bem mais simples.
Sugiro as seguinte alterações:
1 - no cabeçalho:
 void imprimir_lista_inverso (struct no*);

2 - na chamada:
imprimir_lista_inverso (node);

3 - no corpo da função:
void imprimir_lista_inverso (struct no *aux)
{
    if(aux == NULL)
        return;
    imprimir_lista_inverso(aux->prox);
    printf ("Dado = %d\n", aux -> num);
}

Aqui segue uma breve explicação da função recursiva: A função é chamada primeiramente com o primeiro elemento da lista, é feita a verificação se esse elemento é NULL (que indica o final da recursão). Se não for o último elemento, primeiramente a função é chamada para o elemento seguinte e só depois que retornar dessa chamada é que será impresso o dado.
Ou seja, a primeira impressão de dado só vai ocorrer depois que a recursão encerrar (quando o critério do IF for verdadeiro).
Answer: Na realidade é sobre outra listagem. Listagem ou impressão de listas sequenciais com chave e não ordenada. Se vocês puderem me dá um norte.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Why odd number of players?

Question: Almost all the games and sports involve an odd number of players.
And most the games involve 11 players, eg: football, cricket, hockey etc.
And other games like basketball and all have 5 which is also odd and prime.
i can think of only volleyball that has even and non prime number of players.
My specific question is why are there ODD prime numbers of players in most of the games?
Comment: Hockey 6? I thought it was 11. Which hockey are you reffering?
Comment: @Drewbenn - and Junior and High school leagues... at least in the US.
Answer:
Ice Hockey 6
Softball (mostly played with 10 players with an extra outfielder) 10
Volleyball 6 for indoor 2 for sand
Curling 4
Boblseigh = 2 or 4
Relay Racing - 4
Polo 4

I could go on but I trust you get the point.
Comment: @corsiKa - The goalie is a specialized position sure but the same could be said about any sport with a goal tender.  That does not mean that they are any less part of the team, and at the end of the game in hockey the team that is down will often play empty net with the intent of using the extra man to catch up.
Comment: But still i feel its mostly odd number of player in most of the games.
Comment: @Rohit - thats because most of the games you see on tv regularly use odd numbers.  But 2 or 4 are actually more common when you look at all sports.  Though alot of them its only 1 person active at a time.
Comment: Technically Ice Hockey has 6, but only 5 really move anywhere.
Answer: Surely this is just down to the individual sports and their rules themselves.  When codifying the game, the people in charge of doing so must have picked a number most convenient to them and the space they played in, and didn't consciously try to pick an odd, prime number as you claim is common.  It might just seem that more sports have odd, prime number sized teams because the ones you list are the popular ones that are on television.

Why odd number of players?


Getting the selected option value of a radio button in form_state storage

Question: I'm trying to make a step form which redirects to a special form depending on a radio button option chosen by the user.
My form always go to the default option value. I think I'm doing it wrong with the $form_state['storage'] getting the selected option.
function multiform_second_form(&$form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  $options = array(
  '0' => t('Simple'),
  '1' => t('Multiple'),
  '2' => t('Custom'),
);

  $form['qtype'] = array(
  '#type' => 'radios',
  '#title' => t('question'),
  '#options' => $options,
  '#description' => t('Chose a question type.'),
  '#default_value' => $options['0'],
);

  $option_value = $form['qtype']['options'];
  $form_state['storage'] = array(
      'qtype' => $option_value,
    );

  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Next step'),
  );

  $form['#submit'][] = 'multiform_second_form_submit';

  return $form;
}

function multiform_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  if (isset($values['next']) && $values['op'] == $values['next']) {

  switch ($form_state['storage']['qtype']) {
    case 0:
    $form_state['storage']['step'] = 'multiform_qsimple_form';
    break;
    case 1:
    $form_state['storage']['step'] = 'multiform_qmultiple_form';
    break;
    case 2:
    $form_state['storage']['step'] = 'multiform_qcustom_form';
    break;
}

  }
}

If somebody can give me some advices, it would be really great !
Answer: Try using a string for the step id, something like this:
function multiform_second_form(&$form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  $options = array(
  'simple' => t('Simple'),
  'multiple' => t('Multiple'),
  'custom' => t('Custom'),
  );

  $form['qtype'] = array(
  '#type' => 'radios',
  '#title' => t('question'),
  '#options' => $options,
  '#description' => t('Chose a question type.'),
  '#default_value' => 'simple',
  );

  $option_value = isset($form_state['values']['qtype']) ? $form_state['values']['qtype'] : 'simple';
  $form_state['storage'] = array(
    'qtype' => $option_value,
  );

  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Next step'),
  );

  $form['#submit'][] = 'multiform_second_form_submit';

  return $form;
}

function multiform_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  if (isset($values['next']) && $values['op'] == $values['next']) {

  switch ($form_state['storage']['qtype']) {
    case 'simple':
    $form_state['storage']['step'] = 'multiform_qsimple_form';
    break;
    case 'multiple':
    $form_state['storage']['step'] = 'multiform_qmultiple_form';
    break;
    case 'custom':
    $form_state['storage']['step'] = 'multiform_qcustom_form';
    break;
  }

  }
}


References for profunctors used in program analysis

Question: Profunctors seem like they'd be useful for representing the output of a program analysis.  For example, given some information about a function $f$, the profunctor would tell you what information can be derived about compositions of $f$ with other functions.
Does anyone have any references to work along these lines?
Comment: Perhaps this is more appropriate for cstheory.
Comment: I too think you should ask on [cstheory.SE](http://cstheory.stackexchange.com/). FWIW, sigfpe wrote a [blog post](http://blog.sigfpe.com/2011/07/profunctors-in-haskell.html) on A Neighborhood of Infinity about Profunctors in Haskell. There are couple of references at the end.
Answer: Mike, I am afraid, I do not fully understand what you mean. However, you definitely should take a look at the concept of "arrows" introduced as a kind of a generalisation of computational monads. Perhaps, the best introductory paper is thee following one:
B. Jacobs, C. Heunen, I. Hasuo, "Categorical semantics for arrows."


How can I make a PyQt widget resizable by dragging?

Question: I have a QScrollArea containing a widget with a QVBoxLayout.  Inside this layout are several other widgets.  I want the user to be able to drag the lower borders of those widgets to resize them in the vertical direction.  When they are resized, I don't want them to "steal" size from the other widgets in the scrolling area; instead I want the entire scrolled "page" to change its size.  So if you enlarge one of the widgets, it should push the other widgets down (out of the viewport of the scroll area); if you shrink it, it should pull the other widgets up.  Dragging the border of one widget should not change the size of any of the other widgets in the vertical scroll; it should just move them.
I began by using a QSplitter.  If I use that, I can drag to change the size of a widget, but there doesn't seem to be a way to get it to "push/pull" the others as I described above, rather than growing/shrinking them.  But I can't find any other way to give a widget a draggable handle that will allow me to change its size.  How can I accomplish this?
Here is a simple example of what I'm doing.  (In this example I've commented out the splitter, but if you uncomment it you can see what happens with that version.)
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.Qsci import QsciScintilla, QsciLexerPython

class SimplePythonEditor(QsciScintilla):
    def __init__(self, parent=None):
        super(SimplePythonEditor, self).__init__(parent)
        self.setMinimumHeight(50)

class Chunk(QFrame):
    def __init__(self, parent=None):
        super(Chunk, self).__init__(parent)

        layout = QVBoxLayout(self)
        sash = QSplitter(self)
        layout.addWidget(sash)
        sash.setOrientation(Qt.Vertical)

        editor = self.editor = SimplePythonEditor()
        output = self.output = SimplePythonEditor()
        output.setReadOnly(True)

        sash.addWidget(editor)
        sash.addWidget(output)

        self.setLayout(layout)
        print(self.sizePolicy())

class Widget(QWidget):

    def __init__(self, parent= None):
        global inout
        super(Widget, self).__init__()

        #Container Widget
        widget = QWidget()
        #Layout of Container Widget
        layout = QVBoxLayout(self)

        #sash = QSplitter(self)
        #layout.addWidget(sash)
        #sash.setOrientation(Qt.Vertical)

        for num in range(5):
            editor = SimplePythonEditor()
            editor.setText("Some stuff {}".format(num))

            layout.addWidget(editor)
            #sash.addWidget(editor)

        widget.setLayout(layout)

        #Scroll Area Properties
        scroll = QScrollArea()
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll.setWidgetResizable(True)
        scroll.setWidget(widget)
        scroll.setMaximumHeight(500)

        #Scroll Area Layer add
        vLayout = QVBoxLayout(self)
        vLayout.addWidget(scroll)
        self.setLayout(vLayout)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    dialog = Widget()
    dialog.show()

    app.exec_()

Comment: this could be similar https://stackoverflow.com/questions/14980620/qt-layout-resize-to-minimum-after-widget-size-changes
Comment: Try use [`setSizePolicy`](https://doc.qt.io/qt-5/qwidget.html#sizePolicy-prop) with [`QSizePolicy`](https://doc.qt.io/qt-5/qsizepolicy.html) like this `scroll.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)`.
Answer: class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowTitle("MainWindow")
        MainWindow.resize(500, 500)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)
        QMetaObject.connectSlotsByName(MainWindow)

class Ewindow(QMainWindow,QApplication):
    """docstring for App"""
    resized = pyqtSignal()

    def __init__(self,parent):
        super(Ewindow,self).__init__(parent=parent)
        self.setGeometry(500, 500, 800,800)
        self.setWindowTitle('Mocker')
        self.setWindowIcon(QIcon('icon.png'))
        self.setAttribute(Qt.WA_DeleteOnClose)

        ui2 = Ui_MainWindow()
        ui2.setupUi(self)
        self.resized.connect(self.readjust)

    def resizeEvent(self, event):
        self.resized.emit()
        return super(Ewindow, self).resizeEvent(event)

    def readjust(self):

        self.examForm.move(self.width()-self.examForm.width(),0)
        self.btn_skip.move(self.width()-self.btn_skip.width(),self.height()-100)
        self.btn_next.move(self.btn_showAnswers.x()+self.btn_showAnswers.width(),self.height()-100)
        self.btn_prev.move(0,self.height()-100)
        self.btn_showAnswers.move(self.btn_prev.x()+self.btn_prev.width(),self.height()-100)
        self.btn_home.move(self.width()-200,self.height()-150)

        self.lbscreen1.resize(self.width()-self.examForm.width(),self.height()-200)
        self.examForm.resize(200,self.height()-150)
        self.btn_skip.resize(self.examForm.width(),100)
        self.btn_next.resize(self.btn_prev.width(),100)
        self.btn_prev.resize(self.width()*0.25,100)
        self.btn_showAnswers.resize(self.btn_prev.width(),100)
        self.btn_home.resize(200,50)

here is an example code of a resizable window it moves and stretches widgets as you resize the window. The idea is to keep widget coordinates and sizes relative to each other.
so i had to make a class Ui_MainWindow and set it for my window class ui2.setupUi(self) and also declare the resized = pyqtSignal() which i'd be using to run the readjust function which resets size and coordinates of the widgets like so self.resized.connect(self.readjust).
i hope this helps!


How to make inferences on group SD and and the SD of the group SD in a hierarchical Bayesian model?

Question: The hierarchical model specified below is quite "standard" and easy to implement in for example JAGS/BUGS. It has an hierarchical gamma prior on the subject's precisions ($\tau_j$) which in turn has gamma priors on its mean ($m$) and SD ($d$). After having fitted this model I have access to estimates of the mean group precision ($m$) and SD of the group precision ($d$) but I rather make inferences on the natural scale. That is, the mean group SD and the SD of the group SD.
How can I make inferences on the mean group SD and the SD of the group SD from such a model? Is it at all possible?
Here is a Kruschke style diagram of the model taken from the book Doing Bayesian Data Analysis

And here is the corresponding BUGS code:
model {
  for( i in 1 : Ndata ) {
    y[i]  ̃ dnorm( mu[ subj[i] ] , tau[ subj[i] ] )
  }
  for ( j in 1 : Nsubj ) {
    mu[j]  ̃ dnorm( muG , tauG )
    tau[j]  ̃ dgamma( sG , rG )
  }
  muG  ̃ dnorm( 2.3 , 0.1 )
  tauG  ̃ dgamma( 1 , .5 )
  sG <- pow(m,2) / pow(d,2)
  rG <- m / pow(d,2)
  m  ̃ dgamma( 1 , .25 )
  d  ̃ dgamma( 1 , .5 )
}

One solution would perhaps be to not put the hyperpriors on the precision ($\tau_j$) but rather on the SD ($\sigma_j$) though I'm not at all sure what priors I should use then.
Answer: Given that the $\tau_j$ are i.i.d. Gamma with parameters $\alpha, \lambda$ (where $f(x) \propto \lambda^{\alpha} x^{\alpha-1}\exp\{-\lambda x\}$, to define the parameterization of the Gamma), then $\sigma_j = 1/\sqrt{\tau_j}$ has a Stacy distribution, which is a special case of the Amoroso distribution.  This has a closed form expression for the mean and standard deviation, assuming the parameters are such that the mean and standard deviation exist, in terms of $\alpha$ and $\lambda$, and hence in terms of your m and d.
Define $\theta = 1/\sqrt{\lambda}$.  Then:
$\mathbb{E}\sigma_j = \alpha + \theta {\Gamma(\alpha-{1\over 2}) \over \Gamma(\alpha)} $
and
$\text{Sd}\space \sigma_j = \theta \left[{\Gamma(\alpha-1) \over \Gamma(\alpha)}-\left({\Gamma(\alpha-{1\over 2}) \over \Gamma(\alpha)}\right)^2 \right]^{1\over2}$
where $\alpha > 1/2$ for the mean to exist and $\alpha > 1$ for the variance to exist.  (If you read the article, note the $\beta$ parameter of the distribution $= -2$, as $\tau = \sigma^{-2}$.)
One method for generating MCMC samples of the mean and std. deviation of the $\sigma_j$ would be to take your samples of m and d (or, more simply, rG (= $\lambda$) and sG (= $\alpha$)), and transform them as above.  However, one suspects that you may indeed have samples where $\alpha \leq 1$ or even $\alpha \leq 1/2$.  No doubt many solutions to this exist, but two that come to mind are to 1) throw out all the samples (in their entirety) where this happens, which corresponds to altering your prior on m and d so that they are confined to a region of $\mathbb{R}^{+2}$ where the mean and variance of the $\tau$ exist, or 2) put your prior on $\sigma$ instead of $\tau$, altering the hyperpriors to something appropriate.  Without knowing how strongly you're attached to the particular shape of the priors on m and d, though, it's hard to give advice about what "something appropriate" might be.  Maybe just put a Gamma distribution on the $\sigma_j$ instead of the $\tau_j$ and continue as you did... hopefully the choice of prior doesn't make much difference to your posterior.
If it doesn't happen all that often, and you like those priors as they are, I'd probably go with option 1.  If it happens a lot, though, then those priors in combination with your data are perhaps telling you something about the upper tail of the posterior distribution of the $\sigma_j$.
To summarize why this works, this is equivalent to:
1) Put a Stacy prior on the $\sigma_i$, parameterized by rG and sG,
2) Put hyperpriors on rG and sG as they currently are,
3) Instead of bothering to generate Stacy-distributed $\sigma_i$ and transforming them to $\tau_i$, just generate the $\tau_i$ directly using the relationship between the Stacy prior on $\sigma$ and the equivalent Gamma prior on $\tau$,
4) Calculate samples of the first two moments of the Stacy prior from the sampled rG and sG.
Comment: I know you've seen this link before, but *http://stats.stackexchange.com/questions/6493/mildly-informative-prior-distributions-for-scale-parameters* can help; many of the mentioned distributions can be parameterized by a mean and variance which are transformed to the "usual" parameters (as you did with the Gamma above).  As to why you get many $\alpha < 1$, it's because the tails of your prior on $\sigma$, when you integrate out `m` and `d`, are too fat for $\sigma$ to have a finite variance.  You might also be able to fix it by bounding $d$ above and below (JAGS lets you do this.)
Comment: Thank you! I've been looking for this answer for so long :'-) Really, thanks! You are correct in that I get some (actually a lot of) samples where α < 1. While I try to figure out why that is the case I would be happy to put a prior on σ meanwhile. The reason why I haven't done so yet is because I haven't found any example of someone putting informative on σ, it is always just gamma on τ. What I'm looking for is a reasonable distribution for σ that can be parameterized with scale and location and that is not too "unconventional". Would you say the gamma distribution could work in this case?
Comment: Yes, I looked at that page many times :) Again!


Nested arrays or nested 2D array?

Question: I have created a few headers each which holds an array and they are all nested:

PixelArray[17] inside ScreenArray[10] inside MonitorArray[Dynamic Pointer]

This is because I wanted to test it as I went along (Not a competent programmer by a long shot) it was only after this I realised I could have merged PixelArray[17] and ScreenArray[10] into a single 2D array:

PixelArray[10][17] inside MonitorArray[Dynamic Pointer]

My question is whether it would be more efficient to use a single 2D array or not?
Comment: Efficiency is literally the last thing you should be worried about. In your case you probably won't see any difference in performance, but a definite answer can be only obtained by measuring.
Answer: Managing 2D array requires more competance than managing 1D array, but 2D array is more elegant as you have packaging in better form, since you have the data grouping kept together
Comment: @BuiltonSin They are same from compiler point of view, same amount of data storage, little efficient in 2D as you have less variables to access
Comment: I suppose elegance is something to aim for, but I was wondering on compile whether there is any discernible difference between the methods?
Answer: A single 2D array or an array containing arrays are the very same in C++. Indeed
typedef int InnerArray[20];
InnerArray OuterArray[30];

and
int MyArray2d[20][30];

are basically two ways to say the same thing to a C++ compiler.
Answer: The question of how good a particular data layout is in terms of efficiency can only be answered if you take into account how you access that data.
In general you can say that you should group data in memory such that you access memory consecutively or at least locally most of the time, you will then benefit from hardware support such as data streaming or cache efficiency. This is often referred to as "data-oriented design".
That being said, there is probably not much difference to expect from your two suggestions as the memory layout of both is effectively the same.

Nested arrays or nested 2D array?


Cant find the mistake in code

Question: Hi people i have a small problem i cganged the sql database code and my activity code... Now the app crashes when i try to start the activity(1). I am giving you the sql database code too(2). And the text from logcat(3).
(1):
package com.peky.smartornot;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class POV1 extends Activity {
    Sql ulaz = new Sql(this);
    TextView joke4text;
    TextView joke3text;
    TextView joke2text;
    TextView joke1text;

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

    public void sve() {
        // TODO Auto-generated method stub
        ulaz.open();
        int joker1 = ulaz.procitaj(), joker2 = ulaz.procitaj2(), joker3 = ulaz
                .procitaj3(), joker4 = ulaz.procitaj4();
        ulaz.close();
        TabHost joker = (TabHost) findViewById(R.id.tabhost);
        joker.setup();
        TabSpec izgled = joker.newTabSpec("tag1");
        izgled.setContent(R.id.tab1);
        izgled.setIndicator("Joker 1");
        joker.addTab(izgled);
        izgled = joker.newTabSpec("tag2");
        izgled.setContent(R.id.tab2);
        izgled.setIndicator("Joker 2");
        joker.addTab(izgled);
        izgled = joker.newTabSpec("tag3");
        izgled.setContent(R.id.tab3);
        izgled.setIndicator("Joker 3");
        joker.addTab(izgled);
        izgled = joker.newTabSpec("tag4");
        izgled.setContent(R.id.tab4);
        izgled.setIndicator("Joker 4");
        joker.addTab(izgled);
        joke1text = (TextView) findViewById(R.id.joker1text);
        joke1text.setText("You have " + joker1 + " jokers !");
        joke2text = (TextView) findViewById(R.id.joker2text);
        joke2text.setText("You have " + joker2 + " jokers !");
        joke3text = (TextView) findViewById(R.id.joker3text);
        joke3text.setText("You have " + joker3 + " jokers !");
        joke4text = (TextView) findViewById(R.id.joker4text);
        joke4text.setText("You have " + joker4 + " jokers !");
    }

    public void joker1(View view) {
        Button netocan = (Button) findViewById(R.id.button5);
        Button netocan2 = (Button) findViewById(R.id.button4);
        Button netocan3 = (Button) findViewById(R.id.button2);
        ulaz.open();
        int joker1=ulaz.procitaj(),joker2,joker3,joker4;
        ulaz.close();
        if (joker1 != 0) {
            if(netocan.getVisibility()==View.VISIBLE){
                netocan.setVisibility(View.INVISIBLE);
                ulaz.open();
                joker1=joker1-1;
                joker2=ulaz.procitaj2();
                joker3=ulaz.procitaj3();
                joker4=ulaz.procitaj4();
                ulaz.spremijoker(joker1, joker2, joker3, joker4);
                ulaz.close();
                joke1text = (TextView) findViewById(R.id.joker1text);
                joke1text.setText("You have " + joker1 + " jokers !");
            }else if(netocan2.getVisibility()==View.VISIBLE){
                netocan2.setVisibility(View.INVISIBLE);
                ulaz.open();
                joker1=joker1-1;
                joker2=ulaz.procitaj2();
                joker3=ulaz.procitaj3();
                joker4=ulaz.procitaj4();
                ulaz.spremijoker(joker1, joker2, joker3, joker4);
                ulaz.close();
                joke1text = (TextView) findViewById(R.id.joker1text);
                joke1text.setText("You have " + joker1 + " jokers !");
            }else if(netocan3.getVisibility()==View.VISIBLE){
                netocan3.setVisibility(View.INVISIBLE);
                ulaz.open();
                joker1=joker1-1;
                joker2=ulaz.procitaj2();
                joker3=ulaz.procitaj3();
                joker4=ulaz.procitaj4();
                ulaz.spremijoker(joker1, joker2, joker3, joker4);
                ulaz.close();
                joke1text = (TextView) findViewById(R.id.joker1text);
                joke1text.setText("You have " + joker1 + " jokers !");
            }else{
                Toast imasodgovor=Toast.makeText(getApplicationContext(), "You can not use more JOKERS1 on this question !", Toast.LENGTH_SHORT);
                imasodgovor.show();
            }

        }else{
            Toast nemasjokera=Toast.makeText(getApplicationContext(), "You dont have enought JOKERS1 !", Toast.LENGTH_SHORT);
            nemasjokera.show();
        }

    }

    public void joker4(View view) {
        ulaz.open();
        int joker1,joker2,joker3,joker4=ulaz.procitaj4();
        ulaz.close();
        Button netocan = (Button) findViewById(R.id.button5);
        Button netocan2 = (Button) findViewById(R.id.button4);
        Button netocan3 = (Button) findViewById(R.id.button2);
        if (joker4 != 0) {
            if(netocan.getVisibility()==View.VISIBLE || netocan2.getVisibility()==View.VISIBLE || netocan3.getVisibility()==View.VISIBLE){
            netocan.setVisibility(View.INVISIBLE);
            netocan2.setVisibility(View.INVISIBLE);
            netocan3.setVisibility(View.INVISIBLE);
            ulaz.open();
            joker1=ulaz.procitaj();
            joker2=ulaz.procitaj2();
            joker3=ulaz.procitaj3();
            joker4=joker4 - 1;;
            ulaz.spremijoker(joker1, joker2, joker3, joker4);
            ulaz.close();
            joke4text = (TextView) findViewById(R.id.joker4text);
            joke4text.setText("You have " + joker4 + " jokers !");}else{
                Toast imasodgovor=Toast.makeText(getApplicationContext(), "You can not use more JOKERS4 on this question !", Toast.LENGTH_SHORT);
                imasodgovor.show();
            }
        } else {
            Toast jokertext = Toast.makeText(getApplicationContext(),
                    "Not enought JOKERS4", Toast.LENGTH_SHORT);
            jokertext.show();

        }
    }

    public void joker2(View view){

    }
    public void tocan(View view){
    }
    public void netocanodgovor(View view) {
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.pov1, menu);
        return false;
    }

}

(2):
package com.peky.smartornot;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Sql {
    public static final String KEY_ROWID = "_id";
    public static final String KEY_JOKER1 = "joker";
    public static final String KEY_JOKER2 = "joker2";
    public static final String KEY_JOKER3 = "joker3";
    public static final String KEY_JOKER4 = "joker4";

    private static final String DATABASE_NAME = "SQL";
    private static final String DATABASE_TABLE = "peoples_table";
    private static final int DATABASE_VERSION = 1;

    private DbHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper {

        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
                    + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_JOKER1
                    + " INTEGER, " + KEY_JOKER2 + " INTEGER, " + KEY_JOKER3
                    + " INTEGER, " + KEY_JOKER4 + " INTEGER);");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            onCreate(db);
        }

    }

    public Sql(Context c) {
        ourContext = c;
    }

    public Sql open() {
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        ourHelper.close();
    }

    public long spremijoker(int joker1, int joker2, int joker3, int joker4) {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();

        cv.put(KEY_JOKER1, joker1);

        cv.put(KEY_JOKER2, joker2);

        cv.put(KEY_JOKER3, joker3);

        cv.put(KEY_JOKER4, joker4);

        return ourDatabase.insert(DATABASE_TABLE, null, cv);

    }

    public int procitaj() {
        // TODO Auto-generated method stub
        String[] columns = new String[] { KEY_ROWID, KEY_JOKER1 };
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
                null, null);
        int citac = 0;
        int iJokerammount = c.getColumnIndex(KEY_JOKER1);
        c.moveToLast();
        citac = c.getInt(iJokerammount);

        return citac;

    }

    public int procitaj2() {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        String[] columns = new String[] { KEY_ROWID, KEY_JOKER2 };
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
                null, null);
        int citac = 0;
        int iJoker2 = c.getColumnIndex(KEY_JOKER2);
        c.moveToLast();
        citac = c.getInt(iJoker2);

        return citac;

    }

    public int procitaj3() {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        String[] columns = new String[] { KEY_ROWID, KEY_JOKER3 };
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
                null, null);
        int citac = 0;
        int iJoker3 = c.getColumnIndex(KEY_JOKER3);
        c.moveToLast();
        citac = c.getInt(iJoker3);

        return citac;

    }

    public int procitaj4() {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        String[] columns = new String[] { KEY_ROWID, KEY_JOKER4 };
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
                null, null);
        int citac = 0;
        int iJoker4 = c.getColumnIndex(KEY_JOKER4);
        c.moveToLast();
        citac = c.getInt(iJoker4);

        return citac;

    }

}

(3):
03-16 19:32:11.580: E/AndroidRuntime(26569): FATAL EXCEPTION: main
03-16 19:32:11.580: E/AndroidRuntime(26569): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.peky.smartornot/com.peky.smartornot.POV1}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
03-16 19:32:11.580: E/AndroidRuntime(26569):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)

Comment: Are you sure that is the full log? Also, what attempts have you made so far at trying to track down the problem? Also check out http://stackoverflow.com/help/how-to-ask
Answer: Your error says it all:

CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0

You are attempting to access an empty list of something with an element index of -1. -1 is never a valid array index in Java, so you have two problems:

Why is the list empty, if that is indeed not wanted?
What is causing the incorrect index value of -1?

Since android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970) is where the problem is being caused, that is where you need to look. What in your code is calling it? Since performLaunchActivity is nowhere in your posted code (nor is your main function), and since your stack trace is not more thorough, we'll need more information before we can help you further.
Comment: I haven't gone through your code, but if you are migrating from other languages where -1 is a valid index, you will have to change it to `List.getLength()-1` or similar.
Comment: Changed "never" to "never in Java".
Comment: So if i add in the on create code a content value to put 0 in it it ahould fix my problem? And no the minimal value  should be 0 the list is empty i guess. I will try it out.
Comment: Can't say for sure without seeing more relevant code, but it certainly is worth a try.
Answer: I found a fix for the problem i set in the procitaj method:
for(c.moveToFirst;!c.isAfterLast;c.moveToNext){
 citac = c.getInt(iJoker4);
}

instead of:
c.moveToLast;

Thanks anyway !

Cant find the mistake in code


Erro Python com Django on_delete

Question: Sou iniciante na plataforma Django e na linguagem Python e, estou desenvolvendo um site em Django 2.2 e Python 3.7.3,
e estou com um problema no meu código no models.py da minha app "courses".
class Enrollment(models.Model):

    STATUS_CHOICES = (
        (0, 'Pendente'),
        (1, 'Aprovado'),
        (2, 'Cancelado'),
    )

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, verbose_name='Usuário',
        models.CASCADE,
        related_name='enrollments'
    )
    course = models.ForeignKey(
        Course, verbose_name='Curso', related_name='enrollments'
    )
    status = models.IntegerField(
        'Situação', choices=STATUS_CHOICES, default=1, blank=True
    )

    created_at = models.DateTimeField('Criado em', auto_now_add=True)
    updated_at = models.DateTimeField('Atualizado em', auto_now=True)

    def active(self):
        self.status = 1
        self.save()

    class Meta:
        verbose_name = 'Inscrição'
        verbose_name_plural = 'Inscrições'
        unique_together = (('user', 'course'),)

E está dando esse erro:
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\Luciano\ambientes_virtuais\ambientes_virtuais\virtual_01\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Users\Luciano\ambientes_virtuais\ambientes_virtuais\virtual_01\lib\site-packages\django\core\management\__init__.py", line 357, in execute
    django.setup()
  File "C:\Users\Luciano\ambientes_virtuais\ambientes_virtuais\virtual_01\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Luciano\ambientes_virtuais\ambientes_virtuais\virtual_01\lib\site-packages\django\apps\registry.py", line 114, in populate
    app_config.import_models()
  File "C:\Users\Luciano\ambientes_virtuais\ambientes_virtuais\virtual_01\lib\site-packages\django\apps\config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\Luciano\ambientes_virtuais\ambientes_virtuais\virtual_01\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\Luciano\ambientes_virtuais\ConnectU\ConnectU\courses\models.py", line 53, in <module>
    class Enrollment(models.Model):
  File "C:\Users\Luciano\ambientes_virtuais\ConnectU\ConnectU\courses\models.py", line 67, in Enrollment
    Course, verbose_name='Curso', related_name='enrollments'
TypeError: __init__() missing 1 required positional argument: 'on_delete'

O que eu posso fazer?
Answer: Felipe, se você verificar a documentação do campo Model.ForeignKey verá que a assinatura do método é:
ForeignKey(to, on_delete, **options)

E verificando o código fonte temos o construtor:
def __init__(self, to, on_delete, related_name=None, related_query_name=None,
             limit_choices_to=None, parent_link=False, to_field=None,
             db_constraint=True, **kwargs):
    ...

Isso significa que há dois parâmetros obrigatórios, to e on_delete, o restante é opcional. No seu model você faz:
user = models.ForeignKey(
    settings.AUTH_USER_MODEL,
    verbose_name='Usuário',
    models.CASCADE,
    related_name='enrollments'
)
course = models.ForeignKey(
    Course, verbose_name='Curso', related_name='enrollments'
)

Se você reparar verá que em user você está chamando models.ForeignKey usando:

Um argumento posicional com o valor settings.AUTH_USER_MODEL
Um argumento nomeado verbose_name com o valor "Usuário"
Um argumento posicional com o valor models.CASCADE
Um argumento nomeado related_name com o valor "enrollments"

Você não pode intercalar argumentos nomeados e posicionais ao chamar uma função. Você deve passar os argumentos posicionais antes dos nomeados. E como mostrado no código fonte e na documentação os argumentos são to e  on_delete, então você precisa alterar seu código para que estes parâmetros sejam passados corretamente:

Passando o parâmetro on_delete logo após o parâmetro to:
user = models.ForeignKey(
    settings.AUTH_USER_MODEL,
    models.CASCADE,
    verbose_name='Usuário',
    related_name='enrollments'
)

Passando o parâmetro on_delete em nomeando-o:
user = models.ForeignKey(
    settings.AUTH_USER_MODEL,
    verbose_name='Usuário',
    on_delete=models.CASCADE,
    related_name='enrollments'
)

Erro Python com Django on_delete


How to determine which variables to include in a regression using BIC, but reduce the number of possibilities by using a stepwise algorithm

Question: I want to perform a regression and want an objective strategy to decide on which variables to include (so something besides theory or expert judgement). I am aware of stepwise backward and forward methods, in which the most significant variable is added or the least significant variable is removed up to the point where the model fit does no longer significantly improve.
I want to make a decision based on BIC, but I do not want to consider all possible combinations of variables (excluding polynomial terms and interactions). If I have $n$ variables, then this means I need to perform $(n)  (n!)$ regressions (I think), which is too many.
I was hoping to find a stepwise approach for the BIC methods. The reason is simply to reduce the number of cases I need to check. Does there exist a stepwise algorithm for the BIC method? I could not find any stepwise approach that does not consider p-values.
Comment: If you really want to do this, you would start from a model $M$ and try adding (or removing) one variable at a time, fitting a new model $M'$ and recording the BIC values of all these new models. Then move to the one new model that has the lowest BIC, and iterate. If no model achieves a lower BIC than the current model $M$, then $M$ is your final model. It's completely analogous to adding variables based on their p values in a larger model. (And it's still not a good idea.)
Comment: You can easily adapt the standard stepwise approach to use BIC rather than p values. The bigger question is: why do you want to do this? This *can* work if your goal is predicting, but if you want to do hypothesis testing or inference on the final model, then this approach will render any tests invalid, just as any other stepwise method.
Comment: I want to do this, because my variables are not really direct measures of what I want to predict. For example, I want to explain education by wealth of the parents, but I do not have parental income as variable. However, I do have the value of the house the person grew up in.
Comment: I don't quite see how that is an argument for a stepwise approach. And it does sound like you do want to do inference, so *please* take a look at [the relevant threads](https://stats.stackexchange.com/questions/tagged/stepwise-regression?tab=Votes) - *any* stepwise approach invalidates p values.
Comment: But how would one combine a stepwise approach with BIC, because BIC only says something about the entire model and not about specific variables.
Answer: BIC is one criterion for adding or removing a single variable in stepwise selection. There is the MASS::stepAIC function in R. Similar logic could be applied to BIC.
As is discussed in the comments, though, there are major issues with stepwise selection. Stepwise regression seems like it can be competitive for pure prediction problems, but it's use requires some care, and there are major flaws when you do inference on stepwise-selected variables.


Forgetting the piece when playing for the teacher

Question: I am taking piano lessons that I have to prepare pieces for, and play them for the teacher. After learning a piece, I usually manage to play it when practising in private. However when I come to the lesson, I make mistakes that I never made before, and I never manage to recover and go on. My hands completely forget what to do.
In the past, I used to play for the teacher (another one) only in graded exams and didn't have this problem. I always dreaded the experience but was able to play the pieces and recover from mistakes.
Is this a known issue? Does anyone know of a solution?
UPDATE:
The answers below don't apply to me at all. I have no interest in impressing my teacher. I just want to cope with the course. Actually my interest in music has generally declined after the lessons. Also, now that somebody mentioned nerves/stress, I tend to perform much better when under pressure. In all my exams in the past, I was able to do well in pieces where my hands where shivering through out. One time when I was playing an easy piece in the exam and was starting to get comfortable, my hands all the sudden forgot where to go. (I just started the piece again from the beginning with faster tempo and shivering hands.) Also, in my first lesson with this new teacher, my hands were shivering, and I played what I knew as I wanted to play it.
I don't understand completely why this happens to me. But, I think my coping strategy would be to just shiver my hands when playing.
Comment: This is nothing to do with music, but everything to do with nerves/stress. I think it is covered off by the duplicate.
Comment: stage fright. You do get over it. Get right back on the horse and keep doing it or you never will succeed. Practice the piece endlessly until you can get it right without thinking, then go to that place when you perform.
Answer: Stage fright
You have to learn to live with it or ignore it; absorb yourself in what you are playing & exclude everything around you, or learn to love an audience.
It has to be said, it's far easier to ignore a thousand people than it is to ignore one, especially when you are trying hard to impress that one.
There are as many ways to prepare for a performance as there are performers; so whether you try relaxation, far too much coffee, or a stiff drink [I know, I'm just providing examples] it's up to you how you deal with it best.
If it does strike you just at the wrong moment & you halt completely, then you have to just sit back, take a deep breath & pick up from where you left off.
The more you worry about it, the worse it will become.
It's purely psychological, but that doesn't mean it's not real.


onClick em componentes criados dinamicamente React

Question: Possuo um componente user-defined chamado <Match> que é criado dinamicamente dentro de outro componente <Event>. Porém ao colocar onClick no componente  é estourado uma exceção. Como resolver o problema, sendo que para cada componente criado dinamicamente eu preciso de onClick que futuramente vai criar um novo componente.

Events.js:121 Uncaught TypeError: Cannot read property 'addBetCard' of
  undefined(…)

Event.js
  createMatch (match) {
    return <Match source={match} key={match.id} onClick={this.addBetCard.bind(this)}/>;
  }

  createMatches (matches) {
    return matches.map(this.createMatch);
  }

render() {

   return(
   ...

      {this.createMatches(dataFake)}

)}

Saída temporária, como melhorar?
Meu propósito é ter o onClick dentro do componente <Match> e toda vez que clicar no componente chamar onClick daquele componente.
addBetCard(item){
    console.log("Adicionando item");
  }

createMatch (match) {
    return <Match source={match}/>;
}

createMatches (matches) {
    return matches.map((i) => this.createMatch(i));
    // return matches.map(this.createMatch);
}

render() {

   return(
   ...

      {this.createMatches(dataFake)}

)}

O trecho de código que eu coloquei logo acima resolve meu problema, de que quando clicar no componente chamar o método onClick dele. Porém é uma saída nada elegante onde eu preciso colocar o meu componente <Match> dentro de uma tag  que por sua vez, possui o onClick.
Comment: Falta o `=` e um `}` aí... deve ser `onClick={this.addBetCard.bind(this)}`
Comment: Falta ainda o `=`  depois do `onClick`... não vejo onde a variável `dataFake` é usada. O problema mantem-se ainda?
Comment: Valeu. Alguma sugestão de como resolver o problema?
Comment: Usa this.createMatches.call(this, dataFake)
Answer: Tens de corrigir os "bindings", ou seja garantir que o contexto de execução é o correto.
Podes fazer isso assim:
constructor(props){
    super(props);
    this.addBetCard = this.addBetCard.bind(this);
    this.createMatch = this.createMatch.bind(this);
    this.createMatches = this.createMatches.bind(this);
}

createMatch (match) {
    return <Match source={match} key={match.id} onClick={this.addBetCard}/>;
}

createMatches (matches) {
    return matches.map(this.createMatch);
}

render() {
     // const dataFake = ['etc', 'etc'];
     return (
          // ...

          {this.createMatches(dataFake)}

    )
}

Comment: Infelizmente a solução que você passou não funcionou no meu caso. Consegui resolver mas a forma como resolvi to achando bem 'gambiarrosa'. Vou editar a pergunta acima pra vê se existe uma solução mais elegante.
Comment: @LuKsSys é dificil saber como o teu componente está. Podes adaptar este jsFiddle https://jsfiddle.net/paul_lecam/q2v7t59h/ com o teu componente para eu ver?
Comment: OK! vou fazer isso
Comment: https://jsfiddle.net/lucassilvax/q2v7t59h/255/. O objetivo é clicar em algum dos  e apresentar um alerta ao clicar.
Comment: @LuKsSys ok, revi agora: https://jsfiddle.net/xwzfv7pc/ E o que queres mostrar no `console` quando houver `click`? o nome da equipa?
Comment: Justamente isso que preciso.
Comment: Funcionou, muito obrigado pela ajuda. Por mim daria 2 up na sua resposta!!!


Invalidating session before iPhone application quits

Question: I would like to tell the server to invalidate an ongoing session when the user quits the iPhone application.
In the app delegate, I send a request to the server in the <code>(void)applicationWillTerminate:(UIApplication *)application</code> method. I am not waiting for a server answer, I just want to send the request and quit.
However I cant see any packet leaving the application. The same code in another place works fine.
Session has a limited duration anyway and the server will invalidate it after a while, but I would prefer to do it nicely when leaving application.
Is it normal that no NSURLConnection can be established from the applicationWillTerminate method ?
Thank you.
Answer: If you're sending an asynchronous request, it's very likely that the app quits before the request is made.
Try using a synchronous request as a test, although I wouldn't recommend doing that in production, as synchronous requests can take an indeterminate amount of time. If he app forcibly quits, it'll show as a "time-out on quit" in your crash reports section in iTunes Connect.
Comment: [NSURLConnection sendSynchronousRequest:myRequest returningResponse:NULL error:NULL] worked indeed. But I don't know if I should leave it, as per your warning. Maybe the server should handle the session ending after all.
Comment: If the server can gracefully handle the case where a user quits the app and relaunches it within a very short period of time, then the server should definitely take care of it. In that case it would be ideal for the server to reassign the session to the client (you could use the client's UDID for this) or to just create a new session on startup and let the old one fade into the ether.


Extreme Value Theorem on Manifold

Question: Let $M$ be a compact manifold. Then any $h \in C^{\infty}(M)$, $h$ has a maximum and minimum value.
Since $M$ is compact we know that $M$ can be covered with finitely many charts, but I'm not sure where to go after that.
Comment: You do not need the fact that $M$ is a smooth manifold, you just need the fact that $M$ is a compact topological space. And you do not need the fact that $h$ is $C^\infty$, you just need the fact that $h:M\to\mathbb{R}$ is continuous. So this is basic point-set topology.
Answer: $h$ is continuous, so its image is compact since $M$ is compact, every compact subset of $R$ has a minimum and a maximum.
Answer: The following fact may be helpful: Smooth maps are continuous, and a continuous map from a compact space preserves compactness. This you can prove by pulling back an open cover of the image to the preimage, chopping it down, and then making sure it maps to a finite open cover.
From here, you know what every compact subspace of $\mathbb{R}$ looks like: namely, closed and bounded. Will the image include a maximum/minimum value?
Comment: Don't all continuous maps preserve compactness, without any Hausdorff requirement?
Comment: Ah, yes, sorry. I was proving a stronger statement in my head. I'll edit my answer.

Extreme Value Theorem on Manifold


Find the domain of the sequence in which it converges uniformly.

Question: Let $f_n(x)={x^n\over n}+1$. I need  to find the domain of it's uniform convergence. I tried the $M_n$-test. So, I got the point limit $f(x)=1$ when $x\in [0,1]$. For $x>1$ the point limit wont exist, hence no question of uniform convergence arises. Thus, the convergence in uniform in $[0,1]$. That goes right now hopefully.
UPDATE Also, now I observed the convergence will hold uniformly in $[-1,0]$ by similar argument. For $\vert x\vert >1$, the point limit won't exist. So, the domain of uniform convergence should be $[-1,1]$
Comment: $f_n(2)$ certainly doesn't converge. You might want add some details to your reasoning.
Answer: That is not true. I'll only discuss the sequence for nonnegative $x$. The negative $x$ I'll leave it for you. For $x>1$ the limit is infinity (why?). So $f(x) =1$ cannot be the limit function for ALL $x$! For $x=1$ the limit is $1$. For $x\in[0,1)$ we have $f(x) =1$. That was all pointwise limits.
Now let's check uniform convergence where there is pointwise convergence so only on $[0,1]$. So $f(x) =1$ and
\begin{align}
\sup_{x\in[0,1]} |f_n(x) -  f(x) |\leq \frac{1} {n} \to 0
\end{align}
So uniform convergence on $[0,1]$. Now do the negative half line yourself and conclude.
Comment: _For x>1x>1 the limit is infinity (why?)_ : Yup true That is because for x>1, we obtain the indeterminate form. On applying L Hopital's rule, I got infinity Got it. Thanks.
Comment: @ShatabdiSinha good!
Comment: Sir, by similar argument would it not be correct to say that the convergence is also uniform in [-1,0]..? Because for values of x<-1 the point limit should not exist? Is this right sir?
Comment: @ShatabdiSinha totally correct! Keep up the good work!
Comment: Thankfully I got it right. Thank you for your appreciation.


multiplying Persistenance of an integer

Question: I am trying to make a code that does the following:
Multiplying the digits of an integer and continuing the process gives the surprising result that the sequence of products always arrives at a single-digit number.
For example:
715 -> 35 -> 15 -> 5
88 -> 64 -> 24 -> 8
27 -> 14 -> 4
The number of products necessary to reach the single-digit number is called the persistence number of that integer. Thus 715 and 88 have a persistence number of 3, while 27 has persistence 2. Make a program to find the only two-digit number with persistence greater than 3?
I was able to come up with a rough idea and the code is below but it doesn't seem to work:
#include <iostream>

using namespace std;

/*
 *
 */
int PersistentNum(int digit)
{
    int x;
    int pers = 0;
    int y = 1;

    while(x > 9)
    {
        do {
            x = digit % 10;
            y = y * digit;
            x = x / 10;
        } while(x > 0);
        pers++;
        x = y;
    }
    return pers;
}

int main()
{
    int repNum;
    int Persist;
    cout << "Please enter a  non-zero, positive integer: ";
    cin >> repNum;

    Persist = PersistentNum(repNum);

    cout << " the Persistence of " << repNum <<" is " << Persist;
    return 0;
}

Comment: Please elaborate on what you mean by "_doesn't seem to work_".
Comment: Try with 77.....
Comment: You want the code for finding a two digit number with persistence greater than 3 right?But the largest two digit number is 99 and according to your definition its persistence 99->81->8 is 2 .So no use of writing code
Comment: @GaneshChowdharySadanala Try it with 88.
Comment: @Rags he asked persistence greater than 3 but the persistence of 88 is 3
Comment: Also, `while(x > 9)`...`x` is uninitialized first time through.
Comment: i want the number that is inputed for example 715 should go down to 35 then to 15 then to 5 , so it shows the persistence is 3.
Comment: Also, consider using variable names that are more descriptive than just `x` and `y`. Here's an example of your code with different names. I think it is easier to follow/debug. https://ideone.com/MiNTNP
Comment: @JE3 you can take a glance at my code
Comment: @JE3 i have used break i my code because 77 is the only two digit number with persistence >3
Comment: 77 is the only two digit number with persistence >3
Comment: I recommend inputting the number as text (string).  You can then access the digits as:  `int numeric_digit = number_as_text[i] - '0';`
Comment: learn to use your debugger
Comment: @GaneshChowdarySadanala Indeed. My point was merely that starting with higher numbers didn't automatically produce a higher persistence,  which seemed to be what you were suggesting apologies if I misunderstood what you were saying.
Answer: you have to assign y every time as it here retains the old already multiplied value.
also you messed up the meaning of x and digit in your original code
instead of
func(int x)

you wrote
func(int digit)

corrected code
#include <iostream>

using namespace std;

/*
 *
 */
int PersistentNum(int x)
{
    int digit;
    int pers = 0;
    int y =1 ;

    while(x > 9)
    {
        y = 1;

        do{
           digit = x % 10;
           y = y* digit;
           x = x/10;
        }while(x > 0);

        pers++;
        x = y;
    }
    return pers;
}

int main()
{
    int repNum;
    int Persist;

    cout<<"Please enter a  non-zero, positive integer: ";
    cin>>repNum;

    Persist = PersistentNum(repNum);

    cout<< " the Persistence of " << repNum <<" is " << Persist;

    return 0;
}

Comment: so i assigned y but now it is outputing 1  no matter what the input is:

        while(digit> 9)
        {
        y = 1;
        do{
        x = digit % 10;
        y = digit * y;
        x = x/10;

        }while(x> 0);

        pers++;
        x=y;

        return pers;
        }
        }
Answer: As per your question ,You want me we to find for 2 digit number
#include<iostream>
using namespace std;
int main()
{int y;int z;int temp;int n;
 for(int x=10;x<100;x++)
 {temp=0;n=x;
  while(x>9){
  y=x%10;
  z=x/10;
  x=y*z;temp++;
  }
  x=n;
   if(temp>3){
   cout<<"number is "<<n<<"persistence is"<<temp;
 /*number is 77 persistence is 4 */
   break;}/*i have used break i my code because 77 is the only two digit number with persistence >3*/
  }
   }

Answer: First of all, you have to initialize x before the first loop- or just using do..while loop in both of the loops, read about garbage values.
int PersistentNum(int number)
{
    int digit, pers = 0, curr_num;

    do {
        curr_num = 1;

        do {
            digit = number % 10;
            curr_num = curr_num * digit;
            number = number / 10;
        } while(number > 0);

        cout << curr_num << " ";
        number = curr_num;
        pers++;

    } while(number > 9);

    cout << endl;
    return pers;
}

multiplying Persistenance of an integer


Ultrametric example

Question: Can anybody give an example for ultrametric space? i.e., in the metric space definition, instead of triangle inequality, we have strong triangle inequality, namely $d(x,y) \leq \max \left\{d(x,z),d(z,y)\right\}$ for all $x,y,z$.
A trivial example is the discrete metric. I want some non trivial example.
Answer: First observe that any nonzero rational number in $\mathbb Q$ has a unique factorization into prime numbers (allowing negative exponents of course). Next, let $p$ be a prime and for any $\frac{a}{b}\in\mathbb Q$ define $v_p\left(\frac{a}{b}\right)$ to be the exponent of the prime $p$ in the factorization of $\frac{a}{b}$, and $v_p(0)=\infty$. Now let $\epsilon<1$ be positive, and define $d_p(r,s) = \epsilon^{v_p(r-s)}$.
This is known as the $p$-adic norm on $\mathbb Q$, you can check it is an ultrametric.
Answer: For a very trivial example, let $X$ be any set, and let $d$ be the discrete metric on $X$; $d(x,y)=0$ if $x=y$, and $d(x,y)=1$ otherwise. Clearly this $d$ is an ultrametric, and it generates the discrete topology.
For a much more interesting example, let $D=\{0,1\}$ with the discrete topology, and let $X=D^{\Bbb N}$, the Cartesian product of countably infinitely many copies of $D$. Elements of $X$ are sequences $x=\langle x_n:n\in\Bbb N\rangle$ such that each $x_n$ is either $0$ or $1$. (This space is homeomorphic to the well-known middle-thirds Cantor set.)
For distinct $x,y\in X$ let $\delta(x,y)=\min\{n\in\Bbb N:x_n\ne y_n\}$, the first index at which $x$ and $y$ disagree. We can define a metric $d$ on $X$ by setting
$$d(x,y)=\begin{cases}
0,&\text{if }x=y\\
2^{-\delta(x,y)},&\text{otherwise}\;.
\end{cases}$$
In words, $d$ 'says' that if $x$ and $y$ agree on their first $n$ terms, then $d(x,y)$ is at most $\frac1{2^n}$.
It's clear that $d$ is symmetric and separates points. Now let $x,y,z\in X$; we want to show that
$$d(x,y)\le\max\{d(x,z),d(z,y)\}\;.$$
This is clear if $x=z$, $y=z$, or $x=y$, so assume that the three points are distinct. Let $k=\delta(x,z)$ and $\ell=\delta(z,y)$, and without loss of generality assume that $k\le\ell$. Then $x_n=z_n=y_n$ for each $n<k$, so $\delta(x,y)\ge k$, and therefore
$$d(x,y)=2^{-\delta(x,y)}\le 2^{-k}=\max\left\{2^{-k},2^{-\ell}\right\}=\max\{d(x,z),d(z,y)\}\;,$$
and $d$ is an ultrametric.
I'll leave it as an exercise, if you're interested, to show that $d$ generates the product topology on $X$.
Comment: @ugurefem: No, the Hamming distance is defined only for *finite* binary sequences (of the same length) and is the number of positions in which two sequences disagree.
Comment: Is this the Hamming distance by the way?
Answer: This is an old question, but here is an example that has helped me a lot in visualizing ultrametric spaces.
Consider the taxonomic hierarchy of organisms. Let $X$ be the set of all organisms, and let $d : X \times X \to \mathbb{R}_+$ be a distance function such that $d\left(x,y\right)$ gets smaller as $x$ and $y$ get more and more similar. For example:

$d\left(x,y\right) = 0$ if $x = y$;
$d\left(x,y\right) = 1$ if $x$ and $y$ belong to the same species but are distinct;
$d\left(x,y\right) = 2$ if $x$ and $y$ belong to the same genus but not to the same species;
$d\left(x,y\right) = 3$ if $x$ and $y$ belong to the same family but not to the same genus;

etc.
Then, $\left(X, d\right)$ is an ultrametric space.

Ultrametric example


How is the Duckworth-Lewis Method applied?

Question: I have seen lots of matches in which the D/L method was used to decide victory, but I never found out how it actually works. I know there are two keys in this method: overs and wickets in hand. Can anyone please explain it? And why does it not apply in test matches?
Comment: Plenty of people who've taken the time to read the details understand it. If you read the original paper by Duckwork and Lewis http://www.jstor.org/stable/3010471?origin=JSTOR-pdf you'll see they understand it pretty well. Please don't project your willful ignorance onto everyone else.
Comment: I don't think anyone (even Duckwork and Lewis) knows it to the core. The most confusing thing about Cricket
Answer: The Duckworth-Lewis method is explained on the ICC website:

Duckworth-Lewis Method description and guide to usage
Duckworth-Lewis method FAQ

Despite much confusion amongst the media, the players, and the public, the actual principle is relatively simple. When an interruption causes one team to have less resources available than the other team, the target is proportionally adjusted in the ratio of the resources available to each team.
For instance, if an interruption reduces the resources of the side batting second (Team 2) by 50% in comparison to Team 1's resources, the target would be reduced by 50%.
As you correctly mentioned, resources are composed of both wickets and overs. The D/L method does not add or subtract wickets or overs; it simply calculates what the target should be, given those resources.
While the principle is simple, it raises plenty of questions for discussion. I would strongly recommend reading the FAQ linked above, as they clarify many common queries.
Test Matches do not use the Duckworth-Lewis method because the number of overs per innings is not defined in a Test Match. Furthermore, a draw is a perfectly acceptable result in a Test Match.
Comment: +1 for point out that the basic idea is straight forward. The exact calculation are necessarily somewhat complex in order that they be accurate. A simple formula would be less accurate.
Answer: If any interruption occurs by rain or audience duckworth luis method is applied to the team that takes batting in second innings of that match.It works on reducing overs limit. For example if team A makes170 runs for two wicketsafter 33.2 overs and match gets disturbed by rain,then the number of overs will be reduced to42 overs from 50.Number of overs to reduce depends on resources available i,e overs and wickets.probability works here asuming tht if team A plays 50 overs it might have done 296 runs in 42 0vers where the match overs limit was made.soteam B has to do297 runs in 42 overs to win the match .
If team B can't win, it is not completely due to duckworth law as before beginning of 2nd innings itself a sheet will be given to captain stating at what runs will win the match if match stops at what over


What was the motivation for developing the plugin API?

Question: I am trying to wrap around my head as to what was the need for the Plugin API when the module system extends the Drupal core.
Answer: It is not modules vs. plugins. Plugins are competing against hooks, which they will eventually replace entirely, together with event subscribers and services. By the way, all are implemented by modules because you are not allowed to insert them in core directly.
Comment: It is OOP code and much easier to understand, especially if you didn't write the code yourself.
Comment: What is the advantage of plugins over hooks?