How to setup and interpret ANOVA contrasts with the car package in R?

Question: Let's say I have a simple 2x2 factorial experiment that I want to do ANOVA on. Like this, for example:
d   <- data.frame(a=factor(sample(c('a1','a2'), 100, rep=T)),
                  b=factor(sample(c('b1','b2'), 100, rep=T)));
d$y <- as.numeric(d$a)*rnorm(100, mean=.75, sd=1) +
       as.numeric(d$b)*rnorm(100, mean=1.2, sd=1) +
       as.numeric(d$a)*as.numeric(d$b)*rnorm(100, mean=.5, sd=1) +
       rnorm(100);

In the absence of a significant interaction, by default (i.e. contr.treatment) the output of Anova() is the overall significance of a over all levels of b and of b over all levels of a, is that right?
How should I specify a contrast that would allow me to test the significance of effect a with b being held constant at level b1, of effect a with b being held constant at level b2, and of the interaction a:b?
Answer: Your example leads to unequal cell sizes, which means that the different "types of sum of squares" matter, and the test for main effects is not as simple as you state it. Anova() uses type II sum of squares. See this question for a start.
There are different ways to test the contrasts. Note that SS types don't matter as we are ultimately testing in the associated one-factorial design. I suggest using the following steps:
# turn your 2x2 design into the corresponding 4x1 design using interaction()
> d$ab <- interaction(d$a, d$b)       # creates new factor coding the 2*2 conditions
> levels(d$ab)                        # this is the order of the 4 conditions
[1] "a1.b1" "a2.b1" "a1.b2" "a2.b2"

> aovRes <- aov(y ~ ab, data=d)       # oneway ANOVA using aov() with new factor

# specify the contrasts you want to test as a matrix (see above for order of cells)
> cntrMat <- rbind("contr 01"=c(1, -1,  0,  0),  # coefficients for testing a within b1
+                  "contr 02"=c(0,  0,  1, -1),  # coefficients for testing a within b2
+                  "contr 03"=c(1, -1, -1,  1))  # coefficients for interaction

# test contrasts without adjusting alpha, two-sided hypotheses
> library(multcomp)                   # for glht()
> summary(glht(aovRes, linfct=mcp(ab=cntrMat), alternative="two.sided"),
+         test=adjusted("none"))
Simultaneous Tests for General Linear Hypotheses
Multiple Comparisons of Means: User-defined Contrasts
Fit: aov(formula = y ~ ab, data = d)

Linear Hypotheses:
              Estimate Std. Error t value Pr(>|t|)
contr 01 == 0  -0.7704     0.7875  -0.978    0.330
contr 02 == 0  -1.0463     0.9067  -1.154    0.251
contr 03 == 0   0.2759     1.2009   0.230    0.819
(Adjusted p values reported -- none method)

Now manually check the result for the first contrast.
> P       <- 2                             # number of levels factor a
> Q       <- 2                             # number of levels factor b
> Njk     <- table(d$ab)                   # cell sizes
> Mjk     <- tapply(d$y, d$ab, mean)       # cell means
> dfSSE   <- sum(Njk) - P*Q                # degrees of freedom error SS
> SSE     <- sum((d$y - ave(d$y, d$ab, FUN=mean))^2)    # error SS
> MSE     <- SSE / dfSSE                   # mean error SS
> (psiHat <- sum(cntrMat[1, ] * Mjk))      # contrast estimate
[1] -0.7703638

> lenSq <- sum(cntrMat[1, ]^2 / Njk)       # squared length of contrast
> (SE   <- sqrt(lenSq*MSE))                # standard error
[1] 0.7874602

> (tStat <- psiHat / SE)                   # t-statistic
[1] -0.9782893

> (pVal <- 2 * (1-pt(abs(tStat), dfSSE)))  # p-value
[1] 0.3303902

Comment: THANK YOU!!! You've just answered a question that two semesters of graduate level stats have not. I even considered using one-way anova before, but couldn't find any confirmation that this was a legitimate approach.
Comment: @f1r3br4nd In a 2x2x2 design, there is only one unique A*B*C interaction contrast (like there is only one in a 2x2 case). The coefficients in an A*B*C interaction-contrast have to sum to zero over rows (A), columns (B), and planes (C) in the "design cube". If the order of cells in the associated one-way design is `a1.b1.c1, a2.b1.c1, a1.b2.c1, a2.b2.c1, a1.b1.c2, a2.b1.c2, a1.b2.c2, a2.b2.c2`, then the coefficients are `c(1, -1, -1, 1, -1, 1, 1, -1)`. If you have more than two groups in your factors, all contrasts following the sum-to-zero rule are 3-way interaction contrasts.
Comment: @f1r3br4nd It's legitimate since the error MS is equal in the associated one-way and the original two-way design.
Comment: One last follow-up question, if I may: how does the two-way interaction generalize to interactions of larger numbers of variables? If I had an A*B*C term, would I build that up out of A:B = (A|B=1 - A|B=2), C:B = (C|B=1 - C|B=2), A:B:C = A:B - C:B, and so on?


sendmail TLS issue

Question: I have a user that cannot authenticate. What I am getting is:

did not issue MAIL/EXPN/VRFY/ETRN
  during connection to MTA

I have SASL installed for plaintext passwords. Can someone please point me in the right direction? What am I missing?
Comment: 1. The error message does not have anything to do with authentication. 2. Neither does TLS (if you are using SASL for auth).
Answer: The error message means that the client opens up a connection to port 25 on your server, but does not issue any other commands. I will make a wild guess here and will suspect that this is a TCP window scaling problem. If the client is a Windows Vista / 7 machine try something like:
netsh interface tcp set global autotuninglevel=disabled

or
netsh interface tcp set global autotuninglevel=restricted

from a command prompt that you have started as an administrator. If your server is a linux machine you can try adding these at the bootom of your /etc/sysctl.conf:
 net.ipv4.tcp_rmem = 4096 87380 174760
 net.ipv4.tcp_wmem = 4096 16384 131072
 net.ipv4.tcp_window_scaling = 0

Run "sysctl -p" as root for the changes to take effect. Depending the case you may need both. However this is a workaround and not a solution to the problem, and like I said a wild guess since I've seen such behaviour coupled with the error message that you describe too many times.
Comment: My monitoring system tries to make a TCP connection to my mail server's port 25 and see a sendmail banner; if it does, it promptly disconnects, which produces exactly this log message.  So yes, there are many reasons this message might appear in your logs.

sendmail TLS issue


Redefinir id's de divs por números em ordem

Question: Sou bastante leigo em JavaScript e jQuery, e estava precisando alterar os id's das divs em ordem numérica.
Por exemplo:

e transformar em:

Alguém sabe um método pra fazer isso?
Answer: Podemos utilizar a função each (função que efetua um loop) para percorrermos todas as div do nosso HTML.
Essa função irá realizar um loop em todas as divs (nós especificamos que será nas divs no comando $(div)), e temos também o índice atual do loop no parâmetro index, e o elemento atual (div atual) no parâmetro element. Agora basta definirmos o novo valor para nosso atributo id, utilizando a função attr() do JQuery.
$('div').each(function(index, element) {
    // Já que o índice começa em zero então vamos definir o novo id como índice + 1
    $(element).attr('id', index + 1);
});

Você pode ver o exemplo funcionando aqui: https://jsfiddle.net/o2gxgz9r/76342/
Comment: Obrigado, esse método funcionou também
Answer: Usando JavaScript puro você pode criar um nodelist com document.querySelectorAll("div") e depois iterar com for alterando os id's:

var divs = document.querySelectorAll("div");
for(var x = 0; x < divs.length; x++){
   divs[x].id = x+1;

   // linha abaixo só para visualização
   console.log(divs[x].outerHTML);
}

Comment: Muito obrigado cara, irei utilizar


Api Maps Offline

Question: Boa noite pessoal, tudo bem?
Gostaria de saber se teria como meu aplicativo abrir o mapa quando o usuário estiver sem internet ?
Answer: Olá! Sim, tem como fazer usando o maps api, criando seus próprios tiles e usando o TileProvider para manipulá-los.
Mas o próprio Google não encoraja muito a fazer isto em seus termos de serviço. "No caching or storage."
Uma solução open source é utilizar o OpenStreetMaps com tiles de mapa.
Aqui tem as ferramentas para usar o OSM no Android:
https://github.com/osmdroid/osmdroid
E aqui a ferramenta para você baixar os tiles:
http://mobac.sourceforge.net/
É isto. ;)

Api Maps Offline


How do you capture iteration variables?

Question: When you capture the iteration variable of a for loop, C# treats that variable as though it was declared outside the loop. This means that the same variable is captured in each iteration. The following program writes 333 instead of writing 012:
Action[] actions = new Action[3];
for (int i = 0; i < 3; i++)
    actions [i] = () => Console.Write (i);

foreach (Action a in actions) a(); // 333

