How do I report and interpret the output from linear mixed models with interaction terms?

Question: So, we are doing a linear mixed effects model for analyzing some results of our study. In short, we have performed two different meal tests (i.e., two groups), and measured the response in various biomarkers at baseline as well as 1, 2, 3, and 4 hours after the meal.
I had a meeting with a statistician who explained that we should use linear mixed models for this and as such, using the nlme package in R the syntax looks like this:
model <-lme(biomarker~ as.factor(group)*visit, random = ~1|ID, data=data, method="ML")
summary(model)

The output (abbreviated for readability):
Linear mixed-effects model fit by maximum likelihood
 Data: data
      AIC      BIC    logLik
  137.593 149.0651 -62.79649

Random effects:
 Formula: ~1 | ID
        (Intercept)  Residual
StdDev:    1.462879 0.6039689

Fixed effects: biomarker ~ as.factor(group) * visit
                            Value Std.Error DF   t-value p-value
(Intercept)              7.869766 0.7157143 38 10.995681  0.0000
as.factor(group)3        1.295118 1.0121729  8  1.279542  0.2366
visit                   -0.096024 0.0679003 38 -1.414191  0.1654
as.factor(group)3:visit -0.358905 0.0960255 38 -3.737606  0.0006
 Correlation:
                        (Intr) as.()3 visit
as.factor(group)3       -0.707
visit                   -0.247  0.174
as.factor(group)3:visit  0.174 -0.247 -0.707

Standardized Within-Group Residuals:
         Min           Q1          Med           Q3          Max
-3.107751422 -0.303320567  0.004573801  0.377750437  1.967646127

Number of Observations: 50
Number of Groups: 10

To summarize:

Exposure = one of two meal tests (group in the syntax)
Outcome = Biomarker
Time variable = Visit (5 in total for each participant, continuous)

My questions are:

Am I correct in interpreting this that there is an interaction between group and visit?
I am unclear as to how I should interpret the estimates here. Am I correct in saying that at time = 0, then the group difference (3 vs. 2) is 1.29? And further that this effect depends on the visit? What about the other timepoints?
Is it sufficient to report this model or should we also include a model without the interaction term that is just including group and visit?
Comment: No, you should not remove `as.factor(group)3`. It is part of an interaction.  And you shouldn't remove variables just based on significance, either.
Comment: @Carl The possible overdetermination (we can't really tell if it's overdetrmined without more information) is a separate issue, but an important one.  But if you have a large interaction, then you need both main effects.  I am not sure why one variable is using 38 df.
Comment: The  linear mixed effects model is not suitable if  the objective is what I perceived.
Comment: You need to repeat this without `as.factor(group)3` in the model. It's contribution is not significant to the model: $p=0.2366$ is not significant. You may have to eliminate `visit` as well, but first check what the model shows without `as.factor(group)3`.
Comment: @Carl can you elaborate on why would one need to refit the model without non-significant predictors? That is not what I would do.
Comment: So alot of the comments have been deleted here, which is why my comments now seem very random.

@Carl; I did not see your comment until now, I'm sorry. My questions is how to report and interpret the interaction when the simple (or main) effects are non-significant. And how to eventually report the model. In order to test the interaction, doesn't we need to add the individual covariates as well?
Comment: It seems that you are interested in checking effect of meal on  say,  Y.  and you have two types of meal- one for a  particular group and another for second group. The experiment makes measurements over time for each subject alongwith a baseline measurement i.e. prior to meal. Your questions can be answered if you give more details - number of subjects in each group. I recall that you had reported that there are 5 subjects for  each group  and 5 measurements for each subject.  To me , lme is not a solution. Probably u are interested in main effects and  ... please state problem explicitly.
Comment: @PeterFlom Perhaps. I suppose it does not matter that much that a model is over-determined if it is used for interpolation rather than to establish a physical model that also can serve as one for extrapolation. To do the latter, one has to wonder if the model used has any chance of being physical if the parameters are over-defined, or perhaps the question should be if there is not some other model without the inefficiency seen.
Comment: It would help to know what baseline and effect models are doing. However, in general, I would model this as a nonlinear pharmacokinetic or pharmacodynamic times series at 0,1,2,3 and 4 hours with a dummy variable for meal type. The regression type I would use would depend on the exact characteristics of the modelling equation and type of noise. The data transformation type might include none, semi log, linear log, square root, the regressions might include ANOVA, weighted least squares, and Tikhonov regularization adaptive for the pharmacokinetic parameter of interest.
Comment: Even if I have understood your question properly, without the data, I cannot make a recommendation of less than chapter length. However, for such models, I can state that most current methods are of poor quality, and very few of them have less than the 5% error that I would consider more desirable to commit an act of science, and at least postulate a model that is not physically absurd.
Comment: @subhashc.davar I removed my comments because you removed your and mine suddenly seemed out of context. But yes, 5 participants per group for which we have 5 measurements of the outcome variable. What is the alternative to lme except repeated measures anova?
Comment: @Carl, so you are suggesting that linear mixed models is the wrong approach? I am not a statistician, but I am familiar with some of the alternatives you present. However, I was under the impression that when you have repeated outcome measures LMM is the way to go.
Comment: This is a pilot study and part of a post-doc project (not mine).
Comment: All I am suggesting is that you appear to have a time series that is most commonly amenable to pharmacokinetic modelling of oral dosing, if I am understanding what you are saying correctly. Please confirm that you are measuring plasma concentration or effect monitoring and of what kinetic type, e.g., first order, competitive binding to an enzymatic site, effect kinetics etc. The details here are essential to any recommendation for modeling, and even with the details it is not simple. Physics, if disrespected, will yield garbage of the "not significant" type.
Comment: @Carl the intervention specifically is meals with and without some amino acids (methionine and cysteine). The outcome variables are the baseline and resulting plasma concentrations of those and 17 other amino acids (1-4h) after the test meals. We are not measuring kinetics.
Comment: @Tho The comments indicate that you are interested in finding out whether there is any significant effect of meals with two particular amino acids (additional). IF you confirm that this is the goal of your study, I shall let you know the appropriate technique for your experimental data. The experimental design with repeated measures is good for your study.
Comment: @subhashc.davar I agree with you (+1) on comment. My guess is the linear mixed effects model is being applied to data without model testing for the assumptions of a) linearity and  b) normality, that is pharmacokinetic oral dosing type and *ad* a) is a time series of non-linear type with *ad* b) some peculiar characteristics, e.g., neither it nor residuals from it have much chance of symmetry, never mind normality from an imposed and likely irrelevant linearity.
Comment: @Carl thanks for your +1. Model testing does not appear to be important here.  The  data has been generated by implementing the experimental  design i.e. test group and control group based on with and without certain amino acids. Perhaps linearity and normality issues do not arise here. The data analysis and estimation of descriptive or survey data may have interest in  the  vitues of the two assumptions.
Comment: @subhashc.davar Using a time series as if time offered stationarity for relative amino acid concentrations, e.g., without cross-over, is probably not reasonable. Assumptions need testing, and that takes more thinking than applying a canned program.
Comment: @Carl I may be misinterpreting the idea of stationarity with regard to cocentrations of Amino acids, the data is one ..two .. four hours after meal. The data  further is of pooled nature: time series - cross section. As I interpret the effect of cross- over ( is it something like non- linear moment ?)  is neutralised when we have a number of subjects and series of measurements.  Hopefully, you will condone my poor understanding of medical science. I am a Commerce and management graduate.
Comment: @subhashc.davar Two kinds of people; those who know they are stupid, and those who do not. The former are scientists, and the latter, Democrats ($\leftarrow$ A joke, so laugh). Adding 2 amino acids to a meal might cause a cascade of  temporal disequilibrium; altered time constants for the amino acid pool. If one does not model the amino acids as changing non-linearly and differently for the two meals, the experimental effects may be missed. Conversely, if one has a model with both indispensable and not significant effects, one can ask why one feels stupid, or not.
Comment: @Carl The objective of experiment is to capture the overall effect of two amino-acids  and we have a test group and a control group.
Comment: @subhashc.davar Yes, and there appear to be 5 time-samples as well. All I am suggesting is that the time-samples may be very useful, but only if they are modeled tolerably well. Perhaps take a look at [this](http://link.springer.com/article/10.1186/s40658-016-0166-z) to get some ideas. In that modelling paper the errors are circa 1%, and please note that the data have non-zero modes, just like postprandial data. Now imagine that the OP's postprandial data may have some amino acids with modes occurring at different times than for other amino acids, which if unmodelled may be problematic.
Comment: Time samples are not a problem. Different approaches to statistical analysis are  available and choice of such methods depends on nature of data and data- generation methodology.  Basic modelling requires technical know- how in the field of study. Here, the concern is which statistical model suits for  valid results given a specific objective. thanks for raising important issues.
Comment: Hello guys, sorry for the late response. So where to begin; @Carl, yes linearity is a problem here, especially for the two amino acids (and their related metabolites) that we manipulated. We are however looking at how the meals affected all the other amino acids as well as lipid profile, vitamin profile, glucose tolerance etc for which the curves are somewhat linear. From your discussion, I guess a formal test of the assumptions of lme must be carried out. I will definitely take your points to the statistician involved.
Comment: @subhashc.davar, you percieve correctly. Two groups in which 1) gets a meal without two amino acids and 2) gets a meal with two amino acids. Outcome variables are the amino acids in question (of course) but also several other plasma markers of lipid and amino acid metabolism. The experiment is fairly simple. Give either of the two meals, and take blood samples up to four hours after the meals.
Answer:
1) Am I correct in interpreting this that there is an interaction
  between group and visit?

Yes.

2) I am unclear as to how I should interpret the estimates here. Am I
  correct in saying that at time = 0, then the group difference (3 vs.
  2) is 1.29? And further that this effect depends on the visit? What
  about the other timepoints?

Yes, that is the group difference at time = 0 and yes, it depends on time.  You can calculate the estimate at any combination of the variables by using the formula:
$7.87 + 1.30*(I(\text{group} = 3)) - 0.10*\text{visit} - 0.36*(I(\text{group} = 3))*\text{visit}$

3) Is it sufficient to report this model or should we also include a
  model without the interaction term that is just including group and
  visit?

That depends on what you are interested in, but when there is an interaction, the model with only main effects can be misleading.
Comment: After some reading, I think I understand. This has been the most relevant answer so far, and I'll mark it as such. Thank you very much, Peter.
Comment: Thank you for your thorough response. Regarding your last point, I regularly see studies reporting the p-values and/or coefficients for the entire model with the interaction term. However, does a model like this really test for the differences between groups and does it make sense to report those estimates/p-values in a model with an interaction term? Finally, a means around this would maybe be to do post-hoc tests for the outcomes where the interaction is significant.
Comment: There are differences between groups that differ over time.


Carregar lista a partir de txt em c#

