Why is this probability distribution biased towards even numbers?

Question: I am working on the probabilities of a game where

they pick 20 unique number(non-repeating) from range 1 to 80
sort those 20 numbers in ascending order
sum every 4 numbers and take the last digit as result (so end with 5 numbers).

Normally I could find these probabilities with rules based on combination and permutation but for this one because of the sorting  I am not sure how to work on it.
I tried to brute force all combinations but with some test it would take my old laptop about few thousand years.  So I did some simulations, sampling 100 million samples.  Below is the final result.

So there seems to be a small edge towards even numbers, but I don't understand where this edge comes from (even numbers appear about .5095925 of the time).
I went further down about the first 4 numbers out of the sorted 20 numbers and try based on the fact that the 1st sorted number must be in the range of 1 to 61, 2nd sorted must be in the range of 2 to 62, etc. So odd positions will have 31 out of 61 chances to be odd and even positions have 31 out of 61 to be even. And I did some checks below, but the resulting bias towards even numbers is very small (.50000004 vs the stimulation .5095925).

I wonder where and how the game tends to favor even numbers quite a bit. Or is my simulation code just wrong?
Comment: +1 For a quick insight into this, think about the results you would get if you were to select 76 numbers rather than 20.  It will help to reason in terms of parity: how many odd numbers do you expect to see in each group of four numbers?
Comment: No, that's not it.  You need to look at the chances, *within any given group,* of observing an even number of odd values, because that characterizes the cases where the total will end in 0, 2, 4, 6, or 8.  For instance, any group of four numbers in a row is guaranteed to have two odd and two even values and therefore its sum cannot end in an odd digit.
Comment: Your results look good.  In particular, the first-number percentages for digits 0 - 5 are typically correct in the first four or five significant digits.
Comment: @whuber you mean because there are 40 odd and 40 even, the chance of getting 10 odd and 10 even for the 20 number is higher, then the chance of getting 2 odds and 2 evens (result in even) is higher in a 4 number group base?
Answer: This is an interesting question because the result is a little surprising; it is subtle; and it has been well researched with a large simulation.
Here is a graphical representation of ten iterations of the game.  Each row is an iteration.  It shows the 20 numbers selected, $k_1,k_2, \ldots, k_{20},$ and uses colors to depict their partition into five groups of four.  The game sums the numbers in each group, thereby producing five sums.

Nevertheless, within the large number of simulations reported in the question, there appears to be an imbalance among odd and even sums, although this procedure seemingly would not favor one parity.  Indeed, if we were only to take a subset of four numbers from $\{1,2,3,\ldots, 80\}$ and sum them modulo ten, each digit would have exactly $1/10$ chance of appearing.
To appreciate what's happening, consider extreme versions of this procedure, where instead of partitioning a sample of $20$ into five groups of four, let's take a sample of $76$ and partition it into $19$ groups of four:

What strikes us first about this image are the prominent gray "bubbles" depicting the numbers that were not sampled.  With only $80-76=4$ bubbles in each iteration, we're unlikely to find any bubbles in the first group of four.  Moreover, when there is a bubble in that group, as in the fourth row from the top, it's just as likely to be an even number as an odd number.  That means the first group (in this extreme case) is highly likely to include two odd numbers and two even numbers, making its sum even.
This consideration of bubbles suggests analyzing the game in terms of gaps between the selected numbers.  The first gap is $\Delta_1 = k_1-0,$ the second gap is $\Delta_2 = k_2-k_1,$ and so on.  All gaps are $1$ or larger.  Evidently the last number chosen is $k_{20} = \Delta_1+\Delta_2 + \cdots + \Delta_{20},$ which therefore must be $80$ or smaller.
Let's begin with the first gap, $\Delta_1=k_1.$  What is the chance this gap is only $1,$ the smallest possible value?  That's easy to compute, because

There are $\binom{80}{20}$ distinct, equally-probable subsamples of size $20$ that can be obtained from all $80$ numbers.
Of these, $\binom{79}{20}$ are from the set $\{2,3,\ldots, 80\}.$

Subtracting, we find the number of subsamples with $k_1=1$ and divide that by the total number of subsamples to obtain the probability:
$$\Pr(\Delta_1 = 1) = \frac{\binom{80}{20} - \binom{79}{20}}{\binom{80}{20}} = \frac{\binom{79}{19}}{\binom{80}{20}} = \frac{1}{4}.$$
(Although only one of the ten iterations in the first figure has $\Delta_1=1$--the fifth row from the top--a longer set of simulations confirms that $\Delta_1=1$ in about a quarter of them.)
Analogous reasoning establishes the remaining chances:
$$\Pr(\Delta_1 = j_1) = \frac{\binom{80+1-j_1}{20} - \binom{80-j_1}{20}}{\binom{80}{20}} = \frac{\binom{80-j_1}{19}}{\binom{80}{20}},\ j_1=1, 2, \ldots, 61.$$
Now suppose we have observed $\Delta_1.$  What could $\Delta_2$ be?  If it is equal to $j_2,$ that means the last $20-1$ numbers are a subset of the values from $\Delta_1+j_2$ through $80$ and the remaining $20-2$ numbers all lie between $\Delta_1 + j_2 +1$ and $80.$  In effect, the role of $80$ is now played by $80-j_1,$ $20$ is reduced to $20-1=1,$ and $j_2$ plays the role of $j_1.$ Thus, writing $k_2=j_1+j_2$ for the second lowest value selected,
$$\eqalign{
\Pr(k_2\text{ selected next}\mid k_1\text{ selected first}) &= \Pr(\Delta_2 = j_2 \mid \Delta_1=j_1) \\
&= \frac{\binom{80-k_2}{20-2}}{\binom{80-k_1}{20-1}},\ k_2=j_1+1, 2, \ldots, 80+1-(20-1).}$$
The pattern is clear.  In particular, to study the first group, we can calculate the probability distribution of the sum of just the lowest four numbers in the subsample by summing over all possible values of $\Delta_1,\Delta_2,\Delta_3,\Delta_4.$  There are sufficiently few of these that this computation is feasible.
By the laws of conditional probability, the chance of such a combination $(j_1,j_2,j_3,j_4)$ is obtained by the products of the component probabilities
$$\eqalign{
q_{j_4,j_3,j_2,j_1} &= \Pr(\Delta_4=j_4\mid \Delta_3=j_3,\Delta_2=j_2,\Delta_1=j_1) \\
&\times \Pr(\Delta_3=j_3\mid \Delta_2=j_2,\Delta_1=j_1) \\
&\times \Pr(\Delta_2=j_2\mid \Delta_1=j_1) \\
&\times \Pr(\Delta_1=j_1)}$$
as
$$\Pr(j_1,j_2,j_3,j_4) = \sum_{j_1=1}^{81-20}\ \sum_{j_2=1}^{81-j_1-19}\ \sum_{j_3=1}^{81-j_1-j_2-18}\ \sum_{j_4=1}^{81-j_1-j_2-j_3-17} q_{j_4,j_3,j_2,j_1} .$$
For the game described in the question, there are "only" 635,376 possible combinations in this quadruple sum: the calculations can be carried out in seconds. Here is the interesting part of the probability distribution of the group sum $k_1+k_2+k_3+k_4 = 4j_1+3j_2+2j_3+j_1:$

(The full distribution extends to the largest possible sum that could appear in this first group of four numbers, equal to $61+62+63+64=250.$)
The solid red dots are probabilities a little larger than suggested by their neighbors: the alternation between even and odd is clear.
When we further reduce this distribution by taking just the last digits of the sums, the alternation between even and odd persists:

This plot shows the relative differences between the probabilities and $1/10.$  The actual values (to eight digits) are
Digit Probability
    0  0.10235369
    1  0.09779473
    2  0.10159497
    3  0.09859690
    4  0.10239713
    5  0.09838777
    6  0.10201990
    7  0.09821967
    8  0.10121774
    9  0.09741751

Many of them agree closely (to four or five digits) with the simulation results reported in the question.
Notice (from the equations or the simulations) that the first group of four smallest numbers tends to lie to the left of $20$ or so, leaving about $60$ values from which to select the next four groups.  Thus, the situation with the second group is typically just like the situation with five groups, but with $80$ reduced to around $60$ and only $20-4=16$ numbers to select.  Similar reasoning suggests the situation with the third and fourth groups also is similar.  The simulations in the question bear this out: they still favor even sums over odd.
Analogous discrepancies in probabilities occur when representing the sums in other (non-decimal) bases. Different patterns of discrepancies occur when taking groups of other sizes, especially odd sizes: groups of size $4$ are special because they have a pronounced tendency to include either zero, two, or four odd numbers, which guarantees their sum is even.

Here is the R used to do the calculations.  It is coded so you can experiment with versions of this game simply by changing the parameters n, m, and g.
library(data.table)
n <- 80 # Maximum number available (100 or more may be problematic)
m <- 4  # Group sizes >= 2 (8 or more is problematic)
g <- 5  # Number of groups >= 1 (more is easier!)
#
# Generate all possible vectors of gaps.
#
delta <- 1:(n - m*(g-1) + 1)
X <- do.call("expand.grid", lapply(1:m, function(i) delta))
names(X) <- paste0("k", 1:m)
X <- as.data.table(X)
i <- rowSums(X) < max(delta)
X <- X[i, ]
#
# Generate the numbers corresponding to each gap vector.
#
Y <- apply(X, 1, cumsum)
rownames(Y) <- paste0("k", 1:m)
Y <- as.data.table(t(Y))
#
# Compute log conditional probabilities for each selection.
#
f <- function(k, n, g) {
  m <- length(k)
  k0 <- c(0, k[-m])
  j <- (m*g-1) : (m*(g-1))
  lchoose(n - k, j) - lchoose(n - k0, j+1)
}
Z <- apply(Y, 1, function(k) f(k, n, g))
rownames(Z) <- paste0("p", 1:m)
Z <- as.data.table(t(Z))
#
# Compute the probability of each vector.
#
Z[, pi := exp(rowSums(Z))]
Y[, Sum := rowSums(Y)]
X <- cbind(X, Y, Z)
1-sum(X$pi) # Should be near zero, within floating point roundoff error
#
# Summarize by group sum.
#
H <- X[, .(Probability = sum(pi)), keyby=Sum]
H.mod <- rbindlist(lapply(2:40, function(b)
  H[, .(Probability = sum(Probability), Base=b),
    keyby=(Sum - choose(m+1,2)) %% b]))

with(H[Probability > 0.00025],  {
  above <- sapply(1:length(Sum), function(i) {
    g <- splinefun(Sum[-i], Probability[-i])
    Probability[i] > g(Sum[i])
  })
  colors <- ifelse(above, "Red", "Gray")
  plot(Sum, Probability, type="l")
  abline(h=0)
  abline(v = seq(0, max(Sum), by=5), col="Gray", lty=3)
  abline(v = seq(0, max(Sum), by=10), col="Gray")
  points(Sum, Probability, pch=21, bg=colors)
})
#
# Explore the last digit in various bases.
#
base <- 10
with(H.mod[Base==base], {
  plot(Sum, base*Probability - 1, type="b", ylim=base*range(Probability)-1,
       pch=21, bg=ifelse(base*Probability-1 > 0, "Red", "Gray"),
       xlab=paste("Sum modulo", base, "offset by", choose(m+1,2)))
  abline(h=0, col="Gray")
})

Comment: I am moved by the details and visualization that you offer. There is still much for me to dig into the step by step forming of the formula and the code but first and formal let me thank you for this amazing answer.


what is evaluation_periods in terraform aws_cloudwatch_metric_alarm?