I'm reading C# in a Nutshell (5th Edition) and today i came across this but i can't get my head over it, i don't get why the output is 333 and not 012. Is it because the value of i that's getting printed is the value after the loop? How is that possible? i is supposed to be disposed after the loop, isn't it?
Comment: Have a look at [Jon Skeet's article about closures](http://csharpindepth.com/articles/chapter5/closures.aspx) - it containts good examples and explanations. Another good articles are those of [Eric Lipper - closures](http://blogs.msdn.com/b/ericlippert/archive/tags/closures/).
Comment: @EhsanSajjad a is the lambda variable, in this case an `Action`.
Comment: It's the variable of type `Action` declared in the foreach loop.
Answer: The variable i is captured inside the for loop but your are kind of extending the scope of it by doing so. So the variable is left at it's last state which was 3, hence the code outputting 333.
Another way to write the code is this:
Action[] actions = new Action[3];
int i; //declare i here instead of in the for loop

for (i = 0; i < 3; i++)
    actions [i] = () => Console.Write (i);

//Now i=3
foreach (Action a in actions) a(); // 333

The output is the same as writing:
Console.Write(i);
Console.Write(i);
Console.Write(i);

Comment: Be aware that since C# 5, `foreach` has been fixed to *not* place `i` outside the loop, but inside. In other words, if you changed the loop to this: `foreach (int i in Enumerable.Range(0,3))`, you'll actually get `012`. That fix does not apply to `for`, however.
Comment: @AsadAli It will be disposed when the last reference is gone, so when `actions` is disposed.
Comment: So when is `i` disposed? I assume, since it's being treated like an outer-scope variable, that it gets garbage collected like other normal variables?
Comment: but hoow @AsadAli i never saw this kind of scenarion in my 2 years work
Answer: Because the lambda captures last value of i, and that is 3.Step of your loop is executed for last time,then i becomes 3 and your loop ends.
I think this would make it clear for you:
int i = 0;
for (; i < 3; i++) { }

Console.WriteLine(i);  // writes 3

You could fix this using a temporary variable:
for (int i = 0; i < 3; i++)
{
    int temp = i;
    actions[i] = () => Console.Write(temp);
}

foreach (Action a in actions) a(); // now: 012

I would recommend you to read this article to understand closures better
Comment: So will the `temp` variable be disposed when the loop ends?
Comment: @AsadAli no, it will not, it's still closed over by the lambda
Answer: My approach for understanding the closure in this case is to unroll the for loop:
var actions = new List<Action>();
// this loop is "executed"
for (int i = 0; i < 3; i++)
{
    actions.Add(() => Console.Write (i));
}
// pseudo "unroll" the loop
// i = 0
// action(0) = Console.WriteLine(i);
// i = 1
// action(1) = Console.WriteLine(i);
// i = 2
// action(2) = Console.WriteLine(i);
// i = 3

foreach (Action a in actions)
{
    a();
}
// pseudo "unroll" the foreach loop
// a(0) = Console.WriteLine(3); <= last value of i
// a(1) = Console.WriteLine(3); <= last value of i
// a(2) = Console.WriteLine(3); <= last value of i
// thus output is 333

// fix
var actions = new List<Action>();
// this loop is "executed"
for (int i = 0; i < 3; i++)
{
    var temp = i;
    actions.Add(() => Console.Write (temp));
}
// pseudo "unroll"
// i = 0
// temp = 0
// actions(0) => Console.WriteLine(temp); <= temp = 0
// i = 1
// temp = 1
// actions(1) => Console.WriteLine(temp); <= temp = 1
// i = 2
// temp = 2
// actions(2) => Console.WriteLine(temp); <= temp = 2
foreach (Action a in actions)
{
    a();
}
// pseudo "unroll" the foreach loop
// a(0) = Console.WriteLine(0); <= last value of first temp
// a(1) = Console.WriteLine(1); <= last value of second temp
// a(2) = Console.WriteLine(2); <= last value of third temp
// thus 012

How do you capture iteration variables?


How do I render a Media Entity Reference image field in template_preprocess_node()?

Question: I'm altering the way images are rendered in the node preprocess function, and it is working exactly as expected for images in "Image" fields:
$field_view = $fields['field_image']->view(['label' => 'hidden']);
$field_view['#view_mode'] = 'full';

This results in the regular image array, so when I add it to my twig template, it gets rendered as an image tag.
However, we'd like to start using Media fields instead, and I can't figure out how to get the render array to come back with an image instead of just a text link. If I use the same thing for a media field, I just get a link with the image title as the text of the link:
$field_view = $fields['field_media_image']->view([
  'label' => 'hidden',
]);

This is what the 'file' image render array looks like; it renders as an image, which is what I want to get for the media image field:
#theme => "field"
#title => "Image"
#label_display => "hidden"
#view_mode => "full"
#language => "und"
#field_name => "field_image"
#field_type => "image"
#field_translatable => true
#entity_type => "node"
#bundle => "page"
#object => Drupal\node\Entity\Node (29)
#items => Drupal\file\Plugin\Field\FieldType\FileFieldItemList (9)
#formatter => "image"
#is_multiple => false
#third_party_settings => array (0)
0 => array (6)
#cache => array (3)
#weight => 0

However, when I just use the same view() function on the media image field, I get this, which doesn't render as an image:
#theme => "field"
#title => "Media Image"
#label_display => "hidden"
#view_mode => "_custom"
#language => "und"
#field_name => "field_media_image"
#field_type => "entity_reference"
#field_translatable => false
#entity_type => "node"
#bundle => "page"
#object => Drupal\node\Entity\Node (29)
#items => Drupal\Core\Field\EntityReferenceFieldItemList (9)
#formatter => "entity_reference_label"
#is_multiple => false
#third_party_settings => array (0)
0 => array (5)
#cache => array (3)
#weight => 0

I would guess that the reason this renders as a textual link is because of #formatter => "entity_reference_label" but whenI change this value, I continue to get the same output.
Comment: Does this answer your question? [How to get Media entity image (Entity Reference Field) URL in TWIG theme](https://drupal.stackexchange.com/questions/229402/how-to-get-media-entity-image-entity-reference-field-url-in-twig-theme)
Comment: No. I'm not trying to render the field in the twig template, I'm trying to build a render array for the media field in my `template.theme` file. I understand how to do this for a regular Drupal image field, but not a media entity.
Answer: Try this:
if ($node->hasField('field_name') && $node->get('field_name')->entity) {

  // Set media entity.
  $mediaEntity = $node->get('field_name')->entity;

  // Get media image field.
  $mediaImage = $mediaEntity->get('field_media_image');

  // Get translated media image field.
  if ($mediaEntity->hasTranslation($langcode)) {
    $mediaImage = $mediaEntity->getTranslation($langcode)->get('field_media_image');
  }

  // Get media image entity.
  $mediaImageEntity = $mediaImage->entity;

  // Get image mime type.
  $mediaImageMimeType = $mediaImageEntity->getMimeType();

  // Get image file uri.
  $mediaImageEntityUri = $mediaImageEntity->getFileUri();

  // Set image url.
  $imageUrl = \Drupal::service('file_url_generator')->generateString($mediaImageEntityUri);

  // Set image style url.
  if ($mediaImageMimeType !== "image/svg+xml") {
    $imageUrl = \Drupal::entityTypeManager()->getStorage('image_style')->load('image_style_name')->buildUrl($mediaImageEntityUri);
  }

  $variables['imageUrl'] = $imageUrl;
}

Comment: Thanks for looking at this; I'm not trying to just get the URL, although I suppose that would allow me to build my own image output. With the regular image field, I'm able to just use the `$field->view()` to generate a render array, and I'd like to use the same method (or equivalent) to render the media image field.
Answer: Don't switch the field formatter, switch the entire entity view mode. I've done something similar with Paragraphs and media view modes, the following code is copy&paste from my project. It should be easy to adjust for nodes.
I just replaced the #view_mode key in the render array, but you have to do it for every single ER field value
function theme_preprocess_paragraph(array &$variables) {
  $paragraph = $variables['paragraph'];
  if ($paragraph->hasField('field_image_viewmode')) {
    $imageViewMode = $paragraph->field_image_viewmode->value;
    if (!$paragraph->field_gallery->isEmpty()) {
      $mediaEntities = $paragraph->field_gallery->referencedEntities();
      foreach ($mediaEntities as $idx => $mediaEntity) {
        // this is the key line
        $variables['content']['field_gallery'][$idx]['#view_mode'] = $imageViewMode;
        // this operation is not cache-safe
        unset($variables['content']['field_gallery'][$idx]['#cache']['keys']);
      }
    }
  }
}

But I recommend not doing this anymore. I'm now using view_mode_switch instead, which does the same thing with better code and with an UI (which basically  means it is documented for editors)


Find the equation of the line which goes through $(0,0,0)$

Question: A line which goes through the point $(0, 0, 0)$ and a plane which has the equation $ 2x - y + 3z = 1$ have the angle of $45^{\circ}$ between them. I am supposed to find the equation of the line.
I know that the normal vector of the plane is $n=(2, -1, 3)$ but I get stuck here and don't know how to continue. Any help is appreciated..
Comment: It appears that there's not only one single line that meets your demands.
Answer: You just need a vector $\textbf{w}$ such that the angle between $n=(2,-1,3), \textbf{w}$ is $45^o$. Letting $\textbf{w}$ be a unit vector we have,
\begin{align} (2,-1,3) \cdot \textbf{w} = \sqrt{14} \cos \theta_{n, \textbf{w}} &= \sqrt{14} \cos(45^o)\\ & = \sqrt{14} \cdot \frac{\sqrt{2}}{2} \end{align}
If you let $\textbf{w} = (x,y,z)$ then you have $ 2x-y+3c = \sqrt{7}$. It should be easy to get a $\textbf{w}$ from here. So once you do that, define $L$ to be the line parametrized by $\alpha(t) = \textbf{w}t$. As the other user pointed out, once you have one vector, rotation about the axis made by the normal line to the plane, gives all the others.


Upload de array de imagens PHP e MySQL

Question: Eu tenho o seguinte código:
<?php

if(isset($_FILES['files'])){
    $errors = array();

    foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size = $_FILES['files']['size'][$key];
        $file_tmp = $_FILES['files']['tmp_name'][$key];
        $file_type = $_FILES['files']['type'][$key];
        $file_parts = pathinfo($file_name);//Returns an associative array containing file information
        $extensions = array("jpeg","jpg","png");//Allowed file

    if($file_size > 2097152){

            echo 'Tamanho do arquivo de ser menor que 2MB';

    }else{

    if(in_array ($file_parts['extension'],$extensions)){

        //Rename file
        $file_parts = ".".$file_parts['extension'];
        $file_name = uniqid().$file_parts;

            if(empty($errors)==true){
            //Move the file to a specific folder
            move_uploaded_file($file_tmp, "img/".$file_name);

            }else{
                print_r($errors);
            }//if(empty($errors)==true){

        }else{

            echo'Extensão não permitida';

        }//if(in_array ($file_parts['extension'],$extensions))

    }//if($file_size > 2097152){

    if(empty($errors)){

        print_r("
".$file_name."
");

    }//if(empty($errors))

    }//foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name)

}

?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Upload</title>

    <form action="" method="POST" enctype="multipart/form-data">
        <input type="file" name="files[]" multiple>
        <input type="submit" value="Enviar">
    </form>

Minha dúvida é, o que é melhor, fazer criar uma tabela no banco de dados para as imagens, assim quando eu precisa dessas imagens em algum formulário faço interação um para muitos, ou transformar o array em uma string?
Será que tem outra solução também?
Answer: Eu salvaria tudo num JSON, muito mais rápido a leitura e você pode inserir keys pra vincular a registros também...ficando a seu critério, mas a princípio apenas savaria no JSON mesmo:
$file = "img/images.json";
$json = json_decode(file_get_contents($file), true);
array_push($json, $file_name);
file_put_contents($file, json_encode($json));

Como neste exemplo, o json pode até ficar no mesmo diretório que as imagens, você pode incrementar outras informações da imagem que se fizer necessário no array também...
Answer: Salva no banco de dados, como citou!
Segue um exemplo de como eu faço:
Sugiro uma tabela chamada "Documentos"
Com campos como Id, e Tipo de documento
E outra tabela chamada "DocumentoArquivos"
Com campos como Id, Nome, DocumentoFk, Tamanho, Extensão, Diretorio.
Quanto você enviar os arquivos, salve no seu diretório de imagens e posteriormente use um Begin Transaction para salvar o "Envio" como um "Documento" e cada arquivo como "DocumentoArquivos",
Posteriormente você pode editar este mesmo documento inserindo ou removendo arquivos dele.

Upload de array de imagens PHP e MySQL


phpcs: How to ignore Drupal's 80 char line length limit

Question: I want to use PHP CodeSniffer with the default Drupal and DrupalPractice rulesets to check my custom modules. But I definitly don't want the 80 char line length limit, and phpcs is spamming the report with those warnings. I've created a phpcs.xml in my project root (taken from this blog)
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="my_drupal10_phpcs_configuration">

  <rule ref="Drupal"/>
  <rule ref="DrupalPractice"/>

  <arg name="extensions" value="php,module,inc,install,test,profile,theme,css,info,txt,md,yml"/>

  <exclude-pattern>*/.git/*</exclude-pattern>
  <exclude-pattern>*/.vscode/*</exclude-pattern>
  <exclude-pattern>*/.idea/*</exclude-pattern>
  <exclude-pattern>*/bower_components/*</exclude-pattern>
  <exclude-pattern>*/node_modules/*</exclude-pattern>

  <exclude-pattern>*/vendor/*</exclude-pattern>

  <file>./web/modules/custom</file>
  <file>./web/themes/custom</file>

  <rule ref="Generic.Files.LineLength">
    <properties>
      <property name="lineLimit" value="120"/>
      <property name="absoluteLineLimit" value="0"/>
    </properties>
  </rule>
</ruleset>

but I still get spammed by messages like
 180 | WARNING | Line exceeds 120 characters; contains 141 characters
 187 | WARNING | Line exceeds 80 characters; contains 105 characters

How can I override Drupal's 80 chars with a soft limit of 120 chars?
Answer: My problem was copy&pasting the rule into the root tag. To override the Drupal ruleset, all those overrides have to be nested. My working phpcs.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="drupal10_phpcs_configuration">

  <rule ref="Drupal">

    <exclude name="Drupal.Commenting.FileComment.Missing"/>

    <exclude name="Drupal.Files.TxtFileLineLength.TooLong"/>

    <properties>
      <property name="lineLimit" value="120"/>
      <property name="absoluteLineLimit" value="0"/>
    </properties>
  </rule>
  <rule ref="DrupalPractice"/>

  <arg name="extensions" value="php,module,inc,install,test,profile,theme,css,info,txt,yml,md"/>

  <exclude-pattern>*/.git/*</exclude-pattern>
  <exclude-pattern>*/.vscode/*</exclude-pattern>
  <exclude-pattern>*/.idea/*</exclude-pattern>
  <exclude-pattern>*/bower_components/*</exclude-pattern>
  <exclude-pattern>*/node_modules/*</exclude-pattern>

  <exclude-pattern>*/vendor/*</exclude-pattern>

  <file>./web/modules/custom</file>
  <file>./web/themes/custom</file>
</ruleset>


Closed sets in a given topology

Question: I came across a topology on $ \mathbb Z \times \mathbb Z $ whose basis is defined as follows:
$ B(m,n) = \lbrace (m,n) \rbrace $ if both m and n are odd
$ B(m,n) = \lbrace (m+a, n) | a = -1, 0 ,1 \rbrace $ when m is even and n is odd
$ B(m,n) = \lbrace (m, n+a) | a = -1, 0 ,1 \rbrace $ when m is odd and n is even
$ B(m,n) = \lbrace (m+a, n+b) | a,b = -1, 0 ,1 \rbrace $ when both m and n are even
I was trying to determine the smallest possible closed sets given a point, as the problem requires me to. I showed that when both the coordinates are even, its just the singleton set which is closed.
But in the remaining cases, I think it has to be the entire set itself. However I am lacking a rigorous proof to establish my claim. Can anyone guide me??
Comment: I think your second conclusion is wrong - the smallest closed set containing a point is the intersection of all closed sets containing that point. Can there really be no non-trivial closed set that contains $(1,0)$ or $(1,1)$?
Answer: HINT: Consider the point $\langle 0,1\rangle$, say. A point $p\in\Bbb Z\times\Bbb Z$ is in the closure of $\{\langle0,1\rangle\}$ if and only if every open nbhd of $p$ contains $\langle 0,1\rangle$. This is the case if $p$ is $\langle 0,2\rangle$ or $\langle 0,0\rangle$, but that's it. To see this, let $p=\langle m,n\rangle$. If $m<-1$ or $m>1$, $p\notin B(m,n)$, and similarly if $n<0$ or $n>2$. Thus, we need only consider the nine points in the set $\{-1,0,1\}\times\{0,1,2\}$, and in all cases except the two already noted, $p\notin B(m,n)$.
This argument easily generalizes to show that the closure of $\{\langle 2k,2\ell+1\rangle\}$ is the three-point set $\{\langle 2k,2\ell\rangle,\langle 2k,2\ell+1\rangle,\langle 2k,2\ell+2\rangle\}$ for any integers $k$ and $\ell$. That is, if $p$ is an even-odd point, so to speak, the only points that can't be separated from it are the two adjacent to it vertically.
Now try to analyze the remaining cases in the same general fashion.
Comment: @Vishesh: You're welcome. Sometimes it really does help to look at a few concrete examples, especially when, as here, you can actually draw useful pictures.
Comment: Thanks a lot, I guess I should have just picked up on a specific point to work on than wandering around arbitrarily.

Closed sets in a given topology


LIKE operator to load taxonomy term

Question: I want to retrieve a taxonomy term using this line:
<code>$term = $this->entityTypeManager->getStorage('taxonomy_term')
        ->loadByProperties(['myfield' => 'mytext']);
</code>
How can I rather use the 'LIKE' operator we have in SQL, so that in case the 'myfield' contains a text and not a string in the database, it still works?
Thanks for your help
Answer: I found the answer..I had to use the entity query then load term:
<code>$result = \Drupal::entityQuery('taxonomy_term')
        ->condition('myfield', 'mytext', 'LIKE')
        ->execute();

$term = \Drupal::entityTypeManager()
        ->getStorage('taxonomy_term')
        ->loadMultiple($result);
</code>

LIKE operator to load taxonomy term


Chunked Ajax Responses

Question: Does Drupal support chunked AJAX responses in either direction?
I have not been able to find materials on this so far and am curious:

Is Drupal AJAX capable of working with chunked AJAX responses (Does it have the functionality of waiting until all chunks are received and display them as soon as possible)
Does Drupal have functionality to send Chunked responses to an AJAX request (Send data as soon as it's ready, so it can be displayed to the client)

What I mean by chunked AJAX is basically what multiple service booking sites do (example: airline tickets) They do multiple requests to different service providers and airlines, and results are displayed as soon as they're available and populated with more as they are sent.
Comment: Just to make sure I'm on the same page as you - do you mean "chunked" in the sense that the API requests are made on the back end (in PHP) in one long request, and each result is flushed back to the client immediately, before the next call is made (i.e. one AJAX call from the client)? Or do you mean you want to fire off multiple asynchronous requests from javascript, updating the DOM when each completes? Either way I don't think Drupal has anything specific that would help, but PHP and JS can both do it (maybe with a bit of server tweaking to allow in-request flushes)
Comment: @Clive: I mean the first one, where the PHP script in-turn makes multiple requests and returns the responses as "chunked" by flushing them back to the client immediately yes.
Answer: I don't think Drupal 7 or Drupal 8 support chunked AJAX response. Because AJAX in Drupal is implemented with jQuery.ajax which does not support that.
Comment: That's the saddest thing I've heard all day :( Guess it'll have to come from a custom module and a custom front-end script then.. THANKS!

Chunked Ajax Responses


Apache www permissions for php script

Question: I have a php script which run a private social network.
It's running on a Ubuntu 16.04.03 with an mariadb and apache 2 and php7 config.
I have created a new folder in /var/www/myscript and copied all files in this folder.
My question is now, what permissions are necessary to make the config safe.
Is it safe to set all files to 640 and all folders to 750 and owner and user to www-data?
I found this tutorial, http://fideloper.com/user-group-permissions-chmod-apache
The permissions looks different, are these permissions good, too?
It would be great if someone can help me.
Thank you very much.
Best regards
Comment: We typically don't review other manuals and how to's but take a look at this canonical Q&A https://serverfault.com/q/357108/37681
Answer: It very much depends on your CMS.
I actually really do not like 99% of the CMS available out there. All their PHP files go in the public Apache tree which means clients have access to them. That's not safe. These should be in a place where the client cannot access them. That being said, the index.php needs to be public (obviously?) and a few other files, depending on your CMS. Everything else could be in a folder that Apache does not give access to the client. Then the permissions become much less problematic.
Say you have a folder named public_html where Apache as access, you could have a structure that looks like this:
/var/www/example.com
/var/www/example.com/php  -- put your PHP scripts here
/var/www/example.com/data  -- whatever data files (XML, templates, non-public)
/var/www/example.com/public_html  -- only folder accessible by Apache
/var/www/example.com/public_html/index.php  -- the PHP that handles the CMS

Now... The ownership, unless you use a CMS like WordPress which wants to auto-update itself, the files need to be writable by the Apache2 user (www-data for Ubuntu). In all other cases, you should set the user and group to a different user than www-data and make sure that Apache does NOT have permission to modify those files. Make sure it can read them (maybe other has the 'r' for files (644) and 'r-x' for directories (755).)
Say you use rsync to do your updates and give rsync permission to write files as user www. Now you could make all those files be owned by www and not www-data and the update will work just fine.
Obviously, if you have an upload feature which saves files to your web server, then that directory needs to be writable by www-data. Also those files should be backed up (like your database) since they are accessible (read as: hackable) by clients. Since you have an intranet, it may be less of a concern, although most large businesses report that most of their data losses are because of staff working there and not hackers from the outside. Something to keep in mind.
Something like this work work for such files:
mkdir /var/www/example.com/public_html/download
chown www-data:www-data /var/www/example.com/public_html/download
chmod 775 /var/www/example.com/public_html/download

The path to those files can be different as the CMS sees fit, although the actual files could be in one large directory (it is fast whatever the number of files).
Answer: If you don't really need, do not set write permission to any file or folder. typically you set write permission only for a tmp folders or configuration files which are need to be written by app itself. although it is not really mistake to have write permission on any of your files or folders, you should always consider that the app you are running on it could have a security hole and then attacker is free to save custom scripts anywhere he wants, write your configs, etc.
Answer: Thank you very much for your help.
If i understand all the tips correctly i should do the following:
the owner of /var/www/mysite and all files and subfolders should not www-data (is it ok to set to root?)
The group of /var/www/mysite and all files and subfolders should be www-data
All files should be 644 or better 640 and directorys 755 or 750?
If user upload files from the website i have a folder /var/www/mysite/uploads and on this folder i will set the www-data as owner and group and set the permission to 775.
At the moment my folder looks like this:
/var/www/mysite -> root:www-data (for all files and folders)
files have 640 permissions
folders have 750 permissions
Is this a config that looks ok and secure or should i change the user from root to the user that i'm using for maintaining the server?
thank you again for your help.

Apache www permissions for php script


How to calculate out of sample R squared?

Question: I know this probably has been discussed somewhere else, but I have not been able to find an explicit answer. I am trying to use the formula $R^2 = 1 - SSR/SST$ to calculate out-of-sample $R^2$ of a linear regression model, where $SSR$ is the sum of squared residuals and $SST$ is the total sum of squares. For the training set, it is clear that
$$ SST = \Sigma (y - \bar{y}_{train})^2 $$
What about the testing set? Should I keep using $\bar{y}_{train}$ for out of sample $y$, or use $\bar{y}_{test}$ instead?
I found that if I use $\bar{y}_{test}$, the resulting $R^2$ can be negative sometimes. This is consistent with the description of sklearn's r2_score() function, where they used $\bar{y}_{test}$ (which is also used by their linear_model's score() function for testing samples). They state that "a constant model that always predicts the expected value of y, disregarding the input features, would get a R^2 score of 0.0."
However, in other places people have used $\bar{y}_{train}$ like here and here (the second answer by dmi3kno). So I was wondering which makes more sense? Any comment will be greatly appreciated!
Answer: First of all is need to say that for prediction evaluation, then out of sample, the usual $R^2$ is not adequate. It is so because the usual $R^2$ is computed on residuals,  that are in sample quantities.
We can define: $R^2 = 1 – RSS/TSS$
RSS = residual sum of square
TSS = total sum of square
The main problem here is that residuals are not a good proxy for forecast errors because in residuals the same data would be used for both, model estimation and model prediction accuracy. If residuals (RSS) are used the prediction accuracy would be overstated; probably overfitting occur. Even TSS is not adequate as we see later. However we have to say that in the past the mistaken use of standard $R^2$ for forecast evaluation was quite common.
The out of sample $R^2$ ($R_{oos}^2$) maintain the idea of usual $R^2$ but in place of RSS is used the out of sample MSE of the model under analysis (MSE_m). In place of TSS is used the the out of sample MSE of one benchmark model (MSE_bmk).
$R_{oos}^2 = 1 – MSE_m/MSE_{bmk}$
One notable difference between $R^2$ and $R_{oos}^2$ is that
$0 \leq R^2 \leq 1$ (if the constant term is included)
while $-\infty \leq R_{oos}^2 \leq 1$
If $R_{oos}^2 < = > 0$ the competing model perform worse/equal/better than the benchmark one. If  $R_{oos}^2 =1$ the competing model predict perfectly the (new) data.
Here we have to keep in mind that the even for the benchmark model we have to consider the out of sample performance. Therefore the variance of the out of sample data underestimate $MSE_{bmk}$.
In this sense something like
$$ MSE_{bmk} = (1/n)\Sigma (y - \bar{y}_{test})^2 $$
seems to me a wrong choice.
While something like
$$ MSE_{bmk} = (1/n)\Sigma (y - \bar{y}_{train})^2 $$
seems to me plausible.
In my knowledge this measure was proposed for the first time in:
Predicting excess stock returns out of sample: Can anything beat the historical average? - Campbell and Thompson (2008) - Review of Financial Studies.
In it the the bmk forecast is based on the prevailing mean given information at time of the forecast.
Comment: It seems me that Campbell and Thompson do not speak, at least not exsplicitely, about this question. However, what matter for oosR-squared  is that both predictions of the model under analysis and of benchmark model can be computed with data actually available at the time of the prediction. So someting like $Y_{test}$ sound me a wrong choice. Campbell and Thompson benchmark forecast are not a constant (a plain average) but are consistent with previus concept.
Comment: The Campbell/Thompson argument would seem to favor using $\bar y_{train}$, agreed?
Comment: "predictions...of benchmark model can be computed with data actually available at the time of the prediction" This is the logic behind my stance, and I am with you that this is consistent with the way Campbell and Thompson think of the problem.
Answer: You are correct.
The OSR$^2$ residuals are based on testing data, but the baseline should still be training data. With that said, your SST is $SST=Σ(y−\bar y_{train})^2$;  notice that the is the same for $R^2$
Comment: Although I have fixed some obvious and some apparent errors from previous edits some of the notation and some of the intended meaning are still unclear.
Comment: @Firebug I wouldn't worry about the interpretation of $R^2$ as proportion of variance explained. [That turns out to be the exception, not the rule.](https://stats.stackexchange.com/q/551915/247274) Further, we don't even need a nonlinear regression [for that interpretation to break down](https://stats.stackexchange.com/questions/494274/why-does-regularization-wreck-orthogonality-of-predictions-and-residuals-in-line).
Comment: Thanks for the answer! Do you have any reference on this? It seems stat softwares use commonly the alternative definition, with y_test?
Comment: Do you have a reference for this? Granted, if you take $R^2$ to be a comparison of deviances, ergo a comparison of likelihoods I think you're right. But if you take $R^2$ to be the proportion of explained variance then not, because the total sum of squares won't appear anywhere.
Answer: We have just published an article on this subject in The American Statistician here
Similar to @markowitz, we define out-of-sample $R^2$ as a comparison of two out-of-sample models: the null model using only the mean outcome of the training data $\bar{y}_{train}$, and the more elaborate model using covariate information.
For the squared error loss of the null model (which we call the MST), we derive an analytical expression showing that
$$
MST = \operatorname{Var}(\bar{Y}_{train}) + \operatorname{Var}(Y) = \frac{n+1}{n}\operatorname{Var}(Y),
$$
meaning that the prediction error is a sum of estimation error on $\bar{y}_{train}$ and irreducible error. This is a useful expression in absence of a test set. But if you have an independent test set, I would indeed prefer the expression $n^{-1}\sum_{i \in \text{test}}(y_i-\bar{y}_{train})$ as suggested above. In principle, both estimators have the same estimand, but the latter is more robust to differences between training and test sets. Finally, we show through simulation that the expression $n^{-1}\sum_{i \in \text{test}}(y_i-\bar{y}_{test})$ can be badly biased for estimation the true $R^2$.
The squared error loss of the elaborate model (the MSE) is then to be estimated through cross-validation or on your test set. Corresponding out-of-sample $R^2$ is then simply
$$\hat{R}^2 = 1-\frac{\widehat{MSE}}{\widehat{MST}}$$
We provide a standard error for this estimate, unlocking hypothesis testing and confidence intervals.
REFERENCE
Hawinkel, Stijn, Willem Waegeman, and Steven Maere. "Out-of-sample R 2: estimation and inference." The American Statistician just-accepted (2023): 1-16.
Comment: This is awesome. I disagree with the interpretation of [explained variance](https://stats.stackexchange.com/q/551915/247274), but this is a minor point. Your article makes the exact kind of argument I make all the time on here. It is good to see that in a legitimate journal. If I ever get around to writing an article I have in mind, I will cite your work.
Comment: @Dave thanks for your kind words! In your derivation, if $y_i$ is the out-of-sample observation and $\bar{y}$ and $\hat{y}_i$ are calculated based on in-sample data (and out-of-sample regressors), I am not sure that your "Other" term equals zero in the general case of a random design. The proofs I find are for in-sample linear regression, which is the subject of your post, but aren't matters different for out-of-sample prediction? If the out-of-sample design is fixed, I think this term drops for any unbiased prediction model, not just for linear models.
Comment: That is my point: that "other" term is not zero in general, and then claims of $R^2$ as being the proportion of variance explained become dubious.


Slider navigators working very slowly

Question: As I am new to JQuery, I was recently practicing it by creating a simple slider with navigation buttons.
The entire slider is working correctly but the navigation buttons are responding very slowly. When I am clicking on them for the first time, I need to click them twice to make them respond. There is no error on the console. Everything is working correctly, except the navigation button response time.
Thank you for the help in advance.

var slides = document.getElementsByClassName('slide');
var slider_count = 1;
var offset_value;
start();

function left() {

  slider_count--;
  if (slider_count < 0) {
    slider_count = slides.length - 1;
  }
  offset_value = slides[slider_count].offsetLeft;
  $("#wrapper").animate({
    scrollLeft: offset_value
  }, 1000);

}

function right() {

  if (slider_count >= slides.length) {
    slider_count = 0;
  }
  offset_value = slides[slider_count].offsetLeft;
  $("#wrapper").animate({
    scrollLeft: offset_value
  }, 1000);
  slider_count++;
}

function start() {

  if (slider_count == slides.length) {
    slider_count = 0;
  }

  offset_value = slides[slider_count].offsetLeft;
  slider_count++;
  $("#wrapper").animate({
    scrollLeft: offset_value
  }, 1000);
  setTimeout(start, 3000);
}
html,
body,
body * {
  margin: 0;
  padding: 0;
}

#wrapper {
  height: 300px;
  white-space: nowrap;
  overflow: hidden;
}

.slide {
  display: inline-block;
  width: 100%;
  height: 100%;
}

#slide-option-1 {
  background-color: #808080;
}

#slide-option-2 {
  background-color: green;
}

#slide-option-3 {
  background-color: blue;
}

#main {
  position: relative;
}

.nav {
  position: absolute;
  cursor: pointer;
}

#nav-1 {
  left: 10px;
  top: 45%;
}

#nav-2 {
  right: 10px;
  top: 45%;
}

  Left

  Right

Answer: initialize slider_count with 0.

var slides = document.getElementsByClassName('slide');
var slider_count = 0;
var offset_value;
start();

function left() {

  slider_count--;
  if (slider_count < 0) {
    slider_count = slides.length - 1;
  }
  offset_value = slides[slider_count].offsetLeft;
  $("#wrapper").animate({
    scrollLeft: offset_value
  }, 1000);

}

function right() {

  slider_count++;
  if (slider_count >= slides.length) {
    slider_count = 0;
  }
  offset_value = slides[slider_count].offsetLeft;
  $("#wrapper").animate({
    scrollLeft: offset_value
  }, 1000);
}

function start() {

  slider_count++;
  if (slider_count >= slides.length) {
    slider_count = 0;
  }

  offset_value = slides[slider_count].offsetLeft;
  $("#wrapper").animate({
    scrollLeft: offset_value
  }, 1000);
  setTimeout(start, 3000);
}
html,
body,
body * {
  margin: 0;
  padding: 0;
}

#wrapper {
  height: 300px;
  white-space: nowrap;
  overflow: hidden;
}

.slide {
  display: inline-block;
  width: 100%;
  height: 100%;
}

#slide-option-1 {
  background-color: #808080;
}

#slide-option-2 {
  background-color: green;
}

#slide-option-3 {
  background-color: blue;
}

#main {
  position: relative;
}

.nav {
  position: absolute;
  cursor: pointer;
}

#nav-1 {
  left: 10px;
  top: 45%;
}

#nav-2 {
  right: 10px;
  top: 45%;
}

  Left

  Right

Answer: increase  setTimeout(start, 9000); so it will slow

var slides = document.getElementsByClassName('slide');
var slider_count = 1;
var offset_value;
start();

function left() {
  slider_count--;
  if (slider_count < 0) {
      slider_count = slides.length - 1;
  }

  offset_value = slides[slider_count].offsetLeft;
  $("#wrapper").animate({
      scrollLeft: offset_value
  }, 100);

}

function right() {
  if (slider_count >= slides.length) {
    slider_count = 0;
  }

  offset_value = slides[slider_count].offsetLeft;
  $("#wrapper").animate({
    scrollLeft: offset_value
  }, 100);
  slider_count++;
}

function start() {
  if (slider_count == slides.length) {
    slider_count = 0;
  }

  offset_value = slides[slider_count].offsetLeft;
  slider_count++;
  $("#wrapper").animate({
    scrollLeft: offset_value
  }, 1000);
  setTimeout(start, 9000);
}
html,
body,
body * {
  margin: 0;
  padding: 0;
}

#wrapper {
  height: 300px;
  white-space: nowrap;
  overflow: hidden;
}

.slide {
  display: inline-block;
  width: 100%;
  height: 100%;
}

#slide-option-1 {
  background-color: #808080;
}

#slide-option-2 {
  background-color: green;
}

#slide-option-3 {
  background-color: blue;
}

#main {
  position: relative;
}

.nav {
  position: absolute;
  cursor: pointer;
}

#nav-1 {
  left: 10px;
  top: 45%;
}

#nav-2 {
  right: 10px;
  top: 45%;
}

  Left

  Right

Comment: Sorry. But still the navigation buttons respond very slowly.
Comment: Improved a little bit. But still sometimes need to click twice on the navigation buttons.
Comment: b'coz of you use timeout and function for it thats why it perform slow

Slider navigators working very slowly


Using the web interface or using Drush cause different result?

Question: What is the difference executing an upgrade from Drupal 6 or 7 to Drupal 8 using the web interface or it's better to use Drush?
If the database is heavy, using either of them would have different result?
Answer: From the technical perspective, the PHP configuration can be different for web server (Apache) and when running from CLI (drush), since different php.ini is loaded, therefore different limits are applied, sometimes your PHP could be different.
If you're non-technical person and it's one time (simple) process, it's better to use web interface, which is recommended way to upgrade your Drupal. The size of database doesn't make any difference, since the batch operation can perform long operations, but it may fail in the middle if you lost your connection.
On the other hand if you're repeating the process many times in order to test it properly, Drush may be a better solution, since you can test the process in more efficient and consistent way especially across multiple environments, this is especially useful if you've continuous integration in place (such as deployments).
So it's really depending on your needs.


Adding a class to current taxonomy term link

Question: Hi I wrote a SQl query to generate a list of taxonomy terms, I want to add a class to each taxonomy term when its clicked, like when I click any term  it goes to its term page, on that page I want some class should be be added to this taxonomy term.
I tried with jquery when I click any term, the class gets added but the page refreshes as it goes to this term page, the class is removed. I can do with cookie procedure, but I think there might be any other way in drupal.
Answer: The only thing to think about here is the page you end up on (the term page), so don't worry about links that appear on any other pages.
So what you want to do is on taxonomy/term/% pages, add a class to links that match that page.
Seeing as we are adding a class to an a tag, we want to be altering/overriding the markup output of an a tag.
So then you just have to find the best way to do that.
There are a lot of places that a link might come from in drupal, so to try to cover the most you possibly can, you want to be as general as possible, which in this case means theme_link(), which as the name indicates, handles the themeing of a link.
For more information on overriding themeable output see About overriding themable output. There are also many other examples across the internet.
In this case you will want to do something like this...
In your theme's template.php file add this:
/**
 * Theme a link tag.
 */
function YOURTHEMENAME_link($variables) {
  // If we are on a term page.
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2)) {
    // The easiest way to check all possibilities, like absolute & relative
    // paths and path aliases and real paths is to compare via the url function,
    // which will normalise all this stuff.
    if (url($variables['path'], array('absolute' => TRUE)) == url($_GET['q'], array('absolute' => TRUE)) {
      // Add the class to the link definition so that it will be
      // added to the rendered link.
      $variables['options']['attributes']['class'][] = 'your-class-goes-here';
    }
  }

  // Print the link as usual.
  return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}

After adding this function to your template.php you will have to clear the drupal cache for it to take effect.
Note that if your theme or any modules print links without using the l() function or theme('link') or similar then it won't be affected by this.
If you have user entered content that has these links in them then they will also not be affected by default.
The easiest way to make it so they are also handled is to enable and configure the pathologic module.
The other option is javascript, but that is not ideal as it isn't really necessary in this case and doesn't work for users that don't have javascript.
In that case you need to include your script on the taxonomy/term/% pages only (see drupal_add_js()), then in the script check for the current page matching any link hrefs and add the class.
Answer: Thanks Rooby, I did it with jquery.

$('li').each(function(){
        if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
        {
    $(this).addClass('activelink').siblings().removeClass('activelink');

    }
});


How to compare times?

Question: i'm looking for an algorithm to compare 2 different time records.
My time format is hour:minute:second:nanosec
I tried something like this, but its not working well:
if (hour <= anotherHour) {
            if (min <= anotherMin) {
                if (sec <= anotherSec()) {
                    if (msec <= anotherMsec()) {
                        return -1;
                    } else {
                        return 1;
                    }
                } else {
                    return 1;
                }
            } else {
                return 1;
            }
        } else {
            return 1;
        }
Answer: Convert all times into a common unit, for example seconds, and then you don't need to do nested if statements.
Comment: Your base unit $u$ would be the nanosecond, so $u=n+1000000000(s+60(m+60h))$, where $n$ stands for nanoseconds field, $s$ stands for seconds field, $m$ stands for minutes field, and $h$ stands for hours field. Then compare $u$s.
Comment: @SenexÆgyptiParvi There's no requirement to use nanoseconds as the base unit. You could use hours if you want to. Just have the data be doubles.
Comment: The reason I specified nanoseconds is that the top line of the OP's   own work did so.

How to compare times?


How to select different database row base on which radio button selected

Question: I am currently doing a bank project which I could select the months of transaction history I want to view ( Eg: Current Month, Current Month n last 1 month ) Now, I only manage to retrieve all the transaction history I had using grid view. May I know how to view transactions for different period based on the radio button selected? I'm currently using asp.net n C#
  myConnection.ConnectionString = strConnectionString;
    SqlCommand cmd = new SqlCommand("SELECT thDate, thType, thAmountIn, thAmountOut from [Transaction]", myConnection);

    myConnection.Open();

    SqlDataReader reader1 = cmd.ExecuteReader();

    GridView1.DataSource = reader1;
    GridView1.DataBind();

Comment: No one has the idea how your radio button values look like. But you can use WHERE clause in your query. `SELECT ... FROM ... WHERE thDate BETWEEN '2012/01/01' AND '2012/07/01'`
Answer: For your SQL command you could try:
SqlCommand cmd = new SqlCommand("SELECT thDate, thType, thAmountIn, thAmountOut from [Transaction] where thDate=" + RadioButtonList1.Text + ", myConnection);

Where RadioButtonList1 is replaced by the name of your RadioButtonList. This should place the value of the selected radio button into the SQL statement.
Comment: You need to create SqlConnection prior to this.
Comment: @nvrtheless I know that but I was working with the information provided, and by the sounds of it the connection has already been established as they are already able to retrieve all the details and they wanted help to narrow down the search


Como testar curl PHP?

Question: Tenho um projeto hospedado em um servidor, porém pretendo fazer uma integração para um outro site usando o curl. Só que ao passar os valores vindas do nosso banco de dados, dá erro nesse site que pretendo fazer integração, dizendo que os dados estão incorretos. Esse site é do nosso grupo, mas está em um outro servidor. Fui informado que o problema pode ser que o PHP não está fazendo o request para o Curl, outros dizem que o problema está no Curl, mas quando dou uma olhada no info.php, o curl está ativo. Tem algum meio de testar a CURL.
Alguém sabe me informar o porque isso ocorre?
Comment: Poste o código pra sabermos se é um problema nele.
Answer: Seria melhor se você mostrasse a parte do código que tá dando erro. Mas os erros comuns ao usar CURL é o fato de não estar instalado no servidor, a forma como se trata os dados e a configuração de SSL. Você pode tentar o seguinte:
Verifique se está instalado:
function _isCurl() {
    return function_exists('curl_version');
}

Na definição dos parâmetros coloque 0 (zero) para o SSL:
$ch = curl_init("URL_PARA_CONECTAR");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
...

Trate o resultado como um json array:
...
$data = curl_exec($ch);
$response = json_decode($data, true); // o true indica que você quer o resultado como array

Um exemplo de configuração seria:
$valoresParaSubmeter = array('key1' => 'valor1', 'key2' => 'valor2');
$ch = curl_init("URL_PARA_CONECTAR");

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $valoresParaSubmeter);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$data = curl_exec($ch);
$response = json_decode($data, true); // o true indica que você quer o resultado como array

var_dump($response);

Espero ter ajudado. :)
Comment: Se retorna 1 (true) significa que a curl está instalada. Tenta executar o código acima submetendo outra url que retorne um json. Ex.: site.com.br/arquivo.txt - Onde este arquivo é um código json simples. Como você disse que tem acesso aos dois servidores, tenta primeiro no mesmo servidor da aplicação solicitante e depois no servidor remoto. Obs.: Certifique-se que esteja mandando os valores na requisição exatamente como o outro site pede.
Comment: Olá Paulo. A verificação da Curl retorna (1), mas quando dou var_dump, não retorna nada.
Comment: Fiz o teste no servidor onde está o código e trouxe o resultado. Isso quer dizer que o problema pode estar no outro servidor?
Comment: Isso mesmo ou os dados que o outro servidor está pedindo não estão sendo enviados corretamente. Após a linha `$data = curl_exec($ch);` execute `echo curl_error($ch);` para ver qual o erro que está acontecendo. Se houver algum posta aqui para investigarmos. Por boa prática no final de tudo adicione a linha `curl_close($ch);` para liberar os recursos.
Answer: Não tenho muita paciência para utilizar as funções do  Curl do php, pois você acaba tendo que digitar muita coisa.
A minha sugestão é utilizar o Guzzle, que é uma biblioteca em PHP, que trata-se de um cliente para fazer requisições HTTP.
Você pode instalá-lo pelo Composer.
Daí eu utilizaria uma simples requisição:
$client = new GuzzleHttp\Client();

