Why do linear regression and ANOVA give different $p$-value in case of considering interaction between variable?

Question: I was trying to fit one time-series data (without replicates) using regression model.
The data looks like follows:
> xx.2
          value time treat
    1  8.788269    1     0
    2  7.964719    6     0
    3  8.204051   12     0
    4  9.041368   24     0
    5  8.181555   48     0
    6  8.041419   96     0
    7  7.992336  144     0
    8  7.948658    1     1
    9  8.090211    6     1
    10 8.031459   12     1
    11 8.118308   24     1
    12 7.699051   48     1
    13 7.537120   96     1
    14 7.268570  144     1

Because of lack of replicates, I treat the time as continuous variable. Column "treat" shows the case and control data, respectively.
First, I fit the the model "value  = time*treat" with "lm" in R:
summary(lm(value~time*treat,data=xx.2))

Call:
lm(formula = value ~ time * treat, data = xx.2)

Residuals:
     Min       1Q   Median       3Q      Max
-0.50627 -0.12345  0.00296  0.04124  0.63785

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  8.493476   0.156345  54.325 1.08e-13 ***
time        -0.003748   0.002277  -1.646   0.1307
treat       -0.411271   0.221106  -1.860   0.0925 .
time:treat  -0.001938   0.003220  -0.602   0.5606

The pvalue of time and treat is not significant.
While with anova, I got different results:
 summary(aov(value~time*treat,data=xx.2))
            Df Sum Sq Mean Sq F value Pr(>F)
time         1 0.7726  0.7726   8.586 0.0150 *
treat        1 0.8852  0.8852   9.837 0.0106 *
time:treat   1 0.0326  0.0326   0.362 0.5606
Residuals   10 0.8998  0.0900

The pvalue for time and treat changed.
With linear regression, if I am right, it means the time and treat has no significant influence on value, but with ANOVA, it means time and treat has significant influence on value.
Could someone explain to me why there is difference in these two methods, and which one to use?
Comment: You may want to look up the different kinds of sums of squares. Specifically, I believe linear regression returns type III sum of squares, while anova returns a different kind.
Comment: If you save the results of `lm` and `aov` you can check they produce identical fits; e.g., compare their residuals with the `residuals` function or examine their coefficients (the `$coefficients` slot in both cases).
Answer: Peter Ellis' answer is excellent, but there is another point to be made. The $t$-test statistic (and its $p$-value) is a test of whether $\beta = 0$. The $F$-test on the anova() printout is whether the added variable significantly reduces the residual sum of squares.
The $t$-test is order-independent, while the $F$-test is not. Hence Peter's suggestion that you try the variables in different orders. It is also possible that variables significant in one test may not be significant in the other (and vice-versa).
My sense (and other contributors are welcome to correct me) is that when you're trying to predict phenomena (as in a systems application), you are most interested in reducing variance with the fewest predictors, and therefore want the anova() results. If you are trying to establish the marginal effect of $X$ on $y$, however, you will be most concerned with significance of your particular $\beta$ of interest, and all other variables will just control for alternate explanations your peer reviewers will try to find.
Comment: "The F-test on the anova() printout is whether the added variable significantly reduces the residual sum of squares." Would you mind telling me what is the mathematically written $H_0$ in this case?
Comment: I believe it could be written like $h_0: RSS_\beta = RSS_{\beta'}; h_a: RSS_\beta < RSS_{\beta'}$
Answer: The fit for lm() and aov() are identical but the reporting is different.  The t tests are the marginal impact of the variables in question, given the presence of all the other variables.  The F tests are sequential - so they test for the importance of time in the presence of nothing but the intercept, of treat in the presence of nothing but the intercept and time, and of the interaction in the presence of all the above.
Assuming you are interested in the significance of treat, I suggest you fit two models, one with, and one without, compare the two by putting both models in anova(), and use that F test.  This will test treat and the interaction simultaneously.
Consider the following:
> xx.2 <- as.data.frame(matrix(c(8.788269, 1, 0,
+ 7.964719, 6, 0,
+ 8.204051, 12, 0,
+ 9.041368, 24, 0,
+ 8.181555, 48, 0,
+ 8.041419, 96, 0,
+ 7.992336, 144, 0,
+ 7.948658, 1, 1,
+ 8.090211, 6, 1,
+ 8.031459, 12, 1,
+ 8.118308, 24, 1,
+ 7.699051, 48, 1,
+ 7.537120, 96, 1,
+ 7.268570, 144, 1), byrow=T, ncol=3))
> names(xx.2) <- c("value", "time", "treat")
>
> mod1 <- lm(value~time*treat, data=xx.2)
> anova(mod1)
Analysis of Variance Table

Response: value
           Df  Sum Sq Mean Sq F value  Pr(>F)
time        1 0.77259 0.77259  8.5858 0.01504 *
treat       1 0.88520 0.88520  9.8372 0.01057 *
time:treat  1 0.03260 0.03260  0.3623 0.56064
Residuals  10 0.89985 0.08998
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
> mod2 <- aov(value~time*treat, data=xx.2)
> anova(mod2)
Analysis of Variance Table

Response: value
           Df  Sum Sq Mean Sq F value  Pr(>F)
time        1 0.77259 0.77259  8.5858 0.01504 *
treat       1 0.88520 0.88520  9.8372 0.01057 *
time:treat  1 0.03260 0.03260  0.3623 0.56064
Residuals  10 0.89985 0.08998
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
> summary(mod2)
            Df Sum Sq Mean Sq F value Pr(>F)
time         1 0.7726  0.7726   8.586 0.0150 *
treat        1 0.8852  0.8852   9.837 0.0106 *
time:treat   1 0.0326  0.0326   0.362 0.5606
Residuals   10 0.8998  0.0900
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
> summary(mod1)

Call:
lm(formula = value ~ time * treat, data = xx.2)

Residuals:
     Min       1Q   Median       3Q      Max
-0.50627 -0.12345  0.00296  0.04124  0.63785

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  8.493476   0.156345  54.325 1.08e-13 ***
time        -0.003748   0.002277  -1.646   0.1307
treat       -0.411271   0.221106  -1.860   0.0925 .
time:treat  -0.001938   0.003220  -0.602   0.5606
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.3 on 10 degrees of freedom
Multiple R-squared: 0.6526,     Adjusted R-squared: 0.5484
F-statistic: 6.262 on 3 and 10 DF,  p-value: 0.01154

Comment: Thanks for thorough explanation, it reminds me of the ANCOVA (analysis of covariance). The first step of ANCOVA is to test the interaction between categorical factor and covariate to see if they have identical slope for both condition. It is quite similar to what I did here. In ANCOVA, it gives same pvalue for interaction in t-test and F-test since  interaction is the last term in `aov`.
Answer:
The difference has to do with the type pairwise comparisons of cascading models.
Also, the aov() function has an issue with how it chooses the degrees of freedom. It seems to mix two concepts: 1) the sum of squares from the stepwise comparisons, 2) the degrees of freedom from an overall picture.

PROBLEM REPRODUCTION
> data <- list(value = c (8.788269,7.964719,8.204051,9.041368,8.181555,8.0414149,7.992336,7.948658,8.090211,8.031459,8.118308,7.699051,7.537120,7.268570), time = c(1,6,12,24,48,96,144,1,6,12,24,48,96,144), treat = c(0,0,0,0,0,0,0,1,1,1,1,1,1,1) )
> summary( lm(value ~ treat*time, data=data) )
> summary( aov(value ~ 1 + treat + time + I(treat*time),data=data) )

SOME MODELS USED IN THE EXPLANATION
#all linear models used in the explanation below
> model_0                      <- lm(value ~ 1, data)
> model_time                   <- lm(value ~ 1 + time, data)
> model_treat                  <- lm(value ~ 1 + treat, data)
> model_interaction            <- lm(value ~ 1 + I(treat*time), data)
> model_treat_time             <- lm(value ~ 1 + treat + time, data)
> model_treat_interaction      <- lm(value ~ 1 + treat + I(treat*time), data)
> model_time_interaction       <- lm(value ~ 1 + time + I(treat*time), data)
> model_treat_time_interaction <- lm(value ~ 1 + time + treat + I(treat*time), data)

HOW LM T_TEST WORKS AND RELATES TO F-TEST
# the t-test with the estimator and it's variance, mean square error, is
# related to the F test of pairwise comparison of models by dropping 1
# model parameter

> anova(model_treat_time_interaction, model_time_interaction)

Analysis of Variance Table

Model 1: value ~ 1 + time + treat + I(treat * time)
Model 2: value ~ 1 + time + I(treat * time)
  Res.Df     RSS Df Sum of Sq      F  Pr(>F)
1     10 0.89985
2     11 1.21118 -1  -0.31133 3.4598 0.09251 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

> anova(model_treat_time_interaction, model_treat_interaction)

Analysis of Variance Table

Model 1: value ~ 1 + time + treat + I(treat * time)
Model 2: value ~ 1 + treat + I(treat * time)
  Res.Df     RSS Df Sum of Sq      F Pr(>F)
1     10 0.89985
2     11 1.14374 -1   -0.2439 2.7104 0.1307

> anova(model_treat_time_interaction, model_treat_time)

Analysis of Variance Table

Model 1: value ~ 1 + time + treat + I(treat * time)
Model 2: value ~ 1 + treat + time
  Res.Df     RSS Df Sum of Sq      F Pr(>F)
1     10 0.89985
2     11 0.93245 -1 -0.032599 0.3623 0.5606

> # which is the same as
> drop1(model_treat_time_interaction, scope  = ~time+treat+I(treat*time), test="F")

Single term deletions

Model:
value ~ 1 + time + treat + I(treat * time)
                Df Sum of Sq     RSS     AIC F value  Pr(>F)
<none>                       0.89985 -30.424
time             1  0.243896 1.14374 -29.067  2.7104 0.13072
treat            1  0.311333 1.21118 -28.264  3.4598 0.09251 .
I(treat * time)  1  0.032599 0.93245 -31.926  0.3623 0.56064
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

HOW AOV WORKS AND CHOOSES DF IN F-TESTS
> #the aov function makes stepwise additions/drops
>
> #first the time, then treat, then the interaction
> anova(model_0, model_time)

Analysis of Variance Table

Model 1: value ~ 1
Model 2: value ~ 1 + time
  Res.Df    RSS Df Sum of Sq      F  Pr(>F)
1     13 2.5902
2     12 1.8176  1    0.7726 5.1006 0.04333 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