Question: I see the definition in terraform docs for aws_cloudwatch_metric_alarm paramter evaluation_periods is "The number of periods over which data is compared to the specified threshold."  I don't understand what this means though.  Can someone please explain it?  Maybe an example.
Answer: Its explained in AWS docs:

Evaluation Periods is the number of the most recent periods, or data points, to evaluate when determining alarm state.

An example with explenation is also given in the docs.
Answer: I also thought the docs weren't entirely clear, but here's my understanding after another read-through:
From the example given in the docs:
    resource "aws_cloudwatch_metric_alarm" "foobar" {
      alarm_name                = "terraform-test-foobar5"
      comparison_operator       = "GreaterThanOrEqualToThreshold"
      evaluation_periods        = "2"
      metric_name               = "CPUUtilization"
      namespace                 = "AWS/EC2"
      period                    = "120"
      statistic                 = "Average"
      threshold                 = "80"
      alarm_description         = "This metric monitors ec2 cpu utilization"
      insufficient_data_actions = []
    }

The period (required) is the time in seconds over which the specified statistic is applied.  The evaluation_periods (also required) then is the number of periods over which data is compared to the specified threshold.
So in this example, you have period set for 120s (2min).  After two periods have passed, it will then compare to the threshold (80) to determine whether or not the alarm is tripped.


Is it possible to "add" a rotary fifth valve to a 4-valved tuba?

