Show that this sequence of events is independent (b-adic expansions)

Question: The exercise reads:
Let $\Omega:=[0,1[$, $\mathcal{A}:=\Omega\cap \mathcal{B}(\mathbb{R})$ and $P:=\lambda_{\Omega}$ (Lebesgue measure on $\Omega$). Let $b\in\mathbb{N}$ with $b\geq 2$ and $\varepsilon \in \{0,\dots,b-1\}$. For each $n\in \mathbb{N}$ let
$$A_n:=\bigcup_{k=0}^{b^{n-1}-1}\bigg[ \frac{kb+\varepsilon}{b^n}, \frac{kb+\varepsilon+1}{b^n} \bigg[$$
Show that this sequence of events is independent by showing that
$$P(A_{i_1}\cap \dots \cap A_{i_n})=\frac{1}{b}P(A_{i_1}\cap \dots \cap A_{i_{n-1}}) \hspace{1cm}  $$ for every finite set of distinct natural numbers $i_1,\dots,i_n$.
A few examples convinced me that this is true but how to prove it? Any ideas how to proceed?
Thanks a lot for your help.
Comment: What is $\varepsilon$?
Comment: @LostStatistician Sorry I forgot to mention $\varepsilon$ is an integer between $0$ and $b-1$.
Answer: I add a bit of notation to write
$$
A_{i, \varepsilon} = \cup_{k=0}^{b^{i-1}-1} \left[ \frac{kb+\varepsilon}{b^i},\frac{kb+\varepsilon+1}{b^i} \right) =: \cup_{k=0}^{b^{i-1}-1} A_{i,\varepsilon}^{(k)}.
$$
Evidently
$$
P(A_{i,\varepsilon} ) = \sum_{i=0}^{b^{i-1}-1} \frac{1}{b^i} = \frac{1}{b},
$$
for each $i$. We also see that for each $i$,
$$
\cup_{\varepsilon=1}^{b-1} A_{i,\varepsilon}= [0,1).
$$
Now fix $\varepsilon_0 \in \{0,...,b-1\}$. We wish to show that for all natural numbers $i_1< \cdots < i_n$
$$
P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_n,\varepsilon_0}) = \frac{1}{b}P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0}).
$$
According to the above
$$
P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0}) = \sum_{\varepsilon=0}^{b-1} P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0} \cap A_{i_{n},\varepsilon} )
$$
Now the aim is to show that
$P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0} \cap A_{i_{n},\varepsilon} )  = P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0} \cap A_{i_{n},\varepsilon'} ) $ for all $\varepsilon,\varepsilon'$. The reason this holds is that for $j > i$, either
$$\cup_{\varepsilon=0}^{b-1} A_{j,\varepsilon}^{(r)} \subset A_{i,\varepsilon'}^{(k)}$$
or
$$
\left[ \cup_{\varepsilon=0}^{b-1} A_{j,\varepsilon}^{(r)}\right] \cap A_{i,\varepsilon'}^{(k)} = \emptyset.
$$
This is a straightforward calculation, and also describes the essence of why this result is true-- the intervals are $A_{j,\varepsilon}^{(r)}$ are nested and maintain their relative size within eachother for increasing $j$. Notice that this implies that for any $\varepsilon$, $P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0} \cap A_{i_{n},\varepsilon} )$ reduces down to a sum of the probabilities of intervals of the form $A_{i_n,\varepsilon}^{(k)}$, namely the sum over those intervals that intersect $ A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0}$. Since those by the above must coincide in a 1-1 correspondence with the intervals $A_{i_n,\varepsilon'}^{(k)}$ for all other $\varepsilon' \in \{0,...,b-1\}$ that intersect $A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0}$, we must have
$$P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0} \cap A_{i_{n},\varepsilon} )  = P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0} \cap A_{i_{n},\varepsilon'} ) $$
as needed. Hence
$$
P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0}) = b P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0} \cap A_{i_{n},\varepsilon_0} ).
$$
Comment: I followed until "The reason this holds is that..." I don't see why this proves the result $P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0} \cap A_{i_{n},\varepsilon} )  = P(A_{i_1,\varepsilon_0}\cap \cdots \cap A_{i_{n-1},\varepsilon_0} \cap A_{i_{n},\varepsilon'} )$. Could you expand on that?
Comment: I added some more details. I'm not providing the details as to why you must have that all of the smallest intervals are either contained in or are disjoint from a larger interval-- but this is a fairly straightforward calculation.
Comment: I tried to understand why this dichotomy holds and I came up with the following argument below. What do you think?
Comment: Looks good! It again captures the main point that the intervals are nested and maintain their relative size within each other.
Answer: To show independence we may assume WLOG that $i_1< \dots<i_n$. For each $n$ consider the grid of points in $[0,1]$ defined by
$$P_n:=\bigg\{\frac{k}{b^n}:k=0,1,\dots,b^n\bigg\}$$
We see that $P_{n}\subset P_{n+1}$, i.e. the grids are getting finer when $n$ gets larger. Each grid $P_{n}$ determines a set of $b^n$ half-open disjoint intervals in $[0,1)$ of the form $I^k_n=[\frac{k}{b^n},\frac{k+1}{b^n})$ $k=0,1,\dots,b^n-1$. If we divide these intervals into $b^{n-1}$ disjoint groups of $b$ intervals from left to right, then we see that $A_n$ is formed by selecting the $(\varepsilon+1)$th interval  in each group. Hence each $A_n$ is the disjoint union of $b^{n-1}$ intervals of length $1/b^n$, and therefore has measure $1/b$.
What happens if we intersect $A_{i_1}$ and $A_{i_2}$ with $i_1<i_2$? Each of the $b^{i_1-1}$ half-open intervals of $A_{i_1}$ will be sub-divided into $b^{i_2-i_1}$ half-open intervals by the points in $P_{i_2}$, and $A_{i_2}$ selects one interval per group of $b$ such sub-intervals. So the result is a disjoint union of $b^{i_1-1} \cdot b^{i_2-i_1-1}=b^{i_2-2}$ half-open intervals of the form $[\frac{k}{b^{i_2}},\frac{k+1}{b^{i_2}})$.
If we intersect $A_{i_1}\cap A_{i_2}$ with some $A_{i_3}$ with $i_1<i_2<i_3$, then the same reasoning gives that $A_{i_1}\cap A_{i_2}\cap A_{i_3}$ is a disjoint union of $b^{i_2-2} \cdot b^{i_3-i_2-1}=b^{i_3-3}$ half-open intervals of the form $[\frac{k}{b^{i_3}},\frac{k+1}{b^{i_3}})$.
Inductively we get that $A_{i_1}\cap \dots \cap A_{i_n}$ is a disjoint union of $b^{i_n-n}$ half-open intervals of the form $[\frac{k}{b^{i_n}},\frac{k+1}{b^{i_n}})$. Therefore the formula $$P(A_{i_1}\cap \dots \cap A_{i_n})=\frac{1}{b}P(A_{i_1}\cap \dots \cap A_{i_{n-1}}) $$ is verified for $i_1< \dots<i_n$. Then induction gives us independence.


Create solr_core for search_api_solr 4.x with docker solr 8

Question: I used to create my solr instance for drupal like this:
docker run -v $PWD/solrconf:/asdentcore  -e SOLR_JAVA_MEM="-Xms2G -Xmx2G" --restart unless-stopped  -p 8984:8983 -t --name asdentDevSolr -d solr:8.11
docker exec -it --user=solr asdentDevSolr  bin/solr create_core -c asdentcore -d /asdentcore

Where ./solrconf contains the files from modules/contrib/search_api_solr/solr-conf-templates/7.x.
With the new 4.x branch of search_api_solr (and 8.x contents) I get
ERROR: Error CREATEing SolrCore 'asdentcore': Unable to create core [asdentcore] Caused by: solr.ICUCollationField

I've already tried https://stackoverflow.com/questions/53161034/solr-error-unable-to-create-core-mycore-caused-by-solr-icucollationfield - didn't help.
Container logs shows the following errors:
Caused by: org.apache.solr.common.SolrException: Unable to create core [asdentcore]
Caused by: org.apache.solr.common.SolrException: Could not load conf for core asdentcore: Can't load schema /var/solr/data/asdentcore/conf/schema.xml: Plugin init failure for [schema.xml] fieldType "collated_de": Error loading class 'solr.ICUCollationField'
Caused by: org.apache.solr.common.SolrException: Can't load schema /var/solr/data/asdentcore/conf/schema.xml: Plugin init failure for [schema.xml] fieldType "collated_de": Error loading class 'solr.ICUCollationField'
Caused by: org.apache.solr.common.SolrException: Plugin init failure for [schema.xml] fieldType "collated_de": Error loading class 'solr.ICUCollationField'
Caused by: org.apache.solr.common.SolrException: Error loading class 'solr.ICUCollationField'
Caused by: java.lang.ClassNotFoundException: solr.ICUCollationField