> anova(model_time, model_treat_time)

Analysis of Variance Table

Model 1: value ~ 1 + time
Model 2: value ~ 1 + treat + time
  Res.Df     RSS Df Sum of Sq      F   Pr(>F)
1     12 1.81764
2     11 0.93245  1    0.8852 10.443 0.007994 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

> anova(model_treat_time, model_treat_time_interaction)

Analysis of Variance Table

Model 1: value ~ 1 + treat + time
Model 2: value ~ 1 + time + treat + I(treat * time)
  Res.Df     RSS Df Sum of Sq      F Pr(>F)
1     11 0.93245
2     10 0.89985  1  0.032599 0.3623 0.5606

>
> # note that the sum of squares for within model variation is the same
> # but the F values and p-values are not the same because the aov
> # function somehow chooses to use the degrees of freedom in the
> # complete model in all stepwise changes
>

IMPORTANT NOTE
> # Although the p and F values do not exactly match, it is this effect
> # of order and selection of cascading or not in model comparisons.
> # An important note to make is that the comparisons are made by
> # stepwise additions and changing the order of variables has an
> # influence on the outcome!
>
> # Additional note changing the order of 'treat' and 'time' has no
> # effect because they are not correlated

> summary( aov(value ~ 1 + treat + time +I(treat*time), data=data) )

        Df Sum Sq Mean Sq F value Pr(>F)
treat            1 0.8852  0.8852   9.837 0.0106 *
time             1 0.7726  0.7726   8.586 0.0150 *
I(treat * time)  1 0.0326  0.0326   0.362 0.5606
Residuals       10 0.8998  0.0900
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

> summary( aov(value ~ 1 + I(treat*time) + treat + time, data=data) )

                Df Sum Sq Mean Sq F value  Pr(>F)
I(treat * time)  1 1.3144  1.3144  14.606 0.00336 **
treat            1 0.1321  0.1321   1.469 0.25343
time             1 0.2439  0.2439   2.710 0.13072
Residuals       10 0.8998  0.0900
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

> # This is an often forgotten quirck
> # best is to use manual comparisons such that you know
> # and understand your hypotheses
> # (which is often forgotten in the click and
> #     point anova modelling tools)
> #
> # anova(model1, model2)
> #     or use
> # stepAIC from the MASS library

Answer: The above two answers are great, but thought I'd add a bit more.  Another nugget of information can be gleaned from here.
When you report the lm() results with the interaction term, you're saying something like: "treat 1 is different than treat 0 (beta != 0, p=0.0925), when time is set to the base value of 1".  Whereas the anova() results (as previously mentioned) ignore any other variables and concerns itself only with differences in variance.
You can prove this by removing your interaction term and using a simple model with only two main effects (m1):
> m1 = lm(value~time+treat,data=dat)
> summary(m1)

Call:
lm(formula = value ~ time + treat, data = dat)

Residuals:
     Min       1Q   Median       3Q      Max
-0.54627 -0.10533 -0.04574  0.11975  0.61528

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  8.539293   0.132545  64.426 1.56e-15 ***
time        -0.004717   0.001562  -3.019  0.01168 *
treat       -0.502906   0.155626  -3.232  0.00799 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2911 on 11 degrees of freedom
Multiple R-squared:   0.64, Adjusted R-squared:  0.5746
F-statistic: 9.778 on 2 and 11 DF,  p-value: 0.003627

> anova(m1)
Analysis of Variance Table

Response: value
          Df  Sum Sq Mean Sq F value   Pr(>F)
time       1 0.77259 0.77259  9.1142 0.011677 *
treat      1 0.88520 0.88520 10.4426 0.007994 **
Residuals 11 0.93245 0.08477
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

In this case we see that the reported p-values are the same; that's because in the case of this simpler model,
Comment: One should also add that `summary(lm)` and `anova(lm)` will not always give identical result if there is no interaction term. It just so happens that in these data `time` and `treat` are orthogonal and so type I (sequential) and III (marginal) sums of squares yield identical results.
Comment: This answer unfortunately looks unfinished. Still +1 for the link and for mentioning that the effect is due to different coding schemes.


CRM Report Miscalculating columns

Question: I have created a custom column, in a CRM report, and the column sometimes does not calculate the answer correctly.
See Attached image: https://i.stack.imgur.com/l3D4J.jpg
The left column is: =CDbl(Sum(Fields!ask_totalduration.Value/60)).ToString("N1", Microsoft.Crm.Reporting.RdlHelper.ReportCultureInfo.GetCultureInfo(Parameters))
The Middle column is: =Fields!ask_response.Value
The right column is: =iif(Fields!ask_response.Value>Fields!ask_totalduration.Value, "Time Met", "Time not Met")
As seen in the picture, something is not working properly, but I am unable to figure it out.
Thanks Joe
Comment: I have now got it to format in 2 decimal places. I am still however unable to get it to show the correct output! See attached screenshot: http://imgur.com/IijkmL3   (Sorry I don't have enough points to post images)
Comment: This still appears to be an issue. I unable to find how to solve it. http://imgur.com/zvt6LYu     (If the left column is lower than the right it should display a message saying Time Met, otherwise display the message Time not met.
Comment: I have now located the problem to be the decimal numbers. It is not looking at the decimal numbers while calculating.
Answer: Looks like it might be a type coercion issue.
Try changing your formula to this:
=IIf(CDbl(Fields!ask_response.Value) > CDbl(Fields!ask_totalduration.Value), "Time Met", "Time not Met")
This will ensure no implicit conversions are being performed.
Answer: If you want to keep it simple you can use below formula since you have only 2 decimal points.
iif(Fields!ask_response.Value *100 >Fields!ask_totalduration.Value *100, "Time Met", "Time not Met")

CRM Report Miscalculating columns


Changing dockers port in docker-compose has no effect on containerized java app

Question: Assuming, that this is true:
 service port:container port
         8081:8080

The application starts on port 8080, according to its startup logs (see below).
Now I changed the ports to 8083:8083, expecting that the service port and container port both will be 8083.
After changing the port in the docker compose I redeploy it using docker stack deploy -c docker-compose.yml somename
When I do another docker ps I see that the container is still running on port 8080.

Containerized java app startup logs:

2019-02-24 17:06:00.665  INFO 1 --- [           main] c.l.a.ArticleServiceApplication          : Starting ArticleServiceApplication v0.0.1-SNAPSHOT on 42ccc7a1554c with PID 1 (/articleservice-0.0.1-SNAPSHOT.jar started by root in /)
2019-02-24 17:06:00.748  INFO 1 --- [           main] c.l.a.ArticleServiceApplication          : No active profile set, falling back to default profiles: default
2019-02-24 17:06:30.505  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-02-24 17:06:32.601  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 1643ms. Found 1 repository interfaces.
2019-02-24 17:06:48.016  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$33ba8b8e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-02-24 17:07:01.769  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)

docker-compose file:

version: "3"
services:
  articleservice:
    image: elps/articleservice:126.96.36.199
    deploy:
      replicas: 2
      restart_policy:
        condition: on-failure
      placement:
        constraints:
          - node.role == manager
    ports:
      - "8081:8080"
...

Answer: Internally, during startup time, your Java app needs to be told that it should start up on port 8083 - simply putting it in the port forward config won't do the trick since the java application startup is isolated from how you want to configure your containers to get started up.
Usually, for most OSS applications, there should be some environment variable that you can set to make the Java application start up on a certain host/port (inside the container network interface, which is different from that on the host).
After that, if you have 8080:8083, that means that you are wanting to forward the container's port 8083 to your host system's port 8080.


How do I solve this sum of series problem?

Question: I'm studying for a test, I chose a random question and this one came out. How do I solve it? What does it do? Thanks!
Comment: Where did you run into trouble applying the extremely detailed instructions in your question?
Comment: Follow the instruction and proceed. Find the representation of $1/(1-x)$ which very common.
Comment: I didnt know the geometric series way of 1/(1-x).
Answer: The question basically gives you the steps on how to solve for the sum.Start with $1/(1-x) = 1 + x + x^2 + x^3 +......  $
Differentiate: $$[1/(1-x)]' = 1/(1-x)^2 = 1 + 2x + 3x^2 +.... $$
Multiply by x:$$x/(1-x)^2 = x+ 2x^2 + 3x^3 + ..... $$
Differentiate again:$$[x/(1-x)^2]' = (1+x)/(1-x)^3 = 1 + 4x + 9x^2 + 16x^3 +..... $$
Multiply by x again:$$x(1+x)/(1-x)^3 = x + 4x^2 + 9x^3 + 16x^4 +..... $$
So when $x = \frac12$, $\frac12(1+\frac12)/(1-\frac12)^3=6$
Comment: Thanks! I know, but I didnt know the 1/(1-x) as a geometric series.
Answer: Hint
Write the series as $$S=\sum_{n=0}^\infty n^2 x^n=\sum_{n=0}^\infty (n(n-1)+n) x^n=x^2\sum_{n=0}^\infty n(n-1) x^{n-2}+x\sum_{n=0}^\infty n x^{n-1}$$ So $$S=x^2\Big(\sum_{n=0}^\infty  x^{n}\Big)''+x\Big(\sum_{n=0}^\infty  x^{n}\Big)'$$ I am sure that you can take it from here. When you finish, make $x=\frac 12$.


How can I display a Google map with Search API Views and Search API DB

Question: I am using Search API with Search API DB, and Facets, with Search Views.  I want to display a map to plot the results from the search.  Is this possible?  I have looked everywhere and can't seem to figure it out.
My nodes currently use geofield for the individual node pages.
Comment: did you try this, https://www.drupal.org/project/getlocations
Comment: I did, but couldn't get it to work.
Answer: Have you ever tried these two modules?
https://www.drupal.org/project/gmap
https://www.drupal.org/project/location
With these two modules, you can create google maps and put your location data into a referenced google map.
Comment: Yes, but it doesn't seem to work for me.
Comment: any error message?
Comment: It's because I don't have something configured right I think.  At this point, I think I'm going to add the lat/lng vals to the Drupal JS object, and gather them up and plot them with Google Maps API.
Answer: You could simply write your own field.tpl file for displaying that field and see how to display google map based on geofield values take a display google maps using Geolocation values.
Your tpl file will be named views-view-field--{field_name}.tpl.php be in the adefault theme folder you could check:
 views -> advanced -> Theming information and rescan templates button.
Copy the file views-view-field.tpl.php and read its docs for variables available.


Power series convergence (hypergeometric)

