What is the right way to analyze a nested design in R?

Question: I know that there are already a host of questions about nested designs but many of them haven't been answered or come from biological domains which I sometimes find hard to transfer to my domain.
I am currently trying to analyse the data from a psychological study. Participants read four statements and indicated how appropriate they found each on a 5-point Likert-scale. But I'll just call the outcome variable "out" and so the content will not distract from the statistical problem at hand.
There are two IVs, one that was varied on three levels between subjects (let's call it "between" and the levels 1, 2 and 3) and one on two levels within subjects ("within" with its levels a and b). The within subjects factor is realised in such a manner that two of the four statements correspond to one of the levels and the other two to the other.
Correspondingly, for every participant, I now have four "out" data points, two for the a statements and two for the b statements, like this (in long format):
subj    between within  item    out
123     1       a       a1      3
123     1       a       a2      4
123     1       b       b1      1
123     1       b       b2      2
124     2       a       a1      5
124     2       a       a2      4
124     2       b       b1      2
124     2       b       b2      3
125     3       a       a1      1
125     3       a       a2      1
125     3       b       b1      2
125     3       b       b2      3

and so on
What is the right way to analyse the effect and interaction of between and within? I assume that the two different a and the two different b statements do not differ systematically but are just two instances of the same thing. Or do I need an additional factor that tells R which of the four statements it is in order to allow for that error? Anyway, I have tried these options:
m1 <- aov(out~between*within+Error(subj/within))
summary(m1)

m2 <- lm(out~between*within+within/subj)
anova(m2)

m3 <- lmer(out~between*within+(between|subj))
Anova(m3)

They produce different results but I'm not entirely sure about which one is right or what the differences are. Could anyone enlighten me on this? I assume this is about fixed and random effects which always gets my head in a twist. I have read other posts about nested designs and I think this one comes nearest. But unfortunately the question ID being nested groups wasn't answered. Any help would be very much appreciated!
Edit:
I greatly appreciate the answers so far! The comments prompted me to read some more tutorials on mixed effects models as well as answers to similar questions. This enables me to clarify my question: I know that I will need to specify random intercepts at least for subjects and probably also the four different items representing the two levels of the within factors. However, I am unsure about the specific fixed/random effects structure I would have to model, and specifically what the maximal model in my case would look like.
Right now, I have tried some code which roughly looks like this:
m1 <- lmer(out ~ between * within + (between|subj) + (within|subj) + (between|within/item))

This is probably wrong on several levels so any feedback would be greatly appreciated! Just for clarity: The item factor has no intrinsic meaning, but both levels of the within factor is realised by two items each (which every participant sees) and I am unsure whether this is relevant to the model.
Apart from the model specification, I am still getting confused about the concepts nested and crossed and which one applies to my setup. Lastly, most of my models fail to converge but that is probably a matter for another question (and has been discussed here in length.)
Comment: @SpookyFM @jona The documentation for `clmm()` on CRAN is out of date, make sure to take a look over at the package on R-Forge. See [this message thread](https://stat.ethz.ch/pipermail/r-sig-mixed-models/2014q3/022593.html) from the R special interest group for mixed models.
Comment: The package "ordinal" does Ordinal Logistic Regression with mixed effects (clmm), which may be apt for Likert ratings.
Comment: I can share my Stan code with you if you want to try that, although I can't promise it's any good.
Comment: @jona Thanks for the reference to Stan which I did not know. I am unsure if I am willing to learn yet another language just yet but maybe your code can still be enlightening to me. I have also updated the question statement so if you could provide any feedback on my model specification (especially your thoughts on what the maximal model would look like in this case), I would be very grateful!
Comment: @jona Thanks for the advice! I had found that package too when googling but wasn't sure about it. I have now tried it but, referring to your comment in the emudrak's answer, it doesn't let me specify random slopes... Do you know any solution for this?
Comment: I just analyzed a Likert ratings experiment using ordered logistic regression in [Stan](http://mc-stan.org), which let me freely estimate slopes for subjects and items. However, setting up a Stan model is a somewhat involved procedure. Alternatively, binomial regression in lmer gave fairly similar results compared to the ordinal regression - maybe you can try doing the biggest mixed model you can build in clmm and compare its results to binomial and/or linear regression using lmer.
Comment: Wait ... are you sure clmm doesn't do random slopes? Because this code worked for me (although it failed to converge):  cmod = clmm(a ~ OA + (OA|S), df, link = c("logit"))
Comment: Hm, it says so in the [documentation](http://cran.r-project.org/web/packages/ordinal/ordinal.pdf). Maybe it's outdated? I'll give it a try, thanks!
Comment: @jona You are right, it computes and even converges for me (which lmer doesn't) but it only gives the parameter estimates, no standard errors, z values or probabilities... However, it does give the error message "Variance-covariance matrix of the parameters is not defined" which I can't interpret.
Answer: As discussed in the comments, here is my Stan model for an Ordered Logistic Regression. It takes long format data (one observation per row) and estimates the following parameters: coefficients for dummy-coded predictors (you can for example use Rs model.matrix) from the matrix preds as fixed effects, and also "maximal" (intercept + slope for all terms plus all interaction) random subject and item effects. It does not estimate or disallow correlated random effects.
It should give you the coefficients for your predictor matrix (in beta) and the cutoff points.
data{
int<lower=2> K;                 // number of outcomes
int<lower=1> n_conds;           // e.g. 32 (5 factors and all interactions)
int<lower=0> n_obs;             // e.g. 12000 (observations)
int A[n_obs];                   // outcomes (e.g. Likert scale rankings, 1-4)
matrix[n_obs,n_conds] preds;    // predictor matrix of 0s and 1s

int<lower=0> Ss;                // e.g. 190 (subjs)
int<lower=0> Is;                // e.g. 2560 (items)

int<lower=0,upper=Ss> S[n_obs]; // subj per observation
int<lower=0,upper=Is> I[n_obs]; // item per observation

}

parameters{

vector[n_conds] r_subj[Ss];     // random effects subject
vector[n_conds] r_item[Is];     // random effects item

real<lower=0,upper=10> sigma_s; // one sigma for all subjs
real<lower=0,upper=10> sigma_i; // one sigma for all items

real<lower=0,upper=10> sigma;   // one sigma for all fixed
ordered[K-1] c;                 // cut points
vector[n_conds] beta;           // fixed effects

}

model {
    sigma ~ cauchy(0,5);        // rather narrow prior for all sigmas
    sigma_s ~ cauchy(0,5);
    sigma_i ~ cauchy(0,5);

    beta ~ normal(0,sigma);     // moderate prior for effects

for (s in 1:Ss)                 // prior for subj rand. eff.
    r_subj[s] ~ normal(0,sigma_s);

for (i in 1:Is)                 // prior for item rand. eff.
    r_item[i] ~ normal(0,sigma_i);

for (n in 1:n_obs)              // loop to estimate using ordered logistic regr.

    A[n] ~ ordered_logistic(  preds[n] * beta           // fixed

                            + preds[n] * r_subj[S[n]]   // random s
                            + preds[n] * r_item[I[n]]   // random i

                        , c);                           // cut points

After you've specified all values asked for in the data part of the code in a list dat, you can run it, e.g. via fit <- stan(model_code = code, data=dat, chains = 0, iter = 10), and print the values via print(fit,"beta").
I can't promise this works as intended, but I've compared it with simple ordinal regression using clmm and "maximal" linear regression using lme4 and the results are qualitatively very similar!
Answer: Your variables for between and subj are completely confounded- every observation for subj=123 has between=1, subj=124 has between=1, etc...
Therefore the between variable is redundant, and including both between and subj in your model is likely causing many of of the problems.
Is there really an independent variable associated with between?  If so, then you have no replication at that level (each between level was tested at only 1 subj), and you can't separate the IV between from the subject random effect.
If the independent variable you called between is just to differentiate subj, let subj do that.
I sugget this code:
m3 <- lmer(out ~ within + (1|subj)

For more information about syntax for specifying nested random effects in lme4, see page 51 of chapter 2 of the book.
Comment: Aren't [random-intercept-only models anti-conservative?](http://idiom.ucsd.edu/~rlevy/papers/barr-etal-2013-jml.pdf) IE., lmer(out ~ within + (within|subj) is better?
Comment: @emudrak Thank you very much for your response! But my sample data was probably misleading: Of course I have more than three subjects so subject 126 would have between = 1 again, 127 would have 2, 128 3, 129 1 again and so on.


C++ code segfaults when compiled -O with Apple's LLVM compiler, but not with g++ -7.2.0

Question: Update: I've created an even more M, but still CVE that reproduces the crash. Summary: removed all use of the Bool* bools_ field in Base class (but it still must be defined or the crash does not happen). Also removed Base::Initialize() and the virtual method Rule from Base and its descendants. New MCVE is attached.
I've managed to create an MCVE for this code and posted it below.
Some descriptive details: the code uses virtual base and derived classes, and certain derived classes that are instantiated have constructors that call a non-virtual method inherited from a "base" class (actually a derived class, but higher up in the inheritance hierarchy than what I am calling the "derived" classes) to initialize "base" class data. That method calls a virtual method that is overridden in the derived classes. I realize that that is a dangerous thing to do, but from my (possibly limited) understanding of C++, it seems like it should work because the body of the derived class constructor does not execute until the "base" class virtual tables are set up. In any case, the segfault does NOT occur during the call to the "base" class's initialization method.
The segfault occurs in the "base" class constructor, and ONLY when the body of the constructor is empty. If I add a debugging line to the constructor to print out when that point is reached, the debugging line is printed out and the code runs normally. My guess is that for some reason the compiler is optimizing away the initializations that should happen before the body of the "base" class's constructor is executed, including the setting up of the vtable.
As the subject line says, this code runs fine when compiled without optimization using either Apple's g++ or g++ 7.2.0, and it runs fine when compiled even -O3 using g++ 7.2.0. It ONLY segfault when compiled -O2 or -O3 with Apple's LLVM implementation of g++. The output of g++ --version for that compiler is:
% /usr/bin/g++ --version

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin17.3.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Content

The MCVE follows.
#include <iostream>

using namespace std;

class OriginalBaseClass {
public:
  OriginalBaseClass(long double data1 = 1, long int data2 = 1) : data1_(data1), data2_(data2) { cout << "In OriginalBaseClass constructor\n"; }
private:
  long double data1_;
  long int data2_;
};

class Base : public virtual OriginalBaseClass {
public:
  Base(long int data1 = 0, long int data2 = 0) : data1_(data1), data2_(data2) { cout << "In Base constructor\n"; }
  virtual ~Base();
private:
  bool* bools_;
  long int data1_;
  long int data2_;
};

Base::~Base()
{
  cout << "In Base destructor\n";
}

class Derived_A : public virtual Base {
public:
  Derived_A() { cout << "In Derived_A constructor\n"; }
};

class Derived_B : public Derived_A {
public:
  Derived_B() : OriginalBaseClass(), Base(4, 1), Derived_A() { cout << "In Derived_B constructor\n"; }
};

int main()
{
  Derived_B Derb;
}

Link to bug report: https://bugreport.apple.com/web/
Reference number 36382481
Comment: "_The source code is too long to post and I cannot reproduce it with a simpler code fragment._" So, try to manufacture [mcve]. If you can't reproduce the issue with smaller code fragment, you are taking out too much of the code (maybe the issue is due to the code you deemed irrelevant?). Typical cause of such issues is undefined behavior somewhere in your code. Can't tell more without, at least, [mcve].
Comment: I recommend you use a debugger to pinpoint the general problem area that results in a segfault then either debug it yourself or extract that into smaller program that successfully crashes and share so we can help you debug
Comment: @PaulMcKenzie Well, this time it seems to be a bug in Clang.
Comment: Hi, and thanks. Is there any debugger other than the one in Xcode that will work with code compiled with Apple's g++? I've tried using the one in Xcode and it simply gets stuck at the "base" class constructor. It won't even step into it - that's one of the reasons I suspect the compiler is essentially optimizing away the constructor.
Comment: Try to compile with -fsanitize=address and run your program. It's available in both clang and gcc. This tool is quite good at catching such kind of problems. Most likely you have undefinded behaviour in your code.
Comment: Well i might be wrong but if the segfault happens at base class constructor then issue is in base class constructor and you can extract that into a new program so it can crash independently
Comment: So to boil everything down -- you have bugs in a big program.  Also, it doesn't matter how many compilers it runs on -- that one compiler that is used extensively throughout the industry that shows the error is what you should be concerned about.
Comment: @fizzixgal -- *I'm looking for pointers on how to figure out if this is an actual bug in my code*  -- These types of issues really can be spotted by an experienced C++ programmer who knows most, if not all of the pitfalls.  If you don't know what to look for, you aren't going to find the problem since everything will look "ok" to you.
Comment: Well, extract a minimal example, even if that minimal example is large. First step is to copy all code together into a single file. If that already "fixes" the issue, you might be violating the One Definition Rule (ODR), for example.
Comment: The beauty of making a MCVE is as you narrow in on isolating the problem code, the bug often jumps out and dances around, mocking you for not spotting it sooner.
Comment: I have managed to create a MCVE for this problem that boils the code down to 72 lines. Is this too long to post here? Assuming not, what is the best way to post it?
Comment: It doesn't seem possible to post a code sample in a comment, and the system won't let me post another question (question limit is 1??)... so I am not sure how to go about posting my MCVE.
Comment: I added the MCVE by editing my original post... sorry for being a bumbling idiot, I'm new to this forum.
Comment: @fizzixgal `if (bools_) delete bools_;` -- 1) Wrong form of `delete`.  It should be `delete []`.  2) There is no need to check for null when issuing a call to `delete[]`.
Comment: @PaulMcKenzie - thanks, corrected with an edit. But that doesn't solve or explain the segfault issue.
Comment: I've updated my MCVE to remove all use of Base::bools_, the Base::Initialize method and the virtual method Base::Rule. This new code still crashes.
Comment: A user on another forum pointed out that the two levels of inheritance are not necessary to make the code crash. Remove the definition of Derived_B and instantiate a Derived_A object instead, and the code will still crash with the latest clang.
Answer: This looks like a bug in Clang caused by invalid generation of unaligned SSE stores. Below is a minimal example based on your code:
struct alignas(16) Base1 { };

struct Base2 : virtual Base1 {
    __attribute__((noinline)) Base2() : data1_(0), data2_(0) { }

    long dummy_, data1_, data2_;
};

struct Base3 : virtual Base2 { };

int main() { Base3 obj; }

This is layout generated by Clang (GCC uses the same layout):
*** Dumping AST Record Layout
         0 | struct Base1 (empty)
           | [sizeof=16, dsize=16, align=16,
           |  nvsize=16, nvalign=16]

*** Dumping AST Record Layout
         0 | struct Base2
         0 |   (Base2 vtable pointer)
         8 |   long dummy_
        16 |   long data1_
        24 |   long data2_
         0 |   struct Base1 (virtual base) (empty)
           | [sizeof=32, dsize=32, align=16,
           |  nvsize=32, nvalign=8]

*** Dumping AST Record Layout
         0 | struct Base3
         0 |   (Base3 vtable pointer)
         0 |   struct Base1 (virtual base) (empty)
         8 |   struct Base2 (virtual base)
         8 |     (Base2 vtable pointer)
        16 |     long dummy_
        24 |     long data1_
        32 |     long data2_
           | [sizeof=48, dsize=40, align=16,
           |  nvsize=8, nvalign=8]

We can see that Base3 is merged with Base1, so they share address. Base2 is instantiated by Base3 and is placed afterwards with 8 byte offset, aligning Base2 instance at 8 bytes, even though alignof(Base2) is 16. This is still correct behavior, since this is the maximum alignment among all member fields in Base2. Alignment inherited from virtual base class Base1 does not need to be preserved, as Base1 is instantiated by derived class Base3 which is responsible for aligning Base1 properly.
The problem is with the code Clang generates:
mov    rbx,rdi ; rdi contains this pointer
...
xorps  xmm0,xmm0
movaps XMMWORD PTR [rbx+0x10],xmm0

Clang decides to initialize both data1_ and data2_ with a single movaps instruction which requires 16 byte alignment, but Base2 instance is only 8-bytes aligned, leading to segfault.
Looks like Clang assumes it can use 16-byte aligned stores because alignof(Base2) is 16, but such assumption is wrong for classes with virtual bases.
If you need a temporary solution, you can disable usage of SSE instructions with -mno-sse flag. Note that this can have performance impact.

Itanium ABI document can be found here: https://refspecs.linuxfoundation.org/cxxabi-1.75.html
It explicitly mentions nvalign:

nvalign(O): the non-virtual alignment of an object, which is the
  alignment of O without virtual bases.

Then there is an explanation on how allocation is done:

Allocation of Members Other Than Virtual Bases
If D is not an empty base class or D is a data member: Start at offset
  dsize(C), incremented if necessary for alignment to nvalign(D) for
  base classes or to align(D) for data members. Place D at this offset
  unless doing so would result in two components (direct or indirect) of
  the same type having the same offset. If such a component type
  conflict occurs, increment the candidate offset by nvalign(D) for base
  classes or by align(D) for data members and try again, repeating until
  success occurs (which will occur no later than sizeof(C) rounded up to
  the required alignment).

Looks like both Clang and GCC honor Itanium ABI, properly aligning Base2 using non-virtual alignment. We can also see that in the record layout dump above.

You can compile your program with -fsanitize=undefined (both GCC and Clang) to get this false-positive warning message at runtime:
main.cpp:29:5: runtime error: constructor call on misaligned address 0x7ffd3b895dd8 for type 'Base2', which requires 16 byte alignment
0x7ffd3b895dd8: note: pointer points here
 e9 55 00 00  ea c6 2e 02 9b 7f 00 00  01 00 00 00 00 00 00 00  02 00 00 00 00 00 00 00  f8 97 95 34

So there are three bugs at the moment. I have reported all of them:

Clang's unaligned movaps bug: https://bugs.llvm.org/show_bug.cgi?id=35901
Clang's sanitizer bug: https://bugs.llvm.org/show_bug.cgi?id=35902
GCC's sanitizer bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83780
Comment: I will definitely bookmark this question / answer. As one of the freak cases where a low-rep newcomer reports a problem and it *actually is a bug in the compiler*. :-D
Comment: Thank you, yes I have gotten this answer also on another board, particularly the hint to compile with -fsanitize=undefined, and verified that the problem is incorrect address alignment. Thank you for the detailed explanation though, that is way beyond the level of my knowledge of assembly code generation. In any case, I submitted a bug report to Apple. The bug reference number is 36382481, in case you would like to add any information, or reference it in your own bug report, if you plan to or have submitted one.
Comment: Found another question on this: https://stackoverflow.com/questions/46474238/misaligned-address-using-virtual-inheritance
Comment: @fizzixgal I am going to submit bug reports to both clang and gcc tomorrow. I will edit the answer and add link to them later.
Comment: 3 compiler bugs, hats off to you!


Show that $\lim_{z\to z_0}|f(z)|=\infty$ if and only if $z_0$ is a pole

Question: Im stuck with this exercise

Let $f$ holomorphic on $U\setminus\{z_0\}$ where $U$ is open. Show that $\lim_{z\to z_0}|f(z)|=\infty$ if and only if $z_0$ is a pole.

One direction is easy to show, Im stuck trying to show that
$$\lim_{z\to z_0}|f(z)|=\infty\implies z_0\text{ is a pole}$$
In particular Im having a hard time to figure how to show that if $\lim_{z\to z_0}|f(z)|=\infty$ then $z_0$ cannot be an essential singularity.
My work so far: if $\lim_{z\to z_0}|f(z)|=\infty$ then $f$ have a non-removable singularity at $z_0$. If $z_0$ would be an essential singularity then I know that (this is my definition of essential singularity) the principal part of the Laurent expansion of $f$ around $z_0$ have infinitely many non-zero coefficients, that is
$$\lim_{z\to z_0}|f(z)|=\lim_{z\to z_0}\left|\sum_{k=1}^\infty c_{-k}(z-z_0)^{-k}\right|\tag1$$
where there are infinitely many $c_{-k}\neq 0$. Then to show that the limit of $(1)$ doesnt exists is enough to show that there is some $\theta\in[0,2\pi)$ such that
$$\lim_{r\to\infty}\left|\sum_{k=1}^\infty c_{-k}e^{ik\theta}r^k\right|<\infty\tag2$$
That is: if there is some linear path $z\to z_0$ such that $\lim_{z\to z_0}|f(z)|<\infty$ we are done. However Im not sure if this approach is useful or not. In any case I get stuck here, I dont have a clue about how to show that $z_0$ cannot be an essential singularity if $\lim_{z\to z_0}|f(z)|=\infty$.
Some help will be appreciated, thank you.

EDIT: I think I see a path for a solution. We can write $\omega_k(\alpha_k)^k$ for $\omega_k\in\mathrm S^1$ and $\alpha_k\in(0,\infty)$ such that $\lim \alpha_k=\infty$ instead of $c_{-k}e^{ik\theta}r^k$ (because $\lim c_{-k}= 0$) what give us great freedom to choose suitable sequences $(\omega_k)$ and $(\alpha_k)$ to try to prove $(2)$.
Indeed, if Im not wrong, choosing $\omega_k=(-1)^k$ we are done.
Comment: You can also prove it with out computing Laurent series.
Answer:
$\lim_{z\to z_0}|f(z)|=\infty$ only if $z_0$ is a pole.

Proof: Suppose $z_0$ is an isolated singularity of $\ f$ such that $\lim_{z\to z_0}|f(z)|=\infty$. Then you can find a $\delta>0$ such that $|f(z)|>1$ for $0<|z-z_0|<\delta$. Thus the function $\frac{1}{f(z)}$ is analytic, bounded and nonzero on that punctured disc and hence $z_0$ is a removable singularity of $\frac{1}{f(z)}$ (by Riemann's theorem). Now consider the function,
$$g(z)=\begin{cases}\frac{1}{f(z)}&  \text{if}\ 0<|z-z_0|<\delta \\0& z=z_0 \end{cases}$$
Then $\ g$ is analytic on that disc and has a zero at $z_0$ (say, of order $m \ge 1$) . Then $g(z)=(z-z_0)^m \phi(z)$, where $\phi$ is analytic and $\phi(z_0) \ne0$. Thus $f(z)=\frac{1}{(z-z_0)^m \phi(z)}$, for $0<|z-z_0|<\delta$.
This shows $z_0$ is a pole of $\ f$ of order m.
Comment: well, I would need to prove that doesnt exists zeros of infinity order. Anyway this is a very interesting (an simple) approach.
Comment: well what do you mean by "zeros of infinity order"?
Comment: that the order of the zero is not finite (you assumed that the order of the zero is finite).
Comment: Zeros of an analytic function is always of finite multiplicity...
Comment: also is not so clear to me that $1/f$ is analytic in the punctured disc
Comment: $f$ is analytic and $f \ne 0$ in $0<|z-z_0|<\delta$, so is $1/f$ except at $z=z_0$... ..where it may have an removable singularity ...
Comment: ah!, I see it. Thank you very for your patience.


Android: How to detect parent tag of XML tags

Question:
Possible Duplicate:
Android: How to get values in under specific xml tags

Hi guys, I want to detect the parent tags of my XML file to download and rename the correct file. I have my code on this link.
Comment: See my suggestion to use Simple XML instead on your other post.
Comment: I think your answer to my other post wasn't saved? It's not there...
Comment: I got an answer to this question [in this link](http://stackoverflow.com/questions/6026916/android-how-to-get-values-in-under-specific-xml-tags/6027016).
Comment: Just look at this blog post. It explains how to use Simple XML in Android: https://massaioli.wordpress.com/2011/04/21/simple-xml-in-android-1-5-and-up/
Answer: If you can select any node in your XML document, you can then use XPath's ancestor  axis to find all ancestors (see http://www.w3schools.com/xpath/xpath_axes.asp). Then test them, and if one doesn't have its own ancestor then it's your root element.


Existe algum plugin que sirva de máscara e validador para horários 24h?

Question: Pesquisei mas só encontrei plugins para hora com "select" e com os horários no formado AM/PM.
Gostaria de um que a pessoa pudesse digitar e ficasse nesse formato:
23:59:59

Answer: Isso é mais ou menos simples de fazer, ou seja uma máscara para inserir : quando se está a inserir numeros.
Pode ser mais complexo para não permitir numeros grandes demais e excluir letras.
Um exemplo simples seria:
document.getElementById('hora').addEventListener('keyup', function(e){
    var str = this.value.split(':').join('');
    if (str.length > 6) str = str.slice(0, 6);
    var formatado = str.match(/.{1,2}/g).join(':');
    this.value = formatado;
});

jsFiddle: http://jsfiddle.net/5hupmfr9/
Essas 4 linhas de código explicadas:

remover : eventuais que hajam na string
tirar o ultimo caractere caso seja longo demais
partir em pedações de dois caracteres e colar de novo com : entre eles
colocar de novo no input
Answer: Veja se isso lhe ajuda:
var time = new Date(params.tweetDate),
h = time.getHours(), // 0-24 format
m = time.getMinutes();

Font:
http://www.javascriptkit.com/jsref/date.shtml
Answer: Utilizei o plugin jQuery-Mask-Plugin: http://igorescobar.github.io/jQuery-Mask-Plugin/
E fiz as validações de horário 24h que eu precisava. Ele não permite 24:59:59, 23:69:59 ou 23:59:69,  por exemplo.


How to translate views infinite scroll Loading message

Question: I have an Arabic website and I have views infinite scroll module to allow ajax paging.

I want to translate Loading the next set of posts.... I have tried to search for it in the translate interface, but I could not find it. I tried to import its *.po file from this link but also I could not find it. I have tried to search among the module views_infinite_scroll files, for that string to change it from the source, but also I could not find.
Answer: I'm using webpal pinteros theme, and it has its own js/views_infinite_scroll.js file, in-which the message could be translated. However, this solution is not suitable for multiple languages sites.


Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3

Question: After a recent migration from Oracle to Postgres and an upgrade from Django 1.2 to 1.3, we began having problems when saving objects to our database. When save() is called no id is returned, this occurs even when saving the standard django auth models through the standard django admin panel ('/admin/auth/user/None/' is returned even though the user was added to the db and had an id).
All our other sites that run off the same db do not have this problem, however they are running either Django 1.1 or 1.2.
We discovered that for new tables created post-migration their sequence had an 'owned by' attribute that was owned by the column that the sequence was on (usually the id column). Altering the 'owned by' attribute fixed the issues we were having in 1.3.
Does anybody know what the under lying cause for this is? We have found a solution if anyone else is having this issue, but we would love to know what caused it.
Comment: I'm having the same issue. Would you mind sharing you're solution? It would be much appreciated.
Comment: @iain-shelvington How did you solve this?
Comment: @Neil All our tables had a primary key of "id" and we ran this SQL for all of our tables.

ALTER SEQUENCE tablename_id_seq OWNED BY tablename.id;
Answer: In postgresql if you own an object you can effectively do anything you want with it. As a result if you are not the owner you will need to grant the user "USAGE" on the sequence.
Postgresql Ownership
Postgresql Grants
Answer: It seems like django probably uses pg_get_serial_sequence to get the sequence associated to the table's column and then currval to get the sequence's current value, but if the sequence is not owned by the table, it's not associated to the column, so it won't work.
The OWNED BY attribute associates a sequence with the given table and column. If a sequence has OWNED BY set to NULL it is essentially a stand-alone sequence, and not really associated in any way to any table or column, and even less associated with a primary key.


Is there a difference in the use of hook_preprocess_HOOK()

Question: Is there a difference in the use of hook_preprocess_HOOK()?
In Drupal 8 when I use :

hook_preprocess_page
hook_preprocess_node
hook_preprocess_block

All my Implements for page, node or block work good.
But when I use hook_preprocess_menu some staff don't want to work, what work in preprocess function up.
For example:
This work perfect
function theme_name_preprocess_page(&$variables) {
  $variables['logopath'] = '/' . drupal_get_path('theme','theme_name') . '/logo.png';
}

But this don't work.
function theme_name_preprocess_menu(&$variables, $hook) {
$variables['logopath'] = '/' . drupal_get_path('theme','theme_name') . '/logo.png';
  }

Comment: Looking your question there is nothing wrong, if doesn't work is because something else is wrong. Are you using the right template for menu (menu.html.twig)?
Comment: What do you mean by _this doesn't work_? What are you expecting it to do and what do you get?
Comment: If you think on my example he print logo.png in page where i write {{logopath}}. Its all work nice on page, node or block but dont work on menu. Its not only example i have some other what dont work on menu.
Comment: Yes I use menu--main.html.twig because I have other meny. I write this code
Comment: That's you doing wrong. Posting an answer.
Comment: Ooo.. I undestend new.  hook_preprocess_menu__main.. :)
Answer: If you use:
function theme_name_preprocess_menu(&$variables, $hook) {
  $variables['logopath'] = '/' . drupal_get_path('theme','theme_name') . '/logo.png';
}

The hook is menu, so Drupal will look for menu.html.twig, if you define any var inside this preprocess you only be able to use in menu.html.twig. Look the Hook at your theme suggestions comments, if you see 'block' you will need use theme_name_preprocess_block instead.
Comment: Thank you a lot. New I understend. I learn new staff in Drupal.
Answer: I think you need to check the file-suggestion by enabling in services.yml debugging, after that you will find the right Hook name. Then you can use....
function theme_name_preprocess_Hook_name(&$variables, $hook) {
  $variables['logopath'] = '/' . drupal_get_path('theme','theme_name') . '/logo.png';
}


Zero-inflated negative binomial mixed-effects model in R

Question: Is there such a package that provides for zero-inflated negative binomial mixed-effects model estimation in R?
By that I mean:

Zero-inflation where you can specify the binomial model for zero inflation, like in function zeroinfl in package pscl: zeroinfl(y~X|Z, dist = "negbin")
where Z is the formula for the zero inflation model;
Negative binomial distribution for the count part of the model;
Random effects specified similar to function lmer of package lme4.

I understand glmmADMB can do all that, except the formula for zero inflation cannot be specified (it is just an intercept, i.e. Z is just 1). But are there any other packages that can do it all?
I will be very thankful for your help!
Comment: As an update, the [glmmTMB](https://cran.r-project.org/web/packages/glmmTMB/index.html) package by Ben Bolker supports a zero-inflated generalized linear mixed
model (ZIGLMM).
Comment: I'm looking for the same thing. I think glmmADMB is what I want, but I can't get it running.
Comment: I'm wondering whether or not the [ZIM](http://cran.r-project.org/web/packages/ZIM/) or [aod](http://cran.r-project.org/web/packages/aod/index.html) packages can do what you want to do?
Answer: I think this is the package you need: glmmADMB.
I downloaded it here: http://otter-rsch.com/admbre/examples/glmmadmb/glmmADMB.html
But I still had some problems to get it to run, so I followed the instructions provided in this link and now it works fine http://glmmadmb.r-forge.r-project.org/
Hope this helps!
Comment: Note that this package only allows the fitting of a constant term for the zero-inflation part of the model.
Answer: The pscl package provides for a zero inflated Poisson model. I don't think that it can do a negative binomial model, but it might be a place to start. The linked JSS article also discusses related packages, which may lead you to what you're looking for.
Comment: The pscl package does (now) allow negative binomial models by using `zeroinfl(..., dist = "negbin", ...)`
Answer: Depending on what you're trying to do, you might want to look at the aster package. Aster models allow joint analysis of multiple variables that have different probability distributions, and recently have been updated to allow for random effects. They were designed for life history analysis and will work in situations where you can split your response into distinct parts with different distributions, (e.g. survival = Bernoulli, reproduction = Poisson). They can handle "zero-inflation" by modeling the majority of zeroes as bernoulli, and the remainder of the response as negative binomial.
You'll find plenty of documentation here:
http://www.stat.umn.edu/geyer/aster/
Answer: There are a lot of packages available. This link might be helpful:
https://journal.r-project.org/archive/2017/RJ-2017-066/RJ-2017-066.pdf


Intersection of finite number of compact sets is compact?

Question: Is the the intersection of a finite number of compact sets is compact? If not please give a counter example to demonstrate this is not true.
I said that this is true because the intersection of finite number of compact sets are closed. Which therefore means that it will be bounded because the intersection is contained by every set. I am not sure if this is correct.
Thank you for the help
Comment: What is your definition of compactness?
Answer: For Hausdorff spaces your statement is true, since compact sets in a Hausdorff space must be closed and a closed subset of a compact set is compact. In fact, in this case, the intersection of any family of compact sets is compact (by the same argument). However, in general it is false.
Take $\mathbb{N}$ with the discrete topology and add in two more points $x_1$ and $x_2$. Declare that the only open sets containing $x_i$ to be $\{x_i\}\cup \mathbb{N}$ and $\{x_1 , x_2\}\cup \mathbb{N}$. (If you can't see it immediately, check this gives a topology on $\{x_1 , x_2\}\cup \mathbb{N}$).
Now $\{x_i\}\cup \mathbb{N}$ is compact for $i=1,2$, since any open cover must contain $\{x_i\}\cup \mathbb{N}$ (it is the only open set containing $x_i$). However, their intersection, $\mathbb{N}$, is infinite and discrete, so definitely not compact.
Comment: As written, that sentence was wrong. There is more than one open cover. However every open cover must contain $\{x_i\}\cup \mathbb{N}$, and hence has a finite subcover consisting of a single set. I've edited the final paragraph to remove this inaccuracy.
Comment: Whether or not the final phrase is "wrong" depends on your precise definition of compactness for a subset. One definition is that a subset is compact if and only if it is compact as a space with the subspace topology. With this definition the final sentence is fine, as $\{x_1, x_2 \} \cup \mathbb{N}$ is not a set in the relevant topology. This definition is clearly equivalent to the definition where one considers covers of the subspace by open sets in the ambient space.
Comment: How is {xi}∪N compact? What is the finite subcover of the only open cover -- itself? You can't cover N with a finite subcover right?
Comment: I think you are confused about what finite cover means. A cover is a collection of sets. It is finite if this collection contains only finitely many sets. It does not mean that the sets in the cover are finite (indeed, as in this case the sets themselves can be infinite).
Comment: The example is quite nice, but the final phrase is wrong. The correct phrase is:  «... since any open cover must contain either {xi}∪N or {x1,x2}∪N (they are the only open sets containing x_i ). » Etc.
Comment: I am sorry I am still confused. Say I take the open cover {xi}∪N, how can you find a finite subcover? If you cannot even cover N with a finite subcover, how can you cover {xi}∪N with one? Thanks
Comment: @verticese The open cover $\{x_i\}\cup\Bbb N$ must contain an open member $U$ with $x_1\in U$. But then necessarily $\Bbb N\subset U$ as well.
Comment: @HagenvonEitzen But then $U$ would be infinite, as $\mathbb{N}$ is. How can it be a finite subcover then?
Comment: @am70 True, but the latter is the whole space and any cover containing it has the obvious singleton subcover so we don't usually take it as part of a cover.
Comment: One can get a slightly nicer example by taking $$\big\{\{x_i\}\cup(\Bbb N\setminus F):F\subseteq\Bbb N\text{ is finite}\big\}$$ as a local base at $x_i$: the resulting space, sometimes called the sequence with two limits, is $T_1$.
Answer: I would like to supply another answer to this interesting question. I learnt the following example in a masters thesis of Cecil Eugene Denney (Kansas State University, 1966). Here is a link to the thesis. What follows below is a modified version of Example 3 in page 27 of the thesis.
Example. Let $X=\{a, b\}$ be a topological space whose only open sets are $\emptyset$ and $X$ itself (so $X$ has the indiscrete topology). Let $Y=\mathbb{R}$ be the set of all real numbers with the standard topology. We will consider the topological space $X\times Y$. Consider the following two subsets of $X\times Y$:
$$
C = \{(a, y): 1\leq y < 3\} \cup \{(b, y): 3\leq y \leq 4\}
$$
and
$$
D = \{(a, y): 2<y \leq 4\} \cup \{(b, y): 1\leq y \leq 2\}.
$$
We claim that $C$ and $D$ are both compact. Indeed, in given any open cover $\mathcal{U}$ for $C$, each open set must be of the form $X\times U$ where $U$ is an open subset of $Y$ (this is where we use the fact that the only open subsets of $X$ are $\emptyset$ and $X$). Using the projection $\pi_Y: X\times Y \to Y$, we note that the collection of all $U$ such that $X\times U\in\mathcal{U}$ forms an open cover of $\pi_Y(C) = [1, 4]$ which is compact. Thus, there are finitely many $U_i$ which cover $[1, 4]$, and consequently finitely many $X\times U_i$ which cover $C$. This shows $C$ is compact, and the verification for compactness of $D$ is identical.
However, $C\cap D = \{(a, y): 2 < y < 3\}$ is homeomorphic, via the projection $\pi_Y$, to the open interval $(2, 3)$ in $Y=\mathbb{R}$, and it is well-known that $(2, 3)$ is not compact.
Answer: The intersection of two compact subsets is not, in general compact. A possible example is $\mathbb R$ with the lower semicontinuity topology, i.e. the topology generated by sets of the form $(a, +\infty)$.
A subset $A\subseteq\mathbb R$ is compact in this topology if it has a minimum. Now, consider $A=[0, 1)\cup(3, +\infty)$ and $B=[2, +\infty)$. Both $A$ and $B$ are compact, but their intersection $A\cap B=(3, +\infty)$ is not.
Notice that the lower semicontinuity topology on $\mathbb R$ is not Hausdorff. As others have pointed out, the intersection of two compact subspaces of a Hausdorff topological space is still compact.
Answer: In a $T_2$ space (Hausdorff), compact subsets are closed. Let  be a $T_2$ space and let $F$ be a family of compact subsets of $S$. To avoid trivial cases  let $F$ have at least one non-empty member $f$.
Now $G=\cap F$ is closed and $G^c=S\backslash G$ is open. If $V$ is a family of open sets with $\cup V\supset G,$ then  $V'=V\cup \{G^c\}$ is an open cover of $f.$ (Indeed, $\cup V'=S.$)
Since $f$ is compact, there exists a finite $H\subset V'$ with $\cup H\supset f.$  Then $H'=H\backslash \{G^c\}$ is a finite subset of $V$,  and $\cup H'\supset G.$
So $G$ is compact.
Note that we needed each member of $F$ to be closed, so that $G$ is closed, so that $G^c$ is open, so that $V'$ is an open family. As an earlier answer shows, if $S$ is not $T_2$ then this can fail.


Implicit differentiation , leibniz notation- problem differential operator notation in multivariable calc

Question: here are three examples of what im finding troublesome in understanding, i can workout the basics by myself but when it comes to iterating the differential operator i find the notation and the process convoluted. My biggest problem is i dont know in which logical step im making the mistake and so i dont know what to search so i can clear my confusion.
example one change the equation $y'' +\frac{2}{x}y'+y=0 $ by taking "$x$ as a function and $t=xy$ for a free variable"
my work- i take $\frac{\mathrm dy}{\mathrm dx}=\frac{\frac{\mathrm dy}{\mathrm dt}}{\frac{\mathrm dx}{\mathrm dt}}=\frac{1}{x\frac{\mathrm dx}{\mathrm dt}}$ but my book solution says $\frac{1}{x\frac{\mathrm dx}{\mathrm dt}}-\frac{1}{x^2}$ and i have no idea why since even if they used the chain rule $\frac{\mathrm d (\frac{t}{x})}{\mathrm dt}$ it would not give the book answer.even if we swapped in $y=\frac{t}{x}$ and then using the chain rule i dont get and extra $t$ as in  $\frac{1}{x\frac{\mathrm dx}{\mathrm dt}}-\frac{t}{x^2}$
example two find $\mathrm d z , \mathrm d^2 z$ given implicit function (1) $\frac{x}{z}=\ln(\frac{z}{y})+1$ so i use the total differential on (1) to get $$\frac{z\mathrm dx-x \mathrm dz}{z^2}=\frac{y}{z}\frac{y \mathrm dz - z \mathrm dy}{y^2}$$   from which by rearranging we can get $\mathrm d z$ $$\mathrm d z=\frac{z(y\mathrm dx+z\mathrm dy)}{y(x+z)}$$ $(x\neq-z)$  by simple algebra manipulation, now we use total derivative on  (2)$$ zy\mathrm dx-xy \mathrm dz -yz \mathrm dz-z^2 \mathrm dy=0$$ to get (book answer gives this)$$y(x+z)\mathrm d^2 z=z\mathrm dx \mathrm dy+(z \mathrm dy - x \mathrm dy)\mathrm dz -y^2 \mathrm dz^2$$ and i dont understand this process at all as by going by partial derivatives i dont get the second derivative to look like that(i dont know how i would use chain rule on for example $yz \mathrm dx=z\mathrm dx\mathrm dz+y\mathrm dx\mathrm dz$ ?) and im confused as to what $\mathrm dz^2$ is supposed to mean rigorously at this point. after rearranging and using $\mathrm dz$ the book answer gives $$\mathrm d^2 z=-\frac{z^2(y\mathrm dx-x\mathrm dy)^2}{y^2(x+z)^3}$$
example three  transform $y'''=\frac{6y}{x^3}$ if new variable is $t=\ln(|x|)$ so i begin to calculate $y'$ as follows $$\frac{\mathrm dy}{\mathrm dx}=\frac{\mathrm dy}{\mathrm dt}\frac{\mathrm dt}{\mathrm dx}=\frac{1}{x}\frac{\mathrm dy}{\mathrm dt}$$ now to calculate the second derivative by t i do as follows $$\frac{\mathrm d^2y}{\mathrm dx^2}=\frac{1}{x}\frac{\mathrm d}{\mathrm dx}\left(\frac{\mathrm dy}{\mathrm dt}\right)=\frac{1}{x}\frac{\mathrm dt}{\mathrm dx}\frac{\mathrm d}{\mathrm dt}\left(\frac{\mathrm dy}{\mathrm dt}\right)=\frac{1}{x^2}\frac{\mathrm d}{\mathrm dt}\left(\frac{\mathrm dy}{\mathrm dt}\right)$$ and i thought that was it but the book solution gives this for the $\frac{\mathrm d}{\mathrm dt}(\frac{\mathrm dy}{\mathrm dt})=\frac{\mathrm d^2 y}{\mathrm dt^2}-\frac{\mathrm dy}{\mathrm dt}$ and i dont get how we got to this by using the  chain rule given the first derivative like so $\frac{(\mathrm dy)'\mathrm dt-\mathrm dy (dt)'}{(\mathrm dt)^2}$
im not sure what im getting wrong and i think i need a bit of "hand holding" so i would beg   please explain where im making the mistake or link me to a book/theory for this. i have no formal knowledge in differential forms or wedge products as im a second year math student.
Answer: Example one. Since $x$ is a function of $t$ and $y$ is a function of $x$, we have
$$
t=x(t)y(x(t))
$$
or
$$
y(x(t))=\frac{t}{x(t)}.
$$
Applying the chain rule, we get
$$
\frac{dy}{dx}\cdot\frac{dx}{dt}=\frac{1\cdot x-t\cdot \frac{dx}{dt}}{x^2}
=\frac1{x}-\frac{t\cdot \frac{dx}{dt}}{x^2}
$$
and
$$
\frac{dy}{dx}=\frac1{x\cdot \frac{dx}{dt}}-\frac{t}{x^2}.
$$
Example two. Technically, the procedure looks like this: the differential from the left and right sides of the equality is taken. The differentials of $dx$ and $dy$ are equal to zero, $d(dz)=d^2z$. We have
$$
zy\, dx-xy \, dz -yz \, dz+z^2 \, dy=0.
$$
The first term, $zy\, dx$, gives us $y \,dx\, dz+z\,dx\, dy$; the second, $xy \, dz$, gives $y\,dx\,dz+x\,dy\,dz+xy\,d^2z$, etc.:
$$
y \,dx\, dz+z\,dx\, dy-(y\,dx\,dz+x\,dy\,dz+xy\,d^2z)
$$
$$
-(z\,dy\,dz+y\, dz^2-yz\,d^2z)+2z\,dy\,dz=0
$$
Example three. Here $x$ is a variable, so you shouldn't treat it like a constant:
$$
\frac{d^2y}{dx^2}=\frac{d}{dx} \left( \frac{1}{x}\cdot\frac{dy}{dt}\right)=
-\frac{1}{x^2}\cdot\frac{dy}{dt}+\frac{1}{x}\cdot\frac{d}{dx} \left( \frac{dy}{dt} \right)
$$
Comment: @bek3711 Yes, definitely.
Comment: @bek3711 By definition $dz^2=(dz)^2$. This should not be confused with $d(z^2)=2z\,dz$.
Comment: just one question, you and me both have an extra $t$ in example one but the book solution gives $\frac{1}{x^2}$ without the t. just a typo in the book?
Comment: and in example two i take the $\mathrm d z^2=(\mathrm d z)^2$ when inserting the first total differential in the second to get the full equation?
Comment: @bek3711 This is a historically established notation.


Ito integral almost sure and $L^2$ limit

Question: why does one define the Ito integral as the $L^2$ limit, although it can be shown by Doob's martingale inequality and Borel-Cantelli lemma that there exists a t continuous version, which is constructed as almost sure limit. So why not define the Ito integral as the continuous almost sure limit?
Thank you in advance
Comment: Why are people voting to close this?  It looks like a perfectly valid question to me.
Answer: The key advantage of Ito integrals is that they are martingales. For this, a.s. convergence would not be enough in general. You don't quite need $\mathcal{L^2}$ convergence, but something almost as strong implying some boundedness. For a reference and good discussion, maybe compare Øksendal; also this question at MathOverflow.
Comment: Thank you for your answer. After the proof, that there exists a continous version of the ito-integral, which is the almost sure limit, Oksendal mentioned that in the further he always considers that continous version. So why cant someone define the ito-integral from the beginning as this continous almost sure limit. As a limit of continous Martingales this almost sure limit is a martingale itself, is it?
Comment: @alL: Not necessarily. If you go through the proofs, you see where he uses the stronger conditions. This, in itself, obviously doesn't show that you couldn't do as you suggest. However, it just won't work in general. To fully use the strength of Ito calculus, a.s. wouldn't be enough.
Comment: I am trying to understand it step by step, I think I miss the hole picture. But I am right, that for example Oksendal uses after the proof that there exists a continous Version of the ito integral, which is constructed as almost sure limit, only uses that one in the further of the book? The question is so remaining: Why not define it from the start like that. I get the feeling that I am overlooking something very fundamental.
Comment: Reformulation of my question: In a manuskript I a use for learning at the moment the ito-integral is defined as the L^2 Limit and after that is stated that the process is continous in t. Is that true? I dont think so. Moreover because the unification of overcountable nullsets must not neccasseraly be a nullset, there even is no correct definition of a ito-integral process as long as we dont take the t continous version. But if we do so, I ask myself again wy we have defined the ito-integral as the L^2 limit at first. Thank you so much for any help!
Comment: @alL: Arguing from Øksendal's book, as I don't have your lecture notes, go to page 35 which is in the preview linked. There is a difference between the limit *being* $t$-continuous, or the limit *having a $t$-continuous version*, as Øksendal states. If you use existence of a limit in a sense differently from how he does this (and how Ito-Integration is introduced in any source I've read), you could not guaranty that the Ito-Isometry and such holds for such limit. Hence, you go the $\mathcal{L^2}$ route, and *pick* an appropriate *version* of the limit. I hope this was of some help.
Comment: Thank you for your help! Would you mind to go to page 33. There is shown that there exists a t-continous version of the ito-integral process (L^2 limit). This picked version is constructed as almost sure limit. Is the following right?: Do one define the Ito-Integral as L^2 limit because it's then possible to show that the picked version (page 33, almost sure limit) is a martingale? Thank you in advance!
Comment: @alL: If I understand you correctly, that is my understanding. As a disclaimer, please do keep in mind that, while something like this was actually my thesis topic, my thesis was over ten years ago, and except for casual reading, I haven't used it much since. But you're on the right track there, alL!
Comment: Thank you for your help. I will examine some proofs deeper to get the hole picture if its neccessary.


Schedule taks with schtask.exe gives error invalid syntax in script

Question: I want to create a scheduled task using C:\Windows\System32\schtasks.exe in a perl script. I'm using the following script:
use strict;
my $createScheduleTask = `SchTasks /Create /SC WEEKLY /D MON,TUE,WED,THU,FRI /TN \"updater\" /TR \"\\\\network\\shared\\updater.bat\" /ST 19:00`;

But I get the following response:
ERROR: Invalid syntax.
Type "SCHTASKS /?" for usage.

When I run the same command in the CLI it works fine (I did remove the escape '\'-s.)
I've tried about every possible combination of escape characters, but I cannot find out what is wrong.
So does anybody know what is wrong or does anybody know how to debug it?
Thanks
Rudy
PS I don't want to use Win32::TaskScheduler since it is not installed on all clients.
Comment: Your code worked fine at my end. I got the following output: `C:\Users\Chankey\Desktop>perl test.pl
SUCCESS: The scheduled task "updater" has successfully been created.`
Comment: Works here, cut and paste error? Permissions problem?
Comment: Change `my $createScheduleTask = \`...\`;` to `my $cmd = qq\`...\`; my $createScheduleTask = \`$cmd\`;`, so you can print the command you actually ran and find the syntax error.
Comment: Ok, on two other machines the script works fine. So I will be blaming it on 'some' machine configuration. Thanks guys.
Answer: This is likely due to the shell that you are running the command from.
I had this problem when running from a bash shell, but when I opened a standard Windows command prompt it runs fine.
Comment: I had the same problem. I was trying to run it through Git's bash shell. Running it through the standard CMD shell solved the problem. Thank you!


Implementing EM clustering for a mixture markov model

Question: I have a mixture Markov model (containing K clusters, or components) that I am trying to train, e.g perform clustering over a set of varying length sequences. Each component of the model is a first order Markov chain. The model is defined by the following:

where

is the model describing behaviour of sequences in the k-th cluster.
Each kth model component(cluster) has initial probability distribution vector (theta_KI) and a transition matrix (theta_tK) - see equation 2. Each sequence seq_i in the set of sequences has a different length L (so the L in the 2nd equation would be different for each sequence in the set).
There is n possible visible states in the model and m sequences in each cluster, and the total amount of sequences is M.
In this case, how would I define e- and m-steps for my EM algorithm? My understanding is that I have to maximize log likelihood function of the model, which would be a sum of likelihoods across all vectors v_i ( synonym with sequence seq_i)-  something like:

However, I get stuck not knowing if this is the right definition for what needs to be maximized and which arguments need to be found for that. I have looked for literature but it is very sparse, almost nonexistent.
Another question: is there actually an R library that has functions that can be extended to include such a model for EM algorithm?
Comment: Please define the notation.
Answer: As you say, the EM is an algorithm aiming at maximizing the log-likelihood of your model.
The fact that the sequences have different lengths is not a problem. To see why let us first assume that you have trained your model. What does this mean?. That you have estimates for the transition probabilities, $\hat{p}(v_{i}|v_{i-1};\theta_{K})$ and for the priors $\hat{p}(c_{K};\theta_{K})$.
How do you perform classification in such a model?
You take your sequence, for example $v_{2}, v_{7}, v_{12}$ and calculate,
$$\mathbf{argmax}_{K} \hat{p}(c_{K};\theta_{K})p(v_{2};\theta_{K}) \hat{p}(v_{7}|v_{2};\theta_{K}) \hat{p}(v_{12}|v_{7};\theta_{K})$$
Hence, whether you have longer or shorter sequences does not change anything substantially. You need the same amount of parameters for each cluster. Which, without further simplification, would be the number of free parameters for the transition matrix, $N*(N-1)$, plus 1 for the prior.
The EM algorithm would be as follows:
start with some values for the transition matrix (you could try generating a random matrix such that corresponds to a transition matrix) and for the $\theta_{i}'s$.

Expectation: estimate the priors. You may do this by calculating the maximum likelihood estimator, i.e. the number of sequences belonging to each cluster divided by the total number of sequences. A sequence belongs to cluster $K$ if $K = \mathbf{argmax}_{j}p(v|c_{j}, \theta)$.
Maximization: based on the resulting assignment of sequences to clusters, estimate the transition probabilities. Here, some smoothing technique, like Laplace smoothing might be necessary in order to ensure numerical stability.

You go on like this until convergence, that is, until the value of the likelihood does not further improve.
Regretfully I am not familiar with R.
Comment: Thank you @juampa for a thorough description. Just to clarify, in step 1 - by priors do you mean the probability that a sequence belongs to cluster c_k? Secondly, how would I calculate argmax in each step? Is by argmax meant the parameters of the given cluster? ( transition probabilities. is there a method to estimate this?
Comment: 1. the probability that the sequence is generated by component $k$ of the mixture, 2. for each cluster you have a set of sequences, from which you estimate the transition probabilities. Notice that for each component, you get different estimattes. When presented a sequence, you calculate the probability of that sequence for each of the clusters, i.e. the probability that the sequence has been generated by each of the components (as in the expression above), and pick up the index corresponding to the component yielding highest probability.
Comment: thank you again for the answer. Perhaps you could suggest a tutorial on Expectation Maximization with regards to Mixed Markov Models with first order Markov Chains? Also, the article that I am using as a guidance, [link here](http://link.springer.com/chapter/10.1007/11589990_16), seems to initialize the model including the assumption that there are k sequences in each cluster. I am not completely understanding how is such a model initialized. Is the first step parameters estimated from the complete dataset as if there is 1 cluster? How would you initialize such a model?


How to find $A_1A_2  + \cdots + A_{2010}  A_{2011}$, where $A_{n+1} = \frac{1}{1+\frac{1}{A_n}}$

Question: My question is:

If $$A_{n+1} = \frac{1}{1+\frac{1}{A_n}}$$ ($n\in\mathbb{N}$) and $A_1=1$, then find the value of:
  $$A_1A_2 + A_2A_3 + A_3A_4 + \cdots + A_{2010}  A_{2011}.$$

Please I would like to get some hints to solve this question.
Comment: Is that supposed to be $$A_{n+1}= \frac{1}{1+\frac{1}{A_n}}$$or $$A_{n+1}=\frac{1}{1} + \frac{1}{A_n}\ ?$$
Comment: Welcome to math.SE. In order to get the best possible answers, it is helpful if you say what your thoughts on it are so far; this will prevent people from telling you things you already know, and help them write their answers at an appropriate level. Also, please provide an answer to Arturo's question about your intended notation - I chose what I assumed you meant, but you need to specify the correct one.
Comment: @ArturoMagidin:The first one is correct
Comment: @ArturoMagidin:I am really sorry as the way I typed my question was very confusing.But I dont know how to write them the way u have wrote.
Comment: @user1396721: You can find guides to using LaTeX [here](http://meta.stackexchange.com/questions/68388/there-should-be-universal-latex-mathjax-guide-for-sites-supporting-it/70559#70559) and [here](http://meta.math.stackexchange.com/questions/480/math-markup-diagrams-etc-pointers-please/484#484)
Answer: Here is a hint: Calculate the first few values of $A_n$; you will notice a clear pattern which you can prove to be true in general with induction. Then, note that
$$\frac{1}{n(n+1)}=\frac{(n+1)-n}{n(n+1)}=\frac{1}{n}-\frac{1}{n+1}.$$
Comment: Zev Chonoles::I observed that:A1=1 , A2=1/2 , A3=1/3...
Comment: :thus An=1/n , An+1=1/n+1.....
Comment: Because
$$\frac{1}{n(n+1)}=\frac{1}{n}-\frac{1}{n+1}$$
as I noted above, we have that
$$A_1A_2=\frac{1}{1}\frac{1}{2}=\frac{1}{1}-\frac{1}{2}$$
$$A_2A_3=\frac{1}{2}\frac{1}{3}=\frac{1}{2}-\frac{1}{3}$$
$$\cdots$$
$$A_{2010}A_{2011}=\frac{1}{2010}\frac{1}{2011}=\frac{1}{2010}-\frac{1}{2011}$$
so that
$$A_1A_2+\cdots+A_{2010}A_{2011}=\frac{1}{1}-\frac{1}{2}+\frac{1}{2}-\frac{1}{3}+\frac{1}{3}-\cdots+\frac{1}{2009}-\frac{1}{2010}+\frac{1}{2010}-\frac{1}{2011}$$
A lot of terms cancel :)
Comment: :Thanks a lot!!! Had great fun:)
Comment: Zev Chonoles:what is induction?
Comment: @user1396721: See [the Wikipedia page](http://en.wikipedia.org/wiki/Mathematical_induction#Description) - it is a fundamental technique of proving mathematical statements. This problem should provide an excellent first experience with it.
Comment: Excellent! Can you use induction to *prove* that, in general, $A_n=\frac{1}{n}$? Note that this involves showing that $A_1=\frac{1}{1}$ (we know that already) and then showing that, **assuming** that $A_k=\frac{1}{k}$ for some $k$, **then** we also have $A_{k+1}=\frac{1}{k+1}$.
Comment: :I did not get what you said.Sorry:(
Comment: Ok fine having aaumed that we have proved An=1/n what can be done next?
Comment: No problem, glad to help! If my answer is satisfactory, you can click the check mark beneath the arrows on the upper left of the answer to accept it.
Comment: Good follow-through, good technique. +1
Answer: Notice that $A_{n+1} = (1+A_n^{-1})^{-1} = A_n/(1+A_n)$, we get $A_{n+1}^{-1} = 1 + A_n^{-1}$, and the recurrence relation $A_{n+1} = (\alpha{}A_n+\beta)/(\gamma{}A_n+\delta)$ where $\gamma\ne0$ can be solved systematically:

Solve the equation $x = (\alpha{}x+\beta)/(\gamma{}x+\delta)$.
If the equation has two distinct roots, say, $x_1$ and $x_2$, the sequence $\big\langle(A_n-x_1)/(A_n-x_2)\big\rangle_{n>0}$ is a geometric progression(AP). Goto 4.
Otherwise, the equation has two same roots, say, $x_0$. The sequence $\big\langle(A_n-x_0)^{-1}\big\rangle$ is an arithmetic progression(GP).
Find a closed-form for the AP or GP, then get the solution of the recurrence.

Some degenerate cases are not discussed, but they're trivial.


Local grocery store just received a large shipment of apples, oranges, pears, and bananas—more than $100$ pieces each.

Question:
Your local grocery store just received a large shipment of apples, oranges, pears, and bananas—more than $100$ pieces each. You are shopping at the store and will purchase your fruit for the week.

$1$. How many ways can you select $10$ pieces of fruit from your store's supply of apples, oranges, pears, and bananas?

Is it like there are more than $400$ fruits in total, so is it $$\binom{400+10-1}{10-1}$$

$2$. How many ways can you select $10$ pieces of fruit from your store's supply of apples, oranges, pears, and bananas if you need at least one piece of each kind of fruit?
Comment: No.  This is a [stars and bars](https://en.wikipedia.org/wiki/Stars_and_bars) problem.
Answer: As stated in the comment, this is a stars and bars problem. The supply of the grocery store is of no concern as long as they have more than your maximum amount for each fruit (10 of each fruit in this case)
Now let o denote a fruit and | denote a bracket. You'll have 10 o as you are going to pick 10 fruits. You'll need only 3 | tho, because 3 separation points are enough to divide into 4 groups.
Now that you have 10 fruits and 3 seperation points, each of the combinations will represent you how much to buy which fruit. for instance;
000|00|00|000 denotes you'll buy 3 of the first fruit 2 of the second 2 of the third and 3 of the 4th.
0000000||000| denotes that you'll get 7 of the first fruit , 3 of the thrid and none of the others.
As you can see we can arrange it in $\frac {13!} {10!.3!}$ = $13 \choose 3$ ways.
For the second part of the question, we need to pre-allocate 1 fruit each to all brackets, so you will have 4 of the 10 fruits already allocated, for the remaining 6 we can use the same method and find that we can choose in $6+3 \choose 3$ = $9 \choose 3 $ ways


setElapsedRealtimeNanos() call in android mock location provider app

Question: I am developing an android app, which will receive the current location and display it on the map with a marker and then will keep updating that in regular intervals. I followed the following tutorials:
Google Maps Android API v2
Retrieving the Current Location
Receiving Location Updates
I wanted to test my app with mock locations so I followed this tutorial:
Testing Using Mock Locations
However, because of Google's confusing documentation despite my best attempts the first approach failed. I was having this issue:
Android LocationClient mock location not set
Then, I decided to use the mock location provider app and discovered that even though the manifest of the downloaded app has android:minSdkVersion="7", it has a SendMockLocationService.java file which has two function calls elapsedRealtimeNanos() and setElapsedRealtimeNanos() which were added in API Level 17. I need to run this mock location provider app in a device with API Level 8. So, I have changed the line:
elapsedTimeNanos = SystemClock.elapsedRealtimeNanos();

to
elapsedTimeNanos = SystemClock.elapsedRealtime()*1000000;

It is not clear to me how to change this line:
mockLocation.setElapsedRealtimeNanos(elapsedTimeNanos);

How can I change the above-mentioned line so that the mock location provider app becomes compatible with API Level 8?
Comment: You wouldn't change that line because you have already changed the value of elapsedTimeNanos.
Answer: I updated the sample project you referenced to build with gradle this evening, and noticed the same issue with the use of setElapsedRealtimeNanos, introduced in API level 17. The app worked fine on my 4.4 device, but would crash with a NoSuchMethodError on my 4.1 device.
I went digging in the source code of the location class to see exactly what changed for API 17. Here's the corresponding diff:
https://android.googlesource.com/platform/frameworks/base/+/2eeeec248a38ff33999c83f4b8d5bab7d50e79d2%5E%21/
If you search for usages of the newly-introduced field mElapsedRealtimeNano, you'll see that its value is only queried in a single spot (+ retained to indicate newly-inserted lines):
+    public boolean isComplete() {
+        if (mProvider == null) return false;
+        if (!mHasAccuracy) return false;
+        if (mTime == 0) return false;
+        if (mElapsedRealtimeNano == 0) return false;
+        return true;
+    }

The newly-introduced notion of a Location being 'complete' is also only used in a single spot:
     public void setTestProviderLocation(String provider, Location loc) {
+        if (!loc.isComplete()) {
+            if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN) {
+                // for backwards compatibility, allow mock locations that are incomplete
+                Log.w(TAG, "Incomplete Location object", new Throwable());
+                loc.makeComplete();
+            } else {
+                throw new IllegalArgumentException(
+                        "Location object not complete. Missing timestamps or accuracy?");
+            }
+        }
+
         // original setTestProviderLocation code is then executed here
     }

Since this validation is missing from the Location class before API 17, the app should work just fine on all API levels >= 7 if you wrap both calls to SystemClock.elapsedRealtimeNanos() in version checks, i.e.
elapsedTimeNanos = SystemClock.elapsedRealtimeNanos();

should be replaced by
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    elapsedTimeNanos = SystemClock.elapsedRealtimeNanos();
}

and
mockLocation.setElapsedRealtimeNanos(elapsedTimeNanos);

should be replaced by
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    mockLocation.setElapsedRealtimeNanos(elapsedTimeNanos);
}

within the SendMockLocationService class. Android Studio will complain that elapsedTimeNanos may not have been initialized - you can safely initialize it with value 0 to resolve this.
With these changes, the app runs fine on my 4.1 device. Let me know if you have any problems on older versions of Android.
Edit: repository for my updated version of the Google sample app.


When creating a new user with a order, how to email the new user login details

Question: I am using Commerce Admin Order Advanced. It allows the following extras when creating an order in Drupal Commerce

Search users by email or profile name before creating the order
Select existing customer profiles before creating the order Validates
Check a new customers email against existing customers to prevent duplicates
Moves customer profiles to the top of the admin order form
Provides copy address profile functionality on the admin order
interface (uses the same settings as the checkout pane for this
feature)

But it also will create a new user with an order, however there is no email sent to the new user with a one time link to login and set a password.
Does anyone know how this could be achieved?
Answer: I have achieved this using Rules
The Rule is as follows.
Events
After updating an existing commerce order
Conditions
Data value is empty - commerce-order:owner:last-login
Actions
Send account e-mail
The reason why I have used this Event rather than 'After creating a new order' is to do with how this 'Commerce Admin Order Advanced' module works. You create the order before adding line items. And since I only need this email to be sent when a certain product type is created, this should suffice, hence I add the following condition
Order contains products of particular product types - Bespoke (an arbitrary product type)
But in order to prevent these emails being sent again should an admin update the order again, I have added the following extra Condition
Data comparison - commerce-order:created == commerce-order-unchanged:changed


Are inverted scales a thing?

Question: Inverted chords are a thing.
But are inverted scales a thing?
What do I mean with that?
A scale is defined by a certain set of notes where one of them is the root key. Playing the root key feels like coming home and most melodies in that scale start with that note.
So let's say in a song I'm using the notes of a certain scale. However, the note that it feels like coming home to and I often start a melody with, is another note than the root key of the scale I'm using.
Could you say I'm using an inverted version of that scale? Is there any other name for it?
Or doesn't it really matter and I'm still using the same scale? If that is the case, wouldn't that mean that C Major and A Minor are not two different scales with the same set of notes, but actually the same scale which just has two different names?
An example:
For now, let's just assume C Major wouldn't exist as a named scale. Yes, weird, but bear with me. However I'm making a song in a scale that would be C Major. Since it has the same notes and I want to be able to communicate what scale I'm using, I'm would say that my song is in A Minor - second inversion.
Of course, it's a bit weird that I'm using a major scale and I'm calling it a minor scale, but I think you understand my point.
Comment: Strictly speaking C major doesn't exist as a named scale, it is a chord. What you are thinking of is C ionian, which is the "root position of the scale" of a total of 7 "inversions" which are the modes. All explained in these good answers below
Answer: We call these rotations (or modes) of a scale. We can rotate any scale such that any member of that scale can be a tonic.
The most common rotations are the seven diatonic church modes (see also this question), where we rotate the major scale to begin on each of its seven pitches.
But you can rotate every scale out there, and there's likely a name for it. Rotating the harmonic minor scale to begin on the fifth scale degree, for instance, creates the Phrygian dominant scale, something very common in Klezmer music.
Answer: There are seven of them. They're called modes. They use exactly the same notes as the 'standard major scale', but are rooted on each of the scale notes. And, there are many tunes which use them.
Let's take C major. CDEFGAB. As it stands, it's the C major scale. But if we reconfigure that abd go from , say D to D, it beecomes D Dorian. the root is  now D, and the sound is minor. The scale now is DEFGABCD.
That same idea carries through with each 'root note'.
Answer: You have a lot of questions in your "question" so I will try and hit on them in order.
So let's say in a song I'm using the notes of a certain scale. However, the note that feels like coming home to and I often start a melody with, is another note than the root key of the scale I'm using. Could you say I'm using an inverted version of that scale? Is there any other name for it? Or doesn't it really matter and I'm still using the same scale?
OK, 3 at a time, here goes: If your home key or tonality is the root of the particular major scale then you are playing just that scale and not an inverted scale. There is no rule stating that melodies have to originate or end on any specific note within a scale. If you are in C major and playing E to E you are still using a C major scale.
There is a name for what you are more or less describing, explore "modes", which is the process of creating 7 different scales from one scale, say a C major scale, by using the 7 different starting notes, i.e. D to D, E to E, etc. In each of these cases though the starting note becomes the new tonality. There are MANY answered questions about modes on this site or you can do an independent search about them.
If that is the case, wouldn't that mean that C Major and A Minor are not two different scales with the same set of notes, but actually the same scale which just has two different names?
C major and A minor are two different scales which contain the exact same notes BUT they have different root notes and are also constructed very differently.
An example: For now, let's just assume C Major wouldn't exist as a named scale...
As for your example, C would be the 3rd inversion of the Am scale, not the 2nd (B is the second) if they were called inversions but this is really about what I mentioned before, "modes". Actually the A minor scale (Aeolian mode) is built on the 6th degree of the C major scale (Ionian mode) Explore modes and I think you will see things more clearly. Here's a wiki article to get you started:
https://en.wikipedia.org/wiki/Mode_(music)
Answer: You mention "inversion" in the context of chords and scales. Inversion means different things depending on the context so I though it might be helpful to list out some examples in notation (which makes it easy to see direction and position) ...including rotation/modes of a scale which I think is the crux of your question.
Chord inversions are about which chord tone is in the bass, regardless of how the tones are distributed in the upper voices...

Rotating through a scale will give you "modes" of a scale, each with a new "tonic" which is the starting/ending - or "home" - tone of the scale...

Finally, inverting (melodic inversion) means to change the interval direction of a melodic line, in other words: playing it upside down...
Comment: Note that the chords shown are all in *closed* position - with the triads having notes as close as possible to each other. Although that's somewhat negated by the errant bass note!
Answer: Like others have said, what the original question stated as "A minor, second inversion" is in fact 2nd rotation. The "melodic" inversion or maybe "horizontal" inversion is an important tool in set class theory. There, you would write a major scale as [0,2,4,5,7,9,E] (E for "eleven"). If you invert that set, you'll get [0,1,3,5,7,8,T] (T for "ten"), which actually is the same as "phrygian".
That "set class inversion" (for my personal lack of a better term) is something totally different than harmonic inversion can be seen by inverting the set class [0,3,7] which represents a minor triad. (with c=0: C, Eb, G) Inverting it gives [5,9,0], (c=0: F, A, C) which is actually the 5th transposition of [0,4,7]: a major triad.
What is referred to as "inversion" of a triad in classical theory is rotation in set class theory, since you don't change the pitch class set content, but the order: [0,4,7] => [4,7,0] => [7,0,4].

Are inverted scales a thing?


Is it possible to preserve long lines in Sphinx?

Question: My restructuredText input file to Sphinx has a long line:
This is a long line text that I want to keep as a long single line. It should not be wrapped in the text output.

Using the text builder of Sphinx, I get this output:
This is a long line text that I want to keep as a long single line. It
should not be wrapped in the text output.

Sphinx wraps the line.
I would like to keep the single long line as is. Is this possible?

Using Line Blocks was suggested in this answer. However using line blocks changes the indentation of the line. I could not find a way to keep the indentation same with Line Blocks.
For input:
Prev Line

| This is a long line text that I want to keep as a long single line. It should not be wrapped in the text output.

Next Line

I get this output:
Prev Line

   This is a long line text that I want to keep as a long single line. It should not be wrapped in the text output.

Next Line

The long line is kept long but it is indented now.

I was not able to find a setting about line wrapping in Sphinx configuration page.

I am using sphinx-build version 1.7.4 and the command I use is:
 sphinx-build -M text "." "_build"

Update:
The code-block directive also indents the long line.
Input:
Prev Line

.. code-block:: text

  This is a long line text that I want to keep as a long single line. It should not be wrapped in the text output.

Next Line

Output:
Prev Line

   This is a long line text that I want to keep as a long single line. It should not be wrapped in the text output.

Next Line

Comment: Perhaps `.. code-block:: text` preceding the long line, with the long line indented? I'm unsure how it will render in text output, but it works well for HTML output.
Comment: @StevePiercy Tried the `code-block` directive. It still indents the long line in the text output. Updated my question with an example. FYI.
Comment: That's not quite correct. The white-space you see is a result of CSS, not actual indentation with space characters. You can use a custom CSS file to override your theme that removes left- and right-padding from the `` tag. See a related answer here: https://stackoverflow.com/a/45501239/2214933
Comment: @StevePiercy I am using the [text builder](http://www.sphinx-doc.org/en/master/builders.html#sphinx.builders.text.TextBuilder) of Sphinx. The output is not html but a raw text file. In that case, are the css files used ?
Comment: Ah, my mistake, I missed that you were using the text builder. I don't know if there is a way to do what you want. I'd suggest asking through Sphinx's support channels.
Answer: Monkey-patching the rendering of line blocks for Text writer works for me:
add this to conf.py
def my_visit_line_block(self, node):
    # type: (nodes.Node) -> None
    self.new_state(indent=0)
    self.lineblocklevel += 1

def setup(app):
    from sphinx.writers.text import TextTranslator
    TextTranslator.visit_line_block = my_visit_line_block

The obvious defect is that it modifies rendering of all line blocks...
I am not familiar enough about sphinx.writers.text (and docutils) to see immediately if there is better way than the above monkey-patching.
I could re-insert indentation via this mark-up:
| \    one
| \    two
| \    three

but being forced to modify mark-up is bad.


Counting (Stars and Bars)

Question: I'm currently preparing for my final in discrete mathematics and encountered what appears to be a stars and bars problem. The problem is framed as follows:

A bowl containing hard candies has 50 cherry pieces, 50 strawberry pieces, 40 orange pieces, and 70 pineapple pieces. All pieces of a flavor are identical. You grab 15 pieces of candy.

The aspect I'm finding challenging is:

How many different handfuls are possible?

I came across a similar question on a forum, but one of the answers involves generating functions, a topic we haven't covered in class, and the top response was a bit unclear.
According to the answer key provided by my professor, the solution is:
$$C(18,15) = 816$$
I'm curious to understand where this comes from, especially since the answer on the forum is different:
$$C(19,4)=3876$$
Could someone please explain how to approach and solve this problem? I'm familiar with binomial coefficients but am unsure about the origin of the number 18 in this context.
Answer: Given that the number of candies of each flavor is greater than or equal to the size of the handful, the amounts in the bowl don't matter.
So you have $4$ choices of flavor, and you want to count how many ways you can select $15$ out of the $4$ possibilities, with repetitions allowed. That's a classic stars-and-bars/combinations-with-repetitions problem. To compute the number of ways of making $k$ choices out of $n$ possibilities with repetitions allowed and where order does not matter is given by
$$\binom{n+k-1}{k}.$$
That's what you professor gave.
The problem you point to is different, because there you have five, not four, flavors available (cherry, strawberry, orange, lemon, and pineapple; your problem does not have lemon flavored candy). That's why the answer is different there. (Also, the first, accepted answer does not use generating functions, so you were not paying very much attention in that post...)
Comment: Thank you for pointing that out. Just to make sure, my `n` would be 15 (size of handful) and my `k` would be 4 (number of flavours)? When would we consider `n` to be the sum of the candies in the bowl and `k` to be "amount getting picked"
Comment: I know the first one does not use generating functions, but the second one does. The first answer wasn't very clear as I am struggling with discrete mathematics at this very moment.
Comment: @Jakob: What's unclear about the first answer? You have 19 places where you can say "no", and you need to pick the $4$ places where you say "no". So that's $\binom{19}{4}$ ways of making those choices. Also, your post says "The answerS involve generating functions." There are two answers, only one of which involves generating functions. So your post is inaccurate.
Comment: I apologise, I was unclear in my question. I will edit it accordingly. And as I mentioned I am struggling with combinatorics and I have a final coming up next week.
Comment: @Jakob See also [this Stars and Bars article](https://brilliant.org/wiki/integer-equations-star-and-bars/) and
[this Stars and Bars article](https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)).

Counting (Stars and Bars)


Composer not autoloading files included through repositories > type > path

Question: The Problem
I have two PSR-4 composer projects and I wish to classes from one in the other, the file structure is as follows:
projectfoo
-public
--index.php
-src
--CompanyName
---Foo
----Foo.php
-composer.json
projectbar
-src
--CompanyName
---Bar
----Bar.php
-composer.json

The composer.json files are defined for projectfoo as (note the repositories > type > path dependency):
{
    "name": "companyname/foo",
    "require": {
        "companyname/bar": "*"
    },
    "repositories": [
        {
            "type": "path",
            "url": "../projectbar"
        }
    ],
    "autoload": {
        "psr-4": {
            "CompanyName\\": "src/CompanyName"
        }
    }
}

And projectbar as:
{
    "name": "companyname/bar",
    "version": "1.0.0",
    "autoload": {
        "psr-4": {
            "CompanyName\\": "src/CompanyName"
        }
    }
}

Running composer update correctly produces the vendor folder containing the companyname/foo folder.
In index.php in projectfoo I have:
require_once '../vendor/autoload.php';

$bar = new \CompanyName\Bar\Bar();

However, when run \CompanyName\Bar\Bar is undefined.

The question
Why is Bar not being included in the autoload.php file?

What I've tried

Refreshing the autoload file using:
composer install
composer update
composer dump-autoload
Changing the vendor name CompanyName to something different.
Looking at the installed.json file in the vendor\composer folder the bar project is listed as:

#
{
    "name": "companyname/bar",
    "version": "1.0.0",
    "version_normalized": "220.127.116.11",
    "dist": {
        "type": "path",
        "url": "../companyname/bar",
        "reference": "f35ed0ad82c8280db9b603712dd256074f99e196",
        "shasum": null
    },
    "type": "library",
    "installation-source": "dist",
    "autoload": {
        "psr-4": {
            "CompanyName\\": "src/CompanyName",
        }
    }
}

Strangely, when bootstrapping the autoload.php file to phpunit the files autoload correctly and are available in my test classes.
Answer: The issue revolves around the way composer links "path" projects using symlinks.

In short
Because I was developing on a windows system and executing the code on an Ubuntu vagrant box the symlinks set up on windows, when running composer install were resolving to broken paths inside the box. This also explains why tests run on windows managed to locate Bar but not tests run in the virtual box.

Solutions
To solve this I initially forced composer to mirror the project rather than symlink it, however, this still caused issues with symlinks in the vendor folder.
I have now started hosting my libraries in seperate repositories and importing them using the "type": "vcs" tag which works well. Composer also handles updating package when new commits are made which doesn't happen when using the "type": "path" tag with mirroring.


Why doesn't deleting a file in TFS and then recreating it wipe out the history?

Question: I wanted to wipe out the history of a file in TFS for a variety of reasons. (For the record, I do realize that that's a somewhat controversial thing to do). I tried deleting the file completely, checking in the deletion, and then re-adding a "fresh" copy of a file with the same name. However, in spite of having successfully checked in the deletion, the recreated file still has all of the history of the old file, as shown below:

I have read other Stack Overflow posts, such as this one (and several others like this), discussing removing the history of a file (either the entire thing or certain parts of it) using the tf utility. However, I'm looking for an easy way to do this from the UI - either Visual Studio itself or the TFS web interface.
How can I do something like this?
Comment: It seems to me it would be pretty poor version control software if it allowed you to accidentally delete a file, check in changes, realize the mistake, and not be able to recover the history after a restore. I don't think there is (or should be) an easy way to do this from within the UI.
Comment: @KenWhite That's a reasonable point - so the answer could be "that's a dumb way to try to wipe out the history in the first place"? Maybe it would be better to try with the `tf` utility after all?
Comment: I think I'd phrase it more as *I don't think it's a reasonable expectation that deleting a file would erase that file's history*. :-)
Comment: Ever try to rename a branch in TFVC?  Bye bye history for the entire branch.
Answer: You're looking for tf destroy. There's no way to do it via the UI.
Comment: The poster indicated he was aware of tf, but was looking for a way to do it from the UI.
Answer: The Source Control Explorer Extension will allow you to enable Destroy in the UI.

see bottom item in the context menu
Answer: Deleting the folder in TFS will only actually perform a "soft delete". The branch will still exist complete with all of its history, except it will be hidden. You could show the deleted items in VS follow this tutorial.
If you want to permanently deletes version-controlled files from Team Foundation version control, need to perform a tf destroy command.
tf destroy [/keephistory] <itemspec1>[;<versionspec>][<itemspec2>...<itemspecN>]
[/stopat:<versionspec>] [/preview] [/startcleanup] [/noprompt] [/silent] [/login:username,[password]] [/collection:TeamProjectCollectionUrl]]

There is not any built-in button or UI designed to quick destroy files in TFS. We suggest you to use some tf command line to achieve this.
Make things complicated is preventing user destroy files/folders accidentally.  Since  tf destory command permanently deletes files from TFS. Use with great caution. There is no recovery.
Besides, even though you don't have to delete a file/folders before destroying it in TFS.  However:

Before you run tf destroy without the /keephistory option, we
  recommend that you first delete the files you want to destroy.
After you delete the files you can synchronize the Team Foundation
  warehouse. Otherwise, the warehouse will not be synchronized with the
  destroyed items.

For more detail information, see Delete Files and Folders from Version Control.
Answer: Since you are dealing with a version control system delete in essence means hiding the file from plain view as the delete action is just another step in the item history. So when you create a file with the same name you are continuing the history of the same file.
As others have indicated you can use tf destroy to remove the file with its history giving you a clean plate for creating a 'new' file.


Is this a theorem (is it correct?)?

Question: My instruction notes have specified a theorem of matrix transpose that be there two compatible matrices $A$ and $B$ in respect of their sums and products, then:
$(AB)^T =A^TB^T$
So I set on to verify if indeed this is correct:
Let $A = \begin{pmatrix}2 & 2 \\ 6 & 4\end{pmatrix}  $
Let $B = \begin{pmatrix}1 & 0 \\ 7 & 3\end{pmatrix}  $
$A^T=\begin{pmatrix}2 & 6 \\ 2 & 4\end{pmatrix}  $
$B^T=\begin{pmatrix}1 & 7 \\ 0 & 3\end{pmatrix}  $
$(AB) = \begin{pmatrix}2 & 6 \\ 2 & 4\end{pmatrix}\begin{pmatrix}1 & 7 \\ 0 & 3\end{pmatrix}$=$\begin{pmatrix}16 & 6 \\ 34 & 12\end{pmatrix}  $
hence $(AB)^T=\begin{pmatrix}16 & 34 \\ 6 & 12\end{pmatrix}$
and....
$A^TB^T=\begin{pmatrix}2 & 6 \\ 2 & 4\end{pmatrix}\begin{pmatrix}1 & 7 \\ 0 & 3\end{pmatrix}=\begin{pmatrix}2 & 32 \\ 2 & 26\end{pmatrix}$
$\therefore (AB)^T\neq A^TB^T $
Is the theorem wrong or am having a rough time understanding?
Comment: The $\alpha$ has to be a *scalar* (i.e. a number). For matrices, $(AB)^T = B^TA^T$.
Comment: As I already said, it should be $(AB)^T = B^TA^T$.
Comment: @mrf, sorry I got mixed up on the theorem. The correct one has been specified.
Answer: The assertion is false; what is true is that
$$
(AB)^T=B^TA^T
$$
which can be easily proved. Actually, the product $A^TB^T$ need not be defined when the product $AB$ is defined, so the equality doesn't make sense unless both matrices are square. However, the equality doesn't generally hold in this case.
Let's see what happens if you also have, for two square matrices, $(AB)^T=A^TB^T$:
\begin{gather}
A^TB^T=B^TA^T\\
(A^TB^T)^T=(B^TA^T)^T\\
(B^T)^T(A^T)^T=(A^T)^T(B^T)^T\\
BA=AB
\end{gather}
Conversely, it's obvious that from $AB=BA$ you can deduce $(AB)^T=A^TB^T$.
So the equality you read in your instructions is wrong.

Is this a theorem (is it correct?)?


Como uma aplicação Ionic se conecta a um servidor?

Question: Criando uma Calculadora Cliente/Servidor Mobile

Crie uma calculadora em que o usuário digite dois números e submeta
para um servidor calcular
O servidor irá fazer o cálculo e sua aplicação irá mostra o resultado
para o usuário
O servidor já está implementado aqui:
https://www.fernandoxavier.com.br/ensino/calculadora/calculo.php
Esse servidor espera dois valores via GET (x e y) e retorna a soma
deles.
Um exemplo de requisição seria:
https://www.fernandoxavier.com.br/ensino/calculadora/calculo.php?x=10&y=9
Logo, a sua tarefa será criar apenas o lado do cliente usando Ionic

Já criei o app em ionic, mas como jogo a url desse servidor no meu código?
Pelo que eu entendi, tenho que importar uma API de HTTP, e instalar um provider... Mas como faz isso?
Answer: Amigo, é bem simples. Basta importar a bilioteca Native Http do ionic e fazer as requisições ao sevidor necessário.
Documentação Ionic
Exemplo:
<code>import { HTTP } from '@ionic-native/http';

constructor(private http: HTTP) {}
this.http.get('http://enderecoservidor.io', {}, {})
  .then(data => {

    console.log(data.status);
    console.log(data.data); // data received by server
    console.log(data.headers);

  })
</code>


Combine modular with the blog in Grav

Question: I'm trying to achieve something in Grav, but I cannot wrap my head around the logic.
I have a blog in Grav, which works great. I put these pages below the blog and the different posts are displayed like I want to.
Now I want to add a module, a simple form, where users can leave their name and email address so they get a notification with a new post.
But I checked the docs, and it looks like you cannot combine these pages and modular pages or do I miss something here?
Or do you need to do this manually and is it not possible with the admin Grav plugin?
Answer: To create a form follow the docs here. Make sure that the definition of the form is within the frontmatter of the blog page file, which is actually displayed. Within the template file just use:
<code>{% include "forms/form.html.twig" with { form: forms('<the name of the form>') } %}
</code>
Comment: Thanks this is the answer

Combine modular with the blog in Grav


JFXTextField is not a valid type. Erro ao iniciar o aplicativo em JavaFX

Question: Estou utilizando uma lib em JavaFX para estilização, e uma das estilizações que estou utilizando é o JFXTextField, porém, ao compilar o aplicativo, eu me deparo com este erro:

JFXTextField is not a valid type

Qual a solução? Grato.
Comment: Isso é um erro de compilação. Você está utilizando JFoenix? Se sim, você colocou o `import com.jfoenix.controls.JFXTextField;`?
Comment: Boa noite Victor, isso mesmo, estou utilizando o JFoenix, e realmente este era o problema, apesar de ter baixado o .jar, precisei realizar este import, Obrigado!!.
Comment: @VictorStafusa Acho que você poderia publicar uma resposta para essa pergunta, já que o seu comentário resolveu o problema.
Comment: @FagnerFonseca Feito.
Answer: Aparentemente, você está ussando o JFoenix.
Isso é um erro de compilação. Você esqueceu de colocar isso:
<code>import com.jfoenix.controls.JFXTextField;
</code>


How do I use a pre-set list of choices from a foreign key as the options to select from in a ModelForm in Django?

Question: I have 2 models, one is a profile user model and the other for categories of that profile. (see below). The category model has one 'name' attribute which consists of a  set of choices that users must choose as their profile type.
class DkUser(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    category=models.ForeignKey(Category, blank=True, null=True)

CATEGORIES = (
             ('cat1', 'Category1'),
             ('cat2', 'Category2'),
             ('cat3', 'Category3'),
             )

class Category(models.Model):
    name=models.CharField(max_length=100, choices=CATEGORIES)

My form thus far:
class ProfileForm(forms.ModelForm):
  category = forms.ChoiceField()
  class Meta:
        model = DkUser
        fields = ('category')

What I'm trying to do is to include a drop-down choice-field on the form that allows users to select one of 'category 1', 'category 2' or 'category3'.
I've looked at ModelChoiceField, but that appears to be for choosing from the Model Instances.
How might I achieve this? All help greatly appreciated.
Comment: You're trying to edit the `Category` model from a form for `DkUser`. Are you sure you don't want to just select a category for the user instead?
Answer: I believe you don't need to have a ProfileForm defined, and what you need is to have a str method for your Category model, and django will do everything for you. As far as i know following should work as you want:
class DkUser(models.Model):
   user = models.OneToOneField(settings.AUTH_USER_MODEL)
   category=models.ForeignKey(Category, blank=True, null=True)

CATEGORIES = (
         ('cat1', 'Category1'),
         ('cat2', 'Category2'),
         ('cat3', 'Category3'),
  )

class Category(models.Model):
   name=models.CharField(max_length=100, choices=CATEGORIES)

def __str__(self):
    return self.name

And on Admin page you should see a combo-box for category field for DKUser model.
Comment: That doesn't seem to work for me, it is associating the the Category model with the DkUser Model, but I think what I need to do is to actually create instances of each of those categories in order for it to have something to choose from. Is there a way to initialize each of the CATEGORY choices within the model and then repeatedly select from those initialized models?
Comment: Django Admin will add the + button near the category field, when you look to DkUser. So you can add a view. But let me ask in this case why you need to have separate model for Category? why you just not keep it only in single model DkUser and provide a list of Categories directly instead of foreignkey