$res = $client->get('https://u.github.com/user', [
    'params' => ['id' => 1]
]);

Se a requisição não tiver erros, você pode capturar  a resposta com um echo $res->getBody().
Se a requisição falhar, uma Exception será lançada. Assim você poderá ver se há algo de errado com as requisições, ou até mesmo capturá-las.
try{

    $rest = $client->get('https://non-exists');

} catch (\GuzzleHttp\Exception\RequestException $e) {

        var_dump($e->getResponse()->getBody());
}

Comment: `GuzzleHttp` utiliza cURL para os requests. Ele apenas é uma biblioteca de poder de abstração e funcionalidade. Recomendar fazer uso dele sem ao menos saber utilizar a basica que é cURL pode acarretar em confusão e falta de experiência. Mas anyway, bela sugestão e examplo.
Comment: @juniorb2ss eu não sei se você compartilha da mesma opinião, mas tenho acho a forma de usar o curl (para um simples teste) mais confusa do que usar uma simples instância do Guzzle
Comment: Abstração é sim mais completo e de maior facilidade, porém, meu comentário foi a recomendação para alguém que não sabe os principios bases de cURL, compreende? Alias, Guzzle é ótimo e utilizo ele com frequencia.
Comment: Entendi sim. Obrigado pela suas colocações