Question: Tenho o seguinte problema, eu pego os dados de um txt que eu preciso devolver em forma de List<List<string>>, porém eu só consigo pegar do txt um  string [] linha, então eu estava adicionando string por string no meu list, isso funciona, porém a cada vez que é adicionado o novo list, os mesmos valores são adicionados mais uma vez no mesmo list, segue o código.
   public List<List<string>> carregaHistoria( string nomeHistoria ){

      List<List<string>> historia = new List<List<string>> () {} ;

      List<string> listaIntermediaria = new List<string>(){};

      FileInfo theSourceFile =
            new FileInfo ( Application.persistentDataPath + "/" + nomeHistoria + ".txt");

      StreamReader reader = theSourceFile.OpenText();

      string text;

      string [] linha;

      do
      {
         linha = reader.ReadLine().Split('|');

         text = reader.ReadLine();

         for(int j = 0; j < linha.Length ; j++){

            listaIntermediaria.Add(linha[j]) ;
         }

         historia.Add( listaIntermediaria );

         //listaIntermediaria.Clear();

      } while (text != null);

      return historia;
   }

Exemplo do que acontece para ficar mais claro:
se no meu txt eu tiver:
"alguma coisa|outra coisa"
"mais uma coisa|mais outra coisa"
"que coisa|mais coisa"

no meu lista final eu terei todas as linhas na primeira posição do list, as duas primeiras linhas na segunda posição, e somente a primeira linha na terceira posição do list, esse foi o resultado que obtive. E tentei adicionar o comando listaIntermediaria.Clear();, mas ai o list fica completamente vazio o tempo todo.
Comment: a primeira linha tem dois texto, a segunda linha tem dois textos é isso ??? que você quer como resultado, 3 linhas e cada linha com dois textos?
Answer: Um exemplo minimo seria:
List<List<string>> lista = new List<List<string>>();
lista.Add("1|2|3".Split("|").ToList());

ou seja, no texto encontrada em cada linha eu faria o split e no por fim o método ToList() para adicionar na List<List<string>>.
No seu código utiliza um algo assim:
public List<List<string>> carregaHistoria( string nomeHistoria )
{
    List<List<string>> historia = new List<List<string>>();

    FileInfo theSourceFile =
           new FileInfo ( Application.persistentDataPath + "/" + nomeHistoria + ".txt");

    using (StreamReader reader = theSourceFile.OpenText())
    {

        string line;

        while ((line = reader.ReadLine()) != null)
        {
            historia.Add(line.Split('|').ToList());
        }

    }

    return historia;

}

Comment: eu não entendi exatamente o que acontece, pois quando tentei ajeitar a minha função adicionando o .ToList(), no meu dava um erro falando que .ToList() não era valido, mas então copiei e colei o seu código e funcionou Obrigado!

Carregar lista a partir de txt em c#


Probability of 1 trial getting 8 or more heads/tails in 10 trials of 10 flips

Question: I was recently reading a book on probability "Drunkard's Walk: How Randomness Rules Our Lives" and there is a probability problem below that I cannot seem to replicate:
"if each of 10 Hollywood executives tosses 10 coins, although each has an equal chance of being the winner or the loser, in the end there will be winners and losers. In this example, the chances are 2 out of 3 that at least 1 of the executives will score 8 or more heads or tails."
I tried replicating the 2/3 (~67%) but I keep running into some sort of error (unless the book is wrong).
Essentially, I know the probability of 8 or more heads or tails in 10 flips is 56/1024 (this is 10 choose 8 + 10 choose 9 + 10 choose 10 for coin flips).  However, when I try to replicate the "the chances are 2/3 that at least 1 executive will score 8 or more heads" I do not get 67% but rather closer to 43%.
Here are my binomial inputs:
p (success)=56/1024, n (trials)=10, k (successes)=0.
If I run the numbers, 10 choose 0 = 1, p^k = 1, and (1-p)^n-k = 0.57.
This means that the chance that NO executives get 8 or more heads/tails is (1 * 1 * 0.57)=57%, which means that the probability of at l least 1 executive getting it should be 1-this, which is 1-0.57=0.43 (or 43%).
Can someone tell me where I went wrong with this problem??  Thanks!
Comment: The $\dfrac{56}{1024}$ is only counting heads. Multiply that by 2 and you'll get the correct probability.
Comment: Thank you!  That makes sense.
Answer: As Kenny Lau noted in a comment, you're missing a factor $2$ since both heads and tails are allowed. The desired probability is therefore
$$
1-\left(1-\frac{112}{1024}\right)^{10}=\frac{790888173149955727}{1152921504606846976}\approx69\%\;.
$$


Async programming against non-async services

Question: This past year we've been working on a new web app that calls into our company's existing service layer.
We made the decision to wrap up all of our service oriented calls into our own service layer (which I'll refer to as our web-service layer) so that the details of which services we use (we'll move to a new API at some point in the future) are hidden from the web layer itself.
We also decided that most of our web-service layer methods would return Task<T>.
As it stands, the underlying services that we call are not async and so there are some concerns that our web-service layer will max out the available threads and cause problems when we have a large volume of users.
I'm looking for information, one way or the other, to further understand how our decision to return Task<T> will impact our site and whether or not we need to consider changing our return types.
We'll be moving to VS2012 at some point but right now we're using VS2010 and are not using async and await.
Answer:
As it stands, the underlying services that we call are not async and
  so there are some concerns that our web-service layer will max out the
  available threads and cause problems when we have a large volume of
  users.

Yes that's something you should be concerned with. I would recommend you doing this only if you have real asynchronous methods. But simply wrapping blocking synchronous methods into an async API will be worse than calling the synchronous methods directly from the consuming code. In an ASP.NET application you will get benefit from asynchronous calls only if the underlying API is relying on I/O Completion Ports. Otherwise it's just a waste of resource.
The only useful scenario in which you could do that is if your methods could be called in parallel instead of sequentially. This is possible only is the different methods are not connected between them. In this case you could indeed wrap your sync methods in async tasks.
Comment: We do call all of our web-service layer methods in parallel (using Task.WaitAll).
Comment: Alright, in this case there could be a justification to do that, as I mentioned in my answer.


AngularJS directive in directive is not setting up scope value

