Why current_thread() always return MainThread?

Question: I started learning threads in python.
I saw this code here that says that if i want to run 2 threads at the same time
I am learning from a free udemy course and this is how he prints the threads name.
Only he gets "thread-1", "thread-2".
I should do it like this:
if __name__ == '__main__':
Thread(target = displayNums()).start()
Thread(target = stam()).start()

Saw it here:
Make 2 functions run at the same time
Now, what I am trying to do is to run 2 or 3 threads at the same time, and get their name.
But I always get MainThread
my code:
from threading import *

def displayNums():
    i = 0
    print(current_thread().getName() , "suo")
    while i <= 10:
        print(i)
        i+=1
print(current_thread().getName())
t = Thread(target=displayNums())

def stam():
    k = 0
    print(current_thread().getName(), "sss")
    while k <= 50:
        print(k,"k")
        k+=1

if __name__ == '__main__':
    Thread(target = displayNums()).start()
    Thread(target = stam()).start()

I get no errors but i get this output:
    MainThread
MainThread suo
0
1
2
3
4
5
6
7
8
9
10
MainThread suo
0
1
2
3
4
5
6
7
8
9
10
MainThread sss
0 k
1 k
2 k
3 k
4 k
5 k
6 k
7 k
8 k
9 k
10 k
11 k
12 k
13 k
14 k
15 k
16 k
17 k
18 k
19 k
20 k
21 k
22 k
23 k
and so on...

Comment: _import *_ is bad practice, be careful!
Answer: Change this:
if __name__ == '__main__':
    Thread(target = displayNums()).start()
    Thread(target = stam()).start()

to this:
if __name__ == '__main__':
    Thread(target = displayNums).start()
    Thread(target = stam).start()

The thread target is the function itself, not the returned value from the function.  stam() calls the function and returns its value, but stam is the function object itself.  When you create a thread you want the function itself, not its returned value.
EDIT:  You call a function when you want to run it right now.  You can access its returned value, for example x = f() will assign the returned value of f to x. There are other situations where you don't want to run a function right now, but you want to keep track of it so you can call it later.  This is the case with threads.  You don't want to run the function, you want to tell the thread constructor what function to run in the second thread.  So in that case you pass the function itself as an argument.  Usually that means the function name without any brackets.
Python treats functions like any other object.  In Python you can assign a function to a variable, and then the variable is, for all intents and purposes, the function itself.  It can be called just like the original function (with curly braces) or it can be passed to a function, or whatever.
Try this:
# print is a function (built-in), and I can assign it to a variable
a = print
# Nothing gets printed yet
# the variable 'a' is now the same thing as the print function
a("Hello world")

This is a silly example but there are lots of real-world situations where this is very useful.
Comment: Marcin's answer was up before mine, so please approve his answer in preference to mine.  I'll leave mine up because my explanation is a little different and that might be helpful.
Comment: thank you both :) it's working. how do i know in which cases i should invoke the method like in your examples or with the brackets? it very confusing for a new learner. plus if you can please explain the `if`. i know its comparing two names, but why the string is `MainThread` for example?
Comment: Thread names are usually just created by python automatically.  If you want to assign a particular name to a new thread,you can use the name= keyword in the constructor.  I've rarely if ever found a use for that.  I am modifying my answer to try to answer your first question..
Answer: Your code is actually calling thread targets outside of threads. Edit your code to:
if __name__ == '__main__':
    Thread(target = displayNums).start()
    Thread(target = stam).start()


Assign email on user registeration

Question: I have a custom user email field,
I want when the user signs up to automatically set the email for he/she.
For example, when the username field is user1 I want set the email to firstname.lastname@example.com and save it in email field.
How can I do this?
Answer: If you'd like to customize the user registration form, you're probably looking at a custom module to take care of this; an invocation of hook_form_alter() can step in and alter the behavior of the user registration form. For example, adding the following functions to MYMODULE:
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  // Disable the email field
  $form['account']['mail']['#access'] = FALSE;

  // @TODO: Override validation functions in $form['#validate']
  // that check the mail field

  // Replace the user registration form submission with
  // the function MYMODULE_form_user_register_form_submit
  $form['#submit'] = array('MYMODULE_form_user_register_form_submit');
}

// Alter the disabled mail field before
// submitting registration form to user_register_submit()
function MYMODULE_form_user_register_form_submit($form_id, &$form_state) {
  // add '@mydomain.com' to the submitted username field
  $form_state['values']['mail'] = $form_state['values']['name'] .  '@mydomain.com';
  user_register_submit($form_id, $form_state);
}

This only get you partially there, as overriding such key functionality requires many scenarios to validate now that a key assumption is gone (e.g. what happens when someone enters an email for a name, what happens when a user needs to recover password, etc.).
It might be helpful to look at the source code of the Optional mail on register module to see how that is accomplished so you can under how modules can override Drupal's user registration functionality.

Assign email on user registeration


Resource's businessHours is not working on weekends in agendaDay view

Question: First of all, excuse me for my english, I'm from México.
My problem is this...
I have this code:
$('#calendar').fullCalendar({
    defaultView: 'agendaDay',
    businessHours: false,   // to enable all 24 hours regardless of the businessHours per resource
    weekends: true,         // to allow navigation between weekend days
    resources: [
        { id:1, title: "Employe 1", businessHours: { start:"08:00:00", end:"12:00:00" } },
        { id:2, title: "Employe 2" }
    ]
});