Comment: Never had an issue like this. Can you actually verify the container directory is mounted and accessible to the container user at that location?
Comment: Yes, I did, it's accessible. I'll add the java errors to my question.
Comment: Also, if I set up the solr as usual with the 7.x templates till it works, then bash into the container and copy over the new conf/* files downloaded via search-api UI to /var/solr/data/asdentcore/conf - the server breaks with java.lang.ClassNotFoundException: solr.ICUCollationField - bah that's sooo bad...
Comment: Is that container missing those files?
Comment: Which one? Yes, the classes I'd suppose.
Comment: https://www.drupal.org/project/search_api_solr/issues/3181819#comment-13899895
Answer: Kudos to Kevin. The solution is
here https://stackoverflow.com/questions/62652640/error-when-initializing-solr-core-error-loading-class-solr-icucollationfield
and here https://www.drupal.org/project/search_api_solr/issues/3181819#comment-13899895
I had to replace in the downloaded solrcore.properties the line solr.install.dir=../../.. with solr.install.dir=/opt/solr.
One day of my live ...


Can I do skewness on multiple standard deviation?

Question: I have a 1000 sample of an electrical test at each 4 different time, so I do simple descriptive statistic to obtain standard deviation at each 4 different time. Can I then use skewness on standard deviation itself to know if all my standard deviation is symmetrical? From my search, I only see people choose either one as a measure, not in a way that use both as I intended.
My idea is I want to see if the dispersion itself has any changes. I know ANOVA or F-test is another method can be considered by checking equality of variance, but it seem quite complex for technician to implement.
Answer: Welcome to the site. While you can certainly calculate the skewness of four numbers (whatever they may be, including standard deviations) with only four numbers you aren't going to get reliable estimates.
It's also not clear why you  want to know if the sds of the different samples are symmetric. You say you "want to see if the dispersion itself has any changes".  Skewness will not tell you that.
You could just look at the four numbers and try and see if there is a pattern. You could make a graph to help.  And, while you could try to model the change in SD using regression with SD as the DV and time as the IV, with only four values, you are, again, going to have unreliable estimates.
Even the usual test with ANOVA isn't very good. There's a quote that I only vaguely remember, something like "checking the equality of variances with ANOVA is like sending out a rowboat to see if it safe to launch a ship" (maybe someone knows the exact quote).
As for being too complex for a technician ... Well, often, you have to hire a statistician. Just like you often have to hire a doctor, or a lawyer, or some other professional.
Comment: Your idea of putting the standard deviation sample into regression make me think possibility of analyzing by standard error or maybe by sample variance of the standard deviation. Is it possible?
Comment: I think you really need to hire a consultant, so that you can discuss, in detail, what you want. Not me, I'm retired.


popBackStack() after saveInstanceState()

Question: I'm running into an issue where I have an Activity with multiple fragments. For any individual fragment, you can perform a search operation, which works just fine...if you search from any of the fragments, it will display a new Activity to handle the searching, then return the result to the Activity to handle displaying a new fragment. The problem is, after a search operation, I want to be able to clear (almost) all the fragments away using popBackStackImmediate(...) and since saveInstanceState(...) was called, I get an exception that says:
"java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState"

Any idea how to pop from the back stack after onSaveInstanceState has been called?
Answer: Apparently my issue spawned from the call being made in onActivityResult(...)
I was able to fix the issue by putting the UI modification code inside a Runnable, then posting the Runnable to the main thread:
Runnable r = new Runnable() {
    @Override
    public void run() {
        // UI code here
    }
};
Handler h = new Handler();
h.post(r);

Comment: call super.onActivityResult first before your logic and the issue will get fixed as FragmentActivity's onActivityresult calls mFragments.noteStateNotSaved();
Comment: Man you just saved my mind. I almost gone crazy trying to figure out whats wrong. +1
Comment: Fixed the problem I was having! SingleTop activity, popping fragment backstack in onNewIntent. adding @UiThread to my method with AndroidAnnotations fixed the crash.
Comment: Thanks bro you just made my day. I was stuck in this for decades.
Answer: call super.onActivityResult first before your logic and the issue will get fixed as FragmentActivity's onActivityResult calls mFragments.noteStateNotSaved();
Answer: This answer is may help to someone. When your activity is not visible, you unable to call popBackStackImmediate(...)  it will throw illegal Exception: can not perform this action after onsaveinstancestate.
Instead of that you can check, Is the activity is visible or not? before call the popBackStackImmediate().
If your activity is not visible, don't call popBackStackImmediate. Through the boolean flag you can achieve, when activity opens again.
Ex:
public class MainActivity extends Activity {

// Below flag used to check activity visible or not?
private boolean isActivityVisible;

    @Override
    public void onResume() {
        super.onResume();
        isActivityVisible = true;
    }

    public void onPause() {
        super.onPause();
        isActivityVisible = false;
    }

}

Comment: This should be the correct answer if a peace of code was included!
Comment: Didn't understand the last part. So if my activity is not visible, and I don't do the operation, how will I know I should do it once the activity is visible?
Comment: If you want to call popBackStackImmediate(...), when your activity is not visible. Set a boolean to true.

When your activity come to foreground, in activity onResume() you can check the boolean, if it is true, then you can call popBackStackImmediate(...)
Comment: How exactly? Can you edit your answer with a code example?
Comment: @YonatanNir It seems sometimes activity go to foreground and available to user's actions before onResume is called. So this crash happens.
Answer: What about popping the stack immediately before starting your associated activity?  onSaveInstanceState wouldn't be called until startActivity was called (and the new activity came in front of the current one0... immediately before that, pop the fragment stack back to your desired state and then call startActivity.
Since the fragment stack is a layer over the normal task/back stack, I think that modifying it "from the middle" would cause issues and that's why you're seeing the issue.
Answer: This is what worked for me is to check if fragment manger doesn't hava a saved state
if (fragmentManager != null && !fragmentManager.isStateSaved()) {
       fragmentManager.popBackStack();
  }
Answer: Or just put it in a try-catch:
try {
  getSupportFragmentManager.popBackStack()
} catch (IllegalStateException e) {
  // ignore
}

This is basically the same as commitAllowingStateloss() except we don't have a popBackStackAllowingStateloss().
In most cases I get an error even though I don't need to save state.


spring-boot camel case nested property as environment variable

Question: I have a spring boot application and want to set, though environment variables, in a class annotated with @ConfigurationProperties a second level nested property which is camel case. Here is an example of the class:
@SpringBootApplication
@EnableConfigurationProperties(SpringApp.Props.class)
@RestController
public class SpringApp {

  private Props props;

  @ConfigurationProperties("app")
  public static class Props {
    private String prop;
    private Props nestedProps;

    public String getProp() {
      return prop;
    }

    public void setProp(String prop) {
      this.prop = prop;
    }

    public Props getNestedProps() {
      return nestedProps;
    }

    public void setNestedProps(Props nestedProps) {
      this.nestedProps = nestedProps;
    }

  }

  @Autowired
  public void setProps(Props props) {
    this.props = props;
  }

  public static void main(String[] args) {
    SpringApplication.run(SpringApp.class, args);
  }

  @RequestMapping("/")
  Props getProps() {
    return props;
  }

}

when I try to run the application with following environment variables:
APP_PROP=val1
APP_NESTED_PROPS_PROP=val2
APP_NESTED_PROPS_NESTED_PROPS_PROP=val3

I'm getting following response from the service:
{
  "prop": "val1",
  "nestedProps": {
    "prop": "val2",
    "nestedProps": null
  }
}

Is this the expected behavior? I was expecting something like this:
{
  "prop": "val1",
  "nestedProps": {
    "prop": "val2",
    "nestedProps": {
      "prop": "val3",
      "nestedProps": null
    }
  }
}

When I am setting the properties through application parameters (eg: --app.prop=val1 --app.nestedProps.prop=val2 --app.nestedProps.nestedProps.prop=val3), I'm getting expected response.
Is there any workaround using environment variables and without modifying the code to get the expected behavior?
Note: I did some debugging and seems the problem is originated in org.springframework.boot.bind.RelaxedNames not generating candidates for this cases. Here is a test I did to demonstrate it (it fails):
@Test
public void shouldGenerateRelaxedNameForCamelCaseNestedPropertyFromEnvironmentVariableName() {
  assertThat(new RelaxedNames("NESTED_NESTED_PROPS_PROP"), hasItem("nested.nestedProps.prop"));
}

Answer: I would try with the NESTED_NESTEDPROPS_PROP, bcs 'nestedProps' is one property

The _ delimiter must not be used within a property name. i.e.
  database-platform must be written as DATABASEPLATFORM and not
  DATABASE_PLATFORM.

source: https://github.com/spring-projects/spring-boot/wiki/Relaxed-Binding-2.0


custom module to create multiple forms with pop-ups

Question: I am working on a custom module to create a form. Functionality of the module is as follows: The first form has an url, on clicking the url it should show another form as a pop-up.
How can i call these forms in the hook menu.
Does tools_js has any significance?
<?php

function patient_menu() {

$items['patient_add/mainpage'] = array(
    'title' => 'New Patient',
    'page callback' => 'patient_form',
    'page arguments' => array(),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);
//a link to add patient diseases

$items['patient_add/%ctools_js'] = array(
'page callback' => 'patient_callback',
'page arguments' => array(1),
'access callback' => 'user_is_logged_in',
'type' => MENU_CALLBACK,
);

return $items;
}

 // a function to make a  link
function _patient_make_link($link_text = '') {

 return '
' . l($link_text, 'patient_add/nojs', array('attributes' => array('class' => 'ctools-use-modal'))) . '
';
}
//first form

function patient_form($form, &$form_state)  {
ctools_include('modal');
ctools_modal_add_js();

$form['p_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#size' => 30,
    '#maxlength' => 128,
    '#required' => TRUE,
);

$form['age'] = array(
    '#type' => 'textfield',
    '#title' => t('Age'),
    '#size' => 30,
    '#maxlength' => 30,
    '#required' => TRUE,
    '#attributes' => array('placeholder' => t( 'in Years' )),
);

$form['submit'] = array(
    '#value' => t('Add Patient'),
    '#type' => 'submit',
);

_patient_make_link('add disease details');

return $form;

}

//Ajax menu callback

function patient_callback($ajax) {
if ($ajax) {
ctools_include('ajax');
ctools_include('modal');

$form_state = array(
  'ajax' => TRUE,
  'title' => t('disease details'),
);
$output = ctools_modal_form_wrapper('disease_form', $form_state);
if (!empty($form_state['ajax_commands'])) {
  $output = $form_state['ajax_commands'];
}
print ajax_render($output);
drupal_exit();
}
 else {
  return drupal_get_form('disease_form');
  }
}
//second form
function disease_form($form, $form_state){
  $form['disease_ids'] = array(
    '#type' => 'select',
    '#title' => t('Disease IDs'),
    '#multiple' => TRUE,
    '#options' => array(
        'Cancer' => 'Cancer',
        'Dengu' => 'Dengu',
        'Viral Fever' => 'Viral Fever',
        'Malaria' => 'Malaria',
    ),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;

}

function patient_form_submit($form, &$form_state) {}

Answer: You are partial on the right path, I would suggest following a guide like https://www.deeson.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7 and then work your way towards what you need based on that.
Comment: I am working with two forms. In the above example they are working with only one form.


If $A$ is a vector space over $Q$, $Ext_{R}^{n}(C,A)$ is a vector space over $Q$.

Question: Let $R$ be a domain with fraction field $Q$, and let $A$, $C$ be $R$-modules. Then, if $A$ is a vector space over $Q$, $Ext_{R}^{n}(C,A)$ is a vector space over $Q$.
Let $0\rightarrow A\xrightarrow{\eta}E^0\xrightarrow{d^0}E^1\xrightarrow{d^1}E^2\rightarrow\cdots$ be an injective resolution. Then, by definition, $Ext_{R}^{n}(C,A)=\mathrm{ker}\  d^{n}_{*}/\mathrm{im}\ d^{n-1}_{*}$, where $d^{n}_{*} : Hom_{R}(C,E^n)\rightarrow Hom_{R}(C,E^{n+1})$.
I guess $Hom_{R}(C,E^n)$ should be a vector space over $Q$ but I am not sure.
Comment: You should rather use a projective resolution of $C$.
Comment: I see. I guess that's because two ways give the canonical isomorphism.
Answer: The statement is a bit sloppy: $A$ should not be just a $Q$-vector space, but rather it should be a $Q$-vector space so inducing the structure of $R$-module.
You should rather use a projective resolution of $C$, because if $M$ is any $R$-module, you can give $\operatorname{Hom}_R(M,A)$ a structure of $Q$-vector space which is functorial: if $M\to N$ is a morphism of $R$-modules, then the induced map $\operatorname{Hom}_R(N,A)\to\operatorname{Hom}_R(M,A)$ is a morphism of $Q$-vector spaces.
Comment: For your first sentence : you are correct that it is a bit sloppy, although given an $R$-module $A$, there is at most one way for it to be a $Q$-vector space , so "$A$ is a $Q$-vector space" is a perfectly valid property if $A$ is known to be an $R$-module
Comment: @Max There is at most one way for it to be a $Q$-vector space if we prescribe that the action of $R$ is the same.
Comment: Yes but if $A$ *is* an $R$-module (not its underlying set, or its underlying abelian group), the sentence "a $Q$-vector space structure on $A$" is inambiguous, because $A$ contains the data of the $R$-structure


How to see which device is installed and uninstalled

Question: When I am using my laptop (i.e. writing on keyboard)c, some device is being installed and uninstalled constantly (I hear the windows sound of it). I cannot use windows when it's undergoing (lag). How can I find which usb port/device is installed and uninstalled?
I know this is a programming portal, but i don't have account on serverfault, and maybe anybody here just knows?
Answer: windows - How to enumerate all connected USB devices' device path?:
"
MSDN says that there's a generic USB device interface class named GUID_DEVINTERFACE_USB_DEVICE with the GUID {A5DCBF10-6530-11D2-901F-00C04FB951ED}:
The system-supplied USB hub driver registers instances of
GUID_DEVINTERFACE_USB_DEVICE to notify the system and applications of the presence of USB devices that are attached to a USB hub.
http://www.velleman.eu/images/tmp/usbfind.c contains a code example that seems to do what you want to do, using the DEVINTERFACE_USB_DEVICE GUID.
"


Post edit that didn't change a single character

Question: I had an edit to my post that appears to not have changed a single character.
catalog_product_load_before event gives getRequestedRouteName() error
It is the edit made by Amit Bera at 3:42 PM ET. Am I going crazy, or was nothing edited?
Comment: goose do not fill crazy.it is formatting
Answer: Something was edited. Take a look at the revisions. 2 ` characters were added to format the code.
Comment: ya,marius i was just do a simple formatting.Does not know  why @Goose fell Crazy


Retornar números de uma String

Question: Sou programador PHP e dando manutenção em um projeto Java me vi com a necessidade de retornar apenas números contidos em uma determinada String.
Não encontrei perguntas a respeito disso no SOpt e encontrei no SOen, por isso trago aqui essa questão buscando saber qual é a melhor opção, visto que em Java por ser uma linguagem de mais baixo nível, tudo ou quase tudo faz diferença no processamento e sempre pode ser otimizado...
Um exemplo do que estou solicitando:
String cnpj = "83.411.122/0001-06";

O retorno esperado:
"83411122000106"

Comment: Você pode nos dar um exemplo do que você quer dizer com "[...] retornar apenas números em uma determinada `String`"? Em um assunto paralelo Java é uma linguagem comercial, está bem longe de ser de baixo nível.
Comment: Ok, vamos esclarecer as coisas, Baixo Nível, significa que ela tem mais poder sobre o hardware, mais capacidade de manipula-lo, em segundo lugar, colocarei um exemplo do que estou sugerindo, desculpe por não ser exatamente claro, amigo.
Comment: @Genos, creio que tenha ficado mais claro agora.
Answer: Solução encontrada no SOen:
str = str.replaceAll("\\D+","");

Comment: Nesse caso ele também poderia usar expressão regulares para encontrar apenas os números da variável `String` e depois retornar o que tivesse entrado, certo?
Comment: Desculpe @R.Santos, não entendi bem a sua pergunta, nesse caso o `replaceAll` com a Expressão Regular já retorna o String somente com os números...
Comment: É que quando usei expressões regulares, eu utilizava `matcher` e `pattern` para estipular padrões de o que eu gostaria de selecionar em um texto, nesse caso seria criar uma expressões regular que procurasse apenas números, e que depois de analisar a `String` me retornasse o que havia sido encontrado

Retornar números de uma String


Should I expect inertia from a K-Means solution on counts to be substantially lower than for a similar solution on percentages?

Question: During exploratory clustering with K-Means on agents with a range of events, I created two sets of models across clusters with K in {2,..,9}. In one set, the model is fit using raw counts of five kinds of events for any given agent, three of which are mutually exclusive; in the other set, the features are four percentages (two of the three from the set of mutually exclusive events) that express the percentage of an agent's total events. Both sets of features are scaled using MinMax to the range [-1,1].
I fit the models using PySpark's implementation of K-Means and was surprised to find that inertia (or WSSSE) calculated using the computeCost method, showed an inertia value two magnitudes higher for each cluster solution using percentages than the solution using counts. I'd have thought there would be little difference because both models used the same scaling, but it's almost as if the clusters built on percentages are somehow more diffuse than those built on counts.
What should I look for to help me understand why the inertia is so much higher fitted to percentages rather than to counts?
Comment: I don't think you should scale percentages *ever*. Why do you think that is appropriate?
Comment: @Anony-Mousse, that's a valid question. The events vary across agents so that the model has to fit a huge range - from 8 to 1,700. We're interested in clustering agents to discover preference regardless of the range of events. When I cluster on raw counts, then it's count of events that determines cluster, with average likelihood to engage event by agent relatively homogenous across clusters.

I'm going to try your suggestion of not scaling the percentage-transformed features.
Comment: And I misread your question, @Anony-Mousse. I thought you were asking why I was clustering on percentages.
Answer: Never compare WCSS across different data versions or data sets
It's trivial to see that scaling all attributes by a factor of 2 does not affect the clustering, but changes the WCSS by a factor of 4. So you can arbitrarily inflate WCSS - or reduce them. Just scale your data by 0.00001.
At the very minimum, look at WCSS/TSS - this is at least invariant to homogeneous scaling. But in general I do not recommend to rely on such measures at all, unless you understand them very well (and you very carefully chose weights and scales for your data).
Likely the inappropriate scaling (never scale percentages, they already have a nice scale) emphasized these errors. Don't blindly default to scaling everything; but rather study when and when not to use scaling (and which attributes to scale), and then always also weight different attributes.
Comment: @Anony-Mousee. The nomenclature isn't familiar to me. What's the distinction between within-cluster sum of squares and total sum of squares?
Comment: Found it ... https://stats.stackexchange.com/questions/147007/a-proof-of-total-sum-of-squares-being-equal-to-within-cluster-sum-of-squares-and


play a youtube video by clicking on a button

Question: want to play - stop - pause - a youtube video by clicking on corresponding buttons
according to several tutorials - this code should work - but it doesn't
clicking on btnplay for the first time - youtube logo is removed and it seems it will play - but that's all
clicking each next time - nothing happens

<button id='btnplay'>PLAY</button>

function onYouTubeIframeAPIReady(){
    player = new YT.Player('player');
}

$(btnplay).on('click', function(){
    console.log('clicked'); // works
    player.playVideo();  // doesn't work
});

Answer: Try something like this:

<button id="btnplay">PLAY</button>

// global variable for the player
var player;

// this function gets called when API is ready to use
function onYouTubePlayerAPIReady() {
  // create the global player from the specific iframe (#video)
  player = new YT.Player("video", {
    events: {
      // call this function when player is ready to use
      onReady: onPlayerReady
    }
  });
}

function onPlayerReady(event) {
  // bind events
  var playButton = document.getElementById("btnplay");
  playButton.addEventListener("click", function () {
    player.playVideo();
  });
}

// Inject YouTube API script
var tag = document.createElement("script");
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

Reference: https://developers.google.com/youtube/iframe_api_reference
Comment: it works only if `&mute=1` is inside the iframe.src - but I need the sound, of course
Comment: I keep forgetting autoplay won't work unless the video is muted. It makes sense but it's also easy to get stuck because of this issue. Thank you!
Answer: The problem is that player is undefined when you call the button click. This is because the IFrame Player API is not load asynchronously (as per the docs)
Try the following javascript:
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

let player;

function onYouTubeIframeAPIReady(){
    player = new YT.Player('player');
}

$(btnplay).on('click', function(){
    console.log('clicked'); // works
    player.playVideo();  // doesn't work
});

Comment: Really? This codepen: https://codepen.io/GeneralPoxter/pen/gORLzYM?editors=1011 works fine for me.
Comment: your codepen doesn't work for me. clicking on the button - the video doesn't start to play
Comment: I see now - it works only if  `&mute=1` is added to `iframe` - but I need the sound, of course
Comment: Hm it also seems to pause shortly after I press play.
Comment: it doesn't pause for me - it plays fluently to the end
Comment: I meant without the added `&mute-1`
Comment: without `mute=1` - it doesn't start to play at all for me


Remover posições vazias de um array

Question: Eu estou passando um array via GET para o PHP e depois envio para o lado do cliente (JavaScript). Quando eu o recebo ele fica dessa maneira:
m_prod = [5,,,,,,,,6,,,,,,];

Ou seja ele está incluindo um espaço nas posições que não contém um valor!
Como posso remover esses espaços no JavaScript?
<?php
    $m_prod = trim($_GET['m_prod']);
    print("");
?>

Comment: @Alexandre então o interessante é ver o seu código PHP para resolver o problema na origem. Tem acesso ao PHP?
Comment: @Sergio já modifico o código para mostrar como chega meu php!
Comment: Queres apenas remover os espaços? Ou também reduzir o tamanho do array?
Comment: Bem, a principio gostaria de remover os espaços, pois ai o array ficaria só com  `m_prod = [5,6]; `
Comment: Então parece-me que já tens a resposta em baixo
Comment: @Alexandre pode explicar melhor de onde vem esse array? vem do PHP?
Comment: Sim o array vem do PHP!
Answer: Você pode usar a função filter, da seguinte forma:
var m_prod = [5, , , , , , , , , ,6 , , , ];

var resultado = m_prod.filter(function(ele){
  return ele !== undefined;
});

console.log(resultado);  // [5,6]

Comment: Isso mesmo que eu precisava! Obrigado @BrunoCalza
Comment: Assim @BrunoCalza, ele passa pelo filtro mas ainda continua mantendo as posições vazias! É como se ele não retornasse só os valores!
Comment: desculpe @Alexandre, não entendi. tenha em mente que o m_prod não será alterado.
Comment: Erro meu, em vez de utilizar o `undefined` utilizo o `""` assim retorna os campos que necessito!
Answer: Se o problema vem do PHP acho que deve resolver no PHP.
Para filtrar uma array de elementos vazios:
$m_prod = array_filter($m_prod);

No caso de haver numeros dentro da array então temos de ter extra cuidado pois o 0 valida como false e é retirado da array. Assim pode fazer:
$m_prod = array_filter($m_prod, function($value) {
  return !empty($value) || $value === 0;
});

Para passar isso para o JavaScript pode renderizar assim:
echo '';

Comment: @Alexandre, Se você futuramente precisar criar uma API, sempre vai ter que sanitizar os resultados. Use o PHP para transitar as informações corretas.
Comment: Dessa maneira também é tranquilo! Obrigado @Sergio

Remover posições vazias de um array


Covariance of a white noise with a constant deterministic trend

Question: I have tried compute the autocovariance of the following process:
$$ Y_t = \beta_0+\beta_1t+\epsilon_t ~~~~~~~~~~~~,~ \epsilon_t \sim WN(0,\sigma^2) $$
I tried this way:
$$COV(Y_t, Y_{t-j}) = E[(Y_t - E(Y_t))(Y_{t-j}- E(Y_{t-j}))]$$
$$ = E[(\beta_0+\beta_1t+\epsilon_t-(\beta_0+\beta_1t))(\beta_0+\beta_1(t-j)+\epsilon_t-(\beta_0+\beta_1(t-j)))] $$
$$= E[\epsilon_t \cdot \epsilon_{t-j}] = 0$$
But this is not correct since if I simulate such a process with R and then I compute its acf, it is not zero. Where is my mistake?
Comment: Your process is not stationary, and you're not estimating the actual autocorrelation function when call R's acf function.
Answer: The underlying problem is that your series is not stationary!
After you simulate your series $y_t$. R is computing the sample mean over time as:
$$ \bar{y} = \frac{1}{T} \sum_{\tau = 1}^T y_\tau $$
While with math, you computed the mean of $y_t$ as:
$$ E[y_t] = \beta_0 + \beta_1 t $$
Observe how completely different these two entities are! Because the process $\{y_t\}$ is not stationary, your sample mean taken over time is NOT an estimate of the population mean!

The population mean of $y_t$, that is $E[y_t] = \beta_0 + \beta_1 t$, is a function of time $t$.
On the other hand, the sample mean $\bar{y}$ is not an estimate of anything useful. It's a scalar, it doesn't depend on time $t$, and it goes to infinity as sample size $T$ goes to infinity.

So when R computes sample covariances etc... using $\bar{y}$, everything is already all fouled up! Look at how entirely non-sensical the calculation of sample covariance is:
$$\hat{\gamma}(k) =  \frac{1}{T-1} \sum_{\tau } \left( y_\tau - \bar{y} \right) \left( y_{\tau - k} - \bar{y} \right)  $$
This makes sense for a stationary process, but it's useless in this case. Taking averages over time of a non-stationary process is generally a huge error.
If you want to simulate to match your math answers, what can you do?
If you want to verify results such as $E[y_t] = \beta_0 + \beta_t$ by simulation, you want to conduct multiple draws from sample space $\Omega$ rather than advancing time $t$. You want to take averages over space $\Omega$ rather than time $t$.
If your process is non-stationary, it's still the case that for any time $t$, $y_t$ is a random variable and you can compute the sample mean etc... of that like any other random variable by taking IID draws from the sample space.
Sample averages over time only converge towards population averages across space in the case of stationary, ergodic processes.
Answer: The autocovariance function of this time series is indeed $0$ for $j \neq 0$ as you have computed quite correctly. So, the question is why R is giving a nonzero value for the acf. Unfortunately, acf is also an initialism for autocorrelation function which is defined as the value of $E[Y_tY_{t-j}]$, not $\operatorname{cov}(Y_t,Y_{t-j})$, in the engineering literature, and possibly in some parts of the statistical literature, and perhaps even in R. So, check what R believes acf means.  If R does define the acf as $\operatorname{cov}(Y_t.Y_{t-j})$, but you are doing a simulation of the time series, then it is almost surely the case that the time-average value that your simulation gives does not exactly equal the ensemble average value of $0$. As long as the time average is small, nothing has gone wrong.
Comment: @Archimede What you say is true except for the assertion that "$E[Y_t] = 0$ as in this case." In this case, $E[Y_t]=E[\beta_0 + \beta_1t +\epsilon_t] = \beta_0 + \beta_1t$ which **does not equal** $0$ for all $t$ except when _both_ $\beta_0$ and $\beta_1$ equal $0$.
Comment: $E[Y_t, Y_{t-j}]$ is the same thing as $COV(Y_t, Y_{t-j})$ when $E[Y_t]=0$ as in this case.
Comment: His process is not stationary...
Comment: @MatthewGunn True,  but irrelevant as far as the autocovariance function is concerned. cov$(Y_t, Y_{t-j})$ depends only on $j$ and not on $t$. It is the _autocorrelation_ function that depends on both $j$ and $t$.


Replacement module for Image FUpload

Question: Last week the Image FUpload module got the "no longer supported" status because "its dependencies swfupload are not maintained and not safe anymore".
Are there any Drupal 6 modules that can replace the Image FUpload module, allowing uploading multiple files/images at once? An HTML5 solution would be great. Thanks!
Comment: It looks like [ImageField Zip/HTML5 Bulk Upload](https://www.drupal.org/project/imagefield_zip) is doing what I need, as it allows you to select one of these upload modes: "Zip Files Only", "**HTML 5 Multi-upload Only**", "Both Zip & HTML 5". In this case I needed the second option ("HTML 5 Multi-upload Only").
Answer: ImageField module is the perfect solution for your requirement. It is dependent on CCK and FileField modules. Some of the additional benefits provided by ImageField are it works fine with AJAX upload and removal, HTML5 and you can also restrict its behavior.
Comment: But you can't use ImageField for bulk uploading, can you? I'm looking for a "one button to upload X images at once" solution.
Comment: Yes in drupal 6 it doesn't support bulk uploading. But you can try jUpload (https://www.drupal.org/project/jifupload) as extension to imagefield
Comment: It looks like [ImageField Zip/HTML5 Bulk Upload](https://www.drupal.org/project/imagefield_zip) is doing what I need, as it allows you to select one of these upload modes: "Zip Files Only", "**HTML 5 Multi-upload Only**", "Both Zip & HTML 5". In this case I needed the second option ("HTML 5 Multi-upload Only").
Comment: Look into imagefield configuration @user34515

Replacement module for Image FUpload


Prove $2^n-1$ is divisible by $(2^m-1)^2$ iff...

Question: Prove that for any $m,n\in\mathbb{Z}^+$, the number $2^n-1$ is divisible by $(2^m-1)^2$ iff the number $n$ is divisible by $m(2^m-1)$.
My work so far:
It's an if and only if statement, so the common approach is to split the proof into two "if then" proofs ($A\rightarrow B \text{ and } B\rightarrow A$).
Starting with $A\rightarrow B$, for a direct proof, I would assume $A$ and prove $B$. I can use the definition of divisibility:
Assume $n=m(2^m-1)k$ for some integer $k$
Then I need to prove that $2^n-1=(2^m-1)^2h$ for some integer $h$
So I'm thinking I need to start with the expression $2^n-1$ and transform it to $(2^m-1)^2h$, or vice versa, and I need to use the assumption $n=m(2^m-1)k$ somehow.
I notice that the LS of the equality contains the variable $n$ while the RS contains $m$, and the assumption relates $n$ to $m$, so that could be a way forward. For example, simple substitution gives $2^{m(2^m-1)k}-1$, but I'm not sure what I could do from here. Perhaps there's a divisibility theorem that could help?
Other things I notice: $2^n-1$ and $(2^m-1)^2$ are always odd. Also, the divisors in both cases are multiples of $2^m-1$.
Any help/hints appreciated.
Answer: Hints.
$$\gcd(2^n-1,2^m-1) = 2^{\gcd(m,n)}-1,\tag{1} $$
hence in order that $(2^m-1)\mid (2^n-1)$, we must have $m\mid n$, and this is a sufficient condition, too, since:
$$ y^a-1 = (y-1)\cdot(y^{a-1}+\ldots+y+1).\tag{2} $$
Suppose now that $n=mh$. We have:
$$ 2^n-1 = (2^m-1)\cdot\left(2^{m(h-1)}+\ldots+2^{m}+1\right)\tag{3} $$
and:
$$ 2^{mu}=\left((2^m-1)+1\right)^{u}\equiv 1\pmod{(2^m-1)}\tag{4} $$
hence in order that $(2^m-1)^2\mid (2^n-1)$ we must have $(2^m-1)\mid h$, and it is also a sufficient condition. Putting all together:
$$ (2^m-1)^2\mid (2^n-1)\quad\Longleftrightarrow\quad m(2^m-1)\mid n. \tag{5} $$
Comment: Thanks very much Jack. I don't know what rule justifies (1)?
Comment: @yroc: if you like, write $n$ as $km+r$, then apply $(4)$.
Comment: @yroc See also [this](http://math.stackexchange.com/questions/225289) or more generally, [this](http://math.stackexchange.com/questions/7473)


What is the keyword "license" used for in python?

Question: I just went to use "license" as a variable name and it became highlighted to indicate that it was a reserved word, what is "license" used for?
Comment: It is not a keyword, but a builtin function; you could have just run the shell and type it to figure it out :)
Comment: It's *not* mentioned in the list of [built-in functions](https://docs.python.org/3/library/functions.html), but *is* mentioned in the list of [built-in constants](https://docs.python.org/3.12/library/constants.html#constants-added-by-the-site-module).
Answer: It's not a keyword, it's a constant added by the site module (some others are copyright and credits). If you want to know what it does, try:
print license
>>> Type license() to see the full license text

then if you type
license()

output will be:

A. HISTORY OF THE SOFTWARE
Python was created in the early 1990s by Guido van Rossum at Stichting
  Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
  as a successor of a language called ABC.  Guido remains Python's
  principal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for
  National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
  in Reston, Virginia where he released several versions of the
  software.
In May 2000, Guido and the Python core development team moved to
  BeOpen.com to form the BeOpen PythonLabs team.  In October of the same
  year, the PythonLabs team moved to Digital Creations (now Zope
  Corporation, see http://www.zope.com).  In 2001, the Python Software
  Foundation (PSF, see http://www.python.org/psf/) was formed, a
  non-profit organization created specifically to own Python-related
  Intellectual Property.  Zope Corporation is a sponsoring member of the
  PSF.
All Python releases are Open Source (see http://www.opensource.org for
  Hit Return for more, or q (and Return) to quit:
Comment: 6 years later... don't know how I managed to log back into this account. Anyway, thanks.
Answer: license is one of the built-in constants added by the site module.
It's use is entirely within the interactive interpreter:
>>> license
See http://www.python.org/2.7/license.html

Other such objects are credits and copyright, plus the quit() and exit() functions.
If you are curious as to its implementation, see the setcopyright() function source.
Comment: Well, `license()` and `quit()` etc.. works perfectly in non interactive mode, as functions.
Comment: @GuillaumeLebreton: sure, but they are rarely *useful* outside of the interpreter.
Answer: It's not a reserved word in Python: http://docs.python.org/2/reference/lexical_analysis.html#keywords
It's a built-in function; try running it in an interactive shell:
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> license
Type license() to see the full license text
>>> license()
A. HISTORY OF THE SOFTWARE
==========================

Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
as a successor of a language called ABC.  Guido remains Python's
principal author, although it includes many contributions from others.

In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
in Reston, Virginia where he released several versions of the
software.

In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team.  In October of the same
year, the PythonLabs team moved to Digital Creations (now Zope
Corporation, see http://www.zope.com).  In 2001, the Python Software
Foundation (PSF, see http://www.python.org/psf/) was formed, a
non-profit organization created specifically to own Python-related
Intellectual Property.  Zope Corporation is a sponsoring member of
the PSF.

All Python releases are Open Source (see http://www.opensource.org for
Hit Return for more, or q (and Return) to quit:

Comment: It's not even really a builtin, it only exists at the interactive interpreter and is defined in `site.py`.
Comment: Interesting, that's not what the distributed 2.7.3 source would print.
Comment: @MartijnPieters Any code can put anything into `__builtin__`, I use "builtin" in the sense of http://docs.python.org/3/library/functions.html and the like. Stuff from the interpreter core.


Once I add session in edit form, I could not get selected values in dropdown

Question: Once I add session in edit form, I could not get selected values in dropdown menu. I am using bootstrap framework. When I remove session from the same beginning it works.
edit.php file
<?php
  session_start();
  $car=$_POST['car']
?>
<form method="post" action="">

  Car
    <select class="form-group" name="car" id="car" value="<?php echo $car; selected?>">
      <option value=<?php echo $car?> selected>
         <?php cars()?>
      </option>

</form>

I have created "cars" function in which I get values of all cars from database.
function cars(){
   $link = new mysqli("", "", "", "");
   $link = set_charset("utf8);

   $sql = mysqli_query($link, "SELECT * FROM db_cars ORDER BY CarId")
   echo '<option value=""> Choose car </option>'
   while ($record = mysqli_fetch_array($sql)) {
       echo '<option value = "'.$record['CarId']'"> . $record['CarName'].' </option>
   }
}

Any help or advice is appreciated.
Comment: Do you have a ``? `` and `mysqli_query(` are not closed. Please check your code.
Comment: Yes I do. I forgot to post it
Comment: first of all correct this  $link = set_charset("utf8"); instead of  $link = set_charset("utf8); also i think you start session two times.
Comment: I see in the HTML no semicolon (;) for `$car = $_POST['car']` that can be the problem also, also add it to the value in the `option ` and when you call the function `car()`
Answer: The select element has no name attribute, so it cannot be a successful control (i.e. submit any data).
The form has no submit button, so there is no obvious way for you to trigger the form submission. (You have to submit the form in a new HTTP request to the server to run the PHP and get the data from the user).
Comment: It is unclear to me if I remove seession_start it works. once i add it it does not
Answer: First, add the semicolons after every line when you use PHP. That can make a lot of troubles.
Second, some attributes have just one ("), like the label in the HTML.
Third, you are adding "something" called selected after echoing $car.
In the function cars() you are echoing without a semicolon (;) and just after doing a while() loop.
Check out all, you are missing very important and essential things
Also, I gonna guess this is not a "copy-paste" from your code, but if it's, you also are missing </select>
Comment: It is not copy pase. All those you have mentioned is written in my code. Thanks for reply. But I am wondering if I do not use session_start() it works. Once I add that line on the same beginning of code it does not work
Comment: are you including some other pages that also contains `session_start();`?
Comment: No I am including jquery files, connection to db, and functions file but seession_start is not in function file
Comment: Then I recommend you the copy-paste your exact code (overriding sensible information for Foo), not all, but things it requires. With the code above given, we only can tell you some errors.


Diferenças de retorno booleano

Question: Me deparei com o seguinte exemplo:
$umidade = 91;

$vai_chover = ($umidade > 90);

if ($vai_chover) { echo "vai chover"; }

A $vai_chover retorna um booleano no if, porém achei muito código para fazer pouca coisa, não seria a mesma coisa se ela fosse escrita assim:
$umidade = 91;

if ($umidade > 89) { echo "vai chover"; }

Teoricamente o if faz o mesmo teste, o que muda só que ele não esta armazenado numa variável.
Em que casos usamos um ou outro?
Answer: Para entender melhor deve ler O que é uma variável?.
Sabendo o que é uma variável a pergunta a ser feita é se precisa armazenar o seu valor em algum lugar. Qual o motivo de armazenar o valor em uma variável e depois usá-la apenas uma vez?
Parece que nenhuma, certo? Eu concordo com isso e de forma geral não vejo vantagem em fazer dessa forma.
Porém existe uma "escola" (no sentido de grupo que segue determinadas formas de fazer) que prega a legibilidade do código acima de qualquer outra coisa. E eles tem certa razão. Você escreve o código apenas uma vez e lê diversas, inclusive é comum que pessoas que não o escreveram leiam diversas vezes. Quanto melhor documentar o que está fazendo e deixando óbvio o que significa aquilo, melhor o código é.
Uma das formas de fazer isso é colocar muito comentário para dizer que está acontecendo. Mas comentário viola o DRY e você acaba tendo duas informações sobre a mesma coisa, então toda vez que mexer em algo no código tem que lembrar de mexer no comentário, se não fizer você tem o pior dos dois mundos, um comentário que diz que o código faz algo que ele não faz.
Veja mais sobre isso em:

O que são comentários WET?
Como saber a medida certa de comentários?
Comentários em código ao trabalhar em grupo
Existe uma forma correta de comentar um trecho de código?
O que é uma documentação formal?
Recomendações para comentários em uma interface e seus contratos

E também Como escrever um código legível e de fácil manutenção?.
Então como documentar de forma legível o que é aquilo e não parecer uma expressão mágica sem usar comentários?
Fácil, crie um código descritivo do que é aquilo. A forma simples de fazer isso é criar um identificador para aquilo. Esse identificador pode ser uma função ou uma variável.
Se fizer uma função ela poderá ser usada em vários outros pontos do código e será bem DRY. Se optar pela variável pode usar de novo ali mesmo naquele trecho, mas não fora da função atual, e será DRY se houver repetir.
Eu respondi isso em Atribuir uma expressão a uma variável e "if" elegante em PHP e também "== true" é útil para alguma coisa? É melhor "!" ou "== false"?.
Mas se eu só vou usar uma vez não seria redundante? Não, não é, tem um motivo para isso, não muda nada na execução, mas documenta melhor de forma canônica. É bom, deixa de ter magia, o código está explicando que vai chover, não é só uma análise de um número que nada indica o que é aquilo.
Então você deve ter pego um código ou explicação de alguém que segue a escola da boa documentação, do explícito melhor que o implícito (que me lembra de Python que tem isso em sua filosofia básica e quase ninguém segue, principalmente os novos usuários dessa linguagem que não ligam a mínima pra programação).
Você quer seguir essa escola? Alguns não querem. Mas sabem porque não querem. Uma decisão avaliada, justificada é uma boa decisão. Você sabe porque não seguirá isso. Qualquer decisão sem pensar bem é uma má decisão.
Talvez o caminho seja o meio termo, seja pensar bem o que está fazendo e fazer mais legível quando é necessário, quando não é bastante óbvio mesmo sem um nome identificador.
Você precisa achar seu jeito. Ou seguir o jeito da sua equipe. O mais importante é pensar sobre todo código que cria, e isso poucas pessoas fazem. Cada código que coloca deve ser justificado, e se deixa de colocar algo que poderia ter escrito tem que ser justificado.
Costumo colocar isso nas minhas palestras:

E as pessoas não entendem que o código deve refletir o que é definido fora dele. Parece óbvio, mas não é. Se fosse, todo mundo seguiria isso muito bem. As pessoas tendem achar que estão seguindo, mesmo não sendo verdade.
Então seu problema precisa de uma definição clara que a umidade maior que 90 é quando chove? Ou só precisa saber que essa quantidade de umidade deve fazer algo?
Nesse código em específico eu diria de cara que a variável não é necessária porque a ação seguinte já indica o que é aquilo. Mas isso só ocorre porque o código é artificial.
Eu costumo dizer que você pode aprender um mecanismo com um código artificial, mas só aprende programar com códigos reais. Esse não ensina o jeito certo de fazer porque ele é todo redundante.
Sim, todo, porque nem o if precisa nesse código. Você já sabe o valor antes então não tem porque comparar algo.
Esse código pode demonstrar o uso de uma variável como forma de documentação, mas não pode ensinar quando usar essa técnica, porque esse caso ele é inadequado.
Como exemplo do mecanismo ele serve, não estou reclamando disso, mas não ensina como deve ser uma codificação real, só precisa ter isso muito claro, a maioria não tem, elas começam copiar sem pensar.
Em paralelo, se acha que algo redundante não deve ser usado, então por que usou chaves? Elas são redundantes nesse caso. Há parênteses que também o são no primero exemplo.
Tem o outro ponto que eu percebi na pergunta: o título fala em retorno. Isso significa que a função ainda retorna um valor? Esse valor é se choveu ou não? Então a variável seria usada novamente? Aí faz muito sentido existir. Se não retorna nada, por que tem isso no título? Seria um título mal definido? Se um problema é mal definido a solução sempre estará errada, mesmo que ela funcione.
isso deve estar em uma função, qual o nome da função? Será que ela já não documenta bem o que faz? Se o nome dela é muito descritivo e ela é bem simples, como parece, então pode ser que não precisa descrever mais ainda.

Conclusão
Não é muita coisa, é só um nome de variável a mais. Documentar bem não é pouca coisa. Se acha que isso não importa experimente colocar todas variáveis que são obrigatórias apenas com uma letra, ou usar palavrões em vez de nomes significativos (já vi fazerem isso).
Em algumas linguagens criar uma variável pode ter um custo de performance em certas situações, então é algo para se pensar se precisa do máximo da performance, o que não é o caso quando se opta por PHP.
Não tem uma resposta única.
Aprender a tecnologia pouco importa. Desenvolver software é apego ao detalhe. É um pouco uma arte que o bom senso e bom gosto conta, sem deixar a exatidão que a solução exige. É fundamentação. É comprometimento. É questionar tudo, por isso também uso nas minhas palestras:

Coloquei no GitHub para referência futura.
Answer: Não há nenhuma diferença entre os dois exemplos além do valor que você colocou depois do operador de comparação.É como você disse, o primeiro exemplo é muito código para pouca coisa.

Diferenças de retorno booleano


Get title field from another content type in exposed filter

Question: I have two content types: Project and Task. Project has an node reference field of Task - when you create a Task, you add reference to one of Project.
I need to create a view of Project and add the expose filter of title of the Task. I've selected both content type like Project and Task in a filter, I can see all of the fields from the Task content type EXCEPT Title. The only Content: Title that's available is the one from the Project nodes.
Need help.
Answer: You need to create views of one content type ie Project and add a relationship to your views which should say something like this Task Content referenced from Project. Require this relationship to exclude those projects which don't have tasks.
Now come to your filters and add title. In the setting now you will see use relationship dropdown. Select the relationship you added and you will get the required results.


Positioning pinky while playing guitar

Question: I am currently playing a piece on the guitar which is going fine so far, but I have encountered a problem, and I am unsure whether this will have an effect on my guitar playing in the future.
When I play notes with any finger other than my pinky, my pinky seems to curl inwards. This looks strange but feels comfortable.
Will this affect me as a guitarist?
Comment: Can you clear up - which hand is the problem on, as it could be either.
Comment: Almost impossible to answer as is. A picture paints a thousand words, etc.
Answer: Most often this happens simply because your pinky is controlled by some of the same musculature as your other fingers. Every instrumentalist knows all too well that the ring and middle fingers are almost impossible to move independently (until you learn how to compensate). It's not so bad with the pinky, but the same principle applies. If you curl the other fingers, the pinky tends to curl. You can learn more about the anatomy here.
If you stick to a three finger technique this probably won't affect your playing much. However: if you want to take your right hand technique a notch up, you could learn to play from your first joint (where the finger meets the hand). This feels extremely awkward at first, but it's the standard stroke in classical guitar and often considered the most technically correct way to play, because the fingers are almost totally independent at that joint. You can flex any finger halfway to the palm and the others will hardly budge.  Moreover, it's the strongest joint by far, so you'll find yourself playing with more power and authority. Read up about basic classical guitar technique to learn more.
Comment: I'd +million for this if I could. I have never noticed that the fingers are so much more independent at that joint :)
Answer: If you mean the pinkie on your fretting hand, this should not be a problem when playing chords as long as you can easily transition to and from chords that involve the pinkie in fretting.
I just played through a number of chord progressions on my guitar and noticed that when moving to chords that involved the use of the pinkie as a fretting finger, having it curled actually meant it was closer to the position it needed to be in when it was needed for a chord.  Barre chords were the exception but most of those use the pinkie as a fretting finger and those that don't often use the pinkie to help press down the ring finger.
When playing individual notes, having it curled too tightly may make it more difficult to get it in proper position when it's time to use it to fret a note.  The best way to train your mind to keep your pinkie in position above the strings is to play exercises (scales, runs, sections of a melody) that use the pinkie often (every other note or so).  That will automatically get you in the habit of keeping your pinkie poised above the fretboard - particularly as you build speed playing these exercises.
In other words, just use your pinkie more often - and without really thinking about it, you will develop more finger independence with your pinkie and begin to habitually keep it in proper position.
As far as your picking hand goes, many classical and/or fingerstyle guitarist use their pinkie to anchor their picking hand by placing it on the top of the guitar below the strings.  This helps stabilize your picking hand and provides a constant frame of reference for your other fingers because it keeps your hand in a fixed location relative to all the strings.
EDIT: Community member Alex shared in a comment that many guitarist have gotten away from anchoring with the pinkie to allow more freedom in the picking hand using the forearm to anchor instead.  Try both methods and see what is more comfortable to you.  But according to Alex, the free pinkie technique is winning favor among the majority of classical and fingerstyle guitarists.
Have fun improving your skills.  It's a lifelong journey - enjoy it!
Comment: One thing about pinky planting. As you say, many players do it, but surprisingly there's an 80%+ consensus in the fingerstyle and classical world that it's a bad habit. (Google "guitar anchoring" and you'll find pages and pages of savage opposition in fingerstyle forums and Reddit threads.) It limits your right hand dramatically, and most players find it surprisingly easy to steady from the forearm. The opposition is so intense that it sometimes spills over into the pick style world, where anchoring does make some sense, because you're constantly adjusting your distance over the strings.
Comment: (I'm not correcting you, just thought people who run into this thread looking for info on whether to plant should know about the other side too.)
Comment: @Alex  Thanks Alex.  I have not been keeping up with the trends.  Seems I read a long time ago that you should anchor.  But I feel better now because I feel more comfortable NOT anchoring and all this time I thought I was doing it wrong.  Your comment validated my own technique (which I always thought was unsound - lol).
Comment: @Alex In an effort to provide the highest quality content on this site, you  and I have put our heads together to improve it.  Check out my edit as a result of your comment.  That is exactly what comments should be used for.  Thanks again for your contribution.

Positioning pinky while playing guitar


Executing a Python script from Drupal

Question: I'm trying to execute a python script from Drupal using this:
exec('/usr/bin/python name_of_the_script.py')

But it does not work. Although, if I'm on the php console (php -a), then it works fine.
The name_of_the_script.py file has all the permissions.
I thought maybe it was the python command that didn't have all the permissions.
So I checked it with this command:
which python
ls -lisa /usr/bin/python

694 0 lrwxrwxrwx 1 root root 9 2011-03-09 18:41 /usr/bin/python -> python2.6

Similarly I also used this command:
ls -lisa /usr/bin/python2.6

369 2240 -rwxr-xr-x 1 root root 2288240 2010-04-16 10:06 /usr/bin/python2.6

It seems everything is OK.
Do you have any suggestions?
Comment: Executing an external script in Drupal is not different from executing it from PHP, as Drupal doesn't have specific functions.
Answer: Adding 2>&1
exec('/usr/bin/python script.py 2>&1');

Pointed me to the right direction.
I was writting in a file ( inside the script that hadn't enough permissions )
chmod 666 name_of_the_file.txt totally solved the issue!
Thanks!
Answer: Most likely it's a permission of your webserver that is causing this. You should take care  as things could turn out badly should your drupal site be compromised.

Executing a Python script from Drupal


Exibir resultados da pesquisa MySQL de acordo com a sequência mostrada na cláusula in

Question: Como fazer para ordenar os resultados de uma query conforme sequência exibida na cláusula In? Ou seja, a ordenação das linhas deve respeitar a mesma ordem de valores indicados nesta cláusula.
Exemplo:
sql = select var_valor from tabela where var_codigo in (4,2,7);

Neste caso, o resultado deveria exibir primeiro o var_valor do código 4, depois do código 2 e por ultimo codigo 7.
Segue abaixo o código no SQL Fiddle para ilustrar a minha dúvida:
http://sqlfiddle.com/#!9/4c663e/10
Answer: Utilize o ORDER BY FIELD(), assim:
sql = select var_valor from tabela where var_codigo in (4,2,7)
order by FIELD(var_codigo, 4,2,7);

No caso do exemplo que postou no SQL Fiddle, ficaria assim:
select con_valor as valor from tabela where con_variavel in ('corpo','rodape','exibesoma')
order by FIELD(con_variavel, 'corpo','rodape','exibesoma');

Leia esta documentação para saber mais sobre a função FIELD()
Comment: Obrigado Murilo!!!


NGINX default error page

Question: I'm trying to set a default error_page for my entire nginx server (as in for all vhosts).
I'm trying it with following code:
http {
    ...
    ...
    error_page 404 /var/www/default/404.html;
    ...
    ...
}

Also, I'd like to be able to create a vhost and make it use the default 404.html if I don't explicitly write another one.
Something like:
server {
    ...
    server_name mydomain.com
    root /var/www/mydomain.com/;
    ...
}

Anyways, I'm getting the following error:
[error] 16842#0: *1 open() "/var/www/mydomain.com/var/www/default/404.html" failed (2: No such file or directory)

While I do understand the error, and I do understand why it's happening, I can't understand why can't I tell NGINX to user the default error_page as an absolute path instead of appending it to the root of my vhost.
Any idea how to make it?
Regards
Comment: `/var/www/default` is not the same as `/var/default/`, did you modify that output by hand at all?
Comment: @gparent Oh, yes, sorry, that's a typo in the error. I'll change it in a second.
Answer: As you've already discovered, the error_page directive specifies a document that is relative to the document root.
One way to work around this is to create a separate file containing your error page specifications, which contains the appropriate location blocks, and then include that from each server which will use the "global" error_page.
For example, a file /etc/nginx/global404:
location = /404.html {
    root /var/www/default;
}

error_page 404 /404.html;

Now in each server block, you will:
include global404;

Comment: This indeed is a solution, but it's not perfect. Isn't there really some way I could tell NGINX to use a default error_page without having to put it on every server{} ?
Comment: Nope, sorry. This is about the best you can do.
Comment: Do you know if this was asked in the ML of NGINX? If it wasn't, I could try asking and see if they can implement it.
Comment: You can try. Maybe Igor will implement it, or maybe he will yell at you. :)
Comment: Hahaha, let's hope he'll do the first! Or at least won't do the second :P
Comment: @alexandernst Look in `nginx.conf`: if you see the following line in the `http` block:
```include /etc/nginx/conf.d/*.conf;```
then you may simply create a file `errors.conf` in `conf.d` and state your error_page directives in there. They will be applied to all of the server configurations in `http`
Answer: Seems like error_page is inherited only if there's no other error_page directives in server/location. So to reset error_page 404 for your server, just set some other error page, like:
server {
  error_page 399 /;
}

This server won't inherit error_page 404 (and any other) from 'html' block.
Answer: I plan to use the include approach previously submitted but, for the sake of thoroughness, an alternative: Use symlinks. It still requires an extra operation for each vhost you manage but it does offer the benefit of not requiring further server config changes and restarts.
http {
    ...
    ...
    error_page 404 /error/404.html;
    ...
    ...
}

...and then in each vhost's root...
ln -s [path to error page html directory] /[vhost root]/error

This approach strikes me as inelegant and unportable (I'd vote it down if I have enough rep to vote things up or down) but it works.

NGINX default error page


resave all taxonomy terms by vbo

Question: I have a site with a large number of taxonomy terms. Now I need to add meta keywords and meta description to all of this terms.
My solution is :

Resave all terms by VBO module.
Create a rules on "before saving taxonomy term".
The created rules execute a PHP code which adds meta keywords and meta description to each of the tags.

In this way when VBO is resaving terms one by one my rules is executed for each of theme and do the trick.
Now the problem is in step one. I have an "execute arbitrary PHP script" operation in VBO for terms. I use this code in it:
taxonomy_term_save($entity);

but I face this error:

An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging
  information follows. Path: /backup-sar/batch?id=412&op=do StatusText:
  OK ResponseText: Fatal error: Function name must be a string in
  C:\xampp\htdocs\backup-sar\sites\all\modules\views_bulk_operations\actions\script.action.inc(20)
  : eval()'d code on line 1

This one with the same error does not work too:
taxonomy_term_load($entity->tid);
taxonomy_term_save($entity);

Any help would be appreciated. Thanks in advance.
Comment: May I know why you are using custom callback for rule? Are you not able to do it by only vbo?
Comment: @PremPatel I can do it in vbo too. The code is prepared in rules for newly added tags. So I can use it or white it in vbo. No difference. I am  looking for any possible solution.
Answer: If you're executing the VBO operation while in the Views configuration page, you're likely to run into this error. Save your view and go to the URL for that view and then run the operation.
A 200 return code actually indicates success, but the presence of the AJAX debugging screen interferes with the completion of the operation.
I know because I just ran into a nearly identical issue. :-)
Comment: I execute it in the defined url not in the views preview.

resave all taxonomy terms by vbo


Conditions on $x , y , z, t$ such that $a^x \mid b^y \Rightarrow a^z \mid b^t$ for all $a,b\in Z$

Question: Suppose for all $a , b \in \mathbb{Z}$  we have   $a^x | b^y \to a^z | b^t$ . What's the condition for $x , y , z$ and $t$ to satisfying that ? I tried to use Division algorithm but it wasn't helpful .
(Note : My guess is $xt \ge yz$ but I'm unable to proof it .)
Answer: In this answer, I'm assuming that all variables are natural numbers.
The condition $tx\ge yz$ should work. Consider, $b^y=ka^x$, so $b^{ny+l}=(k^nb^l)a^{nx}$. If we write $z=nx, t=ny+l$, this is equivalent to $\frac{t-l}y=\frac{z}x$, which implies $\frac{t}{y}\ge\frac{z}{x}$ or $tx\ge yz$.
Comment: What about $xt \ge yz$ ?
Comment: I think this works. We're assuming everything in sight is a natural number, yes? Considering negatives would add a layer of complication.
Comment: If $a , b \in \mathbb{Z}$ the condition $tx \ge yz$ also works ? (If not  can you give a counterexample ? )
Comment: Yeah, I don't see any problem there. Do you?
Comment: No I don't . I guess it works correctly .
Answer: Let the highest powers of prime $p$ that divide $a,b$ are $u,v$  respectively.
So, we have $v \ge ux/y$
So, $vt\ge  uxt/y$
It is sufficient that the later $\ge uz$
Comment: Can you explain more ?
Answer: $(a^x)^z$ divides$b^{yz}$
and. $(a^y)^x$ needs to be $b^{xt}$
So, it is sufficient to have $$yz\ge xt$$
Answer: Necessity ($\implies$): Take $a=2^y, b=2^x$, then $2^{xy}=a^x=b^y$. Then $(2^{xy})^{z/x} = a^z$ divides $b^t = (2^{xy})^{t/y}$ which means that $z/x \leq t/y$.
Sufficiency ($\impliedby$): Suppose $a^x | b^y$ then $a^{xz} | b^{yz} | b^{xt}$. But $(a^z)^x | (b^t)^x$ implies that $(b^t/a^z)^x =: k$ is an integer. Because the $x$-th root $\sqrt[x]{k} = b^t/a^z$ of an integer is either integer or irrational, $b^t/a^z$ is an integer and $a^z | b^t$.


AD Users sharing a Home Folder/Profile

Question: I'm facing a unique challenge.
As part of our transition to a new Active Directory Domain, we must ensure compliance by assigning each user a unique User Account identified by their name.surname
Given our frequent employee turnover, many users, particularly those in medical roles, will share common applications and files.
Is there a method to set up users to utilize a shared User Profile or Home Folder?
This would allow changes enforced on one user to automatically apply to others within the same group, such as software updates or printer additions.
Based on my research, it seems that Mandatory User Profiles or Roaming Profiles may not suit our needs for this scenario.
Modifying something on Profile1 would necessitate manual adjustments on Profile2, Profile3, and so forth, which isn't feasible for our requirements.
Is it feasible to link multiple sets of credentials to a single user account to avoid the hassle of managing profiles?
Thanks in advance
Answer:
Is there a method to set up users to utilize a shared User Profile or Home Folder?

Not a reliable method. It can be problematic even for the same user, but multiple sessions in different hosts. There is the potential for conflict or overwrite.

Is it feasible to link multiple sets of credentials to a single user account to avoid the hassle of managing profiles?

No, and this wouldn't solve anything.
Move the "shared" data to a folder external to the profile.
Answer:
Given our frequent employee turnover, many users, particularly those
in medical roles, will share common applications and files.

Welcome to every organization in the world. Create shared folders for users in similar roles who need access to the same data and secure accordingly. Use Group Policy to map the appropriate printers to the relevant users. Deploy your software via Group Policy (if possible). You can then apply updates to that software to all users using Group Policy.

AD Users sharing a Home Folder/Profile


How do I sample from a discrete (categorical) distribution in log space?

Question: Suppose I have a discrete distribution defined by the vector $\theta_0, \theta_1, ..., \theta_N$ such that category $0$ will be drawn with probability $\theta_0$ and so on. I then discover that some of the values in distribution are so small that they underflow my computer's floating point number representation, so, to compensate, I do all my calculations in log-space. Now I have a log-space vector $log(\theta_0), log(\theta_1), ..., log(\theta_N)$.
Is it possible to sample from the distribution such that the original probabilities hold (category $i$ is drawn with probability $\theta_i$) but without ever leaving log-space? In other words, how do I sample from this distribution without underflows?
Answer: It is possible to sample from categorical distribution given log-probabilities without leaving log space using the Gumbel-max trick. The idea is that if you are given unnormalized log-probabilities $\alpha_1,\dots,\alpha_k$, that can be translated to proper probabilities using softmax function
$$ p_i = \frac{\exp(\alpha_i)}{\sum_j \exp(\alpha_j)} $$
then to sample from such distribution you can use the fact that if $g_1,\dots,g_k \sim \mathcal{G}(0)$ are independent samples taken from standard Gumbel distribution parametrized by location $m$,
$$ F(G \le g) = \exp(-\exp(-g+m))$$
then it can be shown (see references below) that
$$ \DeclareMathOperator*{\argmax}{arg\,max}
\begin{align}
\argmax_i \,\{\, g_i + \alpha_i \,\} &\sim \frac{\exp(\alpha_i)}{\sum_j \exp(\alpha_j)} \\
\max_i\,\{\, g_i + \alpha_i \,\} &\sim \mathcal{G}(\; \log\sum_i\exp\{\alpha_i\}\;)
\end{align}
$$
and we can take
$$
z = \argmax_i \,\{\, g_i + \alpha_i \,\}
$$
as a sample from categorical distribution parametrized by $p_1,\dots,p_k$ probabilities. This approach was described in greater detail in blog entries by  Ryan Adams and Laurent Dinh, moreover Chris J. Maddison, Daniel Tarlow and Tom Minka gave a speach (slides) on Neural Information Processing Systems conference (2014) and wrote a paper titled A* Sampling that generalized those ideas (see also Maddison, 2016; Maddison, Mnih and Teh, 2016; Jang and Poole, 2016), who refer to Yellott (1977) mentioning his as the one among those who first described this property.
It is pretty easy to implement it using inverse transform sampling by taking $g_i=-\log(-\log u_i)$ where $u_i$ are draws from uniform distribution on $(0,1)$. It is certainly not the most time-efficient algorithms for sampling from categorical distribution, but it let's you to stay in log-space what may be an advantage in some scenarios.

Maddison, C. J., Tarlow, D., & Minka, T. (2014). A* sampling. [In:] Advances in Neural Information Processing Systems (pp. 3086-3094).
Yellott, J. I. (1977). The relationship between Luce's choice axiom, Thurstone's theory of comparative judgment, and the double exponential distribution. Journal of Mathematical Psychology, 15(2), 109-144.
Maddison, C. J., Mnih, A., & Teh, Y. W. (2016). The Concrete Distribution: A Continuous Relaxation of Discrete Random Variables. arXiv preprint arXiv:1611.00712.
Jang, E., Gu, S., & Poole, B. (2016). Categorical Reparameterization with Gumbel-Softmax. arXiv preprint arXiv:1611.01144.
Maddison, C. J. (2016). A Poisson process model for Monte Carlo. arXiv preprint arXiv:1602.05986.
Answer: Here is one common way to avoid underflow/overflow.
Let $m = \max_i \log(\theta_i)$.
Let $ \theta_i' = \exp( \log(\theta_i) - m )$.
You can sample from $\theta' = [\theta_1' , \theta_2',...]$.
Comment: This works as long as the difference between any one value and the max isn't too great---when that happens, the `exp` can lose precision, leading to distributions like [1.0, 3.45e-66, 0.0, 7.54e-121]. I'd like to hold out for some answer that is robust even in that case. But for now I'm upvoting your answer.


How to find the inverse of a continuous linear operator

Question: Let $X$ be a Banach space and $T$ is in the set of bounded linear operators from $X$ to $X$ and norm of $T$ is less than 1. Use contraction mapping principle show $I-T$ is an isomorphism.(I can show it is one to one, but not onto and continuous inverse)
Comment: Hint: $(1-x)^{-1} = 1 + x + x^2 + \cdots$ if $x \in (-1,1)$. Show that $$(I-T)(I + T + T^2 + \cdots) = I$$ if $\|T\| < 1$. The latter sum converging in the norm of ${\cal B}(X)$, of course.
Comment: I still dont see the hint
Comment: I will be more explicit. Show that $$S = I + T + T^2 + \cdots$$ converges in the operator norm. Then show that $(I-T)S = I$ so that $I-T$ has a right-sided inverse.
Comment: Actually $I-T$ is a linear homeomorphism by open mapping theorem.
Answer: If $I -T$ is isomorphism if for all $y \in X$ there only one $x \in X$ such that
$$x - Tx = y$$
or equivalently, $x$ is the only fixed point of map $f_y : X \to X$ given for $f_y(z) = Tz + y$. But,
$$||f_y(z) - f_y(w)|| = ||Tz - Tw|| \leq ||T||||z - w||$$
that is, $f_y$ is a contraction and therefore has only one fixed point.
Comment: I dont think this helps
Comment: I'm only used contraction mapping principle show I−T is an isomorphism. The inverse you already showed.
Comment: it makes sense, and how do you show it is onto?
Comment: It's because $\forall y \in X$  there is only one $x in X$ such that $f_y(x) = x$, but $f_y(x)= x$, this is $Tx + y = x$, if only if $y = x -Tx$
Comment: sorry, my coment was wrong, how do you show the inverse is continuous?
Comment: Follows from a corollary of Theorem of Open Map, that if an  bounded linear aplication  between Banach space is bijective, then your inverse is  bounded.


Books and bookshelves combinations w.r.t. to book order

Question: It is a practice question for my textbook.

You are given $5$ books and $7$ bookshelves. How many ways are there to place these books
  on the shelves with respect to order?

I checked the back of the book and its says $\dfrac{11!}{6!}$.
Why is it so?
Answer: Split the process of arrangement in two steps, count the ways you can conduct each step and then use the multiplication principle to find the total number of ways you can conduct the whole process. Here you need two steps.
First step. Choose the number of books that will come in each shelf. That is, determine numbers $x_1,\ldots,x_7$ such that $$x_1+x_2+\ldots+x_7=5$$ subject to $0\le x_i$. You can do that in $$\dbinom{5+7-1}{7-1}=\dbinom{11}{6}$$ ways (see here for an explanation).
Second step.Then order your books in.You can do it in $5!$ ways. But now you already know how many books come in each shelf, so determining the order was the only that was remaining.
By the multiplication principle you have that the total number of ways (i.e. both steps) is $$\dbinom{11}{6}\cdot5!=\frac{11!}{5!6!}\cdot5!=\frac{11!}{6!}$$
Comment: kil- Just an add-on to a great explanation: the problem is a variant of the "[stars and bars](http://en.wikipedia.org/wiki/Stars_and_bars_%28combinatorics%29#Theorem_two_2)" problem in combinatorics.
Answer: Put $6$  cardboard dividers on the last shelf, representing the first $6$ shelves. The first book can be placed in $7$ slots and henceforth acts as an additional divider; the second book can then be placed in $8$ slots, and becomes a divider too, and so on. In all we have $7\cdot8\cdot\ldots\cdot 11={11!\over 6!}$ choices.
Answer: The answer by Stefanos is better, since it puts together two natural ingredients. There are other ways. Imagine instead putting the books on a single shelf, together with $6$ books dividers. (Then for the real shelving, we will put the books up to the first divider onto Shelf $1$, and the books from the first divider to the second onto shelf $2$, and so on.)
Imagine that the books are called $a,b,c,d,e$. Write $D$ for a divider. We want to count the number of $11$-letter "words" that use each of $a,b,c,d,e$ once, and $6$ copies of $D$.
If the $Ds$ were distinct, say $D_1$ to $D_6$, there would be $11!$ words. Since they are identical, we divide by $6!$.
Answer: Well first book can be put on any of 7 shelves,second book can be placed 8 ways,any of the shelves and switching place with the first book.Third book can be also put on every shelf + it can be switched with the first two books and etc.
so the result is $7*8*9*10*11$


ReactNative PanResponder limit X position

Question: I'm building a Music Player and I'm focusing on the progress bar.
I was able to react to swipe gestures, but I cant limit how far that gesture goes.
This is what I've done so far. I've reduced everything to the minumal:
constructor(props) {
    super(props);

    this.state = {
      pan: new Animated.ValueXY()
    };
}

componentWillMount() {
    this._panResponder = PanResponder.create({
        onMoveShouldSetResponderCapture: () => true,
        onMoveShouldSetPanResponderCapture: () => true,
        onPanResponderGrant: (e, gestureState) => {

            // Set the initial value to the current state
            let x = (this.state.pan.x._value < 0) ? 0 : this.state.pan.x._value;

            this.state.pan.setOffset({ x, y: 0 });
            this.state.pan.setValue({ x: 0, y: 0 });

        },
        onPanResponderMove: Animated.event([
            null, { dx: this.state.pan.x, dy: 0 },
        ]),
        onPanResponderRelease: (e, { vx, vy }) => {
            this.state.pan.flattenOffset();
        }
    });
}

render() {
    let { pan } = this.state;

    // Calculate the x and y transform from the pan value
    let [translateX, translateY] = [pan.x, pan.y];
    // Calculate the transform property and set it as a value for our style which we add below to the Animated.View component
    let imageStyle = { transform: [{ translateX }, { translateY }] };

    return (
        <View style={styles.container}>
            <Animated.View style={{imageStyle}} {...this._panResponder.panHandlers} />
        </View>
    );
}

Here there is an image showing what the problem is.
Initial position:

Wrong Position, limit exceeded:

So the idea is to stop keeping moving once the limit (left as well as right) is reached. I tried checking if _value < 0, but it didn't work since It seems to be an offset, not a position.
Well any help will be appreciated.
Answer: Instead of letting your animation die at your borders, you could interpolate your
Animated.Value with y=x, but with clamping it to your width.
return (
    <View style={styles.container}>
        <Animated.View
            style={{
                transform: [{
                    translateX: this.state.pan.x.interpolate({
                        inputRange: [0, trackWidth ],
                        outputRange: [0, trackWidth ],
                        extrapolate: 'clamp'
                    })
                }],

            }}
            {...this._panResponder.panHandlers}
        />
    </View>
);

Here's a more in-depth example: https://github.com/olapiv/expo-audio-player/blob/master/src/AudioSlider.js
Answer: onPanResponderMove: (e, gestureState)=> {
    this.state.pan.x._value > 0 ? null : Animated.event([
            null,
            {dx: this.state.pan.x, dy: this.state.pan.y},
        ])(e, gestureState)
    },

Comment: The problem with this approach is that when reaching the limit, you can't move again in the other direction, because the `this.state.pan` was set as null.
Answer: I was trying to do something similar; I wanted to have it so that you can pull the page part way and then release and it goes back to where it was.
My solution was this:
panResponder = PanResponder.create({
  onMoveShouldSetPanResponderCapture: (e, { dx }) => {
    // This will make it so the gesture is ignored if it's only short (like a tap).
    // You could also use moveX to restrict the gesture to the sides of the screen.
    // Something like: moveX <= 50 || moveX >= screenWidth - 50
    // (See https://facebook.github.io/react-native/docs/panresponder)
    return Math.abs(dx) > 20;
  },
  onPanResponderMove: (e, gestureState) => (
    // Here, 30 is the limit it stops at. This works in both directions
    Math.abs(gestureState.dx) > 30
      ? null
      : Animated.event([null, { dx: this.animatedVal }])(e, gestureState)
  ),
  onPanResponderRelease: (e, { vx, dx }) => {
    // Here, abs(vx) is the current speed (not velocity) of the gesture,
    // and abs(dx) is the distance traveled (not displacement)
    if (Math.abs(vx) >= 0.5 || Math.abs(dx) >= 30) {
      doSomeAction();
    }
    Animated.spring(this.animatedVal, {
      toValue: 0,
      bounciness: 10,
    }).start();
  },
});

Answer:
This method doesn't cancel the gesture handler if the user is still holding it down after exceeding the X limit.
Change MaxDistance & MinDistance to whatever values you like
onPanResponderMove: (e, gestureState) => {
  // Configure Min and Max Values
  const MaxDistance = maxDistance;
  const MinDistance = 0;
  const dxCapped = Math.min(Math.max(parseInt(gestureState.dx), MinDistance), MaxDistance);

  // If within our bounds, use our gesture.dx....else use dxCapped
  const values = {}
  if(gestureState.dx < MaxDistance && gestureState.dx > MinDistance){
    values.dx = gestureState.dx
    values.dy = gestureState.dy
  }else{
    values.dx = dxCapped
    values.dy = gestureState.dy
  }

  //Animate Event
  Animated.event([null, {
    dx: pan.x,
    dy: pan.y,
  }])(e, values);
},

Hope this helps some folks.
Answer: A tricky point is that while I can not move the icon beyond that clamp but the pan.x value is indeed beyond the clamp limit although you don't see it. Then, when you want to move it back, you don't know how much swipe you need to move it back. This could be a nuance.
My solution is:
      onPanResponderGrant: () => {
        console.log("pan responder was granted access!")
        pan.setOffset({
          x: (pan.x._value>xMax)? xMax : (pan.x._value<xMin)? xMin: pan.x._value,
          y: (pan.y._value>yMax)? yMax : (pan.y._value<yMin)? yMin: pan.y._value,
        });
      },

Then, can also console.log pan.x._value in following to double check.
      onPanResponderRelease: () => {
        pan.flattenOffset();}

I found this helpful for my own project. Note can only use pan.x_value not pan.x.
In my case I also used useMemo instead of useRef so the limits can be reset, which I learned from React Native's panResponder has stale value from useState?
Answer: There's a solution to a similar problem on this other question: https://stackoverflow.com/a/58886455/9021210
that can be repurposed for what you're looking for
const DRAG_THRESHOLD = /*configure min value*/
const DRAG_LIMIT = /*configure max value*/