Question: I have a controller, with $scope.colorHex value
For example I have the directive colorpickerTooltip and in the template I call another directive: <colorpicker ng-model="colorHex"></colorpicker>
then in the second directive (colorpicker) I set up controller's value:
scope.colorHex = '#cecece';
and then in the second directive I call method scope.doIt(), but something is going wrong:
my $scope value is not updated! But why, maybe because of my 2-level directive?
How to set up the controller variable value?
Comment: Could you put your code in plunker?
Comment: possible duplicate of [angularjs Access parent scope from child controller](http://stackoverflow.com/questions/21453697/angularjs-access-parent-scope-from-child-controller)
Answer: Yes this is the problem of two level directive scope. Please read https://github.com/angular/angular.js/wiki/Understanding-Scopes
Define the colorHex in your controller as an object like:
$scope.dataStore = {};
$scope.dataStore.colorHex = '#cecece';

Then modify at first directive as:
<colorpicker ng-model="dataStore.colorHex"></colorpicker>

And then later use it in your second directive to update in doIt method:
$scope.doIt = function() {
    $scope.dataStore.colorHex = '#fff';
}

Answer: Second directive copies the value from the first one and creates a new object in the second scope.
You can prevent it via using a objective structure such as
$scope.color= {hex=undefined};

and change it in the inside scope
$scopescope.color.hex = '#cecece';

it will prevent this stuation


What does "a key is uniform" mean in cryptography?

Question: In the lecture on Coursera platform, the inequality below was shown: there exists an algorithm $A$ such that
$$\underset{{k \overset{R}{\longleftarrow} \mathscr{K}}}{\operatorname{Pr}}\left[\left.A(G(k))\right|_{1, \ldots, i}=\left.G(k)\right|_{i+1}\right] \geqslant \frac{1}{2}+\varepsilon$$
Here $\operatorname{G}$ is the pseudorandom generator (PRG) function that expands a seed.
My question: In the lecture, this is stated as "$k$ is uniform in the space of keys $\mathscr K$". I do not understand what uniform means in this context.
A uniform random variable means $P(X=t) = 1/|S|$, where $|S|$ is the set of all possible values (assuming $|S|$ is finite). How to interpretate the meaning of this term "uniform" in the inequality above?
Comment: Is the space $S$ of keys not finite?
Comment: $|S|$ is finite
Comment: Just means uniform random variable .
Answer: Here  $k$ is indeed uniformly sampled from a finite keyspace $\mathscr{H}$ (a finite set), it's our seed. This space could be something like "all the 256 bit long bytestrings" (so $2^{256}$ possibilities.). So your formula is correct, for a finite set the distribution is simply the uniform distribution over this set, that is what $k \leftarrow \mathscr{H}$ means
In the context of your equation, it means that for a truly uniformly randomly chosen seed $k$, there exists an algorithm $A$ that if given all the previous outputs of the $k$-seeded pseudorandom generator $G$ is able to predict the next one with a probability $1/2 + \epsilon$.
If your PRG is cryptographically secure, then there shouldn't be an algorithm able to do that in polynomial time.
If you want to characterize pseudorandom number generators, you may want to look at the notion of computational indistinguishability
Answer: The meaning is exactly as you guessed. The key is uniformly distributed in the space $\cal K$ and $k$ shown under $Pr$ in the equation is random sample from this distribution.


Mixed-modeling when no observation contributes both X and Y

Question: I'm working on a project investigating the relationship between (let's say) a face's perceived masculinity and its perceived competence. There was a large number of face stimuli (80). Two completely separate groups of subjects rated the faces on each dimension: a given subject rated a random subset of the 80 faces on EITHER masculinity OR competence, never both. In other words, every subject rated multiple faces on a single dimension, and every face was rated by multiple subjects on both dimensions. (This was done to avoid interference effects and demand bias.) The specific face stimulus is considered a nuisance parameter here; face-specific effects are not really of interest.
A very simple modeling approach would be to treat face as the unit of analysis and characterize each face by its mean masculinity and its mean competence. This would result in a dataset with 1 row per face that would be easily amenable to linear regression, etc.
Obviously, this approach loses a lot of information, particularly failing to account for a subject random effect (such that, e.g., some subjects might generally consider faces more competent than other subjects). The problem invites a mixed-model with random intercepts or slopes by subject and face plus a fixed effect of masculinity, such as (in R shorthand):
competence ~ masculinity + (1|id) + (1|face)
However, I am not sure how this would work in light of the experimental design. I am basically having trouble envisioning how the fixed effect of masculinity will be estimable given that no observation contributes both a masculinity AND a competence rating.
Is this problem conducive to mixed-modeling? If so, how?
UPDATE
I tried fitting the mixed model specified as above using lmer to see what would happen. Not surprisingly, the model throws an error about incorrect grouping structure. This error goes away if I randomly simulate some of the missing-by-design such that there are now observations having both X and Y.
So, I am revising my question:
Is there a modeling approach for this situation that would retain more information than just modeling the face-specific means?
Answer: This is a rather interesting design and I hope that it is not preventing you from what you really want to measure.
Because subjects (id) do not have a measure of both masculinity and competence, you cannot, as you mention, associate them at the subject level. That is, you cannot test whether people who perceive a face as masculine also perceive it as more or less competent. Instead, you have to examine the relationship of these variables at the level of the face because each measure was taken for the different faces.
If you want to use mixed models, it seems that you should specify the model with a random intercept for id partially crossed with face. I am not so familiar with lmer, but it looks like you are specifying this correctly. This documentation would help with specification. Under this specification, you are coming to conclusions more along the lines of "faces that are perceived to be [more or less] masculine tend also to be perceived as [more or less] competent."
Comment: So, I think you need to simply drop the "subject" variable from the random effects. This makes sense: how can the relationship between X and Y be randomly different for subjects if the 2 variables are not measured on the same subject? Rather, I think you have a highly unbalanced design, with "face" being your only random effect. You should then also be able to add a random slope to see if certain faces project a lower or higher slope between masculinity and competence than others. Again, you are operating on the "face" level and not "subject."
Comment: (+1) "faces that are perceived to be [more or less] masculine tend also to be perceived as [more or less] competent." -- Right, that's very much the intention. Thanks for the doc on multiple random effects, and I agree about the random slopes. I'm still wondering about whether mixed-modeling in general is a good idea, though. I know the model with churn through the ML and spit out a fixed effect of competence, but I just can't wrap my head conceptually around how a reasonable fixed effect would be estimated in this case.
Comment: (On second thought, I think certain random slopes could make sense. For example, a random slope of masculinity by subject would model the possibility that certain subjects respond more strongly to masculinity than others.)
Comment: I think what makes it so difficult to wrap one's mind around is that often fixed effects are estimated at the subject level where each person has a measurement of x and y. However, your "subject level" variable is face, while your actual participants are acting like detectors... it would be like measuring different chemicals by many different versions of the same machine in you lab, each with its own bias. So, I think the model makes sense, it is just counter intuitive. I really find this design fascinating!
Comment: And you are right about the random slopes - I think that could be a reasonable thing to test in the models. When I wrote the answer, I was thinking you would include a random slope on the "id" variable, which would not make sense.
Comment: Given this, I've edited out the comment on random slopes.
Comment: Thanks Moose. But per my update, the model does not actually fit (at least using R's lmer), so I suspect it actually may not be estimable?


Clearing old data from sys.stdout in Python

Question: There's something I don't get when writing to sys.stdout in Python.What I want is to write some strings into stdout without preprending the stuff which already has been written before that.
So doing this:
 while True:

    sys.stdout.write("k")
    sys.stdout.flush()

 sys.stdout.write("d")

After some "k" data has been written into stdout in a loop I need to write some new data afterwards,which is "d" for the sake of example.
I am  getting : "k d" in the output."K" from the loop writes is still in stdout.
What I want to get is just "d" .
Why?
How can I clear the stdout before writing new data into it?
Btw,using print() instead still accumulates the old data into final output.
Using python 2.7 on Linux
Comment: Well of course the `k` is printed. You printed it, and then on top of that you flushed `stdout` to force it to be printed immediately! If you don't want something printed, don't... print... it?
Comment: I am not sure I understand the question. What exactly do you mean by "clearing" stdout? What should happen to the stuff already written to the console?
Comment: See my update.I just want to see in the terminal the last written string
Comment: Writing a carriage return (ASCII 13) between the `k` and the `d` might work, depending on your use case. It would help us to help you if you explained where you're going with all this. To me, the question has a strong feel of the XY Problem (http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).
Comment: @kindall no, I do have to print "k" but one line before "d".I want to print "d" in a completely new line.
Comment: @MichaelIV: With respect, this is the most confusingly worded question I have seen for some time. :-(
Answer: Terminals don't work that way.  flush just flushes the buffer (i.e. characters that may not have been printed to screen yet), it does not clear the screen.
If you want to erase one character, you need to print a literal backspace control character, and then print something over your previous output (like a space):
sys.stdout.write("\b ")

However.  Your asking this belies a deep misunderstanding of how terminals work.  Think of it like a text processor - there is text on the screen, and a cursor (which is invisible).  You need to tell the cursor what to do to manipulate the text on the screen.  Since the cursor is always in overwrite mode, a trick that is often useful is to go back to the start of the line:
 sys.stdout.write("\r")

and overwrite your data on that line.  Note that if your new data is of lesser length than your previous data, this will leave some amount of previous data on the screen.
There are other tricks you can use if neither of these fits your bill, like outputting terminal control sequences to stdout.
(also, unless you have a specific need for using sys.stdout, just use print.)
Comment: Good!sys,stdout.write("\r") helped as my last print is longer.Thanks.
Answer:
I do have to print "k" but one line before "d".I want to print "d" in a completely new line.

Simply write a newline between the two:
sys.stdout.write("\n")

Or just use print, which adds an implicit newline at the end:
print "k"
print "d"

Comment: If using print "d"  it adds "k" to the beginning.Just checked that.Also,if using sys.stdout.write("\n") this space  still prepends the "k" from previous print so that I am getting "k" on the new line (after original "K" has been printed) and then "d"


Unity of work used with more database

Question: I am learning some patterns, Unity of work / repository... There are some examples on web, but no one connects to more than one database.
In my applications almost always I have the need to get some object from a database (for example users) and some other object from another, how can I use the patterns ? (Since I am a novice on this subject an explicit example is a must)
Thank you!
Comment: There is something that can I add to increase the chances of a response? The question is not clear?
Answer: As a general reference I advise you and anyone interested to visit http://martinfowler.com/eaaCatalog/index.html
which has a collection of UML and explanation over the most common Design Pattern for enterprises software
In your specific case Unity of work is particularly suited to work along with Data Mapper and Identity Map. I guess to understand 100% unity of work one must master also the other 2 pattern.
To answer your question I think you can create a unity of work and save it in a registry, so it is available all over the application. The unity must be a singleton since you need to ensure a central gateway to communicate with the database. Inside your unity of work you will have an identity map which is a collection of valued Objects in memory representing your model which is responsible to maintain the object states during all the application's operations. The unity will be used by your service layer to perform CRUD operations over the model and commit these changes.
To work with more databases I guess you need to leverage some sort of namespaced access to the object stored in the Identity map. You have the choice where to namespace: unity of work or identity map. The decision is really up to your application and use cases. You might need to connect to different DBs for splitting responsibilities between read and write or trying to integrate heterogeneous data sources.
An alternative would be to inject the DB object into the unity of work methods, in this case the application has 100% control over which database is used.
The repository pattern as far as I understand helps you to abstract to the storage of you model and it is particularly useful when you are working with heterogeneous data sources of you must provide such a flexibility to your application. Therefore I guess it is quite different from unity of work and Data Mapper layer.

Unity of work used with more database


Send a message when a comment is left

Question: I want to send a message to users that have commented on a node each time a new comment is left.
I think I am half way there.
I have created a component of the content type, added a loop that looks at the "node:comments" and set the email up using referenced mail list
I have also created a rule that triggers the component on the event of a new comment.
The problem I have is that I want to exclude the node author as they get notified anyway when a new comment is left in a separate rule.
Also, that if you have left more than 1 comment on the node you get more than 1 email so I need to filter it down.
I am fairly new so as much detail as possible would be appricatied.
Many thanks :-)
David
Answer: How about the modules -
Comment Notify

Comment Notify is a lightweight tool to send notification e-mails to visitors about new, published comments on pages where they have commented. Comment Notify works for both registered and anonymous users.

or
Notify

The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily newsletters sent by some websites.

and see Email notification for new comments
Answer: The better method would be to use the Message stack of modules together with Message Digest, but that requires coding and as you are new it will be a daunting task (however, it will do exactly as your use case demands).
In your instance I will look at Conditional Rules through which you can easily combine complex logic into a single rule. Then also check out this post for good advice: How to build an Email Diggest using Rules
Comment: I have downloaded the additional "conditional rules module" and added conditions to remove the user leaving the comment from the mailing list and the author of the node. The only thing I am struggling with is filtering the list to unique entries i.e. only 1 email per user if they had left more than one comment. Can you point me in the right direction?
Comment: How about changing your approach slightly. Create a non-global node flag for the specific content type. When a user comments, fire of a rule that sets the flag for that user on the node he commented on, then get all the flaggings of that flag on that node and for each flagee send an email. And of course you are never going to display the flag, its just there in the background to help you keep track of who left comments. And even if a single person leaves 1000 comments he/she will only still have one flag on that node.
Answer: Add to @Geoff modules there is a similar module called Thank You Commenter

As the name says, a small and simple module which send a mail to a person who comments on nodes. You can choose from logged in users only or for anonymous users as well.
We also plan to add settings per content type based.

Send a message when a comment is left


Shortcode para Wordpress

Question: Estou usando a IP API para geolocalização em um plugin do wordpress, o plugin está pronto e funciona normalmente! Eu quero acrescentar o seguinte:
Em um dos campos do plugin, o usuário pode inserir um texto e no final desse texto, só que esse campo não aceita shortcode, é um tipo de campo de texto comum, sem editor nem nada, vou anexar a imagem. O shortcode já está pronto, so preciso que o campo aceite o shortcode, por enquanto ele só traz o shortcode como texto.
Código de Saída
$loop_link_rows .= '
meta_id . '">meta_attachment.'" alt="'.esc_attr( stripcslashes($row->meta_title)).'">meta_id . '">'.$row->meta_content.'
';

Answer: Para o shortcode funcionar você precisa chamar um filtro, ou ativá-lo diretamente.
O jeito mais simples é chamar o filtro the_content, que aplica todos os filtros definidos para o conteúdo padrão, inclusive ativando os shortcodes. Serve melhor se você tem texto junto com o shortcode.
// Supondo que sua meta-key seja "chave"
$meta_value = get_post_meta( $post->ID, 'chave', true );
echo apply_filters( 'the_content', $meta_value );

A outra forma é chamar do_shortcode() diretamente.
// Supondo que sua meta-key seja "chave"
$meta_value = get_post_meta( $post->ID, 'chave', true );
echo do_shortcode( $meta_value );

Aplicando no código:
$loop_link_rows .= '

    meta_id . '">
        meta_attachment.'" alt="'.esc_attr( stripcslashes($row->meta_title)).'">

    meta_id . '">'
        .apply_filters( 'the_content', $row->meta_content ).
    '

';

Comment: Com do_shortcode($row->meta_content) não da esse erro nenhum! Vlw pela ajuda!
Comment: Tentei fazer aqui, mas não funcionou, só apliquei os filtros na minha função.. Pelo menos eu entendi que era isso! Vou postar uma Foto do que fiz.
Comment: Você deve aplicar os filtros onde você precisa que o shortcode seja expandido. Normalmente isso é no template onde ele vai ser usado, na hora de imprimir na tela mesmo. Lembrando que shortcodes não se expandem dentro de `input` ou `textarea`
Comment: Eu preciso que o campo $row->meta_content aceite shortcodes, então eu fiz isso. http://imgur.com/a/0Qu7f

Mas, é um campo de textarea, se esse for o problema, qual campo me indica?
Comment: Então, `apply_filters()` retorna o conteúdo com o shortcode expandido mas você não está usando esse retorno. Vcê precisa colocar isso onde tá a segunda menção a `$row->meta_content` ali. Copia esse trecho ali na pergunta e eu atualizo com o exemplo.
Comment: Atualizei a pergunta
Comment: Atualizado com o código.
Comment: Acho que estamos quase lá hein, só apareceu um erro no front agora
http://imgur.com/a/bxlq4
Comment: Esse erro não é relacionado, é o xDebug que tá reclamando do numero de nesting levels. A solução é desativar o xDebug ou aumentar o limite, veja aqui http://stackoverflow.com/questions/8656089/solution-for-fatal-error-maximum-function-nesting-level-of-100-reached-abor
Comment: Show, vou procurar como resolver esse erro!

Shortcode para Wordpress


Why does this complex equation admit infinite solutions in C?

Question: I derived a problem to the equation $$1=zz*$$ where $z*$ is the complex conjugate of $z$, and apparently it admits an infinite amount of solutions in $\mathbb C$ but I do not understand why so?
I know that the number of solutions in the complex space is always equal to the highest degree of the $p(z)$ polynomial i.e for $$z^2= 4$$ you would have 2 solutions (in this case the complex solution and its conjugate)
But how could I proceed here to find the number of solutions in $\mathbb C$?
Comment: $z^2=4$ has two real solutions which are their own conjugates.
Answer: $$zz^{*}$$
Is not a polynomial equation, so it does not have only $2$ or finite solutions. Instead, set $z=a+bi$.
Now note $$zz^{*}=a^2+b^2=1$$
Thus for any $\theta \in \mathbb{R}$ if $z=\cos \theta +i \sin \theta$ then $$zz^{*}=1$$
Comment: Indeed, this could serve as a proof of the fact that $z^*$ is not a polynomial function in $z$. (You could also prove it by noticing that it's not complex differentiable, I guess.)
Answer: Recall that $zz^* = |z|^2$, that is, the product of a complex number with its conjugate is equal to the square of the norm. So the solutions to your equation are exactly the complex numbers of norm 1. This would mean that all complex numbers on the unit circle are solutions, so we have infinitely many solutions.


cypher output in JSON format

Question: Input Data
MATCH (n) DETACH DELETE n;
CREATE (p:Provider {id:1, specialty:"Cardiology",        pcp:0});
CREATE (p:Provider {id:2, specialty:"Internal Medicine", pcp:1});
CREATE (p:Provider {id:3, specialty:"Family Practice",   pcp:1});
CREATE (p:Provider {id:4, specialty:"Radiology",         pcp:0});

MATCH (p1:Provider {id:1}), (p2:Provider {id:2}) CREATE
        (p1)-[:SHARED {mbrid:1}]->(p2),
        (p1)-[:SHARED {mbrid:2}]->(p2),
        (p1)-[:SHARED {mbrid:2}]->(p2),
        (p1)-[:SHARED {mbrid:3}]->(p2);
MATCH (p1:Provider {id:2}), (p2:Provider {id:3}) CREATE
        (p1)-[:SHARED {mbrid:4}]->(p2),
        (p1)-[:SHARED {mbrid:5}]->(p2);
MATCH (p1:Provider {id:1}), (p2:Provider {id:3}) CREATE
        (p1)-[:SHARED {mbrid:6}]->(p2);
MATCH (p1:Provider {id:1}), (p2:Provider {id:4}) CREATE
        (p1)-[:SHARED {mbrid:9}]->(p2),
        (p1)-[:SHARED {mbrid:10}]->(p2),
        (p1)-[:SHARED {mbrid:11}]->(p2),
        (p1)-[:SHARED {mbrid:12}]->(p2),
        (p1)-[:SHARED {mbrid:12}]->(p2);

CREATE INDEX ON :Provider(id);

Query
MATCH (p1:Provider)-[s:SHARED]-(p2:Provider)
WHERE  p1.id<p2.id and (p1.pcp=0 or (p1.pcp=1 and p2.pcp=0))
WITH p1, p2, count(distinct s.mbrid) as cnt
WHERE cnt>1
RETURN p1, p2, cnt;

Output
+------------------------------------------------------------------------------------------------------+
| p1                                         | p2                                                | cnt |
+------------------------------------------------------------------------------------------------------+
| Node[0]{id:1,specialty:"Cardiology",pcp:0} | Node[1]{pcp:1,id:2,specialty:"Internal Medicine"} | 3   |
| Node[0]{id:1,specialty:"Cardiology",pcp:0} | Node[3]{id:4,specialty:"Radiology",pcp:0}         | 4   |
+------------------------------------------------------------------------------------------------------+

I need the output to be in the following format.  Observe that node with id 3 is not listed below since it is not in the output.  Also, the output nodes are indexed 0,1,2 and used in the links
{
    "nodes" : [
        {
            "specialty" : "Cardiology",
            "pcp" : 0
        },
        {
            "specialty" : "Internal Medicine",
            "pcp" : 1
        },
        {
            "specialty" : "Radiology",
            "pcp" : 0
        }
    ],
    "links" : [
        {
            "source" : 0,
            "target" : 1,
            "value" : 3
        },
        {
            "source" : 0,
            "target" : 2,
            "value" : 4
        }
    ]
}

I would appreciate any inputs/pointers on how to create this.
Answer: Refine your query to output only the nodes you require, then in the Neo browser click the 'Export to File' button (next to the query text you have just entered). Then select Export JSON

cypher output in JSON format


Commutate a Quaternion multiplication

Question: I have a fixed Quaternion t that is defined as Quaternion([0.5, -0.5, -0.5, 0.5]);. The order here is w,i,j,k.
In my program I have an function that I would like to modify. The function takes q as an input and calculates t*q.
I would like to calculate a new fixed tprime such that q*tprime gives me the same result as t*q.
I've read about the non commutative properties of Quaternions. But I haven't been able to find a solution to the problem. Is there a general solution? Or is this depend some properties of t ? Thanks.
Comment: In other words, the set of operators "multiply by a quaternion on the left" and "multiply by a quaternion on the right" are different sets.
Comment: Alright this works for me! If you change your comment to an answer I can accept it.
Comment: @JyrkiLahtonen - I think he's talking to you. :-)
Comment: @JonathanZsupportsMonicaC Ok. :-)
Answer: In the ring of quaternions every non-zero element has an inverse. So if $q\neq0$ the only solution $t'$ of the quaternion equation
$$qt'=tq\qquad(*)$$
is (multiply $(*)$ by $q^{-1}$ from the left hand side and apply associativity)
$$
t'=q^{-1}tq.\qquad(**)
$$
Obviously this $t'$ also is a solution — we get $(*)$ as a consequence of $(**)$ by multiplying $(**)$ from the left hand side by $q$.

A consequence of this is that $t'$ depends on $q$. This cannot be helped. When you think how composition of rotations corresponds to the product of quaternions, this should not be a surprise. However, the quaternions $t$ and $t'$ have the same real part (check if you don't see it right away), meaning that their resepective angles of rotation are equal, only the axes are different.

Commutate a Quaternion multiplication


How to insert/find gaps in a table of sqlite

Question: My table in sqlite has column 'name' which takes input like prefix+integervalue. for example p1, p2. and if there are 5 rows p1, p2, p5, p7, p10. I know the input prefix as 'p' and my next insert value must be p3 after that p4, after that p6,p8,.. like that. please help me for a query to find this gaps or any API support, I am using content_provider in android programming. Please help me my client needs this..
Comment: it's easier for people to help you if they have some relevant **piece of code** to work on - please show us what you have tried so far
Answer: Why don't you query whole your table? So you get back the values p1,p2,p5,p7 and p10. Put them as String in an arraylist and iterate over them. Look which values you don't have.
Another possibility is creating a list programmaticaly with p0 to pXXXX. Iterate over them and look then in your db which names you don't have. Create the new records, add them in a list and push them to the db.
Or you just get the max and min value and fill everything up between them and push it to the db(create or replace).
Hope that helps in finding your algorithm.
Answer: You have to extract the number from the name, and use that to search for the next number:
<code>SELECT 'p' || (substr(Name, length('p') + 1) + 1)
FROM MyTable
WHERE NOT EXISTS (SELECT 1
                  FROM MyTable AS T2
                  WHERE T2.Name = 'p' || (substr(MyTable.Name, length('p') + 1) + 1))
ORDER BY substr(Name, length('p') + 1) + 1
LIMIT 1;
</code>


Compactness and positive invariance of set under flow of ODEs

Question: Given a system of ODEs, $$x'=y$$ $$y'=x-x^3-y$$ $$x(0)=x_0$$ $$y(0)=y_0,$$ also given a set $S=\{(x,y):V(x,y)\le k, x>0\}$, $V(x,y)=-\frac{x^2}{2}+\frac{x^4}{4}+\frac{y^2}{2}$, where $-\frac{1}{4}<k<0$, it is needed to be shown that $S$ is compact and positively invariant, and that if $(x_0, y_0)\in S$ then $\lim\limits_{t\to\infty} (x(t), y(t))=(1,0).$
My attempt:
(i) Compactness: Consider $-\frac{1}{4}\le \frac{(x^2-1)^2+2y^2-1}{4}\le k$. Also, $S$ is closed. Therefore, $S$ is a compact set.
(ii) Positive invariance: I think we should use LaSalle's Invariance Principle in this case. Let $E:=\{(x,y)\in S: \dot{V}=0\}=\{(x,0)\}$. Also, consider $V(x, 0) = -\frac{x^2}{2}+\frac{x^4}{4}=-\frac{1}{4} < k$, which implies that $x=1$, $V^{-1}(-\frac{1}{4})=\{(x,0)\in S: V(x,y)=-\frac{1}{4}\}$. Hence, $\omega((x_0, y_0))\subseteq E\cup V^{-1}(-\frac{1}{4})=\{(1,0)\}$.
(iii) It follows from (ii) that $\forall \vec{x_0} \in \Omega$, $\psi_t(\vec{x_0})\to (1,0)$ as $t\to\infty$.
Please let me know if this is correct. I'm concerned about the choice of $-\frac{1}{4}$ - it seems rather arbitrary to me. Also, for the positive invariance, I'm not completely sure that I provided enough details to show it.
Comment: LaSalle's Invariance Principle: unnecessary, as should be clear if only you read what I wrote. Why try to come back to big-name-theorems instead of trying to understand the mathematical situation...
Comment: Well, the set $S$ is invariant (for some suitable $k$), hence one stays in $S$ forever, and there is a unique fixed point in $S$, namely $(x^*,y^*)=(1,0)$, and one knows that some sort of distance to $(x^*,y^*)$ measured by $U(x,y)=(x^2-1)^2+2y^2$ (yes, $U=4V+1$) is nonincreasing along the solutions, now what phenomena could happen? (Note: I do not like so much that you modify your comments after mine answering them are posted since this makes them look partly irrelevant, let me suggest to stop doing that. Likewise for the question itself.)
Comment: ?? No, the fact that $t\mapsto V(x(t),y(t))$ is nonincreasing does not imply that $V(x(t),y(t))\to\min V$ (if this is what you are trying to use). A priori, $V(x(t),y(t))$  could converge to any limit $\ell\geqslant\min V=-\frac14$ (and such that $\ell\leqslant V(x_0,y_0)$).
Comment: Well... Your attempt for (i) is offtopic since a proof that some set $S$ is compact should not rely on the differential system which motivated the definition of the set $S$. Your attempt for (ii) is a mystery as well since positive invariance of $S$ means that if $(x_0,y_0)$ is in $S$ then the whole trajectory stays in $S$. To show this, in 99% of the cases, one simply shows that, for every solution $(x(\ ),y(\ ))$, $t\mapsto V(x(t),y(t))$ is nonincreasing. Re your suggestion for (iii), I even fail to understand what you mean there... So, it seems you should be worried, not about details ...
Comment: ... of otherwise almost correct proofs, but about getting a basic understanding of the notions involved, how they are related, and what is being asked of you.
Comment: ((Additional note: 3 questions on exactly the same differential system, with basically the same underlying misconceptions, maybe these are enough?))
Comment: @Did: the course notes written for the course are laying out the  material very poorly. It's just very disorganized, so I basically have to decipher the concepts, which is almost like trying to translate from Chinese to English, without knowing Chinese.
Comment: The web is full of very good notes, available either as old fashioned downloadable textbook chapters, or as fancier web pages... If what you say of the notes you are using is true, drop them, they are only making you lose your time (and ours, if I may add). The present question is a good exhibit, since one basically has to *deconstruct* what you suggest before being able to turn to what the words mean and what a solution could be.
Comment: By the by, I would be curious to know what in your notes is forcing you, when asked about the compactness of some set $S$ explicitely defined as above, to start a "solution" by "$\dot V=\ldots$".
Comment: @Did: For the compactness - my mistake. I think it's easier to show it by considering $-\frac{1}{4}\le \frac{(x^2-1)^2+2y^2-1}{4}\le k$, which shows boundedness. SInce the set is closed, it is compact. The reason I used $\dot{V}$ to show compactness is because it is defining the set $S$.
Comment: For the invariance part, since we have $\dot{V}=-y^2$, where there is no $x$ present, it should be advisable to use LaSalle's Invariance Principle, which removes the mentioned restriction. LaSalle's Invariance Principle is used to find the limit sets (part iii dealing with (1,0) ).
Comment: @Did: What would you suggest to do for part iii? I appreciate your involvement. I think one has to find the limit set of $S$. Since $S$ is positively invariant and compact, it contains an equilibrium point or a periodic solution.
Comment: I think a trajectory would end up at $(1, 0)$. May I ask why did you define $U$ this way?
Comment: "think"? Can you *prove* it?
Comment: Since $V$ is decreasing and bounded, a trajectory $\psi_t((x,y))$ must end up at a limit set. We need to consider $\dot{V}=0$, which is where $y=0$. Since $V \ge -\frac{1}{4}$, consider $V(x, 0) = -\frac{1}{4}$. $x>0$ implies that $x=1$. Thus, the limit set $\omega_0 = \{(1,0)\}$.
Comment: Until "which is where $y=0$", you are fine. After that, no idea of the logic of the things you write.
Comment: $\dot{V} = -y^2 \le 0$, hence for $\dot{V} = 0$, $y=0$. Since $V$ is decreasing and $V(x,y)=-\frac{1}{4}$ is the lowest bound of $S$, we can consider $V(x,0)=-\frac{1}{4}$.
Comment: Since $y=0$, we plug this into the system and get $x' = 0$, $y' = x-x^3 = 0$. Since $x>0$, $x=1$.
Comment: Well yes, if you *assume* that the trajectory converges to a fixed point, then there is not much to do... But the whole point is that one is supposed to *prove* this.
Comment: There's a corollary from the Poincaré-Bendixson Theorem in the notes which states that if $S$ is a positively invariant compact set of a differential system, then $S$ contains an equilibrium point or a periodic solution of the system. One can check that $\nabla\cdot f(x,y) = -1 < 0$ and does not change sign on $S$, thus the system has no periodic solutions, hence it must have an equilibrium point. Now, since $(1,0)$ is a center point of the system, it is stable, and thus a trajectory must converge to it.
Comment: If you can state this result precisely (at the moment, the notations $f$ and $\nabla\cdot f$ are in need of explanations) and show that it applies to your setting, then you have an answer. Perhaps post your try as an answer and then we will have something solid to discuss.
Comment: Just posted an answer.
Answer: Let $f(x,y):=\begin{bmatrix}
y \\ x-x^3-y
\end{bmatrix}$
A corollary to the Poincaré-Bendixson Theorem states:

If $S$ is a positively invariant compact set of a differential system $\vec{x}'=f(\vec{x})$, then $S$ contains an equilibrium point or a periodic solution to the system.

One can check that the divergence of $f$, namely $\nabla\cdot f(x,y)=−1<0$ does not change sign on $S$, thus the system has no periodic solutions, hence it must have an equilibrium point. Now, since $\dot{V}=-y^2\le 0$, $y=0$. We can substitute $y=0$ into the system and get that $x-x^3=0$. Since $x>0$, $x=1$. In addition, it can be checked that $(1,0)$ is a center point of the system, thus it is stable, and thus a trajectory $\psi_t(\vec{x_0})$ must converge to $(1,0)$.


How to Select by LINQ into anonymous type in F#

Question: I have this code snippet, which creates an array of anonymously typed elements with properties Name and FirstLetter:
string[] arr = { "Dennis", "Leo", "Paul" };

var myRes = arr.Select(a => new { Name = a, FirstLetter = a[0] });

I would like to do the same in F#. I tried:
let names = [| "Dennis"; "Leo"; "Paul" |]

let myRes = names.Select(fun a -> {Name = a; FirstLetter = a[0]} )

But this doesn't compile. It says:
The record label 'Name' is not defined.
How can I get this line to work in F#?
Comment: You can use tuples which are anonymous but do not have labels, or you can define record type before selecting values.
Comment: No such luck yet: https://fslang.uservoice.com/forums/245727-f-language/suggestions/5673015-support-c-like-anonymous-types-in-f (F# supports neither creating Anonymous Types or Anonymous Records)
Answer: As in comments, F# doesn't support anonymous type. So if you want to project your sequence into another sequence, create a record, which is essentially a tuple with named fields.
type p = {
  Name:string;
  FirstLetter: char
}

let names = [| "Dennis"; "Leo"; "Paul" |]
let myRes = names.Select(fun a -> {Name = a; FirstLetter = a.[0]} )

Comment: The request to add anonymous types in F# has been getting a bit of traction lately. https://github.com/fsharp/fslang-suggestions/issues/207
Comment: This answer was right at the time the question was originally asked but see my new answer based on the new Anonymous Records feature in F# 4.6.
https://stackoverflow.com/a/55605117/83658
Answer: Your initial attempts would work more intuitively as of F# 4.6. Testing a similar example using .NET Core SDK 3.0.100-preview4 I was able to prove this out using the new Anonymous Record feature.
let names = [| "Dennis"; "Leo"; "Paul" |]

let myRes = names.Select(fun a -> {| Name = a; FirstLetter = a.[0] |})

Notice the use of the | character on the insides of the curly braces. This is what now distinguishes regular records from anonymous records in F#. Also notice that when accessing the first character of a string in F# that the . method accessor operator must be used to access the indexer just like when accessing other methods.


expose filter work with ajax only on inner pages but work with button submit on front page

Question: What I want is to work expose filter with ajax only on inner pages but work with  button submit on front page i.e when I want my expose filter on front page to work like normal form but on inner page i want it to work with ajax
Comment: Are you doing this programatically, if so what code have you got so far .  you can use drupal_is_front_page() to give a boolean answer for what page you are on.
Comment: I am theming views exposed filters with some conditions
but how can i set ajax enabled only with inner pages
Answer: Disable Use ajax in View settings, in THEME_OR_MODULE_form_views_exposed_form_alter(&$form, &$form_state) function do like this:
function THEME_OR_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form)
  // dpm($form_state)
  if ($form['#id'] == 'MY-VIEWS-FORM-ID') {
    if (!drupal_is_front_page()) {
      $form_state['view']->use_ajax = true;
    }
  }
}