As you can see, I'm using fullcalendar's schedule plugin in agendaDay mode (timeline slot in vertical), and what I do is declaring 2 resources, one with businessHours and other without businessHours. The problem here (I don't know if it's a bug) is in navigation in weekend days. When viewing no-weekend days no problem, but when weekend days are viewed the resources timeline are disabled as if these was without businessHours, BUT that happens only for resources with businessHours (those that don't have this property works fine), STILL when globally the businessHours property is set to false (as you can see in the initializacion). So, the problem is that, I need show resources with businessHours for each, because for my a resource is an employe and each one can has different schedule and can there are more that  one employe by day, and that's because I need manage a businessHour per-resource and not globally.
Some help please?
Regards!
Comment: Try to reproduce the issue in [JSFiddle](https://jsfiddle.net/) or equivalent.
Comment: The agendaDay view knows nothing about resources, it's part of standard fullCalendar and designed to work without resources, which are part of the extra Scheduler plugin. So I think it ignores your resource, and thus your businessHours for that resource. Perhaps if you set  groupByResource (https://fullcalendar.io/docs/vertical_resource_view/groupByResource/) true, then it show a column per resource for that day, and will take the resource settings into consideration. Try it and let me know.
Comment: Void Ray I can't reproduce the issue in JSFiddle because it seems fullcalendar have not url of it's scheduler plugin as cdn or equivalent.

ADyson, this is a url using fullcalendar' scheduler plugin in agendaDay mode, although resources have not defined businessHours at level resource. And I used groupByResource with true value, but not working.
Comment: Sorry I think I misunderstood your question before. This isn't really related to resources specifically. See my answer below, I think this will help you more than my earlier comment.
Answer: It seems that, by default, if you just give times for your business hours and don't set days of the week, then fullCalendar assumes that you meant only Monday to Friday.
The default business hours, if not specified at all, are Monday-Friday 09:00-17:00. It looks like by specifying your own hours, you overwrite only the times, but not the days.
The simple solution is to explicitly specify all the days of the week:
resources: [
    { id:1, title: "Employee 1", businessHours: { dow: [ 0, 1, 2, 3, 4, 5, 6 ], start:"08:00:00", end:"12:00:00" } },
    { id:2, title: "Employee 2" }
]

The dow parameter takes an array of numbers signifying the days of the week o which to enable the business hours, where 0 = Sunday, 1 = Monday etc. through to 6 = Saturday.
See https://fullcalendar.io/docs/display/businessHours/ for more details.
Comment: Hi ADyson, I have found the solution already yesterday and is the same solution that you says, although I still thinking it´s a bug, because the businessHours was set to false globally , and it should works fine, but not.
Thanks! (:
Comment: It's true that businessHours was false globally, but you created a new businessHours object for that resource, so when you create that object it gives it the default days of the week values, because you didn't override them. It has to use some kind of value to decide what days to display it on. I think it's not unreasonable to expect that it could be using the default Mon-Fri, although the documentation could be clearer about it. Personally I don't think it's a bug, for that reason, but if you disagree you could still raise it with the fullCalendar people. Glad you fixed it anyway
Comment: @ADyson See this please :) https://stackoverflow.com/questions/47468891/populating-linq-list-to-calendar-with-checkmarks-on-the-appropriate-dates


Creating a Weekly Scheduled Query Job in Google BigQuery Using Python

Question: I have a function that is supposed to query a table and save a table corresponding to the date the query job is done.
<code>def Query_Schedule(request):
    from google.cloud import bigquery
    from google.cloud.bigquery.job import QueryJobConfig
    from datetime import datetime
    today = datetime.today()
    client = bigquery.Client(project='project-id')
    query_string = """SELECT * FROM dataset.table"""
    dataset = client.dataset('dataset')
    table = dataset.table('table_{}_{}_{}'.format(today.month, today.day, today.year))
    cfg = QueryJobConfig()
    cfg.use_legacy_sql = False
    cfg.destination = table
    cfg.write_disposition = 'WRITE_EMPTY'
    cfg.timeout_ms = 60000
    job = client.query(query=query_string, job_id='weekly-table-creation', job_config=cfg)
    return job
</code>
After referencing this question and adapting it to the most recent documentation I am still getting an error,
Error: function terminated. Recommended action: inspect logs for termination reason. Details:
409 POST https://bigquery.googleapis.com/bigquery/v2/projects/project-id/jobs: Already Exists: Job project-id:US.weekly-table-creation
(job ID: weekly-table-creation)
-----Query Job SQL Follows-----
|    .    |    .    |    .    |
1:SELECT * FROM dataset.table
|    .    |    .    |    .    |
after I test the function. Is there any solution to this problem?
Answer: The issue is that you're specifying a static job_id for all invocations.  Jobs in BQ have unique job IDs, and you can't re-insert a job with the same ID.  Either don't specify the ID at all, or provide a job ID that's sufficiently unique (e.g. suffixed based on the scheduled time, etc).
More info: https://cloud.google.com/bigquery/docs/running-jobs#generate-jobid


Integral equation with kernel $x-y$

Question: I am trying to solve the integral equation
$$
f(x)=\int_0^x (x-y)f(y)dy, \ 0\leq x\leq 1
$$
in the space $C([0,1])$ of continuous functions on $[0,1]$. My reasoning is this: Since $u(y)=(x-y)f(y)$ is continuous, the integral $\int_0^x (x-y)f(y)dy$ is a differentiable function, which means that the solution $f$ will also be differentiable.
Differentiating gives $f'(x)=\int_0^xf(y)dy$. By a similar argument as before $f'$ is differentiable as well, therefore $f''=f$. This equation has the general solution
$$
f(x)=a\exp(x)+b\exp(-x)
$$
for some constants a,b. Now I can use $f(0)=\int_0^0\ldots=0$ to obtain $a=-b$.
My question is whether these are correct and if they are, and how to proceed in determining the constants...
Answer: What you wrote is correct. From $ f'(x)=\int_0^xf(y)dy$ you get $f'(0)=0.$ This gives $a=b=0.$

Integral equation with kernel $x-y$


If both $f \ge 1$ and $f\le 1 $ almost surely then $f = 1_A$, where $A$ is borel

Question: Let $f:[0,1]\rightarrow \mathbb{R}$ be a positive measurable function. If $f\leq 1$ almost surely and $f\geq 1$ almost surely (with respect to lebesgue measure). Show that $f=1_{A}$ for some $A\in B[0,1]$.
I'm not sure how to start.
My attempt is as follows:
So $f\geq 1$ almost surely means there exists some set U in borel algebra on [0,1] such that $\mu(U)=0$ on which $f<1$
$f\leq 1$ almost surely means that there exists some set V in borel algebra on [0,1] such that $\mu(V)=0$ on which $f>1$
By construction of U and V, $U\cap V=\varnothing$. Hence, setting $A=U\cup V$, we obtain
However, I have gotten nowhere.
May someone elaborate? What should I modify the problem for the conclusion to hold (if it doesnt hold?)
Answer: There exist sets $E,F$ of measure $0$ such that $f(x) \leq 1$ if $x \notin E$ and $f(x) \geq 1$ if $x \notin F$. Let $A=E \cup F$. Then $A$ has measure $0$ and $f(x) = 1$ if $x \notin A$ (because $x \notin A$ implies $x \notin E$ and $x \notin F$). Now let $D=\{x: f(x)=1\}$. Then $D$ is a Lebesgue measurable set and  $f=1_D$ almost everywhere. To complete the proof just note that there is a  Borel set $B$ such that $I_D=I_B$ almost everywhere.
Comment: @orientablesurface I used $E,F$ and $A$ to show that $f=1$ almost everywhere. Once this is done it follows immediately that $f=I_D$  almost everywhere where $D=\{x: f(x)=1\}$.
Comment: and D is simply the complement of A, right?
Comment: @orientablesurface Yes, we can take $E=\{x: f(x) >1\}, F=\{x: f(x) <1\}$ and $A =E \cup F$ so $D$ becomes the complement of $A$.


What does the PCA().transform() method do?

Question: I've been taught to think of the PCA as change of basis technique with a cleverly chosen basis. Let's say my initial data is a $m\times n$ matrix $X$ where $m$ is a number of features and $n$ is a number of measurements. I've computed covariance matrix $S$ and got eigenbasis $m\times m$ matrix $P$ (eigenvectors of $S$) which represents my new set of coordinates. I now want to transform my data to this new coordinates by $Y=PX$. Alternatively, I use sklearn.decomposition.PCA class to perform the same procedure, but the transformed data differs from what I get manually.
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA

# generate some random data
m = 10
n = 100
X = np.random.randn(m, n)
X = X - X.mean(axis=1).reshape((m, 1))
S = X @ X.T / (n-1)

# manual computation
P = np.linalg.eig(S)[1] # transformation matrix P
Y = P @ X # transformed data

# using sklearn
pca = PCA()
pca.fit(X.T)
Y_sklearn = pca.transform(X.T).T

The output for the first vector in $Y$, Y[:, 0], is
array([-0.09133876, -1.53859883,  0.86409512, -2.52404208,  0.05910835,
        0.83063718,  0.52757518,  0.7412817 , -0.42611878, -0.71241571])

while for Y_sklearn[:, 0] is
array([ 1.44259169,  1.05948004,  0.87768441,  0.60333571, -1.560406  ,
        0.11799914, -1.91440021, -0.96841104,  0.41010045, -0.38189462])

I am probably making a mistake at some point, but can't find where exactly. Thanks in advance.
Answer: Your P matrix contains the eigenvectors as columns, so you need to reconstruct with P.T @ X in order to project your data (i.e. dot product). Now, they'll be more similar; but still not the same because np.linalg.eig doesn't return eigenvalues sorted. You can achieve the same ordering as follows:
   E = np.linalg.eig(S)
   P = E[1][:,np.argsort(-E[0])]

Finally, since eigenvectors can be $v$ or $-v$ you'll have some sign differences between your projections. But, they'll be quite similar.
Comment: Thank you for your answer. Indeed, sorting eigenvectors and taking transpose leads to the same results (up to a sign). But I don't really get why I need a transpose. If the eigenvectors in $P$ (which is $m\times m$) are my new basis, and I want to transform some $m\times 1$ vector $v$ to a new basis I would do $Pv$, not $P'v$, right?
Comment: Logically, you are projecting data onto eigenvectors. First column of $P$, say $p_1$ is the first eigenvector, it is of dimension $m\times 1$. If we want to project a data vector $v$ onto the vector $p_1$, we'd calculate the dot product $p_1^Tv$, and get  the score. It's an unlucky situation that you have $P$ as $m\times m$. Normally, if you're reducing dimensions, you'll take the first $k$ eigenvectors, therefore the first $k$ columns of $P$. Then your reduced matrix will be of dimension $m\times k$, where you can't multiply with $v$ any more.


publishing different services with same url and managing them separately

Question: We have more than 2000 business methods which we want to expose as soap web service. We decided to use cxf with apache camel for this. We want to publish all these services from same url since we think management of them would be easier(especially for customers who call many web services). However we also have some requirements like:

method based log enabling
method based setting timeout
method based mtom/base64 setting and etc.

My question is, if its possible to publish all the services from same url(same SEI) and also being able to provide all these requirements. And also if we manage to do this, will it be a good and scalable solution?
Comment: From an ops perspective, this sounds...weird. Are all 2k methods related, as in they can be logically grouped together as belonging to the same service? Is your operations team on board with having so many business methods in one place?
Answer:
method based log enabling

If you have 2000 methods in your business logic, I guess you also have logging. You can define multiple loggers for your webservice and use in every method at your convenience

method based setting timeout

CXF allow to configure ReceiveTimeout at server endpoint configuration, so if you use one endpoint, then the timeout will be the same for all your methods

method based mtom/base64 setting and etc.

MTOM is configured by JAX-WS server, enabling or disabling it. Also the methods will have an specific DataHandler to support it. One endpoint means one MTOM configuration
In this link you can see the http-transport variables set by server. Other utilities like interceptors, bus or fault handlers are also configured by JAX-WS server. Check here if any is of interest

will it be a good and scalable solution?

As stated @kolossus, 2k methods is a solution weird.  I do not think you have performance problems, but it will difficult to develop and maintain. Think you can also provide a built client, instead of only the WSDL, that encapsulates several endpoint
Comment: Then its better to group them with some logic.
Comment: It would be recommendable


Prove sequence $\frac{2}{\sqrt{n}} $ converge

Question: I will prove in two ways.Please point the mistake for each method
*the problem doesn't give the limit value
First
$$\left ( \frac{2}{\sqrt{n}} \right )^{2}< \epsilon ^{2} $$
$$ \frac{4}{n}<\epsilon ^{2}$$
$$\frac{4}{\epsilon ^{2}} < n$$
Then the inequality $\frac{4}{n}< \epsilon ^{2} \Rightarrow  \frac{2}{\sqrt{n}}< \epsilon $also hold the sequence converge to some number
Second
if$S_{n}$ converge to some number for $\epsilon > 0$
then
$ \left |S_{n}-L   \right |< \epsilon $ for every $n> $
$$ \left (\frac{2}{\sqrt{n}}  \right )^{2}< \epsilon ^{2}$$
$$ \frac{4}{n}< \epsilon ^{2}$$
$$ \frac{4}{\epsilon ^{2}}< n$$
We choose $N\geq \frac{4}{\epsilon ^{2}}$
then
$$n> N\geq \frac{4}{\epsilon ^{2}}$$
therefore $\left |S_{n}  \right |< \epsilon $ for every n> $N$
Comment: Are you obliged to always use epsilon and delta? I think a lot of these problems can be knocked off together (its what I did as an undergraduate).
Comment: no I mean $\frac{2}{\sqrt{n}}$ as I wrote
Comment: @Alephnull I just read one-fourth of sequence chapter in real analysis book I try to think another way to solve this problem,but I have no idea.
Comment: Prove or disprove: the product of convergent sequences is convergent, the reciprocal of a convergent sequence is convergent, monotone increasing sequences are convergent, a sequence is convergent iff its subsequences all converge to the same point.
Answer: It is monotone. Its subsequence denoted by $n_k=k^2$ converges.


how to remove anonymous user role from list of profile members

Question: I want to remove anonymous role member from the public list of profile users because anonymous roles cannot join so it is confusing to see the anonymous user at top of public profile list.
Comment: How is this list being generated?
Comment: It is being generated through views module.
Answer: Add a filter for user: UID and set to "not equal to" and enter 0 for the value.


Views Output field as a link - Two tokens, use only one of them

Question: I have content type which has field_pdf.
I have made view to show content and there is a field which has set: Output field as a link.
In link path settings I have two tokens: [field_pdf][path]. Idea is to link field either straight to PDF (if there is PDF file in node) or to content node.
How to get view to use only [field_pdf] when this field_pdf has content and not use [path] at all?
Now I'm getting double url for example: http://url.com/pdf-file.pdfhttp://url.com/pdf
Answer: Modules You Need:

Views
Views PHP

Assuming your content type is having these fields:

The VIEWS Code:
Simply go to admin/structure/views/import and then Import the below mentioned code:
$view = new view();
$view->name = 'pdf';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'PDF';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'PDF';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: PDF */
$handler->display->display_options['fields']['field_pdf']['id'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['table'] = 'field_data_field_pdf';
$handler->display->display_options['fields']['field_pdf']['field'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['label'] = '';
$handler->display->display_options['fields']['field_pdf']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['path'] = '[field_pdf][path]';
$handler->display->display_options['fields']['field_pdf']['element_label_colon'] = FALSE;
/* Field: Global: PHP */
$handler->display->display_options['fields']['php']['id'] = 'php';
$handler->display->display_options['fields']['php']['table'] = 'views';
$handler->display->display_options['fields']['php']['field'] = 'php';
$handler->display->display_options['fields']['php']['label'] = '';
$handler->display->display_options['fields']['php']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['php']['use_php_setup'] = 0;
$handler->display->display_options['fields']['php']['php_output'] = '<?php
if (isset($data->field_field_pdf[0][\'rendered\'][\'#markup\'])) {
    $pdf_url = $data->field_field_pdf[0][\'rendered\'][\'#markup\'];
    print $pdf_url;
} else {
    global $base_url;
    $node_url = $base_url . \'/node/\' . $data->nid;
    print $node_url;
}
?>';
$handler->display->display_options['fields']['php']['use_php_click_sortable'] = '0';
$handler->display->display_options['fields']['php']['php_click_sortable'] = '';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'pdf' => 'pdf',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'pdf';

I'm sure you might be having some dummy content for that content-type, if not then do create couple of ones. Some with values in field_php and some with not!
and Voila! Here is your required output:

Updated Code:
$view = new view();
$view->name = 'pdf';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'PDF';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'PDF';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: PDF */
$handler->display->display_options['fields']['field_pdf']['id'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['table'] = 'field_data_field_pdf';
$handler->display->display_options['fields']['field_pdf']['field'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['label'] = '';
$handler->display->display_options['fields']['field_pdf']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['path'] = '[field_pdf][path]';
$handler->display->display_options['fields']['field_pdf']['element_label_colon'] = FALSE;
/* Field: Global: PHP */
$handler->display->display_options['fields']['php']['id'] = 'php';
$handler->display->display_options['fields']['php']['table'] = 'views';
$handler->display->display_options['fields']['php']['field'] = 'php';
$handler->display->display_options['fields']['php']['label'] = '';
$handler->display->display_options['fields']['php']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['php']['alter']['path'] = '[php]';
$handler->display->display_options['fields']['php']['alter']['absolute'] = TRUE;
$handler->display->display_options['fields']['php']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['php']['use_php_setup'] = 0;
$handler->display->display_options['fields']['php']['php_output'] = '<?php
if (isset($data->field_field_pdf[0][\'rendered\'][\'#markup\'])) {
    $pdf_url = $data->field_field_pdf[0][\'rendered\'][\'#markup\'];
    print $pdf_url;
} else {
    global $base_url;
    $node_url = $base_url . \'/node/\' . $data->nid;
    print $node_url;
}
?>';
$handler->display->display_options['fields']['php']['use_php_click_sortable'] = '0';
$handler->display->display_options['fields']['php']['php_click_sortable'] = '';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'pdf' => 'pdf',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'pdf';

Let me know if you need anything else from this.
Cheers!
Comment: I added content type PDF and field_pdf. Then I added content with pdf file and without pdf file. Imported new views with the views code above. But views shows only normal paths, not path to the file.
Comment: @hene, you mean to say you want clickable links?
Comment: Yes. Im building views which shows multiple content from multiple content types. And some of the content has link to the node itself but some content has PDF-file and in those link should be straight to PDF-file instead of node.
Comment: @hene, I've updated the post with the new code, please try re-importing it and do check it. I'm sure it will work as per your requirement. Let me know if there is any issue.
Comment: Ah, now it works. I imported updated views code AND changed Field Content: PHP Formatter from Generic file to URL to file.


Preciso mudar a fonte de um text-Area: Ex: de Negrito para itálico, mas não consegui ainda. Alguém pode me ajudar?

Question: var textarea = document.querySelector(".editor");
var negrito = document.querySelector("button");
var paragrafo = document.createElement('p');

negrito.onclick = function(){
    var select =  document.getSelection(".editor");
    var italico = document.createElement('i');
    var texto = document.createTextNode(select.toString());
    italico.appendChild(texto);
    console.log(select.italico());

}

textarea.onkeypress= function(){

}

Answer: No exemplo abaixo eu pego o valor selecionado pelo usuário, uso um regex para obter somente o texto do textarea, e crio um novo texto acrescentando a tag selecionada pelo usuário e por último adiciono esse novo texto ao textarea.

function opcaoSelecionada(val){
  if(val) {
    let text = document.getElementById('area').value.replace(/(<( |[^>]+)>)/ig, "");
    text = `<${val}>${text}</${val}>`;
    document.getElementById('area').value = text;
  }

}
<textarea id="area"></textarea>

<select onchange="opcaoSelecionada(this.value)">
      <option value="">Selecione uma opção</option>
      <option value="b">Negrito</option>
      <option value="i">Italico</option>
</select>


Need an array where with first element of new array=sum of all elements except the first element-Javascript

Question: I have an array arr[0,1,2,3,..10] in Java script.I need to make a new array with first element of new array=sum of all elements except the first element of the previous array,and goes on.
Description: I have
  Array=new Arr[0,1,2,3,..10].

I need an
  Array=new new Array[first element,second element..]

where
 first element=(1+2+..10)-0 ,
    second element=(0+2+3+..10)-1,
    third element=(0+1+3+..10)-2,

.. goes on till last element.

Answer: Algorithm goes like this

Just calculate the sum of all elements in the array
Traverse the array and reduce the element value from the sum and push into new array

Code
var sum = 0;
var result = [];
for (var i = 0; i < arr.length; i++) {
  sum += arr[i];
}

for (var i = 0; i < arr.length; i++) {
  result.push(sum - arr[i]);
}

console.log(result);

Note that, this can be done with short snippets of code as well using a combination of Array.reduce and Array.every, Array.slice. But these all methods have browser compatibility issues as they are not supported in older IE browsers.
Answer: var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var sum = myArray.reduce(function(previous, current) {
    return previous + current;
}, 0);
var newArray = myArray.map(function(currentElement) {
    return sum - currentElement;
});
console.log(newArray);

Output
[ 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45 ]

Comment: Although OP has not mentioned whether he wants it to work on older IE versions or not. If he wants to support <= IE8, then he has to do polyfill.
Answer: It looks like you'll have to do something like this:
var nums = new Array(0,1,2,3,4,5,6,7,8,9,10);
var sum = Function('return ' + nums.join('+') + ';')();
var final = [];

for(j = 0; j < nums.length; j++){
   final.push(sum - (2 * nums[j]) );
}

console.log(final);

The reason you have to do (2 * nums[i]) in the last step is:

To get rid of the item from the original addition (the 2 in the line below - from your code),
To subtract it at the end of the line.

var third element=(0+1+3+..10)-2,

fiddle
- Cred to @wared for the sum function -
Comment: +1 It seems to be quite close to asker's requirements. Here a quick way to add up all elements : `var sum = Function('return ' + nums.join('+') + ';')();`.
Comment: Nice, I've never seen that before! I hope it's okay I incorporated that into my answer
Answer: You can do this:
arr = [0,1,2,3,4,5,6,7,8,9,10]

//Sum them all
sum = 0
for(i=0; i<arr.length; i++){
   sum+=arr[i];
}

//Calculate the result
result = []
for(i=0; i<arr.length; i++){
   result.push(sum-arr[i]);
}

alert(result);

Check this fiddle: http://jsfiddle.net/eg7F6/
Answer: This is the generic approach:
var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var sum = array.reduce(function (sum, value) { return sum+= value });
var newArray = array.map(function(value) { return sum - value });

However, if the array has always values from 0 to 10, you could do some shortcut – but at this point, I do not understand the point of having that.
Comment: Idential to @thefourtheye's answer. Please check before posting


Somar variáveis para obter data de término

Question: Tenho um formulário com um cadastro de locação. Nele, tenho os campos $datainicio, $meses e $datatermino. A data de início eu coloquei automático, de acordo com a data do dia. Os meses deverão ser colocados no momento do cadastro, sendo 6, 12, 18, 24, 36, 48 ou 60 meses.
O meu problema é o seguinte: Gostaria de pegar a variável $datainicio e somar com a variável $meses para obter o valor de $datatermino, tudo isso no momento do cadastro.
Sei que com PHP puro não consigo fazer isso. Tenho dificuldades com jQuery. Gostaria da ajuda de vocês.
$datainicio + $meses = $datatermino.
Comment: Sim é possível com PHP puro, acredite!
Comment: Sério? Se tiver alguma referência... imaginei não ser possível...
Answer: Você pode fazer isso com o método add() da classe DateTime combinando com a classe DateInterval. O que é feito é adição de um período determinado por uma string como P10D(10 dias);
$dataInicio = DateTime::createFromFormat('d/m/Y', '28/03/2016');
$dataInicio->add(new DateInterval('P10D'));
echo $dataInicio->format("d/m/Y"); //saida: 07/04/2016

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54275/discussion-on-answer-by-rray-somar-variaveis-para-obter-data-de-termino)
Answer: É possível utilizar a função strtotime() do PHP para realizar diversas operações entre datas inclusive a de somar:
ini_set('date.timezone','America/Sao_Paulo');
$datainicio = '28-03-2016';
$meses = '2'; //adicionando meses
$datatermino= date('Y-m-d', strtotime("+".$meses." months",   strtotime($datainicio)));

echo $datatermino;// Saída: 2016-05-28 , dois meses depois

Answer: //Obtem a data atual.
$date   =  date('Y-m-d'); //Data atual 29-03-2016

//Quantidade em meses para somar a data
$qtdMes =  6

//"quebra" a data em 3 partes usando como delimitador o "-"
list($year, $month, $day)  =   explode( '-', $date );

//Usando a função mktime, podemos somar dias, meses, anos, horas, minutos e segundos
$date   =   mktime( 0 , 0 , 0 , $month + $qtdMeses, $day, $year );

//Mostra a data
echo date( 'd/m/Y', $date );

Uma outra forma de fazer isso é:
$date  =  date('d-m-Y', strtotime( '+ 2 mounths' ) );

Como parametro na função strtotime você pode usar days, mounths e years.
Answer: Eu utilizaria o Datetime combinado com o método modify para alterar de acordo com os meses que quero adicionar:
$mes_variavel = 3;

$datetime = new DateTime('2016-08-06');

$datetme->modify(sprintf('+%d months', $mes_variavel));

echo $datetime->format('d/m/Y');


Linux Multimedia Studio Sound Font note fade away

Question: I am currently trying out some sound-fonts I just downloaded, in Linux Multimedia Studio (LMMS). All is going well, besides the fact that I haven't, even after a Google search, found out how to make a soundfont's note fade out or in. At the suggestion of one YouTube video, I tried using the Automation editor, yet, though it affected the default preset and other such types of instruments, it had no effect whatsoever on the soundfont (.sf2) files I am using.
I am still inclined to think that the automation editor is what will accomplish this in the end, yet I need some guidance. Any suggestions? Thank you!
Comment: You used an obscure acronym that you did not define in context, so after I figured out what LMMS is, I modified your question.
Comment: Thank you! I should have used the full name, I guess that I was just to lazy to type it out. :)
Comment: Perhaps I should add that I am on a Windows XP (yeah, yeah, I know) with the latest version of LMMS.
Answer: Sf2 files are harder to modify than built-in instruments. The best bet is to try adjusting the volume's attack level or decay on the instrument. also you can add reverb as an effect. Personally I prefer free VST plugins. They sound more realistic. look up synths like synth1, oatmeal, and dsk music's assortment if you prefer more natural sounds. You can get even nicer ones if you're willing to pay for them, but judging by the fact you're using LMMS in the first place I assume that's not an option.
Comment: :) Yes, I am going with free. I will check out those VST plugins and see what I get with playing around with the SF2s...


Redirecionamento Magento

Question: Eu tenho dois ambientes de um e-commerce em Magento: homologação e produção. O problema é o seguinte: quando vou fazer o login em homologação, ele me redireciona para produção. Na tela de login de homologação, o action do <form> está indo para o servidor de Produção, quando na verdade deveria ir para homologação, porém o link que ele deve fazer o post é recebido pelo código PHP <?php echo $this->getPostActionUrl() ?>, que nesse caso deveria receber o link de homologação, certo? Alguma ideia do que possa ser?
Comment: Limpou a cache do magento? Verificou se está a apontar (veja no XML) para a base de dados correta onde os links apontam para homologação? Verificou se a base de dados tem os links corretos? Verificou se existe algum redirect no ".htaccess"? Se depois disso não funcionar, apelando apague a cache do browser, reiniciei o computador, mude de cadeira...
Answer: Acesse a base de dados de onde está instalado o Magento e altere a tabela CORE_CONFIG_DATA para a nova localização, basta alterar os valores do campo "path" da tabela que são respectivamente: web/unsecure/base_url e web/secure/base_url);
Caso não se recorde em qual banco de dados esta instalado seu Magento, acesse o arquivo 'local.xml' na pasta:
app/etc
Comment: Obrigado pela resposta Rafael, mas os links do base_url já estão apontando para o ambiente de homologação. Isso que me deixou com mais dúvida quanto ao problema, pois mesmo com os links apontando para o ambiente de homologação, ele cai em produção. No momento eu resolvi o direcionamento no hardcode, mas não é o melhor caminho.
Answer: Corrigir esse problema é bem simples – há inclusive duas maneiras de se resolver rapidamente.
A primeira maneira, que vejo como mais simples, é acessar o banco de dados da sua aplicação e modificar direto as URLs nos campos "web/unsecure/base_url" e "web/secure/base_url", que ficam na tabela "core_config_data".
Depois disso, basta apagar todo o conteúdo da pasta /var/cache e… voila!.
Comment: Ambos já estão indicando para homologação, mas mesmo assim o link do post está indo para produção...
Comment: Lembrando sempre de apagar todo conteudo de cache "TODO"
Comment: Limpar o cache pelo admin não é o suficiente?
Comment: Atualizando as informações: Conferi no banco de dados e as "base_url" estão com o link de homologacao. E já apaguei tudo da pasta /var/cache, porém nada mudou.
Comment: apaga tudo do /var
Comment: se com isso não for ta muito estranho isso ai

Redirecionamento Magento


Android overflow menu overlapping actionbar

Question: I'm trying to make a menu with two items, "Exit" and "Settings", where the "Exit" item is located on the actionbar, while the "Settings" item is located in the overflow menu.
However when I click on the menu icon, the overflow menu overlaps the "Exit" item. Is there anyway I can prevent this behaviour?
This is what's currently happening
This is what I'm trying to achive

Menue.XML

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item android:title="@string/setting"
            android:id="@+id/setting"
            android:orderInCategory="2"
            app:showAsAction="never"
        />

        <item android:title="@string/exit"
            android:id="@+id/exit"
            android:orderInCategory="1"
            app:showAsAction="withText|ifRoom"

            android:icon="@drawable/exit"
        />
    </group>
</menu>

Activity_main.XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.meunueexample.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>

Main_Activity.Java

package com.example.meunueexample;

import android.app.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) { // it wil inflate the menue in the action bar
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { // here we will get the selected item form group option
        int id = item.getItemId(); // will get id of selected item these IDs are not user defined
        if (id == R.id.setting) {

            android.app.DialogFragment myfragment= new DialogFragment(); // made object of dialog fragment
            myfragment.show(getFragmentManager() , "thedialog"); // thedialog is object created in DialogFragment class

            return true;
        } else if (id == R.id.exit) {
            finish();

            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Dialog_Fragment.Java

package com.example.meunueexample;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

/**
 * Created by AQ on 9/10/2017.
 */
public class DialogFragment extends android.app.DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) { // override this method to ake dialog box
        AlertDialog.Builder thedialog = new AlertDialog.Builder(getActivity()); // jiss activity ka oper is na show hona hy
        thedialog.setTitle("Sample Dialog");
        thedialog.setMessage("Hlw AQ");

        thedialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { // on click listener on button clicked
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "Clicked OK", Toast.LENGTH_SHORT).show();
            }
        }); // place semicolon there
        thedialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // on click listener on button clicked
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "Clicked Cancel", Toast.LENGTH_SHORT).show();
            }
        }); // place semicolon there

        return thedialog.create();
    } // may change abndroid version from android manifest and from build.gradle
}

Comment: This isn't an Android Studio issue, so don't use the Android Studio tag
Comment: For your information, 'menu' is spelled without 'e' at the end.
Comment: Please add as first statement/paragraph a simple and clean summary of what you want to achieve or need help.
Answer: You can change this behaviour by creating a style with a vertical offset, like so:

You can then apply this style in your theme:
<item name="actionOverflowMenuStyle">@style/OverflowMenu</item>


Understanding Tempered Distributions

Question: I'm reading about tempered distributions in Folland's Real Analysis. In particular, tempered distributions are defined as the class of linear functionals on a Schwarz space. On page 293, Folland says:
If $f\in L_{\mathrm{loc} }^1$ and $\int (1+|x|)^N|f(x)|<\infty$ for some $N\ge 0$, then $f$ represents a tempered distribution since $\int |f \phi|\le C||\phi||_{(0,N)}$.
This statement is a bit puzzling. If $\int (1+|x|)^N|f(x)|<\infty$ for some $N$, then $\int |f(x)|<\infty$. So why bother looking at $N$ other than 0? I though perhaps "for some $N$" needed to be "for all $N$" but that doesn't seem necessary according to my understanding of convergence in the Schwarz space.
In fact, by choosing large $N$, it seems we strengthen our assumption and weaken our conclusion. What am I missing?
Comment: Or the typesetter.
Comment: Somebody forgot a minus sign. If $$\int (1+\lvert x\rvert)^{-N} \lvert f(x)\rvert < \infty$$ for some $N \geqslant 0$, then ...
Comment: Ah thanks. It was Folland.
Comment: Yea true. I just meant it was in the book. I should have seen that myself though. Thanks.
Answer: As pointed out by Daniel Fischer, the correct assumption should be
$$\int (1+\lvert x\rvert)^{-N} \lvert f(x)\rvert < \infty$$
for some $N\geqslant 0$.

Understanding Tempered Distributions


How to add document ID to the firestore document in Python

Question: I am trying to add the document ID of a new document on firestore into the object itself using python, however it shortens the string when adding and doesn't actually add the same ID.
I have printed the ID and it says it should be the same. Though in firestore its different.
doc_ref = db.collection(u'prime_location').document()
        print('ID: ', doc_ref.id)
        docId = doc_ref.id

         # set object and push to firebase
        doc_ref.set({
                u'property_id': docId,
                u'property_address': address,
                u'number_of_beds': number_beds,
                u'number_of_baths': number_baths,
                u'property_rent': property_price,
                u'post_code': postcode,
                u'property_photo': property_image,
            })

An examples of this is that the id of the document is: 'aMqwOsjDbOuQmi8PZmot' but the 'property_id' value comes out as: 'YU1xd09zak...' Anybody know why this sort of behaviour is happening?
Answer: This is happening because you are generating a random id twice.
doc_ref = db.collection(u'prime_location').document()
        print('ID: ', doc_ref.id) //generates one id
        docId = doc_ref.id //generates the second id

To solve this, you sould generate a single id by calling doc_ref.id only once, like in the following lines of code:
doc_ref = db.collection(u'prime_location').document()
        docId = doc_ref.id //generates id
        print('ID: ', docId) //print the generatd id

And then further in your code simply use the docId variable and not doc_ref.id which will generate another id each time is called.


Is there any difference between p.class-name and p[class=class-name]?

Question: Like in title I have a question about css selectors.  Is there any difference between p.class-name and p[class=class-name]? Which is more preferable to use?
Answer: Yes, p[class=class-name] works only if the class attribute is exactly "class-name". Like

But the class attribute can contain more than one class. For example,

has two classes, class-name and other-class-name and can be matched by p.class-name, but not by p[class=class-name].
So the answer to what is more preferable depends on your use case.


How do you determine the significance of individual deviations in categories?

Question: I have observations from human observers that were intended to place subjects into one of four categories (A-D).
In fact, there are 100 subjects in each category. So in an ideal world there should be "100" in each category.
            |  A  |  B  |  C  |  D
Observation | 87  | 110 | 101 | 102
'Ideal'     | 100 | 100 | 100 | 100

If I wanted to know whether the observations as a whole are statistically significantly different from the ideal case, I would do a Chi-Square test.
But which test can tell me whether the observations for a particular category differ significantly? For example, is the value "87" (category A) significantly different?
Comment: Try looking at the individual components of the test, the four things which add to the final chi-squared
Answer: Chi-squared test. It seems you want to see whether results are consistent with
1/4 of the subjects being put into each of 4 categories.
(If you were vetting a die to see if it is fair, you might
roll it 600 times to see if you got nearly 100 counts for each face.)
In R, the chi-squared test goes as shown below. It shows no evidence
to reject the null hypothesis that categories are equally likely:
P-value far above 0.05.
chisq.test(c(87,110,101,102))

        Chi-squared test for given probabilities

data:  c(87, 110, 101, 102)
X-squared = 2.74, df = 3, p-value = 0.4335

Notes: (a) Given this result, it is not appropriate to check whether
each individual category has counts consistent with 1/4.
(b) If no probability vector is supplied, then the 'given probabilities'
are assumed to be equal.
(c) The 'expected counts' used in this chi-squared test are
as follows. Strictly speaking, they are not part of your data table.
chisq.test(c(87,110,101,102))$exp
[1] 100 100 100 100

Binomial test. If you had doubts before seeing the data whether Category A would be
chosen 1/4 of the time, you could have done a binomial test just for Category A, as
shown below. Again, the result is not significant.
binom.test(87,400, 1/4)

        Exact binomial test

data:  87 and 400
number of successes = 87, number of trials = 400,
  p-value = 0.1487
alternative hypothesis:
  true probability of success is not equal to 0.25
95 percent confidence interval:
 0.1780405 0.2611969
sample estimates:
probability of success
                0.2175

However, to be clear, it is not appropriate
to do the binomial test as an 'ad hoc' test to the non-significant chi-squared  test.
Simulation as 'reality check'. Below are four simulated versions of your experiment, in which it is known that categories 1 through 4 are chosen with equal probability. From this brief simulation, it seems that counts as low as 87 in one of the four categories are not especially rare.
set.seed(2020)
x = sample(1:4, 400, rep=T); table(x)
x
  1   2   3   4
111  83 107  99
x = sample(1:4, 400, rep=T); table(x)
x
  1   2   3   4
 93 109  96 102
x = sample(1:4, 400, rep=T); table(x)
x
  1   2   3   4
103 117  94  86
x = sample(1:4, 400, rep=T); table(x)
x
  1   2   3   4
100 101 100  99

In a simulation of 100,000 such experiments, the smallest category
count was $\le 87$ more than a quarter of the time.
set.seed(701)
min.ct = replicate(10^5,
                   min(tabulate(sample(1:4, 400, rep=T))))
mean(min.ct <= 87)
[1] 0.28186


Shade a subset of a sphere's surface in MATLAB

Question: I'm attempting to generate a plot of a hemisphere with a shaded area on the surface bound by max/min values of elevation and azimuth.  Essentially I'm trying to reproduce this:

Generating the hemisphere is easy enough, but past that I'm stumped.  Any ideas?
Here's the code I used to generate this sphere:
[x,y,z] = sphere;
x = x(11:end,:);
y = y(11:end,:);
z = z(11:end,:);
r = 90;
surf(r.*x,r.*y,r.*z,'FaceColor','yellow','FaceAlpha',0.5);
axis equal;

Comment: Do you have some code that you used to generate the hemisphere?  Depending on how you generated the hemisphere, we can then figure out how to subset it and colour it accordingly
Comment: Certainly,[x,y,z] = sphere;
x = x(11:end,:);y = y(11:end,:);
z = z(11:end,:);
r = 90;
surf(r.*x,r.*y,r.*z,'FaceColor','yellow','FaceAlpha',0.5);
axis equal;
Comment: A general way of rendering a pattern on a surface can be found here: http://stackoverflow.com/a/23900282/2777181
Comment: I have an answer for you that'll help you restrict your space using the azimuth and elevation.  Give me a few minutes
Answer: If you want to highlight a certain area of your hemisphere, first you decide the minimum and maximum azimuth (horizontal sweep) and elevation (vertical sweep) angles.  Once you do this, take your x,y,z co-ordinates and convert them into their corresponding angles in spherical co-ordinates.  Once you do that, you can then subset your x,y,z co-ordinates based on these angles.  To convert from Cartesian to spherical, you would thus do:

Source: Wikipedia
theta is your elevation while phi is your azimuth.  r would be the radius of the sphere.  Because sphere generates co-ordinates for a unit sphere, r = 1.  Therefore, to calculate the angles, we simply need to do:
theta = acosd(z);
phi = atan2d(y, x);

Take note that the elevation / theta is restricted 0 to 180 degrees, while the azimuth / phi is restricted between -180 to 180 degrees.  Because you're only creating half of a sphere, the elevation should simply vary from 0 to 90 degrees.  Also note that acosd and atan2d return the result in degrees.  Now that we're here, you just have to subset what part of the sphere you want to draw.  For example, let's say we wanted to restrict the sphere such that the min. and max. azimuth span from -90 to 90 degrees while the elevation only spans from 0 to 45 degrees.  As such, let's find those x,y,z co-ordinates that satisfy these constraints, and ensure that anything outside of this range is set to NaN so that these points aren't drawn on the sphere.  As such:
%// Change your ranges here
minAzimuth = -90;
maxAzimuth = 90;
minElevation = 0;
maxElevation = 45;

%// Compute angles - assuming that you have already run the code for sphere
%// [x,y,z] = sphere;
%// x = x(11:end,:);
%// y = y(11:end,:);
%// z = z(11:end,:);
theta = acosd(z);
phi = atan2d(y, x);

%%%%%// Begin highlighting logic
ind = (phi >= minAzimuth & phi <= maxAzimuth) & ...
      (theta >= minElevation & theta <= maxElevation); % // Find those indices
x2 = x; y2 = y; z2 = z; %// Make a copy of the sphere co-ordinates
x2(~ind) = NaN; y2(~ind) = NaN; z2(~ind) = NaN; %// Set those out of bounds to NaN

%%%%%// Draw our original sphere and then the region we want on top
r = 90;
surf(r.*x,r.*y,r.*z,'FaceColor','white','FaceAlpha',0.5); %// Base sphere
hold on;
surf(r.*x2,r.*y2,r.*z2,'FaceColor','red'); %// Highlighted portion
axis equal;
view(40,40); %// Adjust viewing angle for better view

... and this is what I get:

I've made the code modular so that all you have to do is change the four variables that are defined at the beginning of the code, and the output will highlight that desired part of the hemisphere that are bounded by those min and max ranges.

Hope this helps!
Comment: Thanks very much, that's a great jumping off point for me messing with it.
Comment: @Baconfish - I've made the code more modular so all you have to do is vary the first four lines of the code and the portion of the sphere should highlight according to those min and max ranges.
Answer: One option is to create an array with the corresponding color you want to attribute to each point.
A minimal example (use trigonometry to convert your azimuth and elevation to logical conditions on x, y, and z):
c=(y>0).*(x>0).*(z>0.1).*(z<0.5);
c(c==0)=NaN;
surf(r.*x,r.*y,r.*z,c ,'FaceAlpha',0.5); axis equal;

yields this:

Note: this only works with the resolution of the grid. (i.e each 'patch' of the surface can have a different color). To exactly reproduce your plot, you might want to superpose the grid sphere with another one that has a much larger number of grid points on which you apply the above code.


How to prove that this map is not a quotient map

Question: This question was aksed in my topology quiz and I was unable to solve it.

Let $X=\bigcup_{n\in \mathbb{N}} (\mathbb{R} \times \{n\})$ and let $Y = \bigcup_{n\in \mathbb{N}} \{(x,y)\in \mathbb{R}^2 : y=nx\}$. Suppose both $X$ and $Y$ have the subspace topology induced by usual topology on $\mathbb{R}^2$. Define $p:X \to Y$ by $p((x,n))=(x,nx)$ for each $(x,n)\in X$.
Show that $p$ is not a quotient map.

I have proved the map to be surjective but I am not able to get an idea on how to obtain acontradiction if the map is assumed to be quotient map.
Kindly help me.
Comment: I think you have a typo, what is meant by $\mathbb{R}\times n$?
Comment: @Rdrr I thought it was understandable but i made the edit
Comment: This is a duplicate of https://math.stackexchange.com/q/3680908.
Answer: Notice that $p$ is almost a bijection: it sends all of the points $\langle 0,n\rangle$ to $\langle 0,0\rangle$, but everywhere else it's bijective. Thus, the place to look for problems is around $\langle 0,0\rangle$. What if we can find a sequence $\langle y_n:n\in\Bbb Z^+\rangle$ in $Y$ that converges to the origin and has just one point on each line $y=nx$? Then $\{y_n:n\in\Bbb Z^+\}$ won't be closed in $Y$, because it's missing the limit point $\langle 0,0\rangle$, but its preimage under $p$ will have just one point on each line $\Bbb R\times\{n\}$ and will be closed. If $p$ were a quotient map, this would be impossible: $p^{-1}[C]$ would be closed in $X$ if and only if $C$ were closed in $Y$.
Since we want the sequence to have just one point on each line $\Bbb R\times\{n\}$, we must have $y_n=p(\langle x_n,n\rangle)$ for some $x_n\in\Bbb R$, so that $y_n=\langle x_n,nx_n\rangle$. If these points are to converge to $\langle 0,0\rangle$ in $Y$, clearly the points $x_n$ must converge to $0$ in $\Bbb R$, and they must do so fast enough that the points $nx_n$ also converge to $0$ in $\Bbb R$. An easy way to ensure this is to let $x_n=\frac1{n^2}$, so that $nx_n=\frac1n$. Then

the set $A=\left\{\left\langle\frac1{n^2},\frac1n\right\rangle:n\in\Bbb Z^+\right\}$ is not closed in $Y$, since it has $\langle 0,0\rangle$ as a limit point, but
the set $p^{-1}[A]=\left\{\left\langle\frac1{n^2},n\right\rangle:n\in\Bbb Z^+\right\}$ is closed in $X$.


Confusion on ROC-AUC curve's statistical understanding

Question: I have no trouble understanding the definition of the TP, FP, TN, and FN, along with precision, recall, sensitivity, and the likes. I also understand that ROC-AUC is a graph that plots True Positive Rate against False Positive Rate, parametrized by a threshold of $T$. What I am confused about is depicted in the image below, we can clearly define the red line to be the positive class 1, and the green line to be the negative class 0, subsequently, the author mentioned (rephrased by me) that the green curve shows the distribution of the positive class and the red curve shows the distribution of negative class over the probability assigned to each obs by the classifier under a threshold of $T=0.5$.
Now I am not good in statistics, and by distribution, does the author mean the original distribution of the sample, or the distribution after the classifier predicts? In other words, assuming our ground truth data has 5 patients, and 2 is positive class, 3 is negative class; and our classifier outputs a softmax (preference) of probabilities like
y_preds = [[0.2, 0.8], [0.3, 0.7], [0.6, 0.4], [0.7, 0.3], [0.9, 0.1]]

Now since it's a binary problem, and by definition we should only look at the positive class's probabilities as the negative class's probabilities are derived automatically, the y_preds should be flattened to be:
y_preds = [0.8, 0.7, 0.4, 0.3, 0.1]

Back to out question, so is this graph depicting the distribution AFTER the classifier predicts, or before that? Furthermore, how is this graph plotted? Because to even be able to tell the FP and FN areas (the intersection), we definitely need to compare the predictions to the ground truth. Sorry if I did not make myself clear, but the graph is really throwing me off and would appreciate a more detailed explanation.

Edit 1:
Ok I got it. So there are 100 patients in total and assume 70 benign and 30 malignant as the ground truth labels. Are we trying to say that we individually look at the predictions made for each group, say plot all 70 benign patients predictions on the graph and 30 malignant predictions on the graph with a threshold of T=0.5. A perfect classifier will then have all 70 benign predictions having a probability of less than 0.5 while 30 malignant predictions having a probability of more than 0.5 - the graphs will not intersect.
But if just one patient in the benign group has a prediction probability of 0.8 - that will classify it as malignant in our model - hence there will be an intersection, am I right with the analogy.
To confirm, the author said that the x axis is actually P(X="positive class") but that's not the case here since it's both?
Comment: The first paragraph of your edit is correct for now. You'll go on to learn why accuracy is a surprisingly poor performance metric, but it's fine to discuss now. // The second paragraph contains a mistake. If the threshold is set at 0.5, then that 0.8 will misclassified, but there will be no overlap of the other group has all predicted probabilities $>0.8$. // That author is correct. This is a histogram of predicted probabilities of being in the positive class. You happen to know which samples truly belonged to each class, however.
Comment: And since you know the class to which each prediction belongs, you color-code the graph.
Comment: Dear Dave, the 0.8 is misclassified because the model predicted a benign patient as a malignant patient - this should contribute the false positive right? How then would the graph tell us that this 1 single patient is under the false positive area?
Comment: It's a green patient with a predicted probability over the threshold. That's how it's a false positive.
Comment: Thanks Dave for answering me patiently. I do have some solid background on deep learning in general. But did not really look into the metric details like ROC-AUC. It kinda of threw me off with the graph above. So the color coding is deliberate to indicate our ground truth in a way. Right?
Comment: That's exactly what the color means. To call something a false positive, you need both the classification and the truth. // Unrelated to ROC curves, when you make color-coded graphs, please keep in mind that red/green colorblindness is common enough to warrant a choice of different colors.
Answer:
Those are the probabilities predicted by the model. If you have a million patients in each group, you plot the million probabilities predicted for the red patients and the million probabilities predicted for the green patients.

To evaluate any model, we must compare to the true values. The patients in green are the ones who do not have cancer, and the patients in red do have cancer.
Comment: Thanks for the reply. I have some comments to ask. And I edited in the question as it's too long.


Cannot echo IF () into a text block I am creating in a batch file

Question: Am creating a batch file within a batch file and wanted to use the structure
(
echo line 1
…
) > test1.bat

This all worked good until I tried putting in an if statement.  The ending ")" of the if terminated the text block.  I even tried
set "_ascii=)"
echo %_ascii%

but it was expanded to ")" when echoed and the text block terminated. I don't see how to write the ")" to the batch file I am trying to create.
Sample code:  test.bat
(
echo set "VAR=1"
echo goto SkipOverFunctions
echo :foo
echo if %%VAR%% EQU 1 (
echo echo var is 1
echo exit /B 0
echo )
echo exit /B 1
echo :SkipOverFunctions
echo call foo
) > test1.bat

Answer: You can escape the literal parenthesis with ^ so it isn't parsed as the block terminator :
(
    echo line1
    echo (line2^)
    echo line3
) > output

An alternative would be to use the >> "append" redirection :
echo line1 > output
echo (line2) >> output
echo line3 >> output

Comment: the above works fine when parsing parenthesis in a block but I cannot get that escape too work with angle brackets as in (
^
^
) > test.xml  Going to put this on a separate question when I get a chance
Comment: @JosephStateson it's supposed to work : `echo >foo` writes to a file while `echo ^>foo` displays `>foo`. In general it is useful for the following characters: `& \ < > ^ |`. More infos [there](https://ss64.com/nt/syntax-esc.html)
Comment: I posted a better example of the problem. I did look at a lot of previous solutions but all I saw that worked used the echo mechanism https://stackoverflow.com/questions/58733164/is-way-to-escape-angle-brackets-in-a-text-block-directed-to-a-file


Singing notes aloud while playing a piece

Question: I started learning Piano around 4 months back, a month after I reached 50.
In spite of not enough practice and often missed sessions, my tutor says that I am making "decent" progress, for my age and inexperience of any instrument.
He's been pointing out that when I play those small meody pieces, I don't sing out the notes. I am finding it difficult. I sight read for the first few times with little effort and then it kind of gets in my memory. But I know that I tend to make occasionak mistakes while playing from memory. However, trying to sing out the notes, slows me down almost by half. Like if I have progressed to play a reasonably advanced (my novice standards) at 150 bpm, if I have to read and sing out the notes, then I will be at 80 and if I have to look at my finger and sing out, then I will be at 100. I feel frustrated!!
Am I doing it wrong? How important is it to read and sing the notes while playing melody?
Answer: This is standard for someone in your position, so don't fret!
In terms of practicing this technique, make sure you can do both tasks separately first. Once you can play the piece at 150bpm and sing the piece at 150bpm, only then should you try to do both tasks simultaneously. But you will almost certainly have to reduce the tempo, and often drastically (like your 80bpm example).
But as with most things, this task will become easier the more you do it.
As for "how important" this task is, it's tough to say without knowing your teacher's intent for asking you to do it. A few reasons:

To improve your singing ability
To improve your singing accuracy (i.e., if the pitches are correct)
To make sure you're aware of the melodic line to urge you to play this line as melodically and "songlike" as possible on the piano
As a means of score study, to make sure you know the separate contrapuntal lines
Etc.

For me personally, I think this is a very important task, and I'm glad to hear your teacher is assigning it, and that you're taking it seriously!
Answer: You don't say whether you are expected to actually sight sing. That's a different skill, and a good one to get better at. I doubt if your teacher is doing that, though, as you have enough on your plate already.
I'm a little sceptical about naming each and every note as you play. I don't believe it's the way people sight read anyway. Doing that makes a two stage job: Look at the note, recognise its name, find it on the piano, then play it. Once the first note has been established, if the next is one step higher, it really doesn't matter what its name is - just play the note one step above the last! Naming notes, then, to me, is somewhat academic, and I'm pretty sure that seasoned players do not think 'my next note will be an Eb' in the middle of playing.Even when they're sight reading.
And, it's not particularly helpful when faced with, say, a C followed by a G - going up or down. Yes, sing a G, say the name, but which one?
Try the sight singing as a separate entity for a while, preferrably before trying to play the piece. It'll take a lot of getting right, but it's a good skill. If it helps, sing the letter names, but more importantly, sing the melody, to lah or whatever.
The other aspect of sight reading is the duration of notes, so that needs addressing in a different way. Not in the question, so I'll leave it at that.


If $e^A $ is diagonal matrix. Show that $A $ is diagonal matrix.

Question: Let $A\in\mathcal {M}_n (\mathbb {R})$ diagonalizable matrix. We suppose that $e^A $ is diagonal matrix. Show that $A $ is diagonal matrix.
Hint : if $A$ and $B $ are diagonalizables matrix such that $e^A =e^B$ then $A=B $.
My effort Let $P\in GL_n {(\mathbb {R})}$ and $\lambda_i\in \mathbb {R} $ such that $D=diag (\lambda_1,...\lambda_2)$. Then $$D =P^{-1}AP$$ then $e^D=P^{-1}e^AP$.
Can we say that if $e^A $ is diagonal matrix then $e^A =e^D$?
Comment: You can't , and that's the problem with this approach. But you can do this : take the diagonal entries of $e^A$, prove that they are all positive (the eigenvalues of $e^A$ have to be positive, and for a diagonal matrix the eigenvalues lie along the diagonal). Now take $B$ as the diagonal matrix which has the $\ln$ of these eigenvalues on its diagonal. Then prove that $e^B = e^A$.
Comment: Is diagonal or is diagonalizable?
Answer: Not quite, only up to a permutation of the eigenvalues.
Perhaps a better way to formulate this is as follows: A diagonalizable matrix is diagonal in some basis if and only if it is an eigenbasis. So if $e^A$ is diagonal, then the standard basis is an eigenbasis of $e^A$. But eigenspaces of $A$ and $e^A$ are the same when $A$ is diagonalizable. So the standard basis is an eigenbasis of $A$, i.e. $A$ is diagonal.


How to use login and registration views in a single page?

Question: I am getting an issue. While using Login and Registration views in a single page.    When main view page loaded. I got an error pop up:
You are using dublicating email & password.
Dublicating email & password may lead to big mess.
Please note that it says dublicating not duplicating.
Have any one help me. My code is below.
My Modal is:
public class LoginViewModel {
   public string Email { get; set; }
   public string Password { get; set; }
}

public class RegisterViewModel {
   public string Email { get; set; }

   [DataType(DataType.Password)]
   public string Password { get; set; }
}

public class RegisterLoginViewModel
{
    public LoginViewModel LoginViewModel { get; set; }
    public RegisterViewModel RegisterViewModel { get; set; }
}

My Controller:
[AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        var model = new RegisterLoginViewModel();
        model.LoginViewModel = new LoginViewModel();
        model.RegisterViewModel = new RegisterViewModel();
        ViewBag.ReturnUrl = returnUrl;
        return View(model);
   }

Main View:
@model OpenOrderFramework.Models.RegisterLoginViewModel
@Html.Partial("_RegisterForm", Model.RegisterViewModel
      @Html.Partial("_LoginForm", Model.LoginViewModel)

Partial View _LoginForm:
 @model OpenOrderFramework.Models.LoginViewModel
    @using (Html.BeginForm("Login", "Account", FormMethod.Post))
{   @Html.TextBoxFor(x => x.Email)
    @Html.PasswordFor(x => x.Password)

    <input type="submit" value="Log In" />

}
Partial View _RegisterForm:
@model OpenOrderFramework.Models.RegisterViewModel

@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
    @Html.TextBoxFor(x => x.Email)
    @Html.PasswordFor(x => x.Password)

    <input type="submit" value="Register" />
}

Comment: Potentially related question: http://stackoverflow.com/questions/4902725/duplicate-input-ids-when-using-multiple-partials-in-asp-net-mvc
Answer: Have you tried to rename your properties Email and Password from either or both of the RegisterViewModel and LoginViewModel? It's possible that is causing the problem.


Setting a new users profile fields based on a form

Question: Users on my site all have a "home region" field. This profile field is saved for each user and used to customise various site features, so that the user gets shown local content.
These regions aren't states or cities - they're more like electorate / local council boundaries (I'm not really sure what the US analogy would be). Most users are going to be uncertain about which region they actually want to save to their user profile.
I have a form which allows users to either (A) explicitly select their region from a select dropdown or (B) enter their postcode, submit the form, and get back their region. This form works fine.
I want users to be able to pick a region at registration time using this form, and have that region saved to their profile. Ideally I'd like to integrate the "select region" form with the user_register form, so that they can submit the form, get told "you are part of X region" and then click "register" and create a new user account with that region.
What I'm doing is using hook_user() to insert my form elements, perform my extra validation and then try to save the region data to the user on submit.
EDIT: the below is roughly how I solved this
function mymodule_user($op, &$edit, &$account, $category = NULL) {
  /* add "select your region" functionality to the user edit form */
  $category = 'Regional information';
  switch ($op) {
    case 'register':
    case 'form':
        /* "register": The user account registration form is about to be displayed. The module should present the form elements it wishes to inject into the form. */
        /* "form": The user account edit form is about to be displayed. The module should present the form elements it wishes to inject into the form. */
        $form = array();
        $form['Regional information']['region'] = _region_select('', _region_select_options());
        $form['Regional information']['postcode'] = _postcode();
        return $form;
        break;
    case 'validate':
        /* "validate": The user account is about to be modified. The module should validate its custom additions to the user object, registering errors as necessary. */
        $region = $account['region'];
        $postcode = $account['postcode'];
        // form_set_error() if I need to
        break;
    case 'insert':
    case 'update':
        /* submit happens *before* the user account is saved - we want insert or update
           "insert": The user account is being added.
           "update": The user account is being changed.
           The module should save its custom additions to the user object into the database and set the saved fields to NULL in $edit. */
        $region_code = $edit['region'];
        $postcode = $edit['postcode'];
        if (!$region_code && $postcode) { // pull the region from the postcode
            ...
        }
        if ($region_code) {
            $region_term = taxonomy_get_term($region_code);
            $region_name = $region_term->name;
            /* the profile module wants the name of the region, not the id */
            $profile_edit = array( 'profile_region' => $region_name );
            profile_save_profile($profile_edit, $account, $category);
        }
        break;
  }
}

Answer: Do you think you could just make the select dropdown and postcode input box parts of the user_form? Looks like you've got the functionality working already, so it would be a matter of a simple module implementing the following hook:

hook_user(register) to alter the registration form and add your custom fields. You'll want to use a profile or profile_taxonomy functionality to insert the form element
hook_user(validate) to validate the user input (incorrect postcode etc.)
hook_user(submit) to convert the postcode to region and to save that information in the user profile
Comment: thanks, this sounds much simpler than how I was planning on doing things. I'll give this a try and let you know how it works out.
Comment: One think that makes it interesting is that the postcode form is potentially multistage - some postcodes are associated with multiple regions. I guess I've got to work out how to send the registration form back for another round.
Comment: It would be cool if you could to it in-place. Place a button next to the postcode input that would submit the current postcode and via AHAH replace the select drop down with only appropriate list of regions. Have a look at the [#ahah](http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/6#ahah) form control.
Comment: thanks Jan, finally got around to sitting down and working this out. Your suggestion worked great.


MCMC acceptance formula clarification

Question: Metropolis - Hastings : Data Science Concepts youtube shows the acceptance probability $A(a \rightarrow b)$ is $Max(1, \frac {f(b)}{f(a)})$.
Is it correct or it should have been $Min(1, \frac {f(b)}{f(a)})$?
Comment: A probability larger than one?! What's funny in that the Max gets interpreted as a Min on the final last two lines!!!
Answer: Yes, indeed. See, e.g., Wikipedia article on Metropolis-Hastings algorithm:
$$
A(x,x')=\min\left(1,\frac{P(x')}{P(x)}\frac{g(x|x')}{g(x'|x)}\right)$$
In practice one often simply generates a random number in interval $[0,1]$ and compares it to the ratio $P(x')/P(x)$ (assuming for simplicity that $g(x|x')=g(x'|x)$), which automatically takes into account the case when the ration is greater than unity. Yet, it may be useful to consider  this case separately, if generating random numbers is costly (when running very long simulations). Thus, in pseudocode below the condition skips the second part (what follows or), if $P(x')/P(x)>1$:
if $P(x') > P(x)$ or random_uniform(0,1) < P(x')/P(x):
    accept
else
    do not accept

Related post

MCMC acceptance formula clarification


Tail call optimization in Mathematica?

Question: While formulating an answer to another SO question, I came across some strange behaviour regarding tail recursion in Mathematica.
The Mathematica documentation hints that tail call optimization might be performed.  But my own experiments give conflicting results.  Contrast, for example, the following two expressions.  The first crashes the 7.0.1 kernel, presumably due to stack exhaustion:
(* warning: crashes the kernel! *)
Module[{f, n = 0},
  f[x_] := (n += 1; f[x + 1]);
  TimeConstrained[Block[{$RecursionLimit = Infinity}, f[0]], 300, n]
]

The second runs to completion, appearing to exploit tail call optimization to return a meaningful result:
Module[{f, n = 0},
  f[x_] := Null /; (n += 1; False);
  f[x_] := f[x + 1];
  TimeConstrained[Block[{$IterationLimit = Infinity}, f[0]], 300, n]
]

Both expressions define a tail recursive function f.  In the case of the first function, Mathematica apparently regards the presence of a compound statement enough to defeat any chance of tail call optimization.  Also note that the first expression is governed by $RecursionLimit and the second by $IterationLimit -- a sign that Mathematica is treating the two expressions differently.  (Note: the SO answer referenced above has a less contrived function that successfully exploits tail call optimization).
So, the question is: does anyone know the circumstances under which Mathematica performs tail-call optimization of recursive functions?  A reference to a definitive statement in the Mathematica documentation or other WRI material would be ideal.  Speculation is also welcome.
Comment: @Reb.Cabin I use `n` to count the number of calls.  In the first example, incrementing `n` directly blocked the tail call optimization. So, I moved `n+=1` into another definition -- but as a part of an always-false condition so that the definition is essentially a no-op (albeit with the side-effect of updating `n`).  I wrote `Null` as an arbitrary choice since the return value is never used.  It is possible to achieve the same result in a single definition: `f[x_] := f[x + 1] /; (++n; True)`.
Comment: @Reb.Cabin Because `Fold` is built into the kernel, my suspicion is that it is implemented as a simple imperative loop written in C -- especially since C compilers rarely perform tail call optimization.  But if it _is_ implemented recursively, I agree that it must be optimized.  `FoldList` does not overrun the stack but rather runs out of memory because it keeps a copy of the results from every iteration.  Which is probably a lot of data long before 96 hours :)
Comment: I find the `Null /;` condition mysterious. Would you be so kind as to explain the desired effect and how it achieves that effect? What happens if you leave it off?
Comment: I have a very long-running MMA program going right now. It runs for six to ninety-six hours at a time, delivering results at the end. I use `Fold` for iteration. I presume `Fold` does the equivalent of tail-calling, i.e., replacing the values of accumulation variables instead of accumulating them. My presumption is bolstered by the fact that if I use `FoldList` or if I `Sow` out the intermediate results, I run out of memory. It definitely does something different via `Fold`.
Answer: I can summarize the conclusions I was led to by my personal experience, with a disclaimer that what follows may not be the entirely right explanation. The anwer seems to lie in the differences between Mathematica call stack and traditional call stacks, which originates from Mathematica pattern-defined functions being really rules. So, there are no real function calls. Mathematica needs a stack for a different reason: since normal evaluation happens from the bottom of an expression tree, it must keep intermediate expressions in case when deeper and deeper parts of (sub)expressions get replaced as a result of rule application (some parts of an expression grow from the bottom). This is the case, in particular, for rules defining what we'd call non tail-recursive functions in other languages. So, once again, the stack in Mathematica is a stack of intermediate expressions, not function calls.
This means that if, as a result of rule application, an (sub)expression can be rewritten in its entirety, the expression branch need not be kept on the expression stack. This is probably what is referred as tail call optimization in Mathematica - and this is why in such cases we have iteration rather than recursion (this is one very good example of the differences between rule applications and function calls). Rules like f[x_]:=f[x+1] are of this type. If, however, some sub-expression get rewritten, producing more expression structure, then expression must be stored on the stack. The rule f[x_ /; x < 5] := (n += 1; f[x + 1]) is of this type, which is a bit hidden until we recall that ()stand for CompoundExpression[].  Schematically what happens here is f[1] -> CompoundExpression[n+=1, f[2]] -> CompoundExpression[n+=1,CompoundExpression[n+=1,f[3]]]->etc. Even though the call to f is the last every time, it happens before the full CompoundExpression[] executes, so this still must be kept on the expression stack. One could perhaps argue that this is a place where optimization could be made, to make an exception for CompoundExpression, but this is probably not easy to implement.
Now, to illustrate the stack accumulation process which I schematically described above, let us limit the number of recursive calls:
Clear[n, f, ff, fff];
n = 0;
f[x_ /; x < 5] := (n += 1; f[x + 1]);

