Mixed model applied to transformed data, or paired t-test applied to subject-medians of untransformed (skewed) data?

Question: I am attempting to find the most appropriate way of analysing a set of skewed data, and I'm torn between two different approaches (each approach appears to offer its own advantages and disadvantages). I'm hoping that somebody might be able to offer some advice.
My question is: given a highly skewed data set, are the following two approaches sensible and roughly equivalent to each other?

Perform an appropriate transformation on the response variable, and then fit a (nested) linear mixed model to the transformed data.
Calculate within-subject medians, and then perform a (paired) t-test on the medians.

I now provide a more detailed description of my data and the two proposed approaches, along with a working example in R.
Description of data
I have n=6 subjects, where each subject contains a population of cells. Each cell is of a specific type, and there are only two possible types. Given a sample of cells within each subject, I have measured the speed of each cell, and I would like to test whether or not there is evidence that cells of one type tend to have a higher speed than cells of the other type.
One important consideration is that my data set is unbalanced (one cell type has between 15 and 70 observations per subject, whilst the other cell type has between 100 and 500 observations per subject).
Possible methods of analysis
Method 1: Data transformation followed by linear mixed model
Since the data are skewed, it seems like a sensible idea to perform some kind of transformation in an attempt to make the data as normal as possible. Using the Box Cox transformation, I was able to find a suitable transformation to serve this purpose. I then proceeded to fit a linear mixed model, in which "cell type" is treated as a fixed effect, "subject" is treated as a random effect (since observations within a subject are not independent of one another), and "cell type" is nested within "subject", viz.
$$f(\mbox{value}) \sim \mbox{type} + (1|\mbox{subject}/\mbox{type}),$$
where $f(\mbox{value})$ denotes the Box Cox transformation of value.
Upon fitting this mixed model to my data, I was able to conclude that there is evidence of a difference in the mean of $f(\mbox{value})$ between the two cell types -- which, in turn, allows me to conclude that there is evidence of a difference in median speed between the two cell types. The assumptions of the mixed model appear to be satisfied.
Overall, this method seems to be suitable for analysing my data. However, since it involves analysing transformed data, I can't quantify the effect size on anything other than the transformed scale. If possible, I would like to be able to make some sort of statement regarding the magnitude of the effect size. This leads me on to the second method that is under consideration...
Method 2: Calculate within-subject medians and perform a paired t-test
Since we are dealing with skewed data, the median value is probably a more appropriate measure of central tendency than the mean. Moreover, since we have a relatively small number of observations for some subjects, the median will be more robust to outliers. I therefore begin by taking the median speed across all cells of a given type within each subject. This results in six pairs of medians (one pair for each subject, where each pair comprises a median for each of the two cell types). We can then perform a paired t-test on the resulting pairs of medians.
This method has the benefit of working entirely on the natural (untransformed) scale, thereby allowing us to quantify the typical difference in median speed between the two cell types in addition to testing for a statistically significant difference. It's also a much simpler approach than fitting mixed models, so all things being equal it would be my preferred choice.
Specific questions
I am concerned that I might be making some dangerous assumptions for Method 2. For example

Is it appropriate to work with subject-medians when the data are skewed and some groups comprise few (~15) data points?
Does the unbalanced nature of the study (with far fewer observations for one cell type than the other) pose any problems when performing a paired t-test on subject-medians?

Both methods produce very similar results in terms of statistical significance for my own data and a representative dummy data set that I have prepared (see below), which suggests that I'm (hopefully) not doing anything horribly wrong. But I would really appreciate some advice or reassurance that Method 2 is appropriate in this case.
Complete R code, using representative dummy data
The below R code outlines both of my proposed methods. Note that both methods produce similar results in terms of statistical significance.
# Load required libraries
library(beeswarm)
library(MASS)
library(nlme)

# Generate dummy data
# (N.B. unbalanced design -- n is much smaller in type 1)
# type 1:
n1 <- c(15,15,20,70,25,35)
m1 <- c(-1.9,-1.3,-1.4,-1.6,-1.1,-1.7)
s1 <- c(0.6,0.5,0.8,1,0.7,0.9)
# type 2:
n2 <- c(100,200,250,480,130,270)
m2 <- c(-2,-1.9,-1.7,-2.9,-2.2,-2.2)
s2 <- c(0.8,1.1,1,1,1.2,1.1)
# Set random number seed and populate data frame:
set.seed(123)
dat <- data.frame(x=NULL,subject=NULL,type=NULL)
for(i in 1:6){
  dat <- rbind(dat,
               cbind(x=rnorm(n1[i],m1[i],s1[i]),
                     subject=i,
                     type=1))
  dat <- rbind(dat,
               cbind(x=rnorm(n2[i],m2[i],s2[i]),
                     subject=i,
                     type=2))
}
# Subject and type are factors
dat$subject <- factor(dat$subject)
dat$type <- factor(dat$type)
# Transform the data (inverse of Box Cox power transformation)
lambda <- 0.155
dat$x <- (1 + lambda*dat$x)**(1/lambda)

# Data preparation complete.

# Method 1: Transform the data and fit a linear mixed model
#           to the transformed data.

# 1.1 Find an appropriate Box Cox transformation
bc <- boxcox(x ~ type+subject,data=dat,lambda=seq(-2,2,by=0.005))
lambda <- bc$x[which(bc$y==max(bc$y))]
dat$bc <- (dat$x**lambda - 1)/lambda

# 1.2 Fit a linear mixed model, where type is nested within subject
lmm <- lme(bc~type,
           random= ~ 1 | subject/type,
           data=dat)

# 1.3 Inspect the results ('type' has p-value 0.0322)
summary(lmm)

# 1.4 Check residuals for normality (all okay)
qqnorm(residuals(lmm))
qqline(residuals(lmm))

# Method 2: Calculate the median of each subject using the
#           untransformed data and perform a paired t-test on
#           the two resulting groups of medians.

# 2.1 Calculate the median of each type within each subject
meds <- aggregate(x~subject+type,data=dat,median)

# 2.2 Visually inspect the distribution of medians
beeswarm(x~type,data=meds,pch=21,pwbg=as.numeric(meds$subject))

# 2.3 Calculate paired differences between medians
g1 <- meds$x[which(meds$type==1)]
g2 <- meds$x[which(meds$type==2)]
diffs <- g1-g2

# 2.4 perform a one sample t-test ('type' has p-value 0.03705)
t.test(diffs)

EDIT
Following an incredibly useful discussion with Robert Long, I think it would be helpful for me to illustrate this particular study design.

Note that the six subjects can be treated as independent of one another. There are multiple cells within each subject, and each cell is one of two possible types (so there are many cells of each type within a subject, with an unbalanced split -- i.e. there are not the same number of cells of each type within a subject). Clearly, cells within the same subject are not independent of one another, and type is repeated within subjects. This is what I am attempting to capture in Method 1, by nesting type within subject (1|subject/type).
Comment: Method 1 is good. Given you have original dataset, Method 2 should be avoided.
Comment: Thanks for the advice! Is the stumbling-block of Method 2 the lack of observations per subject for a certain cell type, the unbalanced nature of the data, or the decision to work with medians? Or is it perhaps some combination of the three? I understand that Method 2 disregards a lot of information, but it carries the advantage of being able to quantify the difference (rather than just produce a measure of statistical significance), which I thought would be useful. Of course, if it's fundamentally flawed in some way, then its effect-size estimates can't be trusted in the first place.
Comment: the reliability of the derived variable depends on other factors (such as sample size). But when analyzing the derived variable, the different reliability (variance) is not considered. If you have no original data, using the derived variable is an option.
Comment: Excellent, thank you very much for the explanation -- that's perfectly clear now.
Answer: It's always good to remember

"All models are wrong, but some are useful". (George Box)

With this in mind, we don't always have to choose one "best model". In applied work it is often fine to report the results of different models.
I often advise caution when applying the Box-Cox transform prior to regression. It is not the response variable that is assumed to be normally distributed - it is the residuals. Since you only have 1 covariate, type, measured among different subjects, there are fairly few alternatives, but it is good to consider these because otherwise there are at least 2 possible problems:

you will need to interpret the inverse of the Box-Cox transformation function that you used. This rarely has a nice interpretation.
the parameter of the Box-Cox transformation could be very sensitive to your data. For example, do you get very different estimates of lambda when using different subsets? If so, then you could very well be overfitting: the model will not generalise well to further data,
a generalised linear mixed model with a Gamma distribution may work in your case as an alternative to the Box-Cox transform:
m1 <- glmer(x ~ type + (1|subject) , data = dat, family = Gamma)

The residuals are still somewhat skewed but the ease of interpretation compared to the B-C transformation may be useful.
Edit 1:
Regarding the random effects structure, the issue is whether type should be specified as random, on the basis that it is "nested" within subject. Fixed vs Random is a matter of much disagreement. To model it as random, the usual questions to ask are: Are the levels of this factor a sample from a larger population?  Is the intent to generalise the results to other (unobserved) levels of the factor?  Do we simply want to "adjust" for the effect of the factor (rather than have an interest in its parameter estimates)? If the answer to these questions is NO, that suggests modelling it as fixed.  One of the main reasons for incorporating factors as random effects is that by doing so, the non-independence of observations within each cluster is adjusted for. This can also be achieved by including the factor as a fixed effect. However, when there are many levels of the factor, this can become problematic. So, by including type as a fixed effect you are already adjusting for clustering/nesting.
Lastly,  there is the issue of the number of levels of the factor. Since it appears that type is nested in subject, (1| subject/type) will expand to (1| subject) + (1|subject:type) and so the small number of levels is not the same problem as there would be specifying (1|type).
However, this on its own is not a good reason to model it as random.
Edit 2:
I must apologise for not noticing this originally, but type is not "nested" in subject at all. It is "crossed" with subject. To be nested, each level of type must occur only in a single level of subject. This means that by identifying which level of type a particular observation belongs to, we can immediately determine which subject it belongs to, which we obviously cannot do here.  As an example of nested data, take the famous "Pastes" dataset in the lme4 package.  Strength is the outcome variable, and measurements are nested within sample, which are themselves nested within batch. If we look at any row of the dataset, given the sample ID we know immediately which batch it came from. Your situation is very different: each observation is associated with one of two types, and these observations are nested within subjects. From each observation we can determine the type and/or the subject, but given the type we cannot infer the subject which we could if it was nested.  This is a "crossed" design, and nlme cannot deal with such designs easily. lme4 on the other hand, can. IF you wanted to model type as random you would do so like this:
    (1|subject) + (1|type)