flush the cache.
Comment: i have tried it but with no luck
Comment: @harsh can you show what you've tried? It is working fine in my project..


Getting a date from a week number

Question: I am trying to get a date based on a number of the week, but there are some annoyances.
The date.weekday() returns the day of the week where 0 in Monday and 6 is Sunday.
The %w directive of date.strftime() and date.strptime() uses the 0 for Sunday and 6 for Saturday.
This causes some really annoying issues when trying to figure out a date given a week number from date.weekday().
Is there a better way of getting a date from a week number?
EDIT:
Added the example.
import datetime

original_date = datetime.date(2014, 8, 24)
week_of_the_date = original_date.isocalendar()[1] # 34
day_of_the_date = original_date.isocalendar()[2] # 7
temp = '{0} {1} {2}'.format(*(2014, week_of_the_date, day_of_the_date-1))
date_from_week = datetime.datetime.strptime(temp, '%Y %W %w')
week_from_new_date = date_from_week.isocalendar()[1] # 35!!

EDIT 2:
I ultimately put the date stuff in the view (using jQuery UI), it has more consistent notions of weeks.
Comment: Possibly relevant: http://stackoverflow.com/questions/304256/whats-the-best-way-to-find-the-inverse-of-datetime-isocalendar
Comment: I think the Sunday vs. Monday distinction between `weekday` and `strftime` using `%W` is moot - you could use `isoweekday` to get those to line up. The real problem is that `strftime`, based on the underlying C function, determines the first week of the year differently than the ISO definition. With `%W` the docs say: " All days in a new year preceding the first Monday are considered to be in week 0". ISO calendars count the week containing the first Thursday as the first week, for reasons I do not understand, and it doesn't look like there's a nicer way to reverse that than the answer linked.
Comment: @SylvainLeroux - I suppose there's enough actual information there that I'm not trying to take credit for pointing out a dupe.
Comment: What exactly is a week number in this context, and what does `date.weekday` have to do with it? Sample input and output would be helpful.
Comment: Ah, didn't know about that problem, very ugly inconsistency! Different, but related question [here](http://stackoverflow.com/q/7550726/2647279)
Comment: Week number (usually?) refers to [ISO week date](http://en.wikipedia.org/wiki/ISO_week_date). Regarding the difference in weekday between time and datetime modules, you're right, it's hideous.
Comment: @PeterDeGlopper Sure. I've added an example.
Comment: There's also this module someone linked off one of the answers linked on that older answer: https://pypi.python.org/pypi/isoweek/
Comment: @PeterDeGlopper You should probably post your last two comments as an answer.
Answer: I think the Sunday vs. Monday distinction between weekday and strftime using %W is moot - you could use isoweekday to get those to line up, or %U in strftime if you wanted Sunday as the first day of the week. The real problem is that strftime, based on the underlying C function, determines the first week of the year differently than the ISO definition. With %W the docs say: " All days in a new year preceding the first Monday are considered to be in week 0". ISO calendars count the week containing the first Thursday as the first week, for reasons I do not understand.
Two ways I found to work with ISO weeks, either just getting datetime.date instances back or supporting a variety of operations, are:

this answer with a simple timedelta approach:
What's the best way to find the inverse of datetime.isocalendar()?
this third-party library: https://pypi.python.org/pypi/isoweek/

Getting a date from a week number


Deriving the distribution of Random variable

Question: I am reading a paper here: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7564878
As explained in the following, I cant understand how Eq. 2 is derived by the authors.
$P_I$ is a random variable (Received Power in full-duplex transciever model) and the randomness in $P_I$ is because of random fading power $g = |h|^2$. $P_I$ is given as:
$$P_I = P_T \kappa d^{-\alpha}g$$
$\kappa$, $\alpha$ are constants and $g = |h|^2$. In the following, I cant understand how the authors have come up with Eq. 2.
I will appreciate any help.
Answer: Here we have a r.v. $X\sim\text{N}(\mu,\sigma^2)$, and it is required to find the density function for $Y=c\,X^2$, where $c$ is a positive constant.
$$\begin{align}P(Y\le y)&=P(cX^2\le y)\\[2ex]
&=P(X^2\le {y\over c})\\[2ex]
&=P\left(-\sqrt{y\over c}\le X\le\sqrt{y\over c}\right)\\[2ex]
&=F_X\left(\sqrt{y\over c}\right)-F_X\left(-\sqrt{y\over c}\right)
\end{align}$$
Differentiating to get the densities ...
$$\begin{align}f_Y(y)&={f_X\left(\sqrt{y\over c}\right)\color{blue}{+f_X\left(-\sqrt{y\over c}\right)}\over 2c\sqrt{y\over c}}.\\
\end{align}$$
The portion in blue has been omitted in Equation (2), which is possibly justified by the approximations they are making. In particular, they state that $K$ is "large", which suggests that $v^2$ is only slightly less than $1$, and hence that the variance of the normal distribution is very small. This implies that the distribution of $h$ is very concentrated near the value of $1$, in which case the omitted portion of the density function might be negligible.

Numerical cross-checks:
Technically, Equation (2) fails to describe a probability density function, because of the mentioned omission. Thus, choosing $\tau>0$ and $0<v<1$, we find, for  $f_{P_I}$ given by Equation (2): $$\int_0^\infty f_{P_I}(x)dx \neq 1,$$
although the discrepancy decreases as $v$ increases toward $1.$
Pasting the following into Wolfram Alpha to integrate Equation (2) yields a value less than $1$:
tau=1; v=1/2; integrate (1/(2 sqrt(pi tau x (1-v^2)))) exp(-(sqrt(x/tau)-v)^2/(1-v^2)) dx from x=0 to oo

Pasting the following into Wolfram Alpha to integrate the "corrected" version yields exactly $1$:
tau=1; v=1/2; integrate (1/(2 sqrt(pi tau x (1-v^2)))) (exp(-(sqrt(x/tau)-v)^2/(1-v^2)) +  exp(-(-sqrt(x/tau)-v)^2/(1-v^2)) )  dx from x=0 to oo

Numerical trials suggest that if $0.9\le v < 1$, then Equation (2) integrates to at least $0.998$.
Comment: @Sjaffry At first I thought something like that might be happening, but then I tried specific numerical cases and found the discrepancy too great. (See the cross-check in my edit.)
Comment: What is non-monotonicity here?
Comment: I think the authors must have removed the BLUE part that you have because this is F_X(-\sqrt{\frac{y}{c}}) would be Zero? The reason I say this is because the $X$ here represents the channel here. What do you say?
Comment: @Sjaffry I just noticed the assumption that $K$ is "large", which implies that $v^2$ should be only "slightly" less than $1$ (hence the variance of the normal distribution is very small). In such case, it may  be that the discrepancy is negligible after all.


Integral of a non-uniform convergent series

Question: Hey guys so im asked to calculate this
$f_n(x)=n^2x^2e^{-(n^2x^2)}$
$g_n(x)=f_n(x)-f_{n+1}(x)$
$g(x)=\sum_{n=1}^{\infty} g_n(x)$
$\int_{0}^{1} g(x) dx$
and
$\sum_{n=1}^{\infty} \int_{0}^{1} g_n(x) dx$.
But i have no idea where to start because i cant calculate the integral of $g_n$ specifically and im not really seeing what $g(x)$ is, i guess it is going to be $g_1$ and then the other terms as $n$ goes to infinity are going to be zero. Any advice is aprecciated, Thanks.
Comment: Your question makes no sense as stated. Please clean it up so that everything is clear.
Answer: Both of them can be computed using the fact that $(a_1-a_2)+(a_2-a_3)+\cdots =a_1$ if $a_n \to 0$. For example, this gives $g(x)=f_1(x)$ for $0<x<1$ since $f_n(x) \to 0$ as $n \to \infty$ for $0<x<1$.
Comment: You have to write down the partial sums and take limit to justify it.
Comment: To see that $\int_0^{1} f_n(x)\, dx \to 0$ you can make the substitution $y=nx$.
Comment: Yes i noticed that $f_1(x)$ was going to be the only left but since it was an infinite sum i wasnt sure i could make that assumption.


Showing the number of items in WooCommerce mini cart

Question: I am creating a cart link for my mobile header. I just want to show number of cart items after the cart icon. No text, only a number.
How can I do it?
My code is something like this:

 Here should be the code for no. of items

Thanks.
Answer: You just need to use the method get_cart_contents_count() from WC_cart class, this way:

         <?php echo WC()->cart->get_cart_contents_count( ); ?>

Reference: WC_Cart class - get_cart_contents_count() method
Comment: Thanks man. You are awesome. You solved a big problem of mine


Contexto Delimitado e Módulos/Pacotes

Question: Conforme o Domain Driven Design:

Os pactoes devem contar uma história, fazem parte da linguagem onipresente, organizam conceitos relacionados;
O contexto delimitado é a delimitação onde os termos da linguagem onipresente têm significado;

Dúvidas:

O contexto delimitado deve ser implementado como um pacote/namespace?
Se o contexto delimitado for um pacote/namespace, os pacotes que contam a história do software devem estar dentro do contexto delimitado?

como deve ser declarado o pacote/namespace?
Nome_do_contexto_delimitado \ Nome_do_pacote
ou
Nome_do_pacote \ Nome_do_contexto_delimitado
Answer: Vários packages ("pacotes") podem compor juntos um único bounded context ("contexto delimitado"), não existe necessariamente relação de 1 pra 1.
Uma estrutura de nome de package que funciona bem é:
contexto.assunto

Onde o nome do bounded context é a raiz ou está próximo da raiz do package (a raiz também pode ser algo como com.nomeempresa, daí a estrutura do nome do package seria com.nomeempresa.contexto.assunto)
"Assunto" aqui é uma área de interesse dentro daquele contexto.
Exemplos de nomes de packages e classes:
Bounded context Vendas:
marketing.cliente.Cliente
marketing.cliente.Categoria
marketing.produto.Produto
marketing.produto.Categoria

Bounded context Logística:
logistica.cliente.Cliente
logistica.produto.Produto

O assunto pode ter subdivisões. Por exemplo:
marketing.produto.review.Review
marketing.produto.review.Consumidor
marketing.produto.review.Editor

Identificação da camada no nome do package
Também pode haver na raiz ou próximo à raiz do nome do package a indicação da camada lógica daquele código, assim:
business.contexto.assunto
application.contexto.assunto

Isso ajuda a manter o respeito nas relações entre as camadas (um código de business jamais deve referenciar um código de application).
Há quem faça esta separação usando pastas ou diretórios no projeto. Informar a camada no nome do próprio package, entretanto, permite identificar, analisando apenas o código fonte, que alguma referência está desrespeitando o relacionamento entre as camadas. Por exemplo (Java):
package business.marketing;

import application.marketing.produto.*;

public class Cliente {...

No código acima, a referência que desrespeita as relações está evidente (e pode ser detectada com uma analisadorde código) de uma maneira que não estaria se a camada não estivesse identificada no nome do package.

Contexto Delimitado e Módulos/Pacotes


Load all titles and body text from one content type into array

Question: I'm working on an input format filter that should work as following. I have a content-type called glossary, the user can fill in a word (title) and description (body). Then there is a content-type article. When a word in the article matches a word in the glossary it should wrap that word with a span. Something like word. I already did a quick and dirty tryout and that worked fine. I already did a speed test and it worked out fine only a delay of 0.2s max.
But now I try to make it as it should and I got stuck.
The way I think this could work is to have an array with all words and descriptions from the glossary content-type in a array. And then search through the text.
So I created a Plugin/Filter/Filtername.php file. In this file I try to load all node from the glossary content-type (as advised) via dependency injection.
What I found is a way to get all nids, via this code added in to my filter class:
<code>class FilterName extends FilterBase {
    public function __construct(QueryFactory $entity_query)
    {
        $this->entity_query = $entity_query;
    }

    public static function create(ContainerInterface $container){
        return new static(
          $container->get('entity.query')
        );
    }

    public function process(){
        $query = $this->entity_query
        $query->condition('bundle','woordenlijst');
        $nids = $query->execute();
    }
}
</code>
So this should give me all nids of the node I'm looking for but how do I get these node loaded to get there title and body text? I found this lesson about entity loading. Which is usefull but there are some deprecated functions used and I have no idea how to combine these to to get een array of titles and body texts.
So what is currently the best method to load nodes and how can I combine this with the code I already have? And am I even on the right path or not, or is there a better/easier way to do this?
Thanks in advance.
Comment: There is probably a good reason why you want to do this, but I can't think of one. All I can think of is this not being a scalable approach. That said, caching does work in your favor, but that first load is going to be killer. Are you trying to produce a list of node titles and bodies that can be embedded somewhere on a particular page?
Comment: I have a good reason but maybe not the right method :D. What I try to make is a glossary. So I have a content-type called glossary, the user can fill in a word (title) and description (body). Then there is a content-type article. When a word in the article matches the glossary it should wrap that word with a span. Something like word. I already did a quick and dirty tryout and that worked, but no I try to make it as it should and I got stuck.
Answer: If yau have lots of node's than its difficult load all nodes at a time and also , to get only title and body, its not fair to load complete node.
Rather than load node and get values, we can use select query and fetch required values.
I am using cache concept here, once your query loaded, set it in cache untill any node values changes or any new node creates.
Use node hooks to remove cache for "node_data"
Below is the query:
<code>  $nodedata = array();
  // Check cache exists
  $cache_node = \Drupal::cache()->get('node_data');
  if ($cache_node) {
    $array = $cache_node->data;
    $nodedata = json_decode($array, TRUE);
  }
  else {
    // Query for node title and body.
    $connection = \Drupal::database();
    $query = $connection->select('node', 'n');
    $query->leftJoin('node__body', 'b', 'b.entity_id = n.nid');
    $query->leftJoin('node_field_data', 't', 't.nid = n.nid');
    $query->fields('t', array('title'));
    $query->fields('b', array('body_value'));
    $query->condition('n.type', 'glossary', '=');
    $result = $query->execute()->fetchAll();
    foreach ($result as $key => $value) {
      $nodedata[] = array(
        'node_title' => $value->title,
        'node_body' => $value->body_value,
      );
    }
    // Set Cache.
    \Drupal::cache()->set('node_data', json_encode($nodedata));
  }
  dsm($nodedata);
</code>
Comment: That's a very fast solution! To remove the cache, you could set a cache tag. Put `['node_list']` as 4th parameter when setting the cache data. Then the cache will be invalidated automatically whenever a node is changed or created.
Answer: you can use entityQuery like this for load all nodes of content type.
<code>$node_array = array();
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'woordenlijst');
$entity_ids = $query->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);
 foreach ($nodes as $node) {
  $title = $node->getTitle();
  $body = $node->get('body')->getValue();

  $node_array[] = array(
'node_title' => $title,
'node_body' => $body,
);
}
</code>
Finally you got a array with title and body.Use dpm($node_array);