Como testar curl PHP?


That sound thats used in the drop of most melodic dubstep songs

Question: I am new to music production, and I've been using Ableton for about 2 months now.
I was wondering if I could recreate the sound used in most melodic dubstep drops, here are some examples:
Just A Gent ft. R O Z E S - Limelight
Birdy - Skinny Love (Vanic Remix)
Juventa ft. Kelly Sweet - Superhuman (Culture Code Remix)
I saw it in an FLP file once, when I used FL Studio, and it was made with Harmor.
If anyone has a tutorial I could follow, or even a preset for a VST, that would be greatly appreciated!
Comment: The YouTube links have timestamps :) Just need to click them
Comment: Can you happen to provide timestamps of these melodic dubstep drops?
Answer: It sounds like a big chord played with a few detuned saws, you should be able to get the sound in any synth that you have available.
Here's a tutorial that's using Serum (

).
If you're using Massive a dimension expander will probably help to fill out the sound.


The For loop function won't work but gives the same result without any messaging error

Question: Once the date filter in column L is applied then J1 counts the number of items visible. In the provided code below, I'm trying a date loop where i can go back in time and look at a specific month. E.g look at the month previous to the one i may be looking at and so on.
I have tried making small sub macros that i coulmd call on once the main macro finishes to run but i am not able to put them together such that the small macros are called in order and executed one after the other.
Option Explicit