which brings us back to the problem of estimating a variance from 2 observations.  Don't do it.
Note that I have used quotation marks around "crossed" above - this is because they are not really crossed either! type is not a random effect and it makes no sense to think of it as random, or model it the way you would if it was random.
Moreover……
….I note that model 1.2 in the OP has type as both fixed AND random!! Thus you are attributing some of the variation in your observations to the (fixed) effect of type and some of it to the random variation in type. Since we have already established that type is not a random variable, this is a very dubious model to fit. In the OP, the actual research question is "whether or not there is evidence that cells of one type tend to have a higher speed than cells of the other type". This is exactly what the fixed estimate for type lets you test. Having it as a random effect too just dilutes this. If there is an interaction between type and subject then this can be modeled with either:
(type|subject)

or:
(1|subject) + (1|subject:type)

Regarding the 2nd approach of paired t-tests, I don't have a strong opinion, but my gut instinct is that this approach will lose statistical power compared to the mixed model approach, though I could very well be wrong. Having said that, there is absolutely no reason why you have to choose one and only one model. In addition to the effect size you should also consider the confidence interval of the estimate - if the mixed model approach does have more power it may lead to a narrower confidence interval for the main effect. I would only be concerned if both approaches gave wildly differing estimates.
Comment: Thanks for the helpful response! I've taken 1000 random subsamples (of size 100) from my data, and the Box Cox parameter (lambda) varies between 0.03 and 0.28, with 50% of the lambda values lying between 0.12 and 0.19. In your view, is that indicative of overfitting?
Comment: Also: the use of a generalised linear model is an excellent suggestion, since interpretation of the model output is important (Method 2 was my crude attempt at deriving some real-world quantification of the effect size); note that I'm using (1|subject/type) as my random term, to account for the nesting of type within subject. However, I'm concerned by the skewed residuals, because my understanding is that this suggests the model cannot be trusted. In terms of effect-size quantification, is a glmm with skewed residuals preferable to the crude "paired t-test of subject-medians" approach?
Comment: @homgran it is difficult to say - what is the range of a 90 percent interval for for the B-C transforms ? In the absence of any other explanatory variables, I think you are unlikely to find a model that fits the data well. `subject/type` does not make sense as a random effects structure because `type` has a maximum of 2 levels if I understand correct. `type` should be a fixed effect,
Comment: @homgran also, another thing to consider is: what is the underlying theory of how these data were generated ? This can often inform what transformations (if any) and what type of model (eg linear vs non-linear) are appropriate.
Comment: A 90% interval for the BC transforms is (0.055, 0.230). You are correct, `type` has two levels; my full call to glmer is: `m1 <- glmer(x ~ type + (1|subject/type), data=dat, family=Gamma(link="log"))`. I am prescribing `type` as a fixed effect that is nested within `subject` (which is a random effect). This is because each subject contains a certain number of cells of each type.
Comment: @homgran if it (`type`) is a fixed effect then you shouldn't model it as random. The range (0.055, 0.230)  indicates to me that you are likely to be over fitting.
Comment: In terms of an underlying theory of the data itself: cells were tracked over a period of time, and the average speed of each cell was recorded. I am ultimately trying to determine whether or not there is evidence of a difference in the typical speed (`x`) of one cell `type` relative to the other and, if possible, I would like to quantify that difference.
Comment: I must be misunderstanding the syntax, but how else would I go about informing glmer that `type` is nested within `subject`? If the nesting isn't specified (that is, if `type` only appears in the fixed effect term), then the model doesn't reflect the study design.
Comment: @homgran that's the point - you don't inform `glme`r that `type` is nested in `subject`. Because it isn't. You only need to do that for random factors. It's a little bit like treating ethnicity as nested within people - it isn't - it's fixed.
Comment: Thank you very much for clearing that up -- that makes sense to me. So does this mean that I was previously asking `[g]lmer` to fit a model that doesn't have any practical interpretation? I think I want to use `(1 + type | subject)` as my random effect term, to account for the possibility of `type` having a different effect on different subjects (and I think I was confusing this with the concept of nesting).
Comment: I wouldn't say "doesn't have any practical interpretation" - but you would be asking the software to estimate a variance parameter, based on the variable being normally distributed, from 2 observations, and that's on top of the philosophical objection to treating it as random in the first place. So it is highly questionable, at best. As for fitting random slopes for `type` - yes, that is absolutely fine - just use a likelihood ratio test to compare the models with and without, to determine whether the data supports such a model.
Comment: Sorry for resurrecting a question that I thought had been put to rest, but I'm struggling to shrug-off the idea that my data are nested. In your ethnicity example, a person cannot have multiple ethnicities (and, certainly, a person cannot have multiple instances of the same ethnicity); in my case, each subject contains multiple cells (many of which are of the same type). I have edited the bottom of my question to include a sketch of the study design in the hope that it makes things clearer; it's possible that I didn't explain the design properly in the first place.
Comment: @homgran I will update my answer this evening to address the fixed/random point in more detail.
Comment: Thanks for expanding your answer. I agree with everything apart from the last sentence of the first paragraph. Take the output from `lme` (`1.2` in my sample R script). Using a random effect of `1|subject` instead of `1|subject/type` produces wildly different results for the fixed effect `type`; in particular, the degrees of freedom (1603 vs 5, respectively) and p-value (1.115e-19 vs 0.0322, respectively). Eyeballing the data, and given that we only have 6 independent subjects, the hugely significant `1|subject` results seem unrealistic, whilst the `1|subject/type` results feel about right.
Comment: @homgran Hold on a moment. `type` is not nested in `subject` at all. It is crossed, which changes things quite a lot. I should have spotted that before ! Take a look [here](https://stats.stackexchange.com/questions/228800/crossed-vs-nested-random-effects-how-do-they-differ-and-how-are-they-specified/228814#228814) at the difference and I will post another edit to the question
Comment: Thanks for linking to your other post that describes the differences between nested and crossed random effects, that was very useful indeed. However, I'm now wondering how to handle `type` in a mixed model. It doesn't make sense to specify `type` as both a random effect and a fixed effect (which is what I would need to do if `subject` and `type` are crossed). But having `(1|subject)` as the only random effect seems to result in `subject` being treated as a batch-effect (and it seems to assume that the observations _within_ a subject are independent of each other -- which they aren't).
Comment: Scratch my last comment -- I think I see where I'm going wrong. I simply need to include an intercept term in my random effect, so that I have `(1+type|subject)`. I wish I could double-upvote your answer, because I've learned a lot here. Phew! So, now that we've established the design, to return to my original question (and to incorporate your answer): do you think that a crossed random effects glmm with skewed residuals is considerably better or worse than applying a simple paired t-test to subject-medians ("Method 2" in the question), with respect to estimating effect sizes?
Comment: @homgran I will add to my answer a little later today when I get home. For now, suffice to say that you are on the right track, but try not to think too much in terms of `type` being "crossed" with `subject`- that really makes no sense when one of the factors is fixed. I only used the term as a way to demonstrate that it is not nested, which I should have seen from the beginning !
Comment: The second way of modelling an interaction between `type` and `subject`, namely `(1|subject) + (1|subject:type)`, is the expansion of `(1|subject/type)` - which is what was used in the OP. Am I correct in thinking that, in this case, `type` isn't both fixed and random; instead, it is the _interaction_ between `type` and `subject` that is random? Both `(type|subject)` and `(1|subject) + (1|subject:type)` produce very similar results for the residual variance, but there are more noticeable differences for the fixed effects... conceptually, what are the differences between those two random terms?
Comment: @homgran you are right, it's the same, which, after all that, makes me happy :) `type` is fixed only - not random *and* fixed. But the interaction between a fixed variable and a random variable is random, so it is OK to use `subject:type` as a grouping variable. I feel that the distinction between using `(type|subject)` vs `(1|subject) + (1|subject:type)` is very interesting and maybe worthy of a separate question altogether. Or we can continue here and the system will move us into a chat room pretty soon. I will be available to chat around 20:00GMT
Comment: That's absolutely wonderful! Thanks again for all of your help. I've just posted a new question regarding `(type|subject)` and `(1|subject) + (1|subject:type)`, because I would be very interested to find out how the two models differ. Link: https://stats.stackexchange.com/questions/379263/difference-between-random-slopes-and-a-random-intercept-for-each-combination-of
Comment: @homgran you are welcome. I have seen your new question (+1) but I will refrain from answering yet to see what other responses come first. It is something that has interested me for a while.


Dfferentiability a.e. and integrability

Question: I am trying to understand something. Let $f:[a,b] \to \mathbb{R}$ be absolutely continuous. Then, we know that $f$ is differentiable a.e. on $(a,b)$. We also know that its derivative $f'$ is "integrable", but what does that mean ? With the trace measure we can define the integral of a function on a subset of the whole space (it's the integral of the restriction), but here what do we need to do ? Do we need to consider the trace measure on the set on which $f'$ is defined, and then talk about integrability in this new space ?
Thank you in advance for your answers
Answer: $\{x:f'(x)\, \text {exists}\}$ is measurable set. If you define $g$ to be $f'$ on this set and anything you like on the complement of this set then $g$ is measurable and its integrability does not depend on how you define $g$ outside $\{x:f'(x) \text {exists}\}$. So we can say $f'$ is integrable if any one of these $g$'s is integrable.
Comment: Typo in first line *"if you define $g$ to be $f$ on..."* should be *"if you define $g$ to be $f'$ on..."*
Comment: Thank you very much ! I understand it now
Answer: We can only talk and make conclusions on $[a,b]$. Outside this interval we know nothing. So, all we need is that a function $F$ is AC if-f there is an integrable $f$ such that
$F(x)=F(a)$+$\int_{a}^{x}f(t)dt$. For a detailed account on this subject see https://sites.ualberta.ca/~rjia/Math418/Notes/chap3.pdf
or Royden's "Real Analysis".

Dfferentiability a.e. and integrability


2D arrays in CUDA

Question: I read a  lot about handling 2D arrays in CUDA and i think it is necessary to flatten it before sending it to GPU.however can I allocate 1D array on GPU and access it as 2D array in GPU?I tried but failed my code looks like follows:
__global__ void kernel( int **d_a )
{

   cuPrintf("%p",local_array[0][0]);
}

int main(){

    int **A;

    int i;

    cudaPrintfInit();

    cudaMalloc((void**)&A,16*sizeof(int));

    kernel<<<1,1>>>(A);

    cudaPrintfDisplay(stdout,true);

    cudaPrintfEnd();
}

Answer: In fact it is not necessary to "flatten" your 2D array before using it on the GPU (although this can speed up memory accesses). If you'd like a 2D array, you can use something like cudaMallocPitch, which is documented in the CUDA C programming guide. I believe the reason your code isn't working is because you only malloced a 1D array - A[0][0] doesn't exist. If you look at your code, you made a 1D array of ints, not int*s. If you wanted to malloc a flattened 2D array, you could do something like:
int** A;
cudaMalloc(&A, 16*length*sizeof(int*)); //where length is the number of rows/cols you want

And then in your kernel use (to print the pointer to any element):
__global__ void kernel( int **d_a, int row, int col, int stride )
{
  printf("%p", d_a[ col + row*stride ]);
}

Answer: This is how I fixed problem
I cudaMalloc in usual way but while sending pointer to kernel i'm typecasting it to int(*)[col],and this is working for me

2D arrays in CUDA


ERRO Array to string conversion on line 28

Question: Estava vendo um tutorial e no vídeo do instrutor que foi postado não dava esse erro, e agora está dando comigo:

Array to string conversion on line 28

Já procurei uma solução e nos vídeos falavam para eu colocar um echo, mas já coloquei e não funcionou.
private function GetLista(){
        $i = 1;
        while($lista = $this->ListarDados()):
        $this->itens[$i] = array(
            'cate_id' => $lista['cate_id'],
            'cate_nome' => $lista['cate_nome'],
            'cate_slug' => $lista['cate_slug'],
            'cate_link' => Rotas::pag_Produtos(). '/' .$lista['cate_id'] . '/' . ['cate_slug']
        );

        $i++;
        endwhile;
    }

Comment: Olá Still. Acredito que a resposta do @LipESprY-defolga- está correta. Se ela solucionou o problema, você é o único capaz de aprova-la. Veja mais aqui > https://pt.meta.stackoverflow.com/a/1079/15361
Comment: Fala aí, Still! Nessa pergunta eu editei pra arrumar. Para as suas próximas, leia [formatação](https://pt.stackoverflow.com/help/formatting). Outra coisa: o erro ocorre na linha 28. Mas no seu código postado não tem 28 linhas... Que tal apontar, nesse código, qual é a linha 28? ;D
Comment: Olá, desculpe e que eu não sabia da formatação, mas nos próximos posts eu vou colocar :p
Comment: Dando uma olhada superficial, achei um erro aqui: `'cate_link' => Rotas::pag_Produtos(). '/' .$lista['cate_id'] . '/' . ['cate_slug']
`. Essa parte: `['cate_slug']` deveria ser `$lista['cate_slug']`, não?! :)
Comment: Olá, obrigado esse era o erro mesmo, infelizmente foi um erro meu na hora de digitar, obrigado por me ajudar, tem alguma parte de postagem para iniciantes? Ou posso publicar no geral mesmo?
Comment: O ideal é vc fazer o [tour] e dar uma breve lida na [central de ajuda](https://pt.stackoverflow.com/help). Se já achou o problema, vou formular uma resposta e damos essa por encerrada. =)
Answer: Repare nessa linha:
'cate_link' => Rotas::pag_Produtos(). '/' .$lista['cate_id'] . '/' . ['cate_slug']

Faltou declarar a array aqui: ['cate_slug']... Veja como fica:
'cate_link' => Rotas::pag_Produtos(). '/' .$lista['cate_id'] . '/' . $lista['cate_slug']

Comment: Tinha acabado de postar ... ^^
Comment: Só fiz uma triagem antes, via comentário. ;D
Comment: kkkk Ta certo! =)


Showing that this graph is homogeneous

Question: A graph is homogeneous when every isomorphism between two finite induced subgraphs can be extended to an automorphism of the whole graph. I was reading Diestel's graph theory where he describes the following graph and says its clearly homogeneous. It's not immediately apparent to me why.
If I have an isomorphism between two finite induced subgraphs, and map every other vertex outside the subgraphs to itself, does it become an automorphism of the entire graph? But wouldn't that make almost anything homogeneous? What is special about this one?
Answer: No, we cannot just say that we map every vertex outside the subgraphs to itself. For this to work, every one of those outside vertices would have to have the exact same adjacency relationship to both subgraphs. This is an unlikely coincidence for any graph, but for Rado-like graphs such as this one, the construction mechanism makes it impossible! (No matter which two finite subgraphs we start with, in some stage of the construction, we add a vertex which has neighbors in one, but not the other.)
Instead, we can extend a partial automorphism to a full one, one step at a time, by a back-and-forth argument. Let $S$ and $T$ be two finite subsets of $V(R^r)$, and let $\phi\colon S \to T$ be an isomorphism between the induced subgraphs $R^r[S]$ and $R^r[T]$. (For simplicity, I will stop distinguishing between vertex sets and their induced subgraphs.) We will also need to pick an ordering of the vertices of $R^r$.
The back-and-forth argument alternates between two steps. For one step, let $v$ be the first vertex of $R^r$ not yet in $S$; we identify the subset $S_v$ of all vertices in $S$ adjacent to $v$, and then apply $\phi$ to get an image $\phi(S_v) \subseteq T$. Note that because $v$ is adjacent to all of $S_v$, there cannot be an $(r-1)$-clique in $S_v$: together with $v$ it would form an $r$-clique, which we know cannot exist in $R^r$. So there is no $(r-1)$-clique in $\phi(S_v)$ either.
Because $T$ is finite, $T$ is contained in $\bigcup_{n=0}^N R^r_n$ for some finite $N$. Therefore, $R^r_{N+1}$ adds a vertex $w$ adjacent to every vertex in $\phi(S_v)$ and no other vertex in $T$. Now we can replace $S$ by $S \cup \{v\}$, $T$ by $T \cup \{w\}$, and set $\phi(v) = w$ to extend the isomorphism to subgraphs with one more vertex.
The step above guarantees that eventually, $S$ will grow to include each vertex of $R^r$. We alternate it with a reverse step, that lets $v$ be the first vertex of $R^r$ not yet in $T$, and adds $v$ to $T$ while adding a preimage of $v$ to $S$. It is done in essentially the same way. Alternating both steps, we eventually have both $S$ and $T$ grow to include every vertex of $R^r$, extending $\phi$ to an automorphism.
I understand Diestel's "clearly" as "if you understand the proof of the corresponding property for the Rado graph, it should be clear how to write a similar proof for $R^r$."

Showing that this graph is homogeneous


wxpython gauge does not pulsing

Question: I am struggling to get a gauge bar to pulse while a subprocess runs so I have gone back to basics and got this basic code which still does not work
import wx

class GaugeFrame(wx.Frame):
def __init__(self):
    wx.Frame.__init__(self, None, -1, 'Gauge Example', size=(350, 150))
    panel = wx.Panel(self, -1)
    self.gauge = wx.Gauge(panel, -1, 50, (20, 50), (250, 25))
    self.gauge.Pulse()

app = wx.PySimpleApp()
GaugeFrame().Show()
app.MainLoop()

I have tried the wxpython examples which shows two gauges one uses a wx.Timer and the other is set to pulse. When I remove the timer the gauge which is set to pulse stops working.
Therefore, i can only think that a gauge even set to pulse needs to have a timer.
is this correct?
I have tried adding
self.gauge.Refresh()

and
self.gauge.Refresh(True)

but neither seems to help
Anyone know of a solution
thanks
Answer: From the Gauge document, You are required to call it periodically after making some progress. You have to call it again and again to show progress, Pulse is used for indeterminate mode but you can move a bit to indicate the user that some progress has been made.
But if you just want to fool around the progress then yes you should bind it to timer. Just calling it in init doesn't make any sense.
I have modified example demo code just to fool around, you can bind it to your sub-process and set some checkpoints and increase/decrease the gauge speed if you really want to run it in indeterminate mode.
import wx

class GaugeFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Gauge Example', size=(350, 150))
        panel = wx.Panel(self, -1)
        self.fool = 0
        self.gspeed = 200
        self.gauge = wx.Gauge(panel, -1, 50, (20, 50), (250, 25))
        self.timer = wx.Timer(self)
        self.timer.Start(self.gspeed)
        self.Bind(wx.EVT_TIMER, self.TimerHandler)

    def __del__(self):
        self.timer.Stop()

    def TimerHandler(self, event):
        self.fool = self.fool+1
        if self.fool == 20:
            self.fool = 0
            self.gspeed = self.gspeed - 20
            if self.gspeed <= 0:
                self.timer.Stop()
                self.ShowMessage()
                self.Close()
            else:
                self.timer.Start(self.gspeed)
        self.gauge.Pulse()

    def ShowMessage(self):
        wx.MessageBox('Loading Completed', 'Info', wx.OK | wx.ICON_INFORMATION)

app = wx.PySimpleApp()
GaugeFrame().Show()
app.MainLoop()

Comment: so there is no way for it to just pulse away on launching until i set self.gauage.SetValue(100) which would show the user it has completed?
Comment: Yes , even I am also new to wxpython.. but that's what I understood from the docs out there.

wxpython gauge does not pulsing


Create link to node on view

Question: I want to add a 'like' button to a table. I get as far as the like button appearing on the page, but I can't figure out how to build the link into that spot.
The problem is, the only way to do that (that i've found so far) is to make a full html field on the content item and place the code for the iframe in there. I can't figure out how to make that a link to the node itself.
I tried using the view to add a field Global text, but I can't get an iframe to load from there. If I could do it there then I could use replacement patterns to build the proper link.
If it helps unmuddle it to remove some context: I want to create a table of nodes that pass a filter. I want that to be a table of iframes loading the node the table row represents.
Answer: Is this table generated from Views?
If so, you should be able to just add a node link, rewrite it to output ONLY the URL, hide it, then use that field as a rewrite pattern in your facebook button's output, so the like button is applying to the URL of the node itself.
Comment: I think I get the general idea, but I'm a bit cloudy on how to do it in drupal.  Yes, the table is generated with views.  I made a global custom text field on the view that would do something like  but I can't get views to not strip the html from that.  My original solution was to put the iframe into the content, but that is hard to manage and you can't do replacement patterns there.
Answer: In views you can simply do it with the help of Views PHP module
This module allows administrators to add fields, filters and sorts to views which use PHP code.
Comment: I added that to an install the other day and it locked my site up so all form submissions WSOD'd me with no errors, but I'll do a backup and give it a test run.
Comment: Reported installs: 10776 sites currently report using this module. http://drupal.org/project/views_php.
Comment: I backed everything up (<3 drush) and installed the module.  It didn't cause the same problem this go around so I configured what I needed and got it rolling after 3 fatal errors and one fundamental misunderstanding.  This answer led me to what I needed to get the job done.  Both answers would get +1 but my drupal.stack rep is too low.  Sorry guys.  I'll come back to fix that when I get some rep here.
Comment: Thumbs up. See you soon.

Create link to node on view


Intersection be set and dictionary and intersection of each word in set

Question: The title might sound a little confusing, but what I have is an input of words, for instance:
string = "It was"

I the turn the string into a list of the two words. Then find when each word intersects with a dictionary, where the words in a text file broken up into lines are the keys and the value is a set of line numbers.
I have this part down no problem, the issue is then finding only when it and was are in the same line. I cannot for the life of me figure out how to accomplish this.
I am away from my computer at the moment, but if I need to post the code to look over just let me know.
Any help would be greatly appreciated!
EDIT
def find_cooccurance(D, inp_str):
end_set = set()
words = inp_str.split()
inp_set = set(words)
lst = []

for val in inp_set.intersection(D):
    end_set = D[val]
lst=list(end_set.intersection(D[val]))

if lst == []:
    lst.append("None.")

return sorted(lst)

inp_str = "It was"

D = {'it' : {1,2,3}, 'was':{2}}
This is just a small part of the code, the rest of it is very long.
What I have been getting as a return when I print lst:
  [1, 2, 3]

what I should be seeing is:
 [2]

Since It and was both appear on that line.
Comment: Your intent is extremely unclear. Can you show us samples of the code you've written, the results you want, and the results you're getting?
Comment: sample of your text file will also be helpful
Comment: Terribly sorry, I made some edits and added code.
Answer: It's a bit difficult to tell what you're looking for without any real example code, but the way I have set it up below, you can find the intersection of all sets of lines corresponding to 'It' and 'was' using lambda and  reduce:
from functools import reduce
from collections import defaultdict
import re

file_text = """
First line
It was a good day :)
Third line
It was a decent day :|
Fifth line
It was a bad day :(
"""

word_dict = defaultdict(set)

for line_no, line in enumerate(file_text.split('\n')):
    for word in re.split('\\s+', line):
        word_dict[word].add(line_no)

def lines_containing_all(*words):
    return reduce(lambda a, b: a & b, (word_dict[word] for word in words))

print(lines_containing_all('It', 'was'))


When try to delete a record that stores in the memory throws exception

Question: I was trying to delete a record that was not saved in DB it throws the following exception

Error occurred. Collection was modified; enumeration operation might not execute

I can't understand why i get this error message only when try to delete that record is in memory, i don't have issue to delete a record that saved in the back end.
here is the code throws exception.
 public bool DeleteVegetationZone(ref Assessment objAssessment, int VegetationZoneIDToDelete, string UserFullname, ref string ErrorMessage)
    {
        string RowFilter = @"VegetationZoneID=" + Convert.ToString(VegetationZoneIDToDelete);
        Assessment.tblVegetationZoneRow[] VegetationZoneRows = (Assessment.tblVegetationZoneRow[])objAssessment.tblVegetationZone.Select(RowFilter);
        if ((VegetationZoneRows != null) && (VegetationZoneRows.Length != 0))
        {
            if (VegetationZoneRows.Length == 1)
            {
                if (VegetationZoneRows[0].VegetationZoneID > 0)
                {
                    VegetationZoneRows[0].UpdatedBySystemUser = UserFullname;
                    VegetationZoneRows[0].SaveType = (int)EnumCollection.SaveType.RemoveOnly;
                }
                else
                {
                    VegetationZoneRows[0].Delete();
                    objAssessment.AcceptChanges();
                }
                //Delete the child records
                //tblTransect
                foreach (Assessment.tblTransectRow TransectRow in objAssessment.tblTransect.Rows)
                {
                    if (TransectRow.VegetationZoneID == VegetationZoneIDToDelete)
                        DeleteVegTransectPlot(ref objAssessment, TransectRow.TransectID, UserFullname, ref ErrorMessage);
                }

                //tblManagementZone
                foreach (Assessment.tblManagementZoneRow ManagementZoneRow in objAssessment.tblManagementZone.Rows)
                {
                    if (ManagementZoneRow.VegetationZoneID == VegetationZoneIDToDelete)
                        DeleteManagementZone(ref objAssessment, ManagementZoneRow.ManagementZoneID, UserFullname, ref ErrorMessage);
                }

                //tblThreatenedSpeciesSubzone

                foreach (Assessment.tblThreatenedSpeciesSubzoneRow ThreatenedSpeciesSubzoneRow in objAssessment.tblThreatenedSpeciesSubzone.Rows)
                {
                    if (ThreatenedSpeciesSubzoneRow.VegetationZoneID == VegetationZoneIDToDelete)
                        DeleteThreatenedSpeciesSubzone(ref objAssessment, ThreatenedSpeciesSubzoneRow.ThreatenedSpeciesZoneID, UserFullname, ref ErrorMessage);
                }

                UpdateSpeciesGeoHabitatSurveyTime(ref objAssessment, UserFullname, ref ErrorMessage);
            }
            else
            {
                //Cannot have more than one row with same key
                ErrorMessage = "Error: More than one record found - Vegetation zone ID = " + Convert.ToString(VegetationZoneIDToDelete);
                return false;
            }
        }
        else
        {
            //Must have at least one row with same key
            ErrorMessage = "Error: Record not found - Vegetation zone ID = " + Convert.ToString(VegetationZoneIDToDelete);
            return false;
        }
        return true;
    }

exception thrown at
 foreach (Assessment.tblThreatenedSpeciesSubzoneRow ThreatenedSpeciesSubzoneRow in objAssessment.tblThreatenedSpeciesSubzone.Rows)
                {
                    if (ThreatenedSpeciesSubzoneRow.VegetationZoneID == VegetationZoneIDToDelete)
                        DeleteThreatenedSpeciesSubzone(ref objAssessment, ThreatenedSpeciesSubzoneRow.ThreatenedSpeciesZoneID, UserFullname, ref ErrorMessage);
                }

Comment: types are not clear, what is the type of Assessment.tblThreatenedSpeciesSubzoneRow and what function DeleteThreatenedSpeciesSubzone does ?
Comment: already i looked at that post but i can't help myself with that answer, thats the reason i posted here.
Comment: It's never a great idea to remove items from a collection *during* iteration because it can break the enumerator. Reason being indexes/positions of items will all change, however, if you work your way *backwards* you can remove safely as the positions of the items won't change.
Comment: The two answers you received here basically repeat what is being stated in the duplicate, bu then tailored to your code. That should work. If not, show your `DeleteThreatenedSpeciesSubzone` code.
Comment: @CodeCaster, the answers are not helping me much, it doesn't row[i] or Tolist either.
Answer: Change the loop from foreach to equivalent for:
// Note reversed order of the for loop
for (int i = objAssessment.tblThreatenedSpeciesSubzone.Rows.Count - 1; i >= 0; --i) {
  Assessment.tblThreatenedSpeciesSubzoneRow ThreatenedSpeciesSubzoneRow =
    objAssessment.tblThreatenedSpeciesSubzone.Row[i];

  if (ThreatenedSpeciesSubzoneRow.VegetationZoneID == VegetationZoneIDToDelete)
    DeleteThreatenedSpeciesSubzone(ref objAssessment, ThreatenedSpeciesSubzoneRow.ThreatenedSpeciesZoneID, UserFullname, ref ErrorMessage);
}

Since you can't modify collection within foreach loop but you can do it within for one.
Edit: when Row[i] is not supported, you can emulate it via Linq:
var list = objAssessment.tblThreatenedSpeciesSubzone.Rows.ToList(); // <- Linq

for (int i = list.Count - 1; i >= 0; --i) {
  Assessment.tblThreatenedSpeciesSubzoneRow ThreatenedSpeciesSubzoneRow =
    list[i];

  if (ThreatenedSpeciesSubzoneRow.VegetationZoneID == VegetationZoneIDToDelete)
    DeleteThreatenedSpeciesSubzone(ref objAssessment, ThreatenedSpeciesSubzoneRow.ThreatenedSpeciesZoneID, UserFullname, ref ErrorMessage);
}

Comment: @Dimitry , unfortunately it doesn't like Row[i], updated my code in full.
Comment: @Usher: if direct `Row[i]` is unwanted, you can try creating a copy/cache of items via `.ToList()`
Comment: Thank Dmitry, i do have system.Linq but when i use your code i got this exception @Error 5 'System.Data.DataRowCollection' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'System.Data.DataRowCollection' could be found (are you missing a using directive or an assembly reference?)
Answer: In your foreach loop should look like :
foreach (Assessment.tblThreatenedSpeciesSubzoneRow ThreatenedSpeciesSubzoneRow in objAssessment.tblThreatenedSpeciesSubzone.Rows.ToList())

This occurs as your trying to modify the collection when it is being used.
Comment: As explained above when you are looping  through a collection and you are modifying the same collection , you will get this error.
Comment: I still cant get why this was down voted :0/
Comment: Not mine thumb down, but perhaps idea of creating another collection by calling linq `.ToList()` is not obvious. Or because it's an answer in the linked question.
Comment: i have  row collect and its not showing an option to use .ToList () anyway
Comment: did you add reference to System.Linq ??
Comment: @adityaswami89 i did ,still no luck
Comment: The main problem is you are trying to delete a particular record which is still getting parsed through the collection.
My suggestion is that : You keep a property called as CanDeleted in ThreatenedSpiecesSubzoneRow and just assign CanDelete = true in your method. After parsing try to  delete all the records whose CanDelete == true.
You cannot at anytime modify the collection when it is being used.Kindly let me know if this helps.


Why are random walks in dimensions 3 or higher transient?

Question: I watched this PBS video a while ago (relevant part here) and have been trying to get my head around the idea of transient walks. The video says that a recurrent random walk is one that is guaranteed to return to it's starting position - all 1D and 2D walks - and a walk is transient if there is a positive probability that it never returns - 3D or higher. I've tried to have a think about this and looked some stuff up but I haven't had any breakthroughs.
What confuses me is this: A random walk in 3 dimensions can be split up into 3 independent random 1D walks. If each of these walks is guaranteed to return to the starting position infinitely many times we can say that there is a finite positive probability that they will return to the starting point on a given 'turn'. The product of the three finite probabilities is finite so isn't there a finite chance that any random walk in three dimensions will return to the start on any given 'turn' and hence they are guaranteed to return at some point?
I imagine I am just making incorrect assumptions about the nature of these infinite systems as is too easy to do but I'd like to know exactly where my intuition is wrong.
Comment: Indeed the trouble is that the probability that the second and third coordinates are both at zero when the first coordinate is back at zero for the $n$th time, is decreasing with $n$. The argument you delineate fails if these probabilities sum to less than $1$. (Simple proofs of recurrence/transience can be reduced, considering the mean number of visits of the origin, to noticing that the series $\sum n^{-d/2}$ diverges when the dimension $d$ is $d=1$ or $2$ and converges when $d\geqslant3$... but you did not ask for a proof, did you?)
Comment: I am not an expert, but the obvious problem seems to be your assertion that "we can say that there is a finite positive probability that they will return to the starting point on a given 'turn'" -- if "number of returns in 1D to starting point before turn $n$"/$n$ tends to zero, then your 'probability' can be 0, even if the number of returns is infinite.
Comment: I cannot figure out what your question is. What assumptions are you making? What is your conclusion? Can you tell me step by step how you derived your conclusion and what your reasoning is? I'll give you a few facts and then you may have the answer to your own question. Maybe you'll realize what assumptions you were making that you didn't know how to explain earlier because you performed some calculations without knowing how you did it. If you later figure out the resolution to your problem and write an answer explaining it then accept your own answer which you can do 2 days after you post it,
Comment: it may be very valuable to other people who have the same question and find your answer by a Google search. Anyway, here's the fact. In 2 dimensions, think of the random walk as being continuous rather than discrete because the tendencies approach that as you approach an infinite amount of time. Also, imagine there are concentric circles around the starting point equally spaced apart. Starting on one circle, the probability that the next one you will hit other than that one itself is the the next one out is a tiny bit more than 50%. I believe I once figured out a proof I can't remember anymore
Comment: where Starting somewhere, the probability that the next time you hit a circle that's either twice or half the diameter of the one you're on, it will be the one of twice the diameter is exactly 50%.
Answer: In 1 dimension, although the expected number of times that you will return to the origin before a give time approaches infinity as time approaches infinity, it varies sublinearly with time. When you have 3 independent 1-dimensional random walks all starting at the origin, although you can expect that each of them individually will return to the origin infinitely many times, it does not follow that there will ever be a time when all 3 of them are at the origin, although that might happen.
Answer: The problem is that you don't want each of the three random walks to come back to zero on its own axis. You want those come-back to synchronize, that is, to come back to zero on every axis at the same time.
It turns out that each 1d walk comes back "sufficiently enough" to zero to allow for the synchronization in $2d$, but not in $3d$. Said differently, you're right in the fact that the axis $x_1 = 0$, $x_2 = 0$ and $x_3 = 0$ will be visited an infinite amount of time, but this is very different from visiting $(0,0,0)$ an infinite amount of time.


Counting question proof involving binomial

Question: Let $x,y,z,n$ be positive integers such that $x\leq y\leq z\leq n$. Prove (by counting in two different ways) that:
$\binom {n} {x} \binom {n-x} {y-x} \binom {n-y} {z-y} = \binom {n} {z} \binom {z} {y} \binom {y} {x}$
This is what I have done so far:
Consider an example that there is a box with $n$ beads:
total no. of beads = $n$
No. of square beads = $z$
No. of square beads that are black $=y$
No. of square beads that are black and blue $= x$
Counting method 1:
The number of ways to finding an black and blue bead = $\binom {n} {z} \binom {z} {y} \binom {y} {x}$
How do I finish this proof?
Answer: Ok I have an answer but its not well written:
n-x =>no. of square beads that are not black and blue
y-x =>no. of square beads that are black
n-y =>no. of beads that are not black
z-y =>no.of square beads that are not black
The other counting method should be clear using this.
Answer: Suppose a coach wants to select a team of z people from a group of n people, and then choose y starters on the team and x captains from among the starters.
If the coach first chooses the team, then the starters from the team, and then the captains from the starters, there are $\displaystyle\binom{n}{z}\binom{z}{y}\binom{y}{x}$ possibilities.
If the coach chooses the captains first, then chooses the remaining starters, and then chooses the rest of the team, there are $\displaystyle\binom{n}{x}\binom{n-x}{y-x}\binom{n-y}{z-y}$ possibilities.


Probability question: distance of point from centre of square

Question: A point 'A' is randomly chosen in a square of side length 1 unit. Find the probability that the distance of A to the centre of the square does not exceed x.
I don't get how to even start the solution. Can anyone please help me?
Comment: what can you use?
Comment: Sorry I cannot understand what you want to ask
Comment: is it homework? did you learn markov inequality yet? other formulas?
Comment: Its not a homework question. No I have no idea about Markov inequality. Actually this question appeared in our maths olympiad question paper
Answer: The required probability is the ratio of the area of the circle to the area of the square.
That is $\pi x^2$.
Comment: And what if $x > \frac{1}{2}$?
Comment: But how can I prove that or justify that
Comment: Yes I was thinking of solving it making various cases: x<0,1/2>x>0 and x>1/2
Answer: The point $A$ can be thought of $(X,Y)$ where $X$ and $Y$ are independent uniformly distributed random variables.  Taking the square as having diagonally opposite corners $\left(-\frac 12, -\frac 12\right)$ and $\left(\frac 12, \frac 12\right)$, you are asked to compute the probability that $\sqrt{X^2+Y^2} < x$, which works out to be a ratio of
areas. For the case $x < \frac 12$, see the answer by Abishanka Saha. For $\frac 12 < x < \sqrt{1/2}$, you need to compute the area of the intersection of the square and the circle
which is a more complicated calculation than the $\pi x^2$ of the simpler case.
Comment: Well I think I can give it a try using area under curve using integration since I know the equations of the curves.


How to change the default selection in views filter?

Question: Content type has two fields: Property type and bedroom.
I created a view where above fields were exposed to visitors.
When I visit my site, I see -Any - is the default value for the both fields. First field is the property type and the second field is the bedroom field.

Property type field :

Bedroom field:

How can I replace the default value -Any - by the corresponding field label? For example, for property type field, I like to see Property Type as the default value and for the bedroom field, I like to see bedroom as the default value in the drop down list.
Answer: You can change it with custom code in a module or overriding your theme.
You can also use the Better Exposed Filters module. Change the Exposed form options in your Views to use that module option. Then in the further settings you'll be able to override what the options are called for each filter separately.
Drupal 7 also had Views Advanced Labels.

Use this field to rewrite the filter options displayed. Use the format of current_text|replacement_text, one replacement per line. For example:
 Current|Replacement
 On|Yes
 Off|No

Leave the replacement text blank to remove an option altogether.
Comment: This is for D8. Can you please provide some details about the custom code as well?
Comment: You would have to implement [hook_form_FORM_ID_alter](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_FORM_ID_alter/8.8.x) for views_exposed_form. Better Exposed Filters is a great little module to handle this with configuration though!
Answer: As stated by prkos in his comment (sorry, I don't have enough reputation to reply to his comment), you could benefit of Better Exposed Filters. What you would need to do is:

Enable Better Exposed Filters and clear the cache
In your view, open the Advanced section > Exposed Form > select 'Better Exposed Filters'
On the settings Exposed Form > Exposed form Style > Settings, go down and find your exposed filter
Expand your filter and rewrite the '- Any -' as this: - Any -|Bedrooms
That will change the LABEL of the select option, but the value will always be 'All' unless you change it via code. If code is what you need, please say so and I will try to provide a useful snippet.


Locally Lipschitz implies Lipschitz under equivalent metrics?

Question: Bonjour.
For $i=1,2$ let $X_i$ be a non-empty set and $d_i$ a metric $X_i^2 \to \mathbb{R}$. Suppose $f$ is a locally Lipschitz (*) function $(X_1, d_1) \to (X_2, d_2)$.

Question. Do there exist metrics $\delta_1: X_1^2 \to \mathbb{R}$ and $\delta_2: X_2^2 \to \mathbb{R}$ such that i) $\delta_i$ is (topologically) equivalent to $d_i$ (for $i=1,2$) and ii) $f$ is a Lipschitz function $(X_1, \delta_1) \to (X_2, \delta_2)$?

(*) For each $x \in X_1$, there exists a neighborhood $U_x$ of $x$ in $(X_1, d_1)$ such that the restriction of $f$ to $U_x$ is a Lipschitz function $(U_x, d_1) \to (X_2, d_2)$.
Comment: This question does not make sense to me. You can simply choose $\delta_i = d_i$. Your heading seems to imply that you want to know whether $f$ will remain locally Lipschitz if the $d_i$ are replaced by arbitrary (topologically) equivalent metrics $\delta_i$. While I don't know a counterexample, I doubt this is true, though, cause topological equivalence does not let you control the size of neighbourhoods in the metric sense.
Comment: @Thomas: the OP wants to see if one can find a different metric generating the same topology such that the locally Lipschitz function is now globally Lipschitz. For example, let $f:\mathbb{R} \to \mathbb{R}_{\geq 0}$ be $x\mapsto x^2$. This is locally but not globally Lipschitz. But if you take the diffeomorphism $\mathbb{R}_{\geq 0}\mapsto\mathbb{R}_{\geq 0}$ given by $x\mapsto \sqrt{x}$, you pull back a Riemannian metric (and hence a distance function) w.r.t. which the map $f$ is now Lipschitz globally with Lipschitz constant 1.
Answer: Yes — assuming that "$d_1$ is topologically equivalent to $\delta_1$" means that $d_1$ and $\delta_1$ induce the same topologies.
It is sufficient to require $f$ to be continuous, and only the metric on $X_1$ needs to be modified.
Put $\delta_1(x,y) = d_1(x,y) + d_2(f(x),f(y))$.
Then $\delta_1$ is a metric which is topologically equivalent to $d_1$: Indeed, since $d_1 \leq \delta_1$ we have that $x_n \to x$ with respect to $\delta_1$ implies $x_n \to x$ with respect to $d_1$; conversely, continuity of $f$ ensures that  $d_1$-convergence implies $\delta_1$-convergence. Thus, both metrics describe the same closed sets on $X_1$, so they induce the same topologies.
As $d_2(f(x),f(y)) \leq \delta_1(x,y)$ we see that $f:(X_1,\delta_1) \to (X_2,d_2)$ is $1$-Lipschitz.
Comment: @Jesse: the answer to your question is "yes". (t.b. set $d_2 = \delta_2$.)
Comment: Is the codomain $(X,\delta_2)$ or $(X,d_2)$?


How to order by serializers.ListField on Django Rest Framework

Question: How can I order by a serializers.ListField at a ViewSet?
class FooSerializer(serializers.ModelSerializer):
    bar = serializers.ListField()

e.g.
I want to order by the fist element of the list
GET http://localhost:8000/api/foo?ordering=bar[0]

{
    ...
    results: [{bar:[1,'a']},{bar:[2,'c']},{bar:[3,'d']}]
    ...
}

Comment: Order In what perspective ?
Comment: e.g. `[{bar:[1,'a']},{bar:[2,'c']},{bar:[3,'d']}]`
Answer: You could override list method, evaluate queryset and then sort it by your key:
class FooViewSet(viewsets.ModelViewset):
    queryset = Foo.objects.all()
    serializer_class = FooSerializer

    def list(self, request, *args, **kwargs):
        order = request.query_params.get('ordering')
        q = self.get_queryset()
        serializer = self.get_serializer(q, many=True)
        sorted_q = sorted(serializer.data, key=lambda x: x['bar'][0])
        return Response(sorted_q)

Comment: this doesn't check what type of ordering I'm requesting in the GET request, and also is doing the ordering in the serializer instead of the viewset
Comment: @JulioMarins you don't say any word about `GET` parameters, let me think about it
Comment: @JulioMarins your problem is really weird. If you want to filter all queryset by value in that array it is to put that logic in a filter or viewset. But if you want to change representation it is best way to keep it in a serializer, because in a view you don't wan't to evaluate queryset before response. Can you explain more clear please. The final purpose is change ordering of a `bar` field in each queryset item?
Comment: it's not filtering. The problem is to order the results by the first element of `bar` which is a `serializers.ListField`
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/133017/discussion-between-ivan-semochkin-and-julio-marins).
Comment: With your answer I can change a single object of the results, but what I want do to is to order the results by a property of the object which is a list


Form with Text and Submit give wrong output value

Question: I have a little problem with my HTML Form and can't resolve it.
I have the following form:

   <form action="" method="get">
   <input type="text" name="search" placeholder="Search">
   <input type="submit" value="Search">

It works without any problem, but it appends to the URL another value that is not present.
To give an example, the correct URL will be "SITE_URL/?search=VALUE" but from nowhere it become "SITE_URL/?search=VALUE&cat=-1" with &cat=-1 that I don't know how to remove.
I've got around the problem temporarily with a redirect removing the wrong part, but it's not so elegant nor optimized. I hope someone could help, thanks!
P.S. My bad, </form> was in the wrong position, all okay now...
Comment: Where is the form tag closed?
Comment: ...that's exactly what was the problem, I was rewriting some code and found a lonely `` many lines after... :(
Answer: You forgot to close the form tag. That's why it shows some other input's value too because you must have that somewhere else in the code and the form takes that to be the part of it too. So use this, it will work -

  <form action="" method="get">
    <input type="text" name="search" placeholder="Search">
    <input type="submit" value="Search">
  </form>

Comment: Yeah, I've updated the question because I've found a random `` in the wrong position, obviously causing the problem...


vertical angle between vectors

Question: I'm trying to find out the horizontal and vertical angle between two vectors to determine if an object is withing the field of view of a person by comparing these angles to the maximum horizontal and vertical angles that a human can see.
If human is at position $p_h$, the direction he is facing is given by $a$ and an object is at position $p_o$, then  $p_o-p_h$ gives us a vector  $b$ from  $p_h$ to  $p_o$.
To know if the object is within the hortizontal field of view, I set  $a_y$ and $b_y$ to 0 and calculate the angle between the vectors by
$$\theta = cos^{-1}\frac{a\cdot b}{|a|\cdot|b|}$$
and then comparing the result to the visual field limits.
However to get the vertical angle, it seems I can't just set $a_x$ and $b_x$ to 0 as it is apparently not equivalent to setting $a_z$ and $b_z$ to 0.
I thought it should be equivalent, but after seeing some visualizations I'm convinced they are not.
I realize this should be relatively trivial, but I just can't wrap my head around it and I've been stuck on this for the last few hours. I've also looked for this in google as I thought it would be a rather common problem, but I can't find exactly what I'm looking for.
How do I get the vertical angle between these two vectors?

Here are a few graphs:
The sample vectors could be $a = (4,3,1)$ and $b= (2,7,9)$
In this site z is up, so please don't get confused.
First here is the 3D plot

Then we can project it to a top down view (equivalent to ignoring the y or in this case z component and look at the angle $\theta$). This way we get the horizontal angle between the vectors

If we then try to do the same for the vertical angle, we look at the side and front views and we can see that $\beta \neq \gamma $
Comment: Then how are you able to set $a_y$ and $b_y$ to zero for horizontal field of view? It would be nice if you can include a sketch!
Comment: @samjoe I added a few plots, hopefully this makes it clearer
Comment: How exactly do you define the field of view here? Are its bounds the maximum "up"/"down" and "left"/"right" angles from the view direction $a$? If so, how do you define "up" relative to this vector?
Comment: @amd The field of view is indeed defined as that: 80° to either side of **$a$** is the horizontal view angle.45° up and 60° down are vertical bounds. I'm not sure if I understand your question very well, but maybe this helps: if we have a plane with a normal vector orthogonal to **$a$** and the "up" axis, then up relative to this vector is what lies above vector **$a$** in this plane.
Comment: How about this: are the top and bottom edges of the visible region parallel to the $x$-$y$ plane, i.e., the camera has pitch and yaw, but no roll?
Comment: the camera has yaw and pitch, but roll remains always the same
Comment: Sorry, my answer was wrong! I can't find a relation about how to calculate angle properly! But I think you must first make $a$ horizontal. Then for horizontal range, you can project $b$ on horizontal plane containing $a$. For vertical range, you can project $b$ on vertical plane containing $a$.
Comment: I think i figured it out. I'll try to implement it and see how it works. Then I'll post the answer.
Comment: @samjoe To compute the "vertical" angles via a rotation, rotate $b$ so that it lies in the same vertical plane as $a$.
Answer: Indeed, setting $a_x=b_x=0$ (looking down the x-axis) is not the same as setting $a_z=b_z=0$ ().  The "vertical angle between two vectors" is not unambiguously defined in an obvious way.
If you project the vectors onto a vertical plane to compare the angles, then the angle between the projections in that plane will depend on the choice of your plane, i.e. it will depend on the line you are looking down.
For example let $\mathbf{a}= (1,1,1)$ and $\mathbf{b}=(1,-1,1)$.  If you look down the x-axis, the angle between these two is a right angle, but if you look down the line $x+y=0$, the angle between them is zero.
Consider the plane P that contains the two vectors $\mathbf{a}$ and $\mathbf{b}$.  The angle between the vectors in that plane is well-defined.  That is what we get by using between two 3-d vectors the cosine formula you have written down.
You can choose to make your own definition for "vertical angle".  For example, let $\theta_a$ be the angle between the vector $\mathbf{a}$ and the xy plane. Let $\theta_b$ be the angle between the the vector $\mathbf{b}$ and the xy plane.  You may choose to define the vertical angle as $|\theta_a-\theta_b|$.  In the example I gave, this angle is zero.
A case where it is unambiguous is when the plane P is perpendicular to the xy plane.  In that case, $|\theta_a-\theta_b|$ is the same as the result from the cosine formula.   But please note that in general, that is still going to be different from what you get by looking down the x axis (setting $a_x=b_x=0$) or the y axis.
Answer: You can't really measure the "vertical" angle between the vectors via orthogonal projection because that distorts the angle. The underlying reason that projecting onto the $x$-$y$ plane (in the second coordinate system in the question) works for the horizontal angles but in general there's no orthogonal projection that will get the vertical angles right is that all of the yaw rotations use the same rotation axis, but pitch rotations don't.
You can, however, project the vectors/points onto the unit sphere, i.e., convert to spherical coordinates: $$\theta=\arccos{z\over\sqrt{x^2+y^2+z^2}} \\ \varphi = \arctan\frac yx.$$ (We don't care about $\rho$, the distance from the origin, here.) You need to select the correct quadrant for the arc tangent, but math packages have a built-in variant of this function that takes care of this for you. Note, too, that $\theta$ increases downwards from the $z$-axis. Since there's no camera roll, the horizontal visual angular separation is just the difference between the azimuths $\varphi$ and the vertical visual angular separation the difference in inclination $\theta$.
Using your example of $a=(4,3,1)$ and $b=(2,7,9)$, we have $\varphi_a=\arctan\frac34\approx36.870°$ and $\varphi_b=\arctan\frac72\approx74.055°$, for a difference of approximately $37.185°$, well within the field of vision. This matches the angle obtained from the projections onto the $x$-$y$ plane. It's probably less computationally expensive to use the latter method since you can compare directly against $\cos 80°$ instead of computing an arc cosine, but this really only works because the visual field is horizontally symmetric. If you had different angles to the left and right, using the arc tangent is better since cosine doesn't distinguish between different directions.
For the vertical angles, we get $\theta_a=\arctan 5\approx78.690°$ and $\theta_b=\arctan{\sqrt{53}\over9}\approx38.969°$ for a difference of $39.721°$, also within the field of view.
It's also possible to compare the vertical angles by rotating $b$ so that it lies in the same vertical plane as $a$, but that seems like more work than just converting to spherical coordinates.
If you have to check a lot of points for visibility, computing all of those inverse trigonometric functions could get expensive. The field of view is bounded by four planes through the origin, so an alternative approach is to compute the equations $ax+by+cz=0$ ($\mathbf n\cdot\mathbf x=0$ in vector form) of these planes that make up the sides of this pyramid. The sign of dot product of the normal to the plane $\mathbf n$ with an arbitrary point tells you on which side of the plane the point lies: if positive, then the point lies in the direction of $\mathbf n$ from the plane; if negative, it's on the opposite side; if zero, the point, of course, lies on the plane. You can arrange for all of the normals to be inward-pointing, so that a point is visible iff all four of these test values are non-negative.
Comment: Thanks! I do need to check lots of points so I find your idea with the pyramid especially useful! Do you additionally have an idea on how to compute these planes efficiently? I would make four copies of the gaze direction vector and rotate them vertically and horizontally by the max bounds to make the four "corners" of the pyramid.
Comment: @Girauder If the visual field is specified in terms of visual angles, I think using spherical coordinates is the most straightforward way to go. Add/subtract angles from the line of sight and convert back to Cartesian to get direction vectors of the edges. The four plane normals are their pairwise cross products. Take care with the order of operands so that all of the normals end up inward- or outward-pointing. You could rotate the view vector directly, but that seems more expensive since you have to find the correct rotation axis.

vertical angle between vectors


Is it possible to fall back to a global variable if it isn't defined in the local scope in a Twig template?

Question: Say I have following _teaser.twig partial:

 {{ article.headline }}

 {{ article.lede }}

  {% if {{article.byline }} %}
    <address>{{ article.byline }}</address>
  {% endif %}

Which i include these ways:

  {% for article in teasrs %}
    {% include '_teaser.twig' %}
  {% endfor %}

  {% for article in opinion.items %}
    {% include '_teaser.twig' %}
  {% endfor %}

With the following data structure in a json file:
{
  "article": {
    "headline": "A short headline",
    "lede": "A short descriptive lede paragraph"accusantium"
  },
  "teasers": {
    "article1": {
      "headline": "Some headline",
      "lede": "A lede that describes the article, but without revealing too much, so that users still have a reason to click"
    },
    "article2": {}
  },
  "opinion": {
     "article": {
       "byline": "Anonymous"
     },
     "items": {
       "article1: {},
       "article2: {}
     }
  }
}

Ideally, I'd like the variable resolving to go up the scope, the same way it does in Mustache.
The desired output is:

 Some headline

      A lede that describes the article,
      but without revealing too much, so that
      users still have a reason to click

 A short headline

 A short descriptive lede paragraph

 A short headline

 A short descriptive lede paragraph

    <address>Anonymous</address>

 A short headline

 A short descriptive lede paragraph

    <address>Anonymous</address>

Unless I'm missing something, specifying the default using the default() filter isn't desirable, as I'd like the default content to be derived from the model, not the view. For instance, In the teasers, I don't want to have a fallback byline, but in the opinion section, I'd like to always show a byline, with a fallback to Anonymous, for which using default won't help with.
Answer: Use default pipe
doc : http://twig.sensiolabs.org/doc/filters/default.html

 {{ article.headline|default('default value) }}

 {{ article.lede|default('default value) }}

Comment: Thanks! I know the `default` filter, but I would like the default to be derived from the model not the view (i.e. from the `json` not the `twig` file).

Ideally, I'd like the search to go up the scope, the same way it does in `mustache`. I'll update the question to represent this


Repeat bar errors

Question: I'm triyng to have the second line open at the end as the first. But with repeats bar at the third line the second line get a bar and if I try to overrite with \once \hide Staff.BarLine also the bar at the third line disappears. What's the correct way to do it?
Thank you.

Here is my minimal code.
Comment: @Mahanidhi Could you make sure your minimal code is able to be compiled? Also, I wonder if the repeat at the start of the third line is part of the issue; LilyPond might force a barline at the end of the second system since a repeat is about to start.
Comment: It's a bit hard to tell exactly what you are asking for, but if you want an invisible bar line try `\bar""`
Comment: I want the second line without bar. \bar"" doesn't work.
Comment: Sorry I forgot to add the \include-all file: http://lilybin.com/6s1z36/1
Answer: This is done with the break-visibility property.
Add \once \override Score.BarLine.break-visibility = #'#(#f #t #t).
More about the break-visibility property here.
Minimal example:
\score {
    \new Staff {
        \relative c' {
        \key des \major
        \cadenzaOn
        \repeat volta 2 {
            des4 ees f2
            des4 ees f2 \bar "" \break
            des4 ees f2
            des4 ees f2
        }
        des4 ees f2 \once \override Score.BarLine.break-visibility = #'#(#f #t #t) \break
        \repeat volta 2 {
            des4 ees f2
            des4 ees f2
        }
        }
    }
}

Repeat bar errors


How to show an AlertDialog with a background task in Flutter

Question: Good morning,
I'm developing my first application in Flutter and I would like to implement a background task that every second checks if a condition meets requirement. In other words, while the user uses the application, in background there is a task that checks if the current time is in a particular range (e.g 09:42 is between 09:30 and 10.00, then ok). If yes, I want to show an Alert Dialog
I have already tried to use Isolate but I failed to do that
Thank you
Answer: If you have any state management implemented like bloc or flutter_redux or mobX, you can have a field in your state like "bool showAlert" and have a streambuilder which will listen to your app state changes and show the alert dialog when "showAlert" property is true.


Why didn't classical music use drums?

Question: I was wondering why doesn't most classical music use drums? For example when I type in "classical music" on youtube, most of the music I hear doesn't have drums. Take Bach, Mozart, Beethoven as an example of what I mean. I saw that some orchestras have drums, but the drums usually accent the music rather than drive it.
In contrast, today's music is built on top of drums. It usually starts with a beat and then melody/harmony is layered on top of it, especially in Hip hop and EDM. But in classical music they don't put as much emphasis on drums or beats. I was wondering why this is so?
Comment: The term 'classical' needs defining in this question. That in itself can make a huge difference to answers.
Comment: I'm voting to close this question as off-topic because it's just plain wrong.
Comment: Symphony with drum-roll by Haydn just to mention the most obvious?
Comment: Ravel _Bolero_?  Khachaturian _Sword Dance_?  Copland _Fanfare for the Common Man_? All with lots of drums.
Comment: How about asking something more specific like, why isn't Western classical music composed between the years 1750-1850 driven by drums and percussion? Why did they use drums and percussion mainly for accenting, not driving the music? Why are there no polyrhythms? Why is there a conductor, not a drummer driving the music? Why does Western music need to have a beginning and end, why can't music just be played for hours or days?
Comment: I'm voting to close the question because its validity necessitates that the OP's statements are true, which they are not. "Classical" music is music relating to the Western European musical tradition. "Classic" music is music from the Classic Era (not "Classical") approx. 1750-1832. "Drums" as the OP uses them should be specified as drum kits or drum sets. Composers have been using all outrageous manner of percussion instruments for several hundred years, and it's not worth it to offer examples as there are literally thousands.
Comment: If you think there are no drums in classical music, try [this recording](https://www.youtube.com/watch?v=am8YmCmNZ5s) of Berlioz's *Grand Messe des Morts* and jump to 28m04s to see a **lot** of drums, and indeed drummers giving it large.  I've performed this work, and it sounds pretty much like the end of the world at that point, which is entirely appropriate!
Comment: @b3ko, and it's from the same OP!
Comment: There are Concertoes for Beatboxers are you aware of this or not?
Comment: Classical music uses lots of percussions and drums. See [here](https://www.youtube.com/watch?v=-lJctvybAJ8) (skip the part about chromatic percussions if you want).
Comment: I'm voting to close this question as off-topic because it starts with an assumption which is at least debatable.
Comment: This question seems somewhat related:  https://music.stackexchange.com/questions/90333/can-the-bass-be-used-instead-of-drums?
Comment: Actually plenty of rock music, especially more ballad-like songs, starts with an percussion-free introduction, e.g. _Hiding on the Backstreets_ (Springsteen), though the beat usually kicks in after a while.
Comment: My first thought was that in classical music, the part of carrying the beat is handled by the conductor...
Answer: What you are thinking of as "drums" is really a collection of drums, percussion & cymbals gathered together in such a way as they can be played by one person. A drum kit or trap kit.
This idea came about initially at the end of the US civil war. Until then, marching bands had always been on the move - one drum per drummer was the standard setup.
Drummers in orchestras would also be booked one man per drum, but in smaller theatres with lower budgets, people were trying to come up with methods to reduce the costs.
The first of these was a snare & bass drum, with an overhanging pedal arrangement so one man could play both. Because techniques were still based on marching - we got the bass drum on the 1 & 3.. blend that with early jazz & vaudeville had begun.
Drummers would supplement this basic setup with maybe a cymbal, as Chinese immigrants brought that idea with them & a whole set of things to rattle, blow & bang - tambourines, swanee whistles, wood blocks & cow bells - which they would keep on a tray above the bass drum. This was their 'contraption tray', abbreviated to trap… from where we get the modern definition of a trap kit.
Add to that a couple of Chinese tom drums, then the last part to really complete what we think of as a modern kit came in 1926 with the invention of the hi-hat stand.
So, TL:DR pre-20th century orchestras didn't use drum kits because they didn't yet exist.
Also see Zildjian/Vic Firth's A Century of Drum Set Evolution with Daniel Glass. Well worth a watch.
Comment: This answer has a lot of interesting information, but I don't think it answers the question.  You explain why classical music didn't use a drum kit, but the question is about how drums are used within the music, which is quite different.  Plenty of non-modern genres (in Western classical tradition and elsewhere) use regular drum patterns as a constant driving force much like how modern pop, hiphop, etc do; conversely, plenty of modern pieces use drum kits, but in ways much more like the classical/romantic use of percussion, as a seasoning not a substrate.
Comment: Yup, and lots of other people have already covered that. I read the "question within the question" & answered that, Vote up which answers you like & vote down those you don't like. I'm not going to be modifying my own answer to cover the myriad new viewers who only found this because it hit the HNQ list.
Comment: @PLL - ahh, fair point. I actually hadn't even noticed it had attracted downvotes. As always happens when a question hits HNQ, vote numbers just go out of all proportion to any 'normal' question & any fairly short answers already leading the votes also get disproportionally high extra votes… then come the comments as to why the answer isn't 'perfect' & covers all eventualities. The answer to that is really just 'it was a quick response to what at the time was a rather vague question' - it's only since it hit HNQ that more scrutiny has been applied.
Comment: Fair enough — I'm not asking you to modify the answer, I'm just following the etiquette that when one downvotes, one should leave a comment explaining it.
Answer: Classical music did use drums: timpani and bass drum for starters.

...I'm talking where the rhythm is one of the main driving forces

Rhythm IS a driving force in classical music.
I think what you mean is a combination of: why didn't classical music use constant, repeated, dance patterns? and why didn't classical music use percussion throughout the orchestration of music as a principle instrument?
To the extent that sonata form is the epitome of classical form, repetitious dance patterns were not the norm, because sonata form focuses on different treatment of rhythm. Basically sonata form uses repetition on a much larger scale. It's a bit like asking why a novelist doesn't write all their prose in rhyming couplets... they don't because it's a different form. Sonata form doesn't use dance rhythm, because it isn't dance music.
Why percussion isn't used constantly in classical music can also be explained historically. The history of composition which eventually leads to the classical style starts with purely vocal sacred music, as music evolved wind and string instruments supported the voices, keyboard instruments also developed during those times, secular forms (like the madrigal) used instrumentation more or less similar to sacred. Within that historic context percussion would be associated with folk dance or martial music!
Fast forward to the styles that evolve into jazz - featuring drums as a principle instrument - and we see that the march genre is the direct ancestor! March > ragtime > jazz > popular blues > rock > disco. In other words, martial music, the march, is the form that evolves into jazz and various pop forms familiar now.
So, classical music didn't focus on percussion as a principle instrument like today's pop styles, because the style evolved from sacred vocal music rather than martial music.
Of course the are exceptional cases like Ravel's Bolero featuring the snare drum. Is that classical? Regardless, such exceptions don't make the rule.

Just a comment about folk dance. Obviously folk dance historically uses percussion. I regard that music as not the historic source for the development of classical style. So, for this question I don't compare modern pop with folk dance. Classical music did borrow from folk dance for effect - ex. musette - but folk dance wasn't the evolutionary origin of the classical style.
Comment: Nitpick: march and martial have different origins and meanings. To march comes from the French marche, or to walk, but martial is from Mars, the Roman god of war. I would remove references to martial music.
Comment: @jcupitt, I wasn't making an etymological connection. But, you were to make that connection, it would be: martial troops march, musical marches are an extension of that martial activity of marching. Marches are in fact _martial_ music.
Answer: Your post hints at a common misconception: that Classical music is "old music" and Popular music is "new music". Both traditions go way back, and continue to this day.
The definitions are sometimes contentious, but to get started, here's what Wikipedia has to say:
Art music:

Art music (alternatively called classical music, cultivated music, serious music, and canonic music) is music that implies advanced structural and theoretical considerations or a written musical tradition. The terms "serious" or "cultivated" are frequently used in relation to music in order to present a contrast with ordinary, everyday music (i.e. popular and folk music, also called "vernacular music"). At the beginning of the 20th century art music was divided into "serious music" and "light music".

Popular music;

Popular music is music with wide appeal that is typically distributed to large audiences through the music industry. These forms and styles can be enjoyed and performed by people with little or no musical training. It stands in contrast to both art music and traditional or "folk" music. Art music was historically disseminated through the performances of written music, although since the beginning of the recording industry, it is also disseminated through recordings. Traditional music forms such as early blues songs or hymns were passed along orally, or to smaller, local audiences.

I personally don't like these definitions, as the definition for Art music (and the name itself) is inherently derogatory of Popular and Folk music. So I prefer the term Classical. I also tend to lump Folk music in with Popular, as they're both music which is intentionally simple (so that it can be easily repeated, often by amateur musicians) and designed to have wide appeal.
Arguments about definitions aside, the fact remains that Classical music is a response to Popular/Folk music. Folk music goes back to the earliest musical instruments that humans created, and Classical music takes those ideas and makes them as impressive as possible, in both construction and technical difficulty. Classical music has long forms like Sonata form and multi-movement symphonies, while Popular tends to use things like strophic or verse-chorus form. Classical music is written for extremely difficult instruments like violin, while Popular music is written for relatively simple instruments like guitar (and historically, guitar-like instruments such as the lute) and drums.
So that's the short answer: drums are too easy to play, and drum beats make for too simple of music.
Comment: "drum beats make for too simple of music" should be "the western culture has traditionally been rhythmically very limited, so the only rhythmic things that would cross anyone's mind have been simple" Harmonically rich, rhythmically poor. :) So if your answer is based on the idea that drums are easy to play, it's a misconception and -1 for that. Drums are easy to play only if you settle for dumb simple rhythms.
Comment: Whatever the difficulty level of the violin is, it hasn't stopped people from regularly involving it in folk music (often as a "fiddle").
Comment: Sometimes "classical" means European music written during a certain span of years. Sometimes "classical" refers to a similar golden age for some other genus of music. Sometimes "classical" refers to music performed by professional musicians, dressed in formal black and white, performing before a seated, respectful audience, and playing from a score that was commissioned by some wealthy patron of the arts. Hard to say--maybe futile to say--which definition is the correct one.
Comment: @piiperiReinstateMonica - How come none of the music class drum circles I've ever been involved in have ever been complete flops, then? You'd think that a class of more than 15 students under the age of 13 would be one of the most likely groups that would be collectively unable to get their rhythmic act together, but they never devolved into white noise or a continuous drum roll.
Comment: @Dekkadeci Did I say it's impossible to learn to play drums enough to make anyone content? During the centuries when classical music was developed, it hasn't been a thing in the culture to pay much attention to rhythm. Look at classical music, the rhythms are _very_ simple. Have you ever heard an orchestra try and play even simple pop songs with tight timing? They cannot do it even if they try, the whole setup starting from how the stage and rooms are built and the players spread over a large area, it's designed for rhythmically simple and sloppy music.
Comment: "drum beats make for too simple of music" You should change this into: Some people don't know who Terry Bozzio or Mike Portnoy are and are thus prone to silly statements.
Comment: Can you even play a simple beat well? Most people cannot. If you settle for sloppy playing and dumb rhythms, the problem is with you and not the instrument.
Comment: The point being that it's musicians that add depth and complexity, not genres or instruments. Also, why is the triangle a staple of classical music if this explanation were true?
Answer: You are right that rhythm is usually not that important part of the classical music as for hip-hop or EDM. However, the dividing line does not go between classical and popular music as MattPutnam's answer suggests. The criterion is whether the music is intended to be used for dance (or march) or for listening (concerts).
For dancing and marching, the strong rhythm feeling is important while it might be superfluous or even disturbing if you are seated and listening to a classical concert. The concert music rather focuses on melodic and harmonic parts of the music, the rhythm and tempo can also vary more likely. And if you are used to listening to the concert music, you'll feel the rhythm just from the beats played by the melodic/harmonic instruments.
There are music pieces considered to be classical and use drums intensively. They mostly suggest dance music like Ravel's Bolero or waltzes by Strauss. Anyway, there are not just two types of music, we could very well create a whole spectrum of music based on their rhythmicity.
At the other end of the spectrum than very rhythmic EDM (i.e. Electronic dance music), we could probably find some of the church music, especially the Gregorian chant.
Comment: Looking at e.g. Chopin Waltzes or even Bach French Suites I don't agree with the dance/no dance boundary; I also don't recognize dancing and listening as complements.
Comment: Nevertheless, even church music may make heavy use of drums nowadays. In my church, we actually have a full rock-band line-up with drums, E-guitar, A-guitar, and keys. Other modern stuff like colored lights also have entered the scene. It's really a shift in paradigm that we witnessed in the west over the last century: Away from total focus on melody and harmony towards a more inclusive approach to music that embraces rythmic parts and generally uses whatever seems to make a good addition.
Answer: Historically speaking, classical music is largely from a Western European musical tradition that has never had much all that much emphasis (comparatively) on rhythm nor percussion --choosing instead to focus on the development of complex melodies and harmonic progressions.
In contrast modern popular music is all heavily influenced by music of the African Diaspora (blues, jazz, hip-hop, reggae, bossa-nova, etc.) which has always tended to have a strong percussive, drum-based element, going back to its African roots. So the disparity represents the different cultural origins of those types of music. There's probably no one identifiable reason why drums became less prominent in one culture's music than another --isolated artistic traditions always tend to diverge in one way or another.
It's worth noting, however, that this article argues that the relatively simple rhythms of modern pop music (as opposed to the highly complex and elaborated polyrhythms of African and Latin American music) are a result of its status as a hybrid of both African and European musical traditions (the same, perhaps, could also be said about its relatively simple harmonic progressions).
Answer: Since it is Christmas, what about the first movement of Bach's Christmas Oratorio, with a drum solo right at the beginning.
Comment: Just so no-one impatient is confused, the Bach (with the drums) starts at 1:01, before that there are just church bells. This was also the first piece I thought of, but it does not really answer the question why drums play a different role, nor demonstrate that they do not: to me they see more a dramatic flourish than the basis on which the rest is built. But I could not resist voting up anyway!
Answer: Try Callirhoe - Ballet Symphonique, by the near forgotten Cecile Chaminade (BBC Concert Orchestra).  Huge deep bass drum drives and underpins lively very-French and (I venture to say) very feminine composition.
On the CD go to track 11.  You need sub bass speaker strong down to bottom E for real thrill - as with many music genres.  By the way, Alexa just apologises and goes away.
Answer: Percussion was the last (but not least!) family to be incorporated into symphonic orchestras, since most percussion instruments and percussive elements used in classic music were developed in late 19th and early 20th centuries. There's a lot of historical reasons for this, but most are based in sound balance between instruments (and their blended sounds) and, at a later time, families. Same happened with instruments too mainstream today, as piccolo and trumpets - and still happens with others, as saxophones and guitars.
The music for large forms and operatic effects were some of the factors that drove percussion into a full family. A great anecdote of this topic is the anvil. It was first thought and used as a music instrument by Verdi and Wagner, in operas composed almost in the same year (Il Trovatore and Das Rheingold). Both composers faced similar needs (blacksmithing in scene) and had almost the same idea. Wagner grew a little megalomaniac about it and placed 18 anvils on stage, tuned in F, in a 3 octaves span. How for God's sake he got tuned anvils in 1850's I don't know, hahaha.
But some instruments were there since the beginning consorts, pre-orchestra era: timpani, drums (snare and bass are the greatest examples), lots of cymbals, gongs, thunder sheets, tambourine...
Answer: In pop music drums are used for utilitarian reasons of keeping time for everyone else to be sloppy about it.  Classically trained musicians are independent units capable of keeping their own time according to the score.  That's even more impressive in that the vast majority of pop/rap/rock is primitive common time, whereas a lot of especially later classical  contain complex time signatures and poly rhythms.
Comment: @netfliks Hi netfliks! It's good to see you getting involved! You make a good point about the complex rhythms and time signatures of C20th and C21st classical music, and many here would agree, but the tone of "**for everyone else to be sloppy about it**" won't make you many friends! There are people here who are into all sorts of music: even pop music!
Comment: "In pop music drums are used for utilitarian reasons of keeping time for everyone else to be sloppy about it." Or maybe they are a voice in the music in their own right and can be very simple like Meg White plays them or incredibly complex like
Terry Bozzio plays them.
Comment: If all members of an orchestra were keeping time on their own solely via the score, they wouldn't need a conductor, but conductors are still in common use to this day, and often considered the stars of the performance.  (If you hear a classical piece on the radio, they'll generally give the conductor's name and the name of the orchestra, possibly a soloist, but none of the other performers.)
Comment: Seconding @DarrelHoffman's point. For example I have two recordings of Finlandia. When Sir John Barbirolli is conducting it lasts 8:16, but Herbert von Karajan takes 9:18 - one minute difference. If the musicians were to keep time on their own, what would happen?
Comment: Drummers are the new conductors!
Comment: @YvesgereY Not exactly new - marching bands have been keeping time to drummers for centuries...

Why didn't classical music use drums?


E4 lifeCycleURI property for fragment plugin

Question: I am new to Eclipse 4. I am trying to refactor existing application and move some domain related UI and code to fragment plugin. In existing application I have used lifeCycleURI property of plugin to link java class to register some services at IEclipseContext. But fragment tag at plugin.xml do not recognizes 'property name="lifeCycleURI"'.
How can I register life cycle manager code for fragment plugin?
Answer: Only the org.eclipse.core.runtime.products extension supports the life cycle class, you can't define life cycles for plugins or fragments.
If you want to define OSGi services you can do that with a Component Definition. OSGi services are automatically added to the IEclipseContext.
You can also use a ContextFunction to lazily add to the context. see here
You can also add to the context using an Addon
Comment: Thanks @greg-449, that is very useful. Could you explain the `Addon` option a little more in detail?
Comment: Add Addon is something you specify in the Add-ons list in the application.e4xmi (or a fragment) and lets you run arbitrary code during startup