WORDPRESS Where to find advanced custom fields selects name in phpmyadmin wp database?

Question: I can't find in the database that ACF stores the names of the SELECT type fields. The number of elements is there, but there is no corresponding name. Can somebody help me?
I'm looking at the database, but I'm at a loss.
Answer: Each ACF field is stored as a post in the {{wp prefix}}_posts table, and the public name of the field is in the post_title column, while the slug of the field is in the post_excerpt column.  The post type is acf-field, BTW.
Comment: Ok, it's in wp_posts, not wp_postmeta. I had the wrong idea that it was stored. Thanks!


Thumbnails wordpress em Custom Post Type

Question: Estou usando o seguinte código para habilitar Custom Posts Types em meu site. No functions. O que devo adicionar a este código para que apareça a função de thumbnails ao post personalizado?
add_action( 'init', 'create_post_type' );
function create_post_type() {
  register_post_type( 'portfolio',
array(
  'labels' => array(
    'name' => __( 'Portfolio' ),
    'singular_name' => __( 'Porfolio' )
  ),
  'public' => true,
)
  );
}
register_taxonomy(
"categorias",
  "portfolio",
  array(
    "label" => "Categorias",
        "singular_label" => "Categoria",
        "rewrite" => true,
        "hierarchical" => true
)
);