Sub trial_trial_Table()

    Dim StartDate As Long, EndDate As Long, mois As Long, nextmonth As Long, z As Long, x As Long, i As Long

    z = StartDate
    StartDate = DateSerial(Year(Date), Month(Date) - 1, 1)
    x = EndDate
    EndDate = DateSerial(Year(Date), Month(Date) - 0, 0)

    z = 1

    For z = StartDate - 1 To StartDate

        z = z - 1

        x = 0

        For x = 0 To 12 'EndDate

            x = x - 1

            StartDate = DateSerial(Year(Date), Month(Date) - 1, 1) 'The first day of the previous month:
            EndDate = DateSerial(Year(Date), Month(Date) - 0, 0) 'The last day of the previous month:

            Sheets("Essais").Select

            ActiveSheet.Range("$A$1:$M$4822").AutoFilter Field:=12, _
                                                    Criteria1:=">=" & StartDate, _
                                                    Operator:=xlAnd, _
                                                    Criteria2:="<=" & EndDate
        Next x

    Next z

End Sub

I would like the macro to function. If you may please help.
Answer: Not sure, what you are trying to accomplish. If want to call a "small" sub inside of another sub, you can do it with the command call:
Call NameOfSmallSub()

That way, you can call any number of macros in a row.
A couple of hints to get your code going:
Each long variable holds the value 0, when initialised (your Dim command). So when you assign StartDate to x right after the initialisation, you could just write "x = 0" instead. Since you set another value to x after that without using x in between, this assignment is not needed at all.
Also, when you substract 0 from a number this has no effect on it. So instead of writing "Month(Date) - 0" this would be exactly the same "Month(Date)". I am not sure, what you expect from a DateSerial return with day "0". I would advise you to debug your code line be line and observe all of your variables to see what is actually happening.
Your loop will run forever, since you decrement your looping variable x every time. Your loop can never reach its end like that. But what do you need your loop for anyhow?
It seems, you are not familiar with vba scripting. Probably you can achieve in excel what you want even without vba scripting? I would ask a new question and descrive what I want to have and ask for a good way to achieve that.
I hope this helps a little.
Comment: what i want to accomplish is the following, filter automatically column (12) according to the current month in such that the macro can go: current month-1=april, current month-2=march, current month-3=february and so on.....
Comment: If you are more specific, it will help. How does your table look like? What do mean with "[whatever] can go: current mounth-1 = april" and so on?
Comment: Hey @bejo i've added some information as requested, hope it helps and thanks for yours efforts.
Comment: @Jemmy Please explain, what you do or want to do in excel step by step. Probably then I will have a chance to understand what you need. What do you want to have or see at the end when the macro has finished running?