Question: I am currently playing Wessex TB 692 Grand, which is 4-valved BBb tuba.
I have always cherished a 5-valved BBb, so I wonder if it is possible to add a rotary 5th valve to my Wessex horn..
Is this something that would require I find a technician?
Comment: Since you're in the UK, why not contact Wessex Tubas Ltd directly?  Or exchange your Grand model to a similarly spec'd [Prokofiev model](https://www.wessex-tubas.com/products/bbb-6-4-tuba-with-5-valves-prokofiev-tb693) which has 5 valves.
Comment: What happened to the 5-valved instrument you cherished?
Answer: Yes, it can be done. But it is quite unusual.
An instrument builder can change your instrument basically any way you wish to. It includes loosening the solders between different tube parts, purchasing and installing the fifth valve, making new tube parts and resolder it together and refinishing the lacquer. Not for the faint hearted and not going to be inexpensive.
My guess is that you will be better off financially buying another instrument instead. But as they say in car adverts, YMMV.


How to make a Tile/Grid layout like Gridster.js in AS3?

Question: I want to make a custom layout which behaves like this shown in picture below.
I have already tried Tile Layout and to modify its  calculateDropIndex method but not get desired behavior.
Tile layout works well when all the tiles are of same height and width but in my case tile size are different.
http://gridster.net/

Gridster layout screenshot
Comment: I do not know your end goals for the movable panels, but if you are looking to build a dashboard style application, Quite a while ago, I used the Adobe open-source Flex 3/4 Dashboard (developed by WASI) (http://www.adobe.com/devnet/flex/samples/dashboard.html) and then they had a 4-part series that ported it to Flex4 (http://www.adobe.com/devnet/flex/articles/migrating-flex-apps-part4.html). I ended up writing a custom layout to handle 'pods' that differed in size (just like Gridster). If I'd had to do it again I would just buy Flexicious's Dashboard http://www.flexicious.com/Home/Dashboard
Comment: @RobertN thanks for the reply. i have checked this dashboard example from the links you provide but here  tiles(pods) are re-sizing as number of pods increases. My requirement is to increase height of the pod container as number of widgets increases.As you said you have write custom layout which handles different pod size can i have a demo link for that or the custom layout file itself.
Comment: That was a contract project so I can not redistribute that but most if it was based on the Flex 4 Spark Layout Class, just extended TileLayout...
Comment: OK. no problem but is it possible to achieve same behavior as gridster by extending Tile layout?
Answer: After a little bit more try i am able make a gridster like drag n drop gird component.
here is a brief summery of how i have made this component.
while adding pods in to container add one more pod at the same position and keep it's visibility off. this extra node will be our drop indicator.
keep all the original nodes in one array say nodes, and all extra nodes in another array say dropIndicators.
for example if add nodes A, B and C in the container. we will add three extra nodes X, Y and Z respectively one for each main node.
and over nodes array will be
node[0] = A;
node[1] = B;
node[2] = C;

and dropIndicators array will be
dropIndicators[0] = X;
dropIndicators[1] = Y;
dropIndicators[2] = Z;

now you will need following function to update nodes position when we drag any node.

CalculateDropLocation -  to calculate new drop location while dragging.
CheckCollision -  to check collision between two nodes.
FixCollision - if there is a collision we will fix the collision using this function. this function will mode all the colliding nodes downwards recursively.
updateNodes - once the collision is fixed we will update all the nodes using this function. this function will move node upward if there is an empty space.

now when we start dragging A node calculate new drop location for A node and move it's relative extra node i.e. X to the new drop location, check if X is colliding with any other extra node. we will use the dropIndicators array in all the functions.
if collistion than call fixCollision() function, than call update node function.
and at the end once all the nodes are updated set the position of all the extra nodes to it's original nodes i.e. set X's position to A's position , Y's position to B and so on. while updating original nodes position you can use Move animation to move nodes smoothly in the container.
hope this will help. using this method you can make this type of layout in any language.
hope this will help.
for more details and sample application with source visit this link
http://usefulflexcomponents.blogspot.in/2015/12/blog-post.html


Conflito: JQuery Validation + Bootstrap 3 Tooltip

Question: Estou com um conflito entre o JQuery Validation e o Bootstrap Tooltip, de forma que quando envio o formulário vazio e o Validation entra em ação, e o Tooltip aparece com o focus no input, a cada vez que o input perde o foco e recebe novamente, a mensagem de validação é repetida uma linha abaixo, indefinidamente. Por favor, gostaria de alguma dica, pois não estou conseguindo resolver este conflito!
Obrigado.

$.validator.setDefaults();
$(document).ready(function () {
  //Tooltip
  $('[data-toggle=\'tooltip\']').tooltip({animation: true, placement: 'bottom', trigger: 'focus'});
  //Validator
  $('#form-cadastro').validate({
    rules: {
      confirma: {
        equalTo: '#senha'
      }
    },
    messages: {
      nome: 'Este campo é obrigatório.',
      login: 'Por favor, digite um nome de usuário válido.',
      senha: 'Por favor, digite uma senha.',
      confirma: 'Por favor, repita a senha.'
    },
    errorElement: 'em',
    errorPlacement: function (error, element) {
      // Add the `help-block` class to the error element
      error.addClass('help-block');
      error.insertAfter(element);
    },
    highlight: function (element, errorClass, validClass) {
      $(element).parents('.col-md-12').addClass('has-error').removeClass('has-success');
    },
    unhighlight: function (element, errorClass, validClass) {
      $(element).parents('.col-md-12').addClass('has-success').removeClass('has-error');
    }
  });
});
 /* Tooltip */
.informa + .tooltip > .tooltip-inner {
  background-color: #222;
  color: #fff;
  border: 1px solid #222;
  padding-top: 0px;
  padding-bottom: 2px;
  padding-left: 4px;
  padding-right: 4px;
  font-family: Verdana, sans-serif;
  font-size: 10px;
}

.informa + .tooltip.bottom > .tooltip-arrow {
  border-bottom: 5px solid #222;
}

.tooltip {
  left: 15px !important;
}

/* Error message */
.error {
  font-family: Verdana, sans-serif;
  font-size: 10px;
  font-style: inherit;
}
<!DOCTYPE html>

    <title>Cadastrar usuário</title>
    <meta charset='utf-8' />

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Cadastrar usuário

          <form  action='' method='post' class='form-horizontal' id='form-cadastro'>

                Nome completo
                <input type='text' class='form-control informa' id='nome' name='nome' data-toggle='tooltip' title='Mínimo 6 caracteres' minlength='6' required />

                Nome de usuário
                <input type='text' class='form-control informa' id='login' name='login' data-toggle='tooltip' title='Mínimo 4 caracteres' minlength='4' required />

                Criar uma senha
                <input type='password' class='form-control informa' id='senha' name='senha' data-toggle='tooltip' title='Mínimo 4 caracteres' minlength='4' required />

                Confirme a senha
                <input type='password' class='form-control' id='confirma' name='confirma' required />

              <button type='button' class='btn btn-default' id='botao'>Cancelar</button>
              <input type='submit' name='cadastrar' class='btn btn-primary' value='Criar cadastro' />

          </form>

Answer: No seu erroPlacement tenta colocar assim:
errorPlacement: function (error, element) {
  $('#form-cadastro #'+element.attr('name')+'-error').remove(); // para remover o item caso ele ja tenha, ai logo abaixo adiciona.

  error.addClass('help-block');
  error.insertAfter(element);
},

Comment: :/ Não funcionou.
Answer: Muito obrigado, Douglas! O seu código não deu certo comigo, mas adaptei-o conforme a sua ideia e funcionou... conflito resolvido! Gratidão e abraço.
Minha solução foi:

errorPlacement: function (error, element) {
  $('[data-toggle=\'tooltip\']').removeAttr('name');
  error.addClass('help-block');
  error.insertAfter(element);
},
Comment: Putz... parecia ter resolvido, mas não! Resolveu com o formulário em branco, mas quando é preenchido fica bem ruim novamente. :/


Is there node api hook in drupal 7

Question: Is there still a hook_nodeapi in drupal 7 or do i have to try hook_node_load hook for appending some content to node?
Answer: hook_nodeapi() is split into multiple hooks in Drupal 7, so you should use hook_node_load()

Is there node api hook in drupal 7


What is the meaning of the various fingering on this arpeggio?

Question: What is the meaning of the two fingerings : "3" and "4" in the D # minor arpeggio (second inversion) ?
Should I "choose" one ?
Is there an "academic/official" one ?
for the moment? I use the 4, and it is difficult at high speed, while with 3, it is very easy.
Should a pianist learn the two variantes ? (and why ?)
And what about for cases where there are two fingerings on the left hand and two fingers on the right hand (this is the case for D bemol sharp, 2nd inversion): should we learn 2x2=4 variantes ?
Answer: Fingerings are suggestions and not commands. You can choose the one option, that you find is more comfortable.
You don't have to learn both fingerings at all, but you are invited to try out both suggestions. You also can  always write your own fingerings!
(I used to try sometimes looking for fingerings that where identical or symmetrical for both hands, even if they were less comfortable, but they helped me memorizing the musical motifs and the movement of my fingers ;)


Mostrar dados da BD

Question: Estou criando um site de filmes que deve mostrar os trailers e tal. Quero que ao adicionar na base de dados algum filme o script organize a tela dinamicamente.
Exemplo: na base de dados vamos ter nome do filme, foto e trailer.
Como devo começar? Se não puderem me ajudar a fazer, pelo menos me digam o que procurar.
Comment: Vou postar o que expliquei aqui >>> http://pastebin.com/bbtRiiL8
Comment: Obrigadoo Marcos Vinicios!! era bem isso que eu queria hehehe!
Comment: Você quer dizer alguma forma de verificar na base de dados se há alterações e então ele remover ou adicionar os filmes sem recarregar a página?
Comment: O que você quer dizer com "organizar"?
Comment: Experimente com [Bootstrap](http://getbootstrap.com/) consegue fazer isso tudo.
Comment: Se você estiver querendo organizar os dados fisicamente no banco de dados, tenta criar alguns index em suas tabelas.  Tenta detalhar melhor a sua pergunta, pois, está faltando informações e causando ambiguidade
Answer: Leve em consideração que ao atualizar sua base de dados, os dados já irão vir atualizados quando exibirem a sua consulta de filmes... Agora, tudo depende de como você está fazendo pra exibir seus dados, para organizar a tabela automaticamente de acordo com a qtdDeRegistros que você deve exibir em cada linha, você pode fazer desse modo:
$varConsulta = ConsultaFilmes();
    $i=0;
    if ($varConsulta) {
    echo "

";
        foreach ($varConsulta as $lin) {
            $linhas .= "Filme
[IMAGEM][INFORMAÇÕES REFERENTES AO FILME]	";

            echo $linhas;

            $i++;
            //Aqui é feito a mágica!!
            if ($i % $qtdDeRegistros == 0) {
                echo "
";
                echo "
";
            }
        }

        echo "

";
    }else{
        echo "
 Nenhum filme dísponivel.
";
    }
}

Mostrar dados da BD


Erro na conversão de string para integer

Question: Estou tentando cadastrar um cliente no BD interno do Android. Tenho um campo String onde coloco o telefone do usuário. Este campo eu faço a conversão para Integer utilizando o parseInt
newCliente.setFone(Integer.parseInt(foneDesc));

Se eu cadastrar no máximo dois números de telefone para o usuário ele aceita (foi o exemplo que usei). Mas seu eu digitar os 9 dígitos do telefone que é o correto ele dá erro:

FATAL EXCEPTION: main
  java.lang.NumberFormatException: Invalid int: "4899984829"
  at java.lang.Integer.invalidInt(Integer.java:138)
  at java.lang.Integer.parse(Integer.java:378)
  at java.lang.Integer.parseInt(Integer.java:366)
  at java.lang.Integer.parseInt(Integer.java:332)
  at artur.com.decorusfinal.cadastro.CadCliente$btGravar.onClick(CadCliente.java:68)
  at android.view.View.performClick(View.java:4204)
  at android.view.View$PerformClick.run(View.java:17355)
  at android.os.Handler.handleCallback(Handler.java:725)
  at android.os.Handler.dispatchMessage(Handler.java:92)
  at android.os.Looper.loop(Looper.java:137)
  at android.app.ActivityThread.main(ActivityThread.java:5041)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:511)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
  at dalvik.system.NativeStart.main(Native Method)

No erro ele dá diz que problema é na conversão
newCliente.setFone(Integer.parseInt(foneDesc));

Se não tivesse funcionando ele não deixaria nem eu cadastrar o usuário com apenas 2 números de telefone.
Answer: Acontece o número que você está tentando converter é muito grande para ser int, converta para long...
Veja a tabela a seguir:
        tamanho                      mínimo                          máximo
signed    8 bit                        -128                            +127
signed   16 bit                     -32 768                         +32 767
signed   32 bit              -2 147 483 648                  +2 147 483 647
signed   64 bit  -9 223 372 036 854 775 808      +9 223 372 036 854 775 807
unsigned  8 bit                           0                            +255
unsigned 16 bit                           0                         +65 535
unsigned 32 bit                           0                  +4 294 967 295
unsigned 64 bit                           0     +18 446 744 073 709 551 615

Em java, conforme a documentação
      tamanho                      mínimo                          máximo
byte:   8 bit                        -128                            +127
short: 16 bit                     -32 768                         +32 767
int:   32 bit              -2 147 483 648                  +2 147 483 647
long:  64 bit  -9 223 372 036 854 775 808      +9 223 372 036 854 775 807

Veja que int é 32 bits então o máximo é 2 147 483 647 e você está tentando converter 4 899 984 829, você pode converter para long (64bits) isto resolve seu problema.
long l = Long.parseLong(foneDesc);

Mas como é um número de telefone há realmente a necessidade de converter para número?
Espero ter ajudado!!
Referencias:
max value of integer
Comment: Acho que faltou um pedaço da tabela
Comment: @jbueno editei a resposta já com a outra tabela.
Comment: Agora sim. Boa resposta +1


Group policy preference power plan and console lock display timeout

Question: I have set a default GPP power plan for the domain by creating a GPP power plan under Power Options, checking the default box, and setting the action to Create.
However, on Windows 10 devices, the console lock display timeout setting is set to the default (1 second? or whatever it is) on the device because I don't have the option to configure it in the GPP as seen here.
Is there a registry key I can set to turn the "console lock display timeout" setting off? Or some way I can enable it in GPP so I can set it via group policy management?
Answer: This setting is not available in the Power Plan GPP.
However, you can change this value (videoconlock) by using the following command:
for AC power:
powercfg.exe /setacvalueindex SCHEME_CURRENT SUB_VIDEO VIDEOCONLOCK <number of seconds>
for DC power:
powercfg.exe /setdcvalueindex SCHEME_CURRENT SUB_VIDEO VIDEOCONLOCK <number of seconds>
I recommend creating an Immediate Task via GPP to launch this command only once per computer, as SYSTEM account (for example).
you can find more information about the videoconlock settings here:
https://support.microsoft.com/en-us/help/2835052/monitor-powers-off-after-1-minute-when-pc-is-locked (the KB says Windows 8 but the content is still relevant for Windows 10)


Search for consecutive sequence violation

Question: I want to test for string corruption and it would be easiest to use a regex that finds violations of a repeated sequence of characters.  Suppose the sequence used for validating integrity is 0 to 9.
For example, '0123456790123456789' would match '79' because '8' is missing.
'01234567555890123456789' would match '75558' because '555' doesn't belong.  The specific string returned isn't important, just the flagging of at minimum the first location of corruption.
How can I achieve this with a regular expression, if this is even possible with a regex?
Comment: Please use more words and explain more clearly what it is you are looking for.  Show sample data.  Also, don't assume that the answer to your question is going to use a regular expression.  Regexes are not a magic wand you wave at every problem that happens to involve strings.
Answer: You could spell out the sequence like this:
(0[^1]|1[^2]|2[^3]|3[^4]|4[^5]|5[^6]|6[^7]|7[^8]|8^[9]|9[^0])
In 01234567555890123456789 it returns two matches 75 and 55 - it will at least reliably find the first broken link.
I don't think much more can be done in regex alone since regex cannot do a sorted comparison in itself.
Comment: No need for sorting, really finding at least one occurrence is sufficient.
Comment: Yeah, with sorting I was thinking that the definition of a sequence is a set of rules what element follows which other element. Regex doesn't know that even for 0-9 / a-z etc., so it cannot handle sequences, unless with explicit atomic rules like I tried here.


I need to copy the 6 cells next to an active cell

Question: I know this question has been asked in several different fashions but I'm unable to get the code to run. I'm very new to coding macros (2 whopping days of it now). Here is the part I'm looking for help with.
If Box = "8" Then Workbooks("Narc Log.xlsm").Sheets("Fentanyl").Range("B5:F5").Copy _
    Destination:=Workbooks("Box 8.xlsm").Sheets("Fentanyl").Range("B4")

This copies a specific range of cells. I want to change it to copy the 6 cells to the left of the active cell and paste to the next available line in the other workbook "Box8"
Answer: first you should find the position of your active cell
  Dim c, r As Integer
    r = ActiveCell.Row
    c = ActiveCell.Column
Set sht = ActiveSheet

then you can use range function to get them
with sht
sht.range(.cells(c-7,r) , .cells(c-1,r)).copy
end with

and rest of code below.
P.S. i do not like to use .copy as it always run into error. I would prefer something like
Workbooks("Box 8.xlsm").Sheets("Fentanyl").Range("B4:B10").value = sht.range(.cells(c-7,r) , .cells(c-1,r)).value

Comment: Note that if you `Dim c, r As Integer` only `r` is of type `Integer` but `c` will be `Variant`. You must declare a type for **every** variable in VBA! Also you must use `Long` because Excel has more rows than `Integer` can handle: `Dim c As Long, r As Long`. I recommend [always to use Long instead of Integer](https://stackoverflow.com/a/26409520/3219613) in VBA since there is no benefit in `Integer` at all.


Does this decuplet make sense?

Question: I recently encountered this decuplet as you can see in the picture attached.
To me this doesn't make sense. This makes 10 16th notes instead of 4. This reduces the notes' lentgh 2.5 times.
Should one not write this as 10 32th notes instead of 8? That would make more sense to me. Then the notes' length would only be reduced 1.25 times. Or better even: two quintuplets of 32th notes.
Moreover, this notation makes it impossible to determine how long it should be if not for the bass notes and the rest of the measure. Say for example you use this in an anacrusis, without the bass ...
Comment: For a recording, this is Chopin's Raindrop Prelude. I edited the post to spell 'base' as 'bass' for referring to the left hand notes.
Answer: This isn't going to be played with mathematical precision.  Along with the "smorzando", the choice of note value indicates a relaxed tempo related to the preceding 16th note, rather than something twice as fast.  As you say, there is plenty of information in the rest of the notation.
Comment: True. And probably in this style of music you will long have figured out how to play this before you perform it. But if it wasn't during a smorzando and someone wanted to play it on sight, it might confuse him enough for him to lose the correct tempo.
Comment: Yes, if it wasn't that, it could be something else.  But it IS that!
Answer: What Chopin wrote:

It's 9 underneath, but there are ten notes and editions after (apart from Fontana's copying) show ten
(see Online Chopin Variorum Edition at this bar, bar 79).
My suggestion is that it is in fact 9 and the end three notes are a tuplet nested inside the 9.
Separately, 9 as a division is extremely unique where it can be expressed with two beams and also with three beams. Elaine Gould, 2011, Behind Bars, p.203, shows this in the table below:

Here is how I suggest it should be written:

And this is the pedantic way to write it out (which I would really doubt it existing in a Chopin holograph or any edition):
Comment: A dot of ink spilled and made an Ab5-like notehead. If Chopin wrote it using music notation software then ink drops cannot spill and I think it is like that. Here is [the bar with the 9-tuplet where the ink drop spilled](https://i.stack.imgur.com/esyRK.png) (the nested triplets should be a nonuplet).
Comment: @Vighnesh the notehead does resemble a spill, but there is ample evidence that it is not. Note the stem connecting to the beams above, and note the regular horizontal spacing of the ten stems (with slightly more space where accidentals are needed). Also note that there are several other places where mistakes have been very thoroughly scribbled out; such corrections are absent here. It is a bit weird that the stem extends beyond the ink blob; none of the other stems does. Perhaps an F♯5 was intended when he drew the stem and he changed his mind before writing the notehead.
Comment: There's '9' under the tuplet, so the stem should be a [headless](https://music.stackexchange.com/questions/122711/what-is-the-meaning-of-headless-notes) [nachschlag](https://en.wiktionary.org/wiki/Nachschlag). The ink drop spilled and the publisher thought Chopin made a mistake with the tuplet number and made it as a 10-tuplet. See this [screenshot of the German first edition from the IMSLP without a tuplet number](https://i.stack.imgur.com/5uYQC.png) and the [Karl Klindworth edition from IMSLP with the 10-tuplet number as well as a sub-group](https://i.stack.imgur.com/UmCmq.png)
Answer: Theoretically, you're right, I think. Strictly, the example you show should be read as "play these 10 notes with the same duration that 8 normal 16th notes would have", i.e., the total duration of a half note, which does not fit the meter.
This may be a typesetting mistake, or a simplification for readability (a lot of beam lines in this case don't give a lot of useful information and clutter the score). I'm not saying it's right, but it's quite clear in this presentation what you're supposed to do.
BTW, looking at the pencil markings, it should be noted that the composer (if that's what the composer actually wrote) chose to write a dectuplet and not two qintuplets. That division may be useful when learning the piece, but care must be taken that the 10 notes sound as a continous fluid phrase, not as two separate phrases.
Answer: In the fourth bar of the same Chopin prelude you also find something equally suspicious from the point of view of modern notation practice. There it's seven notes written with a single beam even though their duration is just a quarter note. You'd understand it from context there as well.
Septuples can be confusing, and many people mistakenly would write, say, a septuple over a half note with double beams because each note's duration is so close to a 16th note.
But the rule would be to have the number of beams that would make the tuple, if read as 8th, 16th, 32th (etc) notes longer than the timespan it fits into, but shorter than the double timespan. (Maybe this can be stated much more clearly by someone?)
Comment: I didn't see that septuplet further in the prelude (it isn't my sheet music), so there it is actually the same "mistake"?

I agree that a tuple is always about more notes than the normal notation. So in the example you describe it should indeed be eighth notes since it is 7 instead of 4 and should not be 7 instead of 8.
Comment: "equally suspicious from the point of view of modern notation practice": the takeaway here is that it's not precisely measured, and anyway the meter should be extremely flexible, so even the quarter notes won't all have the same duration.  I recently heard Ivo Pogorelić play music of this period, which I normally find rather boring.  When he played, it seemed that there was no simultaneity.  Nothing ever happened at the same time as anything else, and it was genius.  @LuKas whatever it should be by modern rules, it seems fairly clear that Chopin just wanted a bunch of notes played quickly.
Answer: On slow agogé it makes sense. But there is a big error in the score! the dectuplet must be formed by 10/32, NOT by 10/16 hehehe

Does this decuplet make sense?


Remove `/node` from front page when using a template file (page--front.tpl.php)

Question: As it stands I have no content going to the front page, i am simply using a template file for the front. When I sign out and sign in as any role of user on my site my front page url turns into:
www.mysite.com/node
I do not want this behavior, and have tried several methods but nothing seems to work.
I have tried adding this snippet to setting.php:
function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  if ($path == 'node') {
    $result = '';
  }
}
I have tried creating a custom module and have tried every suggestion from https://www.drupal.org/node/500296 nothing works.
I have encountered this behavior before, and to solve the issue i added the
Node Page Disable module and deselected the Retain /node as an active url? checkbox which removed the /node from the home page URL.
Now when I implement the module and deselect the checkbox and save the form, the checkbox goes back to being selected after the form is submitted. I cannot figure out what is going on, I have cleared every cache known to man-kind, used different machines and operating systems so obviously something is conflicting. I just don't know where to look.
I cannot post a bug/issue to the module page because drupal site is currently broken for creating new users... This is a nightmare. If anyone could give me some insight on possible conflicts or have any crazy ideas how I could get around removing this useless /node from the home page after a user signs in; it would mean the world to me. Thanks regardless.
Answer: I used Global Redirect and it seems to do the trick. I'll still accept someone else's answer if anyone can give any insight on what might of been the solution to my original issue.


Criar pasta em cada utilização do console

Question: Peguei um programinha pronto na internet pra criar pasta, dai tentei adaptar ele pra mim porem não estou conseguindo.
Gostaria de cada vez que eu executasse ele, criasse uma subpasta dentro da principal com um nome diferente, e que esse nome fosse o dia em que estivesse usando, daí se usasse o programa 2x no mesmo dia ele não apagasse a primeira pasta apenas ficasse como se fosse dupla ex 19/09... 19/09 (2).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class CreateFileOrFolder
{
    static void Main()
    {
        // Specify a "currently active folder"
        string activeDir = @"B:\Quality\QAS\FOTOS DO FERRAMENTAL";

        //Create a new subfolder under the current active folder
        string newPath = System.IO.Path.Combine(activeDir, "19/09/2017");

        // Create the subfolder
        System.IO.Directory.CreateDirectory(newPath);

        // Create a new file name. This example generates
        // a random string.
        string newFileName = System.IO.Path.GetRandomFileName();

        // Combina o arquivo com o caminho
        newPath = System.IO.Path.Combine(newPath, newFileName);

        // Criar arquivo e sobrescrever ele.
        // DANGER: System.IO.File.Create will overwrite the file
        // Se já existe ele pode ocorrer a criação de arquivos random
        if (!System.IO.File.Exists(newPath))
        {
            using (System.IO.FileStream fs = System.IO.File.Create(newPath))
            {
                for (byte i = 0; i < 100; i++)
                {
                    fs.WriteByte(i);
                }
            }
        }

        // Ler a data de volta para provar
        // se o código anterior funciona.
        try
        {
            byte[] readBuffer = System.IO.File.ReadAllBytes(newPath);
            foreach (byte b in readBuffer)
            {
                Console.WriteLine(b);
            }
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

        // manter o código aberto no debug.
        System.Console.WriteLine("Diretorio criado com sucesso, Pressione qualquer tecla para iniciar o programa de captura.");
        System.Console.ReadKey();
    }
}

Comment: E qual sua dúvida?
Comment: como eu crio varias subpastas com o nome diferente, uma não apagando a outra
Answer: Para não apagar a pasta e criar uma pasta(2), veja esta função:
void CriarPasta (string path)//Cria a função
{
    if (Directory.Exists(path)) //Verifica se já existe uma pasta com o mesmo nome
    {
        for (int i = 0; !Directory.Exists((path + "(" + i + ")")); i ++)//Verifica se exste uma pasta com o nome + (i)
        {
            Directory.CreateDirectory(path + "(" + i + ")");//Cria a pasta
        }
    }
    else // se não
      Directory.CreateDirectory(path);//Cria a pasta
}

Answer: Se o nome é o mesmo ela não será criada e nem apagará nada, não será feito nada, nem dará erro.
Eu melhorei um pouco, mas este código continua ruim.
using System;
using static System.Console;
using System.IO;

public class CreateFileOrFolder {
    public static void Main() {
        var activeDir = @"B:\Quality\QAS\FOTOS DO FERRAMENTAL";
        string newPath = Path.Combine(activeDir, DateTime.Now.ToString("yyyyMMdd"));
        Directory.CreateDirectory(newPath);
        newPath = Path.Combine(newPath, Path.GetRandomFileName());
        if (!File.Exists(newPath)) { //isto pode dar condição de corrida, mas vou deixar
            using (FileStream fs = File.Create(newPath)) {
                for (byte i = 0; i < 100; i++) {
                    fs.WriteByte(i); //isto é lento pra bedéu
                }
            }
        }
        byte[] readBuffer = File.ReadAllBytes(newPath);
        foreach (byte b in readBuffer) {
            WriteLine(b);
        }
        WriteLine("Diretorio criado com sucesso, Pressione qualquer tecla para iniciar o programa de captura.");
    }
}

Veja funcionando no Coding Ground. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Comment: Brigadão Cara, me ajudou muito


Automorphisms of algebraic groups

Question: I am working through Humphreys' Linear algebraic groups, and I am stuck on the following exercise ( ex 4 on pg 57)
I need to show that the only automorphisms of $G_m$ (as an algebraic group) is $x \mapsto x$ and $x \mapsto x^{-1}$. The thing is I don't see why the second one is a morphism. Since $G_m$ is just $k^* \subset \mathbb{A}^1$ under multiplication, and therefore shouldn't a morphism be a polynomial function?
Thank you.
Answer: This is why I dislike the definition of morphisms of varieties as polynomial maps: it's confusing for the notationally-minded. It is a polynomial map once you embed $\mathbb{G}_m$ into affine space, i.e. choosing the coordinate ring to be a quotient of a polynomial algebra. The coordinate ring of $\mathbb{G}_m$ is the $k$-algebra $k[x,x^{-1}]$, but you can recast it as a quotient of a polynomial ring as $k[x,y]/(xy - 1)$, showing a specific embedding into affine space. On $k$-points, the morphism becomes $(a,b)\mapsto (b,a)$, and of course $b = a^{-1}$. So you see that it is a polynomial map.

Automorphisms of algebraic groups


com.google.firebase.database.DatabaseException

Question: Procurei esse erro e não achei em lugar algum, apenas alguns parecidos mas não esse:

com.google.firebase.database.DatabaseException: Maps with non-string keys are not supported

Controller (onde está o erro):
final DatabaseReference banco = db.getReference("cidade");

//Pega os dados do banco
banco.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        arrayNome.clear();
        for(DataSnapshot data: dataSnapshot.getChildren()){
            Cidade c = data.getValue(Cidade.class);
            c.setKey(data.getKey());

            arrayNome.add(c);
        }
        adapterNome.notifyDataSetChanged();
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

String key = c.getKey();
Map<String, Object> postValues = c.toMap();

Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put(key, postValues);

banco.updateChildren(childUpdates); // <- ESSA LINHA

Model (onde está o método toMap()):
public class Cidade {
    private String key;
    private String nome;
    private String passagem;
    private ArrayList<Bairro> bairro;

    public Map<String, Object> toMap() {
        HashMap<String, Object> result = new HashMap<>();
        result.put("nome", nome);
        result.put("passagem", passagem);
        result.put("bairro", bairro);

        return result;
    }
}

Comment: O que é a variável `c`?
Comment: Minha classe model, `Cidade c`
Comment: O que é o método `getKey()`? Que string aparece no `key`?
Comment: `key` é a chave gerada pelo firebase ela é uma String privada, por isso tem um `get()`, editei e coloquei a parte que pega os dados do banco
Comment: @VictorStafusa esqueci de mensionar, que a variável `bairro` é uma classe
Comment: `banco.updateChildren(postValues);` no lugar de `banco.updateChildren(childUpdates);` funcionaria?
Comment: não, dá esse erro `Can't convert object of type java.util.ArrayList to type Cidade`
Answer: O problema era que a variável key estava null, faltou atribuir a chave gerada pelo firebase


How can I register an already uploaded unmanaged file as managed file?

Question: I am stuck in a point that should be easy but I couldn't figure it out.
To make a long story short; I uploaded manually some images to the public directory and now I want to register them as managed files but I am stuck for some time where I couldn't figure out how to do it.
I tried using system_retrieve_file but it seems to accept only URLs not local paths public:// as it uses cURL to get the file
Also, I tried using file_save_data with no luck as well for the same mentioned points.
Any ideas?
Answer: I ended up creating a new managed file, pretty easy as the following:
$user = \Drupal::currentUser()->id();
    $image = File::create([
    'uri' => $image_local_path,
    'uid' => $user,
    'status' => FILE_STATUS_PERMANENT,
  ]);
  $image->save();


Create a model from the given text (linear programming/optimization)

Question: I'm practicing for a linear programming test and here is a task I like to see if I did it correct and if not maybe how to do it correctly? Need to create a mathematical model whose requirements are represented by linear relationships.

A company wants produce two different kind of cars, $A$ and $B$. The
  production process is set up by these two things: installation and
  finishing. For the installation of $A$, the company needs $4$ hours
  and for the installation of $B$ they need $6$ hours. The finishing
  requires $6$ hours for car $A$ and $3$ hours for $B$. The profit for
  each car $A$ is $4000$ USD and for $B$ is $3000$ USD.
Dependent on other projects, the company has $720$ hours time for the
  installation and $480$ hours for the finishing within a
  production-cycle. The management requests for the duration of a cycle
  at least $20$ cars of kind $A$ and at least $30$ cars of kind $B$.
How many cars of each kind the company needs to produce within one
  cycle such that every (production-)condition is unhurt, the
  requirements of the management satisfied and the maximum profit is
  achieved?

Due to the long text, I like to keep it as short as possible. I have the following model:
$4000x_1 +3000x_2 \rightarrow \min$
$4x_1+6x_2 \geq 720$
$6x_1+3x_2 \geq 480$
$x_1 \geq 20$
$x_2 \geq 30$
Answer: The company wants to maximize the profit: $4000x_1 +3000x_2 \rightarrow \color{red}{\max}$

The company has (at most) 720 hours time for the installation:

$4x_1+6x_2 \color{red}{\leq} 720$

... and (at most) 480 hours for the finishing within a
  production-cycle:

$6x_1+3x_2 \color{red}{\leq} 480$
The other two constraints look O.K.
$x_1 \geq 20$
$x_2 \geq 30$
The linear programming can be solved graphically or with Simplex algorithm.


Pearson Correlation has quizzy results

Question: I investigated experiments with SPSS and following values were out.
I have a question that in which case is possible to get Feature 1 in Group A+B as significant p<.05 while either Group A and B has low significance in Feature 1?
I hardly interpret because Group A have low correlation and Group B also, but combined group have correlation with (very) high significance.

(* p<.05)
Answer: Here you have a simple example with made-up data: there are two groups $A$ and $B$ and two variables $X$ and $Y$. In both groups alone the correlation of $X$ and $Y$ are small (r = -.17 and .23), but if you combine them you see a linear trend (r = .67).

So, as you can see, this kind of relation is possible. Local relations (or lack of them) is not the same as global relations. You can read more on atomistic fallacy and ecological fallacy - i.e. logical errors when drawing conclusions on groups based on individual level data or individuals based on group level data.
Comment: Simpson's paradox is related. One statement is that amalgamation of subsets can result in changed magnitude and even sign of relationships.
Comment: @LinMa groups are groups as in the question.
Comment: @LinMa X,Y are r.v. (on x- and y- axis of the plots). A,B are groups. By saying that I "combine" them I mean that I look at all of the data (third plot) ignoring the grouping.
Comment: Thanks Tim, what means groups here? I think in order to do Pearson's r square analysis, we just need two one dimension random variable?
Comment: Thanks Tim, read the question and analysis again, and still feel confused about group here. I think X and Y are two random variable, and we draw its joint probability distribution in the plots here, it seems X and Y behaves different according to `group`? Is `group` some other random variable? And what means `+` in group A+B?
Comment: Imagine you have two tests X and Y (say on mathematics and English), two groups of students A and B made the tests (say two classes). You can look at the test results taken together (A+B) or on results for each of the classes alone.
Comment: Hi Tim, I think `X` and `Y`  means random variable, it is clear, and what means `group` here? Like group `A` and group `B`?
Comment: And you said "combine them", what exactly you do for `combine`?

Pearson Correlation has quizzy results


Find counterexample of gradient system with non globally convex energy function has globally asymptotic stable equilibrium point?

Question: Given $$\dot x=-\nabla f(x)$$
and suppose it has an equilibrium point $x=0$.
It is known that if $f(x)$ is globally convex, then $x=0$ is globally asymptotic stable.
I am interested its converse: can you find counter example that although if $f(x)$ is not convex everywhere (this is called globally convex right?), $x=0$ is still globally asymptotic stable?
Thanks in advance for any suggestion!
Answer: Try an example where $f$ is radially symmetric and increasing with distance from the origin, but is not convex.
Comment: Using for instance a variation of $f(x)=x+\varepsilon\sin(x)$, like $f(x^2+y^2)$ or $f(x)^2+f(y)^2$,...
Answer: Maybe the paper 1 provides an answer to this question at least in the local neighborhood of $x=0$:
First, it depends on the condition of the energy function $f(x)$.
If $f(x)$ is smooth function ($\in C^\infty$), it is possible that $x=0$ is locally stable, while $f(x)$ is not convex; And, it is possible that $f(x)$ is not convex, while $x=0$ is locally stable. The examples are provided in section 2.
If $f(x)$ is real analytical function, we have something much better: $x=0$ is
a stable equilibrium point if and only if it is a local minimum of $f(x)$.
Note:
In this post, I am asking about the convexity of $f(x)$, thus there is still a gap between convexity and local minimum, which remained to be addressed in the future couple of days.
This answer only addresses locally asymptotic stability, whereas global results still need open.
Papers:
[1] On the stable equilibrium points of gradient systems
[2] Asymptotically Stable Equilibria of GradientSystems (points out error in text books)


Intuition behind auto/cross-correlation

Question: I am really having trouble understanding the intuition behind autocorrelation. I mean why are we even calculating a correlation of some series with itself? Can anybody explain it in lay terms with an everyday example from life?
Also, I see that while calculating the ACF, we have to take lags.  But how does one know in advance how many lags to take so as to make them correlate better?
Answer: Your second paragraph, in a sense, hints at a answer to the first. In time series processes, where you are at point $t$ is partly dependent on where you were just recently, at point $t-1$. Observations in a time series are not independent in most cases. Whether your behaviour is driven or chaotic, you cannot just easily escape the position you were at immediately preceding time $t-1$. If a second ago you were in your kitchen you can't find yourself next moment in any place of you home with equal probability: you are likely to be somewhere still around your kitchen. Time series has "sliding memory". No wonder that it almost always has considerable autocorrelation with itself by lag 1.
Greater lag usually relaxes the autocorrelation since "memory" for the past vanishes. But if the behaviour is cyclic to some extent, with period $p$, you find yourself at $t$ close to where you were at $t-p$. Thus, the autocorrelation with lag $p$ will be strong enough, stronger than with lag $p-1$ or lag $p+1$. Autocorrelograms (ACF) and partial autocorrelograms (PACF) are the main tools to detect autocorrelations with various lags.
Cross-correlations are similar to autocorrelations, only here a time series is correlated not with itself (with a lag) but with some parallel time process (with a lag, lag might be 0).
Auto/cross correlations extend from time series to any series. A series of observations is their sequence. Are observations not random in that they are tied in a chain or in rings? Examining autocorrelations may discover it.
Comment: Thanks a ton for the explanation. You wrote -- "memory for the past vanishes" seems very intriguing. I think this "memory for past vanishes" might have also got some applications in human biology, eg gene sequences and protein sequences , if you might be aware of any ? This correlation seems to be very interesting topic. Do you have any good blog/pop-sci suggestions on the same ?
Comment: Sorry, because my answer was immediate and pointedly intuitive, I didn't think of any sources myself, in particularly with popular explanations. But I'm sure that googling will bring you to a number of pages you are looking for.
Answer: One reason I've used auto-correlation is to determine how often I should sample a time series.  I run simulations that produce time series; I store the value of the output every so often so that I can determine, e.g., the mean of the time series.  There is generally no point in storing consecutive values of the time series since consecutive samples of the time series won't be independent and so won't reduce my estimation error.  Only if I wait until the series has decorrelated can I take an independent sample of the time series (possibly eliding some subtleties).  Put another way, given that I've sampled a time series to calculate its mean, I need to know the auto-correlation time to determine how accurate my estimates will be: assuming that the standard error goes down like $1/\sqrt(N)$ will only work if the samples are independent.
Comment: Thats tough to digest. Could you please simplify it with a simple example  !!!!

Intuition behind auto/cross-correlation


Prove $\sum\limits_{\mathrm{cyc}}\frac{a}{a^2+bc+4} \leq \frac{1}{2}$ for $a,b,c>0$ with $a+b+c=6$

Question:
Prove that for $a, b, c > 0$ where $a + b + c = 6$, the following inequality holds:
$$ \frac{a}{a^2+bc+4} + \frac{b}{b^2+ca+4} + \frac{c}{c^2+ab+4} \leq \frac{1}{2}. $$

From the AM-GM inequality, we find that $ abc \leq 8 $. I attempted to express the first denominator as $(6-b-c)^2+bc+4 = (b+c)^2 - 12(b+c) + bc + 40$. Substituting every $a$ in the inequality with $6-b-c$, the calculations seemed too complicated. I also explored exploiting monotonicity after achieving a common denominator for each fraction.
Comment: math.enthusiast9, what did you try in order to solve your exercise ? Read [this thread](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question) and learn how to ask a good question on this site. Your post is being closed by moderators because it is a very low-quality question.
Answer: Proof.
By AM-GM $a^2+4\ge 4a.$ It implies $$a^2+bc+4\ge 4a+bc \iff \frac{a}{a^2+bc+4}\le \frac{a}{4a+bc}.$$
And we'll prove stronger inequality$$\frac{a}{4a+bc}+\frac{b}{4b+ca}+\frac{c}{4c+ab}\le \frac{1}{2}$$
$$\iff \frac{4a+bc-bc}{4a+bc}+\frac{4b+ca-ca}{4b+ca}+\frac{4c+ab-ab}{4c+ab}\le 2
$$
or$$\frac{bc}{4a+bc}+\frac{ca}{4b+ca}+\frac{ab}{4c+ab}\ge 1.$$
Notice. Equality holds iff $a=b=c=2,$ also for $a=b=3,c=0$ and its permutations.
Now, using Cauchy-Schwarz inequality$$\sum_{\mathrm{cyc}}\frac{bc}{4a+bc}\ge \frac{(ab+bc+ca)^2}{12abc+(bc)^2+(ca)^2+(ab)^2}=\frac{(ab+bc+ca)^2}{2abc(a+b+c)+(bc)^2+(ca)^2+(ab)^2}= 1.$$
Hence, the proof is done. Equality holds iff $a=b=c=2.$
Comment: How does the first inequality found from AM-GM imply the second inequality?
Comment: I added something. See now.
Comment: How does proving this $$\frac{bc}{4a+bc}+\frac{ca}{4b+ca}+\frac{ab}{4c+ab}\ge 1.$$ (2) proves the first inequality. That's the part I don't understand. How did you get (2)?
Comment: @math.enthusiast9 It's equivalence. I added something.


GPIB connection to external device using MATLAB

Question: Is there a way to establish a GPIB connection using MATLAB without the instrument control Tool box? (I don't have it). Also is there a way for MATLAB to know what the external device's RS232 parameter values are ( Baud rate, stop bit etc..). For the RS232 connection I have the following code:
% This function is meant to send commands to Potentiostat Model 263A.

% A run includes turning the cell on, reading current for time t1, turning

% the cell off, waiting for time t2.

% t1 is the duration [secs] for which the Potentiostat must run (cell is on)

% t2 is the duration [secs] to on after off

% n is the number of runs

% port is the serial port name such as COM1

function [s] = Potentiostat_control(t1,t2,n)

port = input('type port name such as COM1', 's')

s = serial(port);

set(s,'BaudRate', 9600, 'DataBits', 8, 'Parity', 'even', 'StopBits', 2 ,'Terminator', 'CR/LF');

fopen(s)

%fprintf(s,'RS232?')

disp(['Total runs requested = ' num2str(n)])

disp('i denotes number of runs executed so far..');

for i=1:n

    i

    %data1 = query(s, '*IDN?')

    fprintf(s,'%s','CELL 1'); % sends the command 'CELL 1'

    %fprintf(s,'%s','READI');

    pause(t1);

    fprintf(s,'%s','CELL 0');

    %fprintf(s,'%s','CLEAR');

    pause(t2);

end

fclose(s)

Answer: For your GPIB question, does the GPIB card come with a callable library (DLL if you're on Windows)?  Matlab has an interface for calling external libraries.  The basic procedure is to have Matlab parse the header file using LOADLIBRARY, then view the available functions using LIBFUNCTIONS and call functions using CALLLIB.
For your RS232 question, I don't think there's any way for the host side to know the device side's parameters without external documentation.
Comment: Thanks mtrw. I will look in to it
Answer: I'm using National Instruments VISA and NI 488.2.
First make sure that you checked the VisaNS.NET API in the NI-VISA Setup, see the following figure:

I'm using the NationalInstruments.VisaNS.MessageBasedSession over the .NET interface from MATLAB.
I've written the following MATLAB class that wraps NI VISA to MATLAB:
classdef Visa
    properties
        vi
        SrqMask
        SrqTimeout
    end
    methods
        function obj = Visa(resourceName)
            NET.addAssembly('NationalInstruments.VisaNS');
            obj.vi = NationalInstruments.VisaNS.MessageBasedSession(resourceName);
            obj.SrqMask = '*CLS;*ESE 1;*SRE 32';
            obj.SrqTimeout = 10000;
        end
        function obj = delete(obj)
            obj.vi.Dispose();
        end
        function obj = Dispose(obj)
            obj.vi.Dispose();
        end
        function obj = Write(obj, data)
            obj.vi.Write(data);
        end
        function data = ReadString(obj)
            data = char(obj.vi.ReadString());
        end
        function data = ReadByteArray(obj)
            data = obj.vi.ReadByteArray();
        end
        function data2 = Query(obj, data)
            data2 = char(obj.vi.Query(data));
        end
        function obj = SrqBegin(obj)
            obj.vi.EnableEvent(NationalInstruments.VisaNS.MessageBasedSessionEventType.ServiceRequest, ...
                NationalInstruments.VisaNS.EventMechanism.Queue);
            obj.vi.DiscardEvent(NationalInstruments.VisaNS.MessageBasedSessionEventType.ServiceRequest);
            obj.Write(obj.SrqMask);
        end
        function status = SrqEnd(obj)
            evt = obj.vi.WaitOnEvent(NationalInstruments.VisaNS.MessageBasedSessionEventType.ServiceRequest, ...
                obj.SrqTimeout);
            evt.Dispose();
            status = obj.vi.ReadStatusByte();
            obj.vi.DisableEvent(NationalInstruments.VisaNS.MessageBasedSessionEventType.ServiceRequest, ...
                NationalInstruments.VisaNS.EventMechanism.Queue);
        end
        function obj = SrqWrite(obj, data)
            obj.SrqBegin();
            obj.Write(data);
            obj.SrqEnd();
        end
        function data2 = SrqQuery(obj, data)
            obj.SrqBegin();
            obj.Write(data);
            obj.SrqEnd();
            data2 = obj.ReadString();
        end
    end
end

I've added as well some methods to handle the SRQ request.
With the following code you can control GPIB instrument for example:
resourceName = 'GPIB0::20::INSTR'; % GPIB adapter 0, Instrument address 20
vi = Visa(resourceName);
idn = vi.QueryString('*IDN?');

A MessageBasedSession can be used to communicate with your instrument over GPIB, Ethernet or USB.
See as well https://stackoverflow.com/a/49388678/7556646.
Answer: I don't know about the RS232 parameters, but for an instrument with tcpip, you can send SCPI commands really easy.
Here is an example where I send a SCPI command to a Rohde&Schwarz instuments. No VISA or IVI needed. Use port 5025.
t = tcpip('18.104.22.168', 5025);
fopen(t);
fprintf(t, '*IDN?');
fprintf(1, DataReceived)

Then close the connection when you are done:
fclose(t);
delete(t);
clear t


Linear discriminant analysis-Do we maximize posterior or joint distribution?

Question: My understanding is that in LDA, we maximize the joint density $ P(X,y) $ using $P(X|y)$ rather than posterior density $P(y|X)$ using $P(X|y)$. In the book "Introduction to Statistical learning with R", the authors say otherwise. Though they do not provide a derivation, they say the expressions for $P(y|X)$ are to be maximised.
https://hastie.su.domains/ISLR2/ISLRv2_website.pdf
See equation 4.15 and 4.17 and paragraphs around them.
Answer: Maximizing the joint density is equivalent to maximizing the posterior because the denominator is the common term across classes, i.e. $P(X)$. In addition to  $P(X|y)$, $P(y)$ is also used in the process as class prior.
Comment: Your argument works for prediction 'after' the estimates are done. However, the estimates for $\mu_k$ etc are done by maximizing the joint density (by multiplying over all observations). If we want to take partial derivatives of posterior instead of joint distribution, the expressions become very complicated due to the denominator.


Find the density function of $(U,V)$

Question: Let $X=(X_1,X_2)^T$ be a random vector with 2-dimensional normal distribution, $E(X_1)=E(X_2)=0 , \operatorname{Var}(X_1)=\operatorname{Var}(X_2)=1$ and $\operatorname{Cov}(X_1, X_2)= \nu$ with $|\nu| <1$. And let $Z \sim \mathrm{Bin}(1,\alpha)$ be independent from $(X_1,X_2)$ and $(U,V)^T := Z(X_1,X_2)^T+(1-Z)(-X_1,X_2)^T.$
I know that $(-X_1,X_2)$ has also normal distribution.
Now I want to find the density function of $(U,V)$.
As a hint: I need to use the formula of total probability.
Futher I would like to find the marginal distribution of $U$ und $V$.
Can you help me, please?
Answer: Hint: consider, from LOTP $$P(U=u, V=v) = P(U=u, V=v \lvert Z = 1) P(Z=1) + P(U=u, V=v \lvert Z = 0)P(Z=0)$$
Also remember that two-dimensional vector of two normals is:
$$(X_1, X_2) \sim N( (\mu_1, \mu_2), \begin{pmatrix} \operatorname{Var} X_1 & \operatorname{Cov}(X_1, X_2) \\ \operatorname{Cov}(X_1, X_2) & \operatorname{Var}(X_2) \end{pmatrix} )$$, which means that:
$$
p(x_1, x_2) \propto \exp( - (x_1 - \mu_1, x_2 - \mu_2)^T \Sigma^{-1} (x_2 - \mu_1, x_2 - \mu_2))
$$
where $\Sigma$ is covariance matrix from second equation. Overall, $\mu_i$ mean respective expected values. In your case these are going to be zero.
Then integrate to find marginal distributions of $U, V$:
$$p(u) = \int p(u, v) dv$$

Find the density function of $(U,V)$


Can a GAN be used for tabular/vector data augmentation?

Question: Can a generative adversarial network (GAN) be used for data augmentation (i.e. to generate synthetic examples that are added to a dataset) for data that is tabular/vectorized (i.e. not an image)? Are there any public implementations of methods to this effect.
I am aware of the following papers on images:
https://arxiv.org/abs/1711.04340
https://arxiv.org/abs/1801.05401
https://arxiv.org/abs/1803.01229
Answer: GANs are primarily used for data augmentation. If you have 1D signals you could use MLP or 1D convolutions. Hope those links will help: http://www.rricard.me/machine/learning/generative/adversarial/networks/keras/tensorflow/2017/04/05/gans-part2.html https://github.com/timzhang642/GAN-1D-Gaussian-Distribution
Answer: Of course, you can generate some new data as data augmentation, check out
Take look at review two recent papers https://towardsdatascience.com/review-of-gans-for-tabular-data-a30a2199342
With code https://github.com/Diyago/GAN-for-tabular-data


Pandas - Problemas com ".loc[]" em múltiplas entradas

Question: Meu projeto possui 4 inputs dado pelo usuário que são armazenados nas variáveis a, b, c, d.
Uso essas entradas para filtrar informações vindas de um .csv gigante, armazenando-as em um dataframe. O filtro é feito usando "loc[]", da seguinte forma:
arquivo = chunk.loc[(chunk['Coluna1'] == a) & (chunk['Coluna2'] == b) & (chunk['Coluna3'] == c) & (chunk['Coluna4'] == d)]

O problema é que o usuário pode ou não preencher os 4 inputs. Preciso que o método "loc" seja capaz de filtrar informações mesmo quando por exemplo, o usuário dê input na variável "a" e deixe as outras em branco.
Da maneira que montei, as variáveis que não receberam informações, recebem o a string: "". O ".loc[]" então tenta achar linhas onde a coluna em questão tem "".
Pensei que uma solução possível, seria atribuir um "valor coringa" às variáveis não preenchidas, porém não sei se isso é possível.
Answer: Creio que isso possa ser feito não na chamada do loc, mas sim quando você obtém as variáveis pelo usuário. Primeiro, precisamos considerar uma entrada que o usuário não forneceu como None. Atualmente, você está considerando uma string vazia (''). Precisamos então convertê-la:
def retorna_variavel(nome):
    # Insira aqui o código para obter a entrada do usuário pela interface
    # gráfica. Estou assumindo que a entrada esteja sendo obtida por meio
    # de uma caixa de texto por exemplo, portanto ela será do tipo string
    texto = retorna_variavel_de_caixa_de_texto(nome)

    # Verifica se o usuário não digitou nada. Essa verificação é equivalente
    # à `if texto is None or len(texto) == 0:`
    if not texto:
        return None

    # Converte a variável inserida pelo usuário para um tipo inteiro. Você
    # também pode convertê-la para o tipo ponto flutuante utilizando `float`.
    return int(texto)

Em seguida, você cria as variáveis a, b, c e d desejadas:
a = retorna_variavel('a')
b = retorna_variavel('b')
c = retorna_variavel('c')
d = retorna_variavel('d')

Por fim, você pode utilizar o seguinte código para filtrar o pd.DataFrame:
import pandas as pd

# Um DataFrame de exemplo
chunk = pd.DataFrame({
    'Coluna1': [1, 1],
    'Coluna2': [2, 2],
    'Coluna3': [3, 3],
    'Coluna4': [5, 6],
})

arquivo = chunk.loc[
    (a is None or chunk['Coluna1'] == a) &
    (b is None or chunk['Coluna2'] == b) &
    (c is None or chunk['Coluna3'] == c) &
    (d is None or chunk['Coluna4'] == d)]

print(arquivo)

Neste exemplo,

caso a == 1, b == 2, c == 3 e d == 4, a saída será

Empty DataFrame
Columns: [Coluna1, Coluna2, Coluna3, Coluna4]
Index: []

caso a == 1, b == 2, c == 3 e d == 5, a saída será

   Coluna1  Coluna2  Coluna3  Coluna4
0        1        2        3        5

caso a == 1, b == 2, c == 3 e d == 6, a saída será

   Coluna1  Coluna2  Coluna3  Coluna4
1        1        2        3        6

caso a == 1, b == 2, c == 3 e d == None (o usuário omitiu o valor de d), a saída será

   Coluna1  Coluna2  Coluna3  Coluna4
0        1        2        3        5
1        1        2        3        6

Como d foi omitido, todos os valores da coluna 4 foram retornados.
Comment: Essas entradas são dadas por uma interface gráfica. Necessariamente recebo valores para todas as 4, porém as que não são preenchidas, recebo: "".

Na minha lógica, precisava que a função loc ignorasse as variáveis não preenchidas, mas não estou conseguindo pensar num jeito de fazer isso...

A variável coringa que quis dizer, seria um valor pelo qual a função loc buscaria na respectiva coluna, mas que trouxesse qualquer coisa, entende?
Comment: Entendi, peço desculpas pelo mal entendido. Atualizei a minha resposta, veja se isso resolve seu problema.
Answer: Você pode fazer o teste iterativamente?
Por exemplo, assumindo que seu DataFrame tenha as colunas v_a, v_b, v_c e v_d e as variáveis que vc recebeu são a, b, c e d que podem ou não ser iguais a "":
df_filtrado=df_original
for (col,valor) in {'v_a':a,'v_b':b,'v_c':c,'v_d':d}.items():
    if valor != "":
        df_filtrado=df_filtrado[df_filtrado[col]==valor]

Ao final, seu DataFrame filtado terá aplicado os filtros desejados apenas quando eles forem diferentes de "".
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Is this a property of an integral domain that is not a field?

Question: I am working on a specific problem and I've almost got it solved. To solve it, however, I need to prove one last claim (if it is even true):

Consider an integral domain $R$ that is not a field. Let $a$ be an element of $R$ that is not a unit or $0$. I want to prove that there cannot exist nonzero elements $r_n$, $n \in \mathbb{N}$, of $R$ such that
$$ r_1 a=r_2a^2=r_3a^3=\cdots= r_na^n=\cdots$$

First of all, is this even true? My intuition says it is. And am I missing something obvious?  This is the last step in a long proof, so I hope it is true!
EDIT: It turns out my proof goes through without this being true (which is good since it's false), but definitely thanks for the answers. It has improved my understanding.
Comment: Well, if you have something like that then you can manufacture a strictly increasing sequence of ideals, so if you know you have a _noetherian_ ring you would have a contradiction.
Comment: @MartianInvader But 2 is a unit in that ring.
Comment: I have a feeling this might fail in a ring which contains an element which cannot be factored into irreducible elements.
Comment: So this does hold in, a UFD for instance.
Comment: The "not a field" requirement seems artificially added to get rid of the obvious finite-field examples like $2 \in \mathbb{Z}_3$.  But you could easily extend to, say, $2 \in \mathbb{Z}_3[x]$, and then it's no longer a field but still a counterexample.
Answer: This is false. As Zhen Lin points out, $R$ can't be Noetherian, so let $R$ be my favourite non-Noetherian domain, $\{f(x)\in \Bbb{Q}[x]\mid f(0)\in \Bbb{Z}\}$, and consider $a=2$. Then $$x=2\frac{x}{2}=4\frac{x}{4}=8\frac{x}{8}=\ldots$$ but $2$ is not a unit.
Comment: Aha! I was trying to extract this from non-standard integers example, but I hadn't realized the ring had such a simple description!
Comment: @Hurkyl, are you saying that the ring provided by Chris Eagle is isomorphic to nonstandard integers?
Comment: @PrimeRibeyeDeal: No, but it is isomorphic to a subring of the nonstandard integers (send $x \to 2^H$). ("subring" is given its standard meaning)
Comment: @Hurkyl, what is $2^H$ in this context? Is there a "nice" description of the nonstandard integers as a ring?
Comment: @PrimeRibeyeDeal: My comments were referring to my answer in this thread. Re your other question, the only "nice" description of the nonstandard integers I know of is that it is a nonstandard model of the integers.
Answer: No. Let $R = \mathbb{Z}[\frac{1}{x}, 2x, 2x^2, 2x^3, ...]$, let $r_i = 2x^i$, and let $a = \frac{1}{x}$.
Comment: $a$ was specified not to be a unit.
Comment: @Greg: fixed. ${}$
Answer: Let $R = {}^\star \mathbb{Z}$ be the hyper-integers; that is, the ring of integers in a non-standard model of real analysis.
Let $H$ be an infinite hyper-integer.
Then, we can choose $a = 2$ and $r_i = 2^{H - i}$ to get a counter-example.
Comment: @Qiaochu Yuan: Yes. And in that case, we might as well make an explicit choice of $H$ and set $r_i = ( 2^{-i}, 2^{1-i}, 2^{2-i}, \cdots )$.
Comment: Hum. If I construct the nonstandard reals via an ultraproduct, does this denote the subring of the nonstandard reals which are a.e. equal to an integer?
Answer: Let $R$ be the ring of functions $[0,1]\to \mathbb R$ that are analytic in $(0,1]$ and  continuous on $[0,1]$.
Let $a$ be the function $x\mapsto x$.
It is not a unit because $a(0)=0$.
For each $n\in \mathbb N$, let
$$r_n(x)=\begin{cases}x^{-n}e^{-\frac1x}&\text{if }x\ne 0\\0&\text{if }x=0\end{cases}$$
Note that $r_n$ is analytic in $(0,1]$ and is continuos also at $0$.
We have $$(a^nr_n)(x)=\begin{cases}e^{-\frac1x}&\text{if }x\ne 0\\0&\text{if }x=0\end{cases}$$
Comment: That's not a domain.
Comment: @anonymous D'oh, you are right. I started off at polynomials and needed more and more. But continuous is of course too big a ring. I had to tighten the conditions to (almost) analytic, but now it's an ugly example.


Peak Height of $\operatorname{sinc}^2(x)$

Question: Consider the following equation,
$$f(\omega) = \frac{\Omega ^2}{\hbar^2}\frac{\sin^2[ (\omega_0 - \omega)t/2]}{(\omega_0 - \omega)^2}$$
As a function of $t$, the graphs looks like $\sin^2t$. As a function of $\omega$, the graph looks like $\DeclareMathOperator{\sinc}{sinc} \sinc ^2(x)$ shifted over to $\omega = \omega_0$. My textbook then says that $f(\omega)$ has a peak height of
$$\bigg( \frac{\Omega t}{2\hbar} \bigg)^2$$
My question is, how did they get this peak height? If the $\sinc^2$ function was only a function of $w$ and not $t$, I'd imagine that the peak height would be just $(\Omega/\hbar)^2$
Comment: Use $$\lim_{x\rightarrow 0} \frac{\sin x}{x} = 1$$
Answer: Use the Taylor series at $x=0$ of  $$g(x) = \left(\frac{\sin(ax)}{x}\right)^2
= \left(a-\frac{1}{6}a^3x^2+O(x^4)\right)^2
= a^2- \frac{1}{3}a^4x^2+O(x^4)$$
Now substitute $a=\frac{t}{2},\,x=\omega-\omega_0,\,$ multiply with $\frac{\Omega ^2}{\hbar^2}$ and get
$$f(\omega_0) = \left(\frac{t}{2}\right)^2 \times \frac{\Omega ^2}{\hbar^2} = \left( \frac{\Omega t}{2\hbar} \right)^2$$


Counting number of items between two values

Question: I have a list of cargo items, each with a Quantity, Length, Width, Height and Weight. I'm trying to produce a summary of how their dimensions are distributed (ideally taking the quantities of each into account, but that's a step beyond where I'm stuck).
I have one spreadsheet with length values in 0.1m intervals in Statistics!A2:A302, and I'm hoping to put the quantity for each length interval in Statistics!B2:B302. The quantities per item are in 'Steel plate list'!$B$3:$B$1002, and the lengths to look at are in 'Steel plate list'!$C$3:$C$1002.
Now, at the moment I have the following formula in Statistics!B2 and filled down:
=COUNTIFS('Steel plate list'!$C$3:$C$1002, ">="&A2, 'Steel plate list'!$C$3:$C$1002, "<"&A3)

That works fine, gives me the number of line items that have that length, but it means that, for instance, a single 8-metre plate counts as heavily as 260 12-metre plates. Is there any way to take the quantities into account? I've thought of using a VLOOKUP for it, but I can't think of a way to make that work.
Any thoughts?
Answer: Instead of COUNTIFS, you should be using SUMIFS. SUMIFS works like COUNTIFS, except that it adds all rows which match your criteria, instead of simply counting them.
So your formula would look almost identical to what you currently have [the first argument passed to SUMIFS is the range which you want summed, and the following arguments alternate as being either the range to look for a criteria, or the criteria to use agaisnt that range]:
=SUMIFS('Steel plate list'!$B$3:$B$1002,'Steel plate list'!$C$3:$C$1002, ">="&A2, 'Steel plate list'!$C$3:$C$1002, "<"&A3)

As you can see, apart from changing the function from COUNTIFS to SUMIFS, all I needed to do was add the first argument referencing column B on the other sheet, which holds the quantities for each row matching all criteria.
Answer: To sum the quantity (not sum the dimensions) of the pieces you can use this array formula:
=SUM(IF('Steel plate list'!$B$2:$B$10>=A2,IF('Steel plate list'!$B$2:$B$10<A3,'Steel plate list'!$A$2:$A$10,0),0))

Press Ctrl+Shift+Enter to create the array formula.
This assumes that column A contains Quantity and column B contains Length.
The formula will show that you have how many pieces for a given dimension on the Statistic page. Example, 1 piece of 8-meter and 260 12-meter pieces.
Comment: @Bacon, You are correct. Array formulas do have their drawbacks. I should point out that both of our formulas have a slight flaw.  We're using cell A3 in the criteria.  At the end of the list (e.g. cell A302), there will be no value in A303 to compare.  We should use "<A2+0.1" to compare.
Comment: This will work, but it is effectively just a recreation of the SUMIFS function, which was purpose-built by Excel for exactly this type of scenario. Array Formulas have drawbacks and should be avoided where possible - compared with a 'Natural Array Formula' like SUMIFS, Array Formulas need to be entered with CTRL + SHIFT + ENTER [as you indicated], which can make a subsequent user accidentally wreck the formula by entering the cell and pressing tab. Also, they are more computationally intensive, and are (somewhat) harder to understand.


Module endomorphisms

Question: Let $R$ be a ring, $M_R$ a right module over $R$.
Let $S:=$ End($M_R)$
I have shown that $R \subseteq$ End$(_SM)$
(pick $r \in R$, then define $f_r(m)$ via $m \mapsto mr$ show $f_r \in$ End$(_SM$))
I have to show proper containment via example.
So an endomorphism of $_SM$ (so scalars are also Endomorphisms) that is not a ring element, I get stuck here, so I need to find an explicit map that is an endomorphism but cannot be a ring element?
Answer: First, the homomorphism $R\to \mathrm{End}({}_SM)$ is an embedding only if $M_R$ is faithful, that is $Mr=0\implies r=0$.
For an example, let $R=\Bbb Z,\ M=\Bbb Q$, then $S\cong\Bbb Q$ as a $\Bbb Z$-endomorphism of $\Bbb Q$ is uniquely determined by the image of $1$.
But we also have $\mathrm{End}({}_SM)\ =\ \mathrm{End}({}_{\Bbb Q}\Bbb Q)\ \cong\ \Bbb Q$ which is a proper superset of $R=\Bbb Z$, and a specific map you're looking for is multiplying by any noninteger rational number.

Module endomorphisms


Using ng-attr-href from angular to direct user interaction

Question: So what I am trying to do is for an icon (link), the user will have already logged on and there is a property identified that is true or false. Based on whether that property is true or false, when the user clicks that icon (link), it will take them to one of 2 pages. So looking at different directives within angular, thought I could use ng-switch, but that doesn't seem viable so I thought ng-attr-href could do it. Trying something like (this is pseudo code):

So this is like an if/else where when user clicks icon and that value true, they go one place, but if false, they go elsewhere. My difficulty is structuring that and how/where the else goes.
Is there a better way to do this than I am thinking based on what I shared?
Thanks much.
Adding to, where could this be wrong?:

Submit a Claim for Reimbursement

Answer: Can use a ternary within  a {{}} expression in ng-href

Comment: Is the "?" mean to be the property? so object.value == 'false' ? 'somepage.html' : ..... ?
Comment: Added some additional detail hoping to get further input.
Answer: Put a function inside your controller to provide the value, then call it inside the ng-href. This type of decision of which link to go is the controller's responsibility.
ng-href="whereToGo(object.value)"

Comment: The ? operator works as an if... object.value ? "url1" : "url2"
Comment: value is the property in this case. so is {{ object.property }} . That said, I understand the controller's responsibility. Just not sure I am understanding the syntax within the view as labeled. Meaning, so you saying that {{ function in controller ? whereToGo : another whereToGo }}. Do you see where I am lost?
Comment: I dont see why you are struggling with this... but the ternary operator could be used... but in this case I would go with the ng-click instead of ng-href
Comment: I am trying to understand what the '?' operator in there is supposed to do within the tenary. Guess it is trying to provide an 'if'. How would the ng-click go into this with an 'if'?


Multiple files created by arecord

Question: I've made custom distribution using buildroot, with hard-flow for ARMv7 processor.
Everything is working except....
# arecord -D hw:0,0 -fdat -d 5 test.wav

This makes multiple files. Thousands of them.
-rw-r--r--    1 root     root        958508 Jan  1 00:19 test-01.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-02.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-03.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-04.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-05.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-06.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-07.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-08.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-09.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-10.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-100.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-101.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-102.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-103.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-104.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-105.wav
-rw-r--r--    1 root     root            44 Jan  1 00:19 test-106.wav

And so on...
This happens if I pass -d parameter. Any idea?
Comment: Have you checked the audio settings with *amixer* or *alsamixer*?  You need to enable record sources.  I guess you mean *hard-float*?  But that should not matter.  You might also try `-N`, in case the driver is buggy.
Comment: In theory, the first file should have 960044 bytes. This looks as if 64-bit arithmetic is not handled correctly.
Answer: The problem seems to appear on ARM architecture starting from 1.0.28 arecord version (arecord --version).
On Raspberry Pi 3 running Raspbian Jessie I managed to downgrade alsa-utils from 1.0.28-1 to 1.0.25-4 (rolling back to Wheezy's repo), so that fixed the problem:

sudo nano /etc/apt/sources.list
add the following line to the end of the file deb http://mirrordirector.raspbian.org/raspbian/ wheezy main contrib non-free rpi
sudo apt-get update
sudo aptitude versions alsa-utils (this should show the old version to become available)
sudo apt-get install alsa-utils=1.0.25-4
now arecord --version should display downgraded version 1.0.25
You probably now want to remove that line you added to /etc/apt/sources.list, so that you don't get other packages from wheezy
sudo nano /etc/apt/sources.list
remove the line deb http://mirrordirector.raspbian.org/raspbian/ wheezy main contrib non-free rpi
run apt-get update again
also, put alsa-utils on hold so it doesn't get upgraded
sudo apt-mark hold alsa-utils
Answer: As an alternative solution is to upgraded alsa-utils to the latest version 1.1.3 from source. This is how I have done it on my Raspberry Pi 3

mkdir ~/alsa-utils
cd ~/alsa-utils/
wget ftp://ftp.alsa-project.org/pub/utils/alsa-utils-1.1.3.tar.bz2
tar xvjf alsa-utils-1.1.3.tar.bz2
cd ~/alsa-utils/alsa-utils-1.1.3/
sudo apt-get install libncursesw5-dev
./configure --disable-alsaconf --disable-bat --disable-xmlto --with-curses=ncursesw
make
sudo make install
arecord --version
Comment: Latest version as of 2018 January is 1.1.5, just update the version number accordingly in the commands.

Multiple files created by arecord


Tela de carregamento/Loading screen

Question: Como fazer uma tela similar a essa no android?
Fazendo a barra encher
Answer: Tente da seguinte forma:
activity_main.xml

<TextView
    android:text="Loading ... Please Wait"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/progressBar"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="36dp"
    android:id="@+id/textView" />

<ProgressBar
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/progressBar"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="170dp" />

MainActivity.java
public class MainActivity extends AppCompatActivity {

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

         progressBar = ProgressBar.class.cast(findViewById(R.id.progressBar));

    }

    @Override
    protected void onStart() {
        super.onStart();
        new Loader().execute((Void)null);
    }

    class Loader extends AsyncTask<Void, Void, Void> {

        private Integer update = 1;
        @Override
        protected Void doInBackground(Void... params) {

            // iteramos ate 100
            while (update <= 100){
                // Criamos um Runnable q ira mandar a atualizacao desta Thread par a tela!
                final Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        // seta o valor atualizado na tela
                        progressBar.setProgress(update);
                    }
                };
                // executa o Runnable na ThreadUI
                runOnUiThread(runnable);
                update++;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            return null;

        }

        @Override
        protected void onPostExecute(Void aVoid) {
           // AQUI SERA CHAMDO AO TERMINAR DE CARREGAR

        }
    }

}

Answer: Utilize ProgressBar, com o indeterminateOnly true, e com o estilo Widget.ProgressBar.Horizontal, dessa forma:
<ProgressBar
    android:id="@+id/progress"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tvProcessing"
    android:indeterminateOnly="true"/>

Style:
style="@android:style/Widget.ProgressBar.Horizontal"

E ai se você quiser crie um drawable e coloque como background, para personalizar o layout
Fonte

Tela de carregamento/Loading screen


If $p$ mod $4=1$, how many elements of order $4$ are in $GF(p^n)^*$

Question: If $p$ mod $4 = 1$ then how many elements of order $4$ are in $GF(p^n)^*$
I know it has something to do with $GF(p^n)^*$ being isomorphic to $Z_4$, thus having $2$ elements of order $4$, but I am not sure the steps in between, any help would be appreciated.
Comment: $GF(p^n)^*$ is *not* isomorphic to $Z_4$.
Comment: It has everything to do with the fact that $GF(p^n)^*$ is cyclic (of order $p^n-1$, not four). The number of elements of order $d$ in a cyclic group of order $k$ is zero, if $d\nmid k$, and $\phi(d)$ is $d\mid k$.
Answer: $\newcommand{\GF}{\mathrm{GF}}$You should know that the multiplicative group $\GF(p^{n})^{*}$ is cyclic, hence it has a unique subgroup of order $m$ for each divisor $m$ of its order $p^{n} -1$, and each of these subgroups is cyclic.
Now you know that $4$ divides $p-1$, and thus $m = 4$ divides $p^{n} - 1 = (p-1) (p^{n-1} + p^{n-2} + \dots + p + 1)$.
So $\GF(p^{n})^{*}$ has exactly one subgroup of order $4$, which is cyclic, and thus has exactly two elements of order $4$.
Answer: Since we're in a field, the equation $x^4=1$ has at most $4$ solutions.
$-1$ and $1$ are two solutions but they don't have order $4$.
When $p \equiv 1 \bmod 4$, we have two other solutions: $\pm \left(\dfrac{p-1}{2}\right)!$ . $\quad$(*)
These are the two elements of order $4$ in $GF(p^n)$, and they live in the prime field $GF(p)$.
(*) This follows from Wilson's theorem.


How can I debug internet server on Windows VirtualBox using NAT and port forwarding?

Question: I am using a program called Memoq that listens on port 2705. I would like to make it accessible from the internet, but it is failing for unknown reasons.
The setup looks like this:
Internet -> Router -> Server -> Virtualbox computer with Memoq
I set the router to forward port 2705 to the server and Virtualbox to forward port 2705 from host to guest (using NAT). I disabled firewall on both computers (they run Windows).
If I try to telnet to port 2705 from virtualbox and server it works, but if i do the same from some other computer (internet or network) it fails.
I'm not a network expert, how could I find out what is wrong?
Comment: Virtualbox is not a reasonable hypervisor technology to be using as an IT professional.  Put a real hypervisor on your server.
Comment: I don't really need professional level of service. Quick, dirty & free is good enough in this specific case.
Answer: Your problem is most likely that you're double-NAT'ing the traffic via both your router and the host server.
I would personally move the VM to use bridged networking, and then port-forward straight to the VM from your router.

I also agree wth HopelessN00b's comment that you should be replacing VirtualBox with a decent hypervisor, such as HyperV on Windows.
Comment: Thanks, bridged connection really helped. I solved the problem with your help.


for xml root('someStr'),type) ''sub-element issue"

Question: I'm building this xml element using the code below
<code>,( select
     case when i.id > 0
         then (select i.id for xml path('parent'),type)
      else null --> don't write this element if id is than 0
end )
</code>
And i get,
<code> <parent>
  <id>some id number </id></parent>
</code>
But, I'm looking for
<code><id>some id number </id>
</code>
Any suggestion....
Comment: What happens if you remove `parent` from path? Just use an empty string `''`.
Comment: Thanks...and using a empty string works.  But, is that the most effective way way to solve the problem ?
Comment: I don't see any problem with that solution. There might be other ways to do it but it is hard to tell without the context of the full query and I don't think you would notice any difference in performance.
Answer: Pass the empty string '' instead of 'parent'.


I'm unable to find configuration of pgAdmin4 on Windows 8.1

Question: I'm new to PostgreSQL, just installed it along with pgAdmin4. After installation when I clicked on the pgAdmin4 it start in the browser of IE. But I want that in my chrome browser so I searched for it. Most of the people have mentioned or shared a picture of pgAdmin 4 configuration like this.

They mentioned it like right click the icon in the Windows System Tray and select Configure but the pgAdmin is not showing in the system tray of window 8.1. Or may be I'm misunderstanding about the system tray. Because in windows 8.1 pgAdmin 4 directly opens in browser.
The browser issues is fixed by change by default browser to chrome but I'm still unable to find this configuration setting. Can anyone help me to understand or get this screen?
Answer: pgAdmin 4 is a web server, so when you click pgAdmin 4 on the start menu, it starts the web server in the background, then opens a browser to connect to it.
The web server running in the background should have added a small icon to the system tray in the lower right corner.
On my Window 7 it looks like this:
Comment: Great its worked for me. I was just misunderstanding the word system tray. On window 8.1 its look like the picture you shared.


Alternative to VBA GoalSeek

Question: Does there exist an alternative to GoalSeek in VBA? My worksheet is filled with functions that do not like GoalSeek called from subroutines, and I'm looking for a alternative for optimization.
Answer: How about Excel Solver? It can be automated too and allows for significantly more complicated inputs
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/using-the-solver-vba-functions

Alternative to VBA GoalSeek


Proving a transformation on an inner product space is self-adjoint

Question: I have a homework question that I am very unsure if my solution is sufficient, mainly in the converse of the proof, since I feel like I need to use $\mu_T(x)$ somewhere in my proof.
Question: Assume $T$ is an operator on the finite-dimensional inner product space $V$ and the minimum polynomial of $T$ is $\mu_T(x)=x^2-x$. Let $U=E_1$ be the subspace of fixed vectors, i.e. $T(u)=u, \forall u\in U$. Let $W=\ker(T)$. Prove that $T$ is self-adjoint if and only if $W=U^\perp$.
My attempt: Assume $T$ is self-adjoint. Thus, we have that $T=T^*$. Let $x\in U,y\in W$. We will show that $\langle x,y\rangle=0$. Since $x$ is fixed by $T$, we have
$$\langle x,y\rangle=\langle T(x),y\rangle=\langle x,T(y)\rangle=\langle x,0\rangle=0$$
Thus since $x,y$ were arbitrary, we have shown that every vector in $U$ is orthogonal to every vector in $W$ and thus $W=U^\perp$.
Conversely, assume $W=U^\perp$. Again, let $x\in U,y\in W$. We can see
$$0=\langle x,y\rangle=\langle T(x),y\rangle=\langle x,T^*(y)\rangle$$
additionally we have
$$0=\langle x,0\rangle=\langle x,T(y)\rangle=\langle T^*(x),y\rangle$$
Thus we have that $\langle T(x),y\rangle=\langle x,T(y)\rangle$ for all $x\in U,y\in W$. Since $U$ is the eigenspace related to $\lambda=1$, $U$ is a subspace of $V$. Thus, we know that $U+W=U+U^\perp=V$, and thus this solution works for all vectors in $V$. So $T=T^*$.
I feel like my solution to the converse is very naive and that I am assuming too much so I feel I am missing a big part of this question. If it is incorrect, some advice on how to start it would be appreciated.
Answer: You have to take arbitrary elements $x,y \in V$ and show that $\langle Tx,y\rangle =\langle x,Ty\rangle$. For this write $x=u+w,y=u'+w'$ with $u,u' \in U$ and $v,v' \in W$. We get $\langle Tx,y\rangle =\langle u,u'+w'\rangle$ (because $T(u+w)=u+0=u$) and this becomes $\langle u,u'\rangle$ (because $\langle u,w'\rangle =0)$. Similarly, $\langle x,Ty\rangle=\langle u+w,u'\rangle=\langle u,u'\rangle$. This finishes the proof.
Comment: Thank you that makes sense, since any vector in $V$ comes from a combination of vectors in $U$ and $W$.
Comment: A quick question: is it necessary to include in the question that $\mu_T(x)=x^2-x$?
Comment: @DangVu No, that hypothesis is redundant.