Answer: Basta que, no segundo parâmetro de register_post_type(), você adicione o seguinte:
'supports' => array( 'thumbnail ')

Como é possível ver na documentação, o array supports é onde você coloca tudo que o seu custom post vai suportar. Veja que, para que isso funcione, o seu tema deve estar com o suporte para thumbnails habilitado. Isso pode ser feito no arquivo functions.php, colocando
add_theme_support( 'post-thumbnails' );

Notei também que o seu código fonte não tem a action necessária para registrar a custom taxonomy (como mostra a documentação).  Então, supondo que voce ainda não a tenha registrado, e para que tudo funcione (e consertando alguns erros de indentação), o seu código deve ficar assim
add_action( 'init', 'create_post_type' );
add_action( 'init', 'register_custom_taxonomy ');

function create_post_type() {

    register_post_type( 'portfolio',
        array(
            'labels' => array(
                'name' => __( 'Portfolio' ),
                'singular_name' => __( 'Porfolio' )
            ),
            'public' => true,
            'supports' => array( 'thumbnail ')
        )
    );
}

function register_custom_taxonomy(){

    register_taxonomy( 'categorias', 'portfolio',
        array(
            'label' => 'Categorias',
            'singular_label' => 'Categoria',
            'rewrite' => true,
            'hierarchical' => true
        )
    );
}


