What speed should I achieve for 8th note exersizes on the guitar

Question: I'm going through Linear Articulations by Pat Martino.  He says "upon completions of this section, one should move to the next phase" after showing a bunch of 8th-note exercises oriented around chords and inversions.
How would you go about taking on a book like this, or any exercise set? I've heard 300bpm is a good tempo for playing jazz. Would you master these at 300bpm and then move on?
Looking for advice from someone who can play really fast.
Comment: @FrankHenard: bpm is just beats per minute; so if you have 4/4 then you'll have that many quarter notes per minute, e.g. 300. This means 600 eighth notes, 1200 sixteenth notes, etc. If you have 150 bpm then you have as many 16th notes per minute as you have 8th notes at a tempo of 300 bpm.
Comment: @DrMayhem: Traditional jazz themes are often based on 8th notes. So 300 bpm is not that uncommon as you may think. It's not rock or pop (where we use lots of 16th notes). It's just about the way it's notated. A fast theme notated with 8th notes (as is common in jazz) will go up to about 300 bpm, which must be compared to 150 bpm if we notate in 16th (as more commonly done in rock/pop music). This is not to say that the OP should not move on before being able to play that fast.
Comment: @Matt L.: Forgive my lack of expertise in time signature.  I'm not an accomplished musician.  However, this discussion is confusing me.  Doesn't bpm mean like quarter notes for 4/4 time?  It seems like you are changing the bpm number based on more granular divisions like 1/8th notes and 1/16th notes.  Perhaps you are right, but I've just never heard of this.
Answer: There are two things to consider here. First, very fast jazz compositions (such as Coltrane's Giant Steps ) are indeed often played close to 300 bpm. This is of course a consequence of the way the theme is notated. The standard notation for Giant Steps found in most real / fake books (see here) is to use half notes in the first two bars. Of course, if you used quarter notes instead you would end up at around 150 bpm, but that's just not the way it is done.
The other important thing is how to work with such a book. Even though you might come across eighth notes at 300 bpm, I would not recommend to wait until you master the first few exercises at that tempo. First of all, it's not only about speed. You want to cleanly execute all examples, and you want to learn how to choose the notes and how to play idiomatic solo lines. Try to play them cleanly and with good timing, and choose whatever tempo is appropriate for you, then move on. You move on to learn more phrases and to improve your solo vocabulary. At the same time you should try to improve your technique and increase the speed, but that's something you do while working through the book. If you try to play the first few examples at very high speeds, you will have almost no solo lines in your repertoire until you've learned enough technique, and that's frustrating and not useful. Because in practice, most pieces you'll come across are NOT played at 300 bpm.
Comment: Thats a good tip.  I think in my obsession with mastering one little exercise i hold myself back from expanding.  Im at like 230 - 250 so I will probably move on now.  Thanks for the insight!
Comment: @MingMan: Clean 8th notes at 250 are not bad at all!
Answer: 300bpm ?   thats insanely fast, I wouldnt expect jazz (and its a broach church from slow jazz blues to fast ragtime) to ever go faster than about 140. If it were me, I would raise it by 10bpm each time.
Comment: Ever listened to Coltrane's [Giant Steps](https://en.wikipedia.org/wiki/Giant_Steps_(composition))? The way it is notated (half notes in the first two bars) you get close to 300 bpm.
Comment: @bigbadmouse You would raise it by 10 but then what?  Would you move on to the next section when you hit 150 (im assuming youre playing 16th notes, which equals time wise my 8th note 300 bpm) would you move on before? My question was less detail oriented and more when do you say "I got this down, time to move to the next exercise"?


How to change fields permission using some action in the Rules module?

Question: I installed the Field Permissions module to grant access of the individual fields to the roles.
I need to change the permission of some fields when an event occurs. How do I can add the field edit permission to the Action component of the Rules module?
Answer: To my knowledge, there is no way you can "add the field edit permission to the Action component of the Rules module" (as in your question), which is somehow confirmed in the Post installation Support forum via the issue about "Field Edit Permissions Based on Rule?" also.
However, in one of the comments of that link, there is an interesting work around that might work in your case also:

Create a user role that has editing permissions for the field, then assign that user role to a user with Rules when the conditions you require are met.
You'd then possibly need to remove that role after updating the content depending on your workflow.

PS: I'm assuming this question is about D7.


Qual o significado e forma de uso de volume no Dockerfile?

Question: Em um arquivo Dockerfile qual o significado da instrução:
VOLUME /arquivos

Imagino que isso crie um volume, mas como isso é usado e qual seu real significado?
Answer: No dockerfile os volumes informam ao docker os pontos de montagem nos containers criados a partir da imagem que está construindo (com o dockerfile).
Isso permite ao docker alocar volumes dinamicamente, ou ainda informar para os consumidores da imagem quais são os pontos de montagem necessários para se manter estado dos containers criados com a tal imagem.
No DockerFile os volumes são definidos como:

VOLUME /path/dir/1/
VOLUME /path/dir/2/

Você pode ainda informar vários volumes (não precisa ser um só) em várias sentenças ou em formato de array: como abaixo.

VOLUME ["/path/dir/1/", "/path/dir/2/"]

No subcomandos Docker Run/Docker Create o parâmetro curto -v ou a versão longa --volume são usados para mapear volumes. Entretanto não há obrigatoriedade/restrição alguma. Você pode mapear os volumes que foram determinados no dockerfile ou outros volumes, ou ainda ignorá-los. Não há validação alguma quanto a isso, portanto é preciso ter atenção e cuidado.
Answer: Volume é quando você precisa compartilhar diretório ou pasta entre o filesystem do host e o filesystem do container.
VOLUME /opt/host /opt/container
No dockerfile sempre o primeiro parâmetro refere-se ao host e o segundo parâmetro refere-se ao mapeado para o container.
Por outro lado, se você omitir o segundo parâmetro como abaixo, então no docker run você poderá passá-lo ou pedir que o docker faça automaticamente.
EXPOSE 8080
Quando rodar o comando "docker run" e passar o comando abaixo então uma porta aleatória irá ser mapeada no host para o porta 8080 do container.
docker run -p 8080
Ou podemos usar:
docker run -p 80:8080
O comando acima quer dizer que a porta 80 do host irá acessar a porta 8080 do container.
Comment: Volume (no dockerfile) não possui 2 partes e não tem relação entre host e container.


Evaluate truthiness in Java

Question: I am writing an interactive console app in Java. I need to ask the user questions with Boolean responses, however, Scanner.in.nextBoolean() is rather brittle in that it throws exceptions on incorrect input, so wrapping it in a method seems like a good idea. I could just use a try/catch block and insist on the user typing "true" or "false" to answer and catch the typos. But then I thought I could use Scanner.in.next() or Scanner.in.nextLine() and evaluate the returned string for truthiness using something like parseBoolean(String s).
Is there a way to evaluate a string for "truthiness" beyond true/false? That is, "0"/"1" "yes"/"no" would also evaluate to true/false.
Comment: @Ron Jensen I have retracted my close flag since you no longer ask for a library, however typically you are required to include the code of what you have attempted and not just ask a general question or ask "provide the solution of this for me".
Comment: How do you want your program to respond if a user enters something that isn't obviously true or false, for example "foo" – should that be treated as "false"? or throw an exception? One approach would be: read a string, then look sequentially for all variations of "true": t, true, 1, yes, y, etc., and then treat every other input as "false".
Comment: @kaan, I don't want to throw exceptions, as I want something self-contained. Everything that isn't explicitly true is false is definitely one way to do it.
Comment: @Nexevis, I re-phrased the question and Butiri Dan provided an answer that does not refer to a book, tool, software library, etc.
Answer: Apache BooleanUtils have a method toBoolean working like this, however it does not parse 0/1 as far as I see in documentation

'true', 'on', 'y', 't' or 'yes' (case insensitive) will return true. Otherwise, false is returned.
Answer: What about a custom implementation?

Use a map and define all the values for true and false
Use a list; true if the value is in the list, otherwise false

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    // Define true and false values
    Map<String, Boolean> truthiness = new HashMap<>();

    truthiness.put("yes", true);
    truthiness.put("1", true);
    truthiness.put("true", true);
    truthiness.put("t", true);
    truthiness.put("ya", true);
    truthiness.put("nein", false);
    //etc

    // Define only the true values
    List<String> trueValues = Arrays.asList("yes", "1", "true", "t", "ya");

    for(int i = 0; i < 5; ++i) {
        String value = sc.nextLine().toLowerCase();

        System.out.println("map: " + truthiness.get(value));
        System.out.println("list: " + trueValues.contains(value));
    }
}

Output
yes
map: true
list: true
1
map: true
list: true
t
map: true
list: true
ya
map: true
list: true
nein
map: false
list: false

Evaluate truthiness in Java


Adding form placeholders to text form elements

Question: Is there a way to add placeholders to a form with a module, or should this be done with a form template?
Answer: That's an HTML5 placeholder, you can just add it as an attribute to any element and HTML5 enabled browsers will react accordingly:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'some_form') {
    $form['some_element']['#attributes']['placeholder'] = t('Placeholder text');
  }
}

A short recursive function like this might be handy if you want to automatically add placeholders for every textfield in a form (based on the field's title in this example):
function MYMODULE_auto_placeholders(&$element) {
  if ( isset($element['#type']) && $element['#type'] == 'textfield') {
    // set placeholder
    $element['#attributes']['placeholder'] = $element['#title'];
    // hide label
    $element['#title_display'] = 'invisible';
  }
  foreach (element_children($element) as $key) {
    MYMODULE_auto_placeholders($element[$key]);
  }
}

Then in your form alter function just call
MYMODULE_auto_placeholders($form);

That method will work for pretty much every textfield on a form, with the exception of those that are added in #process functions (like the alt and title textfields of an image field for example).
Answer: Just add the placeholder in the #attributes array for the form field element, such as in the following code.
   $form['my_textfield'] = array(
      '#type' => 'textfield',
      '#attributes' => array(
        'placeholder' => t('My placeholder text'),
      ),
    );

Answer: I tried Clive's answer:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'some_form') {
    $form['some_element']['#attributes']['placeholder'] = t('Placeholder text');
  }
}

But to my surprise, I got the placeholder in wrapper of textfield, not textfield itself. Then I tried a variation as follows, it worked!
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'some_form') {
    $form['some_element']['und'][0]['value']['#attributes']['placeholder'] = t('Placeholder text');
  }
}