onPanResponderMove: (e, gesture) => {
   if ( (Math.abs( gesture.dy ) > DRAG_THRESHOLD) &&
        (Math.abs( gesture.dy ) < DRAG_LIMIT ) )
   {
       return Animated.event([
           null, {dx: 0, dy: pan.y}
       ]) (e, gesture)
   }
 },

This is not my answer, so I recommend you follow the link to see further explanation and if you like it upvote the original poster! :) I was trying to do the same thing and it worked for me! hope it helps.
P.S. I found that other solutions relying on checking the animation value rather than the gesture value would sometimes get stuck.


Getting a result from a prepared statement into a variable

Question: I've been trying to get a result from a prepared statement into a variable. I've looked around and found something to what I was trying to do however I'm not sure how to implement it correctly. This is how I've tried but when I run it inserts blanks into the table.
Drop procedure if exists campaignTEST;

DELIMITER  $$

Create procedure campaignTEST(in userID smallint)
sp_Campaign17:BEGIN

Declare activityCount mediumint;
Declare lastActivityDate DateTime;

Declare TableName varchar(64);

SET TableName = 'user_activity_';
SET TableName = concat(TableName, convert(userID,char(64)));

SET @lastActivityDateTest = ('SELECT @date := date from ' ,TableName, ' order by date desc limit 1;');
    PREPARE stmt FROM @lastActivityDateTest;
    EXECUTE stmt;
    Select @date AS lastActivityDate;
    DEALLOCATE PREPARE stmt;

