Distribution like hypergeometric distribution, but with false replacements

Question: I'm trying to find probabilities for a scenario that works exactly like hypergeometric distribution, except that every time you make a draw, you replace it with a "failure"-object. So eventually you'd end up with no successes among the population. What I'd like to describe is the probability of a certain number of successes given a certain number of draws.
An example of this situation could be: You're pulling marbles out of an urn. There are green marbles (successes) and white marbles. Everytime you pull out a white marble (failure) you just put it back but every time you pull out a green marble (success) you replace it with a white marble. So the number of marbles remain constant, but the number of successes decreases each time you draw a success.
Do we have a probability distribution to describe this?
Comment: What do you mean by "false" objects? Maybe you could give us an example? Maybe you mean negative hypergeometric distribution https://en.wikipedia.org/wiki/Negative_hypergeometric_distribution
Comment: Hi Tim, thanks for your comment. I added an example to hopefully make it more clear what I'm asking. I hope it makes more sense now. It is unfortunately not negative hypergeometric distribution which I'm looking for.
Comment: What exactly is the random variable you want to find the distribution? You described a proccess, but not the variable you're interested in. Is it the total number of green marbles after a fixed number of trials?
Comment: Hi Victor!
Yes, that is what I am interested in. I have found an expression for the expected number, but would like to add see some probabilities.
Answer: Suppose an urn of $n$ balls begins with $s$ successes.  What are the chances it will end up with $t$ successes ($0 \le t \le s$) after $d$ draws?
Ignoring the trivial case $s=0$, this is a Markov chain on the numbers of successes $s$.  The chance of a transition from $s$ to $s-1$ is $p(s,s-1)=s/n$; otherwise, the state stays the same: $p(s,s)=1-s/n$.
The $n+1\times n+1$ transition matrix $\mathbb{P} = p(s,t)$ (indexing from $0$ through $n$) readily decomposes as
$$\mathbb P = \mathbb{V}\operatorname{Diagonal}\left(\frac{n}{n}, \frac{n-1}{n}, \ldots, \frac{1}{n}, \frac{0}{n}\right) \mathbb{V}^{-1}$$
where $$\mathbb{V} = (v_{ij}, i=0,\ldots,n; j=0,\ldots, n) = \left(\binom{i}{j}\right)$$
is Pascal's Triangle and $$\mathbb{V}^{-1} = (v^{-1}_{ij}) = \left((-1)^{i+j}\binom{i}{j}\right)$$
contains the same values but with alternating signs.
The chance of a transition from $s$ to $t$ after $d$ steps, $p_n(s,t)$, is found from the $s,t$ entry in $\mathbb{P}^n$ (again indexing from $0$ through $n$).  But we easily compute
$$\mathbb{P}^n= \mathbb{V}\operatorname{Diagonal}\left(\frac{n^d}{n^d}, \frac{(n-1)^d}{n^d}, \ldots, \frac{1^d}{n^d}, \frac{0^d}{n^d}\right)\mathbb{V}^{-1}.$$
Consequently, omitting all terms obviously zero,
$$p_d(s,t) = n^{-d}\sum_{j=t}^s \binom{s}{j} (n-j)^d (-1)^{j+t}\binom{j}{t}.$$

These figures plot the chance of reaching an urn with $t$ successes starting with $s=100$ successes in $n=100$ total.  The numbers of draws are 10,50,150,and 250.  As they increase, the distribution moves to the left more and more slowly, first spreading and then contracting to zero.
In terms of $t$, these are generalized hypergeometric distributions.
Answer: There will be a recursion. If $S_{n,g,b}$ is the number of green balls successfully drawn with $n$ attempts starting with $g$ green balls and $b−g$ white balls then
$$\mathbb P (S_{n,g,b} = s)= \frac{g}{b}   \mathbb P (S_{n-1,g-1,b} = s-1) + \frac{b-g}{b}   \mathbb P (S_{n-1,g,b} = s)$$
starting with $\mathbb P (S_{0,g,b} = 0)= 1$, and with $\mathbb P (S_{n,g,b} = s)= 0$  when $s \gt n$ or $s \gt g$ or $s \lt 0$
For example, with $b=15$ balls in total and $n=5$ attempts, the probability of $s$ successes when starting with $g$ green balls is about:
<code>Probability table with n=5 attempts, starting with g green and b=15 total balls
(rows sum to 1)

        s (number of successes)
        0           1           2           3           4           5           6
g start
0       1           0           0           0           0           0           0
1       0.708246    0.291754    0           0           0           0           0
2       0.488946    0.438600    0.072454    0           0           0           0
3       0.327680    0.483797    0.174104    0.014420    0           0           0
4       0.212084    0.462386    0.274015    0.049462    0.002054    0           0
5       0.131687    0.401982    0.352000    0.104691    0.009481    0.000158    0
6       0.077760    0.323563    0.397037    0.174617    0.026074    0.000948    0
7       0.043151    0.242261    0.405689    0.250272    0.055309    0.003319    0
8       0.022133    0.168149    0.380523    0.320790    0.099556    0.008849    0
9       0.010240    0.107034    0.328533    0.374993    0.159289    0.019911    0
10      0.004115    0.061248    0.259556    0.402963    0.232296    0.039822    0
11      0.001348    0.030434    0.184691    0.397630    0.312889    0.073007    0
12      0.000320    0.012342    0.114726    0.356346    0.391111    0.125156    0
13      0.000042    0.003612    0.058548    0.282469    0.451951    0.203378    0
14      0.000001    0.000572    0.021570    0.186943    0.474548    0.316365    0
15      0           0.000020    0.004148    0.089877    0.431407    0.474548    0
</code>
I am not aware of a common named distribution like this
Comment: You can solve this recursion explicitly.  One way is to represent the situation as a Markov chain.  It's a particularly simple one.
Comment: @whuber: No doubt you are correct, but it did not seem particularly obvious to me in general.  Clearly $\mathbb P (S_{n,g,b} = 0) = \frac{(b-g)^n}{b^n}$ and $\mathbb P (S_{n,g,b} = n) = \frac{g!}{(g-n)! \,b^n}$ but it looked more complicated for other values of $s$


Como setar chave e valor de um objeto criando uma instância e colocar os valores no map?

Question: Eu só sei fazer o hashmap de uma forma que é criando uma instância no método put para fazer inserção de valores.
Segue a forma que sei fazer:
import java.util.Map;

public class Teste {

public static void main(String[] args){

//Exemplo com utilização de hashmap

    Map<Pessoa, Pessoa> example = new HashMap<Pessoa, Pessoa>();

    example.put(new Pessoa(12), new Pessoa("Aline"));
    example.put(new Pessoa(13), new Pessoa("Carla"));

    int key = 2;

    if(example.containsKey(key)){
        System.out.println("Valor é:" + key + " = " + example.get(key));

    }else{
        System.out.println("Não existe!");
    }
  }
}

Mas não consegui fazer dessa forma como faz isso? exemplo:
import java.util.Map;

public class Teste {

