Interpretation of R's lm() output

Question: The help pages in R assume I know what those numbers mean, but I don't.
I'm trying to really intuitively understand every number here. I will just post the output and comment on what I found out. There might (will) be mistakes, as I'll just write what I assume. Mainly I'd like to know what the t-value in the coefficients mean, and why they print the residual standard error.
Call:
lm(formula = iris$Sepal.Width ~ iris$Petal.Width)

Residuals:
     Min       1Q   Median       3Q      Max
-1.09907 -0.23626 -0.01064  0.23345  1.17532

This is a 5-point-summary of the residuals (their mean is always 0, right?). The numbers can be used (I'm guessing here) to quickly see if there are any big outliers. Also you can already see it here if the residuals are far from normally distributed (they should be normally distributed).
Coefficients:
                 Estimate Std. Error t value Pr(>|t|)
(Intercept)       3.30843    0.06210  53.278  < 2e-16 ***
iris$Petal.Width -0.20936    0.04374  -4.786 4.07e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Estimates $\hat{\beta_i}$, computed by least squares regression. Also, the standard error is $\sigma_{\beta_i}$. I'd like to know how this is calculated.  I have no idea where the t-value and the corresponding p-value come from. I know $\hat{\beta}$ should be normal distributed, but how is the t-value calculated?
Residual standard error: 0.407 on 148 degrees of freedom

$\sqrt{ \frac{1}{n-p} \epsilon^T\epsilon }$, I guess. But why do we calculate that, and what does it tell us?
Multiple R-squared: 0.134,  Adjusted R-squared: 0.1282

$ R^2 = \frac{s_\hat{y}^2}{s_y^2} $, which is $ \frac{\sum_{i=1}^n (\hat{y_i}-\bar{y})^2}{\sum_{i=1}^n (y_i-\bar{y})^2} $. The ratio is close to 1 if the points lie on a straight line, and 0 if they are random.  What is the adjusted R-squared?
F-statistic: 22.91 on 1 and 148 DF,  p-value: 4.073e-06

F and p for the whole model, not only for single $\beta_i$s as previous. The F value is $ \frac{s^2_{\hat{y}}}{\sum\epsilon_i} $. The bigger it grows, the more unlikely it is that the $\beta$'s do not have any effect at all.
Comment: Minor quibble: You cannot say anything about normality or non-normality based on those 5 quantiles alone. All you can say based on that summary is whether the estimated residuals are approximately symmetric around zero.  You could divide the reported quantiles by the estimated residual standard error and compare these values to the respective quantiles of the N(0,1), but looking at a QQ-plot probably makes more sense.
Comment: One note here: the model $F$ is not $SS_{model} / SS_{error}$, rather it is $MS_{model} / MS_{error}$. $F$ is described correctly in the answer below, but it does not explicitly mention that it is mischaracterized in the question, so someone might not notice the discrepancy.
Comment: residuals are not so badly deviating from normality, why do you think so?
Comment: @nico: I think @Alexx Hardt was speaking hypothetically. I.e. once *could* use the five number summary to see if residuals were deviating from normal
Comment: @Gavin Simpson: you're right, I misread the sentence. Disregard my previous comment.
Answer: Five point summary
yes, the idea is to give a quick summary of the distribution. It should be roughly symmetrical about mean, the median should be close to 0, the 1Q and 3Q values should ideally be roughly similar values.
Coefficients and $\hat{\beta_i}s$
Each coefficient in the model is a Gaussian (Normal) random variable. The $\hat{\beta_i}$ is the estimate of the mean of the distribution of that random variable, and the standard error is the square root of the variance of that distribution. It is a measure of the uncertainty in the estimate of the $\hat{\beta_i}$.
You can look at how these are computed (well the mathematical formulae used) on Wikipedia. Note that any self-respecting stats programme will not use the standard mathematical equations to compute the $\hat{\beta_i}$ because doing them on a computer can lead to a large loss of precision in the computations.
$t$-statistics
The $t$ statistics are the estimates ($\hat{\beta_i}$) divided by their standard errors ($\hat{\sigma_i}$), e.g. $t_i = \frac{\hat{\beta_i}}{\hat{\sigma_i}}$. Assuming you have the same model in object modas your Q:
> mod <- lm(Sepal.Width ~ Petal.Width, data = iris)

then the $t$ values R reports are computed as:
> tstats <- coef(mod) / sqrt(diag(vcov(mod)))
(Intercept) Petal.Width
  53.277950   -4.786461

Where coef(mod) are the $\hat{\beta_i}$, and sqrt(diag(vcov(mod))) gives the square roots of the diagonal elements of the covariance matrix of the model parameters, which are the standard errors of the parameters ($\hat{\sigma_i}$).
The p-value is the probability of achieving a $|t|$ as large as or larger than the observed absolute t value if the null hypothesis ($H_0$) was true, where $H_0$ is $\beta_i = 0$. They are computed as (using tstats from above):
> 2 * pt(abs(tstats), df = df.residual(mod), lower.tail = FALSE)
 (Intercept)  Petal.Width
1.835999e-98 4.073229e-06

So we compute the upper tail probability of achieving the $t$ values we did from a $t$ distribution with degrees of freedom equal to the residual degrees of freedom of the model. This represents the probability of achieving a $t$ value greater than the absolute values of the observed $t$s. It is multiplied by 2, because of course $t$ can be large in the negative direction too.
Residual standard error
The residual standard error is an estimate of the parameter $\sigma$. The assumption in ordinary least squares is that the residuals are individually described by a Gaussian (normal) distribution with mean 0 and standard deviation $\sigma$. The $\sigma$ relates to the constant variance assumption; each residual has the same variance and that variance is equal to $\sigma^2$.
Adjusted $R^2$
Adjusted $R^2$ is computed as:
$$1 - (1 - R^2) \frac{n - 1}{n - p - 1}$$
The adjusted $R^2$ is the same thing as $R^2$, but adjusted for the complexity (i.e. the number of parameters) of the model. Given a model with a single parameter, with a certain $R^2$, if we add another parameter to this model, the $R^2$ of the new model has to increase, even if the added parameter has no statistical power. The adjusted $R^2$ accounts for this by including the number of parameters in the model.
$F$-statistic
The $F$ is the ratio of two variances ($SSR/SSE$), the variance explained by the parameters in the model (sum of squares of regression, SSR) and the residual or unexplained variance (sum of squares of error, SSE). You can see this better if we get the ANOVA table for the model via anova():
> anova(mod)
Analysis of Variance Table

Response: Sepal.Width
             Df  Sum Sq Mean Sq F value    Pr(>F)
Petal.Width   1  3.7945  3.7945   22.91 4.073e-06 ***
Residuals   148 24.5124  0.1656
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The $F$s are the same in the ANOVA output and the summary(mod) output. The Mean Sq column contains the two variances and $3.7945 / 0.1656 = 22.91$. We can compute the probability of achieving an $F$ that large under the null hypothesis of no effect, from an $F$-distribution with 1 and 148 degrees of freedom. This is what is reported in the final column of the ANOVA table. In the simple case of a single, continuous predictor (as per your example), $F = t_{\mathrm{Petal.Width}}^2$, which is why the p-values are the same. This equivalence only holds in this simple case.
Comment: @Gavin (+1) Great response with nice illustrations!
Comment: Nice job. One thing you might clarifiy, with regard to calculating t values: sqrt(diag(vcov(mod))) produces the SE of the estimates. These are the same SEs that are output in the model summary. Easier and clearer just to say that t = Estimate/SEestimate.  In that sense it is no different that any other t value.
Comment: (+1) This is great.  The only thing I'd add is that the $F$ value is the same as $t^2$ for the slope (which is why the p values are the same).  This - of course - isn't true with multiple explanatory variables.
Comment: @Jay; thanks. I thought about mentioning that equivalence too. Wasn't sure if it was too much detail or not? I'll ad something on this in a mo.
Comment: "will not use the standard mathematical equations to compute" What will they use?
Comment: @StudentT R uses a [QR decomposition](http://en.wikipedia.org/wiki/QR_decomposition) to avoid inverting a matrix which would be required if it just literally did the matrix algebra of the matrix equations shown in text books. Computers only do floating point arithmetic and that can cause issues in some circumstances so algorithms have been developed to minimise those issues.
Comment: @Brett; thanks. I've tried to clarify this a bit above as per your comment.
Comment: In the line "The p-value is the probability of achieving .... They are computed as (using tstats from above)" you are writting that the null is $H_{0}: \hat{\beta}_i=0$, but in fact we are not testing whether the estimator is zero, but the true parameter. So it should be $H_{0}: \beta_i=0$, right?
Comment: @MichaelL. Right; we assume the true value of $\beta_i$ is zero and we know that the estimator ($\hat{\beta}_i$) is not zero because we just computed a non-zero value. Knowing me I was probably being lazy and copying and pasting latex around in the answer and forgot to correct this.
Comment: This will take some time and playing around with R to understand. Big thanks for now, I might follow up with some questions at some point :)
Comment: Am I wrong in thinking that a less confusing name for "residual standard error" would be "residual standard deviation"?
Comment: I would like to add that we only use the right tail for the $F$ test here`> pf(22.91, df1=1, df2=148, lower.tail = FALSE) [1] 4.073605e-06`  and we use both tails for the $t$ test `2 * pt(abs(tstats), df = df.residual(mod), lower.tail = FALSE)` https://stats.stackexchange.com/questions/549757/why-does-overall-f-test-is-considering-right-tailed-only
Answer: Ronen Israel and Adrienne Ross (AQR) wrote a very nice paper on this subject: Measuring Factor Exposures: Uses and Abuses.
To summarize (see: p. 8),

Generally, the higher the $R^2$ the better the model explains portfolio returns.
When the t-statistic is greater than two, we can say with 95% confidence (or a 5% chance we are wrong) that the beta estimate is statistically different than zero. In other words, we can say that a portfolio has significant exposure to a factor.

R's lm() summary calculates the p-value Pr(>|t|). The smaller the p-value is, the more significant the factor is. P-value = 0.05 is a reasonable threshold.
Comment: The kinds of misstatements in this paper, exemplified by "When the t-statistic is greater than two, we can say (with ... a 5% chance we are wrong) that the beta estimate is statistically different from zero" [at p. 11], are discussed at https://stats.stackexchange.com/questions/311763 and https://stats.stackexchange.com/questions/26450.
Comment: @Pake fixed link
Comment: Link to the paper seems to be dead now.

Interpretation of R's lm() output


Cascading two comboboxes - Child Combobox not selecting current value

Question: Issue Summary
When using 2 cascading comboboxes, the child combobox does not select the current item, instead an empty item (I don't know where it comes from!) gets selected.
Issue Details
I have two comboboxes declared in xaml as given below. The two entities in play are StandardRack and RelayConfig
XAML:
<ComboBox ItemsSource="{Binding StandardRacks}" DisplayMemberPath="Name"
          SelectedItem="{Binding StandardRack, Mode=TwoWay}"  SelectedValuePath="Id"

<ComboBox ItemsSource="{Binding RelayConfigs}" DisplayMemberPath="DisplayName"
          SelectedValue="{Binding DefaultRelayConfig, Mode=TwoWay}" SelectedValuePath="Id"

Here are the backing properties, and code to load comboboxes in ViewModel
ViewModel
private ObservableCollection<StandardRack> _standardRacks;
public ObservableCollection<StandardRack> StandardRacks {
    get { return _standardRacks; }
    set { _standardRacks = value; RaisePropertyChanged(() => StandardRacks); }
}

private StandardRack _standardRack;
public StandardRack StandardRack {
    get { return _standardRack; }
    set {
        if (_standardRack != value) {
            _standardRack = value;
            LoadRelayConfigs();
            RaisePropertyChanged(() => StandardRack);
        }
    }
}

private ObservableCollection<RelayConfig> _relayConfigs;
public ObservableCollection<RelayConfig> RelayConfigs {
    get { return _relayConfigs; }
    set { _relayConfigs = value; RaisePropertyChanged(() => RelayConfigs); }
}

private RelayConfig _defaultRelayConfig;
public RelayConfig DefaultRelayConfig {
    get { return _defaultRelayConfig; }
    set { _defaultRelayConfig = value; RaisePropertyChanged(() => DefaultRelayConfig); }
}

private void LoadRack() {
    StandardRacks = new ObservableCollection<StandardRack>(
                    unitOfWork.StandardRackRepository.GetQueryable().Include(sr => sr.StandardRelay).ToList());
    if (StandardRacks.Count > 0) {
        StandardRack = Rack.StandardRack; //Set the current value of StandardRacks combobox
    }
}

//Loads RelayConfigs Combobox based on Current Value of StandardRacks Combobox

private void LoadRelayConfigs() {
    RelayConfigs = new ObservableCollection<RelayConfig>(
        unitOfWork.RelayConfigRepository.GetQueryable()
        .Where(rc => rc.StandardRelays.Any(srl => srl.Id == StandardRack.StandardRelay.Id)).ToList());
    DefaultRelayConfig = Rack.DefaultRelayConfig; //Set Current Value of RelayConfigs Combobox. Does not work.
}

The above code loads both the comboboxes (StandardRacks and RelayConfigs) items properly. However the RelayConfigs selected value is not set to the one it is pointing to from XAML. Instead I get an empty item in the RelayConfigs Combobox as the current item.
Answer: Is the 'DefaultRelayConfig' part of the 'RelayConfigs' selection?
Comment: Actually, it is not. Its loaded in the previous Unit Of Work. And that seems to be the issue. Well, but the SelectedValuePath="Id" should take care of that ?
Comment: Diego, DefaultRelayConfig is not the part of the RelayConfigs collection (you asked for selection, I am confused by what you meant). But the DefaultRelayConfig.Id and the RelayConfigs RelayConfig.Id are same so, I was hoping SelectedValuePath="Id" should select the correct RelayConfig from RelayConfigs collection.
Comment: @DiegoModoloRiberio - asking for clarification should be in a comment, not an answer.
Comment: Sorry @WonkotheSane. I'll not do that again.
Comment: @Nirvan, I think the problem is that. Could you post a sample of your project so I could take a better look at it?
Comment: @DiegoModoloRibeiro: Not a problem - just a clarification of how things are usually done 'round here.  Please keep contributing!


Correlation between a continuous variable and a discrete quantitative, count variable

Question: I guess this is a classic statistical question but I can not find any clear answers (or at least one that I can understand) about my problem on the net.
I work in biology and I try to highlight a link between two variables. The first variable is a continuous quantitative variable (it is a measure of the intensity of a given signal, between 0 and 200). The second variable is a discrete quantitative variable (it is the number of stimulations that I do, between 0 and 4; so it is integer, count variable). For each stimulation, I have a number of measurements of my signal (between 4 and 15 measurements).
I have illustrated the kind of measurements that I obtain using a boxplot representation.

I try to highlight the fact that the intensity of my (continuous) signal is correlated to my stimulation number (discrete). I do not think the Pearson or Spearman tests/coefficient are adequate in my case.
Could you tell me what is the statistical approach to follow?
Ideally, I would like to have a value, between -1 and 1, indicating if my variables are linked or not as well as a p-value to determine if they are significantly linked.
Edit
Thank you very much for your feedback and answers. To answer the different points, I went to the Department of Biostatistics and discussed with some folks there.
Many of them told be that I cannot use the Pearson or Spearman tests/coefficient. I went then to the conclusion that "the Pearson or Spearman tests/coefficient are adequate in my case.". From my understanding, I cannot use the Pearson test because of the fact that my data are not normally distributed.. The student gave me this paper to read: https://www.ncbi.nlm.nih.gov/pubmed/22563845. I have no mathematical background at all but my understanding is that I can use the coefficient but non the p-value of the test.. In my case, I really need to have the p-value. It seems that I cannot have/use the test if my data are not normal, so I need to transform them... I have no idea by what to start with..
For the Spearman coefficient and its associated p-value, the software that I am using do not want to provide me a results because of the ties..
I had the feeling that many people at the Department have an idea, but they all have a different solution. I am trying to see in the literature, if someone had the exact same problem ?
Regarding the Binomial regression, will it provide me a coefficient and p-value?
Comment: The dataset sounds small enough to post here should you wish detailed guidance. You're describing your response as continuous but bounded variables have characteristic relations between mean and variance. Consider that a mean of 0 or 200 must mean, in both cases, that all measurements are identical; hence variance must be 0 at the extremes. Conversely variability tends to be maximum for intermediate values. Hence binomial is likely to be roughly correct as a model, more so than normal.
Comment: `I do not think the Pearson or Spearman tests/coefficient are adequate in my case.` Please explain why
Comment: Given a concern for whether there is a relationship here and whether you can claim significance (at conventional levels) I see no reason why you should not use Spearman correlation here. Indeed I see no reason why you should not use Pearson corelation here. You don't explain your reasoning to the contrary. There is some concern that correlation implies a linear model intensity $= a + b$ stimulation number, which is probably not the best model here: Poisson regression is likely to supply a better model. FWIW, I imagine on the evidence of your graph that significance is not an issue.
Comment: For your paper or dissertation fix the typo "mesurements" if you're presenting in English.
Comment: Noting further that the measure is bounded I would revise my suggestion to some kind of binomial regression. The fact that variability is maximum at around 100 is consistent with that.
Comment: Binomial regression will model the relationship, a better achievement statistically and scientifically than a correlation, here at most descriptive. Yes; P-values will be provided.
Answer: This is a wrong statement, I do not have the answer for her problem but: You cannot use here the Pearson coefficient of correlation because the two variables do not follow each a normal distribution (one of them is a discrete variable). Moreover, she cannot use Spearman because there will be many cases with ties (equals value because of the 4 categories)...

Sorry, if I was too straightforward in my answer.
There is not need to rewrite hundreds of books and courses :). The is just a need to read carefully wikipedia. https://en.wikipedia.org/w/index.php?title=Pearson_correlation_coefficient#Testing_using_Student.27s_t-distribution.
As you will see, you cannot use Pearson coefficient and p-value if your data are not normal (at least the p-value computed by the traditional Student t-test)..
I can see the problem of Jess as we had the same problem, but we did not find the solution..
Comment: This is mostly incorrect as stated. 1. Suppose $x$ is uniformly distributed; $y = a + bx, b > 0$ therefore is also uniformly distributed. If your point of view is that lack of normality makes Pearson correlation (identically 1) invalid or inapplicable, you need to rewrite hundreds of books and courses. What you may be driving at is that inference levels for correlations requires some care, but we've had the bootstrap for nearly 40 years as I write. 2. Ties may make Spearman a little more problematic; they don't mean that you "cannot use" Spearman or even that you should not use it.
Comment: As Nick said (and I agree), that is generally incorrect answer in both its statements.
Comment: Please register &/or merge your accounts (you can find information on how to do
this in the **My Account** section of our [help]), then you will be able to
edit & comment on your own question.
Comment: Also please [edit] your answer to specify what statement you are referring to.


yum Proxy connection failed: 407 on redhat 6.5

Question: I keep getting yum proxy connection failed error 407 even though it seems like yum is able to successfully reach the proxy.
I have log from running yum below with highest debug and error to do list packages command:
# yum -d 10 -e 10 --rpmverbosity debug --enablerepo=\* list packages
Not loading "rhnplugin" plugin, as it is disabled
Loading "product-id" plugin
Loading "security" plugin
Loading "subscription-manager" plugin
Running "config" handler for "security" plugin
Running "config" handler for "subscription-manager" plugin
Updating Subscription Management repositories.
Proxy connection failed: 407
Config time: 0.202
Yum Version: 3.2.29
COMMAND: yum -d 10 -e 10 --rpmverbosity debug --enablerepo=* list packages
Installroot: /
Ext Commands:

   packages
Setting up Package Sacks
epel-debuginfo/metalink                                                                                | 2.4 kB     00:00
epel-debuginfo                                                                                | 3.0 kB     00:00
epel-debuginfo/primary_db                                                                                | 675 kB     00:00
epel-source/metalink                                                                                | 2.4 kB     00:00
epel-source                                                                                | 3.5 kB     00:00
epel-source/primary_db                                                                                | 1.8 MB     00:00
epel-testing/metalink                                                                                | 3.0 kB     00:00
Using older repomd.xml
  Latest: Sat May  6 05:04:26 2017
  Using: Fri May  5 22:12:48 2017
epel-testing                                                                                | 4.3 kB     00:00
epel-testing/primary_db                                                                                | 362 kB     00:00
epel-testing-debuginfo/metalink                                                                                | 3.0 kB     00:00
epel-testing-debuginfo                                                                                | 3.0 kB     00:00
epel-testing-debuginfo/primary_db                                                                                |  22 kB     00:00
epel-testing-source/metalink                                                                                | 3.0 kB     00:00
epel-testing-source                                                                                | 3.5 kB     00:00
epel-testing-source/primary_db                                                                                |  90 kB     00:00
rhel-source                                                                                | 2.6 kB     00:00 ...
rhel-source/primary_db                                                                                | 2.0 MB     00:04 ...
rhel-source-beta                                                                                | 1.3 kB     00:00 ...
rhel-source-beta/primary                                                                                |  214 B     00:00 ...
rpmfusion-free-updates-debuginfo                                                                                | 3.0 kB     00:00
rpmfusion-free-updates-debuginfo/primary_db                                                                                |  16 kB     00:00
rpmfusion-free-updates-source                                                                                | 3.0 kB     00:00
rpmfusion-free-updates-source/primary_db                                                                                |  30 kB     00:00
rpmfusion-free-updates-testing                                                                                | 3.6 kB     00:00
rpmfusion-free-updates-testing/primary_db                                                                                | 1.3 kB     00:00
rpmfusion-free-updates-testing-debuginfo                                                                                | 3.0 kB     00:00
rpmfusion-free-updates-testing-debuginfo/primary_db                                                                                | 1.3 kB     00:00
rpmfusion-free-updates-testing-source                                                                                | 2.9 kB     00:00
rpmfusion-free-updates-testing-source/primary_db                                                                                | 1.3 kB     00:00
rpmfusion-nonfree-updates-debuginfo                                                                                | 3.0 kB     00:00
rpmfusion-nonfree-updates-debuginfo/primary_db                                                                                | 4.9 kB     00:00
rpmfusion-nonfree-updates-source                                                                                | 3.0 kB     00:00
rpmfusion-nonfree-updates-source/primary_db                                                                                | 7.3 kB     00:00
rpmfusion-nonfree-updates-testing                                                                                | 3.6 kB     00:00
rpmfusion-nonfree-updates-testing/primary_db                                                                                | 1.3 kB     00:00
rpmfusion-nonfree-updates-testing-debuginfo                                                                                | 3.0 kB     00:00
rpmfusion-nonfree-updates-testing-debuginfo/primary_db                                                                                | 1.3 kB     00:00
rpmfusion-nonfree-updates-testing-source                                                                                | 2.9 kB     00:00
rpmfusion-nonfree-updates-testing-source/primary_db                                                                                | 1.3 kB     00:00
webtatic-archive                                                                                | 2.9 kB     00:00
webtatic-archive/primary_db                                               92% [===========================================================     ] 343 kB/s | 2.3 MB     00:00 ETA

Is it ok ignore this error? Is yum impacted in its functionality somehow, and if so, how should I fix it?
I have already configured the proxy properly via environment variables (http_proxy, ftp_proxy, etc) and also via /etc/yum.conf
I know the proxy configuration is correct because yum is able to do list packages as above. And there is even a progress bar reflecting for the download.
Answer: Try removing the environmnet variables for proxy / yum.conf proxy entries etc and entering the proxy details in /etc/rhsm/rhsm.conf .


RBF kernel algorithm Python

Question: I have this algorithm to compute the RBF kernel and it seems to work just fine. But I would like to understand what kind of operations are involved, for example:

What are the trnorms vectors? What are they for?
What is the meaning of creating the matrices k1 and k2?
Is this algorithm any different from the sklearn implementation?

def compute_RBF(mat1, mat2, sigma):

    trnorms1 = np.mat([(v * v.T)[0, 0] for v in mat1]).T
    trnorms2 = np.mat([(v * v.T)[0, 0] for v in mat2]).T

    k1 = trnorms1 * np.mat(np.ones((mat2.shape[0], 1), dtype=np.float64)).T

    k2 = np.mat(np.ones((mat1.shape[0], 1), dtype=np.float64)) * trnorms2.T

    k = k1 + k2

    k -= 2 * np.mat(mat1 * mat2.T)

    k *= - 1./(2 * np.power(sigma, 2))

    return np.exp(k)

Comment: Voting leave open: Seems focused on the statistical meaning behind the code, i.e. not really a programming question.
Answer: Say that mat1 is $n \times d$ and mat2 is $m \times d$.
Recall that the Gaussian RBF kernel is defined as $k(x, y) = \exp\left( - \frac{1}{2 \sigma^2} \lVert x - y \rVert^2 \right)$.
But we can write $\lVert x - y \rVert^2$ as $(x - y)^T (x - y) = x^T x + y^T y - 2 x^T y$. The code uses this decomposition.
First, the trnorms1 vector stores $x^T x$ for each input $x$ in mat1, and trnorms2 stores $y^T y$ for each $y$ in mat2.
Then, the k1 matrix is obtained by multiplying the $n \times 1$ matrix of $x^T x$ entries by a $1 \times m$ matrix of ones, getting an $n \times m$ matrix with $x^T x$ entries repeated across the rows, so that k1[i, j] is $x_i^T x_i$.
The next line does basically the same thing for the $y$ norms repeated across columns, getting an $n \times m$ matrix with k2[i, j] of $y_j^T y_j$.
k is then their sum, so that k[i, j] is $x_i^T x_i + y_j^T y_j$. The next line then subtracts twice the product of the data matrices, so that k[i, j] becomes $x_i^T x_i + y_j^T y_j - 2 x_i^T y_j = \lVert x_i - y_j \rVert^2$.
Then, the code multiplies by $\frac{-1}{2 \sigma^2}$ and finally takes the elementwise $\exp$, getting out the Gaussian kernel.
If you dig into the scikit-learn implementation, it's exactly the same, except:

It's parameterized instead with $\gamma = \frac{1}{2 \sigma^2}$.
It's written in much better Python, not wasting memory all over the place and doing computations in a needlessly slow way.
It's broken up into helper functions.

But, algorithmically, it's doing the same basic operations.
Comment: If the matrices are of different sizes (one is $n \times d$ and one is $m \times d$, how are you able to do the $2x^Ty$ operation?
Comment: @guy $x$ and $y$ here are each $d \times 1$. In matrix form, the code is using `mat1 * mat2.T`, which (assuming things are in numpy matrices, which you probably shouldn't use, and instead use Python 3.6+'s `mat1 @ mat2.T` matrix multiplication operator) is multiplying an $n \times d$ matrix by a $d \times m$ matrix, getting an $n \times m$ result.
Comment: I guess what I don't understood is where in the code you are computing the RBF kernel between two different size matrices. Because each matrix has the same number of columns but not the same number of rows so how can you find the norm for the rows that don't exist? Maybe I am lost cause the code is written in a roundabout way.....
Comment: OP's code is tbf pretty roundabout. Check out [`sklearn.metrics.pairwise.euclidean_distances`](https://github.com/scikit-learn/scikit-learn/blob/1495f69242646d239d89a5713982946b8ffcf9d9/sklearn/metrics/pairwise.py#L165) instead maybe; [`rbf_kernel`](https://github.com/scikit-learn/scikit-learn/blob/1495f69242646d239d89a5713982946b8ffcf9d9/sklearn/metrics/pairwise.py#L95) is very simple given that.

RBF kernel algorithm Python


Reverse entity reference lookup

Question: I have a data structure where content type research has an entity reference field scientists.
The content type scientists does not have any research reference entity field though.
I can get all scientists that a particular research has through research.
But is there a way to get all researches one particular scientist has? When content types were created I wasn't involved, so I'm trying to see my options whether I can somehow click a checkbox to make this applicable.
When I tried to set up a field with type of entity reference and pointed it to research for scientists, they were empty.
Any help is highly appreciated.
Comment: Does this answer your question? [View for Entity Reference reverse, backwards forwards](https://drupal.stackexchange.com/questions/255447/view-for-entity-reference-reverse-backwards-forwards)
Comment: Have you had a look at [Reverse Entity Reference](https://www.drupal.org/project/reverse_entity_reference), yet?
Comment: @leymannx thanks again for your help. I'm using Drupal 9 actually, but the second link might be helpful. I don't need this in a view but in a preprocess function, so I'm wondering whether this will create the referenced entities when I go along.
Answer:
Is there a way to get all researches one particular scientist has?

Yes, search for the scientist target id:
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'type' => 'research',
  'field_scientists' => $scientist_id,
]);

Comment: +1 upvote. This also works in Drupal 9, 9.3.x - from personal experience - thank you!
Comment: need a similar soluton but where Entity Reference UUID is used: https://drupal.stackexchange.com/questions/310697/programmatically-get-child-nodes-referencing-parent-by-entity-reference-uuid-us please.

Reverse entity reference lookup


Why is it so hard to count beats and play at the same time?

Question: I am just beginning to learn to play the piano on my own. I seem to have much difficulties keeping the beats and play the notes at the same time. For example, I have been practicing on this same measure for 2 hours and there is absolutely no progress at all. It seems okay with 1 hand, but when I combined the 2 hands, I either miss this or that. Is it just me, or should I practice harder? Granted, it's a romantic classical 4/4 piece, the bass clef has uniform 8th notes, but the treble has a variety of quarter, 8th, and 16th notes; some are dotted, making the timing even harder.
I guess I wanted some assurance that spending several hours to learn 1 measure is not too much. Or maybe I should move on to some other hobby that is easier.
Comment: Have you tried slowing down the pace extremely? It's pretty normal that you are having trouble as a beginner. I had a lot of trouble myself. I remember the teacher asking me why I was fighting with the metronome. :D The only trick is to play really slowly. Hands separate first. Make sure you know both hands separately. You should be able to play them blindfolded even.
Comment: Can you play the passage ABSOLUTELY correctly, every time, with seperate hands? If not, practice slower. You seem to be referring to the results within one practice session. Sleep on it. You'll be surprised!
Comment: see https://music.stackexchange.com/questions/73768/is-it-hopeless-in-terms-of-becoming-decent-musicians-if-they-cant-count-beats
Comment: Possible duplicate of [Is it hopeless in terms of becoming decent musicians, if they cant count beats?](https://music.stackexchange.com/questions/73768/is-it-hopeless-in-terms-of-becoming-decent-musicians-if-they-cant-count-beats)
Answer: A couple of possibilites come to mind when I read your question.
It's possible that you are starting with a piece that's simply too difficult.  I don't think it's a terrible thing that you've taken hours to learn one measure (all piano players started somewhere!), but it's a strong indicator that you might be trying "too much, too fast".
If you go to a music store, you can often find "graded" piano books (Beginner, Intermediate, Advanced).  Start with a "Beginner" book.  The songs may seem too easy, but give them a chance.  They are a good way to give yourself some practice on the keyboard - and with reading music.
Also, as @Raskolnikov mentioned in the comments, playing a piece very slowly is often helpful.  Play it slow enough that you can get every note correct, then speed up gradually as you get more comfortable.
Another thing that helps me is to listen to the song I'm learning.  Become familiar with how it sounds.  Listen to both the left and right hand parts.  Read along with the music as it's playing.  I find this to be a great exercise, very helpful in getting comfrtable with a new piece I'm learning.
Finally, this answer to another question has some great tips for practicing a piece.
Answer: The process of performing on any instrument requires learning to do several things at once. This is why you have to start out with simple musical excercises and progress through more challenging ones. It is called "learning to walk before you try to run". It can be very discouraging to beginners but it is necessary.
So please do not be discouraged. You are encountering the same problems that all musicians encountered when they were beginners.


Exercice 5 page 24 of do Carmo book

Question: A regular parametrized curve $\alpha $ has the property that all tangent lines pass thought a fixed point
a. Prove that $\alpha $ is a (segment of a) stright line
b. Does the conclusion in part  still hold if $\alpha $ is not regular ?
answer
a. For the first question we have $\alpha(s)+\lambda(s) \alpha^{'}(s)=cst$
this implies $(1+\lambda^{'}(s))\alpha^{'}(s)+\lambda(s)k(s)n(s)=0$
as $\lambda^{'}(s)=-1$ then $\alpha(s)\neq 0$  and $k(s)=0$ so $\alpha$ is a straight line or a segment of a straight line
b. The answer is no, but what is $\alpha$ in this case , in my opinion if $\alpha$ is a closed curve then the image of $\alpha $ can be polygons what do you think ?
Answer: Take a $C^{\infty}$ parametrisation for the "edge" from $(0,1)$ over $(0,0)$ to $(1,0)$.

Exercice 5 page 24 of do Carmo book


Seemingly pointless eval on local variables in a function

Question: I've got some legacy bash code left from a former employee to rewrite (and add documentation while I'm at it). I don't get what is the point of the last two eval lines, considering those variables are local.
function gen_data_dir {
    local NAME="$1"
    local DB_DIR_VAR="$2"
    local TECH_DIR_VAR="$3"

    local CFG="$DB_CONFIGS_DIR/$NAME"
    if [[ ! -f "$CFG" ]]; then
        echo "no config: $CFG" > /dev/stderr
        return 127
    fi
    echo "processing config: $CFG" > /dev/stderr

    local DB_DIR_="$ANNO_DB_DIR/${NAME}"
    mkdir -p "$DB_DIR_" || return 127

    pushd "$DB_DIR_"
    LC_ALL=C date > DATES
    touch _SHIT

    local TECH_="$DB_DIR_/tech"
    mkdir -p "$TECH_"
    cat "$CFG" > "$TECH_/orig.cfg"
    ${GENOME_DIR}/annotation/parse_db_configs.py "$CFG" "$TECH_"

    rm _SHIT
    popd

    eval "$DB_DIR_VAR"="$DB_DIR_"
    eval "$TECH_DIR_VAR"="$TECH_"
}

Am I missing something? And am I right to assume that taking DB_DIR_VAR and TECH_DIR_VAR is pointless to begin with, since their initial values are never used?
Answer: It's not setting DB_DIR_VAR and TECH_DIR_VAR - it's setting the variables whose names are set in those two variables. So if DB_DIR_VAR is equal to THE_DB_DIR, it will set THE_DB_DIR to the value of DB_DIR_.


Autoload next page while scrolling to the bottom

Question: I am looking for a way to automatically load the next article once a reader has scrolled to the bottom of the page. Something similar to what this wordpress plugin is doing. So I understand that the functionality need to do three things:

Detect that the user has scrolled to the bottom of the page, and then load the next page underneath it, without breaking the theme's structure.
When the user has scrolled on to the next article, the URL and title on the browser should change to reflect that the user is now reading a new article.
The new page view should be trackable by google analytics. This should also create a separate history entry on the user's browser. Any social media share after the scroll should reflect the second article and not the first.

I understand there may be a way to achieve this using views infinite scroll. But that won't be able to achieve conditions two and three.
Comment: Apart from your post not containing any specific question, Drupal Answers is not the right place to ask for recommendations (see https://drupal.stackexchange.com/help/on-topic to find out about what to ask here). To my knowledge, your use case can't be covered by any contrib module alone. But you can easily achieve what you are looking for by some custom coding (e.g. extending views infinite scroll). If you stumble upon a specific issue while you are doing it yourself (e.g. something not working as expected), feel free to come back with this more specific question.
Answer: After a lit bit more looking around, I found that this functionality can be achieved by the Infinite Scroll js plugin. There is no out of box integration with Drupal yet, however, it shouldn't be too hard to build one. This plugin takes care of conditions 2 and 3 mentioned in the question quite nicely. It has the added advantage over the "views infinite scroll module" in that the content can be rendered without using views, and hence is a more flexible option.


when ringer mode is changed to normal stop service

Question: when ringer mode is changed to normal how to do i stop my applications service.
Im new to android programming, confused and just need quick example. I have seen other info online but could not make any sense of it.
Comment: `audioManager.getStreamVolume(2);` this will return the value of ringer range `0-7`
Answer: For this scenario you need to monitor the system event for ringer mode change. In android platform there is an application component called broadcast receiver

You need to create a new class subclassing BroadcastReceiver and register it through xml declaration or program code.
Assign android.media.RINGER_MODE_CHANGED action to its intent filter
Your BroadcastReceiver onReceive() method will be called with an intent as a parameter when the ringer mode is changed.
Check current ringer mode by looking into the received intent extra with EXTRA_RINGER_MODE. And compare the value with RINGER_MODE_NORMAL
Issue an intent to context.stopService() to stop your running service if the condition in point 4 satisfied
Comment: how do i unregister a broadcast receiver once the Ringer Mode has been set to normal. i.e once the Ringer Mode has been set to normal , my service stops by context.stopService() but I also have a class that uses a broadcast receiver I want to unregister it and stop listening for texts once the Ringer mode is set to normal
Comment: So you want your broadcast receiver one time only, is that what you mean? I my point of view, you can just leave it there. Even the broadcast receiver being called twice, stopping a stopped service won't have much negative impact.

[Context.unregisterReceiver()](http://developer.android.com/reference/android/content/Context.html#unregisterReceiver%28android.content.BroadcastReceiver%29) can do what you want


detecting flex-box support with CSS3 @supports

Question: I am planning on implementing flexbox solutions to my layout if they are supported and I am going to feature-detect if they are supported with CSS3's @support{...} queries.
But what should I test is supported? Since feature @support queries look for support of a given style and then implement styles if supported, of what should I look for support?
In other words, what style do all implementations of flexbox support?
I would think it would be the display:box; for the 2009 flexbox implementation, display:flexbox; for the shortlived 2011 implementation, and display:flex; for the current and final implementation of the spec?
Answer: Flexbox (Standard draft) support + Feature Query support:

Opera added support for both in the same version (12.1)
Firefox added support for both in the same version (22), but didn't support flex-wrap until 28
Android added support for both in the same version (4.4)
Chrome added support for Flexbox in 21, but didn't support feature queries until 28

No browser that exclusively supports either of the old Flexbox drafts has support for feature queries.

Browser support for Flexbox
Browser support for Feature Queries

The only practical use for feature queries in combination with Flexbox at this point in time is to detect if a browser supports flex-wrap: wrap.  However, the number of browsers still in use that support display: flex and not flex-wrap: wrap is pretty much the point where you can consider them to be statistically insignificant.
.foo {
    display: -ms-flexbox;
    display: -webkit-flex;
}

@supports (flex-wrap: wrap) {
    display: flex;
}

Related: Flexible box model - display : flex, box, flexbox?
Answer: The browsers that implement display:box / display:flexbox and display:flex are unlikely to support @supports.  Furthermore, until yesterday, Firefox did not support flex-wrap.  Meanwhile, Internet Explorer 11, while supporting display:flex, does not support @supports.
So you are better off with a JavaScript solution like Modernizr or just assume the browser supports display:flex if your users are likely to use Firefox/Chrome on any platform or MSIE11 on Windows 8. If you would like to support iPhone, remember to -webkit- prefix and flex properties and use display:-webkit-flex.
Since flexbox automatically overrides floats and the flex property allows you to override width, chances are you can just mix the CSS for non-display:flex browsers with those that do.


Why is the sample mean's variance smaller when we're sampling without replacement?

Question: I know that we've to use the correction for finite population, but why do we have to use it?
My lecturer said that "Sampling without replacement doesn't waste information by the chance of finding the same observation twice", but I don't get why do the two things are connected.
Answer: Intuitively, when you sample without replacement, opportunities for a
variety of outcomes diminish as you begin to 'use up' the population.
This restriction decreases variability.
The distinction between sampling with and without replacement often
results in choosing a binomial distribution (with replacement) or
a hypergeometric distribution (without replacement).
Suppose you are sampling from an urn containing 4 red balls and 8 black balls.
You sample $n = 5$ balls and let $X$ be the number of red balls chosen.
If sampling is with replacement, then $X \sim \mathsf{Binom}(n = 5, p = 1/3)$
so that $P(X = k) = {10 \choose k}(1/3)^k(2/3)^{5-k},$ for $k = 0, 1, \dots, 5.$ In this case, $E(X) = np = 5(1/3) = 5/3,$ and $Var(X) = np(1-p)
= 5(1/3)(2/3) = 10/9.$
[If we have results $X$ from such a binomial experiment, then
the an unknown $p$ can be estimated by the mean $\hat p = X/n,$ which has $E(\hat p) = p$ and $Var(\hat p) = \frac{p(1-p)}{n}.]$
Below we compare these theoretical values with results from a million 5-draw experiments in R:
x = rbinom(10^6, 5, 1/3)
mean(x); 5/3
[1] 1.668055  # aprx E(X) = 5/3
[1] 1.666667  # exact
var(x); 10/9
[1] 1.113681  # aprx Var(X) = 10/9
[1] 1.111111  # exact

hist(x, prob=T, br=(0:6)-.5, col="skyblue2", main="Binomial")
 k = 0:5; pdf=dbinom(k, 5, 1/3)
 points(k, pdf, col="red")

Histogram bars show simulated results and red circles show exact binomial
probabilities.

If sampling is without replacement, then $X$ has a hypergeometric distribution, with
$$P(X = k) = \frac{{4 \choose k}{{8\choose 5 - k}}}{{12 \choose 5}},$$
for $k = 0, 1, 2, 3, 4.$ (Notice that $k = 5$ is impossible, because only $4$ red balls are available.
Letting $p = n/T = 4/12 = 1/3,$ we can write
$E(X) = np = 5(1/3) = 5/3,$ the same as for the binomial model above. However,
$$Var(X) =np(1-p)\left[\frac{T-n}{T-1}\right] = 5(1/3)(2/3)[7/11] = 70/99 < 10/9.$$
So the variance is smaller when sampling without replacement. The factor in square brackets is sometimes called the finite population correction (because binomial sampling can be regarded as sampling from an infinite population).
x = rhyper(10^6, 4, 8, 5)
mean(x); 5/3
[1] 1.667055  # aprx E(X)
[1] 1.666667  # exact
var(x); 70/99
[1] 0.7061733 # aprx Var(X)
[1] 0.7070707 # exact

hist(x, prob=T, br=(0:5)-.5, col="skyblue2", main="Hyergeometric")
 k = 0:4; pdf=dhyper(k, 4, 8, 5)
 points(k, pdf, col="red")


Adding a jQuery UI widget in the administrative front-end

Question: I have created a form within the administrative front-end in my Drupal 7 site to allow administrators to change some configuration options. I've defined the path to it in the following way (in hook_menu):
$items['admin/config/system/my_site_name/status'] = array(
  'title' => 'Change site status',
  'description' => 'My description',
  'access arguments' => array('administer site configuration'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array('my_form_name'),
  'file' => 'forms_file.inc',
);

I want one of the items in this form to be a jQuery UI slider, bound to a hidden select element that has its same value, which is then fetched in the form's submit method (pretty much like in here: http://jqueryui.com/slider/#hotelrooms) by creating a .js file with the following.
(function ($) {
  Drupal.behaviors.site_status = {
    attach: function(context) {
      var select = $("#edit-site-status");
      var slider = $( "

" ).insertAfter(select).slider({
        min: 0,
        max: 4,
        range: "min",
        value: select[0].selectedIndex,
        slide: function( event, ui ) {
          select[0].selectedIndex = ui.value;
        }
      });
      $( "#edit-site-status" ).change(function() {
        slider.slider( "value", this.selectedIndex);
      });
    }
  }

})(jQuery);

However, I've been unable to load the widget, as it seems the whole jQuery UI js file is missing.

TypeError: $(...).insertAfter(...).slider is not a function

According to http://redhotchilliproject.com/blog/jquery-and-jquery-ui-in-drupal-7, I should manually load the jQuery file in some preprocess function, like this.
function MY_THEME_preprocess_page(&$variables, $hook) {
  drupal_add_library('system','ui.slider');
}

However this method doesn't get called from the page that contains my form. I've even tried to load the jQuery library in MY_THEME_preprocess() without any luck.
I don't want to include the file in the my_module.info file, as I only need the slider to be in the administrative front-end and most users won't need it.
How can I get this slider to show up?
Answer: drupal_add_library() can be called from pretty much anywhere, including your form function:
function my_form_name($form, &$form_state) {
  drupal_add_library('system','ui.slider');

  // Build and return the form.
}

Answer: As alternative to Clive's answer, you can use the #attached property. The example in the documentation makes clear how to attach a library to a form.
if (!$user->uid) {
  $form['#attached']['library'][] = array('system', 'jquery.cookie');
  $form['#attributes']['class'][] = 'user-info-from-cookie';
}

Using #attached is the suggested way in Drupal 8, which doesn't use anymore the hook_init() hook.


Facebook app: Can I view the total number of likes of my app page?

Question: Is it possible to view the total number of likes, and even better, who liked my facebook app profile page? I can't see this option anywhere in the insights.
Answer: Use the GraphApi .Take a look here
<code>* https://graph.facebook.com/--user id--/likes
</code>
Search through the person's likes until you find your application id.
More details here: http://developers.facebook.com/docs/reference/api/user
Take a look at this codes https://gist.github.com/783822
Comment: Thanks, but that is only possible if the user is sharing that information, I remember before it was really easy to see how many people liked your page
Comment: It seems to have stopped working as of mid June 2015. It returns `{"error":{"message":"An access token is required to request this resource.","type":"OAuthException","code":104}}`
Answer: Just go on your application profile page. On the left click on "likes this" under the number of people who likes your page.


Como fazer um contorno em texto via CSS

Question: Pessoal alguém pode me ajudar a fazer esse contorno em texto pelo css
Answer: Você pode usar -webkit-text-stroke, mas não tem suporte para o IE:

.borda_texto{
-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: #000;
font-size: 3em; color: #fffdd9;
}

    Contorno no texto

Answer: Outra forma de fazer esse efeito é colocando o texto dentro de um SVG e usar a propriedade stroke-width no texto. O ideal é que vc construa o viewBox direitinho pro seu SVG para poder aplicar sem dor de cabeça, mas fica o exemplo ai.

<svg>
  <text x="0" y="60px" font-size="60px" style="fill: white; stroke: black; stroke-width: 2px">
    Exemplo
  </text>
<text x="0" y="120px" font-size="60px" style="fill: red; stroke: blue; stroke-width: 3px; font-family: sans-serif">
    Exemplo 2
  </text>
</svg>
Answer: Você pode usar:
text-shadow: 2px 2px black;

Comment: se possível sempre coloque um exemplo ou imagem do resultado do código
Answer:

ou

Comment: o seu deu certo mas eu queria que a borda fosse como mostra na imagem acima bem maior
Comment: É só aumentar o valor de pixels (px)...
Comment: mas qual deles por favor
Comment: Obrigado a todos pela ajuda
Comment: me passa o site que vc viu esse texto
Comment: Você fala da imagem que eu postei?
Comment: isso desta imagem
Comment: brother não foi de site nenhum, eu criei essa imagem pelo photoscape para usar como exemplo, mas tem esse exemplo aqui http://www.paolawilm.com.br/css-borda-e-texto/ mas a borda ta muito fina eu tentei aumentar essa borda e não consegui
Comment: O exemplo que nosso amigo postou abaixo funciona
Comment: Sim obrigado pela ajuda, vcs são feras nisso
Answer: .text-custom {
    -webkit-text-stroke-width: 4px; /* largura da borda */
    -webkit-text-stroke-color: black; /* cor da borda */
    -webkit-text-fill-color: white;
}

Como fazer um contorno em texto via CSS


Notation for writing multinomial coefficient as sum of smaller multinomial coefficients

Question: This question is an attempt to extend the Pascal triangle's hockey stick identity to multinomial coefficients as asked in question Hockey-Stick Theorem for Multinomial Coefficients.
Consider the following recursive relation:
$$\binom{n_1+n_2+\cdots+n_t}{n_1,n_2,\cdots,n_t}=\sum_{\text{For all nonzero $x_j$ except last}}\binom{n_1+n_2+\cdots+n_t-1}{n_1,\cdots,n_j-1,\cdots,n_t}+
\binom{n_1+n_2+\cdots+n_t-1}{n_1,n_2,\cdots,n_t-1}_{\text{$n_t$ being last non-zero $x_j$}}$$
where
$$\binom{n_1+n_2+\cdots+n_t}{n_1,n_2,\cdots,n_t}=\frac{(n_1+n_2+\cdots+n_t)!}{n_1! n_2! \cdots n_t!} $$
Example:
\begin{eqnarray}
\binom{6}{3,1,2}&=&\binom{5}{2,1,2}+\binom{5}{3,0,2}+\binom{5}{3,1,1}\\
&=&\binom{5}{2,1,2}+\binom{5}{3,0,2}+\left\{ \binom{4}{2,1,1}+\binom{4}{3,0,1}+\binom{4}{3,1,0} \right\}\\
&=&\binom{5}{2,1,2}+\binom{5}{3,0,2}+\binom{4}{2,1,1}+\binom{4}{3,0,1}+
\left\{\binom{3}{2,1,0}+\binom{3}{3,0,0} \right\}\\
&=&\binom{5}{2,1,2}+\binom{5}{3,0,2}+\binom{4}{2,1,1}+\binom{4}{3,0,1}+
\binom{3}{2,1,0}+\left\{\binom{2}{2,0,0} \right\}\\
\end{eqnarray}
How may I write the following line in compact sigma notation?
$$\binom{6}{3,1,2}=\binom{5}{2,1,2}+\binom{5}{3,0,2}+\binom{4}{2,1,1}+\binom{4}{3,0,1}+
\binom{3}{2,1,0}+\binom{2}{2,0,0}$$
How to write it for general form?
Answer: $$\binom{n_1+n_2+\cdots+n_t}{n_1,n_2,\cdots,n_t}=1+\sum_{i=2}^t \sum_{j=1}^{i-1} \sum_{k=1}^{n_i} \binom{ n_1+n_2+\cdots+n_{i-1}+k }{n_1,n_2,\cdots,n_j-1,\cdots,n_{i-1},k }$$


Clearing MDTextField from kivymd after submission

Question: I am trying to create a game which requires the user to input coordinates. However, I realise that the fields are not cleared even after the "Enter" button is clicked and the screen is changed. Usually using the normal textinput field, I can just insert a python line of self.shootdepthinput.text='', which will clear the text input in the field as it's a string. However, for MDTextField, the input is in the form of a tuple, which is immutable. Does anyone know of a function for me to clear the MDtextfield? Thank you!
This is an extract of my kivy file where my MDTextField is found in:
<ComputerScreen>:

    shootxinput: shootxinput_id
    shootyinput: shootyinput_id
    shootdepthinput: shootdepthinput_id

    id: "computerscreen_id"
    name: "computer"
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: "battleshipgame.png"

    GridLayout:
        cols: 3
        id: s_input
        pos_hint: {"x":0.03,"y":0.72}
        size_hint : 0.7, 0.1

        MDTextField:
            id: shootxinput_id
            hint_text: "X-Coordinate"
            required: True
            helper_text_mode: "on_focus"
            color_mode: "custom"
            helper_text: "Enter a number from 1 to 10"
            line_color_focus: 0, 0, 0, 1

        MDTextField:
            id: shootyinput_id
            hint_text: "Y-Coordinate"
            required: True
            color_mode: "custom"
            helper_text_mode: "on_focus"
            helper_text: "Enter an alphabet from A to J"
            line_color_focus: 0, 0, 0, 1

        MDTextField:
            id: shootdepthinput_id
            hint_text: "Depth"
            required: True
            color_mode: "custom"
            helper_text_mode: "on_focus"
            helper_text: "0: Surface Level, 1: Sub-sea Level"
            line_color_focus: 0, 0, 0, 1

    FloatLayout:
        id: buttonarea
        Button:
            id: shootsubmitbtn
            size_hint:0.1,0.05
            on_press: root.shoot()
            text: "Enter"
            pos_hint:{"x": 0.75, "y": 0.75}

Answer: create a statement that clear the input field inside the shoot method
def shoot(self, *args):
    shootxinput_id.text, shootyinput_id.text = ""
    # do some other things

Comment: Hello! I have tried that, but for MDTextFields, shootxinput_id.text comes out as a tuple, which is immutable... Is there a way to clear a tuple?


Has any player in NFL history been drafted to more than one team?

Question: Has there ever been an NFL player that was drafted by multiple teams?
How did they manage to do so?
Comment: This question has got a close vote for "unclear what you're asking" - are you asking if a player has ever been drafted by more than one team?
Comment: Under previous CBAs, there were always threats by college juniors to go back to college and thus back into the draft, but I can't remember any player actually doing it.
Comment: @PhilipKendall That is exactly what I meant. Not sure it is unclear though.
Answer: Bo Jackson was drafted first overall in 1986 by the Tampa Bay Buccaneers. He refused to sign after the Buccaneers lied to him about his NCAA eligibility. They told him that it was okay for him to come and tour their facilities. He was informed that he was not NCAA eligible to play and as a result he missed all of his senior year baseball season. He then was drafted by the Kansas City Royals in 1986 to play baseball. The following year, the Oakland Raiders drafted Bo to play football. So Bo Jackson was drafted by the Buccaneers and the Raiders in the NFL, plus the Royals in MLB.


count() parameter must be an array or an object when there is no record in the database

Question: I am using Codeignator, I have a function in the model which is
function getList()
    {
$result = $this->db->where(['members.member_type'=>1,'members.is_Approved'=>1,'members.is_status'=>1])
    ->order_by("members.member_id", "desc")
    ->from('members')
    ->join('admin_users','admin_users.admin_user_id = members.created_by')
    ->get()
    ->result();
        if($result)
        {
            return $result;
        }
        else
        {
            return 0;
        }
    }

Above code, I am using to display the all the list on view page which is working. Now I have one more view page and I am displaying the total number of the users using the same code. So I added the code
$data['primary_data'] = count($this->List_model->getList());
print_r($data['primary_data']);

It's also working but when there are no records then I am getting the error
count() parameter must be an array or an object that implements countable in codeigniter

Would you help me out in this?
Answer: CodeIgniter's $this->db->result() method returns the query result as an array of objects, or an empty array on failure.
Just return the result as it is. If there are results it will return an array of objects. If no result found, it will return an empty array. So the counting on the result will work all the time.
function getList() {
  return $this->db->where(['members.member_type'=>1,'members.is_Approved'=>1,'members.is_status'=>1])
    ->order_by("members.member_id", "desc")
    ->from('members')
    ->join('admin_users','admin_users.admin_user_id = members.created_by')
    ->get()
    ->result();
}

Comment: Oh! Yes, it's correct, It's working if there are no records in the database. give me some time to insert the data
Answer: You can return empty array instead of 0 in getList() method.
return [];

can write this:
return $result ? $result : [];


Find the maximal interval where this IVP has unique solution

Question: Consider the IVP
$t\dfrac{dy}{dt} = t + \left|y\right|$, where $y(-1) = 1$, I need to find the largest interval where this has a unique solution.
Here, if I consider $f(t,y) = 1 + \dfrac{\left|y\right|}{t}$ then  there exist a rectangle
$\left|t+1\right| \le a$, $\left|y-1\right| \le b$ where this $f$ is continuous.
Also, $f$ is Lipchitz Continuous, in this given rectangle, so now by Uniqueness and Existence theorem we get an interval
$\left|t + 1\right|\le h $ where $h = \text{min}(a, b/M)$, $M = \text{max f}$ in the given domain.
Here, I am stuck as I don't get how to compute the maximum of this function on this domain.
The answer provided is $(-\infty,0)$ but I am clueless how to reach this interval ?
Thank You.
Answer: On every domain $(t,y)\in[-b,-a]\times \Bbb R$ with $0<a<1<b<\infty$ you have $L=\frac1a$ as constant in the Lipschitz condition, which holds globally on that domain. This implies that the IVP has a solution on the interval $[-b,-a]$. By the uniqueness part of the theorem, this solution can be uniquely extended to any larger interval of this type. The union of intervals of this type is $(-\infty,0)$.

Determining the maximum intervall of existence
Picard-Lindelöf theorem variations
Globally Lipschitz implies solutions exist for all time
Questions about the Picard–Lindelöf theorem for an ODE
Showing Global Lipschitz $\implies$ Global Solution ODE
Comment: I think you also need to show you can't extend to include $0$ (which is easy).  Picard-Lindelof etc. are all sufficient conditions to guarantee existence and uniqueness, not necessary.
Comment: The line $t=0$ is not in the domain of the ODE as the ODE function is not defined there, and even if a definition were added, it would not be continuous there.
Comment: The equation exists at $t=0$, but it is not an ODE there in the sense of the usual existence theory.
Comment: To complete: the equation $ty'=t+\lvert y\rvert$ exists at $t=0$ provided $y$ is differentiable at $0$ (and this would force $y(0)=0$).  But the one-sided derivative $(D^-y)(0)$ blows up with our $y(t)=t\log(-t)-t$, $t<0$, so although $y(t)$ can be extended continuously up to the boundary $0$, the original DE $ty'=t+\lvert y\rvert$ does not.  Hence the answer $(-\infty,0)$.


Flex add images to datagrid cell programmaticlaly

Question: I have a flex application with a datagrid created dynamically. Also this datagrid is populated dynamically and some columns must show images.
The number of images in each cell is variable and depends on user selection.
I am not sure how I manage this. Should I assign an Item Renderer to those columns with a TileList and then add images to it when the user changes its selection? If so, please tell me how.
Answer: I can manage it using a ItemRenderer with a TileList. then I pass the result data as a itemrenderer parameter. Thanks!


Given a normal vector, what information can you extract?

Question: In my textbook, $n = 3i +2j + 6k$ which lies on the $y$-axis. Can you explain how is that because I understand that it should go $3$ units on $x$ then $2$ on $y$ then $6$ on $z$ which is not on the $y$-axis??
Comment: No we cannot explain how that is, because it isn't. You are correct that this is not on the Y axis. But I strongly suspect that you are incorrect about your book saying so. It likely says something else that you misinterpreted. (Maybe it is talking about projecting this vector onto the Y axis?)
Comment: Re-read the problem , I don't think you understood the problem properly.
Comment: it's a picture.. is there a way to post it here
Comment: https://drive.google.com/file/d/0B1r1TFC-C8m_ODlxSkJFX056NVk/view?usp=sharing
Comment: n is a direction vector
Comment: but it says normal vector which is used with planes!! could you please explain?
Answer: I found out that there's only one normal vector to a plane but it can take different places. so the picture is correct and the normal vector was made on the Y axis to make calculations easier. The result would be the same for my problem even if the normal vector changes its position.


Android updating textviews and alignment

Question: I have 2 textviews side by side, one aligned right and one left to keep them together.  The right side is simply a label for the type of measurement given in the left side.  The problem is that when the left TextView is a large number, the two TextView's are side-by-side with no gap in the middle.  But as soon as the left TextView becomes a small number, it becomes spaced apart from the right side.
For example, it might look like this during one cycle:
3000meters
And then like this on the next:
5   meters
I need it to keep them together.  Is there something I can do to achieve this, xml side or code side when updating the view?
edit - okay I had to edit it in wordpad to get it to show correctly in here
<TableRow android:layout_width="fill_parent"
    android:background="@drawable/maindatabg">
            <TableLayout
                android:layout_gravity="center_horizontal"
                android:stretchColumns="*">
            <TableRow>
               <TextView
                  android:id="@+id/spaceValue"
                  android:text="00.0"
                  android:textStyle="bold"
                  android:textColor="#FFFFFF"
                  android:layout_gravity="right"
                  android:textSize="20dip"/>
              <TextView
                  android:id="@+id/spaceTypeValue"
                  android:layout_height="fill_parent"
                  android:text="meters"
                  android:textStyle="bold"
                  android:textColor="#FFFFFF"
                  android:layout_gravity="left"
                  android:textSize="14dip"/>
          </TableRow>
      </TableLayout>
</TableRow>

Comment: You need to provide some code samples (layout xml) in order to receive answer
Comment: put 2 spaces on the start of each code string
Comment: I was doing that initially but it was still coming out really bad.
Comment: Is it just a part of layout? Why TableRow is a root element instead of TableLayout?
Comment: Yes, there is much more code above that...few more nested tables.  And no, I cannot switch to another form of layout, as this one is highly complex and is laid out very very nice, except for this one bug
Comment: I think you should bring the whole layout here. The only that part looks ok.
Answer: Mention android:gravity="right" to android:id="@+id/spaceValue". A sample layout and tested works fine.
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent" >
<TableLayout android:layout_gravity="center_horizontal"
    android:stretchColumns="*">
    <TableRow>
        <TextView android:id="@+id/spaceValue" android:text="3000"
            android:textStyle="bold" android:textColor="#FFFFFF"
            android:layout_gravity="right"  android:gravity="right"
            android:textSize="20dip" />
        <TextView android:id="@+id/spaceTypeValue"
            android:layout_height="fill_parent" android:text="meters"
            android:textStyle="bold" android:textColor="#FFFFFF"
            android:layout_gravity="left" android:textSize="14dip" />
    </TableRow>
</TableLayout>
    </TableRow>

Comment: Okay, it is not RelativeLayout, but android:gravity : Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view. So, it is not at all related to layout. FYI : I tried it and it works. Check above. Hope this help you.
Comment: gopal thank you very much, that does it!  I didnt know about just gravity, i thought the only option was to use layout_gravity.  Good stuff!
Comment: @Jesse, if my post helped you to resolve your problem, then I will appreciate if you can rate my answer and accept my answer as best answer. Will help me increasing my reputation. Thanks.
Answer: After reformatting your code to
<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:layout_gravity="center_horizontal"
android:stretchColumns="*" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
    <TableRow>
        <TextView android:id="@+id/spaceValue" android:text="4"
            android:textStyle="bold" android:textColor="#FFFFFF"
            android:layout_gravity="right" android:textSize="20dip" />
        <TextView android:id="@+id/spaceTypeValue"
            android:layout_height="fill_parent" android:text="meters"
            android:textStyle="bold" android:textColor="#FFFFFF"
            android:layout_gravity="left" android:textSize="14dip" />
    </TableRow>
</TableLayout>

both 4meters and 30000meters looks the same way.
Comment: At initial runtime, yes it will work....but when i have the code update from a large number to a small number, the gap remains...
Comment: So, say I have a thread that constantly updates spaceValue, spaceView.setText(space.trim());   A way you could test it is to have a button and every time you click it will decrement from lets say 4 digitis down to 1
Comment: You should inspect TextView value with debugger. It could contain spaces.
Comment: woodshy, there are no spaces, look at the code sample I posted space.trim().  android:gravity="right" did the trick


Determining demographics by restaurant visits

Question: Note: The edits below phrase the problem better, but I kept the original post as is. My apologies if not explaining the problem coherently
Assume Person X likes to visit different restaurants at different times. We would like to determine the current estimate of their demographic distribution based on all prior information we know from other sources based on the history of their visits:

Demographic distribution of those who also were at that particular
restaurant at the particular time.
Demographic distribution of those
who were at any restaurant at that particular time.
Demographic
distribution of overall population at that particular time

Let i be the index of each visit. (e.g. i=1 could be January 1, i=2 could be Jan 28th, etc.). Let j be the jth demographic; for simplicity we can assume (Young, Middle, Old)
Not sure if just probabilities can be used, or actual numbers are needed. The possible example thought of for the latter was that if for each $i$ (visit) the percentage of 'Old' may be small for that particular restaurant at that specific time, but that may be the only restaurant 'Old' attends at that time. If for each $i$ Person X also follows the same trend of going to the same restaurant and time as all 'Old' also visit, that should increase the probability Person X is 'Old', even though for that particular restaurant at that time the percentage 'Old' may be small. In order to tell all 'Old' visited that restaurant at that time, the raw numbers are needed. (or conditional based on each demographic)
As a concrete example, for $i=1$:
$POP_1 = [.30,  .20,  .50]$   $n=1000$  (Population at time i=1)
$ANY_1 = [.70, .20, .10]$  $n=300$  (Those going to any restaurant at time i=1)
$REST_1 = [.10, .60, .30]$  $n=100$ (Those also attending same restaurant as Person X at time i=1)
Set wise, REST is a subset of ANY, which is a subset for POP. This is true for each $i$.
EDIT 1
Person X has a true, but unknown demographic. We don't know what it is, so we are trying to estimate it with a "demographic distribution", a categorical distribution of different demographics. Using (Young, Middle, Old) as an example list of demographics then [.1 .8 .1] might be a very good estimate if Person X was truly in 'Middle' demographic.
To try and estimate their demographic we look at which restaurants they visit, and at what times. From another source, we have the number of people who visit any particular restaurant for each time, the number of people who visit any restaurant for each time, and the overall population - along with number in each demographic.
(Side tangent: The restaurant analogy is the closest I can come up without getting into technical details of the actual problem at hand, but the analogy is exact. For Person X we know an activity they did at that time, as well demographic information of other people who did that activity at the same time, and those who did any activity at that time, and population under consideration)
The numbers given above would be identical to if, at time $i=1$: (The triplet refers to (Young, Middle, Old) demographics)

Population had (300, 200, 500) people in each demographic
Of those, (210, 60, 30) went out to eat at the same time as Person X, but may be different restaurants
Of those, (10, 60, 30) were at the same restaurant as Person X and at the same time.

Notice that Person X attended the same restaurant, at the same time, as all 'Middle' and 'Old' also attended. (i.e. no one in those two demographics went to a different restaurant at the same time) This should increase the probability Person X may be one of those two demographics, especially if at time $i=2$ the same event happens. (This may be an extreme example)
At each visit $i=1,2,3,4,...,$ we know the demographic information of those three bullet points above. How can we combine all that information to get an estimate of Person X's demographic?
Edit 2
Assume the demographics under interest are descriptors of age: (Young, Middle, Old).
At the first time index $i=1$ (Calendar day not important), Person X goes to a restaurant at a particular time. At such that time:

Population had (300, 200, 500) people in each demographic
Of those, (210, 60, 30) went out to eat at the same time as Person X, but may be different restaurants
Of those, (10, 60, 30) were at the same restaurant as Person X and at the same time.

At a different time index, $i=2$, Person X also went to a possibly different restaurant. At such time:

Population had (350, 190, 550) people in each demographic
Of those, (300, 150, 20) went out to eat at the same time as Person X, but may be different restaurants
Of those, (50, 10, 20) were at the same restaurant as Person X and at the same time.

How can we use all information about both visits to get an estimate of the probability Person X is each demographic? (Notice both times Person X went exclusively to the same restaurant that all 'Old' also attended - should that increase the probability is in the Old demographic?)
Example estimate might be: (.10, .20, .70) - that is, there is a 70% chance Person X is 'Old' - the categorical distribution representing the probability of being in each demographics would be updated with information gathered from each new visit ($i=1,2,3,...$), taking into account all prior information from other visits as well.
Comment: My apologies, I tried to be clear. Person X has a true, but unknown, demographic. We are trying to estimate their demographic based on which restaurants they visit and at what time. The 'demographic distribution' could be [10% Young, 80% Middle, 10% Old] as an estimate. (And good estimate if Person X is truly 'Middle'). I will try and edit the question to make the example clear.
Comment: You lost me at the second sentence. The first refers to a specific person, whereas the second asks how to estimate their "demographic distribution". How does an individual have a demographic distribution? The rest of the question is so vague that even the example is of little help in understanding what data you have and what you are really trying to find out.
Answer: From what I understand of your post, this is definitely a classification problem. Since it seems like you need to first identify your demographics, it seems like an unsupervised learning problem. So, you might want to think about cluster analysis. You could have variables like [age, restaurant, time] and try to come up with some clusters around these. Then, you can predict what cluster a person will be in.
If you can identify your demographics in advance, you can use supervised learning. Namely, a classification system such as k-nearest-neighbors to predict which demographic a person will be in.


Radius of convergence of $ \sum_{n} \frac{x^n}{n\sqrt{n}}$

Question: Trying to find the radius of convergence for $ \displaystyle \sum_{n} \frac{x^n}{n\sqrt{n}}$
I apply the root test: $\displaystyle \lim_{n \to \infty} \left(\bigg|\frac{x^n}{n\sqrt{n}}\bigg|\right)^{1/n} =\lim_{n \to \infty} \frac{|x|}{n^{1/n}n^{1/2n}} = |x|. $
The series converges absolutely if $|x| < 1$ therefore $R = 1$.
Is the above correct? On Wikipedia I find the formula:
$R = 1/\limsup_{n \rightarrow \infty}{\sqrt[n]{|c_n|}}$
How does one use this to find $R$ in the above case?
Answer: The answer is correct, and the two formulas are equivalent if $$\lim_ \limits{n \to \infty}|c_n|^{1/n}$$exists.
The ratio test is however the easier test in this case. Observe
$$\lim_ \limits{n \to \infty} \left| \frac{x^{n+1}}{(n+1)^{3/2}} \frac{n^{3/2}}{x^n}\right| = |x|,$$ and since ratio test implies absolute convergence when the ratio is less than $1$, we get a radius of convergence of $1$.
Comment: I think you want $n \to \infty$ and not $x \to \infty$.
Comment: @JendrikStelzner You are very correct. Thanks!
Answer: The formula $R = 1/\limsup_{n \rightarrow \infty}{\sqrt[n]{|c_n|}}$ is for the series $\displaystyle\sum_{n = 0}^{\infty}c_nx^n$.
Note that $c_n$ is the coefficient of the $x^n$ term, not the $n$-th term itself.
So, here $c_n = \dfrac{1}{n\sqrt{n}} = n^{-3/2}$, and we need to compute $\displaystyle\limsup_{n \rightarrow \infty}{\sqrt[n]{|c_n|}} = \displaystyle\limsup_{n \rightarrow \infty}n^{-\tfrac{3}{2n}}$.
By taking the logarithm and using L'Hoptital's Rule (or whatever other method you prefer) you get $\displaystyle\lim_{n \rightarrow \infty}n^{-\tfrac{3}{2n}} = 1$.
Since $\displaystyle\lim_{n \rightarrow \infty}n^{-\tfrac{3}{2n}}$ exists, we have $\displaystyle\limsup_{n \rightarrow \infty}n^{-\tfrac{3}{2n}} = \displaystyle\lim_{n \rightarrow \infty}n^{-\tfrac{3}{2n}} = 1$, and thus, $R = 1$.
Answer: First you have to calculate
$$
 \limsup_{n \to \infty} \left( \frac{1}{n \sqrt{n}} \right)^{1/n}
 = \limsup_{n \to \infty} \left( \frac{1}{n^{3/2}} \right)^{1/n}
 = \limsup_{n \to \infty} \left( \frac{1}{n^{1/n}} \right)^{3/2}.
$$
Because $\lim_{n \to \infty} n^{1/n} = 1$ it follows that
$$
 \limsup_{n \to \infty} \left( \frac{1}{n^{1/n}} \right)^{3/2}
 = \lim_{n \to \infty} \left( \frac{1}{n^{1/n}} \right)^{3/2}
 = \left( \lim_{n \to \infty} \frac{1}{n^{1/n}} \right)^{3/2}
 = 1
$$
because the limit exists. The radius of convergence is now given by
$$
 \frac{1}{\limsup_{n \to \infty} \left( \frac{1}{n \sqrt{n}} \right)^{1/n}}
 = \frac{1}{1}
 = 1.
$$
Answer: What you wrote is correct, from the root test the radius of convergence is $R=1$.
You may observe that both series $\displaystyle \sum_{n} \frac{(-1)^n}{n\sqrt{n}}$ and $\displaystyle \sum_{n} \frac{1}{n\sqrt{n}}$ are also absolutely convergent:
$$
\left|\sum_{n\geq1} \frac{(-1)^n}{n\sqrt{n}}\right|\leq \sum_{n\geq1}\left| \frac{1}{n\sqrt{n}}\right|=\sum_{n\geq1}\frac1{n^{3/2}}<\infty
$$ as a $p$-series with $p>1$.
Answer: $$\lim_{n\to\infty} \left|x^nn^{-\dfrac32}\right|^{\dfrac1n} = |x|\lim_{n\to\infty} \exp\left(-\dfrac 32\dfrac {\log n}n\right) = |x|\exp(0) = |x|.$$


How to find the subgroups of $S_n$ which are isomorphic to $\mathbb{Z}_l$?

Question: This post is somewhat generalization of my previous question, number of subgroups in $S_5$ which are isomorphic to $\mathbb{Z}_5$
I want to generalize the previous post and want some procedure or known facts regarding this.
i.e.,

How to find the subgroups of $S_n$ which are isomorphic to $\mathbb{Z}_l$?

My naive idea is to express the explicit element of $S_n$ and see the cyclic order of $l$... But for me it seems it is not enough.
Answer: Yes, every cyclic subgroup of $S_n$ of order $k$ (I'm using $k$ because I find $l$ difficult to read, too close to $1$ for my taste) is generated by an element of $S_n$ of order $k$ (and of course often the same subgroup can be generated by different elements, but you don't seem to be interested in counting subgroups in this question, only finding them - so that's another story - but the below may assist in counting them).
It helps to remember that the order of an element of $S_n$ can be determined from its cycle type - that is, the list of positive integers $(a_1, \dots, a_m)$ for which the element can be written as product of disjoint cycles of lengths $a_1, \dots, a_m$,  respectively.  In this event, fairly simple calculations can show you that the order of an element of cycle type $(a_1, \dots, a_m)$ is $\operatorname{lcm}(a_1, \dots, a_m)$.
So in terms of cycle types, you're looking for ones corresponding to tuples of positive integers $(a_1, \dots, a_m)$ with $\operatorname{lcm}(a_1, \dots, a_m) = k$.  And because the disjoint cycles that make up this cycle type have to fit in $S_n$ it is also required here that $a_1 + \dots + a_m = n$.  (There's no harm in thinking of fixed points of a permutation as cycles of length $1$, which is why I have equality here.)
Recall that tuples of positive integers summing to a positive integer $n$ are sometimes called partitions of $n$.  You're looking to see if there are any partitions of $n$, the $\operatorname{lcm}$ of which is $k$.  If there are any, then you just fill in cycles corresponding to that cycle type.  For many values of $n$ and $k$ computers would likely to be better at performing this computation than people.  I don't know of a way to simplify it, or a simpler way of approaching it.
For example if $n=10$ and $k=6$, I'm looking for partitions of $10$ with $\operatorname{lcm}(6)$.  Doublecheck, e.g. via your own reasoning or via http://oeis.org/wiki/10, that there are not so many such partitions, including e.g. $(3,2,1,1,1,1,1)$, $(3,2,2,2,1)$, and $(6,1,1,1,1)$ and others, but not so many.  If I've done this right that means the subgroups of $S_{10}$ of order $6$ must be generated permutations of these cycle types, e.g. those of the form $(abc)(de)$, or $(abc)(de)(fg)(hi)$, or $(abcdef)$, etc.  It's pretty easy to write down examples of these (and others), and from the above we know that those are all of them.
From there, maybe you can begin identifying when subgroups with these types of generators happen to be equal, and begin counting them.
Comment: @J.W.Tanner Yes. This is why I didn't go into combinatorics or number theory. I have edited so hopefully it is not wrong now. Many thanks
Comment: Only tangentially related, but: I have the same problem with $l$ and usually substitute $\ell$ for it.
Comment: Another note: The largest $k$ such that a $\mathbb{Z}_k$ is a subgroup of $S_n$ is given by [Landau's function](http://oeis.org/A000793).
Comment: Aren't there others, such as $(3,2,2,2,1)$?


Can someone please help me explain this fallacy

Question: $$\Omega = \int_{-1}^1 \frac{dx}{1+x²}\ =\ -\int_{-1}^1\frac{dy}{1+y²} $$ $$ \text{ by using the transformation }\;  x= \frac{1}{y}$$ $$ \Omega = - \Omega ,\ 0\,\text{hence } \Omega =0 $$
but the integral is obviously $$\frac{π}{2} $$
Comment: I'm voting to close this question because frankly, it's kind of stupid.
Comment: Haven't studied integration yet but looks to me the bounds run from x = -1 to 1 which means y = 1/x will run from -1 to -infinity back around to positive infinity back to 1, which is the heart of many fallacies.
Comment: @AndrewChin This is not the problem here, you forgot to change the $\mathrm{dx}$.
Answer: Although $x=-1$ implies $y=-1$ and $x=1$ implies $y=1$, this does not mean the integral on $y$ can be written "from $-1$ to $1$". We need to consider the actual regions of integration, not just the boundary points.
$-1 \leq x \leq 1$ implies $y \leq -1$ or $y \geq 1$. (We can ignore the single point $x=0$.) So the correct transformation is:
$$ \int_{-1}^1 \frac{dx}{1+x^2} = \int_{-\infty}^{-1} \frac{dy}{1+y^2} + \int_1^{\infty} \frac{dy}{1+y^2} $$
The minus sign from $dy = -\frac{dx}{x^2}$ is removed, because when dealing with sets rather than just a monotone increasing or decreasing function on single intervals, we must use the absolute value of the derivative.
Comment: Wait, this can't be right. This still gives a positive equals a negative.
Comment: In some cases only the endpoints matter, but that usually requires complex analyticity. That function has two poles blocking deformation of one path (on the Riemann sphere) to another. Residues might be an unnecessarily complicated point of view to many readers, though.
Comment: I think the limits of your integrals should be from $-1$ to $-\infty$ and from $1$ to $\infty$. If you switch the order of integration, you need to add another minus sign and the RHS becomes positive too.
Comment: @JoonasIlmavirta I don't have a very clear explanation for that which makes sense. But in the more general multi-variable transformation, we use the absolute value of the Jacobian. So for a strictly decreasing one-variable transformation we say it's $\int_{f(a)}^{f(b)}$ even though $f(b)<f(a)$, but that's really just a convenience.
Answer: This is just a slightly different take on aschepler's answer, showing a few more steps:
$$\begin{align}
\int_{-1}^1{1\over1+x^2}\,dx
&=\int_{-1}^0{1\over1+x^2}\,dx+\int_0^1{1\over1+x^2}\,dx\\
&=\int_{-1}^{-\infty}{1\over1+(1/y)^2}\,{-dy\over y^2}+\int_\infty^1{1\over1+(1/y)^2}\,{-dy\over y^2}\\
&=\int_{-\infty}^{-1}{1\over y^2+1}\,dy+\int_1^\infty{1\over y^2+1}\,dy
\end{align}$$
where the negative sign from $dx=-dy/y^2$ goes into reversing the limits of integration, i.e., $\int_b^a=-\int_a^b$.


How can I move the cursor quickly to a specific location in a text I have just copy pasted in an Advanced Scripting command?

Question: I am writing an Advanced Scripting voice command in Dragon NaturallySpeaking Professional 11.5 to write SQL commands by voice. Regarding the ORDER BY variable_name ASC command, I would like to move cursor right before ASC:
Sub Main
    Clipboard(" ORDER BY  ASC ")
    SendKeys "^v"
End Sub

How can I do so efficiently as in the built-in double quotes command?
Answer: Add some arrow keys right after ^v:
Sub Main
    Clipboard(" ORDER BY  ASC ")
    SendKeys "^v^{LEFT}{LEFT}"
End Sub


Interpreting the change of significance when adding an independent dummy variable

Question: I have a regression with my dependent variable being the number of visitors and my independent variable being the presence or absence of a certain kind of ad.
Now, when I run the regression my independent variable is significant. When instead, I add another independent variable (the presence of a big exhibition at the museum) the same variable becomes non significant.
Can someone enlighten me on what to make of this result?
Thank you very much!
Answer: Welcome to the site.
This means that, after controlling for the effects of the big exhibit, the significance of the ad is lessened. You should also look at the effect sizes (parameter estimates).
It also implies that there is some relationship between the ad and the exhibit. In your case, this makes perfect sense: Quite likely, different sorts of ads are run when there is a big exhibit.
You can examine this relationship by making a crosstabulation of "type of ad" and "presence of a big exhibit".
There may be an interaction effect as well, you can examine this by adding "presence of exhibit"*"Type of ad" to the model.
Comment: Hi Peter! Thanks for taking time to answer :) I have added the interaction factor to the model with the ad and the exhibition but the interaction is not significant. Maybe I should specify that I am looking at a specific kind of ad, it doesn't change throughout the period analyzed. Does that help?


float variable height containers

Question: So i have x amount of "blocks" that I want to float left.. Like this :
A  B  C  D
E  F  G  H
BUT, if B is twice as long as the rest, for example, there would be white space between A & E, C & G, D & H.
How can I avoid that and just have all the containers float to the left and then fit in nicely without excess white space in between ?
Comment: Check this out: http://masonry.desandro.com/?resources/jquery-masonry It's not exactly what you're asking, but you might get some good ideas from it.
Answer: CSS cannot handle this in the general case.
If there are a fixed number of columns, you can cheat and do this: http://jsfiddle.net/suaaK/11/
Otherwise:
See this answer for a comparison of the candidate techniques, showing that they don't work:

CSS Floating Divs At Variable Heights

If you're willing to use JavaScript, you should use jQuery Masonry.
Demos:

http://masonry.desandro.com/demos/animating-css-transitions.html
http://masonry.desandro.com/demos/adding-items.html
Comment: on second thought, doesn't really work for me.  I have some dynamic elements in some of the blocks, some which starts hidden, and masonry doesn't seem to cope so well with that.
Answer: Set up your CSS into vertical columns versus horizontals. Smashing Magazine has a great piece about floats and their quirks, go take a look: http://coding.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/

float variable height containers


Como vejo os valores dos registradores no disassembly de um 'olá mundo'?

Question: Eu sei que para ver o código assembly de um arquivo objeto gerado a partir de um código C, podemos utilizar o objdump da seguinte maneira
objdump -d arquivo.obj
No meu caso, dropa o seguinte código assembly na tela:
Disassembly of section .text:

00000000 :
   0:   e92d4800        push    {fp, lr}
   4:   e1a0b00d        mov     fp, sp
   8:   e24dd008        sub     sp, sp, #8
   c:   e3000000        movw    r0, #0
  10:   e58d0004        str     r0, [sp, #4]
  14:   e59f0010        ldr     r0, [pc, #16]   @ 2c
  18:   e08f0000        add     r0, pc, r0
  1c:   ebfffffe        bl      0 <printf>
  20:   e3000000        movw    r0, #0
  24:   e1a0d00b        mov     sp, fp
  28:   e8bd8800        pop     {fp, pc}
  2c:   0000000c        .word   0x0000000c

Mas como eu acesso os valores dos registradores?
Answer: Basicamente, objdump se trata de um programa que realiza a leitura do código binário de um objeto. De forma simplificada, podemos entender que cada linha é um comando para o processador executar.
https://man7.org/linux/man-pages/man1/objdump.1.html
Não é possível olhar o valor dos registradores, pois o programa não está sendo executado, e os registradores não estão computando os valores informados no código.
Para sabermos o valor dos registradores, é necessário utilizar uma técnica de Análise Dinâmica, na qual analisamos o comportamento do programa enquanto o mesmo está em execução. Já a análise de binário por meio do objdump se trata de uma Análise Estática.
https://reverseengineering.stackexchange.com/questions/3473/what-is-the-difference-between-static-disassembly-and-dynamic-disassembly
Para chegar no seu objetivo, estude e pesquise sobre análises dinâmicas, como  o debugging. Dê uma olhada no WinDBG.
https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Why Is It That The View In MVC Is Not Being Displayed?

Question: I had debug and it actually enter the View(survey) but The View is not returning the page. Any help will be appreciated!
//#edit is a submit button, and below is the script.
 $('#edit').click(function () {

    var sid = $('input[type=radio]:checked').val();
    var srid = sid.replace(/[^0-9]/g, '');
    var id = parseInt(srid);
    //alert(id);

    $.ajax({
        type: 'POST',
        url: '@Url.Action("Edit","MainPage")',
        data: { "id": id },
        success: function (result) {

        }

    });

});

//Controller
[HttpPost]
     public ActionResult Edit(int id = 0)
    {
         survey survey = db.surveys.Single(s => s.SurveyId == id);
         if (survey == null)
         {
             return HttpNotFound();
         }
        return View(survey);
    }

Comment: Unless I'm mistaken, your `HttpNotFound()` will never be accessed, because `Single` will throw an exception when there are no record.  Perhaps you wanted `SingleOrDefault()`?
Comment: if not how should I go about doing it to detect selected radiobutton and button click to submit to controller?
Answer: You need to do something with the result variable in the callback, which will contain the HTML source.
Comment: Hmmm... How should I do that? I do not know what I have to put for my controller to call back because of View(survey)
Comment: It is entering the view but just cannot redirect to the page, I do not know why?


Why does ace editor load with all text highlighted and how to remove it?

Question: My code looks like :
$scope.aceIDEs='var hw = new function() {\n  console.log("Hello world!");\n}'

$scope.loadAceJSExample = function (_editor) {
_editor.setValue($scope.aceIDEs);
_editor.getSession().setUseWorker(false);
_editor.setHighlightActiveLine(true);
};

And:

      ui-ace="{onLoad : loadAceJSExample,
      onChange : aceJSExampleChanged,
      useWrapMode : true,
      theme : 'github',
      showGutter: true,
      mode: 'javascript'

    }" />

I tried calling     _editor.getSession().removeMarker(); but did not help
Every time i refresh it looks like this,once i click in it returns to normal:
Answer: Use _editor.session.setValue($scope.aceIDEs); which also resets undomanager.
Alternatively you can use _editor.setValue($scope.aceIDEs, cursorPos);. where cursorPos=-1 puts cursor at start and cursorPos=1 at the end.
Or call _editor.clearSelection() after setting value.
Comment: _editor.session.setValue($scope.aceIDEs); thank you.


Redirect "edit" tab on single node view

Question: I created custom node edit pages and I want the edit tab to redirect from
node/2545/edit
to
topic/2545/edit
or
node/2549/edit
to
arts/2545/edit
depending on the content type
This is not an alias this is a custom edit page/view I created, it is NOT the node edit page or an alias of it. it is a completely separate page and I simply want to redirect to this page when I click edit. In other words "I want to redirect to a completely random page when I click "edit"

http://screencast.com/t/zHcFsr8I
Comment: Are this paths an alias of node/%node/edit or a different menu callback?
Comment: Have you investigated the https://drupal.org/project/subpath_alias module?  It seems to provide what you are asking for if `node/2545` is aliased to `topic/2545` as an example, allowing `topic/2545/edit`.  (I assume your `node/2549` going to `arts/2545` is a typo and you really meant `arts/2549`, too)
Answer: (Disclaimer: This is not tested, it's been a while since I did a D6 site...)
First, I would implement hook_menu_alter and clone the node/%node/edit item into topic/%node/edit and arts/%node/edit. (If you want to use custom page callbacks for the forms, that's fine. You can make all changes you need to the menu items.) At least, you must change the access callback property and set it to the function name of your custom access callback (see below). Now you have three similar menu items with three different URL's. All of these should be visible as tabs on all nodes, so we're not done yet.
Second, I would create a custom access callback to hide the tabs with the incorrect URL's. This is described in HowTo: Add / Remove a menu_local_task for specific node types. In your case, the access callback should check the type of node on the current page and use it to decide if the tab must be shown or not. Don't forget to also call node_access(), because if the user is not allowed to edit that node, the tab must be hidden too.
Sorry I don't have actual code to share, I hope this helps.
Answer: What you are looking for is Sub-path URL Aliases

The Drupal Path module matches only full URLs when creating
  SEO-friendly aliases. This module extends that behavior by also
  matching known sub-paths and replacing them with their respective
  alias. For example, if node/1 is aliased to content/alias, this module
  rewrites the link to the node edit page node/1/edit to use the aliased
  URL content/alias/edit instead. This also includes Views URLs taking a
  node as argument (node/%/yourview), in short, every URL that is based
  on, or extends, an existing alias. In combination with the Pathauto
  module it is possible to get rid of all remaining exposed internal
  URLs.
Comment: Thanks but no this is not an alias this is a custom edit page/view i created, it is NOT the node edit page or an alias of it. it is a completely separate page and I simply want to redirect to this page when I click edit. in other words "I want to redirect to a completely random page when I click "edit"

Redirect "edit" tab on single node view