SET @activityCountTest = ('Select @count := count(*) from ' ,TableName, ' where Month(date) > Month(Date_SUB(CURRENT_date, Interval 1 month));');
    PREPARE stmt FROM @activityCountTest;
    EXECUTE stmt;
    select @count as activityCount;
    DEALLOCATE PREPARE stmt;

INSERT INTO email_tracker
(activity_date,  allocated)
Values
(lastActivityDate, activityCount)

END$$

DELIMITER ;

Comment: I would use select..into and SET activitycount BTW you can select 2 columns into 2 variables.
Comment: I've tried that however the tables I'm pulling from the table name changes based on the user that is passed into the procedure. Which requires a dynamic sql statement, hence using a prepared statement, Can you select 2 variables even if the 1 is a count of a table?
Comment: Ahh it seems I may have miss understood what you were saying.
Answer: I managed to get it working with the help of a friend.
These statements,
SET @lastActivityDateTest = ('SELECT @date := date from ' ,TableName, ' order by date desc limit 1;');
    PREPARE stmt FROM @lastActivityDateTest;
    EXECUTE stmt;
    Select @date AS lastActivityDate;
    DEALLOCATE PREPARE stmt;

SET @activityCountTest = ('Select @count := count(*) from ' ,TableName, ' where Month(date) > Month(Date_SUB(CURRENT_date, Interval 1 month));');
    PREPARE stmt FROM @activityCountTest;
    EXECUTE stmt;
    select @count as activityCount;
    DEALLOCATE PREPARE stmt;