A Laskerian non-Noetherian ring

Question: A Laskerian ring is a ring in which every ideal has a primary decomposition. The Lasker-Noether theorem states that every commutative Noetherian ring is a Laskerian ring (as an easy consequence of the ascending chain condition).

And I've found the statement that there are non-Noetherian Laskerian rings, but I can't find an example. Any ideas?

Edit. As the tag already suggested, I'm particularly interested in a commutative Laskerian non-Noetherian ring, but noncommutative examples are also welcome. It never hurts to know more counterexamples.
Answer: I don't know of any easier examples, but here is one. Let $k$ be a field and $R$ be the set equivalence classes of elements of the form $\frac{f(x,y)}{g(x,y)}$ where $x,y$ are indeterminates over $k$, $f,g\in k[x,y]$, $x$ does not divide $g$ (in $k[x,y]$) and $\frac{f(0,y)}{g(0,y)}\in k$. Make $R$ into a ring by the usual addition and multiplication of rational functions. Then, it can be shown that $R$ is a commutative ring that is not noetherian and every ideal of $R$ has a primary decomposition.
This is an example from Gilmer's paper linked here.
He also gives a characterization of rings in which every ideal has a unique primary decomposition.
Answer: Many interesting examples are in Barucci and Fontana: When are $\rm\ D +  \frak M\ $ rings Laskerian? They construct (non-Noetherian) Laskerian or strongly Laskerian rings and domains either integrally closed or not, of any dimension. They employ a frequently used powerful tool for constructing counterexamples - the  $\rm\ D +  \frak M\ $ construction. For more on this construction see Anderson: Star operations and the  $\rm\ D +  \frak M\ $ construction and see this very informative survey on more general constructions of Zafrullah: Various facets of rings between $\rm\:D[X]\:$ and $\rm\:K[X]\:$.
Comment: Zafrullah's article is also available at [doi:10.1081/AGB-120019008](https://doi.org/10.1081/AGB-120019008). (Just in case the link currently at `lohar.com` ends up broken in the future.)
Answer: See I. Armeanu, On a class of Laskerian rings, Revue Roum. Math. Pures et Appl. XXII,
8, 1033–1036, Bucharest, 1977.

A Laskerian non-Noetherian ring


Migrate a Classic Azure VM to RM in a different region and subscription

Question: I have an SFTP server on a classic Azure VM running in the Southeast Asia region. I would want to migrate the VM to the resource manager version in a different subscription in the East US 2 region. How can I do that?
Answer: First step is to complete the migration from Classic to ARM in the current subscription the resources are located in.
Here is the guide on how to do that: https://docs.microsoft.com/en-us/azure/virtual-machines/windows/migration-classic-resource-manager-overview
Once the resources are migrated from Classic to ARM, you can move on to moving the resources to a new subscription.
https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-move-resources
So all in all, it is a 2 step process. First the Classic to ARM migration then the Subscription Migration.


How can vim keep the content of register when pasting over selected text?

Question: I have a line of text I have yanked yy. Now I want to use this text to replace lines at several other places. The trouble is that when I select V the line to be replaced, and paste p, the text that was selected is automatically yanked! That's what I don't want.
Changing the register does not work, because both the paste and the yank are done with the newly selected register.
What is the command to keep the content of the register when pasting over selected text?
Comment: You're probably already aware, but I think you can always work around the problem with `pdd`.
Comment: @a3nm Don't you mean `pyy`, that would copy again the current line?
Comment: Sorry, I meant `pjdd`. This being said, I don't understand your suggestion.
Comment: @a3nm Well, using `pyy`, you first paste the content of the register, and then yanks the line you've just pasted into the register to overwrite what has been set when pasting. The problem with `pdd` is that it would delete what I`ve just pasted.
Answer: Your original selection should remain in register 0. So you can move through the file and paste your yanked line over other lines using: V"0p
Comment: Also, use `:reg` to look at the current register contents. [This](http://blog.dreasgrech.com/2010/06/vims-black-hole-register.html) is a pretty good explanation of registers, including the black hole register, and the _kill buffer_ registers 0-9. Finally: `:help register`, natch.
Comment: This is the better answer. There is no need to send deleted content to the black hole register when there is already a register made specifically to hold onto yanked text
Comment: @rviertel in which manner is this better? Better to type numerous keyboard keys just to get what you want? And in the end, ask yourself how often you needed replaced content? For me the answer is zero, zero times I needed replaced content
Answer: Each time you p over something it goes into the default register.
To work around this feature you have to use "_, "the black hole register", before you p. Here is a custom mapping I have in my ~/.vimrc:
vnoremap <leader>p "_dP

It deletes the selected content and drops it in the black hole register (this means that the selected text disappears forever) and puts the content of the default register in place of the previously selected text while leaving the default register intact.
I use it often when I need to replace a loooooooong url in a few places with another looooooong url and crafting a s// would be too cumbersome.
Comment: I went even more extream: `vnoremap p "_dP`
Comment: You're a madman!


python gspread not working on GAE

Question: I had a program that ran for years on Google App Engine. It was written in python and uses gspread. It suddenly stopped working on GAE and returns a 404. I tested it locally and it works fine.
Answer: I've found this open public issue tracker where it seems it could be a similar issue than yours. I would suggest you add a comment in that public issue tracker explaining your issue.

python gspread not working on GAE


Supremum of rounded function

Question: Can you please help me to find and prove $\sup\{\sqrt{n}- \left\lfloor \sqrt{n}\right\rfloor : n\in N\}$?
I assume that it is something like $1$ or some other constant, but not quiet sure.
Comment: Oops! I edited it back to the original.
Answer: To prove that $$\sup \left\{ \sqrt{n} - \left\lfloor \sqrt{n} \right \rfloor  : n \in \Bbb{N}  \right\} = 1$$
(note that I use the more modern symbol $\lfloor x \rfloor$ in place of $[x]$ to mean the highest integer not exceeding $x$)
Step 1: For $n \in \Bbb{N}$  or indeed any real value of $n$, $\sqrt{n} - \left\lfloor \sqrt{n} \right \rfloor <1$.  Because if $\sqrt{n} - \left\lfloor \sqrt{n} \right \rfloor  = 1+\alpha$ with $\alpha > 0$, then $\left\lfloor \sqrt{n} \right \rfloor +1  = \sqrt{n}-\alpha < \sqrt{n}$ so $\left\lfloor \sqrt{n} \right \rfloor$ is not the greatest integer not exceeding $\sqrt{n}$ and this contradicts the definition of  $\lfloor x \rfloor$.
Step 2: For any $\epsilon >0$, there exists some $n \in \Bbb{N}$ such that
$$
\sqrt{n} - \left\lfloor \sqrt{n} \right \rfloor > 1-\epsilon
$$
Proof: Choose any $k > \frac1\epsilon + 1$ and consider $n = k^2 -1$. Then
$\left\lfloor \sqrt{n} \right \rfloor = k-1$ and $\sqrt{n} = (k-1) + x$ for some $0<x<1$. Now of any $x : |x|\leq 1$,
$$
1+\frac{x}2-\frac{x^2}8 = \sqrt{1+x-\frac{x^3}{8}+\frac{x^4}{64}} < \sqrt{1+x}
$$
In particular, choose $x = \frac{2}{k-1}$ so that
$$
\sqrt{1+\frac2{k-1}}> 1+\frac1{k-1}-\frac1{2(k-1)^2} \\
(k-1)\sqrt{1+\frac2{k-1}}> (k-1)\left(1+\frac1{k-1}-\frac1{2(k-1)^2} \right)\\
\sqrt{k^2-2k+1+2(k-1)}> k-1+1-\frac1{2(k-1)} \\
\sqrt{k^2-1)}> k-\frac1{2(k-1)} > k-\frac1{2/\epsilon} = k-\frac{\epsilon}{2} > k-\epsilon
$$
So for our arbitrary $\epsilon$ we have demonstrated an $n$ such that
$$\left\{ \sqrt{n} - \left\lfloor \sqrt{n} \right \rfloor \right\}> 1-\epsilon$$
The combination of steps 1 and 2 establishes that $1$ is the desired suprenum.
Comment: Could you please explain how we know that $\left\lfloor \sqrt{n} \right \rfloor = k-1$? Thank's in advance!

Supremum of rounded function


$f_n$ is continuous on $[a,b]$, and for any $x\in [a,b]$, $\{f_n(x)\}$ is a bounded sequence. Show that for some interval, $f_n$ is uniformly bounded