Importing Numpy in embedded Python c++ application

Question: I would like to have a script invoke numpy from a c++ embedded python runtime by setting the runtime path to know about the numpy module located within site-packages.
However I get the error:

cannot import name 'multiarray'

from \Lib\site-packages\numpy\core__init_.py on the line
from . import multiarrray

I have tried to set the os.path to be xxx\numpy\core but it still cannot seem to find the multiarray.pyd file during the import statement
I have read through similar questions posed but none of the answers seem relevant to my case.
I am using Python 3.4.4 (32 bit) and have installed Numpy 1.11.1 using the wheel
numpy-1.11.1-cp34-none-win32.whl

python -m pip install numpy-1.11.1-cp34-none-win32.whl

Completed without any errors.
Seems like the failure message maybe more general than just an incomplete PYTHONPATH?
Also think it might be broader than Numpy in that ANY .pyd based package that is imported from the embedded environment will have this problem?
Any help appreciated.
Answer: Did you ensure all your NumPy includes: \numpy\core\include\numpy\ were present during the build?  That's the only time I get those types of errors was if the build couldn't find all the NumPy includes...  although during embedding I found that the numpy entire directory (already built on your build machine) has to be inside a directory under Py_SetPath(python35.lib;importlibs); assuming importlibs is a directory with NumPy inside and anything else you want to bundle.
Comment: Thanks. Yes I did. We have managed to get it working on another system..only difference being using python 3.4.1 instead of 3.4.4 (python34.dll was for python 3.4.1)
Answer: Seems like the answer was to install python 3.4.1 to match the python34.dll version of 3.4.1.


Is it possible to use non-imported packages in a package vignette?

Question: I'm writing a vignette for one of my packages.
In this vignette, I would like to demonstrate how this package can interact with other packages that are not being imported by the NAMESPACE or by the Imports section of the DESCRIPTION file.
So, I'm putting a require call to use these external packages in my vignette, but of course I got the following NOTE when I try to R CMD check the package:
* checking for unstated dependencies in vignettes ... NOTE
'library' or 'require' call not declared from: 'RColorBrewer'

Is there any way around this, or should I either import these external packages or "fake" the vignette using eval=FALSE?
Answer: Put it in Suggests: of your DESCRIPTION file.
From p. 6 of the R extensions manual:

The 'Suggests' field uses the same syntax as 'Depends' and lists
  packages that are not necessarily needed. This includes packages used
  only in examples, tests or vignettes (see Section 1.4 [Writing package
  vignettes], page 26), and packages loaded in the body of functions.
  E.g., suppose an example from package foo uses a dataset from package
  bar. Then it is not necessary to have bar use foo unless one wants to
  execute all the examples/tests/vignettes: it is useful to have bar,
  but not necessary. Version requirements can be specified, and will be
  used by R CMD check.
Comment: Thanks Ben, that did the trick - I just did not understand the capabilities behind the `Suggests` field obviously. Sorry it turns out to be a bit of a RTFM question!
Answer: In addition if the vignette properly depends on that package, there should be a
% \VignetteDepends{...}

statement in the vignette itself: Sweave, Part II: Package Vignettes, R News 3/2 (Oct. 2003), 21 - 24.
However, your case possibly is a bit different:
I use if (require ("pkgxy")) without % \\VignetteDepends{pkgxy} (Suggests: pkgxy in the DESCRIPTION is needed anyways) for some things I want to show but where I don't want to force the user to have all the suggested pacakges installed. I put a box at the beginning of the vignette where I report which of those packages are available and if a package is not available when the vignette is built, an "pkgxy is needed to do this" text is put into the vignette.
The "introduction" vignette of package hyperSpec is an example (to find out how it actually works, you need not only the .Rnw but also some more definitions).
Comment: Thanks for clarifying! The link to hyperSpec "introduction" is down, perhaps best start [here](http://hyperspec.r-forge.r-project.org/)  instead.


Strange "dancing" effect in a wpf datagrid with horizontal scrollbar

Question:
To reproduce: wpf datagrid - make sure size of the datagrid is such that horizontal scroll bar is visible and choose a datagridtextcolumn of a particular size - now try to enter a text which straddles this size :)
Any ideas how to fix this problem?
Comment: I couldn't reproduce, can you post a working example?
Comment: This is autoSize issue. just make some size for you columns.
Answer: How about disabling the ScrollBar when cells are being edited? Maybe you can add a handler to the DataGrid.BeginningEdit event and disable the ScrollBar there?
ScrollViewer.SetHorizontalScrollBarVisibility(dataGrid, ScrollBarVisibility.Disabled);
ScrollViewer.SetVerticalScrollBarVisibility(dataGrid, ScrollBarVisibility.Disabled);


Backup Exec - Restoring Offline Files Cache

Question: We have a set of mobile users who use Windows XP SP3 offline files to synchronize changes between network shares and their laptops.  We recently had an incident where a user's offline cache was not synchronizing and several weeks worth of changes were lost when the laptop was restaged.  Prior to the restage a full backup was performed using Backup Exec 2010 which completed successfully.  We assumed after the fact that the full backup would include the C:\Windows\CSC folder.  However, it appears that it did not.  At first, we could not see the CSC folder in the restore tree.  After enabling the server (W2K8R2x64) to see hidden files and folders and protected OS files, we can see the CSC folder within the Backup Exec restore tree, but there are no contents in the folder.  Performing a restore supports this view as no files are restored.
We realize that the files should have been synchronized (or checked for errors) before the restage.  Has anyone experienced similar problems backing up or restoring the offline file cache?
Answer: Backup Exec honors the system-wide "FilesNotToBackup" registry key (located at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToBackup) (see http://www.symantec.com/business/support/index?page=content&id=TECH31848 for details). By default, Windows XP includes a REG_MULTI_SZ entry there, "Client Side Cache", with the value "%SystemRoot%\csc* /s". This, I would suspect, is the reason your client side cache files didn't get backed-up.
Comment: That was it.  I hope we never again need to resort to a restore from CSC, but it's good to note for reference. Thanks!


Integrating SharePoint with a web application

Question: Is it possible to have a Java/J2EE web application integrate/communicate with SharePoint to load, search, and retrieve docs?
Answer: You can communicate with SharePoint from Java using the web services:
http://www.developer.com/tech/article.php/3104621

Uploading files to WSS:
Upload file to SharePoint WSS 3.0 with WebRequest PUT
Searching docs: /_vti_bin/Search.asmx
Lists (can query a particular library): /vti_bin/Lists.asmx
Answer: Sharepoint exposes a lot of its functionality through web services.  If you are familiar with working with web services, this could be the easiest way for you to work with Sharepoint.  I found this site just now http://www.developer.com/tech/article.php/3104621  which shows some of the break down of web services available although the code is in VB.  If you do additional searches on Sharepoint and Web Services, you should get more sites that can help you.
Answer: Agreed, web services are the way to go.
http://msdn.microsoft.com/en-us/library/ms479390.aspx
I've done some work on this, with Java, and it's pretty easy to get them talking.
Answer: You can use web services as others have suggested to integrate at the service level, this might be the best way.
There is however, the possibility to intergrate at the UI level using Web Service Remote Portlets. There is a WSRP Toolkit for Sharepoint:
http://blogs.msdn.com/sharepoint/archive/2008/12/05/announcing-the-wsrp-toolkit-for-sharepoint.aspx
Answer: You can use the CNS Media GateWay which can help to intergrate sharepoint or any other ms server with your java web application.
You can connect from any custom application like java to MS Exchange (2000 - 2013), MS SharePoint, Dynamics CRM, Dynamics NAV and many more via the CNS ODBC and JDBC driver, thus accessing, for example, the entire Exchange mailbox from your custom application.
Please let me know if you need some more information.
for more info visit:
http://www.connecting-software.com
Comment: You may want to reformulate your answer to sound less like a sales pitch, and also disclose your own affiliation with the product and/or site.


How to set the ticks on a logarithmic axis in matplotlib

Question: I'm trying to draw nice ticks (scalar not exponential) on a logarithmic y-axis in matplotlib. In general I want to include the first value (100in this example) an work from there. But in some cases I get different tickers like below. I have found no clue as how to manage this. Is there an uncomplicated way to force matplotlib to start with a specific value and automatically select sensible tickers thereafter (in this example 120, 110, 100, 90, 80, 70, 60, 50, 40, 30, 20 would be nice).
My code:
from matplotlib.ticker import  ScalarFormatter, MaxNLocator
x = range(11)
y = [ 100.,   91.3700879 ,   91.01104689,   58.91189746,
     46.99501432,   55.3816625 ,   37.49715841,   26.55818469,
     36.34538328,   37.7811044 ,   47.45953131]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_yscale('log')
ax.yaxis.set_major_locator(MaxNLocator(nbins=11, steps=[1,2,3,4,5,6,7,8,9,10]))
ax.yaxis.set_major_formatter(ScalarFormatter())
ax.plot(x,y)

Result:
Answer: You can use set_ylim():
ax.set_ylim(20, 120)

This could be one way to make the limits depend on the y-data instead of hard-wiring them:
ymax = round(max(y), -1) + 10
ymin = max(round(min(y), -1) - 10, 0)
ax.set_ylim(ymin, ymax)

You can force the tick locations with ax.set_yticks():
ymax = round(max(y), -1) + 20
ymin = max(round(min(y), -1) - 10, 0)
ax.set_ylim(ymin, ymax)
ax.set_yticks(range(int(ymin), int(ymax) + 1, 10))
ax.plot(x,y)

For:
y = [ 100. , 114.088362 , 91.14833261, 109.33399855, 73.34902925,
      76.43091996, 56.84863363, 65.34297117, 78.99411287, 70.93280065,
      55.03979689]

it produces this plot:
Comment: Thanks. But how can I calculate sensible max and min values for an arbitrary case and how can I be sure that my starting value (`100` in the example above) is considered. I don't know the y-values beforehand. They can be almost any in the range [0, infinity[. The lowest value is limited to 0, but the highest is not limited (but probably won't be above a few millions at most)
Comment: You need to have `y` before you can plot. So `max(y)` will give you the maximum value. Than round to the next multiple of 10 or so.
Comment: No, unfortunately not. It works for this example, but if I replace `y=[...]`with `y = np.insert(np.cumprod(1 +(np.random.rand(10) - 0.5) / 1) * 100, 0, 100)` or special case `y = [ 100.0, 115.33050843,  171.99107963,  160.55507531, 228.98360629, 134.5789104 ,  162.94746556, 231.23097845, 295.907982  ,  289.18785165,  242.93483293]` it won't work. `100` is not included in the tickers of the special case.
Comment: I am very sorry, but won't work. For example with `y=[ 100.        ,  114.088362  ,   91.14833261,  109.33399855,  73.34902925,  76.43091996,   56.84863363,   65.34297117,  78.99411287,   70.93280065,   55.03979689]` ticker `100`is missing. Instead you get `..., 90, 99, 108, ...`. It is easy to find a solution for a special case, but very difficult for an arbitrary one.
Comment: Perfect. Works for me too. Thanks!