INSERT INTO email_tracker
(activity_date,  allocated)
Values
(lastActivityDate, activityCount)

Should have been this
SET @statement = CONCAT('SELECT date into @result from ', TableName, ' ORDER BY date DESC LIMIT 1');
PREPARE stmt FROM @statement;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @statement = CONCAT('SELECT count(*) into @result2 from ', TableName, ' where Month(date) > Month(Date_SUB(CURRENT_date, Interval 1 month));');
PREPARE stmt FROM @statement;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

INSERT INTO email_tracker
(activity_date,  allocated)
Values
(@result, @result2)


405 on Exporting CSV file in django

Question: I'm trying to export some data to downloadable csv file. When I click "Export" button on my website everything works up to a point when I get 405 response. The post method works as expected, in response I see all expected data. The filtering ptocess below works as expected as well.
Here is the view class:
class ExportInvoicesToCsvView(View, IsSuperuserMixin):
    http_method_names = ['post', 'get']

    def post(self, request, *args, **kwargs):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = (
            'attachment; filename=raport.csv'
        )

        writer = csv.writer(response, delimiter=';')

        filters = json.loads(self.request.body.decode('utf8'))
        data = Data.objects.filter(filters)

        writer.writerow([
            'data.a', 'data.b', 'data.c', 'data.d', 'data.e'
        ])

        return response