Comment: Thanks! I was starting to go a little crazy -- didn't even think about this.
Comment: What is the "some_element"?Is the ID of the element?How can I find this?
Comment: @sokratis you can get the IDs of elements by dpm($form), they appear in the first level of $form array. The following is an actual example of altering comment form:

    function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
        if ($form_id == 'comment_node_post_form') {
          $form['subject']['#attributes']['placeholder'] = t('Subject');
          $form['comment_body']['und'][0]['value']['#attributes']['placeholder'] = t('Content');
        }
      }
Answer: Stumbled upon this and thought Clive's answer seemed nice to automatically add placeholders.
Thou, a few minor changes are needed to get it right in drupal 8, so here's pretty much the same answer, but suitable for your drupal 8 theme.
/**
 * Implements hook_form_alter
 */
function THEME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  add_placeholders($form);
}

/**
 * Add placeholders to suitable form elements -> textfield, password, email, textarea
 */
function add_placeholders(&$element) {
  if(isset($element['#type']) && in_array($element['#type'], ['textfield', 'password', 'email', 'textarea'])) {
    $element['#attributes']['placeholder'] = $element['#title'];
  }
  foreach(\Drupal\Core\Render\Element::children($element) as $key) {
    add_placeholders($element[$key]);
  }
}

Comment: Thank you, works great! But should be mentioned, that this solution just works for forms without fieldsets, so this may need some recursive loop for nested fields.
Answer: I've found this solution here that worked for me:
/**

 * Implements template_preprocess_input().

 */

function MYTHEME_preprocess_input(&$variables) {

  // Set a placeholder for all search form elements.

  if ($variables['attributes']['type'] == 'search') {

    $variables['attributes']['placeholder'] = $variables['element']['#title'];

  }

}

Answer: Simply add the code for placeholder text
/**
 * Implements hook_form_alter
 */

function MODULENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface
 $form_state, $form_id) {
  form['field_YOURFIELDNAME']['widget'][0]['value']['#placeholder'] = t('Some text');
}

Answer: If you want to target a form instance directly use hook_form_FORM_ID_alter. Might be tidier than using conditionals. My solution for targeting the search form block instance only.
function eyecare_form_search_block_form_alter(&$form, $form_state) {
  $form['keys']['#attributes']['placeholder'] = t('Search');
}


Calendar: How to limit the range of hours in Days display?

Question: I´m using the calendar module in d7.
In the  Day display it shows 01.00 to 23.00 in the hour column. How do I set it to be: 08.00 to 18.00?
I´m sure this is setteable in somewhere but I can´t find it...
I upload a picture which shows the hours to change:
Answer: Change the Settings of the Calendar format in the View and set the time grouping to custom.  In the box, specify the intervals/start times that you want to show up starting at the hour you want to start at.  See illustration below:
Comment: Thanks. It did the job. But to set the range (08:00 hs to 20:00 hs) I have to set the interval to: **08:00:00,09:00:00,10:00:00,11:00:00,12:00:00,13:00:00,14:00:00,15:00:00,16:00:00,17:00:00,18:00:00,19:00:00,20:00:00** Is there a shorter way??
Comment: @chefnelone not that I know of, but feel free to play around and test the values that you can put in that text box.


Tkinter and PIL interfering with each other (Image.open) in Python

Question: keep in mind I am just showing a small part of the code.
Without Tkinter being imported the code below works:
import os
import PIL
from PIL import ImageTk, Image
import cv2
import numpy as np
import pytesseract
import pandas as pd

##CROPS NUMBER PLATE
diretory_save_cut_out_NP = main_folder_directory + '/' + 'Computational directory/NP & VIN/Original NP/'

for x in range(0, file_count):
    im = Image.open(original_file_directory + reg_doc_list_names[0] + '.png')
    x1 = 140
    y1 = 740
    x2 = im.width - 1200
    y2 = im.height - 2470
    region = im.crop((x1, y1, x2, y2))
    region.save(diretory_save_cut_out_NP + reg_doc_list_names[0] + '.png')
    reg_doc_list_names.pop(0)

However if I import Tkinter and try to make a GUI this error pops out:
import os
import PIL
from PIL import ImageTk, Image
import cv2
import numpy as np
import pytesseract
import pandas as pd
import tkinter as tk
from tkinter import *

    ##CROPS NUMBER PLATE
    diretory_save_cut_out_NP = main_folder_directory + '/' + 'Computational directory/NP & VIN/Original NP/'

    for x in range(0, file_count):
        im = Image.open(original_file_directory + reg_doc_list_names[0] + '.png')
        x1 = 140
        y1 = 740
        x2 = im.width - 1200
        y2 = im.height - 2470
        region = im.crop((x1, y1, x2, y2))
        region.save(diretory_save_cut_out_NP + reg_doc_list_names[0] + '.png')
        reg_doc_list_names.pop(0)

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\lol\Anaconda3\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "<ipython-input-11-a57cb1712307>", line 35, in scanner
    im = Image.open(original_file_directory + reg_doc_list_names[0] + '.png')
AttributeError: type object 'Image' has no attribute 'open'

I've tried a few things, however nothing worked, do you guys have any recommendations? Thanks in advance, Ill try and respond as quick as poossible.
Comment: You are using `tkinter.Image()`, not `PIL.Image()` due to `from tkinter import *`.
Comment: @acw1668 mate you're great, its working now, thank you
Comment: `*` imports aren't always evil but they're misused a lot. `import tkinter as tk` is much better if you really need a lot of the `tk` stuff as it doesn't pollute your namespace with potential conflicts.
Answer: Code that works, thanks to @acw1668:
##CROPS NUMBER PLATE
diretory_save_cut_out_NP = main_folder_directory + '/' + 'Computational directory/NP & VIN/Original NP/'

for x in range(0, file_count):
    im = PIL.Image.open(original_file_directory + reg_doc_list_names[0] + '.png')
    x1 = 140
    y1 = 740
    x2 = im.width - 1200
    y2 = im.height - 2470
    region = im.crop((x1, y1, x2, y2))
    region.save(diretory_save_cut_out_NP + reg_doc_list_names[0] + '.png')
    reg_doc_list_names.pop(0)

Comment: btw that is the reason to not use `*` when importing unless certain, otherwise just import what You need, like `from tkinter import Tk, Label, Button` and so on


How to get core to leverage a MySQL master/slave configuration?

Question: I read this question MySQL master/slave replication not working and its answer:

Using slave databases is barely implemented in Drupal core. If you are
  developing your own modules then calls to db_query need to specify
  that they want to use the slave database using the $options array. See
  DatabaseConnection::defaultOptions for how to set this array.

Is there a way without killing kittens hacking the core to get db_query() and db_select() to make more slave SELECT queries ?
By default, these functions will query the master unless specifically told to query the slave (see their API). You have to write db_query($query, $args, array('target' => 'slave')) in order to query the slave and the core (and all the modules) aren't written to achieve this.
Only search (see the slave part) and aggregator seems to leverage this.
Edit: Oct, 25
I saw pressflow 7 is out but I'm not sure if it helps a lot right now.
I haven't found something relevant so let's try a little bounty to help this getting an answer.
Edit: Oct, 31
I'm mainly worried about Crell's comments regarding this topic: What to do with slaves?.
Mainly, is there troubles if I send SELECT queries to the slave, what happens with delays in the replication and the fact that I may want to do a node_load() just after saving a new node.
Answer: Here's how I currently implement this.
First you need to set up a SelectQueryExtender class like this:
class SlaveTarget extends SelectQueryExtender {
  public function __construct(SelectQueryInterface $query, DatabaseConnection $connection) {
    if ($connection->getTarget() != 'slave') {
      $connection = Database::getConnection('slave', $connection->getKey());
    }
    parent::__construct($query, $connection);
    $this->addTag('SlaveTarget');
  }
}

Once you have that, then all you have to do is get all the other queries to extend the extender. :) if that makes sense. Here's the snippet.
/**
 * Implements hook_query_alter().
 */
function example_query_alter(QueryAlterableInterface $query) {
  if (is_a($query, 'SelectQuery') && !$query->hasTag('SlaveTarget')) {
    $query->extend('SlaveTarget');
  }
}