ff[x_] := Null /; (n += 1; False);
ff[x_ /; x < 5] := ff[x + 1];

fff[x_ /; x < 5] := ce[n += 1, fff[x + 1]];

Tracing the evaluation:
In[57]:= Trace[f[1],f]
Out[57]= {f[1],n+=1;f[1+1],{f[2],n+=1;f[2+1],{f[3],n+=1;f[3+1],{f[4],n+=1;f[4+1]}}}}

In[58]:= Trace[ff[1],ff]
Out[58]= {ff[1],ff[1+1],ff[2],ff[2+1],ff[3],ff[3+1],ff[4],ff[4+1],ff[5]}

In[59]:= Trace[fff[1],fff]
Out[59]= {fff[1],ce[n+=1,fff[1+1]],{fff[2],ce[n+=1,fff[2+1]],{fff[3],ce[n+=1,fff[3+1]],
{fff[4],ce[n+=1,fff[4+1]]}}}}

What you can see from this is that the expression  stack accumulates for f and fff (the latter used just to show that this is a general mechanism, with ce[] just some arbitrary head), but not for ff, because, for the purposes of pattern matching, the first definition for ff is a rule tried but not matched, and the second definition rewrites ff[arg_] in its entirety, and does not generate deeper sub-parts that need further rewriting. So, the bottom line seems that you should analyze your function and see if its recursive calls will grow the evaluated expression from the bottom or not. If yes, it is not tail-recursive as far as Mathematica is concerned.
My answer would not be complete without showing how to do the tail call optimization manually. As an example, let us consider recursive implementation of Select. We will work with Mathematica linked lists to make it reasonably efficient rather than a toy. Below is the code for the non tail-recursive implementation:
Clear[toLinkedList, test, selrecBad, sel, selrec, selTR]
toLinkedList[x_List] := Fold[{#2, #1} &, {}, Reverse[x]];
selrecBad[fst_?test, rest_List] := {fst,If[rest === {}, {}, selrecBad @@ rest]};
selrecBad[fst_, rest_List] := If[rest === {}, {}, selrecBad @@ rest];
sel[x_List, testF_] := Block[{test = testF}, Flatten[selrecBad @@ toLinkedList[x]]]

The reason I use Block and selrecBad is to make it easier to use Trace. Now, this blows the stack on my machine:
Block[{$RecursionLimit = Infinity}, sel[Range[300000], EvenQ]] // Short // Timing

You can trace on small lists to see why:
In[7]:= Trace[sel[Range[5],OddQ],selrecBad]

Out[7]= {{{selrecBad[1,{2,{3,{4,{5,{}}}}}],{1,If[{2,{3,{4,{5,{}}}}}==={},{},selrecBad@@{2,{3,{4,
{5,{}}}}}]},{selrecBad[2,{3,{4,{5,{}}}}],If[{3,{4,{5,{}}}}==={},{},selrecBad@@{3,{4,{5,
{}}}}],selrecBad[3,{4,{5,{}}}],{3,If[{4,{5,{}}}==={},{},selrecBad@@{4,{5,{}}}]},{selrecBad[4,
{5,{}}],If[{5,{}}==={},{},selrecBad@@{5,{}}],selrecBad[5,{}],{5,If[{}==={},{},selrecBad@@{}]}}}}}}

What happens is that the result gets accumulated deeper and deeper in the list. The solution is to not grow the depth of the resulting expression, and one way to achieve that is to make selrecBad accept one extra parameter, which is the (linked) list of accumulated results:
selrec[{fst_?test, rest_List}, accum_List] :=
    If[rest === {}, {accum, fst}, selrec[rest, {accum, fst}]];
selrec[{fst_, rest_List}, accum_List] :=
    If[rest === {}, accum, selrec[rest, accum]]

And modify the main function accordingly:
selTR[x_List, testF_] := Block[{test = testF}, Flatten[selrec[toLinkedList[x], {}]]]

This will pass our power test just fine:
In[14]:= Block[{$IterationLimit= Infinity},selTR[Range[300000],EvenQ]]//Short//Timing

Out[14]= {0.813,{2,4,6,8,10,12,14,16,18,20,
<<149981>>,299984,299986,299988,299990,299992,299994,299996,299998,300000}}

(note that here we had to modify $IterationLimit, which is a good sign). And using Trace reveals the reason:
In[15]:= Trace[selTR[Range[5],OddQ],selrec]

Out[15]= {{{selrec[{1,{2,{3,{4,{5,{}}}}}},{}],If[{2,{3,{4,{5,{}}}}}==={},{{},1},selrec[{2,{3,{4,
{5,{}}}}},{{},1}]],selrec[{2,{3,{4,{5,{}}}}},{{},1}],If[{3,{4,{5,{}}}}==={},{{},1},selrec[{3,
{4,{5,{}}}},{{},1}]],selrec[{3,{4,{5,{}}}},{{},1}],If[{4,{5,{}}}==={},{{{},1},3},selrec[{4,
{5,{}}},{{{},1},3}]],selrec[{4,{5,{}}},{{{},1},3}],If[{5,{}}==={},{{{},1},3},selrec[{5,
{}},{{{},1},3}]],selrec[{5,{}},{{{},1},3}],If[{}==={},{{{{},1},3},5},selrec[{},{{{{},1},3},5}]]}}}

which is, this version does not accumulate the depth of the intermediate expression, since the results are kept in a separate list.
Comment: +1 very nice analysis.  I agree that CompoundExpression is a candidate for optimization although I was able to contrive a situation where a subexpression added definitions to CompoundExpression, changing its semantics (which the optimization would thwart).  Emphasis on "contrive" -- I'm not sure it would be an issue in practice.
Comment: Excellent explanation! Now the difference between `$RecursionLimit` and `$IterationLimit` become clear. And what is the `stack` has become significantly clearer.
Answer: The idea of this answer is to replace the brackets () by a wrapper that does not make our expressions grow. Note that the function we are finding an alternative for is really CompoundExpression, as the OP was correct in remarking this function was ruining the tail recursion (see also the answer by Leonid). Two solutions are provided. This defines the first wrapper
SetAttributes[wrapper, HoldRest];
wrapper[first_, fin_] := fin
wrapper[first_, rest__] := wrapper[rest]

We then have that
Clear[f]
k = 0;
mmm = 1000;
f[n_ /; n < mmm] := wrapper[k += n, f[n + 1]];
f[mmm] := k + mmm
Block[{$IterationLimit = Infinity}, f[0]]

Correctly calculates Total[Range[1000]].
------Note-----
Note that it would be misleading to set
wrapper[fin_] := fin;

As in the case
f[x_]:= wrapper[f[x+1]]

Tail recursion does not occur (because of the fact that wrapper, having HoldRest, will evaluate the singular argument before applying the rule associated with wrapper[fin_]).
Then again, the definition above for f is not useful, as one could simply write
f[x_]:= f[x+1]

And have the desired tail recursion.
------Another note-----
In case we supply the wrapper with a lot arguments, it may be slower than necessary. The user may opt to write
f[x_]:=wrapper[g1;g2;g3;g4;g5;g6;g7  , f[x+1]]

Second wrapper
The second wrapper feeds its arguments to CompoundExpression and will therefore be faster than the first wrapper if many arguments are provided. This defines the second wrapper.
SetAttributes[holdLastWrapper, HoldAll]
holdLastWrapper[fin_] := fin
holdLastWrapper[other_, fin_] :=
 Function[Null, #2, HoldRest][other, fin]
holdLastWrapper[others__, fin_] :=
 holdLastWrapper[
  Evaluate[CompoundExpression[others, Unevaluated[Sequence[]]]], fin]

Note: Returning (empty) Sequences might be very useful in recursion in general. See also my answer here
https://mathematica.stackexchange.com/questions/18949/how-can-i-return-a-sequence
Note that this function will still work if only one argument is provided, as it has attribute HoldAll rather than HoldRest, so that setting
f[x]:= holdLastWrapper[f[x+1]]

Will yield a tail recursion (wrapper does not have this behavior).
Speed comparison
Let's create a nice long list (actually an expression with Head Hold) of instructions
nnnn = 1000;
incrHeld =
  Prepend[DeleteCases[Hold @@ ConstantArray[Hold[c++], nnnn],
    Hold, {2, Infinity}, Heads -> True], Unevaluated[c = 0]];

For these instructions, we can compare the performance (and outcome) of our wrappers with CompoundExpression
holdLastWrapper @@ incrHeld // Timing
CompoundExpression @@ incrHeld // Timing
wrapper @@ incrHeld // Timing

--> {{0.000856, 999}, {0.000783, 999}, {0.023752, 999}}
Conclusion
The second wrapper is better if you are not exactly sure when tail recursion will happen or how many arguments you will feed to the wrapper. If you are intent on feeding the wrapper 2 arguments, for example in the case where you realize all the second wrapper does is feed to CompoundExpression and you decide to do this yourself, the first wrapper is better.
-----final note----
In CompoundExpression[args, Unevaluated[expr]], expr still gets evaluated before CompoundExpression is stripped, so solutions of this type are no use.
Comment: @Leonid Shifrin I wonder what tail recursion means if a function calls itself more than once in its body, as in this case it seems necessary to put on the stack that we have to return to the original function call. Looking into it :).
Comment: Looks nice! Would be also nice to take care of `Module`, `With` and `Block` possibly present on the top-level of the r.h.s. of the recusrive definition, more or less automatically. I think @Rojo mentioned that he had a solution using Trott-Strzebonski technique, but I did not have the time to carefully look at it. Having that, one could construct custom assignment operator which would automatically make the wide class of recursive functions tail-recursive. That would be really nice.
Comment: This is very nice! +1. This seems to solve the problem for `CompoundExpression`. In many cases, however, this is not enough, e.g.for such one `f[x_]:={f[x-1],f[x-2]}` - where the container surrounding the calls is not `CompoundExpression` (but, e.g., `List`). Still,this is a very nice achievement, it seems. I have to test more, but right now it seems to be the solution for `CompoundExpression`. In some sense, this is similar to what I did, since it splits this into two rules - but your solution is general. If / when we test and become convinced that it generally works, it would make ...
Comment: ... sense to ask the question like 'programmatic tools for automatic tail-call optimization' and put your suggestion as one of the answers. I also vaguely remember that @Rojo had some method of tail call optimization, based on Trott-Strzebonski technique.
Comment: @Leonid Shifrin Woohoo :). Thank you. I am very interested in looking into these things further. I will also look at the Trott-Strzebonski technique, as yesterday and today I learned a lot by following the trail you laid out :).
Comment: My understanding is that in this case (more than one call in the body), the function can not be made tail-recursive,unless rewritten in such as way that there is only one call. I think that tail-recursion makes more sense when we are working with (perhaps very large) linked lists, so that we convert recursion to interation. When you have multiple calls which you can't seem to be able to avoid, this may be a sign that you need to build a tree. But in a tree, typically, recursion depth is not very big of a problem, since it is typically ~ `Log[n]`, where `n` is a total number of elements in ...
Comment: ... a tree, so for balanced trees, this quantity should never become too large.
Comment: @Leonid Shifrin discussing matters with Rojo lead to many nicer forms of the function. I have edited the answer to show one example. Rojo also had some non-recursive ideas making use of Condition. Note that the wrapper[fin_] := fin statement will often not be necessary.
Comment: Once you guys get something reasonably general and tested, it may make sense to post a self-answered question, describing your findings. I would participate if I have time, but currently I am under a ton of other things alas. But I would certainly appreciate being updated on your progress here.
Comment: @LeonidShifrin I've made a bunch of updates! I am thinking of making a quirky implementation of MergeSort, so quite likely I will spend some more time on the subject and can do additional testing. However, I am quite sure I have a good idea how things work now and that the functions work (unless I made a type in the last edit ;) ).
Comment: @LeonidShifrin I would be interested in looking further at those cases. I've also been looking at whether or not a great number of arguments will slow down Mathematica. I've made a beast of a function using which you can evaluate arguments in batches, where the batch size is customizable. Some problems with Partition and other functions which do not behave exactly as I want (they tend to evaluate things) caused to code to be slower than CompoundExpression. I think I will make a self answered question about that too, but maybe you can tell me if you know more about the subject first.
Comment: The function is itself a decent example of tail recursion. Though this can be a bit obscure because $RecursionLimit may be reached due to the deep nesting of linkedlists.
Comment: Do you mean some new function which you did not publish yet, or is it the one currently posted in your answer? Alas, I have zero free time for the rest of today, and probably also very little time tomorrow. So, perhaps you could discuss with someone else (@Rojo?), if you need some more eye on this right now. I will try to catch up with this in a couple of days.

Tail call optimization in Mathematica?