    public static void main(String[] args){

    //Exemplo com utilização de hashmap

        Map<Pessoa, Pessoa> example = new HashMap<Pessoa, Pessoa>();

        Pessoa pessoa;

        pessoa = new Pessoa();
        pessoa.setId(40);
        pessoa.setNome("Aline");

        example.put(pessoa.getId(), pessoa.getNome());

        int key = 2;

        if(example.containsKey(key)){
            System.out.println("Valor é:" + key + " = " + example.get(key));

        }else{
            System.out.println("Não existe!");
        }
    }

Class Pessoa:

package ibm;

public class Pessoa {
private Integer id;
private String nome;

Pessoa(Integer num){
 this.id    = num;
}

Pessoa(String nome){
    this.nome = nome;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

}
Comment: Se nome é string e id é int, porque você não declarou ` HashMap()` ao inves de usar Pessoa? Não está claro o que você está tentando fazer.
Comment: Quando vc cria um new class vc esta alocando um ponteiro para os dados, talvez vc esteja querendo fazer um map. Realmente não ficou muito claro a pergunta
Comment: Eu só quero fazer a implementação de uma forma que não precise criar instancia. eu quero pegar valores já definidos em uma objeto e inserir.
Answer: Os tipos da chave e do valor do seu Map não batem com o que você está tentando inserir nele.
O Map é um tipo de coleção que guarda chaves e valores, com o objetivo de você localizar um valor através de sua chave. No caso você quer que a chave seja um inteiro (id) e o valor seja o nome da pessoa (String). Então seu Map deve refletir isso. Em outras palavras...
Esta linha:
Map<Pessoa, Pessoa> example = new HashMap<Pessoa, Pessoa>();

deveria ser trocada por:
Map<Integer, String> example = new HashMap<Integer, String>();

ou melhor ainda, por:
Map<Integer, String> example = new HashMap<>();

ATUALIZAÇÃO: Pensando melhor, talvez você queira fazer um pouco diferente e localizar uma Pessoa através do seu id. Nesse caso você deve declarar o seu Map assim:
Map<Integer, Pessoa> example = new HashMap<>();

e alterar seu put() assim:
example.put(pessoa.getId(), pessoa);

Feito isso, você poderá ver qual é o nome da pessoa assim:
Pessoa pessoa = example.get(id);
System.out.println("Nome: " + pessoa.getNome());

Comment: E o que tem isso a ver com o que eu falei? O seu `put(pessoa.getId(), pessoa.getNome())` está correto, o que você precisa trocar é a declaração do seu map de `Map` para `Map`. Porque `getId()` retorna um inteiro e `getNome()` retorna uma String, seu map deve ser compatível com isso, deve guardar inteiros apontando para Strings.
Comment: @user3010128 Correto, a única ressalva é que no lugar de `int` que é um tipo primitivo tem que ser a classe `Integer`, mas acho que você já sabe disso.
Comment: mas na Pessoa estou inserindo um id.
Comment: Vou tentar isso
Comment: Bem, vou tentar explicar, o id é um Integer e o nome é uma String logo o que esta descrito ali é vc irá criar uma mapa de chave Integer (id) que ira guardar Strings (nome), ou seja, Map()
Comment: Pensando melhor, talvez você queira fazer um pouco diferente e localizar uma Pessoa através do seu id. Atualizei a resposta explicando como fazer.


Make Title field "not required" or workaround how to prefill and hide it (drupal 9.2.8)

Question: On my site (drupal 9.2.8) users add content and there is no need to put any information to 'Title' field.
I was trying to make this field not required via form_alter in custom module but it did not work:
function yourmodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if ($form['#form_id'] == 'node_somenode_form' or $form['#form_id'] == 'node_somenode_form'){
    $form['title']['widget']['0']['#required'] = FALSE;    // not working
    $form['title']['widget']['#required'] = FALSE;    // not working
    $form['title']['#required'] = FALSE;    // not working
  }
}

As a workaround in my module I prefill Title using form_alter:
$form['title']['widget']['0']['value']['#default_value'] = 'any default title';

and then just hide this field from form. There are a few ways of doing that (In form alter what is the different way of hiding fields and what is the difference between them?
), I decided to use hide:
hide($form['title']);

but I am curies why ['#required'] = FALSE; doesn't work for Title field but it works fine with other fields.
Comment: You can try this https://drupal.stackexchange.com/questions/183477/how-to-programmatically-create-a-title-for-a-new-node
Answer: You should use Automatic Entity Label:

"Automatic Entity Label" is a small and efficient module that allows hiding of entity label fields.


Is there a way to set the active menu's text as page title?

Question: I would like to set the active menu's text as the page title in drupal7. I tried using the page title module and found no replacement patterns to set the active menu as the page title. Any help is widely appreciated.
Thanks
Comment: Why can't you change the node title to be the same as the menu? Since your menu is static the page title can be too.
Comment: As per my need I should have the Head and page title different, hence I cannot go with the above implementation !!
Answer: I found the answer with this link http://sivaji.drupalgardens.com/how-set-custom-page-title-drupal-7.
There exists no way to dynamically set the active menu as the page title, but with the Classes_array from the vars, we can check the page's id and then set the page title as per our need.
In my case I used a if check to check the page id (Page-contact's page title to Contact) and so. It worked for me though, but still found no way to dynamically set the title from the active menu !
Comment: You are asking for a rare feature, but there are no replacement tokens for the menu items. (And why should there be, menu titles are usually shorter then the real titles). You could try to write a custom drupal modules that hooks onto the menu API ( http://api.drupal.org/api/drupal/includes!menu.inc/group/menu/7 ). But not sure whitch title they mean there.


Change order status string from "Completed" to "Shipped"

Question: I'd like to change the order status string from "Completed" to "Shipped" to allow for better communication between us and the customer.
Commerce Custom Order Status would sidestep this problem by allowing me to create a new status, but that isn't the best way around it, because there might be triggers set for "completed".
Answer: The best thing for you to do would be to alter the order status info array to give the "Completed" status a new title. The example in the documentation actually demonstrates specifically how to change the title of the completed status. Look for hook_commerce_order_status_info_alter() in commerce_order.api.php.
There are ways to override strings through the user interface, but this is such a small module change that I'd really recommend directly making it in a site-specific module.
Comment: thanks! used `hook_commerce_order_status_info_alter(&$order_statuses) {
  $order_statuses['completed']['title'] = t('Shipped');
}
` It worked for the user viewing in their order history, but it still shows "completed" in the admin pages (admin/commerce/orders/list). Is there away to change the name for the admin pages too, because the person who administers that might get confused
Comment: **Ryan** answer @ashash question please, is there any way to change in admin pages too?
Answer: I would suggest adding a new order status instead of modifying the "Completed" order status, since that usually means the order is done-done-done.  Something like "Pending: Shipping" (in the "Pending" order state) would make more sense given a workflow like this:

Pending: Pending -- The order is paid and ready for shipping.
Pending: Shipping* -- The order has shipped and may have a tracking number attached. *Note: You would need to add this status value in a custom module.
Completed: Completed -- The order was delivered, shipping has been fulfilled, no further action required by the store.

See also:

https://drupalcommerce.org/faq/order-states
http://www.drupalcommerce.org/developer-guide/core-architecture/info-hooks/order-info-hooks

You can certainly add to the "Pending" state as suggested above for something simple.  For a more detailed example, you can also have a separate "Shipping" state and statuses:
<code>/**
 * Shipping status
 */
define('SHIPPING_PENDING', 'shipping_pending');
define('SHIPPING_SHIPPED', 'shipping_shipped');
define('SHIPPING_DELAYED', 'shipping_delayed');
define('SHIPPING_CANCELED', 'shipping_canceled');
define('SHIPPING_DELIVERED', 'shipping_delivered');

/**
 * Implements hook_commerce_order_state_info()
 */
function example_commerce_order_state_info() {
  $order_states = array();

  $order_states['shipping'] = array(
    'name' => 'shipping',
    'title' => t('Shipping'),
    'description' => t('Orders in the shipping process.'),
    'weight' => 10,
    'default_status' => SHIPPING_PENDING,
  );

  return $order_states;
}

/**
 * Implements hook_commerce_order_status_info()
 */
function example_commerce_order_status_info() {
  $order_statuses = array();

  $order_statuses[SHIPPING_PENDING] = array(
    'name' => SHIPPING_PENDING,
    'title' => t('Shipping: Pending'),
    'state' => 'shipping',
    'weight' => 1,
  );
  $order_statuses[SHIPPING_SHIPPED] = array(
    'name' => SHIPPING_SHIPPED,
    'title' => t('Shipping: Shipped'),
    'state' => 'shipping',
    'weight' => 2,
  );
  $order_statuses[SHIPPING_DELAYED] = array(
    'name' => SHIPPING_DELAYED,
    'title' => t('Shipping: Delayed'),
    'state' => 'shipping',
    'weight' => 3,
  );
  $order_statuses[SHIPPING_CANCELED] = array(
    'name' => SHIPPING_CANCELED,
    'title' => t('Shipping: Canceled'),
    'state' => 'shipping',
    'weight' => 4,
  );
  $order_statuses[SHIPPING_DELIVERED] = array(
    'name' => SHIPPING_DELIVERED,
    'title' => t('Shipping: Delivered'),
    'state' => 'shipping',
    'weight' => 5,
  );

  return $order_statuses;
}
</code>
Answer: You can use the drupalcommerce complete hook to change the $order status:
<code>function hook_commerce_checkout_complete($order) {
  // insert code
}
</code>
Comment: The questioner doesn't just want to use a different status but actually wants to rename an existing one.


Deep clean sound from Pod X3

Question: I recently got a Pod X3 and like McD's I'm loving it.
I'm trying to get a deep clean riffing sound from it like in Torn by Creed.
I can't seem to find a configuration that gives a deep, bassy sound like that.  I've cranked the bass way up on the EQ, tried a couple of the amp flavors.. but not quite getting that sound.
How exactly would you get a sound like that, (with or without a Pod)?
Comment: You do realize that exactly at 0:52, that little lick before the chorus is actually done by a bass? =D
Answer: "Mark Tremonti's Guitar Gear Equipment and Rig" mentions his amp's settings, and amp types. That's a starting point. Note that it says he uses a "Bogner Uberschall for low end", so on your X3 try setting up a dual-patch with a Rectifier head and cabinet, and a second stack using the Bogner amp model. I don't remember which one it was, but I'm pretty sure they have one in the Pod X3.
Even with the exact same amp, cabinets, guitar, cables, effects, picks and maybe even clothes, you still won't sound like a particular player. A lot of their sound comes from their fingers and picking attack and even attitude.
Besides that stuff, a couple things might help. Have you tried:

Drop-D tuning? The song you link to has that low note that sounds very drop-d-ish.
Cranking the bass on the amp isn't necessarily going to give you a full bass sound. On a lot of amps it will give you a muddy, or flabby sound because the amp can't handle the power demand. A Pod X3 (which I also have) will model the performance of a particular amp, including its (in)ability to stay clean at particular settings.
Cabinet types make a big difference. I've gotten better solid lows out of the modeled Rectifier 4x12-type cabinet than I did from the Marshall imitations but you might not like that particular sound.
What type of guitar and pickups are you using? Hot pickups can push the amp-model too hard so backing down on the volume might be necessary. Unfortunately, the X3 seems to suffer from impedance loading worse than a real tube amp, so your sound might get muddier than you want - it's a balancing act. Also, humbuckers seem to get muddy faster than single-coils, especially when you roll the volume back.
What are you using to monitor your sound? High quality headphones designed for studio work? Plugging into a stereo system? Running into a power-amp then to some high quality keyboard cabinets? Or, are you plugging into a combo's input jack? You want to remove external influences from the sound. I set up my patches using a good set of Sennheiser over-the-ear headphones plugged into the headphone out of the X3. I get the same sound going into the computer that way. My amplification comes from the power-amp section of a Line6 Flextone III, skipping its pre-amp and modeling. It's a very clean amp so the X3 sound isn't messed up like it would be going into a regular guitar amp.
Comment: And don't forget you can use the EQ.
It may help to get the sound you want as it doesn't have the same effects as the bass / middle / treble knobs.
Comment: On the guidance of my singer, I have recently tried a proper EQ footpedal before my effects - makes a hell of a difference when trying to recreate particular sounds!
Comment: I have a MXR 10-band as the first item in my effects chain with the guitar amp.
Answer: Another reply has already been marked as answer, but I do believe that if you are looking for Mark's CLEAN SOUND, the model you want is this:
1965 Double Verb (*based on a Fender Twin Reverb)
This is a later gear post, but worth mentioning:
"For cleans, Tremonti uses a duo of Fender 65 Twin Reissues with a TC Electronic G-Force for delay and reverb"
http://www.premierguitar.com/articles/Rig_Rundown_Creeds_Mark_Tremonti
I believe Mark used Fender Twins even in the early days of Creed and used an A/B switch to move to the Mesa when using high gain. I dont know how early he used the Bogner.

Deep clean sound from Pod X3


IOS. segue.destinationViewController object is different from the Controller loaded

Question: I'm trying to make a transition between two ViewControllers using a Navigation Controller, the object referenced by segue.destinationViewController is: 0x1cd93590 (the next view), but when the change is made to the newly view this has a different number of object: 0x1cd4556d0. My code is:
- (void)updateCodeProduct:(NSString *)code {
    [session stopRunning];

    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    AudioServicesPlaySystemSound(1111);

    // db acces.
    NSString *cadena = @"http://172.20.10.2/consultaProd.php?codigo=";
    cadena = [cadena stringByAppendingString:codigo];
    NSURL *url = [NSURL URLWithString:cadena];
    NSError *error = nil;

    NSString *retorno = [[NSString alloc] initWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
    if (retorno == nil) {
        NSLog(@"Error %@\n%@", url, [error localizedFailureReason]);
        return;
    }

    self.detailProd = nil;
    self.detailProd = [retorno componentsSeparatedByString:@"\n"];

    [self performSegueWithIdentifier:@"DetailSegue" sender:self];
}

The prepareForSegue method is:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSLog(@"%@", [segue destinationViewController]);

    if ([segue.identifier isEqualToString:@"DetailSegue"]) {
        [segue.destinationViewController updateDetail:detailProd];
    }
}

The segue is performed, but the view does not reflect the current information, because is a different object.
Any Help will be appreciated :)
Answer: What does the updateDetail method do? If it's trying to update a control in the destination controller, it's too early to do that, since the controls won't have been created yet. You just want to set properties (e.g. a NSString or whatever) in the destination controller. The destination controller should then take that property and update its controls in viewDidLoad of that destination controller.
In short, the address of the destination controller will be the same as address of the view controller itself. You don't show us your NSLog statements for those two addresses you're reporting, so it's impossible for us to say what's going on there.
Comment: Thanks @Rob, the method -updateDetal belongs to DetailViewControler, and update two UILabels, quote(If it's trying to update a control in the destination controller, it's too early to do that, since the controls won't have been created yet). I correct this creating tho NSString and updating the labels in a -viewdidLoad method. And works fine.... Thanks a lot. :)


Memory monitor in Android Studio reports different RAM usage than the device

Question: When investigating RAM usage in an app I am working on, I have been using the Memory Monitor tool in Android Studio (can be accessed in Android Studio by going to Tools>Android>Memory Monitor). I have noticed the RAM usage of my app that is reported in Memory Monitor, is always far lower than when viewing the RAM usage from the device (can be accessed by going to Settings>Apps>Running).  As you can see in the screenshots below, Memory Monitor is reporting about 18MB of RAM usage (23MB if you include free space), but the device is reporting 43MB.
Why the difference and also is one more accurate than the other?
Comment: I would focus instead on `procstats`: http://android-developers.blogspot.com/2014/01/process-stats-understanding-how-your.html
Comment: In the developer docs Google also has a description on "Investigating RAM Usage" https://developer.android.com/tools/debugging/debugging-memory.html that involves the Android Device Monitor.  This can be accessed in Android Studio by going to Tools>Android>Android Device Monitor
Answer: I suspect that the memory monitor tool is talking to the dalvik virtual machine about heap allocations made by Java code, and the device manager is showing what the entire process is using for memory.  So the first does not include overhead or memory used by the virtual machine itself (or its text and libraries), or any off-heap allocations (sometimes native code can allocate memory that isn't directly visible to the VM).
See https://developer.android.com/tools/debugging/debugging-memory.html#ViewingAllocations and try running the command:
adb shell dumpsys meminfo <package_name>

to get a more precise breakdown of the run-time memory usage of your application.
Answer: I've tested the Android Studio's Memory Monitor's Allocated can be get this way programmatically:

long allocatedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

But this only works to get information of the current app.


How to check if i have strong linear relationship between dependent variable and independent variables in linear regression (OLS)?

Question: I want compare the out of sample prediction from an linear regression model (OLS) and a regression tree. I read that OLS outperforms regression tree if the relationship between the dependent variable and independent variables is strongly linear.
How I can check the linear relationship between dependent and independent variables?
Comment: I dont understand why this question get a downvote...
Comment: ols = ordinary least squares?
Comment: @bi_scholar yes
Comment: "I want compare the out of sample prediction" - maybe I am missing something, but why don't you simply compare the out of sample prediction? If you don't have a source of out of sample data, cross validation is a useful approximation. Checking the linear relationship is just a very indirect proxy for the actual prediction task.
Comment: with out of sample prediction i mean i have a test set
Answer: A better approach is to think hard about the model specification and to seldom assume linearity, as it is unusual for variables to be linearly related to each other.  With very small sample sizes we must sometimes force a linearity assumption because we can't do much else without penalized maximum likelihood estimation.
Making scatterplots isn't always a good idea as if you are using classical frequentist methods, using observed relationships will distort p-values and confidence intervals and also cause overfitting of the model.
My Regression Modeling Strategies book and course notes and accompanying R package rms go into great detail about this, and shows how to use regression splines to relax linearity assumptions.
Single regression trees are not competitive with regression and they do not properly handle continuous variables.
Comment: That's why i tried to test for linearity assumption because i compared a regression tree with a ols regression and get better prediction with the ols model. I read that when the dependent variable and the independent variable have strong linear relationship that the ols regression outperforms the regression tree i terms of prediction so i searched ways to show this strong linear relationship or tried to explaine why ols outperform the regression tree
Comment: You missed all my points.  Please re-read.
Answer: Your question is not very clear. But still you can check the linearity between the independent and dependent variables by plotting them as scatter plots. Scatter plots will give you a very good idea about the linearity of the variables. You will have to plot multiple scatter plots for each independent variables keeping the dependent variable constant.


Blocking HEAD, DELETE, etc. with lighttpd

Question: So I have lighttpd installed and the site it runs only needs to respond to GET requests.
I was wondering how I can return 405 responses with Allow: GET headers to anything but GET requests using lighttpd?
I've had a quick google but even the lighttpd doesn't turn up anything solid.
Update
Limiting by $HTTP["request-method"] works a treat.
Unfortunately when you use url.access-deny lighttpd sets the status code and headers as a fixed thing (403 status), regardless of if you try to add header before or after.
End result:
$HTTP["request-method"] =~ "^(PUT|HEAD|PATCH|DELETE)$" {
    url.access-deny = ( "" )
}

Answer: Since version 1.4.19, you can filter on request-method:
$HTTP["request-method"] =~ "^(PUT|POST|HEAD|PATCH|DELETE)$" {
  url.access-deny = ("")
}

Comment: I think you've got a typo in the regex there - "[" instead of "|".
Comment: @Sam That's right, but I don't know how to send a custom HTTP code. Maybe with [mod_setenv](http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModSetEnv).
Comment: @nickgrim good catch ! thx
Comment: Works a treat in blocking so have accepted, but it does not return a 405, but a 403 instead (I guess who cares at the end of the day).
Comment: @j0k ah didn't know about that module, will give it a go. Thanks for the help!


Run a ASP.Net webpage from IIS in a machine without Visual Studio

Question: this may be a simple question but until now I always created a web site with Visual Studio and ran it via Visual Studio. But now I have to run it in a computer that doesn't have Visual Studio. I'm guessing I have to install IIS but I don't know how to run that website. How can I do it? Thank you.
Answer: You'll need to install IIS on that machine, then set the folder with the site in it as a Virtual Directory. IIS will handle everything else from there.
Assuming you set everything up correctly, you should be able to access the site like so:
http://localhost/whateveryourfolderis
Comment: To add to Steve's answer, if you need help installing IIS this link should help: http://technet.microsoft.com/en-us/library/cc782498%28WS.10%29.aspx
Answer: ASP.NET and IIS Configuration
Answer: you have to install iis 7 or higher version for run .net application if you use windows xp so you have to upgrade it with Service Pack 3 it provide iis 7 for .net application
after install IIS put you application in INITPUB dir in C: run in browser with http://localhost:80/applicationname
it working
Comment: To expand on user653116's answer, what version of IIS you need to install depends on the version of .Net that your application was written in. If it is .Net 3.5 or earlier, then you would be okay with installing II6, otherwise, you will need IIS7.

Just wanted to clarify those requirements. All that said, installing IIS7 is probably the wiser idea.


generate the empty field value

Question: first field
  <input type="text" name="opt_name[]" value="d / ">

    <input type="text" name="opt_sku[]" class="a" size="3">

second field
<input type="text" name="opt_name[]" value="cv / ">

<input type="text" name="opt_sku[]" class="a" size="3">

javascript

Question : How can i generate the empty field value based on beside value when i click the generate button?
Comment: As of jQuery 1.7, the `.live()` method is deprecated. Use `.on()` to attach event handlers. Users of older versions of jQuery should use `.delegate()` in preference to `.live()`.
Answer:

$('#btnGenerateSku').on('click', function() {
    var empty = 0;
    $('.a').each(function(){
       if (this.value == "") {
           empty++;

          $(this).val('test');
       }

    })

   alert(empty + ' SKU field generated ');
});

<input type="text" name="opt_name[]" value="d / ">

    <input type="text" name="opt_sku[]" class="a" size="3">

<input type="text" name="opt_name[]" value="cv / ">

<input type="text" name="opt_sku[]" class="a" size="3">

<button id="btnGenerateSku">Generate</button>
Comment: the second text box will be "text", i want to become first value. For example, first text box is  "d" when generate second box will become "d".Third box is "cv" when generate second box will become "cv".

generate the empty field value


need help setting up smtp from localhost

Question: I'm running XP Pro, and I have a XAMPP setup.  I'm learning Zend Framework, and I'm trying to use Zend_Mail.  I guess I need to setup or configure my SMTP on my machine for this to work?
Can anyone tell me how to do this and most importantly how to test this to know if it's working (maybe an easier way than zend_mail because I'm a newbie there too and I may be doing other things wrong there).
So in short, I just want to set up SMTP and mail from localhost just to be sure things are set up correctly.
PS: so far, I have turned on (installed) the IIS from the windows components.
Answer: It'll likely be easier to use an external SMTP server such as the one provided by your ISP.
See the Zend Framework Manual for instructions on using the smtp transport.
Comment: Yes, I've been reading the horrible manual for days...
Comment: I'm going to mark your answer correct as a combination of my answer and your answer has led me to a solution.
Answer: I found this and it got me up and running and even had a simple test:
http://roshanbh.com.np/2007/12/sending-e-mail-from-localhost-in-php-in-windows-environment.html
Turns out that the Windows component IIS seems unneeded here.  I had to disable it for my apache server to connect.


f:ajax not working as expected for h:selectOneRadio inside ui:repeat

Question: I am rendering a table with , which has a radio button.
i.e. , on selection of radioButton, need to re-render the whole form.
but which is not working.
Here is my code:
<h:form id="summaryForm" prependId="false">

  <ui:repeat var="switchRow" value="#{designBean.switchReport.rowList}" varStatus="rowStatus">

     <h:selectOneRadio id="switchTypeSelectionId"
                  name="switchTypeSelection"
              styleClass="choices"
              onclick="selectRadioButton(this);"
              value="#{designBean.designTool.switchProduct}">
      <f:selectItem itemValue="#{switchRow.rowId}"/>
      <f:ajax event="click" execute="@this" render="@form" listener="#{designBean.showIGBTDetails}"/>
    </h:selectOneRadio>

    <ui:repeat var="switchColValue" value="#{switchRow.rowValues}">

                    <h:outputText value="#{switchColValue}" />

    </ui:repeat>

     </ui:repeat>

</h:form>

Comment: Okay, the EL syntax error is thus not the cause of your concrete problem. Now we can finally advance :) This problem is recognizable as a bug in an older Mojarra version. Are you using Mojarra? If so, which version? If it's rather old (more than ~6 months), have you tried upgrading it?
Comment: Your `` attribute contains a syntax error in the EL expression. Is this also present in your real code?
Answer: I don't know if a click event is what you need in this case. Try using onchange. I remember something that mentioned this in the past. However it wont fire if you click multiple times on the already selected radio item.
Also, did you try using the id of the form instead @form? Like render="summaryForm".
Comment: When using the id of the form instead @form,
Like what you suggested render="summaryForm",
which is giving me the following exception.
when i looked at view source, generated html the component id is same summaryForm.
SEVERE: javax.faces.FacesException:  contains an unknown id 'semiSelectionForm' - cannot locate it in the context of the component switchTypeSelectionId
Comment: Well, this sounds strange. But i forgot something: Maybe it's better to use a colon, render=":summaryForm". JSF is using a colon as ID seperator, (consider a form with id foo nested in something with the id bar, you could access it with foo:bar or :foo:bar. I am no expert here when to use which but it might be worth a try. But, to be honest, I am kind of stuck here. Maybe there are restrictions using this stuff in a  element.
Answer: After some research, i found a simple way to achieve this,
Here is my answer,
instead of using h:selectOneRadio, changed it to HTML  and wrapped it in a , now the click on panelGrid component calling the ajax function/listener.
<h:form id="summaryForm" prependId="false">

  <ui:repeat var="switchRow" value="#{designBean.switchReport.rowList}" varStatus="rowStatus">

          <h:panelGrid id="switchSelectionId" styleClass="choices">
                <input type="radio" name="switchTypeSelection" value="#{switchRow.rowId}" />
                <f:ajax event="click" execute="@this" render="@form" listener="#{designBean.showIGBTDetails}"/>
          </h:panelGrid>

      <ui:repeat var="switchColValue" value="#{switchRow.rowValues}">

             <h:outputText value="#{switchColValue}" />

      </ui:repeat>

     </ui:repeat>

</h:form>


Twig debugging comments stuck on

Question: I'm working on a Drupal 10 upgrade and have run into a strange problem ... the contextual edit buttons on my site will not hide. They should be hidden until you mouse over a region/block/whatever, but mine are currently all on all the time.
I THINK this might be due to the fact that, for some reason, the Twig debugging comments around them seems to be stuck on (for lack of a better term).

  <button class="trigger focusable" type="button" aria-pressed="false">Open  configuration options</button>

Configure block

Remove block

Also, if I open that links.html.twig template and just completely empty it, nothing changes.
I know to normally disable and enable the twig debugging in services.yml and that works for the rest of the page code in terms of showing/hiding the debug info, but no matter what I do, this one template will not change.
Here is my services.yml file...
parameters:
  session.storage.options:
    gc_probability: 1
    gc_divisor: 100
    gc_maxlifetime: 200000
    cookie_lifetime: 0
  twig.config:
    debug: false
    auto_reload: null
  cache: true:
  renderer.config:
    auto_placeholder_conditions:
      max-age: 0
      contexts: ['session', 'user']
      tags: []
  http.response.debug_cacheability_headers: false
  factory.keyvalue:
    {}
  factory.keyvalue.expirable:
    {}
  filter_protocols:
    - http
    - https
    - ftp
    - news
    - nntp
    - tel
    - telnet
    - mailto
    - irc
    - ssh
    - sftp
    - webcal
    - rtsp
  cors.config:
    enabled: false
    allowedHeaders: []
    allowedMethods: []
    allowedOrigins: ['*']
    exposedHeaders: false
    maxAge: false
    supportsCredentials: false

How can I fix this? I'm almost at a loss for how to even ask this question. Thanks!
Answer: Disable Twig debugging in the admin UI.
Comment: Already done. I actually didn't know that was there until today ... been vim editing my services.yml file.
Comment: The global settings, whether in admin UI or services.yml, don't answer why it only affects one template. It could be connected to how the contextual module loads the links, which is very different from the rest of the page content.
Answer: So, it turns out this was something with Chrome. I still can't explain it ... I set debug on and off multiple times, rebooted the server and computer, etc. and it still happens on my Chrome. But I tried it in a different browser and in Chrome incognito mode and the problem wasn't there. I even tried a hard reload in Chrome.
So, thanks for everyone's input, but at this point I'm moving on and writing this off as some glitch in Chrome. Hopefully, it goes away soon.

Twig debugging comments stuck on


how to get id the same input value without refresh

Question: i have input type and button, i need when choose item by click next image by ajax i will get id for this item and put it into input type, and i wont to print this item by using this
<input name="print" type="submit" id="print" value="Print" class="css3buttonblue"  onclick="window.open('BillsPrint.php?bills_ID=<?php echo $_POST['bills_ID']?>', '_blank')" />

the problem here i canot get id value from input type to 'BillsPrint.php?bills_ID=<?php echo $_POST['bills_ID']?>'
how can i put the id on this link BillsPrint.php?bills_ID=<?php echo $_POST['bills_ID']?> without refresh page
Answer: Why not just use this to access the element itself.
You're using JavaScript anyways, so this should be safe:
'BillsPrint.php?bills_ID=<?php echo $_POST['bills_ID']?>&input_id=' + this.id

Comment: are you mean `` i try put id not insert
Comment: ``


Zeros of the derivative of a polynomial.

Question: If all the zeros of a polynomial $f: \mathbb{C} \rightarrow \mathbb{C}$ are real, does this tell us that the zeros of the derivative are also all real valued? i.e, if $f(z) = 0$ only has real roots, will this imply that $f'(z)=0$ only has real roots? Assume that $f$ is monic.
It seems like this should be a really basic question, but attempts at a counter example have proved futile so far.
One thing I have been trying to use is the fact that the coefficients of $f'$ can be written in terms of the symmetric functions on the zeros of $f$ itself.
Answer: this should be true. w.l.o.g let the polynomial $f$ be a monic polynomial. First, if a polynomial has only real roots, its coefficients are also only real, hence you can view the polynomial as $\mathbb{R} \to \mathbb{R}$.
in the real case, this is true: if $f$ has double zeros , $f'$ has a zero there, and the other zeroes of $f'$ must lie somewhere in between, because there need to be a local maximum or minimum somewhere.
So we have exactly $n-1$ zeros of $f'$, where n is the number of zeros of $f$
Comment: The polynomial could have a leading coefficient which is complex. Maybe you could assume it is monic.
Comment: thx @Andrew , i made an edit
Answer: Yes: first, note that the derivative of a polynomial $p$ of degree $n$ has degree $n-1$.Let the roots of $p$ be $\alpha_1, \dotsc, \alpha_n$ in increasing order, not necessarily distinct. Further, the factor theorem shows that
$$ p(x) = a \prod_k (x-\alpha_k), $$
so $p(x)/a$ is a real-valued polynomial. Hence we may take $p: \mathbb{R} \to \mathbb{R}$ with no loss of generality.
Suppose first that all of the roots of $p$ are distinct. Now apply Rolle's theorem to the intervals $[\alpha_i,\alpha_{i+1}]$. This gives you $n-1$ roots, which must be all of them.
The next problem is what happens if two of the roots, $\alpha_k$, $\alpha_{k+1}$ coincide. Then it is easy to show that $p'(\alpha_k)=0$, by, say, formally differentiating the product. You can then use induction to examine the case where $k$ roots coincide to finish the proof.


For a Multi-arm Bandits set-up, does the Signal to Noise Ratio have any meaning there?

Question: Suppose that we have a Multi-arm Bandit set-up with $K = 5$ bandits. Each bandit has a reward distribution of:
$$
X_i \sim Bern(p_i), \ \ \  i \in \{1, \ldots, 5\}
$$
In literature about MABs, authors speak of a signal-to-noise ratio. I was wondering if there was a way to characterize the set-up in terms of a signal-to-noise ratio and what it might mean? Thanks!
Answer: The strategic trade-off in multi-arm bandit problems: In multi-arm bandit problems the gambler plays one "bandit" each round and attempts to maximise his total expected return over a given number of rounds.  In each round of play (except the last), this involves a strategic trade-off by the gambler between two objectives:

Immediate rewards: In each round he would like to choose a distribution that gives him a high expected reward on this round, which entails a preference for distributions he (presently) infers to have a high mean reward;
Future rewards (affected by information gain): On the other hand, he wants to refine his knowledge of the true expected rewards by gaining more information on the distributions (especially those that he has not played as much as others), so that he can improve his choices in future rounds.

The relative importance of these two things will determine the trade-off, and this relative importance is affected by a number of factors.  For example, if there is only a small number of remaining rounds in the problem then inference for future trials is relatively less valuable, whereas if there is a large number of remaining rounds then inference for future rewards is relatively more valuable.
As to the "signal-to-noise" ratio (i.e., the variability of the rewards in each distribution), this affects the speed at which the gambler is able to gain reliable information about the expected gain from each distribution.  If the signal-to-noise ratio is high (i.e., there is low variability in the rewards) then the gambler gains reliable information on the expected rewards with less uses of that distribution.  If the signal-to-noise ratio is low (i.e., there is high variability in the rewards) then the gambler needs more uses of that distribution to gain reliable information on the expected rewards.

Quantifying this strategic trade-off: For problems involving a finite number of rounds, optimal decisions can be solve via backwards induction using Bayesian decision theory.  Without loss of generality, we can consider a general problem with $N$ rounds of play using $K$ reward distributions $F_1, ..., F_K$ with respective means $\mu_1, ..., \mu_K$.
We will denote the choice of reward distribution in a round by the action variable $a \in \{ 1, ..., K \}$ and we note that this is allowed to depend on observations in previous rounds.  We denote the corresponding (random) gains by $G_a$, where we have $G_a \sim F_{a}$.
Assume that when there are $n$ remaining rounds, the gambler has some belief function $\pi_n$ which is a distribution over the vector of reward distributions (or their parameters if this is a parametric problem).  This function represents the gambler's belief about the reward distributions with $n$ remaining rounds, and it obeys the rules of Bayesian updating.  (This is a prior distribution if $n = N$, or a posterior distribution based on the previous rounds of play if $n < N$.  We will depart from standard Bayesian notation for this function by using the subscript to denote the number of remaining rounds, rather than the number of rounds that have already been played.)  Under this belief we denote the corresponding predictive distributions for the rewards as $\tilde{F}_{n,1}, ..., \tilde{F}_{n,K}$.
Consider the situation faced by the gambler with present belief $\pi_n$ facing $n$ remaining rounds of play.  We will denote the expected future gains under present action $a$ by $g_n (a |\pi_n)$ and denote the expected future gains under optimal play by $\upsilon_n (\pi_n) \equiv \max_a g_n (a |\pi_n)$.  Using a simple backward induction argument, we can express the optimisation problem recursively from the last round of play.  Under optimal play these functions must satisfy the following recurrence relation:
$$\begin{equation} \begin{aligned}
g_n (a |\pi_n)
&= \mathbb{E}(G_a | \pi_n) + \mathbb{E} (\upsilon_{n-1} (\pi_{n-1}(a, G_a)) | G_a \sim \tilde{F}_{n,a} ) \\[6pt]
&= \underbrace{\mathbb{E}(G_a | \pi_n)}_{\text{Current}} + \underbrace{\upsilon_{n-1} (\pi_{n})}_{\text{Future}} + \underbrace{\mathbb{E} (\upsilon_{n-1} (\pi_{n-1}(a, G_a)) - \upsilon_{n-1} (\pi_{n}) | G_a \sim \tilde{F}_{n,a} )}_{\text{Value of Information Gain}}
\end{aligned} \end{equation}$$
where $\pi_{n-1}$ is the updated posterior distribution given the additional observation $G_a$ for the reward from distribution $a$ (which depends on the chosen action $a$ and the resulting random variable $G_a$), and $\tilde{F}_{n,a}$ is the predictive distribution for $G_a$ using the distribution $\pi_n$.  This recursive formula decomposes the expected future gain under a particular action as the sum of: (1) the expected gain in the current round; (2) the expected gain in future rounds under our current information $\pi_{n}$; (3) the gain in expected gains in future rounds due to gaining information from the present round (i.e., the value of gaining this additional information and changing our beliefs from $\pi_{n}$ to $\pi_{n-1}$).
In the case where $n = 1$ (i.e., we are at the last round) we have $\upsilon_0 = 0$ so there is no longer any gain in future rounds, or any gain from further information.  By combining this recursive optimisation rule with the rules for Bayesian updating of the belief function, we can solve this problem using backwards induction, by first finding the optimal action in the final round (as a function of the belief at this time) and then solving recursively to find the optimal action in each prior round (each one being a function of the belief at that time).

The relevance of reward variability ("signal-to-noise"): The variability of the reward affects how well the gambler can make inferences about the mean-reward in each reward distribution.  This affects the value of additional information (the last term in the recursive value decomposition).  If the variability of a reward distribution is low, this means that the gambler will learn rapidly about the distribution by only observing a few values, which means that the information gain starts off high, and then rapidly decreases.  On the other hand, if the variability of a reward distribution is high, this means that the gamble will learn slowly about the distribution and will require a lot of observations to make good inferences, which means that the information gain is slower but does not decrease as rapidly.
Given a prior belief $\pi_N$ and a model used by the gambler, it is possible to find the posterior beliefs in each round of play (as a function of the chosen actions and observations in previous rounds), and from this, it is possible to obtain an expression for the term quantifying the value of the information gain from each allowable action.  This is complicated, since it involves the interplay of Bayesian updating and backward induction techniques for decision theory.  Nonetheless, if it is successfully applied, then the "value of information" term will be a function of the chosen action $a$ and the present belief $\pi_n$ (which is itself a function of the prior belief $\pi_N$ and all previous actions and observations).  Since the reward variability affects the posterior updating, any parameters describing this variability should show up as terms in this "value of information" function.

How to model the effect of reward variability: If you would like to characterise this kind of problem in terms of the "signal-to-noise" ratios for each reward (which I take to be some measure of its variability) then you would need to formulate a complete model, solve the resulting posterior form and the optimal strategy, and then use these to calculate the "value of information" function as a function of your "signal-to-noise" measures.
In the model you pose in your question you are using Bernoulli rewards (which is a one parameter distribution) so the mean reward of each distribution fixes its variance.  This one-parameter formulation means that your model cannot really accommodate variable signal-to-noise very well.  If you would like to explore this issue, I suggest you change to some simple two-parameter distribution, where the scale parameter is a known control variable.  A simple example would be to use normally distributed rewards with unknown mean and known variance parameters (with these variance parameters being your measures of reward variability).  You could then formulate a strategy using a simple conjugate prior and solve the resulting model to get the "value of information" function.  You could then have a look at how this function is affected by changes in the known variance parameters.
Comment: In the case of a normally distributed rewards scenario, for the Signal to Noise ratio, I put the square root of $\sigma^2$ in the denominator for the Noise, do you have a suggestion for what to put in the Signal part of the numerator? Would it be the average of the means?
Comment: Using the normal model, I would suggest you take your gains to be normal with unknown means and known variances.  Solving this will give results that depend on these variances, but you might not get a term that exactly matches a "signal-to-noise" ratio.  Still, you should find that the optimisation depends on the means and variances in a similar way.  Just allow the derivation of the optimal solution to unfold and see what you get.


Trouble when deleting emails from Outlook with Python

Question: When using a generator to iterate through emails in Outlook i am having some trouble deleting them. If i call delete on the message the generator will "jump" over the next item so it will only process half of the emails in my Inbox.
for message in scanner.scan_emails():
            message.Delete()
            deleted_counter += 1

As a workaround i save all the messages in a list then loop through them:
    for message in emails_to_delete_list:
            message.Delete()
Is there a better way of doing this ?
Answer: For windows you can use win32com (pip install pypiwin32). 6 is you main "Inbox".
  Iterate through the folders and each email and call Delete.
import time
import win32com.client

def email_deleter():

    folders = ["BORK", "FOO", "SPAM", "EGGS"]

    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

    for folder in folders:
        emails = outlook.GetDefaultFolder(6).Folders[folder]
        for email in emails.Items:
            email.Delete()

if __name__ == "__main__":

    for i in range(10):
        time.sleep(0.1)
        email_deleter()

Answer: See VB reference use backward for loop:
items = outlookObject.Items
for i in range(items.Count, 0, -1):
    items.Item(i).Delete()


Calculating the confidence interval that with proability $x$, the population mean lies within $\pm D$ of the sample mean $m$, when $N > 100$

Question: Suppose one has a series of $N$ ($N > 100$) data points sampled from a population with unknown distribution. $\mu$, the population mean, and $\sigma^2$, the population variance, are thus both unknown.
I'd like to find the interval $D$ around the sample mean $m$, such that $P(m - D < \mu < m + D) = x$. In other words, the probability that $\mu$ lies within distance $D$ of $m$ is $x$.
Since I do not know the true population variance, I only have an estimate of it via the sample variance, which I call $s^2$. This means that I only have an estimate of the standard error $s/\sqrt{N}$.
This would mean that one would have to use the Student t-distribution to determine $D$. However, Wikipedia has the following comment:

Note: The Student's probability distribution is approximated well by the Gaussian distribution when the sample size is over 100. For such samples one can use the latter distribution, which is much simpler.

Does this mean that in my use case, I can effectively assume that $s^2$ is an excellent approximation of $\sigma^2$, and thus proceed with the steps one would use if they knew $\sigma^2$ in order to determine the confidence interval?
Answer: If $\sigma$ is known, you use Gaussian distribution. When it is unknown, to account for the uncertainty over possible $\sigma$'s, you use student-t distribution. So, the issue is the unknown variance. When the student-t distribution is well approximated by Gaussian with large samples, the problem with uncertainty over $\sigma$ decreases and the two distributions become closer. Of course, this means better approximation to $\sigma$, however it's not an excellent approximation (e.g. you wouldn't even still have excellent approximation to the mean, $N=100$ is quite small). The essence here is the uncertainty over $\sigma$ decreases to a level such that it doesn't affect the distribution of the mean significantly.
Comment: Alright, what if I have $N = 18000$, which is the smallest data set I actually have?
Comment: With $N>100$, you can use gaussian distribution instead of student-t as noted in wikipedia. For the excellent approximation, a mathematical definition of excellence should be made.


Find roots of $x^4 + 4x^3 - 25x^2 - 16x + 84$

Question: I'm not quite sure how to approach this, how are you supposed to quickly factor a 4th degree polynomial? For $x^4 + 4x^3 - 25x^2 - 16x + 84$ it's factored into $(x-3)(x-2)(x+2)(x+7)$ which like I said, I have no idea how to approach. Would really appreciate some help, thanks in advance!
Comment: Check out the [rational root theorem](https://en.wikipedia.org/wiki/Rational_root_theorem)
Comment: @JakeDrone Works for polynomials of all degree.
Comment: Thanks, I thought rational root theorem only works for roots up to 3th degree polynomials  for some reason
Answer: First, apply Descartes' Rule of signs.  Now we know this polynomial has either two or zero positive real roots and either two or zero negative roots.  (How does this help?  If we happen to have a long list of candidate roots and, while checking through this list, we find two positive roots, we can immediately discard all remaining positive candidates.)
Then we apply the rational root theorem.  This tells us that the only rational candidate roots are a divisor of $84$ over a divisor of $1$:
$$  \{-84, -42, -26, -21, -14, -12, -7, -6, -4, -3, -2, -1, 1, 2, 3, 4, 6, 7, 12, 14, 21, 26, 42, 84\}  \text{.}  $$
We see the coefficients $4$, $-25$, and $-16$, which are sums of products of roots.  These are "small", so we should probably start in the middle of the list and work our way out.
\begin{align*}
x&  &&|&  &x^4 + 4x^3 - 25x^2 - 16x + 84  \\ \hline
1&  &&|&  &1+4-25-16+84 > 0  \\
2&  &&|&  &16+32-100-32+84 = 0 &&\checkmark \\
3&  &&|&  &81 + 108 - 225 - 144 + 84 = 0  &&\checkmark
\end{align*}
Having found two real roots, any further real roots are negative.  Continuing the table, starting from $-1$, you will find $-2$ and then $-7$.
But we can go a little faster.  By synthetic division (or long division), once we have the root $x = 2$, we can reduce the polynomial.
$$  x^4 + 4x^3 - 25x^2 - 16x + 84 = (x-2)(x^3 + 6x^2 - 13x - 42)  $$
So any root of $x^3 + 6x^2 - 13x - 42$ is also a root of the original polynomial.  By the rule of signs, this has one positive real root and two or zero negative real roots.  Any rational root is a divisor of $42$ divided by a divisor of $1$.  This reduces the previous list of candidate roots to (excluding $1$, the one candidate we definitely verified is not a root)
$$  \{ -42, -21, -14, -7, -6, -3, -2, -1, 2, 3, 6, 7, 14, 21, 42\}  \text{.}  $$
Testing $2$ in this reduced polynomial, we find $2$ is not a repeated root.  And then we find $3$ is a root:
$$  3^3 + 6\cdot 3^2 - 13\cdot 3 - 42 = 0  \text{.}  $$
That's the last possible positive root and we are left with
$$ \frac{x^3 + 6x^2 - 13x - 42}{x-3} = x^2 + 9x+14  \text{.}  $$
Of course, this is quadratic, so there is no reason to avoid directly applying the quadratic formula...  Alternatively, we compute the discriminant : $9^2 - 4 \cdot 14 = 25$, so the two roots differ by $\sqrt{25} = 5$.  (Since the discriminant is a square, we know the remaining two roots are rational, hence are on our list.)  Looking at the negatives on our list, the only pairs that differ by $5$ are $\{-1, -6\}$ and $\{-2, -7\}$.  Checking $-1$, we find that $-1$ is not a root, so $-2$ and $-7$ are the final two roots.
Answer: You can use synthetic division in $$p(x)=x^{4}+4x^{3}-25x^{2}-16x+84.$$
To do this, notice that the divisors of:

$a=1$: $\{\pm1\}$.
$b=84$: $\{\pm 1, \pm 2, \pm 3, \pm 4, \pm 6, \pm 7, \pm 12, \pm 14, \pm 28, \pm 42, \pm 84\}$.

Then the synthetic division gives us that $$p(x)=x^{4}+4x^{3}-25x^{2}-16x+84=(x-3)(x-2)(x+2)(x+7).$$
Comment: Did you need to check every single root to see if that works out?
Comment: The synthetic division method tells you what the possible roots might be. Do you know the method to do synthetic division?


Glissando during arpeggiando on string instruments

Question: (Related to this question for the case without glissando)

Consider following example of an arpeggiando on the four open strings of the cello (but the question also holds for violin or viola).

Is it now possible to add fingers on the neck and realize an upwards glissando on all four notes at the same time while repeating the figure (i.e. same position for each of the four strings)? Or should one use different positions for each string to be able to shift the hand?
Also, how far can one shift the figure upwards?
Comment: Hm. As I think more about this,: Do you want a true glissando? As in, the left hand is constantly moving? If so, no matter how rapidly the bow crosses the strings, there will be some upward shifting during each iteration of the pattern. Which means the notes won't be precise and neither will the intervals. If this is your goal, not precise intonation but just a pattern generally moving upward, then many of the warnings about intonation will be moot.
Answer: The answer is sort of "Yes, but."

The general principle is sound: You can take a four-string chord and "translate" it up the fingerboard in parallel motion. And sure, the fact that you're rolling the bow back and forth across the strings doesn't affect that.
One warning: What's shown here is a chord made up entirely of fifths. Once you get beyond open strings, this would mean a "barre" technique in which one finger is supposed to stop all four strings. This is very challenging to do with good intonation on fretless instruments. It would be much easier if the chord let the player use a different finger on each string.
Be aware that as you go up the fingerboard, distances shrink. I.e. the actual string length of a whole step becomes shorter the higher you go. This means that the player will not simply slide their hand upward exactly in parallel, but will have to adjust finger distances as they go. A skilled player will do this automatically, but be aware that it presents a challenge for intermediate players (and beginners probably don't move beyond first position anyway). Be aware that at the extreme end of the fingerboard, you might even have notes so "crowded" together that standard fingerings become problematic.

"How far can you shift the figure upwards?" Well, pretty much until you hit the same limits of "how high can you play on a given string." At some point the tone quality just becomes unpleasant, or the technical demand becomes greater than your intended players. But you could go right to the end of the fingerboard or maybe a couple of notes beyond!
Comment: Also doing a four string glissando might be a bit tricky. You've got a lot of pressure with four fingers and doing this with decent intonation should be quite a challenge.


7 white balls and 3 black balls in a box. You take out in sequence 3 balls at random without replacement. Probability that all 3 balls are black?

Question: What i did was say that the probability the first ball is black is 3/10, then since we removed one the probability the second is black is 2/9 and third is ⅛. So then the probability all three are black is 3/10 + 2/9 + ⅛?
Comment: Suppose that you had a box with 10 black balls.  If you choose 3 balls, it is clear that the probability they are all black is 1.  But your method gives $10/10+9/9+8/8=3.$
Comment: You have to multiply the probabilities, not add them.
Answer: Hint.  If you did the same thing for white balls you would get
$$\frac{7}{10}+\frac69+\frac58\ ,$$
which cannot be right as it is bigger than $1$.  Can you see how you have to amend this answer, and your answer too?
Comment: is that why then it should be (7/10)(6/9)(⅝) instead of adding them?
Comment: @user180069 That's right.  As you are drawing one ball **and** then a second **and** then a third, you have to multiply the probabilities.  If you were performing one action **or** another then (under suitable conditions) you would add the probabilities.
Comment: does that mean that the probabilities are dependent?
Comment: In this problem it is a case of conditional probabilities: the factor $2/9$ is the probability that the second draw is black, **given** that the first is black, and we have the formula$$P(A\ \hbox{and}\ B)=P(A)\,P(B\ \hbox{given}\ A)\ .$$It is possible that you have not yet been formally introduced to conditional probabilities.
Comment: @user180069 You have asked 20 questions and never accepted an answer.  Have you never found an answer useful?
Answer: Here is a rule of thumb you can use for questions like these:
And means multiply, Or means add.
In the context of your problem, you need to know the probability that ball 1 is black, AND ball 2 is black, AND ball three is black. Hence, you multiply your quantities.
If you have a question like "What is the probability that you pull out a black ball or a white ball?" Then your answer would be $$\frac{3}{10}+\frac{7}{10}$$
Comment: Thank you that helps a lot


Beginning on the Dulzaina

Question: I'm keen to receive advice or tips on how one can start out with the Spanish wind instrument the Dulzaina (in Catalan it is called the Dolçaina).
Dulzaina on Wikipedia
Since we're not in Spain we don't have access to local teachers. Given it's supposed similarity to other instruments (listed here) would it be feasible to work of some of the resources for similar instruments?
So far, my wife who has a lot of (not recent) experience with the clarinet struggles with it a bit, whereas my ten-year-old daughter plays it somewhat instinctively, just like she plays a recorder and with a similar level of success.
Answer: Since it is a double reed, single reed technique like the clarinet will not help you. If you can't find an instructor specifically for the Dulzaina, you could look for other similar double reed instrument teachers to get you started on the reed technique.
The Zurna, Bombard, or an Oboe teacher could start you on the reed technique. Depending on the music stores in your area you can probably rent an oboe for a short time to get started.  Instrument rentals are available through the internet now as well.
As you pointed out about your daughter, picking up a recorder or other similar instrument will get you started with fingering. You could look at the bagpipe practice chanter or the penny whistle for a fairly simple start. While not always directly translatable, fingering and reed technique should be similar enough to get you started in the right direction.

Beginning on the Dulzaina


Unable to authenticate MediaWiki (on LAMP/Ubuntu) users using AD (on Windows Server 2012 R2) via LDAP

Question: I am working in an AD domain with a single DC running Windows Server 2012 R2. On the domain's network (though not formally domain-joined) is a LAMP web server running Ubuntu Server 14.04.3 LTS. All machines are able to reach one another by both IP address and DNS record, and the LAMP stack is (as far as I can tell) appropriately configured; HTTP requests are served as expected.
The aim is to set up an instance of MediaWiki on the LAMP server. Moreover, MediaWiki should - using Ryan Lane's excellent extension LdapAuthenticate - contact the AD DC to authenticate user logins.
I have tried to follow setup instructions as closely to the book as possible. LAMP installation is mostly taken care of by the Ubuntu Server installer, and I additionally install via apt-get the packages php5-intl php5-gd texlive php5-xcache imagemagick mediawiki mediawiki-math and their dependencies.
I next uncomment the #Alias... line in /etc/mediawiki/apache.conf, run the commands a2enconf mediawiki and php5enmod mycrypt, and lastly install the LdapAuthenticate MediaWiki extension according to tutorials at the author's website.
Appended to my /etc/mediawiki/LocalSettings.php are:
ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);

require_once("$IP/extensions/LdapAuthentication/LdapAuthentication.php");

$wgLDAPDebug = 3;
$wgDebugLogGroups["ldap"] = "/tmp/debug.log";

$wgAuth = new LdapAuthenticationsPlugin();

$wgLDAPDomainNames = array("MYDOMAIN");
$wgLDAPServerNames = array("MYDOMAIN" => "addc.local.domain.com");
$wgLDAPSearchStrings = array("MYDOMAIN" => "firstname.lastname@example.com");

$wgLDAPEncryptionType = array("MYDOMAIN" => "tls");

I next add the AD DC's self-signed CA certificate to /etc/ssl/certs on the LAMP server, run c_rehash, and restart everything.
At this point I am able to get into MediaWiki and navigate to the login form no problem. The login form shows MYDOMAIN, and PHP reports no errors - the LdapAuthentication plugin looks good to go.
When I try to login using an AD credential set, however, MediaWiki reports a wrong password. A PHP error on the web page reports that PHP was unable to start TLS (Warning: ldap_start_tls(): Unable to start TLS: Connect error in...), and this same message is reconfirmed by the LdapAuthentication plugin's debug log which I set earlier to /tmp/debug.log.
Looking now at the AD DC, I note the following event in the system log:
Error from Schannel, Event ID 36874
An TLS 1.2 connection request was received from a remote client application, but none of the cipher suites supported by the client application are supported by the server. The SSL connection request has failed.

This error coincides with repeated attempts to authenticate user logins on MediaWiki with AD via LDAP.
I don't know enough about managing cipher suites to approach resolving this issue. Moreover, days upon days of Google searching hasn't yielded me any productive results. Could someone point me in the right direction?
Answer: I don't know about MediaWiki - but I have DokuWiki doing what you are looking for. I use the Apache / Kerberos integration to get things going - perhaps you could do that too. To get going, you need to:

Generate a Kerberos keytab file. This is sort of a pre shared credentials set needed for Kerberos trusts. Do this by issuing
ktpass -princ HTTP/<service host name>@<DOMAIN NAME> -mapuser <security principal> -crypto RC4-HMAC-NT -ptype KRB5_NT_PRINCIPAL -pass <password> -out <filename>.keytab

on your AD server.
If your Apache is on a Linux box (mine is), install the libpam-krb5 package (or equivalent on your system). Then, edit your /etc/krb5.conf:
 [libdefaults]
 default_realm = <YOUR DOMAIN>

Modify the Directory section of your apache.conf that applies to your Media Wiki setup. Add Kerberos integration like this:
# Kerberos Auth
<Directory>
    .... # Your Media Wiki stuff here
    AuthType Kerberos
    KrbAuthRealms <YOUR DOMAIN>
    KrbServiceName HTTP/<service hos name>
    Krb5Keytab /etc/apache2/<filename>.keytab
    KrbMethodNegotiate on
    KrbMethodK5Passwd on
    require valid-user
</Directory>

Once you have this, browsers will be able to sign in local users SSO style (if you configure browsers accordingly). If they are not local users, they will get a basic login prompt that accepts AD credentials.
This setup works nicely for me using the DokuWiki authad plug-in. Whether it adapts to Media Wiki, I don't know, but the Apache / Kerberos Stuff is really nice for a lot of things. Hope it helps!
Comment: Thank you for the suggestion - it's always good to hear how people are solving these problems in other labs! Unfortunately we're bound to MediaWiki, and I'd very much like to have the MediaWiki-integrated account features (such as who edited what and when).
Answer: After hacking at the LdapAuthentication (version 2.0d) MediaWiki extension and introducing my own break points, I was able to track down the problem. It turns out that binding to my AD server over SSL only works following a call to PHP's ldap_connect() that looks like,
ldap_connect("myserver.com", 636);

rather than,
ldap_connect("ldaps://myserver.com:636");

upon which LdapAuthenticate insists.
I note also that LdapAuthenticate wraps PHP's ldap_connect() in the following way,
public static function ldap_connect( $hostname=null, $port=389 ) {
    wfSuppressWarnings();
    $ret = ldap_connect( $hostname, $port );
    wfRestoreWarnings();
    return $ret;
}

but then only ever passes in $hostname, as a URI formatted as one of,
ldapi://myserver.com:port
ldap://myserver.com:port
ldaps://myserver.com:port

leaving $port to its default value of 389. This means that, say you're attempting to bind over SSL, the actual call to PHP's ldap_connect() looks like this,
ldap_connect("ldaps://myserver.com:636", 389);

which must be causing some problems!
I think this might be a bug in LdapAuthenticate, but then again it might just be me totally misinterpreting the PHP (it's been a while). In any case I managed to get the authentication working by hacking LdapAuthenticate to force a call to,
ldap_connect("myserver.com", 636);

This does, however, leave one unanswered question. Why does my AD server happily accept binds to myserver.com, but not to ldaps://myserver.com? (I have confirmed that this is the case using ldp.exe on Windows). I suspect that this is a DNS issue, since myserver.com is actually handled according to a record on my local DNS server (on which I may have indeed missed a trick!) I will ask another question elsewhere!


Co-domain of a sheaf

Question: We know that sheaves take open sets in some topology to values in some category. I want to know if it's possible for a sheaf $\mathcal{F}$ to take values in some category $\mathcal{C}$ which has no products. I am asking this because I want to do the standard problem about the gluability of sheaves. It seems to me that it is just about taking products.
Answer: The definition of a sheaf works in any category. A functor $F : \mathsf{Open}(X)^{op} \to \mathcal{C}$ is a sheaf iff for every "test" object $T \in \mathcal{C}$ the functor $\hom(T,F(-)) : \mathsf{Open}(X)^{op} \to \mathsf{Set}$ is a sheaf in the classical sense.
In order to glue $\mathcal{C}$-valued sheaves, we need limits in $\mathcal{C}$.
Comment: I see what you mean about limits Martin. By doing the obvious thing to the sheaves I want to glue, I can get a presheaf. By taking direct limits (sheafifying), I can get the sheaf I want. Thanks.
Comment: No, gluing of sheaves doesn't involve any sheafifying.

Co-domain of a sheaf


Abrir item clicado da ListView em uma nova activity

Question: Estou criando um projeto, porém não estou conseguindo abrir o item da listView. Já estou inserindo e editando, mas só consigo abrir o último item criado. Por exemplo, tenho 10 itens na lista, mas somente o ultimo que eu criar, independente do qual eu clique, abre sempre o mesmo. Se eu excluo o último criado, somente o anterior a ele abre.
Gostaria de saber como posso fazer para abrir o item clicado com seu conteúdo, pois somente quando clico é que posso apagar ou editar. O que preciso implementar é o listaUma no final do DAOideia.
ListaIdeia.class
public class ListaIdeia extends ActionBarActivity{

    private ListView listView;

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

        this.listView = (ListView)findViewById(R.id.listView);

        ArrayList<Ideia> lista = new DAOIdeia(this).buscar();
        IdeiaAdapter ideiaAdapter = new IdeiaAdapter(this,lista);
        this.listView.setAdapter(ideiaAdapter);

        this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

           @Override
            public void onItemClick(AdapterView<?> adapter, View view, int p, long id) {

                if(p < 200) {
                    Intent segundaActivity = new Intent(ListaIdeia.this, DetalhesIdeia.class);
                    startActivity(segundaActivity);

                }
            }
        });

DAOIdeia.class

public class DAOIdeia {
    private SQLiteDatabase db;

    public DAOIdeia(Context context){
        this.db = new SQLiteCore(context).getWritableDatabase();
    }

    public void insert(Ideia ideia){
        ContentValues valores = new ContentValues();
        valores.put("nome",ideia.getNome());
        valores.put("descricao",ideia.getDescricao());

        this.db.insert("ideia",null,valores);
    }

    public void update(Ideia ideia){
        ContentValues valores = new ContentValues();
        valores.put("nome",ideia.getNome());
        valores.put("descricao",ideia.getDescricao());

        this.db.update("ideia",valores,"_id = ?",new String[]{""+ideia.get_id()});
    }

    public void delete(Ideia ideia){
        this.db.delete("ideia","_id = ?",new String[]{""+ideia.get_id()});
    }

    public ArrayList<Ideia> buscar(){
        ArrayList<Ideia> lista = new ArrayList<>();
        String[] colunas = new String[]{"_id","nome","descricao"};
        Cursor cursor = this.db.query("ideia",colunas,null,null,null,null,"nome DESC");

        if (cursor.getCount() >0){
            cursor.moveToFirst();
            do{
                Ideia ideia = new Ideia();
                ideia.set_id(cursor.getInt(0));
                ideia.setNome(cursor.getString(1));
                ideia.setDescricao(cursor.getString(2));
                lista.add(ideia);
            }while(cursor.moveToNext());
        }
        return lista;
    }

    public ArrayList<Ideia> listaUma(){
        ArrayList<Ideia> lista = new ArrayList<>();
        String[] colunas = new String[]{"_id","nome","descricao"};
        Cursor cursor = this.db.query("ideia",colunas,null,null,null,null,"nome DESC");

        if (cursor.getCount() >0) {

            Ideia ideia = new Ideia();
            ideia.set_id(cursor.getInt(0));
            ideia.setNome(cursor.getString(1));
            ideia.setDescricao(cursor.getString(2));
            lista.add(ideia);

        }
        return lista;
    }

Parte que cria o ArrayList
public class DetalhesIdeia extends ActionBarActivity {

    private ListView listView;

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

        this.listView = (ListView) findViewById(R.id.listView);

        ArrayList<Ideia> lista = new DAOIdeia(this).listaUma();
        IdeiaAdapterEdit IdeiaAdapterEdit = new IdeiaAdapterEdit(this, lista);
        this.listView.setAdapter(IdeiaAdapterEdit);
    }

}

Comment: Não entendi sua condição ali do `if(p < 200)`. O que quer dizer?
Answer: Para resolver esse problema você precisa criar uma condição para reconhecer o item que foi clicado. Veja abaixo como seria:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {

            /* o position representa a posição que o usuário clicou*/

            switch (position){
                // case clicar na posição 0, significa que e o primeiro item
                case 0:
                    // faça algo referente ao item 1 a este item aqui dentro

                    break;
                // case clicar na posição 1, significa que e o segundo item
                case 1:
                    // faça algo referente ao item 2 a este item aqui dentro

                    break;
                // case clicar na posição 2, significa que e o terceiro item
                case 2:
                    // faça algo referente ao item 3 a este item aqui dentro

                    break;
                // assim por diante ...
            }
        }
    });

Comment: Não tem uma forma melhor de se fazer isso? visto que uma lista pode ter centenas de itens... Não programo em android, mas creio que desta forma esteja "errada"


Prove $\left | \int_{\gamma} \frac{\sin z}{z+i}dz \right | \leq \frac{\pi \sinh 1}{\sqrt{2}}$

Question: Let $\gamma$ be a upper half of unit circle. Prove:
$$\left | \int_{\gamma} \dfrac{\sin z}{z+i}dz \right | \leq \dfrac{\pi \sinh 1}{\sqrt{2}}$$
My try:
Using Jordan lemma, I get :
$\left | \int_{\gamma} \dfrac{e^{iz}}{z+i}dz \right | \leq \dfrac{\pi }{\sqrt{2}}$. And if R big enough $\left | \int_{C_R} \dfrac{\sin z}{z+i}dz \right |= \dfrac{\pi \sinh 1}{2}$
.
Answer: If $z$ belongs to the upper half of unit circle, then $\lvert z+i\rvert\geqslant\sqrt2$ and\begin{align}\bigl\lvert\sin(z)\bigr\rvert&=\left\lvert z-\frac{z^3}{3!}+\frac{z^5}{5!}-\cdots\right\rvert\\&\leqslant\lvert z\rvert+\frac{\lvert z\rvert^3}{3!}+\frac{\lvert z\rvert^5}{5!}+\cdots\\&\leqslant1+\frac1{3!}+\frac1{5!}+\cdots\\&=\sinh(1).\end{align}Since the length of the upper half of unit circle is $\pi$, you get that$$\left\lvert\int_\gamma\frac{\sin z}{z+i}\,\mathrm dz\right\rvert\leqslant\frac{\pi\sinh(1)}{\sqrt2}$$indeed.


Improving driving

Question: I am enjoying playing golf, hitting a straight ball (usually around a 210-yard drive). However, I am always slightly intimidated/put off by the guys in some of the competitions that can hit a drive 75-100 yards further than I can.
I've been told it's all about getting good clubhead speed, not power. So, what can I do to improve my driving?
Answer: The first thing you must understand is that a 210-yard drive that flies in the direction you want it to go is much preferred over a drive that would have gone 300 yards had it not taken that huge right turn in mid air and sailed out of bounds. A "grip it and rip it" mentality will be far more detrimental to your score than a shorter drive distance.
Second, yes, the professional players have great drives. However, they "drive for show, and putt for dough". Tiger can hit an 8-iron 180 yards and can drive well over 300. He still takes his putter with him for the round (even when he leaves his driver behind). Given that you can put a drive, wood or long iron shot on the fairway, and have at least one club in your bag that can reach that par-3 green (most par-3s I've seen are in mid-iron range, with a couple 200-yarders requiring a wood shot; they don't tend to test the 240-yard upper limit of what you can call a par-3, at least not from the normal Men's tee box), it's the short game that determines your score for a hole; I've had beautiful tee shots ruined by skulling the approach chip shot, and made the green in regulation only to four-putt. The drive distance used as a benchmark for the USGA's hypothetical "scratch golfer" (and thus for determining the par of a hole and course difficulty ratings) is only 250 yards, so if you can drive that distance, you can achieve a zero handicap. More distance is always desirable (until you're carrying your drives over the green into a lake) but never at the expense of accuracy and control.
Given that, 210 yards is more like a good 3-wood distance than a drive, and it's understandable that you would want to improve that (again, not by much). Here are some dos and don'ts:

Do take a second look at your driver. Drive distance is a function of the golfer and the club; the club should fit the player. The two biggest areas of change are the flex of the shaft, and the loft angle of the clubface. Shaft flex determines how energy is stored and released in the shaft during your swing; too whippy and the shaft is still flexed at impact, too much and the shaft doesn't flex (or releases what little you had too early). Just right and the shaft straightens right at impact, producing maximum clubhead speed for the swing. Loft angle determines the ball's launch angle and the amount of backspin it has. A higher launch angle keeps the ball in the air longer so it can carry further, but the energy sending it higher is no longer sending it out, and the increased backspin will reduce rollout distance. A lower launch angle uses more of the swing energy to send the ball out over the course instead of up in the air, and reduces backspin for more rollout, but because of the reduced "hang time", the ball may not carry as far as you'd want it to.
There's a balance point to all of this that maximizes total distance for a player's individual swing; the average golfer generally gets the best results out of a driver with 10.5 degrees of loft and a "regular" shaft flex. "Regular" differs slightly between clubmakers, but generally falls in a bell curve. This combination produces the best distance from a correct swing between 80 and 95mph at impact. Golfers with a lower swing speed may benefit either from a lighter flex to increase the "whip" effect at impact, a higher loft to increase hang time, or both. Golfers with a higher swing speed may benefit from some combination of a stiffer flex to allow them to store and properly release more power during their downswing, and a lower loft angle which reduces the launch trajectory, using the player's greater power to send the ball out instead of up.

Do take a look at your preferred ball. Golf balls these days have a lot of subtle variations that can produce significant changes in flight path and energy transfer. One of the key variations is the compression rating or "hardness" of the ball, which determines two things; the "feel" of the shot (a harder high-compression ball feels like hitting a rock which can be good for players who want to dial in their ball-striking; a softer low-compression ball will reduce the shock through the shaft at impact which can be preferable to players seeking a "smoother" feel), and the amount of backspin (the softer a ball is, the more of its surface that will be in contact with the clubface at impact).
A common misconception is that you have to match this rating to your swing speed in order to get the best performance; players with slower swings should use a softer ball. This isn't true; while theoretically the physics involved would indicate that a slower swing compresses the ball less, in practice the difference is insignificant. What you have to match is the feel and the spin characteristics of the ball to your personal preference and game needs; a lower-compression ball trades drive distance for that smooth shot that sticks on the green, while a higher-compression ball will launch straight off the club like a rocket and roll out for an additional 20-30 yards, but will feel like a rock and won't stay where you put it on those close-in shots (unless your home course has really soft greens).

Do compare your drive distance to the distance from your other clubs. Especially pay attention to the difference between your driver and 3-wood, and between your woods and irons. Your driver distance is about what I'd expect a 3-wood to do (on a good day; often I have to choke down on or soften my 3-wood swing for a straight shot and that drops about 20 yards). So, take your driver and 3-wood out to the range and look at the relative distances. If you're hitting them about the same, that indicates that you're doing something different with the driver that's sapping range (or that the driver is a very bad fit for you).
If you get a decent spread through your woods (between 20-40 yards difference between odd-numbered lofts depending on the exact clubs; the modern driver's designed for pure distance off the tee, and so it may outclass the 3-wood of the same model line by a greater margin than between a 3 and 5), then pull out your 4 or 5 iron and take a few swings. Your 4 iron (or hybrid) should be getting you about 20-30 yards less than your 3-wood, and each progressively higher loft number through the irons should be producing about 10 fewer yards. If any of these clubs goes about the same distance or longer than the next longer club, you're changing something between your wood swing and iron swing that is reducing distance.

Do get a club fitting. You can find the right club two ways: by guessing, buying a club, figuring out which way you erred, and buying a new club to correct, then rinsing and repeating until you find exactly the right one (or you're broke); or, by going to a custom clubfitter and getting a swing analysis. You'll stand in a computerized driving range and hit balls off a tee, while a high-speed camera watches the clubhead and ball at impact, producing data such as clubhead speed, launch speed, launch angle, backspin and side spin, which it can use to model the ball in flight and compute carry distance and rolling distance (and thus total distance), as well as undesirable flight patterns like slices and hooks. You'll try several demo clubs in various launch angles and shaft flexes, to find the one that maximizes the distance of your current swing. When you're done, you should know at least what loft angle and shaft flex to shop for, if not a particular brand or model of club that just felt right and went the distance.

Do pay attention to what muscles you're using as you swing. A good swing engages all the muscles that can be employed to add acceleration to that clubhead, in a balance that maintains your alignment with the ball and the desired direction of travel. However, a bad swing engages muscles to extremes, or involves movements that pull you out of alignment.
Your core is a good place to start. Specifically, your obliques will rotate your shoulders, and your pecs, lats and delts will rotate your arms. Your legs play a minor role, but you do twist at the hips a little which engages the quads, hamstring, gastronemius, etc. Work on building and toning these groups to gain core and leg strength. Your arms bend slightly as you backswing, and so your triceps enter the picture. Don't over-focus on any of these, though.

Do get a lesson or two. A professional trainer knows how to swing, and more importantly knows how to teach swinging. If your swing doesn't feel natural or you still think there's something missing, cough up for a couple hours of lessons. An instructor will be able to see what might be wrong with your swing and suggest things to work on, for instance to "unhitch" something you're locking up as you swing, or to engage muscles and joints you're not using, or conversely to reduce overuse of certain groups that bring you out of alignment, thus forcing you to slow something else down to compensate.

Don't just "grip it and rip it". Again, you will lose more in accuracy than you gain in distance by just hauling off and swinging at the ball. When you're working on improving your swing speed, always be thinking "faster", not "harder". There is a big difference between those two in a golf swing; a hard swing will use a lot of energy flexing your muscles in conflict with each other, or will focus too much on adding power to one set of muscles which will put some part of your swing ahead of other critical elements. A "fast" swing uses the muscles efficiently to maximize clubhead acceleration while maintaining alignment.

Don't change too many things at once. Your friends, your instructor, online videos, answers from this site, etc are all going to recommend things to try. Try one or two things at a time. Again, if you have an accurate drive, you will lose more than you gain by tearing your swing apart and starting from scratch. If you have an accurate drive, more likely than not you won't need to change much.

Don't get discouraged. Again, a 210-yard drive that goes where you want it is usually very playable (the only time I can think of where it's otherwise is when you have to carry a water hazard over 200 yards). A 300-yard drive into the trees or that lake on the right side of the fairway is not. You're already ahead of the curve if you have an accurate drive, no matter the distance.

Don't forget to have fun. It's a game. From a probability standpoint you are highly unlikely to make enough money playing the game to cover expenses incurred, and so it's a hobby. You simply don't play a game or pursue a hobby you don't enjoy. If you get outdriven, so what? Drop that chip shot within a foot of the hole and you'll have their jaws dropping.
Comment: I read the question as originally asked and realized that the only section that addresses the original question is "Do pay attention to what muscles you're using as you swing." I now understand that the question was edited to cover your all-encompassing answer (which a great answer, don't get me wrong) but I was looking for an answer specific to the original question as I had a similar question.
Answer: A strong core is essential to a strong, balanced golf swing. This is because the core links the upper and lower bodies. The stronger the core, the more power the body can generate for more clubhead speed.
SOURCE

Furthermore, lighter clubs contribute to more clubhead speed, but control is sacrificed.

A fast swinger dropping 30 grams from his or her driver will pick up 3
miles per hour of ball speed, more than offsetting the loss of 1 mph
of ball speed due to less mass in the head. The bottom line: a boost
of nearly eight yards.

SOURCE

As for exercises to strengthen your core, I recommend the following (take a look at the linked videos/visual explanations for further detail):

Crunches

Mason Twist
In a sitting position with heels off the ground, clasp your hands together and touch the ground with the back of your clasped hand on each side of your body. Using weights (or a kettlebell or a medicine ball) makes this exercise more effective.

Leg Lifts
Lying down with your legs straight out, heels off the ground by 6 inches, lift your legs (while keeping them as straight as you can) to a 90 degree angle and lower them back to 6 inches. For more of a challenge, do it slowly.

Bicycles
Lying down with your legs straight out, bend one leg toward your upper body and move both your legs as you would if you were riding a bicycle. As you do that, crunch toward the side where your knee is bent.

NOTE: If you have a desk job, I recommend replacing your office chair with an exercise ball. Anything to help your core out during the day. I would also look into core stability....also helps in treating lower back pain.
Comment: Would controlling an improved swing be directly proportional to your fitness? I'm specifically intrigued by the "control is sacrificed" part of your answer. Though it is generally accurate that the longer you hit, the less accurate you may become, but would improved fitness cause other factors outside of distance to remain equivalent?

Improving driving


RAW Device mappings

Question: I am new to ESXi, I am going to be using a hard disk attached to my VM with Raw device mappings that connects back to our SAN.
What are the recommended options to choose?
Where to store the LUN mappings, on the VM or with the Datastore?
What compatibility mode to use physical or virtual?
We are going to be using this for database server in our dev environment.
Comment: Why do you think you need an RDM? what are you trying to actually achieve, functionally I mean? Presumably the DB server is a VM right? is it part of a cluster, is that why you want RDMs?
Answer: Generic recommendation is to store LUN mapping with VM and use physical compatibility. If you need the other options, you'll know why.

RAW Device mappings