Number of elements in cartesian power with a majority constraint

Question: Problem: I would like to know the number of elements in the cartesian power $X^n$ (cartesian product of one set $X$ by itself, $n$ times) with a majority constraint: how many elements in $X^n$ have a (relative) majority of one element of the set (say $x\in X$)?
On top of that, I'd like to fix one element in the cartesian power to a certain value (say the second), and count the number of possibilities with this fixed value.
Simple example: with $X=\{A, B, C\}$ and $n=4$. The question is: how many four-letter words with an $A$ in the second position have a (relative) majority of $A$'s? And how many have a (relative) majority of $B$'s?
Solution for the simple example: We can iterate on the total number $k$ of the element we want as a (relative) majority (say $A$).

With $k=4$ elements being $A$, there is 1 option ($A$ is the majority, and $A$ is in the second position)

$AAAA$

With $k=3$ elements being $A$, there are three possibilities for locating $A$'s. The second element is $A$ by constraint. The two extra $A$'s can be in position $(1,3), (1,4)$ or $(3,4)$. And there is one free position, where it can be everything but $A$: 2 possibilities. In total: $3\times 2=6$ possibilities.

$AAAB, AAAC, AABA, AACA, BAAA, CAAA$

With $k=2$ elements being $A$'s, there is an extra-challenge: the two remaining positions should not be the same, otherwise $A$'s are not a majority anymore. About locating the $A$'s, one is fixed in the second position and the other $A$ can be in position $(1)$, $(3)$ or $(4)$: 3 possibilities. In the two remaining positions, there are 2 possibilities for the first one ($B$ or $C$ but not $A$) and 1 possibility for the second one (not $A$ and not the same than the first one). Total: 6 possibilities.

$AABC, AACB, BAAC, CAAB, BACA, CABA$

With $k=1$ element being $A$, there are zero possibilities for $A$ to be a majority (three remaining possibilities, with only two letters, $B$ and $C$, so necessarily a majority of $B$ or $C$).

So with $n=4$ and 3 elements in the original set, there are 13 possibilities.
General solution? Is there a closed form formula to compute this number?
Same problem, expressed in a network formulation: In a network with 3 rows ($\{A, B, C\}$) and $n=4$ columns, assuming paths from left to right (e.g., using node $A_1$, then $B_2$, then $A_3$ and finally $C_3$), the question becomes: how many paths are going through node $A_2$ and have a (relative) majority of $A$ nodes?
Same problem, expressed in a voting context: Calculate winning outcomes of plurality voting
Comment: I asked a similar-but-more-complex question here: http://math.stackexchange.com/questions/1157735/counting-elements-in-cartesian-power-with-majority-constraint-pattern-constrai
Answer: Let $|X|=m$ (the number of candidates) and $n$ be the number of voters.  For the first question, by the basic theory of exponential generating functions, the number of ways for candidate $A$ to get a plurality of votes is the coefficient of $\frac{x^n}{n!}$ in the sum
$$\sum_{k\ge0} \frac{x^k}{k!}\left(1+x+\frac{x^2}{2!}+\cdots+\frac{x^{k-1}}{(k-1)!}\right)^{m-1}.$$
To see this, sum over all possible numbers $k$ of votes that $A$ gets; the other $m-1$ candidates can get up to $k-1$ votes each.  (Some terms in this sum are zero, but that's OK.)
For the second question, if you fix one of the votes, there are two possibilities, depending on whether you're fixing a vote for $A$ or for another candidate.  In the former case, the answer will be
$$\left[\frac{x^{n-1}}{(n-1)!}\right]
\sum_{k\ge0} \frac{x^{k-1}}{(k-1)!}\left(1+x+\frac{x^2}{2!}+\cdots+\frac{x^{k-1}}{(k-1)!}\right)^{m-1}
$$

(the notation $[z^n]f(z)$ denote the operation of extracting the coefficient of $z^n$ in the formal power series $f(z)=\sum f_n z^n$ in analytical combinatorics. See Philippe Flajolet and Robert Sedgewick, Analytic Combinatorics, Cambridge University Press (2009), p.19))
(the coefficient $A_n$ in an exponential generating function is recovered by $A_n=n!\cdot [z^n]A(z)$, since $[z^n]A(z) = A_n/n!$ (ibid., p.98))

since we now have to place $k-1$ votes for $A$.  (This gives the same $13$ as in your example.)  Similarly, if you're fixing a vote for one of the other candidates, the expression becomes
$$\left[\frac{x^{n-1}}{(n-1)!}\right]
\sum_{k\ge0} \frac{x^{k}}{k!}\left(1+x+\frac{x^2}{2!}+\cdots+\frac{x^{k-1}}{(k-1)!}\right)^{m-2}\left(1+x+\frac{x^2}{2!}+\cdots+\frac{x^{k-2}}{(k-2)!}\right).
$$
Comment: First, the sum over $k$ is really a finite sum, since you only have to consider terms up to $k=n$ -- $A$ can only get $n$ votes.  So the sum is just a polynomial.  You can use a free computer algebra system such as Wolfram Alpha to expand it out, or just ask for the coefficient of $x^n/n!$.  (To get this, you can simply grab the coefficient of $x^n$ and then multiply by $n!$)
Comment: Thank you for your answer. I'm not familiar with exponential generating function. How can I use your results to compute the number of ways with a majority of votes for $A$ for, say, $m=8$ and $n=12$? Sorry if it is a stupid question, but I don't understand.
Comment: I'm not familiar with Wolfram Alpha, so I did it in Python: http://stackoverflow.com/a/28581921/762435
Comment: Tad and others interested in this answer: I asked a similar-but-more-complex question here: http://math.stackexchange.com/questions/1157735/counting-elements-in-cartesian-power-with-majority-constraint-pattern-constrai
Answer:
If $k>n/2$:

For non-fixed elements of the majority ($k-1$), there are $\binom{n-1}{k-1}$ possibilities (it works in the simple example with $k=4$: $\binom{3}{3}=1$; and $k=3$: $\binom{3}{2}=3$).
The number of "free" positions (for other elements than the majority) is $n-k$. For each position, there are $|X|-1$ possibilities (all elements in $X$ but the majority one). So, $(|X|-1)^{n-k}$ possibilities.
In total: $(|X|-1)^{n-k} \cdot \binom{n-1}{k-1}$ possibilities

If $k<n/2$:

Same reasoning for the positioning of "majority" elements: $\binom{n-1}{k-1}$ possibilities.
The number of free positions for other elements is also $n-k$. But no element in these combinations must appear more than $k$ times. One way of computing this is to (1) count all possibilities: $(|X|-1)^{n-k}$ and (2) remove all possibilities with $k, k+1, k+2, ..., n-k$ of one element, for each element.
Step (2) as a subquestion here: Number of elements in cartesian power with a maximum constraint

Step (2) for one given other element

For one specific other element, with $k$ of this element: we fix $k$ times the other element: $n-k$ free spaces, $k$ elements, $\binom{n-k}{k}$ possibilities. For each possibility, we put the others (no majority, no other one): $n-k-k$ free spaces, $|X|-2$ elements, $(|X|-2)^{n-k-k}$ possibilities.
In total: $(|X|-2)^{n-k-k}\cdot \binom{n-k}{k}$ possibilities for a given other element with $k$ appearances.
For $k+1$ appearances: $(|X|-2)^{n-k-k-1}\cdot \binom{n-k}{k+1}$ possibilities
...
For $n-k$ appearances: $(|X|-2)^{n-k-k-n}\cdot \binom{n-k}{n-k}= 1$ possibility, intuitive.

So, for one specific other element: $\sum_{j=k}^{n-k} (|X|-2)^{n-k-j}\cdot \binom{n-k}{j}$ possibilities. BUT double counting (see Number of elements in cartesian power with a maximum constraint), so $j$ in the sum has a different starting point: $j=k + \lfloor \frac{n-k-k}{2} \rfloor=k + \lfloor \frac{n-2k}{2} \rfloor = k + \lfloor \frac{n}{2} - k \rfloor = \lfloor \frac{n}{2} \rfloor$, and so for one specific element: $\sum_{j=\lfloor \frac{n}{2}\rfloor}^{n-k} (|X|-2)^{n-k-j}\cdot \binom{n-k}{j}$

Step (2) for all other elements:

There are $|X|-1$ other elements, so the number of possibilities with more than $k$ times any other element is $(|X|-1)\sum_{j=k}^{n-k} (|X|-2)^{n-k-j}\cdot \binom{n-k}{j}$
Final answer: $\sum_{k=1, k>n/2}^n (|X|-1)^{n-k} \cdot \binom{n-1}{k-1} + \sum_{k, k\leq n/2} \Bigg((|X|-1)^{n-k}-(|X|-1)\sum_{j=\lfloor \frac{n}{2}\rfloor}^{n-k} (|X|-2)^{n-k-j}\cdot \binom{n-k}{j}\Bigg)\cdot \binom{n-1}{k-1}$
With the simple example and $k=2$, the equation gives us $(|X|-1)^{n-k}-(|X|-1)\sum_{j=\lfloor \frac{n}{2}\rfloor}^{n-k} (|X|-2)^{n-k-j}\cdot \binom{n-k}{j} = (2^2-2)\cdot 3=6$, which is correct.


How to read result from Kolmogorov-Smirnov one-sample test in SPSS?

Question: I'm newbie and bit lost... Can someone help me read this result from SPSS 1-sample Kolmogorov-Smirnov test (poisson distribution).
<code>                                        SUBKEY1   SUBKEY2  SUBKEY3  SUBKEY4    SUBKEY5

N                                128       128       128      128    128

Poisson Parametera,,b     Mean          .4609     .4609    .4922     .5156  .4922

Most Extreme Differences  Absolute  .092      .092     .103      .113   .103

                      Positive  .079      .079     .088      .095   .088

                      Negative     -.092     -.092    -.103     -.113      -.103

Kolmogorov-Smirnov Z                1.037    1.037    1.171     1.276   1.171