The url config is as follows:
url(
        r'^invoices-csv/$',
        ExportInvoicesToCsvView.as_view(),
        name='invoices-csv'
    ),

And html template:

     {% trans 'Exportuj do csv' %}

EDIT
Here is console log.
Method Not Allowed (GET): /accountant/bills/invoices-csv/
[27/Oct/2017 16:41:12] "GET /accountant/bills/invoices-csv/ HTTP/1.1" 405 0
[27/Oct/2017 16:41:15] "POST /accountant/bills/invoices-csv/ HTTP/1.1" 200 0

As I can see there is some sort of problem with methods used. nonetheless I am able to step into the post method and get data I want.
Answer: I think you need quotes around the filename part of your Content-Disposition definition. This:
response['Content-Disposition'] = (
        'attachment; filename=raport.csv'
    )

Should be this:
response['Content-Disposition'] = (
        'attachment; filename="raport.csv"'
    )

Comment: It seems there were 2 problems with my code. I can accept only 1 answer but I'm giving this an upvote since it also helped.
Answer: You shouldn't need http_method_names. Generally speaking, Django views will only process requests for HTTP verbs if a corresponding method exists in the view class. So, since your view has a post, method, that's enough to tell Django that this view handles POST requests.
A 405 response means Method Not Allowed.
It doesn't look like your template is making a POST request. Without seeing the getSelected() function, I can't know for certain, but I'd guess that you're not actually making a POST; you're making a GET, and since your view doesn't implement a get() method, you're seeing the 405 response.
Try the following:

remove the http_method_names
make sure you're actually making a POST request from your template (use your browser's developer tools to inspect the network request).
Comment: I've changed `post` to `get` and it started to work more or less (I get 405 on POST this time) but I'm albe to download the file. I'll investigate it further.
Comment: Then that's proof that you're not making a `POST` request from your template. Your `` tag is just a link to the view (`GET`). Ask yourself; why do I need `POST`?
Comment: It's for changing data on server as far as I remember. True, it should be only GET.

405 on Exporting CSV file in django