And now all your SelectQuery hit the slave ;-) This is the only way I've been able to accomplish this. Anyways it works great.
Also if you have this on a custom module you can set up the SlaveTarget to be it's on file SlaveTarget.inc and add a files[] = SlaveTarget.inc to your module info file.
Comment: Hi Eric, thanks for your answer, what mainly worries me is this thread: [What to do with slaves?](http://groups.drupal.org/node/27820) and [Crell's comment regarding slave](http://groups.drupal.org/node/27820#comment-94430). So is you solution safe in any cases ? Do you restrict some `SELECT` queries ? How do you deal with delays in the replication and the fact that loading a node just after saved it may causes troubles ?
Comment: This is changing the database to slave only on Select queries. This only happens when the query has been written with SelectQuery not db_query so no need to worry about and insert or update being targeted to the slave. We're running this on 3 huge production environments without any problems. I've haven't worried much about the mysql replication as its almost instant (in my case) but I can see how that might be a small issue issue in certain environments.
Comment: Thanks for your answers, it's a great solution, I'll see if this is viable on our environment.
Comment: Eric, is this code out there somewhere as a contrib or sandbox module?
Comment: @paul-m: see https://drupal.org/project/autoslave.
Comment: I have tested this solution, and it either no longer works with Drupal 7, or never worked. I've posted an alternative solution [here](http://drupal.stackexchange.com/a/83838/147).
Comment: Yes, it appears even though the connection can be set to "slave", if the query itself doesn't have the `target => 'slave'` option set, it will still run on the default connection. It's a pain it's not easier to set the connection target more easily at the `query_alter` level like `$query->setOption` or `$query->target = 'slave';`
Answer: The AutoSlave module redirects SELECT queries to read-only replicant databases, and it takes into account replication lag.
According to the module docs, it only uses the read-only replicant when all of the following conditions are true:

The query is a select query
The tables in the select query have not been written to during the request and within the assumed replication lag
A transaction has not been started
The tables in the select query are not specified in the 'tables' option in the driver settings
A lock has not been started (core db-lock and memcache-lock supported)
Answer: from what I heard at the recent Drupal BADcamp Pressflow is the way to go if you want master/slave configurations. You'll be limited to Mysql as the DB.
Also, checkout the "high performance group" on d.o.
Comment: Currently Pressflow 7 = D7, there's nothing (yet) that Pressflow do that D7 don't :(
Answer: Despite all of the amazing work done on the database abstraction layer in Drupal 7, this is still surprisingly difficult to do with Drupal core out of the box. As others have mentioned, AutoSlave is an option, although not one I've attempted due to my stubborn refusal to believe that it should be that difficult to do this.
A simpler solution I have found is the following. To route all SELECTs to the slave server, you create a file titled select.inc inside of the core includes/database/mysql directory with the following contents:
<?php

/**
 * @file
 * Select builder for MySQL database engine, routing all SELECTs to the slave.
 */

/**
 * @addtogroup database
 * @{
 */

class SelectQuery_mysql extends SelectQuery {
  public function __construct($table, $alias = NULL, DatabaseConnection $connection, $options = array()) {
    $key = $connection->getKey();
    $connection = Database::getConnection('slave', $key);
    $options['target'] = 'slave';
    parent::__construct($table, $alias, $connection, $options);
  }
}

/**
 * @} End of "addtogroup database".
 */

There are some risks with this method:

This method will hijack all SELECTs and direct them to the slave, which will undoubtedly cause issues if you have any lag in replication. Read that sentence again.
When you upgrade Drupal core, it is possible that this file will get deleted.
If Drupal core were ever to start shipping with its own includes/database/mysql/select.inc, your file would get overwritten during upgrade, and you would have to start maintaining your own patched version of the select.inc that ships with Drupal core.

If you don't have any slave servers specified in settings.php, the above code will not cause a problem. It will still gracefully degrade to using the master server.
Comment: Yes, it appears even though the connection can be set to "slave", if the query itself doesn't have the `target => 'slave'` option set, it will still run on the default connection. It's a pain it's not easier to set the connection target more easily at the `query_alter` level.


Confidence interval of the parameter of $\exp$ and normal distribution from MLE?

Question: I have a sample $X_1,X_2,\ldots,X_n$

If the sample is from exponential distribution, I want to use MLE to estimate the parameter $\beta$. I know the result that $$\hat{\beta}=\frac{X_1+X_2+\ldots+X_n}{n}$$But how can I calculate the $95\%$ confidence interval of $\beta$?
If the sample is from normal distribution, I want to use MLE to estimate the parameter $\mu$ and $\sigma$. I also know the result that $$\hat{\mu}=\frac{X_1+X_2+\ldots+X_n}{n}, \quad \hat{\sigma}=\left[\frac{n-1}{n}\cdot S^2(n)\right]^{1/2}$$
But how can I calculate the $95\%$ confidence interval of $\mu$ and $\sigma$?

Step1 to calculate confidence interval,  $$\hat{θ}\pm z_{1-\frac\alpha2}\sqrt{\frac{\delta(\hat{θ})}{n}}$$
Step2 to calculate confidence interval $$\delta(\hat{θ})=-n\left(E\left[\frac{d^2}{dθ^2}\ln \mathcal L(θ)\right]\right)^{-1}$$

I know the equation, but I am still confuzed how to calculate $$\left(E\left[\frac{d^2}{dθ^2}\ln \mathcal L(θ)\right]\right)$$
I want to know the equation in the red frame of this picture.
Comment: I get the sigma hat from my text book and i also calculate to get this. i think that my MLE is right. But i don't know exactly how to calculate confidence interval.
Answer: The term you cannot calculate is (essentially) the Fischer information:
$$I(θ)=-E\left[\frac{d^2}{dθ^2}\ln \mathcal L(θ)\right]$$
Then $δ(θ)=n(I(θ))^{-1}$. So, to calculate $I(θ)$ for the exponential:
$$\mathcal L(θ)=\prod\limits_{j=1}^nθ e^{-θx_j}=θ^n e^{-θ\sum_{j=1}^{n}x_j}$$
and therefore $$\ln \mathcal L(θ) = \ln{\left(θ^n e^{-θ\sum_{j=1}^{n}x_j}\right)} = n\ln{(θ)}-θ\sum_{j=1}^{n}x_j$$
which you can differentiate twice with respect to $θ$:
\begin{align}\frac{d}{dθ} \ln (\mathcal L(θ)) &= \frac{n}{θ}-\sum_{j=1}^n x_j \\ \frac{d^2}{dθ^2} \ln (\mathcal L(θ)) &= -\frac{n}{θ^2}\end{align}
So,
$$I(θ)=-E\left[\frac{d^2}{dθ^2}\ln \mathcal L(θ)\right]=\frac{n}{θ^2}$$
and therefore $δ(θ)=n(n/θ^2)^{-1}=θ^2$. To make calculations simpler use that

If $X_j$ are i.i.d. for $j=1,2,\ldots,n$ you can take the $I(θ)$ for a single observation $X_j$ and obtain the Fisher information for $X$ with $nI(θ)$.

For the normal distribution $N(\mu,θ^2)$ you should find: $I(θ)=n/(2θ^2)$ (single parameter) and if you estimate both parameters, i.e. $Ν(μ,σ^2)$ with $θ=[μ,σ^2]^Τ$ then $I(θ)$ is a matrix: $$I(θ)=\begin{bmatrix}\frac{1}{2σ^2}&0 \\ 0& \frac{1}{2σ^4}\end{bmatrix}$$
Comment: I use the parameter beta of exp distribution to do the fisher information. And i differcentiate twice with respect to beta, and i get the equation that still contain X1+X2+,...,+Xn. How should i do with X1+X2+,...,+Xn?
Comment: You should do the differentiation again, because the $X_i$'s go away if you do it correctly. It is in my answer above. But even if they did not go away, that would not be a problem. This $X_i$'s are your sample and therefore known.
Comment: I add my additional problem in my original question. That is from my text book. Can you help me explain that red frame in my picture?
Comment: Yes, $E[X_i]=\frac{1-p}{p}$ when $X$ geometric, so by linearity $E[\sum X_i]=n(1-p)/p$. The author is missing an $E$ symbol before the sum. But please: do not edit so much an already posted question. A, and stop posting the same question again.
Comment: I'm sorry. I shouldn't change my problem so much and shouldn't post that problem again. But i still wonder that if we meet ∑Xi in the calculation proccess of fisher information, we have to replace E(∑Xi) with the mean of that predetermined distribution?
Comment: Ok, apology accepted. $E[X_i]=μ$, it is not that you "replace" it. It is so, you actually yes, that is what you do.
Comment: OK, thank you very much~


Question on closed sets

Question: If $A,B\subset\mathbb{R}^n$ are closed. Let
$$M=\{p\in\mathbb{R}^n\,:\,\exists\,t\in[0,1],a\in A,b\in B\;\mathrm{s.t.}\;p=t\cdot a+(1-t)\cdot b\}$$
Is $M$ closed? Why?
Comment: possible duplicate of [Is the convex hull of closed set in $R^{n}$ is closed?](http://math.stackexchange.com/questions/340324/is-the-convex-hull-of-closed-set-in-rn-is-closed)
Comment: @Julian Kuelshammer: But $M$ here is not exactly the convex hall of anything. Moreover, $M$ doesn't have to be convex here
Comment: @DennisGulko True, but the ideas to construct counterexamples are very similar.
Answer: Here is a counterexample. Take $A=\{(1,0)\}$ and $B=\{(0,m)\;|\;m\in Z\}$. Note both sets are closed since all points are isolated. On the other hand, $M$ contains all line segments connecting each point in each set. The slope of these lines approach a vertical line, so we can get arbitrarily close to any point on the line $x=1$, but this line is not in $M$.
Comment: Probably not. In the counterexample I gave it is very important that $B$ is unbounded. If it is bounded, then it is likely I don't have enough wiggle room. I would use sequential compactness, or the Heine Borel theorem, to try and show that the set is closed for compact sets.
Comment: Ok, thanks. Suppose $A,B$ are compact. Can you give a counterexample for that case too?
Answer: Suppose $A,B$ are compact.  Note that $M$ is the image of the compact set $A \times B \times [0,1]$ under the continuous map $f(a,b,t) = ta+(1-t)b$.

Question on closed sets


How to recognize modulations by ear?

Question: I'm surprised this this question hasn't been asked before (or at least I couldn't find it). If you're listening to a piece, and it suddenly modulates, how can you tell? and how can you determine the interval between the two tonics?
Although I have a good enough ear for recognizing scale degrees, I often can't tell if a modulation has happened, let alone guess the new key. The only scenario where I succeed is when the same melody note is sustained throughout the key change. For example, the fifth is sustained, but later is starts to sound like the tonic, this way I can tell that the new tonic is the fifth of the previous key.
What is the recommended approach? Is there a method that doesn't rely too much on theory? For example, if you can identify secondary dominants or some common patterns used for modulation you may be able to figure it out, but you wouldn't be relying completely on your ears. Can it be done without 'doing the math'?
Answer: Adding to what tim's said, a key modulation can be made more or less subtle by what happens before the actual key change is made.  Changing less notes at a time will make it less noticable, using Chords from the new key before the switch makes them less noticable later on when the switch happens.
Songs that are already very dissonant can be hard to pick up on in terms of key changes.  You also have the concept of a transient key change, in which the key will change, but then change back, sort of like holding on to an interesting chord before going back to the tonic.  Doing this once followed by another permanent key change can throw the ear off.
There's a piece I'm learning by Bach at the moment which seems to change key multiple times very subtly, but only for short periods called Invention Number 8, though perhaps someone else can clarify this for me.
Key point which I believe Tim has already said is that a key change usually doesn't just happen, there is a transition cadence that will usually happen right before it which will give you clues as to what's about to happen.  I suggest learning how to modulate, and trying out a few chord progressions.  They commonly have a very distinctive sound/pattern to them.
Answer: I'm trying to teach exactly this for grade 8 aural tests for some of my piano students, and a useful resource (although pricey, and comes with other stuff you maybe don't want) is the ABRSM book and CD "Aural Training in Practice grade 6-8". Having the CD means you can practice hearing examples and test yourself. It is all classical, but the chords are the same whatever style you use.
Answer: When a tune modulates, it will often go into - * a fourth up. *a fifth up. *its relative minor/major. A key change could be considered as a big modulation.
With the first examples, there is only a change of one note from old into new.E.g.,from key Amaj to Dmaj., one sharp is lost.The overall sonority of the tune may remain very similar.
With a key change, there will be more than one note change .This becomes obvious to the ear. For a big change, the dominant of the new key is usually played to get the listener ready.This is sometimes preceded by that chord's dominant - the secondary dominant.To sound smooth with this transition, usually there's a common note between the original key chord and the dominant/sec. dom. of the new key. Bear in mind that sec. doms can be major or minor.  Listening for this will give clues.
Playing an instrument along with such pieces will quickly give you more insight.
Answer: Well, the answers above are true, but I don't think they give the OP anything to work with. What you need to do is listen to a bunch of songs with someone who has a good ear, and every time there is a key modulation, that person alerts you and then explains a little of how they know there's a key modulation. The theoretical explanations aren't going to help you recognize it in practice. You have to train your ear.
Comment: This makes sense, but what if I have no one to help me like you described? How can I train my ears alone? Look at sheet music to identify modulations, then listen to them?
Comment: Listen to a bunch of songs that are in one key only. And then listen to the same songs that are reharmonized, and/or a different set of songs that modulate keys. If you are a musician, then play a bunch of tunes only in one key. And then do different tunes that modulate.
Answer: For me, a key change that happens subtly is a key change that happens quickly. I feel that my ears love 1-5 relationships and any time a melody plays that interval, I will modulate. So in the key of C , if an F and C are played one after the other, I will switch to hearing that as a 1-5 scale degree as well i.e I will modulate. Even if I play a C, an F and another C at a higher octave, I will hear that as an F double stop chord. The other fast subtle modulation (as mentioned in previous posts) is between the relative major and minor, and just the sound of that modulation is something that one can easily recognize over time. Other modulations for me happen more boldly, and as long as I follow on what note the modulation occurred on, I know where I am. I still have to master the 2 note ear training series by Bruce Arnold, and that should help.
Answer: It is much different than scale degrees and diatonic chords (and even secondaries) because your ear cant remain in the same tonal system. My suggestion would be to make a chart with all modulation possibilities and then search for pieces with those modulations (hopefully multiple examples for each separate case). Then through listening you might gradually begin to hear what it sounds/feels like to modulate to the dominant or subdominant, etc. Something like this:
Modulation type ---  Piece --- technique used///
I to V          --- many binary forms --- pivot chord, etc///
I to III        --- Waldstein --- chromaticism to new V///
I to IV         ---  Hey Jude --- V of new key///
I to bVI        --- insert Beethoven --- borrowed chord/unprepared shift///
I to vi         --- etc///
i to x///
etc
You might also look to jazz harmony to help with this as well, either for examples or additional listening practice.
Comment: Thanks Bill, this makes a lot of sense, but also takes a lot of dedication. It also suggests that there are no shortcuts and one must learn what each modulation sounds like the way they learned what each interval or degree or chord sounds like.

A realistic goal for me would be to learn the more common ones that way.

How to recognize modulations by ear?


Inconsistent notation of BWV 565 mm. 39–40 makes it unclear whether to play C or C#

Question: In the passage shown below (from Bach's Toccata and Fugue in D minor, BWV 565, mm. 39–40), the C#s and C-natural in the right hand are all explicitly notated, but in the left hand, no indication is given either way for the C. Should it be a C#, following the usual rule of accidentals lasting through the measure, or should it be a C-natural, following the right hand in which all accidentals are explicit (or, if not indicated, then according to the key signature)?
Comment: @Aaron I'm sure there's also a dupe (or several) of the reformulated question.
Comment: @Dom Respectfully, I disagree. Restating the rule of how long accidentals are scoped, or the existence of courtesy accidentals, does not answer this specific question. The confusion is related to the specific manner in which these two bars are notated, not any ambiguity in understanding of the rules themselves. Were I the OP, none of the existing questions (so far as I'm aware of them) would sufficiently address my confusion. We commonly answer specific instances of general questions as separate from the general question. I think that allowance applies here.
Comment: Hi EmilyJ. I've substantially rewritten your post, because I believe it was being misunderstood. However, if my rewrite has misrepresented your question in any way, please roll it back, or let me know, and I'll take care of it.
Comment: @PiedPiper FYI, I've rewritten the question to better reflect what I think OP is trying to ask. Pending feedback from the OP, the question is specific to the manner in which the passage is notated, and not addressed by the general rule of accidental scope.
Comment: @Aaron I have voted to reopen this question.  The inconsistency in the application of the rule deserves special treatment.  It would also be nice if someone could look at the source material and add an answer saying whether this inconsistency exists there or was added by the editor.  That's unlikely to happen if the question is closed.
Comment: See also https://music.stackexchange.com/questions/42935/useless-natural-accidental
Comment: @Aaron to help combat questions in a similar vein, I think marking it a duplicate makes sense. There's nothing really special  about this question that would make is unique from the others.
Comment: Related: https://music.stackexchange.com/questions/76793/accidental-written-twice/
Answer: It is a C#. The reason the second C# in the RH part is explicitly given is for clarity in light of the B-natural immediately preceding it.
Comment: As you note, this question regards a special case, so IMO it's worth calling out even more explicitly the inconsistency that has confused the OP. I.e. it's not a "convention in the right hand that all accidentals are explicit"; it's just a courtesy accidental. Besides the B natural, we might assume that they *didn't* use one in the bass because it's only been two notes since the first accidental.


Best way for ASP.NET App to deliver images: use httphandler or static resource

Question: On our web server we want to provide urls that can be used in HTML elements, for displaying user profile pictures.
I could do this in two ways:

put the images on the web server as static resources: mysite.com/user1.jpg
implement an IHttpHandler: mysite.com/images?userid=1

are there any benefits of one method over the other?
Answer: Not handling images via ASP.NET but letting IIS deal with them as static content and circumventing the ASP.NET pipeline altogether would be fastest.
Implementing an HttpHandler, apart from requiring code, would require the ASP.NET pipeline to be involved - this takes more resources from the server.
Basically, if the content is static, let it be static and let IIS handle it.
Answer: Whilst allowing IIS to handle the images would be easier, it depends on whether or not you want to compress the files as they are sent?
Certain versions of IIS support GZIP compression, thus meaning you can compress the files as IIS serves them, however, older versions of IIS may not, meaning if you need to compress the files, you would have to use an HTTPHandler or similar to compress and serve them.
Comment: we are using IIS 7.5, but a good point. Is IIS clever enough to only compress when the calling browser can handle it?
Comment: In that case, I think you should serve them naturally and implement GZIP compression. This will speed things up and reduce bandwidth ;)
Answer: Let IIS deal with them. Serving images from a handler can take up a lot of resources.
Don't do that unless absolutely necessary.
If your site has a lot of images, this means that many extra requests for Asp.net to handle.
Asp.net needs quite a lot more resources per request than what IIS would need to push out a static file.
Comment: good answer - Oded was a little quicker so he gets marked as 'correct'


Methods of fitting a dynamic linear model

Question: I'm taking a time series course and am learning about exchangeable time series form of dynamic linear models (DLMs). This is given by:
\begin{align*}
\mathbf{y}_t' &= \mathbf{F}_t'\boldsymbol{\Theta}_t + \boldsymbol{\nu}_t', \qquad \boldsymbol{\nu}_t \sim \mathcal{N}(0, v_t\mathbf{V})\\
\boldsymbol{\Theta}_t &= \mathbf{G}_t\boldsymbol{\Theta}_{t-1} + \boldsymbol{\Omega}_t, \qquad \boldsymbol{\Omega}_t \sim \mathcal{N}(0, \mathbf{W}_t, \mathbf{V})
\end{align*}
$\boldsymbol{\Omega}_t$ comes from a matrix-variate normal distribution.
All parameters except $\mathbf{U}$ and $\mathbf{V}$ can be fit using forward filtering backward sampling (FFBS). In order to fit $\mathbf{U}$ and $\mathbf{V}$, we must do a Gibbs sampling step.
My question is: what is the difference between FFBS and the Kalman filter? What other ways are there to fit DLMs? For example, I have heard of the particle filter - is this something that can be used in this context? And finally, is it always possible to do Gibbs sampling (perhaps with Metropolis-Hastings if prior distributions are not conjugate) to fit a DLM?
Answer: The Kalman filter is the "forward filtering" part of FFBS, while the "backward sampling" part provides a draw from the joint distribution for the $\Theta_t$ for all $t$.
All the other ways of performing statistical parameter estimation, e.g. maximum likelihood, can be used for DLMs. Yes a particle filter could be used here, but since the model is linear and Gaussian, i.e. a DLM, you won't be gaining anything. Particle filters are better when you have non-linear or non-Gaussian models and thus cannot perform FFBS.
Yes, it is possible to perform Metropolis-within-Gibbs for any Bayesian model.


CSS/JQUERY make div scrollable without showing scrollbar

Question: is there any way to make a div scrollable with overflow-y:hidden; and overflow-x:hidden?
i'm trying without success, maybe i need some js or jquery script?
i mean, i would like to make div scroll on y axes without showing scrollbar on right side( as it is now).
itryed:
.get-list{
  position:absolute;
  z-index:444;
  text-align: center;
  display: none;
  bottom:0;
  clear:both !important;
  left:0;
  right:0;
  top:11%;

  margin:0 auto;
  background:#fff;
  max-height:800px;
  overflow-y:no-display;
  overflow-x:hidden;
  display: block;
 }

thanks
EDIT
.log-widget-list{
  position:absolute;
  z-index:444;
  text-align: center;
  display: none;
  width:99%;
  margin:0 auto;
  background:#fff;
  height:800px;
  overflow: hidden;
 }

.log-widget-list .scroller{
  overflow: scroll;
  height:800px;
  width:100%;
}

it shows right scrollbar anyway
Comment: If there is no scrollbar, how is it supposed to scroll? Automatically?
Comment: @SimpleCoder: I think OP has tried `overflow-y: hidden` and `overflow-x: hidden`, but that did not work.
Comment: Yes you can by using jQuery.scrollLeft and jQuery.scrollTop.
Comment: some trick to hide scroll bar i mean
Comment: @Ispuk You can use scrollTo(xpos,ypos);
Comment: @Blender: Not quite - that's why I asked. (see edit)
Comment: i'm on boostrap don't want to use more plugins :(
Comment: examples? i mean $('get-list').scrollTo(); i tink is not ok :P
Comment: need to bind mouse wheel event? :P
Answer: Let's create a div with a width of 200px: (note the overflow:hidden)
#sidebar{
width: 200px;
height: 300px;
border: 1px solid #000;
overflow: hidden;
}

Inside that div we will create the 'scrollable' div. See:
#sidebar #scroller{
    width: 215px;
    height: 300px;
    padding-bottom: 15px;
    overflow: scroll;
}

Altough we give it overflow:scroll, the scrollbar isn't visible. This is because this div has a total width of 215px which will make the scrollbar disappear outside the div.
Also see: http://jsfiddle.net/TBsN8/
Comment: You should copy the code over to this answer and explain how/why it works.
Comment: @Sebass van Boxel: Try your demo in Chrome/Safari: highlight/select a line and drag your mouse to the right and you'll see the scrollbar. Or use a textarea instead of the inner div and then fill it with some text. Then use the keyboard keys `Page Up` and `Page Down`.
Comment: true. will certainly get my `+1` after that :)
Comment: @Sebass van Boxel i edited code , i think % width still not working
Comment: man it's clear but it doesn't works for me :( does it's a problem position:absolute or %width? :P check my question is updated
Comment: Delete position:absolute and display: none and add padding-right:15px; to .log-widget-list .scroller{
see: http://jsfiddle.net/TBsN8/1/
Comment: fixed ;) thx never seen this css trick really good trick man!
Answer: fixed as shown thanks to Sebass van Boxel
.log-widget-list{
  position:absolute;
  display: none;
  width:98% !important;
  top:11%;
  max-height:500px;
  overflow: hidden;
  bottom:0 !important;
  left:0;
  right:0;
  margin:0 auto !important;
 }

.log-widget-list .scroller{
  overflow: scroll;
  max-height:500px;
  padding-bottom:3%;
  width:104% !important;
}


Multiple buttons used to JQuery slideToggle one div

Question: I have a series of buttons and a form on a webpage.
The form is hidden on page load and i'm using slideToggle to show the form when a button is pressed.
The html is like this:

    <button id="btn_01" class="tog active">Open</button>
    <button id="btn_02" class="tog">Open</button>
    <button id="btn_03" class="tog">Open</button>

  <button id="close">Close</button>
  <form>Form contents...</form>

and so far the JS i have (to fire from one button) is:
$("#form").hide();

$("button.tog").bind("click", function(){

    if($("button.active").length) $("button.active").removeClass("active");
    if($("#form").is(":visible") == true) { $("#form).slideUp();

    $(this).addClass('active');
    $("#form").slideToggle();
});

$("buttton#close").click( function {
    $('#form').slideUp();
});

when any button is clicked, if #form is open it should slideUp, and the active class should be removed from the old button and added on the one that's just been clicked.
there should also be the ability to click button#close from within #form to fire the slideToggle (and also remove the active class from the #links button.
i'm fairly new to JQuery and am having trouble with the order of the code.
when #form is open and the original button is clicked the slideToggle function closes then re-opens the div.
i've tried lots of variations of this but can't get it to work properly.
any help would be much appreciated.
cheers, Leon
JSFiddle mockup: http://jsfiddle.net/leonharris/9mKTc
Answer: Try
$(document).ready(function () {

    var $frm = $('#form').hide();

    var $bts = $("button.tog").on('click', function () {
        var $this = $(this)
        $bts.filter(".active").not(this).removeClass('active');
        $this.toggleClass('active');

        if ($this.hasClass('active') && $frm.is(':visible')) {
            $frm.stop(true, true).slideUp(function () {
                $(this).slideDown()
            });
        } else {
            $frm.stop(true, true).slideToggle();
        }
    });
    $bts.filter('.active').click();

    $("#close").click(function () {
        $bts.filter(".active").removeClass('active');
        $frm.slideUp();
    });
});

Demo: Fiddle
Comment: thanks Arun, it's heading in the right direction.

a few questions though:

there's a slight problem. if a button is active then i click on another button, #form closes but the new button get's the class active.

when another button is clicked #form should close then re-open (to simulate a new form) and the .active class should shift to the current button.
Comment: and can it be hidden on page load?
Comment: @user2843317 it can be... but I displayed it because there is a button with active class
Comment: so i just remove the active class to start with?
Comment: wow. thats amazing - thanks so much for the help. does exactly what i wanted.
Comment: sorry, one more thing: can the 'Open' button text be changed to 'Close' when button has .active class?


One class of Ordinal DV values has too few observations - best way to address

Question: I am doing an ordinal classification using glmnet, with 3 level class DV: 1 (bad), 2(ok), 3(good). I am trying to fit a model to this ordinal DV, and find best features. The problem is that one of the classes, ie (1- bad), only has 50 out of 5000 observations, the other two classes have around around equal number of observations. This is leading to a number of problems, I believe, and I am trying to find the best solution to address it.
Here is what I've tried:

model <- polr(Y ~., train, Hess=TRUE)

output:
Warning message:
In polr(Y ~ ., train, Hess = TRUE): design appears to be rank-deficient, so dropping some coefs

Also
    qda.fit=qda(Y~.,data=train)
Error in qda.default(x, grouping, ...): rank deficiency in group 1

So I read the following which explains there could be a number of reasons for insufficient data here: What is rank deficiency, and how to deal with it?. The main quote here below is intro. The answer suggests some causes without going into best way- at least not that I can glean - to address my specific case.

"Rank deficiency in this context says there is insufficient
  information contained in your data to estimate the model you desire.
  It stems from many origins. I'll talk here about modeling in a fairly
  general context, rather than explicitly logistic regression, but
  everything still applies to the specific context."

My thinking about options:

Remove level 1 class and do a binomial logistic regression
Merge the level 1 with another class somehow - not sure best way to do that
Something else?

Option 1 is easiest but is that the best option. My concern is this: While there is very little data, there is a pattern, and it also makes sense that very few reviews would be the lowest, relative to others. I'm loath to throw the data out.
Would appreciate some insight from those more experienced.
Comment: When I create data with 50 in outcome category 1 versus ~2475 in other two outcome categories, I am still able to obtain results for the models you demo. For ordinal regression, this type of problem may be a separation problem. And the most common method for dealing with such problems is a penalization method. Usually, the regression should run, but you should obtain strange large standard errors. Check out the ordinalNet package, it is supposed to perform penalized ordinal regression.
Answer: Assuming your logic in using polr initially was sound, it follows from this logic that you should merge Bad and OK together and estimate the binary model. You will only lose a tiny bit of information as a result (the logic of deleting Bad is that you would expect the covariates relationship for OK/Bad to be different to Good/OK, and, if that is the case, polr is the wrong model anyway).
However, your logic may not be sound, and if so you may learn something by exploring the data to work out what is causing the error. Were it me, I would start by building CART models for OK/Bad and Good/OK. My guess is that you may find that the OK/Bad model is surprisingly good, and, by taking the time to interpret it you will learn a lot (NB: CART doesn't suffer from separability issues).
Comment: Thanks @Tim, I'm using polr to get the t-test (and manual subsequent p-test calculation), to see which variables are significant and worth considering in an ordinal multinom classification ie using multinom method in caret with ordered=True. I'll check out CART class. tree to see what happens there and will examine the ok/bad combo.


Was Array.prototype.sort.call() ever supposed to return the window object?

Question: I have been toying around with obfuscating Javascript with just brackets and other symbols, as per this question and this automatic  generator - for purely educational reasons, may I say :)
For example, evaluating (![]+[])[+!+[]] gives me the letter "a".
However, it seems that the examples rely on [].sort.call() returning the window object. My problem is that whenever this doesn't seem to work on any of the browsers I have installed (Chrome 14, FF 9, IE 9):
//They told me this would return the window object
[].sort.call()

//But I get an exception instead:
"TypeError: Array.prototype.sort called on null or undefined"

So I ask:

Was [].sort.call() fixed on recent browsers or does it still return the window object and its just me doing something wrong?
If it is the case that I can't use this approach anymore, are there any other ways I can access the window object using only brackets, parenthesis, exclamation marks and the + operators?
Comment: What code gives you `"TypeError: Array.prototype.sort called on null or undefined"` ?
Comment: @Sarfraz: `[].sort.call()` gives the error. I wanted it to return the window object instead.
Answer: This was changed with ECMAScript 5. From 188.8.131.52:

NOTE The thisArg value is passed without modification as the this value. This is a change from Edition 3, where a undefined or null thisArg is replaced with the global object and ToObject is applied to all other values and that result is passed as the this value.

...and sort() calls ToObject on that this value, throwing the TypeError exception.
And, given the addition of strict mode, which further reduces access to the global object, your options are probably few. Though, without "use strict", you might try using this.
Comment: Using `this` looks less cool then just a bunch of brackets though :(. But it looks like there is no alternative, since we can't think of ways to get the window from either properties or method calls of regular objects, arrays or numbers...
Comment: Actually, I think i found an alternative. `[]['filter']['constructor']` is not hard to get to and gives us eval-like powers. From there its not hard to get whateverI want (although it might get a bit long)
Comment: @hugomg - Alternatively `""["sub"]["constructor"]` or `[]["pop"]["constructor"]`


Base Rate fallacy in Conditional Probability P(A|B) vs P(B|A)

Question: From Wikipedia:

P(A|B) (the conditional probability of A given B) is not equal to
  P(B|A). For example, if a person has dengue they might have a 90%
  chance of testing positive for dengue. In this case what is being
  measured is that if event B ("having dengue") has occurred, the
  probability of A (test is positive) given that B (having dengue)
  occurred is 90%: that is, P(A|B) = 90%. Alternatively, if a person
  tests positive for dengue they may have only a 15% chance of actually
  having dengue because most people do not have dengue and the false
  positive rate for the test may be high. In this case what is being
  measured is the probability of the event B (having dengue) given that
  the event A (test is positive) has occurred: P(B|A) = 15%. Falsely
  equating the two probabilities causes various errors of reasoning such
  as the base rate fallacy. Conditional probabilities can be correctly
  reversed using Bayes' theorem.  Falsely equating the two probabilities
  causes various errors of reasoning such as the base rate fallacy.

$P(A|B)$ -- I understand what it means and it is correct. With common-sense it is easy to understand that if it is already known that you have dengue then testing positive for dengue will be 90% probable ( 10% false-negatives)
$P(B|A)$ --  While reverse is different, generally in real life, if someone is tested positive for dengue, we know he has dengue, for 100% sure and we put him in hospital immediately (we just do it, we don't take any chances). But we ignored the fact that, statistically, we are looking at within our own smaller number of experiences of family, friends and relatives (30 cases e.g.). If we take whole country's population (1.25 billion) into account then we will know that 85% is the false-positive rate  for dengue and only 15% people tested positive really have it.
My question is how to learn to not to ignore such facts ? (like I remembered only friends and relatives and TV adverts for dengue) but when author brought facts:  false positives and whole population, I understood why it is 15%, I would have laughed if someone would have said so without such statistical data. I think if one learns to think this way of not ignoring but looking for facts then one can learn Probability easily. How can I learn such way ?
Comment: You might also be interested in the prosecutor's fallacy https://en.wikipedia.org/wiki/Prosecutor%27s_fallacy
Comment: From Wikipedia link:  *A lottery winner is accused of cheating, based on the improbability of winning*  I could not understand, just like my question above. Yeah,  if 100,000 bought lottery ticket, it is pretty sure that only one will win. The winner could  be any one out of 100,000.  They pick up balls from a bowl full of balls with numbers on them,  randomly they shake and pick a ball up, publicly. What cheating can  be done there ? https://www.youtube.com/watch?v=Vc_PRhQpeJI
Answer: You can use the Bayes' theorem:
Let's denote the test event by $T$(the outcome space is $\{0, 1\}$) and the event of getting struck by the disease by $D$(its outcome space: $\{0,1\}$). If we know the prior probability of someone having the disease is $\frac{1}{10,000}$(only one of the 10,000 people in the population get stricken by the disease), that's $P(D=1)=\frac{1}{10,000}$. And the the machine can test accurately 99 percent of those who have the disease, that is $P(T=1|D=1)=0.99$. We want to know how likely those who are tested as having the disease truely have the disease: $P(D=1|T=1)$.
We can form an equation according to the Bayes' theorem:
\begin{align}
p(D=1 \mid T=1) &= \frac{p(T=1 \mid D=1)p(D=1)}{p(T=1)} \\
& = \frac{p(T=1 \mid D=1)p(D=1)}{p(T=1 \mid D=1)p(D=1) + p(T=1 \mid D=0)p(D=0)} \\
& = \frac{0.99 \times \frac{1}{10, 000}}{0.99 \times \frac{1}{10, 000} + 0.01 \times \frac{9, 999}{10, 000}} \\
& = 0.0098 \ll 0.99 = P(T=1|D=1)
\end{align}
The intuition behind this is that the smaller the prior(the larger the population but the lower the disease incidence rate) the less likely the machine is right, because it can increase the false positive rate: $P(T=1, D=0)$ or $P(T=1|D=0)P(D=0)$ in the denominator.
Hope this would be of help.
Reference: An Intuitive (and Short) Explanation of Bayes' Theorem


flowtype- string is incompatible with null

Question: Flow is telling me that an explicitly passed-in string is incompatible with null, and it seems to have something to do with an exploded object also being passed in.
I have the following in my react bootstrap library interface definition file:
declare export type FormControlProps = {|
  componentClass?: ?componentClass,
  // componentClass is an enum of strings 'select' | 'div' etc
  // There are other params here, too.
|}

And the following in a component:
import { FormControl, type FormControlProps } from 'react-bootstrap';

type EnumSelectProps = {|
  defaultText: string,
  ...FormControlProps,
|};

// and in the render method:
  const { defaultText, ...other: FormControlProps } = this.props;

  <FormControl
    {...other}
    componentClass="select"
    value={this.state.value}
    onChange={event => this.onChange(event.target.value)}
  >
    { children }
  </FormControl>

This seems to be fine, right? ...other has the type FormControlProps. However, I get the complaint:
           v-----------
 43:       <FormControl
 44:         {...other}
 45:         componentClass="select"
...:
 48:       >
           ^ props of React element `FormControl`
 45:         componentClass="select"
                            ^^^^^^^^ string. This type is incompatible with
463:     componentClass?: ?componentClass,
                          ^^^^^^^^^^^^^^^ null. See lib: flow-typed/npm/react-bootstrap_v0.x.x.js:463

What gives? If I cast other as any (i.e....(other: any)), it works. Also, if I make componentClass only left-hand-side optional componentClass?: componentClass, it works. (That's not the correct definition, though.) Is there any less-hacky way to handle this? Thank you!
Answer: This should work in flow v0.56.0 as you can see on flow.org/try


How to validate a locale in java?

Question: I read a file in an application that specifies a language code:
public void setResources(String locale) {

    // validate locale
    // ULocale lo = new ULocale(locale);
    // System.out.println(lo.getDisplayCountry());

}

that must be in the format: <ISO 639 language code>_<ISO 3166 region code> eg. en_UK, en_US etc. Is it possible to validate that the locale string is valid before continuing?
Answer: I do not know ULocale, but if you mean java.util.Locale, the following code may do:
public void setResources(String locale) {
  // validate locale
  Locale lo = parseLocale(locale);
  if (isValid(lo)) {
    System.out.println(lo.getDisplayCountry());
  } else {
    System.out.println("invalid: " + locale);
  }
}

private Locale parseLocale(String locale) {
  String[] parts = locale.split("_");
  switch (parts.length) {
    case 3: return new Locale(parts[0], parts[1], parts[2]);
    case 2: return new Locale(parts[0], parts[1]);
    case 1: return new Locale(parts[0]);
    default: throw new IllegalArgumentException("Invalid locale: " + locale);
  }
}

private boolean isValid(Locale locale) {
  try {
    return locale.getISO3Language() != null && locale.getISO3Country() != null;
  } catch (MissingResourceException e) {
    return false;
  }
}

EDIT: added validation
Comment: Tried isValid and it fails for a locale that was created with Locale.forLanguageTag("abc")
Comment: I think ULocale is referring to [this](http://icu-project.org/apiref/icu4j/com/ibm/icu/util/ULocale.Type.html).
Comment: @BernieLenz right, but the question was about underscore
Comment: Just as an FYI. The ISO default delimiter is "-" instead of "_". See https://stackoverflow.com/questions/4904803/en-us-or-en-us-which-one-should-you-use
Answer: isAvailableLocale(Locale locale)

Is answer to your question.
Example:
String key= "ms-MY";
Locale locale = new Locale.Builder().setLanguageTag(key).build();
 if (LocaleUtils.isAvailableLocale(locale))
 {
  System.out.println("Locale present");
 }

Avoid using getAvailableLocales() it will return you 155 locales Its time consuming.
If possible please explore more at LocaleUtils class and Locale
Comment: but it is org.apache.commons, I dont want to include more libs
Comment: +1 for this one is more simple than that 5 y.o. aswer above. Thank you so much. I think you can use this whenever you like without concern about high ammount of loop
Comment: This is the best answer if you already have org.apache.commons included in your project. Also this should be the accepted answer
Comment: Note that the implementation of LocaleUtils.isAvailableLocale() simply iterates through a cached list of locales. The performance is slightly better due to the caching, but it doesn't avoid the linear time search (aka high amount of loop mentioned by @poring91 ). https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/LocaleUtils.java
Answer: You can get the available locales like so and enumerate them to see if the locale is valid
boolean isValidLocale(String value) {
  Locale[] locales = Locale.getAvailableLocales();
  for (Locale locale : locales) {
    if (value.equals(locale.toString())) {
      return true;
    }
  }
  return false;
}

Comment: You only need to do it once and put it into a set
Comment: What about mixed locales with a language, which is not commonly spoken in selected country, like "en_RU"? It is a valid locale, but one cannot find it in the list of available locales.
Comment: This is very inperformant because of the large number of available locales!
Comment: You could introduce a sorted list with the most used locales, which is checked first and adds new locals if confirmed, this should reduce the checks of the whole available locales!
Comment: +1. If the resources are part of the actual application itself (and not integrated into the system from an external source or interface), I'd integrate the above code snippet into a unit test of sorts that checks all the resources filenames with the list found in `Locale.getAvailableLocales()`.
Comment: If the system doesn't know about it then you're out of luck I guess. You could I suppose decide to "special case" "en_XX" to default to en_US or something in that case.
Answer: use org.apache.commons.lang.LocaleUtils.toLocale(localeString).
one-liner, other than catching java.lang.IllegalArgumentException.
Answer: commons lang has a utility method to parse and validate locale strings: LocaleUtils.toLocale(String)
After that, you just have to check whether the variant is empty:
Validate.isTrue( StringUtils.isBlank( locale.getVariant() ) );

Answer: There are plenty of answers already but for a fast one-liner:
Arrays.asList(Locale.getAvailableLocales()).contains(Locale.US)

In a method:
boolean isLocaleAvailable(Locale locale) {
   return Arrays.asList(Locale.getAvailableLocales()).contains(locale);
}

Answer: You could check if the String is contained in the Arrays returned by the getISOCountries() or getISOLanguages() methods of Locale. Its kinda crude but may actually work.
You could also extract all available Locales with getAvailableLocales() and search them for display names.
Answer: Now I just do:
ULocale uLocale = new ULocale(locale);
if (uLocale.getCountry() != null && !uLocale.getCountry().isEmpty()) {
  ...
}

which works fine.
Answer: @Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RUNTIME)
@Constraint(validatedBy = ValidLocaleValidator.class)
@Documented
public @interface ValidLocale {
    String message() default "{constraints.validlocale}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class ValidLocaleValidator implements ConstraintValidator<ValidLocale, String> {
    private Set<String> validLocales = new HashSet<String>();

    @Override
    public void initialize(ValidLocale constraintAnnotation) {
        Locale []locales = Locale.getAvailableLocales();
        for (java.util.Locale l : locales) {
            validLocales.add(l.toString());
        }
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return validLocales.contains(value);
    }
}

public class ValidLocaleTest {
public static class MyBeanWithLocale {
    public static final String MSG = "not a locale";

    private String l;
    public MyBeanWithLocale(String l) {
        this.l = l;
    }
    @ValidLocale(message=MSG)
    public String getL() {
        return l;
    }
    public void setL(String l) {
        this.l = l;;
    }
}

    @Test
    public void testLocale() {
        //success
        MyBeanWithLocale b1 = new MyBeanWithLocale("fr_FR");
        Jsr303.validate(b1); //equivalent to Validation.buildDefaultValidatorFactory().getValidator().validate
        //failure
        try {
        MyBeanWithLocale b2 = new MyBeanWithLocale("FRANCE");
        Jsr303.validate(b2);//equivalent to Validation.buildDefaultValidatorFactory().getValidator().validate
        Assert.fail();
        } catch (Exception e) {
        Assert.assertEquals("[" + MyBeanWithLocale.MSG + "]", e.getCause().getMessage());
        }
    }

}
Answer: I had this problem recently. With the help from Common-lang I came up with this
 public static Locale getValidLocale(final Locale locale) {

    Set<Locale> locales = LocaleUtils.availableLocaleSet();
    List<Locale> givenLocales = LocaleUtils.localeLookupList(locale, Locale.ENGLISH);
    for (Locale loc : givenLocales) {
        if (locales.contains(loc)) {
            return loc;
        }
    }
    return Locale.ENGLISH;

}

LocaleUtils.availableLocaleSet() returns all available locales, but it stores the list in a static variable, so it is iterated only once
LocaleUtils.localeLookupList() takes a locale and creates a list with different granularities.
The code basically validates your locale using a more general version until english is used as fallback.

How to validate a locale in java?


geo:latitude,longitude?z=zoom in android taking me to my current location

Question: I want to call the inbuilt map app from my app. I came across this link. this page also gave me this link where I could really get what I want. I know
geo:latitude,longitude?z=zoom

is still in development mode.
My problem is that when ever I use this it takes to the desired location but then diverts me to my current location.
Here is the piece code I am using it
String uri = String.format("geo:%f,%f?z=18",(float)(latitude /1E6),(float)(longitude/1E6));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);

How can I fix it?
Comment: what is lat and long value also can you paste your code
Comment: Provide Sufficient code and you'll get a solution
Answer: You can try this one.....
Intent mapintent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+lat_string+long_string+"(Title_to_show)"));

Where lat_string and long_string are in there original format i.e 76.6464831 35.494 something..


Looking for some harmonic justification of chord progression: F G Bbm --> F?

Question: I have found this pretty melancholic cadence ( F-G-Bbm--> F) in many songs. For example in the beautiful Alan Parsons's "Since the last Goodbye", (in the form Db-Eb-Gbm--> Db). In this song the cadence is repeatedly modulated to different keys.
To accomplish these chords one need at least two chromatic alterations, so I wonder which are really the tonic. It appears to me that the tonic is F and Bbm is the dominant because it appears to lend and relax to F, and because by adding a minor 7ª: Bbm7 sounds as well good .
Nevertheless  it appears very strange to me to have a dominant that is constructed on the IV degree ( that should be subdominant) and moreover: of the minor kind.
Answer: Looking into the song and playing the progression myself I instantly noticed the connection between the words he was singing, the feelings he was trying to provoke, and the chord progression.
It starts on a hopeful and stable Db major chord which plays a majority of the song (and many of the other chords include Db in them according to the chord charts I'm reading). He moves hopefully up a whole step to Eb major (sometimes written Eb over Db), symbolizing the hope he still has for his lost love. This change happens over the word "goodbye" which also sounds natural when sung higher like that. Then when he sings "wrong" the chord changes to Gb minor (again written over Db) which symbolizing his sinking feeling at the realization he'll never get it back. Not only are we moving into a minor chord instead of a major chord like we would expect, but it's a chromatic movement downward by half step. It gives a very sinking feeling to the line and makes you want to sigh before we come back to rest comfortably on Db.
You could almost think of Db as the V chord and Gb minor as the tonic, symbolizing the unresolved nature of our protagonists dilemma. Yet while technically that works it still sounds like an unresolved cadence in context to the rest of the chords and the focus on Db. There's a lot of things going on here meant to be unresolved, nostalgic, longing, hopeful, etc. All the harmony is in service to the song.
Answer: I think we should reserve the term 'dominant' for the V chord in a key.
I can only answer your question with another.  Why SHOULDN'T this progression be OK?  It can be described as I, II, IVm, I.  Yes, two of these are chromatic chords.  Chromatic chords are common, and are perfectly 'allowed'.  This sequence works particularly well over a tonic pedal - F, G/F, Bbm/F, F - but is good with root position chords too.  It's easy to arrange with smooth voice-leading.   Add it to your bag of tricks.


Bootstrap: vertical tabs border content?

Question: Is there a way to put a border around the full content of each tab when using vertical tabs?
The tabs in bootstrap work quite well, but I don't like the default look.
I would prefer the tabs to put a full border around content.
Answer: you can try any of these styles
Bootsnipp tabs


Find the function satisfying these constraints

Question: From Stewart's Caclulus 6e

If $f$ is a differentiable function such that $f(x)$ is never 0 and $\int_0^x f(t) \, dt = \left[ f(x) \right]^2$ for all $x$, find $f$.

My attempt is as follows:
Differentiate both sides and apply the fundamental theorem of calculus
$$ f(x) = 2f(x) f'(x) $$
Since $f$ is never 0 for any $x$
$$f'(x) = \dfrac{1}{2} \implies f(x) = \dfrac{x}{2} + C$$
How can I determine what $C$ is?  I'm inclined to say $f(0) = 0$ since $\int_0^0 f(t) \, dt = 0 = \left[ f(0) \right]^2$ but that would violate the assumption that $f(x) \neq 0 \forall x$.
Plugging in $f$ to the integral yields
$$ \dfrac{x^2}{4} + Cx = \dfrac{x^2}{4} + Cx + C^2 $$
seemingly also implying $C=0$, but that means $f(0)=0$ again violating the initial assumption.
Where have I gone wrong?
Comment: https://math.stackexchange.com/q/1392520/42969
Answer: You are spot on.  The integral from $0$ to $0$ of any function is $0$, so if the first equation is correct for all $x$ you have $f(x)=0$.  The problem would be better stated that $f(x)\neq 0$ except when $x=0$.  You would then have to make a special argument to show $f(0)=0$ but you have that already.
Answer: Either there is a typo in the book, they should have written something like $f(x)\neq 0$ for $x\neq 0$.
But if the problem is correctly written as it is, then you just showed that there exists no such function. In that case, we don't even need to differentiate and solve. We can just put in $x=0$ and show that $f(0)=0$, and hence no such function exists.
Hope this helps. Ask anything if not clear :)


Kernel methods in machine learning?

Question: I am beginning to tackle geostatistics problems where I tried to apply kriging(gaussian processes) to interpolate demographical water drop. According to my understanding, kernel methods are something like this: I define a feature mapping from original space to feature space. kernel function is the function of the two vectors from original space to the dot product of their according mapped vectors in the feature space. Once we have defined the kernel functions, it is very easy to define distance and angel in the feature space. In terms of this, kernel functions can be used to estimate similarity.Thus I see kernel tricks in machine learning as a method to reduce high-dimensional problems to low dimensions.But I kind of do not get a intuition of how kernel is actually applied to these machine learning problems, like gaussian  processes, svm.Look forward to getting some intuition for this method.
I am also a bit confused about the weighted linear regression, gaussian processes and gaussian linear regression after reading a tutorial.(http://www.cs.nyu.edu/~mohri/icml2011-tutorial/tutorial-icml2011-1.pdf) I see gaussian processes as a locally method because of the bandwidth. But I do not know why it is also gaussian? We do not make assumptions on the prior distributions of the parameters.I just see gaussian processes as a constrained optimization problem.
Comment: Check out also our blog post on this in CPCS 481/581, Yale University: [Let's touch base on kernel methods](https://dadashkarimi.github.io/posts/kernel-2021/#page)
Answer: I would recommend you to review the following resources on the topic with excellent explanations:

Nice blog post on kernel functions for machine learning (ML);
Another nice blog post on using kernel approximations / kernel trick in ML;
Yet another nice blog post on using kernel methods in ML;
Great discussion on Cross Validated (CV) on advantages of Gaussian kernel in ML.

For more detailed technical treatment of the topic, see references in the above-mentioned blog posts as well as in answers within the CV discussion, linked above. Hope this helps.
Comment: Thanks for the resources! Ah I come up with a very specific question about kernel methods based on my current knowledge level, could you also have a look? Many thanks:D http://stats.stackexchange.com/questions/143644/locally-weighted-regression-vs-kernel-linear-regression
Comment: @DanqingZ: My pleasure! Thanks for upvoting/accepting - I'm glad to be able to help. I will take a look at the new question and see what I can do (no promises, though, as I'm not an expert in this :-).

Kernel methods in machine learning?


Exchange 2010/2016 Co-Existence, Secondary Logon Prompt

Question: We're currently running 2010 and 2016 in co-existence and we've migrated our first mailbox, woho!
However, on the test user account, the mailbox will not connect to the server, running an auto-discover test, we get prompted with a secondary logon for the user which always fails (see below)
Does anyone have any ideas?
Answer: According to the snapshot you post above, it looks like an Autodiscover action that Outlook uses a set of heuristics to determine whether the provided user account comes from Office 365. If Outlook determines confidently that you are an O365 user, an attempt is made to retrieve the Autodiscover payload from the known O365 endpoints(Outlook 2016 implementation of Autodiscover),
To avoid this action, you could try to add a DWORD value "ExcludeExplicitO365Endpoint" in the registry path "HKEY_CURRENT_USER\Software\Policies\Microsoft\Office\x.0\Outlook\AutoDiscover", then restart Outlook to see the result. If it doesn't work, you could reboot this client to make the change valid.
Answer: There are several areas you need to check:

Patch level of the clients.

Patch level of servers, both 2010 and 2016.

You need to match the authentication protocols between the servers.
Run the following command to compare:
Get-OutlookAnywhere | fl server, Name, URL, hostname, auth

Make sure all client connections are pointing to the highest Exchange version.

Validate that all virtual directories FQDN refer to Exchange 2016 environment, even those virtual directories defined on the Exchange 2010.


Woocommerce related product array with user input

Question: I am using the following code as the footer of my single-product.php page in Woocommerce (I've created a "Related Products" section) and I am wondering if there is a way that I can alter it to make it possible for admin to be able to add values from the product admin page; I want certain products to show closer related products instead of totally random ones.
Is there a way I can create a custom field for something like product ID or tag and then add that custom field as the orderby value so those products/tags have a better change of showing up vs. random products?
If not, is there anything else I can do? I am simply looking for a way to allow an admin to choose closer related products to appear.
$args = apply_filters( 'woocommerce_related_products_args', array(
    'post_type'            => 'product',
    'ignore_sticky_posts'  => 1,
    'no_found_rows'        => 1,
    'posts_per_page'       => 5,
    'orderby'              => rand,
    'post__in'             => $related,
    'post__not_in'         => array( $product->id )
) );
Here is my related-footer.php  file with the complete code that includes the above snippet.
Answer: Yes you can achieve this task as with the following approach:
Create a custom field for the product you want to display a set of your desired related products say the custom field name be "wdm_related_products" set the value to a comma separated list of Product ids eg. 46,15,687,21,48.
Update the product.
Add the following code in functions.php of user child theme or a custom Plugin.
add_filter('woocommerce_related_products_args','wdm_custom_related_products',99,1);

function wdm_custom_related_products($array){
global $product;
if(get_post_meta($product->,'wdm_related_products',true)){
$related=get_post_meta($product->id,'wdm_related_products',true);
$array=array(
    'post_type'            => 'product',
    'ignore_sticky_posts'  => 1,
    'no_found_rows'        => 1,
    'posts_per_page'       => 5,
    'orderby'              => rand,
    'post__in'             => $related,
    'post__not_in'         => array( $product->id )
);
}
return $array;
}

Let me know it it resolved your issue.
Comment: Hmm nope, it breaks my site when I put it into the functions.php file. There is a link to my related-footer.php file that's found in woocommerce > single-product folder, is there code I need to remove from there?


Finding basic probabilities of events

Question: Mike is sitting a multiple-choice exam, each question has four answer options, only one is correct. Mike takes $5$ guesses.
a) What is the expected number of correct answers Mike obtains from the 5 guesses?
I put $\frac54 = 1.25$, is this right?
b) What is the probability that all 5 of his guesses are incorrect?
I put $(\frac34)^5 = \frac{243}{1024}$, is this right?
c) What is the probability exactly $4$ or the $5$ are correct?
I put $(\frac14)^4 \times \frac34 = \frac{3}{1024}$, is this correct?
Answer: Everything is fine except for your last calculation. Think about how many different ways you can have 4 out of 5 correct, and multiply that by the probability that 4 out of 5 are correct after you have decided which 4. (Hint: It should have both $1/4$ and $3/4$ in the formula)
Comment: Woops I meant (1/4)^4*(3/4)
Comment: I would add another hint: The number of correct answers is a random variable with binomial distribution.
Comment: @user2850514 Even so, you are missing another important factor.  Remember the binomial distribution (if you have learned it) else think of a tree diagram and how many different spots that the correct answer could have been.
Comment: There are also 5 ways of doing this so we should multiply by 5
Comment: Right, if you multiply your formula by $5$ then you should get the right answer.
Answer: Yes. Your solution in the comment, $(\frac{1}{4})^{4}\cdot\frac{3}{4}$, is the correct answer on the last question.

Finding basic probabilities of events


How to get feedback from chef-clients

Question: We are considering using chef to manage our application servers. So, we are creating recipes which configure resources for us as needed in certain situations.
But what happens if the execution fails? Do we have to manage for this cases manually? Are the logs of failing recipes posted somewhere for centralized monitoring? Are there common solutions for this cases like adding some kind of fail handler which notifies the interested parties?
UPDATE: We are running chef-client on the servers as a daemon with <code>-d -i 60</code>
Answer: Chef logs output to STDOUT or a file. Sometimes that is not enough, though, especially if it fails when running as a daemon and the logs were rotated, or simply difficult to mine out of a centralized log server.
Chef has a reporting / exception handling API. It is documented in detail on the wiki, including links to example handlers written by the community.
http://wiki.opscode.com/display/chef/Exception+and+Report+Handlers

How to get feedback from chef-clients


how to activated piece of code inside an if statement

Question: I've made a simpler example of what i'm actually trying to do http://jsfiddle.net/r5o6cmmd/1/
i want Jquery to change the div's color once $change = true however that does not seem to work. could anyone explain why? and how can i do it anyway? (changing the color by pressing a button will not do, i need the color to change through the if statement - only when $change = true)
$(document).ready(function(){
$div = $('#div');
$button = $('#button');
$change  = false;

$button.on('click',function(){

   $change = true;

});

if($change)
     $div.css('background-color','red');

});

Comment: Upon clicking the button, the only code that runs is the code inside the `click` handler. Your `if ($change)` only run once, and it's before the event is fired. Why not change the background-color in the event handler itself?
Comment: The `$` prefix for variables has no meaning in JavaScript, it is sometimes used by programmers to indicate a jQuery variable. Prefixing a regular variable name with `$` makes absolutely no sense.
Comment: is there a way to make the entire code rerun once the button clicked?
Comment: The right way to do it, is to put the `if` inside the event handler. Re-running your `document.ready()` would reset `$change` to false anyway.
Answer: DEMO
You do not want to change the color upon clicking of the button and yet the condition upon changing of the color depends on the click!! Well, the changing of the color has to be moved to  where that condition changes, which is inside the click handler as below, and there's not need to test the variable because you know it's true. In fact there's no need for the variable unless you need it later.
$(document).ready(function(){
    $div = $('#div');
    $button = $('#button');

    $button.on('click',function(){
        $div.css('background-color','red');
    });
});

Comment: Kind of silly to test a variable you just set, don't you think?
Comment: No need the condition.
Answer: If you want to test the variable periodically, use setInterval
setInterval(function () {
    if (change) {
        $div.css('backgroundColor', 'red');
    }
}, 500);

Answer: You're missing curly braces for the if statement. Also, if that doesn't fix it...try moving the if outside of the ready function.
if (change) {
    $div.css('backgroundColor','red');
}

Comment: Yes, it's bad practice, I always recommend against it. But it's not a problem, so this isn't an answer.
Comment: If there's only one statement in the body, you don't need braces.
Comment: I didn't know that, but that seems like bad practice and might burn you later on in the code. @Barmar


How do I pass a specific argument from a rules event to a condition?

Question: I am setting up a default rule for my custom Drupal 7 module, as follows:
<code>$rule->event('commerce_cart_product_add')
->condition(
  'mymodule_condition_1',
  array('something' => 'something_else'))
->action(
  'drupal_message',
  array(
    'message' => t('Example message'),
  ),
));
</code>
I have written a function, mymodule_condition_1, which returns TRUE or FALSE based on what product is being added to the cart. I need to be able to get the product from the rules event, and pass this to the condition. I have looked through all the documentation and example code but I can't seem to see a way to do this.
In the above example, 'something' and 'something_else' need to be specific values, but I can't see what I can refer to in order to find out what they should be.
Answer: In a case like this, you'd going to have to use what Rules calls a data selector. If you were building this Rule through the UI, you would click the "Switch to data selection" and enter some token that corresponds to the type of parameter required.  In this case, the commerce_cart_product_add event provides the arguments commerce_order, commerce_product, quantity, commerce_line_item, and commerce_line_item_unchanged.  (See all this in the event's definition in commerce_cart.rules.inc.)  So when trying to select the product passed to the event through the UI, you'd use commerce-product as the value for your condition's product parameter.
When building this Rule in code, you specify a data selector by appending :select after your condition's parameter's name.  So, if the name of the product parameter for your condition (as defined in hook_rules_condition_info()) is commerce_product, your "something" would be commerce_product:select.  The "something_value" would be the same token you'd enter through the UI, commerce-product (as that's the name of the product argument passed to the Rule).
And touching on one more aspect, the event info defines the variables that must be passed to Rules when an event is invoked.  Your condition can use any, none, or all of these - it doesn't really matter. A condition or action's definition simply states what kind of parameters it needs, and the Rule configuration is responsible for passing the parameters to the condition from the pool of available variables (or from variables you load as part of the configuration).
Comment: Thanks, I was missing the bit in my condition that tells rules what parameters I want to accept. So, I had told it which bit of the event's parameters I wanted to use, but the condition was not aware I wanted to use it. This answer really helped!


Where condition in Razor DropdownList MVC

Question: I am generating a dropdownlist in MVC. I have a model in view which have two list values. My code looks like
@Html.DropDownList("Test", new SelectList(
                            Model.Test.Where(i=>i.Id = *from other list*), "Id", "Name"))

In my Model I have two Lists :
List<Test> and List<Test2>. What I am trying is generate dropdown where Test1.Id is equal to Test2.Id.
Answer: Try this:
@Html.DropDownList("Test", new SelectList(
     Model.Test.Where(i=>Model.Test2.Any(ii=> i.Id == ii.Id)), "Id", "Name"))

Example with Any statement:
    static void Main(string[] args)
    {
        List<string> listA = new List<string>() { "A", "B", "C" };
        List<string> listB = new List<string>() { "D", "F", "A", "B", "E" };

        var result = listB.Where(lb => listA.Any(la => la == lb));
        Console.WriteLine(result.Count());
    }

Result: 2


Instagram API - How to build a media viewer to get posts by hashtag from some users?

Question: Is it possible? I have read the documentation but I wish to know there is one way. I need to create a gallery with some hashtags and filter by some users. Maybe something in the backend can do it?
Answer: No. From the official api, you can't get other users' media anymore. They only allow developers or users to fetch their own "RECENT" media. So does hashtags.
More and more restrictions and fewer and fewer APIs opened by Instagram, it's hard to do valuable stuff around IG now.
Answer: It is possible. The developer client key defaults to your own content in sandbox mode. You have to create a submission for approval, you can do this via: https://www.instagram.com/developer/clients/ and choose the client that you have created, then the permissions tab will allow you to apply.
I am going through the application process at the moment for our App, it is very difficult as Instagram are stringent.


How to pass custom parameters to Facebook share link

Question:
Possible Duplicate:
How does Facebook Sharer select Images?

How do I make a link that I can customize the title, image, link, and description that's shared?
Answer: This no longer works as of 18/12/2013. See comments for alternatives.
http://www.facebook.com/sharer.php?s=100&p[title]=titleheresexily&p[url]=http://www.mysexyurl.com&p[summary]=mysexysummaryhere&p[images][0]=http://www.urltoyoursexyimage.com

http://blog.cjgammon.com/?p=336
I was tired of scouring sites on google for this.
Comment: As of 18/12/2013, this no longer works. Any other ideas of using custom parameters?
Comment: works perfect!
but what is the strange `s=100` param?
Comment: FYI, the old Facebook share.php api is _**NO LONGER DEPRICATED**_ http://www.joshuawinn.com/facebooks-sharer-php-longer-deprecated-2014/ and if you are still unsure https://stackoverflow.com/q/27973009/1611058
Comment: `` with sharing like this, is it possible to customise the comment too?
Comment: Work partially: http://contat.eu/facebook/vtour/fan.html
Comment: sharer.php is deprecated now. The new way to do it is https://developers.facebook.com/docs/reference/dialogs/feed/
Comment: @Ashish The Feed Dialog for web has been deprecated in API Version 2.0.
Facebook recomeds to use Share Dialog now,
Answer: You do so by using facebook's open graph meta tags. Take a look here:
http://davidwalsh.name/facebook-meta-tags
Comment: Thank you, but that does not address the problem of sharing


Disable form submission on pressing enter because i am using Ajax functionality

Question: I am using ajax functionality. When i am selecting any suggestion using enter key, the form get submitted automatically because the submit button is auto-focused. Is there any way to select ajax suggestion using enter key as well submit the form using enter key. Something like when i input the values of all the fields then only submit button get enabled.
Answer: How are you calling your Ajax function? It should be inside the submit event handler of the form. And then if you have the event handler return false it won't submit normally:
<form onsubmit="doAjaxSubmit(); return false;">
  ...
</form>

Comment: It doesn't seem like this would solve the problem, since hitting enter on the auto-complete field would still cause an AJAX submission.
Comment: but i am using one form validator method on the onsubmit call how i'll call this method if there would doAjaxSubmit().
Answer: You can detect which key is pressed using the .keypress() method. From this you should be able to return false; for form submit and do your ajax stuff on the back of it in an if statement:
http://api.jquery.com/keypress/
Comment: i am not using jquery for the ajax functionality, so cant use Jquery.keypress() function.
Answer: You can have your form's onSubmit return true if all the fields have values, or false if they don't.