Asymp. Sig. (2-tailed)              .233      .233     .129      .077   .129
</code>
From the result above, I define (in simple words):
<code>Ho = satisfied
Ha = not satisfied
</code>
but I don't know how to specify the level significance for this test and I don't know whether have to read Asymp. Sig. (2-tailed) (p-value) or Kolmogorov-Smirnov Z (D value) to be compare with critical value...
Answer: If $\alpha = .05$ is conventional in your field, I would simply state, "A one-sample Kolmogorov-Smirnov test failed to reject the null hypothesis that the data followed the Poisson distribution (D = .092, .092, .103, .113, and .103 respectively for variables 1-5, N = 128 each, and p > .05 each)." You can also report that you set $\alpha = .05$ in your methods section. Note that $Z \approx \sqrt{n} D$ in the SPSS output and that the "Asymp. Sig." (p-values) in the output should be based on critical values of the Kolmogorov distribution to which $Z$ converges in distribution (see here for a description). However, you don't need to find or report these critical values -- I would just report the test statistics and p-value in the manner above.
Comment: Hi, lockedoff... tq for the answer...
Comment: thanks for reply...i really appreciate that. But, i just want to make sure with what i understand that you state above...is it you compare the Dmax value (D = .092, .092, .103, .113, and .103) with the critical value with α=.05 (n>35 = 1.36/sqrt(n))?  which is, if the D < critical value(0.120) than you fail to reject the null hypothesis? or you just compare the p-value>0.05? I'm still newbie in this field so, there a lot of question to be ask... =)
Comment: I just want to make sure with what i understand that you state above...is it you compare the Dmax value (D = .092, .092, .103, .113, and .103) with the critical value with α=.05 (n>35 = 1.36/sqrt(n))? which is, if the D < critical value(0.120) than you fail to reject the null hypothesis? or you just compare the p-value>0.05? I'm still newbie in this field so, there a lot of question to be ask... =)
Comment: Yes, based on a quick web search, it appears that the critical value for $D$ can be approximated by $1.36/\sqrt{n}$ for $\alpha = .05$. I would rather rely on the p-value reported by the program than an imprecise approximation, but either works.
Comment: It is correct if I've got higher value of p-value from 1-sample K-S its means i got better result than the other sample that i compared? eg: Variable_1 (p-value)= 0.09 and Variable_2 (p-value) = 0.06 means that variable_1 is better distribution than variable_2 or its just the same because that accept value is >0.05 so, there is no which result better than other?
Comment: If $\alpha = .05$ then you fail to reject the null hypothesis for either variable, so they can each be considered not to differ from the Poisson distribution. It is a binary decision.


CSS touch like scroll using mouse

Question: How can I add mouse scroll option in my angular app similar to what's present for touch screen devices in which you scroll via holding screen alongside some left or right swipe movement. How can I implement similar scroll technique using mouse so that user can click at some empty area than while holding down the click move mouse in a specific direction to scroll respectively.
Similar to what's available for trello.com:

I would prefer to implement this behavior using pure CSS as chrome's inspector tools also provides this feature while testing site's responsiveness for different screen sizes. So if its possible via CSS it would be great.

If it won't be possible via CSS then I would like to implement using JavaScript or TypeScript.
Comment: Since you haven't posted any of your code I will just link you a sample codepen: https://codepen.io/JTParrett/pen/rkofB and a js library https://github.com/asvd/dragscroll. Both with slight modifications will help you achieve what you need.
Answer: You could use this library: http://hammerjs.github.io/. It covers a large range of gestures you might be interested in.

CSS touch like scroll using mouse


Arrow below staff pointing to number

Question: What does this arrow below the staff pointing to six mean? Do I repeat the measure until 6, rest until 6, or something else? If it helps at all this is pit orchestra music for a musical :)
Thanks!
Comment: @MattPutnam I've been told to ask questions in rehearsals for the exact reasons I mentioned - in case others have the same question. I guess different MDs have different styles.
Comment: You might also ask your MD - even in a rehearsal. Others might have a similar mark on their parts and not know what it means.
Comment: @ToddWilcox do NOT waste time in rehearsal asking pointless questions about measure numbers.
Comment: @ToddWilcox I guess it depends on the type/level of ensemble, but in a musical theatre rehearsal you're typically looking at something like 3 hours to get through 1.5-2 hours of music. You absolutely cannot stop for questions about measure numbers. My general rule is, if your question can be (rudely) answered with "just play the music on the page" then it's a bad question. Because even if your MD manages a more polite response, that's exactly what they're thinking. Maybe it's a typo, maybe it means something, but you should just play the page and if that works, then shrug it off and keep going
Comment: @MattPutnam: Since this question is "Should I play bar 1 on repeat 5 times, play it once and then rest for 4 bars, or something else?", it's not a question that can be answered with "just play the music on the page". Because doing either of the things the questioner has (reasonably) guessed it might mean would be quite disruptive. _You_ may know that the notation in question is merely an irrelevant detail about measure numbers, but someone who doesn't know that... doesn't know that!
Comment: @psmears The question is very valid on this site, but it's still bad etiquette to ask in rehearsal. If you do indeed just play the notes on the staff, you'll accidentally do the right thing. Or maybe you guess wrong--maybe you guess it means to rest until m. 6. Okay, so you mess up once in rehearsal (which is fine), everyone gets to m. 9 4 measure before you, and you figure it out. Similar if you guessed it meant to repeat. All solutions that don't involve interrupting rehearsal.
Comment: @MattPutnam: That... depends. If you get it wrong - either you figure it out by yourself (great!), or the rehearsal is disrupted while the MD tries to figure out why half the players are doing one thing and the others are doing something different and it sounds terrible. (As you say, this will depend _a lot_ on the type/level of the group you're playing with. But if a 10 second question+answer can save a couple of minutes of chaos, it's likely to be worthwhile :) ).
Answer: This is an indication that the measure numbers are discontinuous. The numbering goes from 1 directly to 6, so presumably there were measures 2-5 that got cut at some point.
This happens frequently in musical theater, because during the original production, the music is constantly being adjusted and measures are added or removed. However, the entire production has already started to refer to points in time by measure number, so you can't change measure numbers after they've been written. For example, the Lighting Designer has already decided that a particular lighting cue will happen at m. 50, and if you change the measure numbers, then everyone's notes go out of date and it's pure chaos. So instead, we deal with discontinuities like this.
When measures are added, they'll get a letter suffix. So if it's decided that an intro isn't long enough and 4 more measures need to get added between m. 4 and 5, then those measures get numbered 4A-4D.
Comment: Is the arrow symbol a standard notation for measure number discontinuity?
Comment: @ElementsinSpace It's non-standard (it's the first time I've ever seen it) but very obvious. Often there is no special marking apart from the measure numbers themselves, often the is a marking "[to 6]" over the stave. The arrow seems like a very good solution.
Comment: Preserving measure numbers also also means that cuts can be marked in orchestral parts rather than having to reprint them.
Comment: I guess it's nonstandard in the sense that musical theater does a lot of weird things like this that don't usually happen in other settings. But in the context of musical theater, this is common and I think most of the materials delivered by MTI are marked like this.
Comment: @MattPutnam Non-contiguous measure numbers are standard. The arrow is not (but a good idea).

Arrow below staff pointing to number


when i clicked add row button added row but jquery datepicker not working

Question: when i added datepicker to my added rows.but date picker not working.
but it works only first tr. when i remove first tr datepicker remaining added rows date picker working
please see below code.
$(function() {
    $( ".datepicker" ).datepicker({

         defaultDate: "+1w",
         changeMonth: true,
         maxDate: new Date(),
         dateFormat: 'yy-mm-dd',
         numberOfMonths: 1,

    });  });

function addRow(tableID) {
        var table       = document.getElementById(tableID);
        var rowCount    = table.rows.length;
        var row         = table.insertRow(rowCount);
        var colCount    = table.rows[0].cells.length;

        for(var i=0; i<colCount; i++) {

            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[0].cells[i].innerHTML;
            switch(newcell.childNodes[0].type) {
                case "text":
                        newcell.childNodes[0].value = "";
                        break;
                case "checkbox":
                        newcell.childNodes[0].checked = false;
                        break;
                case "select-one":
                        newcell.childNodes[0].selectedIndex = 0;
                        break;
            }
        }
        var $row = $(row);
        $row.find('input.datepicker').datepicker({
             maxDate: new Date(),
             dateFormat: 'yy-mm-dd',
        });

    }

html code for above js
`
<input type="button" class="btn btn-default" value="Add Row" onClick="addRow('add_row')"/>

                                <input class="form-control datepicker" type="text" name="date[]" id="date" placeholder="Date"/>

                                        <input class="form-control" type="text" name="hours[]" id="hours" placeholder="hours(hh:mm)"/>

                                    <input type="button" class="btn btn-default" id="delPOIbutton" value="Delete" onClick="delete_check('add_row',this)" />

`
Comment: Did you load jqueryui?
Comment: i loaded jquery ui.js and jquery ui.css but not working
Comment: can you also include the css code here.. I got errors of onclick trying to use external source.
Answer: The problem was in the second line.
What you have is:
$( ".datepicker" ).datepicker({

It should be like this.
$(function() {
$(".datepicker").datepicker()({

  defaultDate: "+1w",
  changeMonth: true,
  maxDate: new Date(),
  dateFormat: 'yy-mm-dd',
  numberOfMonths: 1,

}); });

In addition you need bind a click event to the addRow and move the new row up into the dom.
$(".datepick").datepicker();
var newRowNum = 0;

// bind a click event to the "Add" link
$('#addnew').click(function() {

$(".datepick").datepicker("destroy");

You can view more here.
http://jsfiddle.net/norcaljohnny/hq2r9Lbq/
Comment: thanks norcal but this code not suitable for my code. i tried your way but not working.
Comment: my js and css are

jquery version 1.11


Get stacktrace inside c# method

Question: I want to implement universal logger which help me to see call stack of the methods.
I know there are some methods from System.Diagnostic but they were introduced in .net 4.0 and I'm afraid it will not work on xamarin or .net core or something like that. So I want to have more universal solution.
Another problem is async\await which introduce some mess.
I through about passing additional parameter in each method which store some context and help me to determinate call stack, but this solution is a bit complex.
Also I can read thread stack memory using unsafe code and check call stack by myself but it is not reliable.
Are there any other solution ?
Comment: You could certainly hack it around: throw an exception, catch it and read callstack from it :)
Comment: @MarcinJuraszek Nice hack:) but I'm afraid it will affect performance too much.
Answer: You could just use Environment.StackTrace. That has been part of the Framework since the very beginning.
Environment.StackTrace will return the complete stacktrace (including the call to Environment.StackTrace itself) as a line separated string.
Something like this:

at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at WpfApplication2.MainWindow.GetStack(Int32 removeLines)
at WpfApplication2.MainWindow.Button_Click(Object sender, RoutedEventArgs e)
...
at System.Threading.ThreadHelper.ThreadStart()

All you need to do is split/parse/format it, whatever you want to do with it.
Since you'll be using this from within your own classes, remember to remove the newest X lines.
This code should work everywhere since it's deliberately low-level.
private static string[] GetStack(int removeLines)
{
    string[] stack = Environment.StackTrace.Split(
        new string[] {Environment.NewLine},
        StringSplitOptions.RemoveEmptyEntries);

    if(stack.Length <= removeLines)
        return new string[0];

    string[] actualResult = new string[stack.Length - removeLines];
    for (int i = removeLines; i < stack.Length; i++)
        // Remove 6 characters (e.g. "  at ") from the beginning of the line
        // This might be different for other languages and platforms
        actualResult[i - removeLines] = stack[i].Substring(6);

    return actualResult;
}

Comment: One note, .net has different stack trace output for different languages, so it is necessary to be careful while removing "at" and other  language depended words.
Comment: Good thought. I'll include that in the answer for future reference.

Get stacktrace inside c# method