Question:
$f_n$ is continuous on $[a,b]$, and for any $x\in [a,b]$, $\{f_n(x)\}$ is a bounded sequence. Show that for some interval, $f_n$ is uniformly bounded.

What to do? Heine-Borel property? How to find such an interval? For any $x\in [a,b]$, there exists $M_x>0$ such that for all $n$, $|f_n(x)|\leq M_x$. How to bound $M_x$ for $x$ in some nice interval?
Answer: $[a,b]=\bigcup_m \bigcap_n\{x: |f_n(x)| \leq m\}$. This is a countable union of closed sets.  Apply Baire Category Theorem to get the answer immeditely.
Ref: https://en.wikipedia.org/wiki/Baire_category_theorem


Similarity metrics for more than two vectors?

Question: I am aware of Cosine Similarity which measure the angle between "two" vectors. Prototype for cosine similarity would look something like this:
float cosine_similarity(vector<float> a, vector<float> b);

Are there any similarity measures that measure the similarity between "n" vectors? Prototype of this function would look something like this:
float cosine_similarity(vector<vector<float>> vectors);

PS: I am NOT looking for clustering/classification sort of a thing.
I will appreciate if someone can point out in some direction.
Thanks!
Comment: @user3667569 there are many variants, and the best choice will vary depending on your data and goals. However, the basic idea is do an [SVD](https://en.wikipedia.org/wiki/Singular_value_decomposition#Low-rank_matrix_approximation) on a [data matrix](https://en.wikipedia.org/wiki/Design_matrix) of your vectors. A simple example would be to use the ratio of the first singular value and the matrix norm, which is similar to an $R^2$, giving the "fraction of variance explained", a number between 0 and 1. ([PageRank](https://en.wikipedia.org/wiki/Google_matrix) is similar.)
Comment: Would you like a single number to represent the similarity among all the samples in a group? What should this value signify in your case? The purity of the group? Or perhaps an average of all pairwise cosine similarities?
Comment: If you start to look at all pairwise cosine similarities, then this falls under a [standard class](http://stats.stackexchange.com/a/22520/127790) of "linear dependence" metrics. This suggests a natural possibility could be linear [dimension reduction](http://stats.stackexchange.com/a/134283/127790) techniques.
Comment: @GeoMatt22 could you please elaborate?
Comment: @user115202 yeah I'd like for it to be a single number but definitely more sophisticated than an average of cosine similarities.
Comment: @GeoMatt22 possible to give an example of what you said as an answer?
Comment: @user3667569 I put an answer, as you requested.
Comment: @GeoMatt22: Thanks, I will wait for some more time for the answer before accepting it as the final answer.
Thanks again, gave me some important things to think about.
Answer: The cosine similarity between two column vectors $x_1$ and $x_2$ is simply the dot product between their unit vectors
$$\mathrm{CosSim}[x_1,x_2]=\frac{x_1}{\|x_1\|}\bullet\frac{x_2}{\|x_2\|}$$
and varies from -1 to +1, similar to a correlation coefficient $R$ (to which it is closely related).
There are many ways to generalize this idea to a set of $n$ vectors, but as requested in the comments, here I will expand on one possibility, related to the idea of (linear) dimensionality reduction.
First, in the $n=2$ case, we can think of $R^2\in[0,1]$ as the "fraction of the variance explained" by a linear regression. For the squared cosine similarity, a similar interpretation is possible, except the associated regression has no "intercept term" (i.e. the vectors are scaled, but not centered).
In the $n$ dimensional case, we can concatenate the vectors into a matrix
$$X=\begin{bmatrix}x_1 \, \ldots \, x_n\end{bmatrix}$$
analogous to the cosine similarity case, we can consider dot products based on the scaled matrix
$$Y=\begin{bmatrix}y_1 \, \ldots \, y_n\end{bmatrix}$$
assembled from the corresponding unit vectors
$$y_i=\frac{x_i}{\|x_i\|}$$
In general we could then conduct varying analyses on the "correlation matrix"  $Y^TY$, including dimension reduction via PCA.
The general idea here is to create a low-rank approximation to the matrix $Y$ by truncating its singular value decomposition (SVD). Mathematically, we have
$$Y=USV^T=\sum_{k=1}^n\sigma_ku_kv_k^T$$
where the singular values $\sigma_1,\ldots,\sigma_n$ are non-negative and arranged in decreasing order. (For simplicity I am assuming that for $x_i\in\mathbb{R}^m$ the number of vectors is at least $n\geq m$. Otherwise the sum will have $m$ terms.) If we truncate the sum at $K<n$, then we get a "rank $K$ approximation" $\hat{Y}_K$ to the matrix $Y=\hat{Y}_n$. The truncated SVD is optimal in the sense that it minimizes the  Frobenius norm of the reconstruction error $\|\hat{Y}_K-Y\|_F^2$.
The squared Frobenius norm is just the sum of the squares of all the entries of a matrix. In particular, for the scaled matrix $Y$ we will always have $$\|Y\|_F^2=n$$
For any matrix, the Frobenius norm is also equal to the sum of the squares of the singular values. In particular, for the $K$-rank approximation $\hat{Y}_K$ we have
$$\|\hat{Y}_K\|_F^2=\sum_{k=1}^K\sigma_k^2$$
So we can define an "order $K$ coefficient of determination" as
$$R_K^2\equiv\frac{\|\hat{Y}_K\|_F^2}{\|Y\|_F^2}\in[0,1]$$
A simple option would be to just use the first singular value, i.e.
$$R_1^2\equiv\frac{\sigma_1^2}{n}$$
The maximum similarity would be for $n$ parallel vectors (i.e. scalar multiples of a single vector), giving $R_1^2=1$. The minimum similarity would be for $n$ orthogonal vectors, giving $R_1^2=\frac{1}{n}$.
A few final notes:

The first singular value $\sigma_1$ can be computed via an iterative method, so no detailed SVD need be computed. (Similar to PageRank; e.g. svds(Y,1) in Matlab.)
To get a similarity that can range over the entire [0,1] interval, you could simply normalize, i.e.
$$\hat{R}_1^2\equiv\frac{\sigma_1^2-1}{n-1}$$
So in Matlab the similarity function could be defined via      CosSimN = @(Y) (svds(Y,1)^2-1)/(size(Y,2)-1), if we assume that $Y$ is already available as input.
For $n=2$ the above will reduce to the absolute value of the standard cosine similarity.
Comment: @D.Phi sorry for the confusion. My proposed $n$-vector similarity measure $\hat{R}_1^2$ can be applied to any collection of vectors. (The only limitation is that no vector is entirely zeros, which also applies to cosine similarity.) For the special case of $n=2$, the result will just be the absolute value of the cosine similarity. So $n > 2$ and negative data are no problem.
Comment: @D.Phi as for the size: As noted in my answer, the sum of squares of singular values by definition equals the sum of squares of the matrix entries (squared Frobenius  norm). If you input a $Y$ with normalized (unit-vector) columns, then the sum of squares of $Y$'s entries will be the number of columns. This is the max you can get for the square of $Y$'s first singular value. (If you do not normalize the columns first, this would not hold.) As for "What is the benefit of this approach?", as I mentioned in my initial comment to OP, this is simply one plausible approach to generalizing CosSim.
Comment: thank you for your elaborate answer. Does the equation CosSimN = @(Y) (svds(Y,1)^2-1)/(size(Y,2)-1) also hold for n > 2 and possibly negative data? If not, is there a way to support negative data?
Comment: Thanks, I appreciate your answer. I implemented your code and found an error. You divide by the column count of Y instead of n (which is row count * column count). Here is the code which works for me: CosSimN = @(Y) (svds(Y,1)^2-1) / (prod(size(Y)) - 1)
Comment: I've noticed that your proposed formula does not work well on vectors with many zeros. E.g. if Y = [[1,0,0],[1,0,0],[1,0,0]], then CosSimN(Y) = 0.25, even though it should be 1. Is there a benefit to this approach in comparison to the average of pairwise cosine similarities?
Comment: @D.Phi my comment "no vector is entirely zeros" was referring to instances like your second case. The Cosine Similarity is similarly undefined for all-zero vectors (i.e. it requires unit vectors, or normalizable ones at least).


Angular.js group by sub property

Question: I have such JSON file:
{
"dates":
[
    {
    "day": "Monday",
    "shifts": [
        {
            "shift-name": "shift 1",
            "assignments": [
                {
                    "position-name": "supervisor",
                    "location-name": "Location 2",
                    "persons": [
                        {
                            "person-name": "USI, ANTHONY RN"
                        }
                    ]
                },
                {
                    "position-name": "driver(s?)",
                    "location-name": "LOCATION 1",
                    "persons": [
                        {
                            "person-name": "LOVELAND, VIVIENNEW"
                        },
                        {
                            "person-name": "LOVELAND, VIVIENNEW"
                        }
                    ]
                }...

And I need to create a loop using this JSON. But I need to make it in a way that all persons are grouping by location-name. But I don't know how to do it as location name could be duplicated. So the structure should be like this:
Date
  Location1
     Shift1
       Supervisors
       Drivers
     Shift2
       Supervisors
       Drivers
  Location2
     Shift1
       Supervisors
       Drivers
     Shift2
       Supervisors
       Drivers

Thank you!
Answer: You need to map this data to a new flatter structure that represents what you want to use it for
Generally the best way to approach something like this is to create a temporary object that uses the common value as keys. Then push items to array(s) based on those keys.
So first you would iterate dates.
Within each iteration of dates create an empty object.
Then you would loop over assignments creating object keys using location-name values as keys.
That object would look something like:
{
   "Location 1":{"supervisors":[], "drivers":[]},
   "Location 2":{"supervisors":[], "drivers":[]}
}

Then as you iterate over persons you use "position-name" to determine which array to push to. That step would look something like:
Finally you iterate that object to create the arrays needed for locations for that date and the dates loop continues and repeats process in next iteration
Answer: For example I take abstract test.json file with your structure. And get the data form XmlHttpRequest:
    var xhr = new XMLHttpRequest();
    xhr.open("GET", 'test.json', true);
    xhr.onload = function(){
        // get result
        var data = JSON.parse(xhr.responseText);
        // result
        var result = {};
        // go loop!
        data.dates.forEach(function(day){
            // check if day exists
            result[day.day] = result[day.day] || {};
            day.shifts.forEach(function(shift){
                shift.assignments.forEach(function(assignment){
                    //check if location exists
                    result[day.day][assignment['location-name']] = result[day.day][assignment['location-name']] || {};
                    // ... if shift exists in this location
                    result[day.day][assignment['location-name']][shift['shift-name']] = result[day.day][assignment['location-name']][shift['shift-name']] || {};
                    // ... if position-name exists in this location -> shift
                    result[day.day][assignment['location-name']][shift['shift-name']][assignment['position-name']] = result[day.day][assignment['location-name']][shift['shift-name']][assignment['position-name']] || [];
                    // ... push persions in position-name array
                    assignment.persons.forEach(function(person){
                        result[day.day][assignment['location-name']][shift['shift-name']][assignment['position-name']].push(person);
                    })
                });
            });
        });
        // print result
        console.log(result)
    };
    xhr.send();

Angular.js group by sub property