Question: Consider the power series $\sum a_nx^n $ where $$a_n = \frac{2.4.6...(2n)}{1.3.5...(2n+1)}$$
Now the ratio test shows absolute convergence for all $|x|<1$ and divergence for $|x|>1$. Also Raabe's test shows divergence for x=1. The remaining case is for x=-1 which I'm not able to solve. Help will be highly appreciated.(using only basic inequalities/methods. No sterling's formula etc :) )
Comment: It can be shown that $\frac12\sqrt{\frac\pi{n+1}}\le a_n\le\frac12\sqrt{\frac\pi{n+1/2}}$
Answer: The series is alternative, so we may consider the Leibniz test. Pretty clear that the series converges for $x =-1$. Could you find out why?
UPDATE
To show $a_n\to 0$, one may try prove that [WRONG INEQUALITY]
$$
\frac {(2n)!!}{(2n+1)!!} < \frac 1{\sqrt {2n+1}}.
$$
Also the series diverges at $x = 1$ as the OP mentioned by Raabe test.
EDIT
Thanks to @robjohn who pointed out the inequality is reversed. It should be
$$
\frac {(2n)!!}{(2n+1)!!} < \frac 1{\sqrt {n+1}}.
$$
Comment: I'm not able to find a bound for a_n
Comment: +1 Alternatively, the series is absolutely convergent, as the $x = 1$ case indicates.
Comment: How will you show an goes to 0?
Comment: @JohnMitchell Sorry about my wrong comment.
Comment: an is certainly decreasing but that does not show it goes to 0.
Comment: For x=1 it diverges right?
Comment: @JohnMitchell UPDATED. Feel free to check.
Comment: This is correct indeed
Comment: Your inequality is backward. However, we do have $\frac{(2n)!!}{(2n+1)!!}\lt\frac1{\sqrt{n+1}}$, which does give the same result for the series.
Comment: @robjohn Thank you, I'll fix it.
Answer: Using Simple Estimates
Let
$$
a_n=\frac1{3/2}\frac2{5/2}\cdots\frac{n}{n+1/2}
$$
and
$$
b_n=\frac{3/2}2\frac{5/2}3\cdots\frac{n+1/2}{n+1}
$$
and
$$
c_n=\frac{1/2}1\frac{3/2}2\cdots\frac{n-1/2}{n}
$$
Since $\frac{x}{x+1/2}\lt\frac{x+1/2}{x+1}$, we get
$$
c_n\lt a_n\lt b_n
$$
Therefore,
$$
\frac1{2n+1}=a_nc_n\le a_n^2\le a_nb_n=\frac1{n+1}
$$
This means that
$$
\sum_{n=0}^\infty a_nx^n
$$
converges for $-1\le x\lt1$.

Applying More Power
Since
$$
a_n=\frac{\Gamma\!\left(\frac32\right)\Gamma(n+1)}{\Gamma(1)\,\Gamma\!\left(n+\frac32\right)}
$$
and by the log-convexity of $\Gamma$, we get
$$
\frac12\sqrt{\frac\pi{n+1}}\le a_n\le\frac12\sqrt{\frac\pi{n+1/2}}
$$


Is it possible to have a button start a download of a dom element?

Question: I have an svg that is generated in a page, I am not bringing it in from an outside source. I want this svg to be downloadable for printing. Is there a way (using client side Javascript) to download a dom node as a text file? I am limited to dojo and d3 libraries for this project.
Comment: Since I haven't had the time to complete my answer, here are links for further information: [File API: Writer, FileSaver Interface](http://www.w3.org/TR/file-writer-api/#the-filesaver-interface), [Sample code of an answer here](http://stackoverflow.com/questions/7160720/create-a-file-using-javascript-in-chrome-on-client-side/7160827#7160827). Note that the neccessary feature aren't implemented in all browsers (e.g. no IE 10) support because they're still a draft. See also here: [Can I use: Fileystem](http://caniuse.com/#feat=filesystem).
Answer: Assuming the client is using a HTML5 web browser, this can be achieved pretty easily using s download attribute. You will need to simulate a click with a MouseEvent on this element if you want the behaviour to be invoked by some other means, but the node does not have to be appended to the document. I've answered a similar question about this before, but here, set the s href to the svg's file location unless it is created dynamically ‒ in that case you would encode the text describing it to create a data URI.
XML text describing a SVG can be obtained from it's SVGSVGElement node using XMLSerializer.
var serializer = new XMLSerializer();
serializer.serializeToString(svg); // xml string for `svg` (your node)

Please note that any "Save As" dialogue will depend on the client's configuration.
// assuming var `svg` for your SVG node
var a = document.createElement('a'), xml, ev;
a.download = 'my_svg.svg'; // file name
xml = (new XMLSerializer()).serializeToString(svg); // convert node to xml string
a.href = 'data:application/octet-stream;base64,' + btoa(xml); // create data uri
//  constructed, simulate mouse click on it
ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(ev);

Comment: The SVG I am trying to make downloadable is not in a file, it is generated in the browser using d3.js. I have no outside file to reference, just a domNode.
Comment: So you want to know how to get the string describing it from the SVGSVGElement? Edited in how to do that too, now.
Comment: @AdamSpurgin also, the data URI doesn't really need to be in base64 as the XML is a string, but safety first! Changing the MIME should be okay, too. I chose _application/octet-stream_ because it should start a download even if the browser doesn't understand a _download_ attribute (although you usually end up with a hash as a file name).
Comment: Is there any way to specify a filename otherwise? From firefox all i get is a hash name, not really an option for me.
Comment: The [MDN page about it](https://developer.mozilla.org/en-US/docs/HTML/Element/a#attr-download) suggests that it might be some same-origin stuff making it break in FireFox? Maybe file a bug on bugzilla.


Kill specific cmd.exe from BAT file containing string

Question: I am currently running into an issue where a "cmd.exe" process remains active despite a particular service being stopped. This in turn is causing problems for an automated script that performs actions on the folder, preventing it from being renamed/moved/etc.
As my automated script runs from a BAT file, I believe I can kill it with TASKKILL. Using "Process Explorer", I searched for the folder name and it was able to locate the "cmd.exe" that was using it. I am having trouble finding a way to automate this though without some type of "Contains String". My pseudo example is...
taskkill /IM cmd.exe /FI "NAME contains TC38247178584278321320778"
php\php.exe migration.php TC38247178584278321320778

Comment: Here is an alternative question, that may even lead to a better solution: [How do I find out which process has a file open?](https://blogs.msdn.microsoft.com/oldnewthing/20120217-00/?p=8283) And the answer is: Use the [Restart Manager](https://msdn.microsoft.com/en-us/library/windows/desktop/cc948910.aspx).
Comment: This looks very neat, although seems a bit too much given I am currently using a BAT and PHP file
Comment: If you can switch to using [PowerShell](https://msdn.microsoft.com/en-us/powershell/mt173057.aspx) instead of batch files, this would be a viable option. Even if with lots of P/Invoke calls.
Answer: wmic process where "commandline like '%TC38247178584278321320778%'" get name

to see what next command will kill
wmic process where "commandline like '%TC38247178584278321320778%'" call terminate

See wmic /?, wmic process /?, wmic process get /?, wmic process call /?, wmic process set /?, wmic /format /?, wmic /node /?, etc.
Like is % 0 or more characters and _ is a single character. Otherwise =, <>, <, >, <=, =>.


How to remove duplicate values within a list element in R

Question: I need to remove duplicate values within a list element in R.
In the reprex below this would mean I need to remove the second "A" in [[4]].
I have tried to use unique(), but this function removes entire elements ([[3]] in the reprex below).
I have been unable to find any SO questions/answers solving my problem.
Minimal reprex:
df <- data.frame(
  a=1:4,
  b=I(list("A", "A", c("A", "B"), c("A", "B", "A"))))

# I need to remove the second "A" in [[4]]

df$b
#> [[1]]
#> [1] "A"
#>
#> [[2]]
#> [1] "A"
#>
#> [[3]]
#> [1] "A" "B"
#>
#> [[4]]
#> [1] "A" "B" "A"

# unique does not work because it removes [[3]]
unique(df$b)
#> [[1]]
#> [1] "A"
#>
#> [[2]]
#> [1] "A" "B"
#>
#> [[3]]
#> [1] "A" "B" "A"

Created on 2021-07-07 by the reprex package (v2.0.0)
Answer: You need to apply unique() to the elements of df$b, not to df$b itself.
df <- data.frame(
  a=1:4,
  b=I(list("A", "A", c("A", "B"), c("A", "B", "A"))))

df$b <- lapply(df$b, unique)
df
#>   a    b
#> 1 1    A
#> 2 2    A
#> 3 3 A, B
#> 4 4 A, B

Created on 2021-07-07 by the reprex package (v2.0.0)


How to programmatically create views in Drupal 7

Question: How do I programmatically create views in Drupal 7?
I would like to create a custom module that would output data as a view.
Is there any documentation on how to output views from a custom module?
Comment: this has some good pointers as well:  http://views-help.doc.logrus.com/help/views/api-default-views
Comment: Do you mean you want to execute an existing view (possibly with arguments), or that you want to define and create a new view from scratch in code?
Comment: Clive, I would like to define a new view from scratch in code but to reuse the Views functionality instead of adding php code inside an existing view to avoid storing php code inside the drupal database.
Comment: I found views api is described here: http://drupalcontrib.org/api/drupal/contributions%21views%21views.api.php/7
Answer: My first guess was to create a desired view using UI, export it and paste the generated code into own module.
And I guess this is how admin_menu installs their admin views. You could install the module just for testing and see the contents of <code>/admin_menu/admin_views/views_default/</code>. At any rate, you would have to resort to writing a custom module and adhere to views' hooks syntax.
Answer: There is a very good step-by-step tutorial here: http://www.packtpub.com/article/creating-views-3-programmatically
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


How to use AWS Lambda synchronously with AWS Glue

Question: I have a lambda function that executes a crawler, SNS job and ETL. Is there any way to make the lambda function wait for the crawler to finish first before the SNS and ETL?
Thanks
I currently don't have the IAM access for step functions yet but still require this to be done. Currently it just all executes in one go therefore the SNS and ETL aren't working as intended.
Answer: Either you can use this answer to do it really synchronous (waiting for Glue Crawler to finish inside the Lambda) or, if the Crawler takes to long and the Lambda times out, you create separate Lambdas for starting the crawler and ETL, and let the ETL Lambda be invoked by an EventBridge rule.


Represent a function as a difference of two convex function

Question: I know that if $f:\mathbb{R}\to\mathbb{R}$ is $C^2$ it can be rewrite as a difference of two convex function. I ask to you if there is someone who know if it's possible extend this property to the function which have $\mathbb{R}^n$ as domain.
Comment: Does this answer your question? [A $C^2$-function as difference of two convex functions](https://math.stackexchange.com/questions/2693451/a-c2-function-as-difference-of-two-convex-functions)
Comment: There is an answer here https://math.stackexchange.com/questions/2693451/a-c2-function-as-difference-of-two-convex-functions
Comment: In the question of the links the function is a one variable function, I want to know if a multivariable function have the same proprietie. For me can be helpful either have some bibliographies reference. Thanks in advance.
Answer: It is possible, for example:
If $f \in C^2(D,\mathbb{R})$ and $D$ a non-empty, convex and compact subset of $\mathbb{R}^n$, then $f$ is a dc-function, i.e. the difference of two convex functions.
The proof can't be done the same way as in $\mathbb{R}$. Note that in this statement you need a compact subset.
Here is a reference (Sanjo's answer): https://math.stackexchange.com/a/843020/797553
For a proof use $g(x)=f(x) + \rho/2 \cdot x^Tx$ and $h(x)=\rho/2 \cdot x^Tx$, where $\rho=\left| ~min ~\{\lambda_{min}(Hessf(x)): x\in D\} ~\right|$. Then $f=g-h$. Note that $\rho$ only exists as $D$ is compact.
EDIT: For $D=\mathbb{R}^n$ the statement is still true. (see [Konno H., Thach P.T., Tuy H. (1997) D.C. Functions and D.C. Sets. In: Optimization on Low Rank Nonconvex Structures. Nonconvex Optimization and Its Applications, vol 15. Springer, Boston, MA]). In this book you'll also find a proof for the statement above.
Comment: So if D isn't  compact the tesis is not true. Do you have an example of a function which is in $C^2(D,\mathbb{R})$ (with D non-compact set) but it isn't representable as a difference of two convex function?
Comment: Also for $D=\mathbb{R}^n$ and $f \in C^2$, the statement is true. See my edit.
Comment: I don't know if the satetment is false for $n \geq 2$ and $D$ non-compact. Only that we would need a different proof/approach. I guess it's false, but I'm not sure. A counterexample to find is really hard and I don't know any easy one.


Get all Taxonomy Terms

Question: I have added a vocabulary as Sites with machine name as sites. I have added two custom fields in this vocabulary as :
1) URL
2) Status 0 or 1
I need to make a dropdown of all terms with status 1 something like.

get term.name from term join vocabulary on vid where vocabulary.machine_name = sites and term.status = 1

$v =  taxonomy_vocabulary_machine_name_load('sites');

$t = taxonomy_get_tree($v->vid);

How do I get an array of enabled terms in the 'sites' vocabulary?
Answer: Yes, entity_load can be used, but you have to retrieve entity ids yourself:
$terms = array();

$v = taxonomy_vocabulary_machine_name_load('sites');
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', $v->vid)
  ->fieldCondition('field_status', 'value', 1) // If your field name is 'field_status'
  ->execute();

if (!empty($result['taxonomy_term'])) {
  $terms = entity_load('taxonomy_term', array_keys($result['taxonomy_term']));
}

// dpm($terms);

Get all Taxonomy Terms


Can a sequence with increasing variance satisfy weak stationarity

Question: In Section 3 of Page 3, the notes that one of the conditions for weak stationarity is that $\gamma_{X}(h)=Cov(X_t, X_{t+h})$, essentially that the covariance of $X_s$ and $X_t$ depend only on $t-s$ and not $t$ or $s$. If I understood this correctly, this implies that it's possible to have a sequence of random variables whose the variance increases with time and yet the sequence can still be weakly stationary? So visually the data can look more and more "spread out" with time but still be stationary?
Answer: No. Use $h=0$ to see that the condition you quote implies constant variance over time:
$$
\gamma_X(0)=\text{Cov}(X_t,X_{t+0})=\text{Var}(X_t).
$$


Wave breaking in Burgers' equation

Question: My understanding is that Burgers' equation is a prototype for wave breaking: Solution $u(x,t)$ stays bounded as its derivative $u_x(x,t)\to\infty$. I solved
$$u_t+uu_x=0,\,\,\, u(x,0)=-x,\,\,\, x\in[0,1],$$
and got
$$u(x,t)=-\frac{x}{1-t},\,\,\, u_x(x,t)=-\frac{1}{1-t}.$$
Surely $u_x(x,t)\to-\infty$ everywhere in $[0,1]$, but $u$ also does at any $x\in(0,1]$. I know $u$ along characteristics is constant, in this case it equals $-x$, and at the singularity time, $t^*=1$, all characteristics are converging to $x=0$, where $u$ is zero. So there is steepening happening in $u$ at $x=0$, but $u$ is not bounded for $t\in[0,t^*)$.
Comment: So, what is your question?
Comment: From the example $u$ is not bounded for $t\in[0,1)$ and $x\in(0,1]$, thus what's happening here is not wave-breaking if the definition for such a phenomenon requires $u$ to remain bounded.
Comment: Still do not see a question.
Comment: Thanks. I'll wait for someone who knows about Burgers' equation.
Answer: Since the Burgers equation is nonlinear, there can be infinitely many solutions in the sense that you are considering (just taking the derivatives and plugging them in the equation).
In order to select the solution to the equation, one has to be more restrictive on what can be considered a solution. In that sense, shocks are defined, mass conservation is imposed... and rarefaction waves appear. In your case, a rarefaction wave arises in $(x=1,t=0)$, opening to the left, which controls the height of the peak you are mentioning. In the graph below (characteristics in $x$ vs. $t$), you can see that, while the non-zero part of the initial data moves into a shock at $t=1$ (in red), a rarefaction wave appears in the empty space that it appears behind it.

I really like how this is explained in Partial Differential Equations by Lawrence C. Evans, but you can find lots of notes about the topic in Google.

EDIT: In that book, you can find a theorem that describes the behavior of solutions to the Burgers equation in the whole spatial domain. It says that for bounded and summable initial data (hence, vanishing at $\pm\infty$), there exists $C>0$ such that $|u(x,t)|\le Ct^{-1/2}$ for all $x\in\mathbb{R}$ and $t>0$.
Moreover, the dynamics of the Burgers equation push all such initial data (whatever their shape is) towards a function called N-wave, which IMHO is fascinating.
Comment: Thanks! I found that with $u_0(x)=x(1-x)$ and boundary conditions $u(0,t)=u(1,t)=0$, the solution $u$ nos stays bounded on $0\leq x\leq1$ but its derivative goes to $-\infty$. But I am still wondering what types of initial conditions and/or boundary conditions will lead to that as opposed to both $u$ and $u_x$ diverging at some finite time.
Comment: I do not think I understood what is your doubt. Are you considering the whole spatial domain or just a bounded interval? Note that it is quite tricky to impose boundary conditions to this type of equations, since not all of them are _admissible_. On the other hand, if you consider the whole spatial domain, any compactly supported and bounded initial data remains bounded (with this bound going down to 0) and preserves the mass.
Comment: I was considering two settings, one with domain $[0,1]$, $u$ zero at the endpoints and $u(x,0)=x(1-x)$. The other on the same unit interval, but $u(x,0)=-x$ and no boundary conditions. For the first one, integrating the equation between 0 and 1 leads to the mean of $u$ being conserved. May be that and vanishing at the boundary  forces the solution to stay bounded (?).
Comment: Yes. Solutions to the Burgers equation with bounded initial data vanishing at the boundaries (or at $\pm\infty$) remain bounded.
Comment: I added a short paragraph at the end regarding this behavior. Please, accept the answer if you feel it fulfills your requirements.

Wave breaking in Burgers' equation


how to access many parameters from the GUI

Question: I am writing a Java application that takes a lot of parameters as input (~100). I am exposing some of the in the GUI, but of course it is impossible to show all of them at once.
I am curious if there is a shared way to let a user access a large amount of parameters like that. Right now, I have some buttons in the GUI, and each of them opens a JPanel which show a sub-set of the parameters. Is this a common solution? or are there more efficient solution from a human-interface point of view?
Thank you in advance for your advices,
Simone
Answer: I think it makes a lot of difference how that mass of information is best understood by the user.  Is it something organized in categories, that the user will want to browse through?  Are there salient parameters that the user is more likely to want to know, and so should be made more easily accessible?  You could have a tabbed panel with tabs for groups of parameters, you can alphabetize them and color them and put them in different fonts, etc., but there isn't going to be one answer regardless of what the parameters are.
Answer: I would suggest a wizard that guides the user through all parameters. All general information on user interface creating you can refer to ISO DIN 9241.
Answer: One way I've found effective is to have a single-selection JTree on the left side of the user interface.  Whenever the user selects a tree node, a corresponding panel is shown on the right.  I typically will place all the panels into a CardLayout to ensure the UI's preferred size accommodates all of them.
This has the advantage of allowing you organize your information hierarchically.


Não consigo fazer o botão de fechar janela do Pygame funcionar

Question: Estou aprendendo a usar as funções do Pygame, mas fiquei travado nesse problema. Eu criei uma janela com o Pygame, e depois fiz esse código para quando eu clicar no botão de sair a janela fecha-se.
Código
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break
        print(event)
    # Atualizando a tela
    pygame.display.update()

pygame.quit()

Não consigo entender porque ele não funciona, o programa durante a execução não mostra nenhum erro, mas quando clico no botão de fechar, nada acontece.
Answer: Tenta colocar pygame.display.quit() antes do pygame.quit(), já fora do loop.
Já vi pessoas que só conseguiram fazer dar certo colocando exit() depois, mas so tenta isso se a primeira opção não der certo.
Answer: isso é fácil de resolver, basta usar a função nativa exit, cujo objetivo é fechar o programa
o pygame.quit() é para resolver um bug do pygame e deve sempre ser chamado antes do fechamento
import pygame
from pygame.locals import *

for event in pygame.event.get():
   if event.type==QUIT:
      pygame.quit()
      exit()

Answer: Segue um código básico para complementar a resposta do Henrique Seta.
Neste exemplo o while será executado enquanto sair for igual a False.
Note que dentro do for se o evento QUIT for capturado a variável sair será definida como True encerrando o loop para fechar programa como o pygame.quit().
import pygame

def main():
    pygame.init()
    tela = pygame.display.set_mode([300,300])
    pygame.display.set_caption("Iniciando com Pygame")
    cor = (255,255,255) # cor branca
    sair = False

    while sair != True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sair = True

            tela.fill(cor) # preenche a tela com a cor branca

            pygame.display.update()

    pygame.quit()

main()

Answer: O problema é bem simples. você colocou o loop como sendo "True". sendo assim, não há parâmetro para que ele se encerre e ele roda infinitamente.
Você deve criar uma variável e atribuir o valor true a ela, dai então você coloca
while variavel:
e lá no código você coloca que, se o evento for "quit" a variável recebe false
continuar = True
while continuar:
for event in pygame.event.get():
if event.type == pygame.QUIT:
continuar = False
print(event)
# Atualizando a tela
pygame.display.update()
pygame.quit()
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Answer: Use o sys.exit no if event.type == pygame.QUIT: isso evita o erro no terminal após fechar a janela
for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Calculate G Force On Cannon Payload

Question: Have a pneumatic cannon that launches a mouse via a pusher plate when lured into the barrel. How many Gs will the mouse feel when launched?
Pusher Plate Stroke = 8"
Distance Mouse Travels (at 45 deg): 20 feet
Weight of Mouse: 0.8oz  (is this needed?)
This is a real thing that has attracted some criticism for being cruel to animals, even though it is one of many ways to collect vermin for disposal. I'd like to be able to point out that the G forces are non-lethal. The mouse/rat is in contact with the pusher plate at the time of firing so it isn't smacked in the face with the pusher...it's pushed. I figured that if a human cannonball can be fired for 200 feet uninjured, what about this mouse being shot 20 feet into a bucket?
Comment: I would approach this by first figuring out the launch velocity. We know the range of the projectile, and we can (at least numerically) solve for the initial velocity (see https://en.wikipedia.org/wiki/Range_of_a_projectile). After that, consider the movement in the barrel. The initial velocity (zero) and end velocity (solved in previous step) are known now, and also the distance that it travels in the barrel. Then you can solve for the acceleration.
Comment: Is the landing at the same level as the barrel? That's the quantity $y_0$ in the equation.
Comment: Thanks for looking into this Matti. And yes, the landing is at the same level as the cannon.
Answer: Let's first solve for the launch velocity. If the landing is at the same level as the cannon, the range of a projectile (assuming no air drag etc) is
$$
d = \frac{v^2}{g} \sin{2 \theta}
$$
where $v$ is the launch velocity, $g$ is the acceleration of gravity and $\theta$ is the launch angle. Solving for $v$, we obtain
$$
v_{\text{launch}} = \sqrt{  \frac{dg}{\sin{2\theta}}  }
$$
Now let's look a the the barrel. It's essentially a linear path that the projectile goes through before launching into the air. The initial velocity is zero, so the following equation ca be written for the velocity of the projectile within the barrel:
$$
v(t) = at \qquad \Rightarrow \qquad t = \frac{v_{\text{launch}}}{a}
$$
where $a$ is a (constant) acceleration and $t$ is time. On the other hand, integrating this equation, we can obtain the equation for the distance (as a function of time) inside the barrel:
$$
s(t) = \frac{1}{2}at^2
$$
plugging in the previous result for time, we obtain
$$
s(t) = \frac{1}{2} a \left( \frac{v_{\text{launch}}}{a}\right)^2
 = \frac{ v^2_{\text{launch}} }{2a}
$$
from which we can solve for the acceleration $a$:
$$
a = \frac{ v^2_{\text{launch}} }{2s}
$$
Here, $s$ is the length of the barrel. Now we can plug in the result for the launch velocity:
$$
a = \frac{ \left( \frac{dg}{\sin{2\theta}} \right)  }{2s} = \frac{dg}{2s \, \sin{2\theta}}
$$
the "G" acceleration is specifically acceleration divided by $g$, so the "G" acceleration as a formula is
$$
\frac{a}{g} = \frac{d}{2s\, \sin{2 \theta}} = \frac{ \left(6.096~\text{m} \right)}{2 \left(0.203~\text{m} \right) \sin{90^{\circ}}} \approx 15~\text{g's}
$$
Comment: Thank you very much Matti. I believe a mouse can withstand 15 Gs for a fraction of a second without damage.
Comment: You're welcome. If you feel like I answered your question, feel free to mark and upvote it.

Calculate G Force On Cannon Payload


Can someone tell me how to show this is linearly independent or not without using Wronskian?

Question:
Not sure how to do this without using the Wronskian.
Comment: Hint:  what do you know about $e^{a+b}$?
Comment: Right, so $e^{x+1}=?$
Comment: It's equal to $e^{a}*e^b$
Comment: @lulu $$e^{x}e$$
Comment: True.  So the second function is a constant times the first.  Can you finish from here?
Answer: The set of four functions are dependent.
Note that $$ e\times  e^x + (-1)\times e^{x+1} +0\times e^{x^2}+0\times sin(x) =0$$ without the coefficients being all $0$
If you through away one of $e^x$  or $e^{x+1}$, then you have a set of three independent functions.


How many teams have forced a game 7 after being down 3-1 in the series?

Question: I know 9 teams in NBA history have come back to win a series after being down 3-1 in the playoffs, but how many managed to take it to 7, regardless of whether they won the series or not?
Answer:
...how many managed to take it to 7, regardless of whether they won the series or not?

This has happened 31 times, courtesy mostly of Ps3FifaCfc95 of Reddit. This can be verified using Basketball Reference or any respectable NBA source.
A 3-1 deficit has been overcome 11 times.

2016 Cavaliers Warriors 4th away yes
2016 Warriors Thunder 3rd home yes

Note: "The first team is the one that came from 3-1 down, then there's the round, whether the recovering team were home or away, and whether they pulled off the comeback."


Know when CCScene is shown after scene on top of stack is popped

Question: Using `cocos2d-x, say I am on Scene 1 and I add a new scene (Scene 2), but I later pop that scene:
CCDirector *pDirector = CCDirector::sharedDirector();
pDirector->popScene();

How do I know when Scene 1 has appeared again? Is there any sceneDidAppear method or something similar?
Answer: CCScene is derived from CCNode, therefore you can override onEnter() and onExit() method to know when a scene is pushed or poped.
Comment: But would I implement the `onEnter()` method in my class? I tried and I get the error "Out-of-line definition of onEnter does not match and declaration"
Answer: Adding to @Vikas Patidar answear : you can override onEnterTransitionDidFinish() - this will fire after the transition animation is complete. Docs : link
Comment: Where do I override this? I tried in my class and I get an error.
Comment: What kind of error? It has to be in a subclass of `Node`. I just tested it and it went fine.


calculate all possible combinations with respect to a conditions

Question:
we have a group of people 5 men and 7 womens
we take 2 men and 3 womens to form a group
how many possible groups we can have if 2 women can't be in the same group?
the 2 women can be any womens from the  7 womens
Comment: Let number of women = $w$, men = $m$, are you saying that in a group $w \neq 2$ or that $w \leq 1$?
Comment: 2 womens like may a and b can't be in the same group so we have to rmove them
Comment: You cannot select three women if *any* two women can't be in the same group.  They would have to be two *particular* women.
Answer: How many ways can you select $2$ from $5$ men, $2$ from $5$ women, and $1$ from those $2$ specified women?
How many ways can you select $2$ from $5$ men, $3$ from $5$ women, and $0$ from those $2$ specified women?
Add the result.


Auto resizing qt application. (main window)

Question: I've recently started development in qt and so far it's going good. Now my question is : can I auto re-size qt application as per my screen resolution ? Say, I 've a main window designed for 1366 x 768. And it works for one system. While porting it to another system which supports 1280 x 800 or 800 x 600, is there an easy way to do it ? without changing UI design in creator ?
I appreciate any help regarding this.
Thanks in advance.
Answer: Try do this (for example put it in the mainWindow's constructor)
this->showMaximized();

Anyways you can simply get resolution of current screen with this code:
qDebug() << QApplication::desktop()->size();

And QWidget have resize() method. QMainWindow inherits QWidget, so you can use resize() in your mainWindow.
Comment: Does using resize in QMainWindow constructor help all the components in that window as well ?
Comment: @dastaan your question was about resizing window accordingly to the screen size and I wrote answer already. If you want that all widgets which mainWindow contains will be automatically resized accordingly to the new size of mainWindow you should use QLayout. This class was created for this purpose. You can create Layouts in Qt Designer or you can write it yourself.
Answer: Qt (and many other UI toolkit) solve auto resize problem with a layout manager, it depend on how do you design your UI to choose a layout or mix them. See http://qt-project.org/doc/qt-4.8/layout.html
Comment: Thanks. It's worth going for layout.


What are the benefits of a non-linear promotion/relegation system?

Question: In Italian rugby you can be promoted from III division (Serie A girone B) directly to I division (Eccellenza), and you can be relegated from II division (Serie A girone A) directly to IV division (Serie B).
Which are the benefits of such an odd format?
Is this format really odd, or is it somewhat widespread in team sports?
Comment: This was due to the Serie-A/B inclusion...but please accept my apologies as I overlooked the `rugby` tag. Since you were going broader, I did not feel `italy` was appropriate for either question. Thanks for the clarification.
Comment: Rugby's your main example, but added `international-sports` to include other team sports broadly.
Comment: @edmastermind29 While here I'm trying a broader question and any team sports employing such a rule would fit, I again wonder why you specifically added [tag:uefa].
Comment: @edmastermind29 nevermind, I'm perfectly fine with that! (good idea to remove [tag:italy], I'm wondering if it would be better to remove [tag:rugby], since I would accept answers on other team sports too.
Answer: Possibly the most extreme system comes from Chess, and the McMahon competition format.
The idea behind big drops in those instances are to ensure that competitors are, as often as possible, meeting evenly matched competitors.
How often large adjustments in seeding, ranking and match-pairing are made in team sports, I cannot say.


Meteor Cordova app unable to connect to remote MongoDB

Question: I have an existent Meteor+React application that works with a remote MongoDB. This application connects to the remote database if I run it with the following .sh file:
DB_URL="mongodb://..."

MONGO_URL=$DB_URL \
meteor run --settings config/settings.json

But if I try to run a Cordova application it always connects to the local MongoDB and ignores any configurations. I'm trying it this way:
DB_URL="mongodb://..."

MONGO_URL=$DB_URL \
meteor run ios-device --verbose --settings config/settings.json

How could I setup a MongoDB url for Cordova app properly?
Answer: I think you might be experiencing this issue.
Try with meteor shell (as a second instance) to see if the database is accesible from the server. If you can then it's a DDP problem, set a ROOT_URL environment variable for the server instance and try again.


SQL trying to use a column from a joined table in a subquery

Question: Here is what I currently have which returns 3 columns for patient_id, group_concat_1, and group_concat_2:
SELECT patient_id,
(SELECT GROUP_CONCAT(column1) FROM
table1 where patient_id = patient.id
) group_concat_1,
(SELECT GROUP_CONCAT(column1) FROM
table2 where patient_id = patient.id
) group_concat_2
FROM patient

However, I need to return a single column with group_concat_1 and group_concat_2 combined, so I tried this:
SELECT patient_id,
SELECT CONCAT(group_concat_1, group_concat_2) FROM (
    (SELECT GROUP_CONCAT(column1) FROM
    table1 where patient_id = patient.id
    ) group_concat_1,
    (SELECT GROUP_CONCAT(column1) FROM
    table2 where patient_id = patient.id
    ) group_concat_2
)
FROM patient

But his clearly doesn't work since now it can't find patient.id in the inner subquery. Any advice? Thanks!
Comment: Theres nothing 'clearly' about it. Please see [Why should I provide an MCRE for what seems to me to be a very simple SQL query](http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query)
Answer: You can concatenate directly the 2 columns:
SELECT p.patient_id,
  CONCAT(
    (SELECT GROUP_CONCAT(column1) FROM table1 where patient_id = p.patient.id),
    (SELECT GROUP_CONCAT(column1) FROM table2 where patient_id = p.patient.id)
  )
FROM patient p

Answer: I'm pretty sure you want concat_ws() for this purpose:
SELECT patient_id,
       CONCAT_WS(','
                 (SELECT GROUP_CONCAT(t1.column1) FROM table1 t1 where t1.patient_id = p.id
                 ),
                 (SELECT GROUP_CONCAT(t2.column1) FROM table2 t2 where t2.patient_id = p.id
                 )
                ) as combined
FROM patient p;

There are two reasons:

You can distinguish between the last element from table1 and the first from `table2.
If one of the tables has no matching values, this returns the results from the other.

Also note that I added table aliases and qualified column names.  This is quite important when working with queries that have multiple table references -- it helps prevent some very hard to debug errors.
I should add that your original query would run in most databases.  MySQL and Oracle happen to be two that don't understand nested correlation clauses.


Tips on arranging music on ukulele?

Question: I started off by writing the melody line because I need them on top. Let's just assume the melody note I'm working on is C on the C major scale; I will have like 3 chords to choose from which are C(C,E,G), A minor(A,C,E) and F(F,A,C).
Then, I tried to figure out which note from A,E,F,G that sounds great with C. If it sounds just like I wanted it to with G, I'll go with G chord but if it sounds good with another note such as the A, E, and F, I need to choose between A minor or F chords. Of course I can make it sound good with another note other than what I had mention but this alone has consumed a lot of time let alone another note which in my opinion I might as well try it with every note in the scale and probably a flatted 7th.
This probably is the worst way you ever seen of people arranging tune. I realize that this could be all wrong, that's why I make this post. Is there any kind of pattern I should be looking out for in my melody line? Shouldn't I start the whole process with just melody line alone? I'm looking forward to make simple full-sounding arrangement and practice my music theory at the basic level. I have learn all the 12 scales and basic chord building for major, minor, augmented, diminished, dominant 7th and major 7th just to later find out that I don't know how to apply them practically.
Comment: Second para. second line : did you mean C chord rather than G chord?
Answer: I would say the question, as written, is a bit open-ended, as there are many aspects to consider any time you arrange music. I'll try to broadly highlight what some of those issues are, without going in to much depth, to give you a starting point for further investigation.
When arranging music, it's important to understand what the components of a piece of music are. Music will typically consist of a melody line, a bass line, supporting harmonies, and some type of rhythm. Additional components can be added or removed, (for example, adding a counter melody, or dropping out the bass) but this is sort of a standard model. It's also important to have an idea of what your available forces are (i.e. the number of different performers and instruments available), and which of those musical components they can play (good luck getting a bass line out of your ukulele!).
A ukulele is easily capable of playing a melodic line, or it is capable of performing a simple harmonic/rhythmic part. Going beyond these (or perhaps combining them all in a single arrangement) is going to be more difficult, and dependent on the skill level of the performer -- for example, possibly using fingerpicking and arppegiation. I'm not sure what you're specifically after, but a pretty typical simple arrangement would have a singer to sing the melody, then use the ukulele to just fill the harmonies and rhythms (leaving out the bass line altogether, of necessity). Note that in this case, the ukulele does not need to explicitly play the melody, since another instrument (or in this case, voice) is playing it. That frees up the ukulele to just play harmonies/rhythms.
If this is the style of arrangement that you are after, than there are really only two broad things you need to know: what chords to play, and what rhythms to play them with. Choosing a rhythm determines which strumming pattern you use, and can be a matter of personal taste or an attempt to match the original song's style. The rhythm is important to have, to give  song its groove, but even a simple rhythm will go a long way.
As for the question of which chords to use, this gets into the question of harmonization. I have a feeling that this is what your actual question may be (how can I select chords to harmonize a melody), but that's another long answer, based on music theory, and isn't specific to ukulele, so I won't go into detail here. If you're playing an existing song, you can often find the chords listed online somewhere. More generally, you'll want to figure out what key you're playing in, and what chords are likely to go in that key. As mentioned in the comments of another answer, not every melody note needs a chord. The rate at which chords change is called the harmonic rhythm, and in a lot of pieces, it tends to be just one chord per bar, with other notes being non-harmonic tones.
If you don't have a voice or other instrument to play the melody, another option is to play just the melody on ukulele. In this case, the question of arranging the melody becomes largely a question of ornamenting the melody line. You can add various embellishments such as rhythmic variations, hammer-ons, pull-offs, harmonics, arppegios, glissandi, and (because ukes don't sustain a tone so long) repeated notes. This gets into performance techniques, and will probably overlap a lot with guitar technique.
A great way to learn how to arrange is to watch other arrangements, and deconstruct what they're doing. Here's an example arrangement I found on youtube of two ukuleles, one playing a simple harmonic/rhythmic style, and the other, an ornamented melodic style. The two performers switch back and forth between styles every once and a while. Note how little movement there is in the left hand of the person who is simply strumming the chords, compared to the person playing the melody line.

Once you've mastered each of these kinds of arrangement techniques, you could go beyond this into more complex arrangements, where you are playing melody, and harmony, and elaborate rhythms. But this will take considerably more skill to arrange and perform. One thing that you will need to be very comfortable with is moving chords up and down the neck, so that you can play any chord in any position along the neck. By way of example, here's Jake Shimabukuro playing a rather involved arrangement. Watch how much his left hand is moving up and down the neck, and pay attention to the way he incorporates various techniques, to highlight rhythms, harmonies, and the melody.

I hope this gives you a good starting point, and happy strumming!
Comment: The title of this post might sound open ended but my explanation define the context. My bad for the unsuitable title. Mostly, I play with four finger on the string but I don't do fancy alternating between strumming and picking because it's just beyond my comprehension. I want to make a rather simple single ukulele arrangement without having to use some fancy technique which in my opinion could come later when I'm better at arranging.
Answer: You are on the right lines. Every note in your tune will not need its own chord, though.Look at a whole bar, not just one note. All of those notes will probably work with just one chord. That's what will fit in that bar. For example, in a bar with C, D, E and G, the best fit chord is C maj. With A, F, F, G  an F chord is best fit. Reasons are first, the note on the strongest beat is in a particular chord, as you found out.Then you look at the other notes, and see which fit from the same chord.The strong beats are often 1st and 3rd,(in 4/4 time) so notes from a good fit chord will be on those. Sometimes all the notes will fit, but if 2nd and 4th don't, then it's not so important.
There will be times when one chord sounds wrong for the whole bar. Then use two, using the same idea.
Often, you'll find that two, or even three different ones could fit.Like A, A, F, G could use Dmin.instead of F. Then look at the bar before and the bar after, to hear what sounds good. If it sounds good, it usually is.
Several times I've mentioned that theory is more useful (to most people) when there's some practical knowledge to hang it on. Your case seems to agree with this. Good luck in your search for the 'lost chord'!! Also, try to make up a series of chords, then put a melody on top of that.
Comment: To be frank with you, I don't know how to divide my melody line into measure and I don't even know what time signature my melodies are on; at least in the way they are notated. Anyway, is it true if I say I should be looking at the pattern of chord tone, passing and neighboring tone in a bar to help me decide?
Comment: Yes, that's the way to go. Funny, I found it hard to understand the other answer as well.
Comment: Maybe he forget to consider the context of the matter. I'll rate yours as useful and thanks. For now, I'll just keep the post on just to see if there are any other suggestions or if the moderator feel suitable to; until the moderator close this post.
Answer: If you want to have easy start, just jump to 2nd part-special tuning part.
standard tuning
Let's talk standard tuning GCEA
If you are familiar with guitar than it won't take you a long time to get used to ukulele. The interval of ukulele string are same as 1st-4th string on guitar. Only different is 4th string is one octave higher. Basically you can starts on Major G(Major D on guitar) use 4th strings as root note.
In the beginning you can work on songs of D Major keys on guitar and play the same chords (some are even same positions) on ukulele.
Second step is try to transfer your root notes from 4th string to 3rd string. This is a big step, because from now you are trying to get ride of guitar's interval and arrangement.
Open D tuning
If you want to start from special tuning, i recommend to start with DADA (i call it open D for Ukulele) (correspond to open D on guitar)
for this tuning, you just treat 2-4th string of ukulele as 4-6th string  on guitar; 1st string of ukulele as 1st string on guitar
4th-2nd string forms a natural major 3 or minor 3 chords. than use 1st string to play melody, what you need to do is just to hold 2-4th string on same fret all the time.
here's some positions on this tuning:
open: D major 3
2nd frets: E minor 3
4th: #F minor
5th: G major(sub dominant)
7th: A major (dominant)
9th: B minor (relative minor)
if you want to play some 7th or 9th-13th,  suspend , aug chords, just use 1st string ad decoration notes.
For example :
Em7: 2nd fret one 2-4 string and open string on 1st string
Comment: I'm sorry my good man, I can't seems to understand either part of your answer. And your example from guitar doesn't knock any sense into me as I don't have any experience with guitar. I mainly started with music by playing only melody line on a recorder and become good at guessing what notes come next and be able to play most melodies by ear but that is a monophonic instrument. On ukulele I would just sound dumb playing just melody line on a polyphonic instrument wouldn't I?

Tips on arranging music on ukulele?


A fair dice is rolled until a 2 comes up. Given the first roll is not 2, what's the probability it'll take more than 3 rolls?

Question: Also,
if it takes an even amount of rolls, what's the probability of exactly 2 rolls?
I am completely lost so any help would be appreciated.
Answer: Suppose an event has probability $p$ of happening. On the first trial, there is a $$p$$ chance that it occurs. To happen for the first time on the second trial, it would have to fail once and then succeed (let $q=1-p$): $$qp$$
To happen for the first time on the third trial, it would fail twice (two q's) and then succeed: $$qqp=q^2p$$ In general, the probability of it happening for the first time on trial $n$ is $$q^{n-1}p$$
To find the probability that it takes more than three rolls, add the probabilities that it takes 0, 1, 2, or 3 rolls, and then take 1 minus that answer. Do the same to find the probability that the first roll is not a two, and divide those results to get the answer.
Given that it's even, you know that $$P(2|even)=\frac{P(2 and even)}{P(even)}=\frac{P(2)}{P(even)}$$
The probability that it is even is $$P(2)+P(4)+P(6)...=qp+q^3p+q^5p+...=pq(1+q^2+q^4+...)$$ Use the geometric series formula to find what this is equal to.
Answer: Let $X$ be a random variable with geometric distribution with parameter $p = \frac{1}{6}$:
$
  P[X = k]
= (1-p)^{k-1} p.
$
Then the probability you ask for is
\begin{align}
   P[X > 3 | X \neq 1]
&= \frac{P[X > 3]}{P[X \neq 1]} \\
&= \frac{1 - P[X=1] - P[X=2]-P[X=3]}{1 - P[X=1]} \\
&= \frac{1-(1-p)(p+p^2+p^3)}{1 - (1-p)p}
\end{align}


maven-plugin error while building maven projects

Question: When I am importing my maven project in my eclipse, I am getting this error:

Plugin execution not covered by lifecycle configuration:
  org.codehaus.mojo:buildnumber-maven-plugin:1.0:create-timestamp
  (execution: generate-build-number, phase:
  generate-sources) pom.xml /DataClient line 6  Maven Project

Does anyone know how to fix this problem? I tried several other ways which was listed in SO questions but it didn't worked.
I am using eclipse kepler and I do have pluginManagement as well in my pom.xml file.
My pom.xml snippet where I am using plugins:
<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <argLine>-javaagent:"${settings.localRepository}"/com/googlecode/jmockit/jmockit/1.7/jmockit-1.7.jar</argLine>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <configuration>
                    <instrumentation>
                        <excludes>
                            <exclude>**/test/**/*.class</exclude>
                        </excludes>
                    </instrumentation>
                    <formats>
                        <format>xml</format>
                        <format>html</format>
                    </formats>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9.1</version>
                <configuration>
                    <author>false</author>
                    <keywords>true</keywords>
                    <show>public</show>
                    <links>
                        <link>http://docs.guava-libraries.googlecode.com/git-history/v16.0/javadoc/</link>
                        <link>http://netty.io/4.0/api/</link>
                    </links>
                    <doctitle>Data Client API (${project.version})</doctitle>
                    <windowtitle>Data Client API (${project.version})</windowtitle>
                    <groups>
                        <group>
                            <title>Core API</title>
                            <packages>com.host.grads.client:com.host.grads.client.resources</packages>
                        </group>
                        <group>
                            <title>Miscellaneous</title>
                            <packages>com.host.grads.client.utils</packages>
                        </group>
                    </groups>
                </configuration>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

Comment: Can you copy your complete pom.xml ? It seems that the plugin `buildnumber-maven-plugin` involved in the issue is not present in the part you copied. For later, `buildnumber-maven-plugin` site : http://mojo.codehaus.org/buildnumber-maven-plugin/
Comment: Default the correct version of the buildnumber-maven-plugin cause it looks you are using an extreme old version of it.
Comment: @Fabien These are the only plugins I have in my `` in my pom.xml file. Do I need to add anything to fix this issue?
Answer: I found this on SO and I think that it is the answer to your problem : Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)
I copy the text initially written by Jan :

This is a "feature" of the M2E plugin that had been introduced a while ago. It's not directly related to the JBoss EAR plugin but also happens with most other Maven plugins.
If you have a plugin execution defined in your pom (like the execution of maven-ear-plugin:generate-application-xml), you also need to add additional config information for M2E that tells M2E what to do when the build is run in Eclipse, e.g. should the plugin execution be ignored or executed by M2E, should it be also done for incremental builds, ... If that information is missing, M2E complains about it by showing the "Plugin execution not covered by lifecycle configuration" error message.
See here for a more detailed explanation and some sample config that needs to be added to the pom to make that error go away:
https://www.eclipse.org/m2e/documentation/m2e-execution-not-covered.html

If you need to implement this solution, you can have a look to this comment of the previously mentioned question : https://stackoverflow.com/a/26447353/4810148
Here is a copy of what coderplus answered. Of course you will have to replace the groupId and artifactId by the ones of the plugin that is concerned by your case.

Eclipse has got the concept of incremental builds.This is incredibly useful as it saves a lot of time.
How is this Useful
Say you just changed a single .java file. The incremental builders will be able to compile the code without having to recompile everything(which will take more time).
Now what's the problem with Maven Plugins
Most of the maven plugins aren't designed for incremental builds and hence it creates trouble for m2e. m2e doesn't know if the plugin goal is something which is crucial  or if it is irrelevant. If it just executes every plugin when a single file changes, it's gonna take lots of time.
This is the reason why m2e relies on metadata information to figure out how the execution should be handled. m2e has come up with different options to provide this metadata information and the order of preference is as below(highest to lowest)

pom.xml file of the project
parent, grand-parent and so on pom.xml files
[m2e 1.2+] workspace preferences
installed m2e extensions
[m2e 1.1+] lifecycle mapping metadata provided by maven plugin
default lifecycle mapping metadata shipped with m2e

1,2 refers to specifying pluginManagement section in the  tag of your pom file or any of it's parents. M2E reads this configuration to configure the project.Below snippet instructs m2e to ignore the jslint and compress goals of the yuicompressor-maven-plugin
<pluginManagement>
      <plugins>

          <plugin>
              <groupId>org.eclipse.m2e</groupId>
              <artifactId>lifecycle-mapping</artifactId>
              <version>1.0.0</version>
              <configuration>
                  <lifecycleMappingMetadata>
                      <pluginExecutions>
                          <pluginExecution>
                              <pluginExecutionFilter>
                                  <groupId>net.alchim31.maven</groupId>
                                  <artifactId>yuicompressor-maven-plugin</artifactId>
                                  <versionRange>[1.0,)</versionRange>
                                  <goals>
                                      <goal>compress</goal>
                                      <goal>jslint</goal>
                                  </goals>
                              </pluginExecutionFilter>
                              <action>
                                  <ignore />
                              </action>
                          </pluginExecution>
                      </pluginExecutions>
                  </lifecycleMappingMetadata>
              </configuration>
          </plugin>
      </plugins>
  </pluginManagement>

3) In case you don't prefer polluting your pom file with this metadata, you can store this in an external XML file(option 3). Below is a sample mapping file which instructs m2e to ignore the jslint and compress goals of the yuicompressor-maven-plugin
<?xml version="1.0" encoding="UTF-8"?>
<lifecycleMappingMetadata>
  <pluginExecutions>
      <pluginExecution>
          <pluginExecutionFilter>
              <groupId>net.alchim31.maven</groupId>
              <artifactId>yuicompressor-maven-plugin</artifactId>
              <versionRange>[1.0,)</versionRange>
              <goals>
                  <goal>compress</goal>
                  <goal>jslint</goal>
              </goals>
          </pluginExecutionFilter>
          <action>
              <ignore/>
          </action>
      </pluginExecution>
  </pluginExecutions>
</lifecycleMappingMetadata>

4) In case you don't like any of these 3 options, you can use an m2e connector(extension) for the maven plugin.The connector will in turn provide the metadata to m2e. You can see an example of the metadata information within a connector at this link . You might have noticed that the metadata refers to a configurator. This simply means that m2e will delegate the responsibility to that particular java class supplied by the extension author.The configurator can configure the project(like say add additional source folders etc) and decide whether to execute the actual maven plugin during an incremental build(if not properly managed within the configurator, it can lead to endless project builds)
Refer these links for an example of the configuratior(link1,link2). So in case the plugin is something which can be managed via an external connector then you can install it. m2e maintains a list of such connectors contributed by other developers.This is known as the discovery catalog. m2e will prompt you to install a connector if you don't already have any lifecycle mapping metadata for the execution through any of the options(1-6) and the discovery catalog has got some extension which can manage the execution.
The below image shows how m2e prompts you to install the connector for the build-helper-maven-plugin.
  .
5)m2e encourages the plugin authors to support incremental build and supply lifecycle mapping within the maven-plugin itself.This would mean that users won't have to use any additional lifecycle mappings or connectors.Some plugin authors have already implemented this
6) By default m2e holds the lifecycle mapping metadata for most of the commonly used plugins like the maven-compiler-plugin and many others.
Now back to the question :You can probably just provide an ignore life cycle mapping in 1, 2 or 3 for that specific goal which is creating trouble for you.
Comment: I have seen this answer already but I am not sue what I need to do to fix this issue?


Qual é a importância de indentar o código?

Question: É comum ouvir que é importante manter o código indentado, o que não é uma tarefa difícil com ajuda de uma IDE.
Excluindo as linguagens que obrigam a indentação, como Python, por que é importante manter o código indentado? Seria somente a mérito de legibilidade?
Além do programador, quem lê o código é o compilador. Faz alguma diferença para ele, nas linguagens que não obrigam a indentação, processar o código com uma boa/má/sem identação?
Comment: 22h da noite , você cansado , virada de implantação ou algo assim ,  ai precisa analisar um código de uma linguagem que não domina muito em um módulo do sistema que tem um conhecimento parco , não precisa alterar só mesmo tirar uma dúvida , aí você pega um código bagunçado e não indentado ...
Comment: @MurilloGoulart, o correto é [indentação](https://duvidas.dicio.com.br/identacao-ou-indentacao/). Identar não existe na língua portuguesa.
Comment: Uma observação: a indentação no Python é obrigatória, sim.
Comment: Tá, mas é indentação ou identação? :)
Comment: @AndersonCarlosWoss bom comentário, um adicional: temos uma comunidade sobre português na rede e tem esta pergunta inclusive sobre o assunto [**Identar, indentar, ou endentar?**](https://portuguese.stackexchange.com/q/1823/8)
Answer: Serve para manter o código mais fácil de entender.
Por exemplo, veja este código sem indentação alguma:
if (a) {
if (b) {
while (c) {
d();
}
} else if (e) {
f();
} else if (g) {
h();
}
} else if (i) {
while (j) {
k();
}
}

Agora veja o mesmo código com uma indentação muito mal-feita:
if (a) {
    if (b)
  {
        while (c) {
    d();
}
  }
else
      if (e)
 {
 f();
        }
else if (g)
       {
      h();
              }
   } else
 if (i) {
    while (j) {
      k();
         }
    }

E agora o código bem indentado:
if (a) {
    if (b) {
        while (c) {
            d();
        }
    } else if (e) {
        f();
    } else if (g) {
        h();
    }
} else if (i) {
    while (j) {
        k();
    }
}

Observe que no código bem indentado, é muito mais fácil se perceber logo de cara, como é que as estruturas estão aninhadas. Já no código sem indentação, o que o olho e o cérebro humano vê é apenas uma sopa de abre e fecha chaves, ifs, whiles, etc e fica difícil saber onde as coisas começam e onde terminam. No código mal-indentado, é ainda pior, pois há um esforço mental extra em perceber que a indentação sugerida é inadequada e entender qual seria a correta.
Enfim, tudo se resume a facilitar a leitura do código para um humano, e não para uma máquina.
Em especial, veja esses exemplos terríveis onde a indentação errada faz as instruções parecerem estar no lugar errado:
if (x)
    y();
    z();

if (a)
    if (b)
        c();
else
    d();

if (x)
    // y();

z();

No primeiro caso, o z() parece estar dentro do if, mas está fora. No segundo caso, o else está no if interno, mas foi indentado como se estivesse no externo. No terceiro caso, como a linha do y() foi comentada, o z() acabou entrando de carona dentro do if. Esses casos patológicos são evitados se você delimitar o escopo sempre com chaves (ou o equivalente dependendo da linguagem) ou usar uma linguagem sensível a indentação como o Python.
Para o compilador, a indentação quase sempre não importa. A principal exceção é obviamente o Python, onde o compilador se utiliza da indentação para aninhar as estruturas. Uma outra exceção que lembro é de Scheme/Racket, onde embora o compilador não precise da indentação quando o código está correto, no caso de haver um erro de compilação ele vai usar a indentação para sugerir onde é o local mais provável do erro ter ocorrido.
Answer:
A resposta do @Victor trata perfeitamente de linguagens curly bracketed, as demais focam em questões mais conceituais

Em Python, código mal identado não é nem código válido:
# inválido
if marmota:
marmotante()
executoso()

# válido
if suricate:
    seboso()
executoso()

Também perceba que a identação define os blocos. Então, caso se dê suricate, então executamos seboso, caso não se dê, não executamos seboso; já executoso sempre é executado, independente do retorno de suricate.
A questão de identação e blocos de códigos em Python é tão forte que statements que necessitam um bloco de código em seguida, precisam ter pelo menos uma operação de noop identada (vide essa pergunta: Qual a diferença entre break, pass e continue em python? )
# exemplo copiado da resposta da pergunta acima
def soma_de_quadrados(x, y):
    pass # noop, nenhuma operação =]

Não conheço nenhuma outra linguagem que preza por identação forte como o Python preza, normalmente a identação é algo que o autor faz para o leitor do código, estando preso a elementos sintáticos.
Answer: A identação é um recurso fundamental para a legibilidade de um código, pois adiciona informação importante, do tipo: qual bloco de código pertence a uma função ou método? Ela também ajuda a entender a hierarquia de elementos em código HTML e XML. Acredito que todo programador já espera encontrar algum tipo de indentação quando vai ler qualquer código.
A indentação é completamente irrelevante para o compilador, já que ele elimina quaisquer caracteres não significativos para a sua análise.
Mas lembre-se:

Qualquer idiota pode escrever código que um computador entenda. Bons
  programadores escrevem código que humanos podem entender. - Martin
  Fowler

Mais sobre o tema pode ser encontrado aqui.
Answer: A indentação é bastante importante.
Para pessoas que seguem profissões de programação há que ter em conta que não estamos a trabalhar sozinhos e que outras pessoas poderão ter de via a pegar no nosso trabalho. Quem diz a indentação diz o uso de comentários.
Algumas empresas grandes como a Google/Microsoft têm até regras de organização de código para diferentes projetos. Estas regras incluem indentação/comentários/organização do código em geral etc.


Dragging in UIWebView

Question: Is there a way to prevent a UIWebView from being dragged?
Also, is there a way to actually overwride the common UIWebView functions such as highlighting?
Hope someone can answer me.
Thanks
Answer: webview.scrollView.scrollEnabled = NO;

Answer: You can look up the scrollView of the webView and disable the scrolling with this code:
UIScrollView *scrollView = nil;
for(UIView *aView in webView.subviews){
    if([aView isKindOfClass:[UIScrollView class] ]){
        scrollView = (UIScrollView *)aView;
        scrollView.scrollEnabled = NO;
        scrollView.bounces = NO;
    }
}

Answer: To prevent the drag:

To override the highlighting:

So, on the highlighting part:

The 1st line disables selection (like on text)
The 2nd line disables the actual highlight
The 3rd option disables the "popup" you see when you press an image for 2 seconds, asking if you'd like to download/save

Keep the ones you need.
Hope this helps :)

Dragging in UIWebView


Neo4j OGM 3.0.0-M1 Failed to instantiate [org.neo4j.ogm.session.SessionFactory]

Question: In my Spring Boot 1.5.2 / Neo4j 3.1.2 / SDN 4 application I'm trying to use Neo4j OGM 3.0.0-M1
Right now the application fails with a following exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.data.neo4j.transaction.SharedSessionCreator#0': Cannot resolve reference to bean 'sessionFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.example.domain.configuration.Neo4jTestConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.session.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:634)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:448)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:659)
    ... 56 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.example.domain.configuration.Neo4jTestConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.session.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    ... 71 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.session.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 80 common frames omitted
Caused by: java.lang.NullPointerException: null
    at org.neo4j.ogm.config.Configuration.equals(Configuration.java:159)
    at org.neo4j.ogm.session.SessionFactory.<init>(SessionFactory.java:72)
    at org.neo4j.ogm.session.SessionFactory.<init>(SessionFactory.java:52)
    at com.example.domain.configuration.Neo4jTestConfig.sessionFactory(Neo4jTestConfig.java:22)
    at com.example.domain.configuration.Neo4jTestConfig$$EnhancerBySpringCGLIB$$a7edbc94.CGLIB$sessionFactory$0(<generated>)
    at com.example.domain.configuration.Neo4jTestConfig$$EnhancerBySpringCGLIB$$a7edbc94$$FastClassBySpringCGLIB$$ffac7974.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
    at com.example.domain.configuration.Neo4jTestConfig$$EnhancerBySpringCGLIB$$a7edbc94.sessionFactory(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 81 common frames omitted

This is my Neo4jConfig:
@Configuration
@EnableNeo4jRepositories(basePackages = "com.example.domain.repository.neo4j")
@EnableTransactionManagement
public class Neo4jTestConfig {

    @Bean
    public Neo4jTransactionManager transactionManager() throws Exception {
        return new Neo4jTransactionManager(sessionFactory());
    }

    @Bean
    public SessionFactory sessionFactory() {
        return new SessionFactory("com.example");
    }

}

What can be a reason of this issue and how to solve it ?
Answer: There are significant changes in OGM 3.0 that are not backwards compatible with the Spring 4.x, Spring Boot 1.x and Spring Data Neo4J 4.x family.
If you want to use the new OGM 3.0 please use the Spring 5.x, Spring Boot 2.x and Spring Data Neo4J 5.x family. Note that all these projects are currently under active development and may not be 100% stable.


Unsure how to move text outside of staff in LilyPond

Question: I'm attempting to notate a choral psalm where only certain refrains are sung in four-part harmony, with the first few refrains are just the unison psalm melody sung by all parts. I'm attempting to do this by placing text between the instrument names before the staves on the first line, as with this example:

This is what I have so far: http://pastebin.com/Tu7tW27X
So far, I've attempted to do this by placing a boxed text object above the lower staff and then moving it left, but this still leaves an unsightly gap between the staves that I can't seem to remove. Is there a way to either directly print this text between the instrument names or move it from elsewhere without disturbing the spacing between the staves?
Comment: You really should be asking such specific questions on the Lilypond user list (lists.gnu.org/mailman/listinfo/lilypond-user), which is full of people only too happy to show exactly this kind of specialist knowledge.
Answer: Instrument names can contain markups, so you can put the box inside one.
\markup {
    {
      \center-column {
        \raise #5 \box \center-column {
          "SATB"{"after v.3 & 4"}
        }
        "Tenor & Bass." " " " " " "}
    }
  }

Answer: The cleanest way to do this is to create a new StaffGroup for your SA and TB staves, and give it its own instrumentName. That will automatically center the boxed text between the staves, without having to manually raise it by the correct amount depending on how Lilypond formats the music on the first system of the score.
You need to suppress the extra bracket around the new StaffGroup.
This is a basic skeleton. Personally I prefer to put all the instrument names in the score block, rather than scattered around the rest of the input, but whoever wrote the MuseScore-to-Lilypond converter did it differently!
\score {
  <<
  \context ChoirStaff = B {
    <<
    \context Staff = ATrpartA {
      \set Staff.instrumentName = #"Discantus."
      <<
        \context Voice = ATrvoiceAA { }
      >>
    }
    \new StaffGroup {
      \set StaffGroup.systemStartDelimiter = #'SystemStartBar
      \set StaffGroup.instrumentName = \markup {
        \box \center-column { "SATB"{"after v.3 & 4"} } }
      <<
        \context Staff = ASpartB {
          \set Staff.instrumentName = #"Soprano & Alto."
          \ASpartB
        }
        \context Staff = ABpartC {
           \set Staff.instrumentName = #"Tenor & Bass."
           \ABpartC
        }
      >> }
    >> } % end of StaffGroupB
  >> } % end of score-block