When is it ok to remove the intercept in a linear regression model?

Question: I am running linear regression models and wondering what the conditions are for removing the intercept term.
In comparing results from two different regressions where one has the intercept and the other does not, I notice that the $R^2$ of the function without the intercept is much higher. Are there certain conditions or assumptions I should be following to make sure the removal of the intercept term is valid?
Comment: **NB**: Some of these comments and replies address essentially the same question (framed in the context of a housing price regression) which was merged with this one as a duplicate.
Comment: What would the intercept mean in your model? From the information in your question, it seems it would be the expected value of your response when sqft=0 and lotsize=0 and baths=0. Is that ever going to occur in reality?
Comment: Instead of the y= a + b1 x1 + b2 x2 + b3x3,  can I omit a?
Comment: A side point: $R^2$ does not have such good properties when you don't include an intercept in your model, so it's not the best statistic to use for your comparison.
Comment: the intercept has no meaning. so when writing up a formula for the expected value of a house, can I leave this out?
Answer: The shortest answer: never, unless you are sure that your linear approximation of the data generating process (linear regression model) either by some theoretical or any other reasons is forced to go through the origin. If not the other regression parameters will be biased even if intercept is statistically insignificant (strange but it is so, consult Brooks Introductory Econometrics for instance). Finally, as I do often explain to my students, by leaving the intercept term you insure that the residual term is zero-mean.
For your two models case we need more context. It may happen that linear model is not suitable here. For example, you need to log transform first if the model is multiplicative. Having exponentially growing processes it may occasionally happen that $R^2$ for the model without the intercept is "much" higher.
Screen the data, test the model with RESET test or any other linear specification test, this may help to see if my guess is true. And, building the models highest $R^2$ is one of the last statistical properties I do really concern about, but it is nice to present to the people who are not so well familiar with econometrics (there are many dirty tricks to make determination close to 1 :)).
Comment: -1 for "never", see example 1 of Joshuas' answer
Comment: @Curious, "never" is written with "unless" examples below just show the exceptions when it is legal to remove intercept. When you don't know the data generating process or theory, or are not forced to go through the origin by standardization or any other special model, keep it. Keeping intercept is like using the trash bin to collect all the distortions caused by linear approximation and other simplifications. P.S. practically the response shows that you read just shortest :) Thanks a lot to Joshua (+1) for the extended examples.
Comment: You missed the point of Joshua Example 1 and seem to still ignore it completely. In models with categorical covariate the removal of the intercept results in the same model with just different parametrization. This is a legitimate case when intercept can be removed.
Comment: @Curious, in Joshua example 1, you need to add a new dummy variable for the level of the categorical variable you previously considered as baseline, and this new dummy variable will take the value of the intercept, so you are NOT removing the intercept, just renaming it and reparameterizing the rest of the parameters of the categorical covariate.  Therefore the argument of Dmitrij holds.
Answer: Removing the intercept is a different model, but there are plenty of examples where it is legitimate.  Answers so far have already discussed in detail the example where the true intercept is 0.  I will focus on a few examples where we may be interested in an atypical model parametrization.
Example 1: The ANOVA-style Model.  For categorical variables, we typically create binary vectors encoding group membership.  The standard regression model is parametrized as intercept + k - 1 dummy vectors.  The intercept codes the expected value for the "reference" group, or the omitted vector, and the remaining vectors test the difference between each group and the reference.  But in some cases, it may be useful to have each groups' expected value.
dat <- mtcars
dat$vs <- factor(dat$vs)

## intercept model: vs coefficient becomes difference
lm(mpg ~ vs + hp, data = dat)

Coefficients:
(Intercept)          vs1           hp
   26.96300      2.57622     -0.05453

## no intercept: two vs coefficients,
## conditional expectations for both groups
lm(mpg ~ 0 + vs + hp, data = dat)

Coefficients:
     vs0       vs1        hp
26.96300  29.53922  -0.05453

Example 2: The case of standardized data.  In some cases, one may be working with standardized data.  In this case, the intercept is 0 by design.  I think a classic example of this was old style structural equation models or factor, which operated just on the covariance matrices of data.  In the case below, it is probably a good idea to estimate the intercept anyway, if only to drop the additional degree of freedom (which you really should have lost anyway because the mean was estimated), but there are a handful of situations where by construction, means may be 0 (e.g., certain experiments where participants assign ratings, but are constrained to give out equal positives and negatives).
dat <- as.data.frame(scale(mtcars))

## intercept is 0 by design
lm(mpg ~ hp + wt, data = dat)

Coefficients:
(Intercept)           hp           wt
  3.813e-17   -3.615e-01   -6.296e-01

## leaving the intercept out
lm(mpg ~ 0 + hp + wt, data = dat)

Coefficients:
     hp       wt
-0.3615  -0.6296

Example 3: Multivariate Models and Hidden Intercepts.  This example is similar to the first in many ways.  In this case, the data has been stacked so that two different variables are now in one long vector.  A second variable encodes information about whether the response vector, y, belongs to mpg or disp.  In this case, to get the separate intercepts for each outcome, you suppress the overall intercept and include both dummy vectors for measure.  This is a sort of multivariate analysis.  It is not typically done using lm() because you have repeated measures and should probably allow for the nonindepence.  However, there are some interesting cases where this is necessary.  For example when trying to do a mediation analysis with random effects, to get the full variance covariance matrix, you need both models estimated simultaneously, which can be done by stacking the data and some clever use of dummy vectors.
## stack data for multivariate analysis
dat <- reshape(mtcars, varying = c(1, 3), v.names = "y",
  timevar = "measure", times = c("mpg", "disp"),
             direction = "long")
dat$measure <- factor(dat$measure)

## two regressions with intercepts only
lm(cbind(mpg, disp) ~ 1, data = mtcars)

Coefficients:
             mpg     disp
(Intercept)   20.09  230.72

## using the stacked data, measure is difference
## between outcome means
lm(y ~ measure, data = dat)

Coefficients:
(Intercept)   measurempg
      230.7       -210.6

## separate 'intercept' for each outcome
lm(y ~ 0 + measure, data = dat)

Coefficients:
measuredisp   measurempg
     230.72        20.09

I am not arguing that intercepts should generally be removed, but it is good to be flexible.
Comment: +1. I didn't take people to be rigidly saying 'never', but it's always nice to have another perspective & this is a very clear & thoughtful response. Welcome to CV, it'll be great to have you as part of the community.
Comment: @Joshua: Sorry that I am asking a question on a almost 2 year old post, but are there any references on your first example? I am thinking of running a no-intercept model on my data where the predictor variable is categorical, and I am interested in knowing whether each level is significantly different from 0. Thanks!
Comment: @Alex Any good regression text ought to do (chapter 8 of Applied Multiple Regression/Correlation Analysis for the Behavioral Sciences 3rd ed. covers this some)--- you just need it to talk about contrasts and how to dummy code categorical variables.  One way to think about it is that you are estimating separate intercepts for each group, rather than leaving the intercept out.
Comment: @Joshua , your first example has caused some confusion [elsewhere on this site](https://stats.stackexchange.com/a/369729/).  My understanding here is that you are suggesting a handy trick to show parameter estimates without needing to mess with adding the value for the intercept, and that you are not suggesting that the usual course is to use a model with the intercept removed to conduct anova.  In R, in just about every case, one would use a model with an intercept to conduct a traditional anova.
Comment: @SalMangiafico Yes, that's correct. I'm not advocating removing the intercept as a standard model approach.
Answer: There are good answers here.  Two small things:

Regarding a higher $R^2$ when the intercept is dropped, you should read this excellent answer by @cardinal. (In short, statistical software sometimes uses a different definition for $R^2$ when the intercept is forced to 0. So the reported $R^2$ for models with and without an intercept might simply not be comparable.)
Several people make the point that you should be certain the intercept must be 0 (for theoretical reasons) before dropping it, and not just that it isn't 'significant'.  I think that's right, but it's not the whole story.  You also need to know that the true data generating function is perfectly linear throughout the range of $X$ that you are working with and all the way down to 0.  Remember that it is always possible that the function is approximately linear within your data, but actually slightly curving.  It may be quite reasonable to treat the function as though it were linear within the range of your observations, even if it isn't perfectly so, but if it isn't and you drop the intercept you will end up with a worse approximation to the underlying function even if the true intercept is 0.
Comment: @AdamO makes a similar point to #2 here: [positive linear regression coefficient](http://stats.stackexchange.com/a/89775/), but develops the idea much more fully.
Comment: "if it isn't and you drop the intercept you will end up with a worse approximation to the underlying function even if the true intercept is 0" Wouldn't this be the case for many other terms as well?  For example, the function $y=x^3+x+1$ has no quadratic term, but the model family $y=mx+b$ will fit worse than one without a quadratic term.  This just seems to be a symptom of underfitting generally, and not a unique property of the intercept term.
Comment: @Scott, when you have a cubic term, the $x^2$ is a kind of intercept (see here: [Does it make sense to add a quadratic term but not the linear term to a model?](https://stats.stackexchange.com/a/28741/)).
Comment: *"even if it isn't perfectly so, but if it isn't and you drop the intercept you will end up with a worse approximation to the underlying function even if the true intercept is 0."* If dropping the intercept would result in a lot worse estimate/prediction then the intercept term will often not be insignificant. When the intercept term is insignificant then this means that the noise is probably larger than the value of the intercept term. The estimate of the intercept might fit the noise rather than the true underlying intercept and this can increase the expected squared error.
Comment: @SextusEmpiricus statistical significance isn't the same as predictive accuracy.  It's a fallacy to assume that whatever is significant will enhance your out of sample predictive accuracy & that whatever is nonsignificant will lead to overfitting & detract from predictive accuracy.
Comment: @gung I agree that significance is not the best measure and something like cross validation should decide whether or not a model with/without intercept is better. However, when we have a case where the intercept is not significant, then at least we have a case where the noise is large relative to the parameter size. Significance might not be the best way to include a parameter or not, but neither is it correct to say that the intercept always needs to be included except when it is theoretically zero. It is also when the intercept is relatively small that we might decide on leaving it out...
Comment: ... and as you point out it is not just about the intercept being zero because a function might actually not be truly linear, and the intercept term might help to 'correct' for the false model specification. But, then the intercept is just like other parameters and a way to improve the fit, as well as a potential danger for over-fitting. Leaving it out can be an option and not just when it is theoretically zero.
Answer: You shouldn't drop the intercept, regardless of whether you are likely or not to ever see all the explanatory variables having values of zero.
If you remove the intercept then the other estimates all become biased.  Even if the true value of the intercept is approximately zero (which is all you can conclude from your data), you are messing around with the slopes if you force it to be exactly zero.
UNLESS - you are measuring something with a very clear and obvious physical model that demands intercept be zero (eg you have height, width and length of a rectangular prism as explanatory variables and the response variable is volume with some measurement error).  If your response variable is value of the house, you definitely need to leave the intercept in.
Comment: Can you please explain, why we need the intercept for house price prediction? why would all the X be zero for any house?
Comment: A bit late here, but I'm guessing because it's unlikely the value of a house would ever be 0, regardless of it's characteristics.
Comment: *"If you remove the intercept then the other estimates all become biased"* This is not specific for the intercept. The same is true for other regressor terms. If we leave out other regressor terms that are approximately zero then we also introduce bias. It also doesn't matter so much because bias is not the main parameter that we care about. Often we find it more important to reduce the expectation of the square of the error or the expectation of some other non-linear cost function.
Comment: Land alone is worth something, so even a dimensionless house is valuable.
Answer: OK, so you've changed the question a LOT
You can leave out the intercept when you know it's 0.  That's it.  And no, you can't do it because it's not significantly different from 0, you have to know it's 0 or your residuals are biased.  And, in that case it is 0 so it won't make any difference if you leave it out... therefore, never leave it out.
The finding you have with $R^2$ suggests the data are not linear.  And, given that you had area as a predictor that particular one is probably definitely not linear.  You could transform the predictor to fix that.
Comment: What about when we wish to test for cointegration using Engle/Granger 2-step? http://en.wikipedia.org/wiki/Cointegration
Comment: "you have to know it's 0 or your residuals are biased" many people miss this crucial point and say that the beta will be biased, but that's wrong because the betas are not in any way dependent on the intercept.
Comment: @baibo the betas/coefficients might become biased when the regressors correlate with the (removed) intercept term. When you fit a model $y = bx$ while the true model is $y=a+bx$ then the estimate of $b$ will become biased. An obvious example is in the image here: https://stats.stackexchange.com/a/325395/164061
Comment: *"you have to know it's 0 or your residuals are biased*" What is the problem with this? Do we care about this bias when the goal is to make a best prediction, for instance based on reducing the expectation of the squared error?
Answer: Most multiple regression models include a constant term (i.e., the intercept), since this ensures that the model will be unbiased--i.e., the mean of the residuals will be exactly zero. (The coefficients in a regression model are estimated by least squares--i.e., minimizing the mean squared error. Now, the mean squared error is equal to the variance of the errors plus the square of their mean: this is a mathematical identity. Changing the value of the constant in the model changes the mean of the errors but doesn't affect the variance. Hence, if the sum of squared errors is to be minimized, the constant must be chosen such that the mean of the errors is zero.)
In a simple regression model, the constant represents the Y-intercept of the regression line, in unstandardized form. In a multiple regression model, the constant represents the value that would be predicted for the dependent variable if all the independent variables were simultaneously equal to zero--a situation which may not physically or economically meaningful. If you are not particularly interested in what would happen if all the independent variables were simultaneously zero, then you normally leave the constant in the model regardless of its statistical significance. In addition to ensuring that the in-sample errors are unbiased, the presence of the constant allows the regression line to "seek its own level" and provide the best fit to data which may only be locally linear.
However, in rare cases you may wish to exclude the constant from the model. This is a model-fitting option in the regression procedure in any software package, and it is sometimes referred to as regression through the origin, or RTO for short. Usually, this will be done only if:

it is possible to imagine the independent variables all assuming the value zero simultaneously, and you feel that in this case it should logically follow that the dependent variable will also be equal to zero; or else
the constant is redundant with the set of independent variables you wish to use.

An example of case (1) would be a model in which all variables--dependent and independent--represented first differences of other time series. If you are regressing the first difference of Y on the first difference of X, you are directly predicting changes in Y as a linear function of changes in X, without reference to the current levels of the variables. In this case it might be reasonable (although not required) to assume that Y should be unchanged, on the average, whenever X is unchanged--i.e., that Y should not have an upward or downward trend in the absence of any change in the level of X.
An example of case (2) would be a situation in which you wish to use a full set of seasonal indicator variables--e.g., you are using quarterly data, and you wish to include variables Q1, Q2, Q3, and Q4 representing additive seasonal effects. Thus, Q1 might look like 1 0 0 0 1 0 0 0 ..., Q2 would look like 0 1 0 0 0 1 0 0 ..., and so on. You could not use all four of these and a constant in the same model, since Q1+Q2+Q3+Q4 = 1 1 1 1 1 1 1 1 . . . . , which is the same as a constant term. I.e., the five variables Q1, Q2, Q3, Q4, and CONSTANT are not linearly independent: any one of them can be expressed as a linear combination of the other four. A technical prerequisite for fitting a linear regression model is that the independent variables must be linearly independent; otherwise the least-squares coefficients cannot be determined uniquely, and we say the regression "fails."
A word of warning:  R-squared and the F statistic do not have the same meaning in an RTO model as they do in an ordinary regression model, and they are not calculated in the same way by all software.  See this article for some caveats.  You should not try to compare R-squared between models that do and do not include a constant term, although it is OK to compare the standard error of the regression.
Note that the term "independent" is used in (at least) three different ways in regression jargon: any single variable may be called an independent variable if it is being used as a predictor, rather than as the predictee. A group of variables is linearly independent if no one of them can be expressed exactly as a linear combination of the others. A pair of variables is said to be statistically independent if they are not only linearly independent but also utterly uninformative with respect to each other. In a regression model, you want your dependent variable to be statistically dependent on the independent variables, which must be linearly (but not necessarily statistically) independent among themselves.
Comment: What article are you referring to?
Answer: Short answer: (almost) NEVER. In the linear regression model
$$
   y = \alpha + \beta x + \epsilon
$$,
if you set $\alpha=0$, then you say that you KNOW that the expected value of $y$ given $x=0$ is zero.  You almost never know that.
$R^2$ becomes higher without intercept, not because the model is better, but because the definition of $R^2$ used is another one! $R^2$ is an expression of a comparison of the estimated model with some standard model, expressed as reduction in sum of squares compared to sum of squares with the standard model. In the model with intercept, the comparison sum of squares is around the mean. Without intercept, it is around zero! The last one is usually much higher, so it easier to get a large reduction in sum of squares.
Conclusion: DO NOT LEAVE THE INTERCEPT OUT OF THE MODEL (unless you really, really know what you are doing).
Some exceptions:   One exception is a regression representing a one-way ANOVA with dummies for ALL the factor levels (usually one is left out) (but that is only seemingly an exception, the constant vector 1 is in the column space of the model matrix $X$.)
Compositional data compositional-data as predictors (but also only seemingly an exception) as an example see How to measure ML model performance across race via area level demographic info
Otherwise, such as physical relationships $s=v t$ where there are no constant. But even then, if the model is only approximate (speed is not really constant), it might be better to leave in a constant even if it cannot be interpreted.
There are also special models which leave out the intercept. One example is paired data, twin studies.
Answer: Full revision of my thoughts.  Indeed dropping the intercept will cause a bias problem.
Have you considered centering your data so an intercept would have some meaning and avoid explaining how some (unreasonable) values could give negative values?  If you adjust all three explanatory variables by subtract the mean sqrft, mean lotsize and mean bath, then the intercept will now indicate the value (of a house?) with average sdrft, lotsize, and baths.
This centering will not change the relative relationship of the independent variables.  So, fitting the model on the centered data will still find baths as insignificant.  Refit the model without the bath included.  You may still get a large p-value for the intercept, but it should be included and you will have a model of the form y=a+b(sqrft)+c(lotsize).
Answer: I just spent some time answering a similar question posted by someone else, but it was closed. There are some great answers here, but the answer I provide is a bit simpler. It might be more suited to people who have a weak understanding of regression.
Q1: How do I interpret the intercept in my model?
In regression models, the goal is to minimise the amount of unexplained variance in an outcome variable:
y = b0 + b1⋅x + ϵ
where y is the predicted value of your outcome measure (e.g., log_blood_hg), b0 is the intercept, b1 is the slope, x is a predictor variable, and ϵ is residual error.
The intercept (b0) is the predicted mean value of y when all x = 0. In other words, it's the baseline value of y, before you've used any variables (e.g., species) to further minimise or explain the variance in log_blood_hg.
By adding a slope (which estimates how a one-unit increase/decrease in log_blood_hg changes with a one unit increase in x, e.g., species), we add to what we already know about the outcome variable, which is its baseline value (i.e. intercept), based on change in another variable.
Q2: When is it appropriate to include or not include the intercept, especially in regards to the fact that the models give very different results?
For simple models like this, it's never really appropriate to drop the intercept.
The models give different results when you drop the intercept because rather than grounding the slope in the baseline value of Y, it is forced to go through the origin of y, which is 0. Therefore, the slope gets steeper (i.e. more powerful and significant) because you've forced the line through the origin, not because it does a better job of minimizing the variance in y. In other words, you've artificially created a model which minimizes the variance in y by removing the intercept, or the initial grounding point for your model.
There are cases where removing the intercept is appropriate - such as when describing a phenomenon with a 0-intercept. You can read about that here, as well as more reasons why removing an intercept isn't a good idea.
Answer:
This question has already many answers and basically they relate to the two cases (the first and second point below). But the answers make not clear why it is the case. While pondering about this and thinking about why the intercept would be different from other regressors (why should we never exclude the intercept term but is this not the case for other regressors?), I came to the idea that the intercept is not different. The intercept does have a special role like computations of the $R^2$ value and making the mean of residuals zero, but that does not make it that you can not remove it like you can with other regressor terms.
It can be ok to remove the intercept when ...

When you have categorical variables. In that case the intercept is already in the column space of the regressors.
Example this answer to 'Lm adding coefficients for different level of variable'.

When you theoretically know that it should be zero.
Example: fitting an exponential decay for which the function is $y(t) = y_0 e^{-ct}$.
In some way you could see the $y_0$ as an intercept, because it behaves like an intercept when you plot the logarithm of $y$. But this function is different from $y(t) = y_0 e^{-ct} + b$ where this $b$ might be some baseline. Even when it is possible, due to measurement error, that the intercept/baseline $b$ is not zero, then one might whish to not include it (see next point).

Not only when the intercept is theoretically exactly zero but also when the intercept is small.
The variance in the estimate of the intercept might introduce an increased variance in the estimates or predictions. A model without the intercept could have better performance.
In this way the intercept is like any other regressor variable that we might choose to eliminate based on some bad performance in a cross validation. If you do model selection and believe that regressor variables can be eliminated, the the same must be true for the intercept term.
Because I am too lazy to prove this rigourously, I made an example in R code that demonstrates this
set.seed(1)

### this function makes a linear fit
### either with or without intercept
### and it returns the squared error of the estimates
sim = function(intercept = TRUE){

  ### the data
  x = -10:10
  u = 0.1+x
  y = u+rnorm(length(x))

  ### fitting
  if (intercept == TRUE) {
    mod = lm(y ~ 1+x)
  } else {
    mod = lm(y ~ 0+x)
  }

  ### return the error in the estimates
  sum((predict(mod)-u)^2)
}

### perform simulations
r1 = replicate(10^4,sim(TRUE))
r0 = replicate(10^4,sim(FALSE))

### with intercept 1.981789
mean(r1)
### without intercept 1.206731
mean(r0)

Sidenote: Not including the intercept (or any other parameter), just to reduce the variance is a bit rigorous. Alternatives to not including the intercept could be some regularisation.

The reason why we say that we should never exclude the intercept is, I guess, not because there is some theoretical reason that should give the intercept some advantage that other regressor terms do not have. But instead, it is because in practice the intercept is non zero and large enough to be important for the estimates.


Functional equation on $\mathbb Q_p^\star$

Question: I am trying to find solutions of functional equation $f(xy)=f(x)+f(y)$ for all $x,y\in\mathbb Q_p\setminus\{0\}=\mathbb Q_p^\star$. Where $f:\mathbb Q_p^\star\to\mathbb R$. I know some solutions:
1) $f(x)\equiv 0$.
2) $f(x)=\log |x|_p$
Here, $p$ is prime and $\mathbb Q_p$ is the field of all $p-$adic numbers.
My question is: Does there exist any other solution which of cause not similar to these solutions as above? (ie.. I mean $f(x)=\log |x|^n_p$ is "similar" to 2).)
Comment: My question might be silly, how does the $p$-adic field differ from the rational number field?
Comment: @Hai: Probably you want $\mathbb{Q}_p^*$ instead of $\mathbb{Q}_p$.
Comment: I don't think that constant function $\equiv 1$ works. Also, probably you meant $f(x)=n\log |x|_p$. That is, a multiple rather than a power of the logarithm of the $p$-adic absolute value
Comment: $f(0\cdot 0)=f(0)+f(0)$ implies $f(0)=0$. Then $f(x\cdot 0)=f(x)+f(0)$ implies $f(x)=0$.
Comment: @Easy: $\mathbb{Q}_p$ is uncountable, complete with respect to the $p$-adic metric, etc.
Comment: Yes I mean $x,y\in\mathbb Q_p^\star$, I have edited
Answer: You are asking for homomorphisms from the multiplicative group $\mathbb{Q}_p^*$ to the additive group of real numbers.
It is known that $\mathbb{Q}_p^*$ is a direct product of three subgroups. The infinite cyclic subgroup generated by $p$, the cyclic subgroup of order $p-1$ consisting of non-zero Teichmüller elements (generated by $\zeta$, a primitive root of unity of order $p-1$), the group $1+p\mathbb{Z}_p$ of $p$-adic integers congruent to $1$.
A homomorphism from a direct product of groups is determined, if we know its restriction to the constituent groups. The infinite cyclic group is easy to handle, as we can select the image of $p$ to by any real number $a$ we want, and define $f_a(p^n)=na$. The finite cyclic group is also easy to handle: the additive groups has darn few elements of a finite order, so such a homomorphism has to be trivial.
The last factor, $U:=1+p\mathbb{Z}_p$, is more interesting. It is actually a bit scary to think about classifying the homomorphisms from $U$ to $\mathbb{R}$. For one, I can't write down a single non-trivial one. Yet the following argument shows that they exist. Consider the subgroup $K=\langle 1+p\rangle \le U$. This is an infinite cyclic group, so we get a homomorphism $\phi_b$ from $K$ to $\mathbb{R}$ simply by sending $1+p$ to an arbitrary real number $b$, and extending that. Because the additive group of $\mathbb{R}$ is divisible, it is an injective object in the category of abelian groups (see e.g. Hilton-Stammbach). Therefore there is a homomorphism $g_b:U\to\mathbb{R}$ such that the restriction of $g_b$ to $K$ is equal to $\phi_b$. The proof of this involves a typical use of Zorn's lemma, so if you belong to the church that does not believe in the axiom of choice, then I cannot convince you that such a homomorphism exists.
Given the above there will other such functions. Namely those of the form
$$
f(p^n\zeta^j u)= na + g_b(u).
$$
If $g_b$ is the trivial homomorphism, then you get a scalar multiple of the logarithm of the $p$-adic value. Otherwise you get something else.
Comment: Note that the multiplicative unit group $U_1:=1+p{\bf Z}_p$ is isomorphic to ${\bf Z}_p$ under addition, which is clearly a ${\bf Z}_{(p)}$-vector space of uncountable dimension (where ${\bf Z}_{(p)}:={\bf Z}_p\cap{\bf Q}$). This allows a full characterization of $\hom({\bf Q}_p,{\bf R})$ as ${\bf R}^{\oplus{\frak c}}$. (For the background facts you mention, I [plug this answer of mine](http://math.stackexchange.com/questions/283293/what-is-the-index-of-the-p-th-power-of-mathbb-q-p-in-mathbb-q-p/301551#301551).) Or we could have just noticed $\dim_{\bf Q}{\bf Q}_p={\frak c}$ to begin with..
Comment: @anon: The use of the isomorphism of $U_1$ and the additive group of $\mathbf{Z}_p$ is a nice idea. But why is $\mathbf{Z}_p$ a free $\mathbf{Z}_{(p)}$-module? Assuming that's what the rest of your argument is based on?
Comment: Erm, I forgot ${\bf Z}_{(p)}$ is not a field. Now it's not as clear to me if ${\bf Z}_p$ is a free ${\bf Z}_{(p)}$-module.
Comment: @anon:  No problem, obviously. I was hoping that you had found a way of avoiding the use of injectivity of $\mathbf{R}$. I didn't, so I didn't bother using the $\mathbf{Z}_p$-module structure of $U_1$.
Comment: A very nice answer, thanks
Comment: What does the $\mathbb R^{\oplus c}$ mean?
Comment: @HaiMinh: A direct sum of ${\frak c}:=|{\bf R}|$-many copies of $\bf R$ as an additive group. (Err, ignore that last sentence I just said about ${\bf Q}_p$ as a $\bf Q$-vector space, I momentarily forgot we were talking about the units ${\bf Q}_p^\times$...)


Issue with the train_test_split function of sklearn library

Question: from sklearn.utils import shuffle
dataset,labels = shuffle(dataset,labels)
print("Shuffling of dataset is completed")
print(" ")

from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(tokenizer=lambda doc: doc, lowercase=False)
X = vectorizer.fit_transform([dataset])

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,labels,test_size=0.1,stratify=labels)
print("Completing the splitting of data.")
print(" ")

This is a classification model which I am building using sklearn library.
I am getting an error by the function train_test_split() where the error states :

ValueError: Found input variables with inconsistent numbers of samples: [1, 88702]

I have tried to resolve this error through different methods which were present like changing the shape of X and Y but still I am not able to get desired result.
Comment: Can you show me the shape of X and labels?  What is the dataset look like?
Answer: This error means that the length of your X vector does not equal the length of your labels vector.  If you print the shapes of the X vector I would expect it to be of length 1.
It seems like the line
X = vectorizer.fit_transform([dataset])

should be changed to
X = vectorizer.fit_transform(dataset)

according to the documentation for sklearn.feature_extraction.text found here


How do I call some function after an AHAH callback that adds a new item?

Question: I've tried
<code>'#ahah'   => array(
        "url": "/?q=content/js_add_more/pmemo/field_tracks_disks_chapter",
    "event": "mousedown",
    "keypress": true,
    "wrapper": "field-tracks-disks-chapter-items",
    "selector": "#edit-field-tracks-disks-chapter-field-tracks-disks-chapter-add-more",
    "effect": "fade",
    "method": "replace",
    "progress": { "type": "throbber" },
    "button": { "field_tracks_disks_chapter_add_more": "Add another item" } ,
        'after' : 'myJsFunction'
),
</code>
But it is not working.
I wasn't able to find any solutions to this problem.
Thanks for any help.
Answer: You could handle ajaxComplete jquery event, which is called right after completion of ajax/ahah requests.


Find the kernel of a linear transformation of $P_2$ to $P_1$

Question: For some reason, this particular problem is throwing me off:
Find the kernel of the linear transformation:
$T: P_2 \rightarrow P_1$  $T(a_0+a_1x+a_2x^2)=a_1+2a_2x$
Since the kernel is the set of all vectors in $V$ that satisfy $T(\vec{v})=\vec{0}$, it's obvious that $a_0$ can be any real number. What matters, if I understand correctly, is that $a_1$ and $a_2$ should equal 0 in order to satisfy the zero vector (i.e. $0+2(0)x$).
Granted that what I stated is correct, why would my book say that the $\ker(T)=\{a_0: a_0 \; \text{is real}\}$?
Yes, $a_0$ can be any real number, but what must $a_1$ or $a_2$ equal? I don't see it specified within the set. Perhaps it's implied - I'm not sure.
Let me add some more detail:
Again, if I understand correctly, I could make a system of equations as such:
$a_1 = 0$
$2a_2 = 0$
From that I can translate it into a matrix and find that $a_1$ and $a_2$ really does equal zero.
Answer: Your argument is totally correct. Your book means that $\ker(T)=\{a_0+0\cdot x+0\cdot x^2|a_0\in \mathbb{R}\}$, i.e. $a_1=0$ and $a_2=0$, which is the same as you proved.
Comment: If the vectors in that space were given as tuples $(a_0,a_1,a_2)$, you'd have to say that $\ker T=\{(a_0,0,0)\mid a_0\in\mathbb R\}$. But here we are allowed to write simply $a_0$ instead of $a_0+0\cdot x+0\cdot x^2$.
Comment: Thanks, I thought there was something I completely missed! For some reason, my book states the answer for any transformation for polynomials in that form.


Send email to users that checked 'yes' - php and modx

Question: I have a database of 'user comments' that holds the comment, the userId, true/false for if they want to be emailed.
My issue is that if a user comments on a post 5 times, they are in that database 5 times and thus, they get 5 of the same emails. Here is my setup:
Find users in the database that want to be emailed about this comment
<code>$ab = $modx->newQuery('Comments');
$ab->leftJoin('modUserProfile','Profile',array('Profile.internalKey = Comments.author'));
$ab->leftJoin('Bulletin','Bulletin',array('Bulletin.id = Comments.bulletin_id'));
$ab->where(array('Comments.bulletin_id' => $bullId));
$ab->where(array('Comments.email' => 1));
$ab->select(array('Comments.*','Profile.fullname as fullname' , 'Profile.email as email' , 'Bulletin.title as title'));
$emailList = $modx->getCollection('Comments',$ab);
</code>
Now, email them
<code>foreach ($emailList as $e){
$modx->getService('mail', 'mail.modPHPMailer');
$modx->mail->address('to',$e->email);
$modx->mail->set(modMail::MAIL_BODY,$message);
$modx->mail->set(modMail::MAIL_SUBJECT,'A new comment has been posted!');}
</code>
What should I use to email the users so that they only get 1 email regardless of the amount of comments they have made? Please let me know if the above is not clear enough. Thank you!!
Comment: You're looping through the results of `$emailList`. Don't loop, just send the email if result is `$emailList >= 1`
Comment: @relentless thanks for this. I've just had a chance to attempt your resolution but I am a bit confused as to how I would capture the email address of the user? If I don't loop (which makes sense) then how can I get the address of those that fit `$emailList >= 1`?
Answer: I think you can add a groupby....
<code>$ab->groupby('email');
</code>
after your select
Comment: Thank you Sean, this was the perfect solution. I read up on this and it's very helpful. Thanks again.


GPO to set DFS Path to Active in Referral List for mapped drive

Question: I have a DFS Namespace of domain.lcl\DFS that replicates a folder ReplFolder across 3 geographically dispersed servers:
\\VANCOUVER\FolderA
\\MADRID\FolderA
\\TOKYO\FolderA

I can manually map a drive to \\domain.lcl\DFS\ReplFolder and it works great.
However, I want to be able to set up a GPO to set the active path so that the users in Vancouver, their active path is set to \\VANCOUVER\FolderA, and same for the users in the other 2 locations. Is there a GPO or Registry setting that would be able to set this?
This can already be manually done by right clicking the drive letter on the client, selecting the DFS tab, and setting the preferred Path to "Active". But for 500+ users, I'd like to automate this somehow.
Unfortunately we do not have the capability to configure AD Sites & Services in our environment (it is hosted by another organization), otherwise I would go that route.
Thanks very much in advance.
Comment: AD Sites & Services is a core "component" of AD. It's always "enabled". You may not have it configured with your sites and subnets but it's never not "enabled". Why don't you take the time to configure it?
Comment: Yes, apologies, you are correct. It is not "configured" and we go through another organization that manages our AD who tell us they can't because of how their subnetting is set up. I've updated the question to reflect that, thanks for the clarifying comment.
Answer: DFS clients rely on ADS&S configuration to locate the "nearest" available copy of a DFS share.
Also, the same approach is used to locate the "nearest" Domain Controller(s).
You definitely should get it configured properly.
It's crucial to proper AD operation in a multi-site environment.


How do I chose recipient email address depending on textfield value?

Question: I have created a webform which has a "Reference number" textfield.
When someone types 101 in that textedfield, the submitted form should be send to email@example.com; if someone types 777, the submitted form should be send to email@example.com.
Is there a way to achieve this?
Comment: Nearly sure it is a token or replacement string based off the field name.
Answer: The first solution that comes to my mind will be using hook_form_alter.
and take the value of the field.
Based on the value, send the mail to appropriate address.
But most likely there will be a module for that.
Meanwhile..
http://agileadam.com/webform-mail-alter
can be of service
Regards
Oleg


PHP MySQL Time Attendance - How to limit Time In (Once a day)

Question: I have a Textbox(which is for the Employee ID) and a Time In button that saves the Employee ID, and the current date, and current time(different columns) to the database when clicked. The question is how can I limit the Time in to just once a day.
Here is my code:
<?php
    require "sampledb.php";

    date_default_timezone_set("Asia/Hong_Kong");

    $date = date('Y-m-d');
    $time = date('h:i:s');

    if(isset($_POST['in'])){
        $sql = "INSERT INTO timein(empid, date, time) VALUES(".$_POST['eid'].", '$date', '$time')";
        $conn->exec($sql);

        if($sql==true){
            echo '';
            echo '<meta http-equiv="refresh" content="0;url=sample.php" />';
            }else{
            echo "Time in Failed";
        }
    }
?>

        <form method="POST" action="">
            <?php echo date("d/m/y : h:i:sa", time()) . "
"; ?>
            <input type="text" name="eid" placeholder="Employee ID">
            <input type="submit" name="in" value="Time in">
        </form>

Comment: you can mae the date unique with respect to empid in the table timein. So that there will be only one entry for particular empoyee for that particular date
Comment: Let MySQL handle this with a UNIQUE KEY
Comment: But if I set the date to UNIQUE KEY, the new employee ID will not be able to Time IN
Comment: Combine it with employeeID
Answer: You can add a UNIQUE CONSTRAINT on both the column(empid & date)
Run below query to your table first
ALTER TABLE `timein` ADD UNIQUE `unique_index`(`empid `, `date`);

The combination of empid and date must be unique.
Answer: Before doing your sql insert, do a SELECT statement to see if there is a row for that employee in the required date.
If the num_rows is 0 then proceed to INSERT.
If num_rows is not 0 show error alert message.
Try the below in your php.
if(isset($_POST['in'])){
        $eid = $_POST['eid'];
        $sql = "SELECT empid FROM timein WHERE empid='$eid' AND date='$date'";
        $con->exec($sql);
        $count = $con->rowCount();
        if($count == 0){
           $sql = "INSERT INTO timein(empid, date, time) VALUES(".$_POST['eid'].", '$date', '$time')";
           $conn->exec($sql);
 echo '';
            echo '<meta http-equiv="refresh" content="0;url=sample.php" />';
        } else {
            echo "Time in Failed";
        }

    }

Comment: This might cause duplicate records in rare cases. (user double clicks, 2 select queries return 0 records, 2 inserts will happen). So a unique key is the solution
Comment: I don't get why the downvote. He can use Post, Redirect, Get method if that's the case. Or disable the button upon the first click.
Comment: Because its only half a solution in my opinion. The database should be responsible for the integrity of your data. Not a (client side) script


substituting ID for value

Question: I have two tables, one is Players and second one is Participant's List. I keep full data about player only in Players table and i want to display Participant's data but i don't want to show ID, which are stored in this table. I want to replace them with data relevant to stored ID. So i wrote script:
SELECT pl.surname as Name FROM players pl, participants_list p
WHERE pl.player_id = p.player_id

And it works, but it replaces only one value which is the name of player. I need to replace also name of the tournament from other table. I don't know how to combine those two operations, which may result in getting 2 columns replaced with value. For example

Smith | Tournament 1
Kowalsky | Tournament 2

The data I have is:
Players Table
Player's id|Player's Name| and more

Events Table
Event's id|Event's Name| and more

Participant's Table
Player's id|Event's id

Comment: update your question add  a clear data sample and the expected  result
Answer: Try this out:
select b.player_name,c.event_name
from
Participants_table a
left join
players table b
on a.player_id = b.player_id
left join
events_table c
on a.event_id = c.event_id;

Let me know in case of any queries.

substituting ID for value


Postfix main.cf wildcard emails using access

Question: In my postfix main.cf I have:
smtpd_recipient_restrictions = reject_unauth_destination, check_recipient_access regexp:/etc/postfix/access.me

...
virtual_alias_maps    = hash:/etc/postfix/virtual

...
In my virtual file I have:
email@example.com                            firstname.lastname@example.com
firstname.lastname@example.com                           firstname.lastname@example.com
@mydomain.com                             email@example.com

In my access.me file I have:
/^abc/ OK
/email@example.com/  OK
/email@example.com/  REJECT failed test
/@mydomain.com/  REJECT failed test contact email@example.com

With this I have successfully failed (!) to send to email@example.com so I know access.me is being read correctly by postfix.
If I send to firstname.lastname@example.com it fails (correctly) rejected by Line 4 of access.me
However if I try to mail firstname.lastname@example.com it fails with "User unknown in virtual alias table" which shows that it is accepted by line 1 of access.me, but I need this email to succeed and get through.
So nearly there but I must be misunderstanding postfix logic...
Tim
Comment: Can you post the entire maillog,generated by postfix, when the mail was sent to `email@example.com`? Also post your `postconf -n` if possible.
Answer: Having tested it again to provide more information I found that it did actually work (for the first time) so either the virtual file was not the latest version or there was a delay in propagation.
This configuration was designed so that customers could send emails to us where the email address itself was generated from data (ex: location and language of user), since coupled with the sender address the customer need not input anything apart from their comments.
So this does seem to be a valid way to enable customised email addresses to get through postfix while rejecting randomised email addresses / spam.
Tim


Consulta SQL com ID a partir de uma combobox - C#

Question: Estou montando um pequeno sistema onde eu criei um Formulario em que há um Combobox que lista o nome dos funcionários armazenados no banco e um DataGrid que mostra os serviços feito por eles (valor, descrição e cliente).

Ao selecionar o funcionario no Combobox,eu queria que mostrasse os servicos feito por ele,entao eu criei
SELECT func_nome, serv_desc, serv_cliente, serv_valor FROM func_serv
INNER JOIN func_dados ON func_serv.func_id = func_dados.func_id
WHERE func_serv.func_id = //codigo da funcionaria;

Minha duvida é, ao pegar o índice do combobox selecionado, como posso usa-lo como parâmetro para minha consulta sql, substituindo aquela parte comentada do código.
Eu pensei em criar vários ifs, mas se for criado um novo funcionário, irei ter de por mais um if.
Me ajudem, por favor
Comment: como você preenche o Combobox? Se você pegar os dados diretamente do banco de dados, pode usar as propriedades DisplayMember e ValueMember do ComboBox e pegar o SelectedValue do combo com o ID selecionado.
Comment: conexao = new SqlConnection(conexao_sqlserver);
            SqlCommand sql = new SqlCommand("select func_nome from func_dados", conexao);
            SqlDataAdapter da = new SqlDataAdapter(sql);

            DataTable dt = new DataTable();

            da.Fill(dt);

            try
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    cb_func_caderneta.Items.Add(dt.Rows[i]["func_nome"]);
                }
            }
            catch (Exception erro)
            {
                throw erro;
            }
Answer: Basta você concatenar o valor do comboxBox, usei o @ para escapar a string para melhor visualização.
SqlCommand sql = new SqlCommand(@"SELECT func_nome, serv_desc, serv_cliente, serv_valor FROM func_serv
                                INNER JOIN func_dados ON func_serv.func_id = func_dados.func_id
                                WHERE func_serv.func_id = " + comboBox1.SelectedValue);

Comment: Obrigado,acho que isso irá resolver meu problema, testei de uma maneira mais generica e vi que vai da certo.
agora so to procurando um jeito pegar o valor do combobox e passar pro DAL ,que é outra classe
Comment: Você pode passar o valor pro DAL por parâmetro, não? Se a resposta solucionou seu problema, peço que marque como resposta.
Comment: Eu teria que criar um metodo getCombo pra pegar o valor do combobox?
Comment: Algo assim: http://pastebin.com/8isc9B1B
Answer: @Vinicius Caminha,
você pode usar o

SelectedValue

. Where meucampo = combobox.SelectedValue;
Comment: Eu posso chamar a funçao SelectedValue dentro da pesquisa sql ?
Answer: E se você fizesse algo assim:
public SqlDataReader lista_dados_servico(object idFuncionario)
{
    conexao = new SqlConnection(conexao_sqlserver);
    var query = @"SELECT func_nome, serv_desc, serv_cliente, serv_valor FROM func_serv
        INNER JOIN func_dados ON func_serv.func_id = func_dados.func_id
        WHERE func_serv.func_id = @idFuncionario";

    using (var comando = new SqlCommand(query, conexao))
    {
        comando.Parameters.AddWithValue("@idFuncionario", idFuncionario);

        return comando.ExecuteReader();
    }
}

e usasse assim:
var idFuncionario = comboBox1.SelectedValue;

var reader = lista_dados_servico(idFuncionario);

while (reader.Read())
{
    var index = dataGridView1.Rows.Add();

    int indexColunaNome    = 0,
        indexColunaServico = 1,
        indexColunaCliente = 2,
        indexColunaValor   = 3;

    dataGridView1[index, indexColunaNome].Value    = reader["func_nome"];
    dataGridView1[index, indexColunaServico].Value = reader["serv_desc"];
    dataGridView1[index, indexColunaCliente].Value = reader["serv_cliente"];
    dataGridView1[index, indexColunaValor].Value   = reader["serv_valor"];
}

isto não resolveria seu problema?
Answer: Primeiramente alteraria a forma como você preenche o comboBox para:
conexao = new SqlConnection(conexao_sqlserver);
SqlCommand sql = new SqlCommand("select func_nome,func_id from func_serv", conexao);
SqlDataAdapter da = new SqlDataAdapter(sql);
DataTable dt = new DataTable();
da.Fill(dt);

comboBox1.DataSource = (dt.Tables[0]);
comboBox1.DisplayMember = ("func_nome");
comboBox1.ValueMember = ("func_id");

Depois no IndexChanged do Combobox ou em um botão de pesquisa colocaria o código do @Laerte
SqlCommand sql = new SqlCommand(@"SELECT func_nome, serv_desc, serv_cliente,serv_valor FROM func_serv
                            INNER JOIN func_dados ON func_serv.func_id = func_dados.func_id
                            WHERE func_serv.func_id = " + comboBox1.SelectedValue);

SqlDataAdapter da = new SqlDataAdapter(sql);
DataTable dt = new DataTable();
da.Fill(dt);

Datagrid1.DataSource=dt.Tables[0];

Obs.: Caso o sistema não esteja organizado em camadas para uma melhor organização e Prática de Desenvolvimento de Sistema segue alguns links para possível estudo.
http://www.devmedia.com.br/desenvolvimento-em-3-camadas-conceitos/22277
https://rafaelnicolettdeveloper.wordpress.com/2012/07/04/projeto-em-camadas-c-crud/


How to solve this nonlinear differential equation?

Question: The nonlinear differential equation is:
$$y''+ a(\sin(y))y'+ b(\cos(y))=0$$
where $a,b \in \mathbb{R}$ and $b>0$.
How could i solve? Thank you in advance for any idea or proposed solution.
Answer: As you can see that this does not contain $x$, you can put $v=y'$ so that:
$$
y''=\frac{dv}{dx}=\frac{dv}{dy}\frac{dy}{dx}=\frac{dv}{dy}v
$$
Hence the equation becomes,
$$
v\frac{dv}{dy}+a\sin(y)v+ b\cos(y)=0
$$
From this first order differential equation u can get $v=f(y)$ and hence you can get $y$ from it.
Hope this helps you......
Refer 2nd point of this link
Answer: You could assume you knew a power series for $y =\sum_{n=0}^{\infty} a_nx^n$ and take two formal derivatives and plug everything into the DE.   With a certain amount of tedium, you can get expressions for $\cos y$ and $\sin y$ and then $(\cos y)y^{\prime}.$  Keep grinding away and you can write out the first few terms of the power series for the left side.  The power series for the right side has zeros for all coefficients, so if you set the left-side coefficients equal to zero, you can successively solve for each $a_n$ in terms of $a_0$ and $a_1$.  You end up with $y= a_0y_1+a_1y_2$ where $y_1$ and $y_2$ are power series, with as many terms as you care to grind out.
Comment: Hello B. Goddard, thank you very much for your time and for your feedback.
With respect to the solution in power series could you please (if you like and you have time) to show me some steps?
Because I remember that the solution in power series is used to solve some differential equations in the case, however, they are linear, but this being a non-linear as use this method?
Thank you so much for your concern!


Retornar dia da semana a partir de uma data no formato dd/mm/yyy

Question: tenho essa função que me traz o dia da semana:
public static String getWeek(String date){ //ex 07/03/2017
    String dayWeek = "---";
    GregorianCalendar gc = new GregorianCalendar();
    try {
        gc.setTime(new SimpleDateFormat("MM/dd/yyyy", BRAZIL).parse(date));
        switch (gc.get(Calendar.DAY_OF_WEEK)) {
            case Calendar.SUNDAY:
                dayWeek = "DOM";
                break;
            case Calendar.MONDAY:
                dayWeek = "SEG";
                break;
            case Calendar.TUESDAY:
                dayWeek = "TER";
            break;
            case Calendar.WEDNESDAY:
                dayWeek = "QUA";
                break;
            case Calendar.THURSDAY:
                dayWeek = "QUI";
                break;
            case Calendar.FRIDAY:
                dayWeek = "SEX";
                break;
            case Calendar.SATURDAY:
                dayWeek = "SAB";

        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dayWeek;
}

Mas ela esta me trazendo o dia da semana anterior, ex: 07/03/2017 terça-feira ele traz como segunda-feira.
Answer: Sua máscara de formatação de data está errada. Você está usando o formato MM/dd/yyyy quando sua string recebe um formato dd/MM/yyyy. Apenas altere a máscara:
public static String getWeek(String date){ //ex 07/03/2017
    String dayWeek = "---";
    GregorianCalendar gc = new GregorianCalendar();
    try {
        gc.setTime(new SimpleDateFormat("dd/MM/yyyy").parse(date));
        switch (gc.get(Calendar.DAY_OF_WEEK)) {
            case Calendar.SUNDAY:
                dayWeek = "DOM";
                break;
            case Calendar.MONDAY:
                dayWeek = "SEG";
                break;
            case Calendar.TUESDAY:
                dayWeek = "TER";
            break;
            case Calendar.WEDNESDAY:
                dayWeek = "QUA";
                break;
            case Calendar.THURSDAY:
                dayWeek = "QUI";
                break;
            case Calendar.FRIDAY:
                dayWeek = "SEX";
                break;
            case Calendar.SATURDAY:
                dayWeek = "SAB";

        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dayWeek;
}

Bastou esta alteração e funcionou corretamente, veja: https://ideone.com/LLcvyr
Answer: A sua máscara está errada, como o Articuno respondeu.
Você também pode encurtar o seu código para:
public static String getWeek(String date){ //ex 07/03/2017
        String dayWeek = "---";
        GregorianCalendar gc = new GregorianCalendar();
        try {
            gc.setTime(new SimpleDateFormat("dd/MM/yyyy", new Locale("pt", "BR")).parse(date));
           return new SimpleDateFormat("EEE", new Locale("pt", "BR")).format(gc.getTime()).toUpperCase();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dayWeek;
    }

Comment: Alternativa interessante, +1 :)
Answer: A partir do Java 8, você pode usar a API java.time
import java.time.DayOfWeek;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;

public static String getDayOfWeek(String data) {
    DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    DayOfWeek dow = DayOfWeek.from(parser.parse(data));
    return dow.getDisplayName(TextStyle.SHORT, new Locale("pt", "BR")).toUpperCase();
}

System.out.println(getDayOfWeek("07/03/2017")); // TER

Eu também poderia fazer LocalDate.parse(data, parser).getDayOfWeek() para obter o DayOfWeeek, mas se você só quer o dia da semana, não precisa criar um LocalDate à toa.
E mudei o nome do método, pois getWeek dá a impressão de que vai retornar toda a semana, mas você só quer um dia da semana, então deixei como getDayOfWeek.

Outro detalhe é que no seu método você está capturando a exceção (ParseException caso a data seja inválida), imprimindo o stack trace e depois retornando "---". Sem entrar no mérito de não estar tratando o erro, uma forma de ter o mesmo comportamento é:
public static String getDayOfWeek(String data) {
    try {
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd/MM/uuuu")
                                      .withResolverStyle(ResolverStyle.STRICT);
        DayOfWeek dow = DayOfWeek.from(parser.parse(data));
        return dow.getDisplayName(TextStyle.SHORT, new Locale("pt", "BR")).toUpperCase();
    } catch (DateTimeException e) {
        e.printStackTrace();
    }
    return "---";
}

System.out.println(getDayOfWeek("31/02/2017")); // ---

O ResolverStyle, conforme explicado aqui, serve para garantir que datas como 29 de fevereiro em anos não-bissextos e 31 de abril sejam consideradas inválidas - tem uma explicação mais detalhada nesta resposta, na seção "Modos de parsing".

Mas este método não é muito eficiente, pois toda vez que for chamado, cria duas instâncias de DateTimeFormatter: uma explicitamente, e outra implicitamente, dentro de getDisplayName (veja no código fonte).
Sendo assim, uma alternativa é guardar essas instâncias em variáveis estáticas, assim eles são criados apenas uma vez:
public static DateTimeFormatter DOW_FMT = DateTimeFormatter.ofPattern("E", new Locale("pt", "BR"));

public static DateTimeFormatter PARSER = DateTimeFormatter.ofPattern("dd/MM/uuuu").withResolverStyle(ResolverStyle.STRICT);

public static String getDayOfWeek(String data) {
    try {
        return DOW_FMT.format(PARSER.parse(data)).toUpperCase();
    } catch (DateTimeException e) {
        e.printStackTrace();
    }
    return "---";
}

Repare que assim você nem precisa criar o DayOfWeek, pois o resultado do parsing é passado diretamente para o formatador, que já pega o dia da semana e formata.

Se quiser continuar usando SimpleDateFormat, há um detalhe importante: por padrão, esta classe aceita datas inválidas como "33/22/2017", fazendo alguns ajustes bem estranhos:
// 33/22/2017 vira 2 de novembro de 2018
System.out.println(new SimpleDateFormat("dd/MM/yyyy").parse("33/22/2017")); // Fri Nov 02 00:00:00 BRT 2018

Para evitar esse problema, basta setá-lo como não-leniente:
public static String getWeek(String date) { // ex 07/03/2017
    String dayWeek = "---";
    GregorianCalendar gc = new GregorianCalendar();
    SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yyyy");
    parser.setLenient(false); // <- setar como não-leniente, assim não aceita datas inválidas
    try {
        gc.setTime(parser.parse(date));
        switch (gc.get(Calendar.DAY_OF_WEEK)) {
            etc...

Uma outra resposta sugeriu usar DateFormatSymbols, mas foi usado getWeekdays, que retorna os nomes completos ("Domingo", "Segunda-feira", etc). Sem contar que se você criá-la sem especificar um Locale, como foi sugerido, ela usará o default que está configurado na JVM (por exemplo, se a JVM estiver configurada com algum locale em inglês, serão retornados os nomes neste idioma - "Sunday", "Monday", etc).
Então se quiser usar aquela solução, você precisa especificar o locale para que use o português, e usar getShortWeekdays para ter os nomes abreviados. E como esse array é fixo e será usado sempre que o método for chamado, pode criá-lo apenas uma vez também:
public static String[] WEEKDAYS = new DateFormatSymbols(new Locale("pt", "BR")).getShortWeekdays();

public static String getDayOfWeek(String data) {
    try {
        SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yyyy");
        parser.setLenient(false);
        Calendar cal = Calendar.getInstance();
        cal.setTime(parser.parse(data));
        return WEEKDAYS[cal.get(Calendar.DAY_OF_WEEK)].toUpperCase();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return "---";
}

Ou, se quiser otimizar mais ainda, já deixe o array com os nomes em maiúsculas, assim você não precisa chamar toUpperCase:
public static String[] WEEKDAYS;
static {
    WEEKDAYS = new DateFormatSymbols(new Locale("pt", "BR")).getShortWeekdays();
    for (int i = 0; i < WEEKDAYS.length; i++) {
        WEEKDAYS[i] = WEEKDAYS[i].toUpperCase();
    }
}

public static String getDayOfWeek(String data) {
    try {
        SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yyyy");
        parser.setLenient(false);
        Calendar cal = Calendar.getInstance();
        cal.setTime(parser.parse(data));
        return WEEKDAYS[cal.get(Calendar.DAY_OF_WEEK)];
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return "---";
}

E claro que também tem a opção de usar um array com os valores fixos:
public static String[] WEEKDAYS = {"DOM", "SEG", "TER", "QUA", "QUI", "SEX", "SAB"};

public static String getDayOfWeek(String data) {
    try {
        SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yyyy");
        parser.setLenient(false);
        Calendar cal = Calendar.getInstance();
        cal.setTime(parser.parse(data));
        return WEEKDAYS[cal.get(Calendar.DAY_OF_WEEK) - 1];
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return "---";
}

O detalhe é que arrays começam do índice zero, mas os valores de DAY_OF_WEEK vão de 1 a 7 (Domingo a Sábado), então preciso subtrair 1 para obter o valor correto (no caso de getShortWeekdays não é necessário porque ele retorna um array cuja primeira posição é uma string vazia).
Answer: Costumo usar o componente DateChooser na interface.
O componente DateChooser retorna um java.util.Calendar.
Com isso, você poderá  usar métodos como estes:
public String diaDaSemana(Calendar calendar) {
    return new DateFormatSymbols().getWeekdays()[calendar.get(Calendar.DAY_OF_WEEK)];
}

public String nomeDoMes(Calendar calendar) {
    return new DateFormatSymbols().getMonths()[calendar.get(Calendar.MONTH)];
}

Comment: Isso não retorna no formato indicado ("SEG", "TER", etc), pois `getWeekdays` retorna os nomes completos ("Domingo", "Segunda-feira", etc) - deveria ser `getShortWeekdays` para ter os nomes abreviados - e se a JVM estiver configurada com um *locale* que não seja em português, os nomes virão em outro idioma - veja os detalhes na [minha resposta](https://pt.stackoverflow.com/a/463769/112052) :-)


Associative array, sum values of the same key

Question: So I have this associative array (dump done with kint)

d
Instead of having the key "Conference" repeating 3 times. I want to have it just once and sum the 3 values into one in order to have something like:
Conference : 4534
And same thing for all other keys that are repeating..
Is there a native function that can do that ?
Answer: You can try
$data = array(
  0 => array(
    'event' => 'Conference',
    'budget' => 3700,
  ),
  1 => array(
    'event' => 'Conference',
    'budget' => 500,
  ),
  2 => array(
    'event' => 'Showroom',
    'budget' => 1000,
  ),
  3 => array(
    'event' => 'Mission Chez client',
    'budget' => 2000,
  ),
  4 => array(
    'event' => 'Séminaire',
    'budget' => 700,
  ),
  5 => array(
    'event' => 'Livraison',
    'budget' => 4000,
  ),
  6 => array(
    'event' => 'Conference',
    'budget' => 334,
  ),
);

$sum = array_reduce($data, function ($a, $b) {
    isset($a[$b['event']]) ? $a[$b['event']]['budget'] += $b['budget'] : $a[$b['event']] = $b;
    return $a;
});

print_r(array_values($sum));

Output
Array
(
    [0] => Array
        (
            [event] => Conference
            [budget] => 4534
        )

    [1] => Array
        (
            [event] => Showroom
            [budget] => 1000
        )

    [2] => Array
        (
            [event] => Mission Chez client
            [budget] => 2000
        )

    [3] => Array
        (
            [event] => Séminaire
            [budget] => 700
        )

    [4] => Array
        (
            [event] => Livraison
            [budget] => 4000
        )

)

Comment: It preserves the second key "budget" but not the first one "event", it gives this: [link](http://d.pr/i/7rKM)
Comment: I really need to keep the same structure but sum values with the same key
Comment: Thx Baba, it is exactly what I'm looking for, but it seems that the values are sumed twice:
1- original array [link](http://d.pr/i/AfGz)
2- array after sum function [link](http://d.pr/i/8tEP)
'Livraison' for example should have 4000, any idea why It has 8000 ?
Comment: I can't work with image ... use print_r of the original array and add it to pastebin
Comment: Original array [link](http://pastebin.com/C2KenBt5) . Results array [link](http://pastebin.com/KpeSNrjx)
Answer: A simple suggestion:
$results = array();
foreach ($budgetByEventTemp as $value)
{
  if( ! isset($results[$value['event']]) )
  {
     $results[$value['event']] = 0;
  }

  $results[$value['event']] += $value['budget'];

}

var_dump($results);

Update according to comments
You can run over them again:
foreach($results as $key => $value)
{
  $structured_results[] = array('event' => $key, 'budget' => $value);
}

var_dump($structured_results);

Comment: Thank you for the suggestion, but that would not preserve the keys of the array (event and budget)
Comment: I fail to see why it should, when you wan't to sum up the values?
Comment: This array is encoded via json and sent to be cooked somewhere else, so I need to preserve the same structure and just sum values with the same key
Answer: $sumArray = array();

foreach ($myArray as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
  $sumArray[$id]+=$value;
  }
}

print_r($sumArray);

Comment: This unexplained answer generates warnings/errors.  Proof: https://3v4l.org/CHfSE
Answer: This option will group and sum values of all repeated indexes in an array.
Code here :
$aValues[]=array("nametogroup",10);
$aValues[]=array("nametogroup",20);
$aValues[]=array("nametogroup2",30);
$aValues[]=array("nametogroup2",20);
echo var_dump($aValues); // array before grouping
foreach ($aValues as  $id=>$value)
{
  $a2sum["{$value[0]}"]=$value[1] + $a2sum["{$value[0]}"];
}
echo var_dump($a2sum); //array after group and adding values

This will result into:
array
0 =>
array
  0 => string nametogroup (length=11)
  1 => int 10
1 =>
array
  0 => string nametogroup (length=11)
  1 => int 20
2 =>
array
  0 => string nametogroup2 (length=12)
  1 => int 30
3 =>
array
  0 => string nametogroup2 (length=12)
  1 => int 20

array
nametogroup => int 30
nametogroup2 => int 50

Answer: To iterate a set of data and return a potentially smaller set of data, array_reduce() is a wise "functional" choice.  Here is a slight variation on @Baba's answer using a null coalescing operator and a more intuitive variable naming convention.
Code: (Demo)
var_export(
    array_reduce(
        $data,
        function ($carry, $row) {
            $carry[$row['event']] = ($carry[$row['event']] ?? 0) + $row['budget'];
            return $carry;
        }
    )
);


Meu código Python funciona, mas não entendo o porquê de um int()

Question: Fiz um programa para cálculo de tempo de medicações. De acordo com os cálculos está tudo rodando perfeitamente, mas eu não entendi um detalhe, o porquê da necessidade de usar um int() em determinado momento.
Podem me explicar? Segue o código completo e abaixo a parte específica do 'problema':
# utf -8
import shutil

columns = shutil.get_terminal_size().columns
print("Olá, Rafaela, vamos calcular quantos dias seus medicamentos irão durar!".center(columns))

quantidade1 = float((input("Quantos comprimidos de 300MG você possui? ")))
quantidade2 = float((input("Quantos comprimidos de 600MG você possui? ")))
dosagem = float((input("Quantos MG você toma diariamente? ")))

total_mg = (quantidade1 * 300) + (quantidade2 * 600)

dias = (total_mg / dosagem)
meses = int((dias / 30))

if dias < 30:
    print("Seus medicamentos irão durar %.2f dias!".center(columns) % dias)
elif 60 > dias >= 30:
    dias -= 30
    print("Seus medicamentos irão durar %d mês e %d dias!".center(columns) % (meses, dias))
else:
    dias = dias - (meses * 30)
    print("Seus medicamentos irão durar %d meses e %d dias!".center(columns) % (meses, dias))

A questão é: se na linha 14 eu retirar o int(), o else simplesmente para de funcionar adequadamente e todas as respostas serão X meses e 0 dias (sempre 0 dias), mas eu não entendi o porquê. Alguém consegue me explicar?
meses = int((dias / 30))

Aqui está o exemplo do output do código com e sem int(), para o else, com os inputs() sendo , respectivamente, 240, 450 e 1500.
Seus medicamentos irão durar 7 meses e 18 dias!  usando int()
Seus medicamentos irão durar 7 meses e 0 dias!   não usando int()
Comment: Se foi você que escreveu o código, recomendo fortemente rever o seu processo de desenvolvimento. O natural é primeiro você entender o problema e a partir disso elaborar a solução; não elaborar uma solução para a partir dela buscar entender o problema, como fez.
Comment: Porque você está fazendo o casting de float para inteiro. Seu print está usando %d para mostrar o número, que espera um inteiro. Tente trocar de %d para %.2f assim como fez acima e tirar o int.
Comment: Troquei para %.2f e tirei o int, mas o problema voltou! _Seus medicamentos irão durar 822463 meses e 0.00 dias!_
Comment: Quanto ao processo de desenvolvimento, eu entendo o ponto, mas é só porquê estava tentando por em prática o que aprendi sobre Control Flow mesmo e parecia tudo ok, mas excepcionalmente o else não batia com o resultado esperado. Mexi em todos os cálculos pensando que eram a causa, mas no fim acabou sendo esse int.
Comment: A função `int()` retira todos os valores após o ".". Ela serve para transformar um valor para inteiro de base decimal, o que acaba truncando os valores para 0 casas decimais. Então, ao invés de ser _"3.5 meses"_, o correto para mostrar para o usuário seria _"3 meses e 15 dias"_
Answer: Seu problema está na última condição, mais precisamente em dias = dias - (meses * 30) (o qual você pode simplificar para dias -= (meses * 30)).
Se você não forçar com que meses seja um inteiro (usando int()), dias -= (meses * 30) sempre será igual a zero (uma vez que dias = meses * 30).
Com o exemplo que você deu, meses = 7.6 e meses = int(7.6) = 7. Percebe a diferença? Sempre é interessante checar a documentação oficial se tiver dúvidas dos comportamentos de funções built-in.
Ainda com o seu exemplo, dias = 228.0. Logo, 228.0 -= 7.6*30 = 0 e 228.0 -= 7*30 = 18.
Comment: Caraca, muito obrigado! Quebrei um pouco a cabeça mas entendi, no final das contas eu acabei cometendo o erro de lógica ao multiplicar `meses * 30` que nada mais foi o contrário do que eu tinha feito antes e os dois acabavam se subtraindo. Também percebi que se eu colocar `dias -= (int(meses) * 30)` só nesta linha, também viria a funcionar. Muito obrigado!
Comment: @AlecsanderCamilo se a resposta lhe ajudou, aceite-a


Tidyverse version of nested for loops

Question: I am wondering if there is a tidyverse implementation of the nested for loop. I am trying to "walk" along the elements of two nested lists and print out formatted tables.
library(xtable)

for (i in 1:9) {
  for (j in 1:7) {
    result <- tab_male[[i]][[j]]
    cat(result$form, result$num, sep = "\n")
    result_f <- xtable(result$table, digits = c(0, 0, 3, 2, 2, 3, 0))
    print(result_f, type = "html", include.rownames = FALSE)
  }
}

Data:
> list(list(list(form = "ISL_cor ~ MHQ_Heading_Male_Quartile +
> AHQ_Out_Games_MainPos",
>     num = "n = 243, v = 694", table = structure(list(term = c("MHQ_Heading_Male_Quartile6.01-15",
>     "MHQ_Heading_Male_Quartile15.01-53", "MHQ_Heading_Male_Quartile53.01+",
>     "MHQ_Heading_Male_Quartile"), estimate = c(-0.0791579099605819,
>     -1.31886212979935, -1.48893696108341, NA), std.error = c(0.401568948969462,
>     0.473022615063467, 0.530936266824937, NA), statistic = c(0.0388569214847496,
>     7.77382905796715, 7.86444062797599, 13.2403535895265), p.value = c(0.843732388037004,
>     0.00530085657147317, 0.00504164207971813, 0.00414463354304205
>     ), DF = c(NA, NA, NA, 3)), row.names = c(NA, -4L), class = c("tbl_df",
>     "tbl", "data.frame"))), list(form = "ISL_cor ~ AHQ_Heading_Male_Quartile + Visit_age + AHQ_Out_Games_MainPos",
>     num = "n = 243, v = 691", table = structure(list(term = c("AHQ_Heading_Male_Quartile435.01-861",
>     "AHQ_Heading_Male_Quartile861.01-1964", "AHQ_Heading_Male_Quartile1964.01+",
>     "AHQ_Heading_Male_Quartile"), estimate = c(-0.89154000871825,
>     -0.994316436351536, -1.57011199247759, NA), std.error = c(0.702047826647497,
>     0.661044419168572, 0.735530040163908, NA), statistic = c(1.61268028305808,
>     2.26249668129015, 4.55680487390649, 4.65540410577618), p.value = c(0.204115445829441,
>     0.13254022774479, 0.0327881883499254, 0.198840443392366),
>         DF = c(NA, NA, NA, 3)), row.names = c(NA, -4L), class = c("tbl_df",
>     "tbl", "data.frame"))), list(form = c("ISL_cor ~ MHQ_Unintentional_Impacts_Category + AHQ_Out_Games_MainPos + ",  "
> SchoolYears"), num = "n = 243, v = 694", table = structure(list(
>     term = c("MHQ_Unintentional_Impacts_Category1", "MHQ_Unintentional_Impacts_Category2+",
>     "MHQ_Unintentional_Impacts_Category"), estimate = c(-0.330107428454537,
>     -1.11363290045085, NA), std.error = c(0.421259777743314,
>     0.584132185200777, NA), statistic = c(0.614059714422183,
>     3.63464361400689, 3.74972860573148), p.value = c(0.433263337741689,
>     0.0565887187958448, 0.153375778086435), DF = c(NA, NA, 2)), row.names = c(NA,
> -3L), class = c("tbl_df", "tbl", "data.frame"))), list(form = c("ISL_cor ~ MHQ_Heading_Male_Quartile + AHQ_Heading_Male_Quartile +
> ",  "    Visit_age + AHQ_Out_Games_MainPos"), num = "n = 242, v =
> 690",
>     table = structure(list(term = c("MHQ_Heading_Male_Quartile6.01-15",
>     "MHQ_Heading_Male_Quartile15.01-53", "MHQ_Heading_Male_Quartile53.01+",
>     "AHQ_Heading_Male_Quartile435.01-861", "AHQ_Heading_Male_Quartile861.01-1964",
>     "AHQ_Heading_Male_Quartile1964.01+", "MHQ_Heading_Male_Quartile",
>     "AHQ_Heading_Male_Quartile"), estimate = c(-0.0479970904647452,
>     -1.12670431496527, -1.21854957357748, -0.700531880187201,
>     -0.49732099940717, -1.03791500617207, NA, NA), std.error = c(0.420765861836252,
>     0.530854303316158, 0.608326118209642, 0.701020625547379,
>     0.699785302029764, 0.77990402300362, NA, NA), statistic = c(0.0130121430708719,
>     4.50473482079907, 4.01248551738978, 0.99860610382089, 0.50506114901101,
>     1.77109256901535, 7.77644180358569, 1.97339725616004), p.value = c(0.909181684413754,
>     0.033801136898189, 0.045164522721187, 0.317648025163335,
>     0.477284698622016, 0.183246922804758, 0.0508651484245062,
>     0.577946522968363), DF = c(NA, NA, NA, NA, NA, NA, 3, 3)), row.names = c(NA,
>     -8L), class = c("tbl_df", "tbl", "data.frame"))), list(form = c("ISL_cor ~ MHQ_Heading_Male_Quartile +
> MHQ_Unintentional_Impacts_Category + ",  "    AHQ_Out_Games_MainPos +
> SchoolYears"), num = "n = 243, v = 694",
>     table = structure(list(term = c("MHQ_Heading_Male_Quartile6.01-15",
>     "MHQ_Heading_Male_Quartile15.01-53", "MHQ_Heading_Male_Quartile53.01+",
>     "MHQ_Unintentional_Impacts_Category1", "MHQ_Unintentional_Impacts_Category2+",
>     "MHQ_Heading_Male_Quartile", "MHQ_Unintentional_Impacts_Category"
>     ), estimate = c(-0.0437266901073021, -1.02439627611215, -1.01609109823191,
>     -0.167581634650727, -0.691121853494014, NA, NA), std.error = c(0.408524542630128,
>     0.473755244140277, 0.586929872792396, 0.426960923639793,
>     0.633883630020921, NA, NA), statistic = c(0.0114566304473933,
>     4.6754984937607, 2.99704224605943, 0.154055279458038, 1.18874903889876,
>     6.89149629148188, 1.19563579590938), p.value = c(0.914760697307542,
>     0.0305958220319473, 0.0834166758023506, 0.694689724690443,
>     0.275582035248557, 0.0754377535413996, 0.550010506640863),
>         DF = c(NA, NA, NA, NA, NA, 3, 2)), row.names = c(NA,
>     -7L), class = c("tbl_df", "tbl", "data.frame"))), list(form = c("ISL_cor ~ AHQ_Heading_Male_Quartile +
> MHQ_Unintentional_Impacts_Category + ",  "    Visit_age +
> AHQ_Out_Games_MainPos"), num = "n = 242, v = 690",
>     table = structure(list(term = c("AHQ_Heading_Male_Quartile435.01-861",
>     "AHQ_Heading_Male_Quartile861.01-1964", "AHQ_Heading_Male_Quartile1964.01+",
>     "MHQ_Unintentional_Impacts_Category1", "MHQ_Unintentional_Impacts_Category2+",
>     "AHQ_Heading_Male_Quartile", "MHQ_Unintentional_Impacts_Category"
>     ), estimate = c(-0.895040230761059, -0.912702903399016, -1.37975890875964,
>     -0.489641166512556, -0.988393112135669, NA, NA), std.error = c(0.694777627862569,
>     0.661366030220224, 0.729574978477178, 0.41719736053471, 0.576184797609155,
>     NA, NA), statistic = c(1.65956192470069, 1.90447420695097,
>     3.57656853703012, 1.37744016843595, 2.94263116126483, 3.74480686353552,
>     3.6683597648995), p.value = c(0.197662482281952, 0.167578366779483,
>     0.0586000822386175, 0.240537661418808, 0.0862700996563112,
>     0.290371619583202, 0.159744457294298), DF = c(NA, NA, NA,
>     NA, NA, 3, 2)), row.names = c(NA, -7L), class = c("tbl_df",
>     "tbl", "data.frame"))), list(form = c("ISL_cor ~ MHQ_Heading_Male_Quartile + AHQ_Heading_Male_Quartile + ",  "
> MHQ_Unintentional_Impacts_Category + Visit_age +
> AHQ_Out_Games_MainPos" ), num = "n = 242, v = 690", table =
> structure(list(term = c("MHQ_Heading_Male_Quartile6.01-15",
> "MHQ_Heading_Male_Quartile15.01-53",
> "MHQ_Heading_Male_Quartile53.01+",
> "AHQ_Heading_Male_Quartile435.01-861",
> "AHQ_Heading_Male_Quartile861.01-1964",
> "AHQ_Heading_Male_Quartile1964.01+",
> "MHQ_Unintentional_Impacts_Category1",
> "MHQ_Unintentional_Impacts_Category2+", "MHQ_Heading_Male_Quartile",
> "AHQ_Heading_Male_Quartile", "MHQ_Unintentional_Impacts_Category" ),
> estimate = c(0.027473221623339, -0.983296707817596,
> -0.998915061769465,
> -0.729302185929289, -0.516076193503656, -0.988004708036804, -0.326646742422211,
> -0.65317896922332, NA, NA, NA), std.error = c(0.428839704885747,
> 0.543671182971852, 0.642027892677446, 0.703866716093322, 0.699712682087769,
> 0.772736325651738, 0.425575113535084, 0.608192913919347, NA,  NA, NA), statistic = c(0.00410420648439035, 3.27112049517389,
> 2.42074660001576, 1.07357940675207, 0.543986547969826, 1.63476515114772,
> 0.589120608607216, 1.15340458748084, 6.043351999308, 1.86319524453419,
> 1.42191994516063), p.value = c(0.948919202216804, 0.0705094492798756,
> 0.11973785101195, 0.300138340000943, 0.460785251427891, 0.20104522602314,
> 0.44275937551614, 0.282837582724352, 0.109520000259034, 0.601280426978633,
> 0.491172458976363), DF = c(NA, NA, NA, NA, NA, NA, NA, NA, 3,  3, 2)), row.names = c(NA, -11L), class = c("tbl_df", "tbl", "data.frame" )))),
> list(list(form = "GMCT_mps ~ MHQ_Heading_Male_Quartile + Visit_age +
> AlcWeek_Category",
>     num = "n = 237, v = 675", table = structure(list(term = c("MHQ_Heading_Male_Quartile6.01-15",
>     "MHQ_Heading_Male_Quartile15.01-53", "MHQ_Heading_Male_Quartile53.01+",
>     "MHQ_Heading_Male_Quartile"), estimate = c(0.0395760177476687,
>     -0.0578397419137515, -0.170261152714884, NA), std.error = c(0.0397676090470122,
>     0.0452542398137336, 0.0525940258932902, NA), statistic = c(0.990387665627256,
>     1.63355644310893, 10.4799281952162, 17.8660680040739), p.value = c(0.319647644086372,
>     0.201211847352926, 0.00120678446475631, 0.000468728794495572
>     ), DF = c(NA, NA, NA, 3)), row.names = c(NA, -4L), class = c("tbl_df",
>     "tbl", "data.frame"))), list(form = "GMCT_mps ~ AHQ_Heading_Male_Quartile + Visit_age + AlcWeek_Category",
>     num = "n = 237, v = 672", table = structure(list(term = c("AHQ_Heading_Male_Quartile435.01-861",
>     "AHQ_Heading_Male_Quartile861.01-1964", "AHQ_Heading_Male_Quartile1964.01+",
>     "AHQ_Heading_Male_Quartile"), estimate = c(0.0782736360902089,
>     -0.048972529752338, -0.054639060767593, NA), std.error = c(0.0597872145397393,
>     0.0604457000742019, 0.0554338598664709, NA), statistic = c(1.71401404789434,
>     0.656408586949, 0.971529990187134, 5.75002358193762), p.value = c(0.190465395485205,
>     0.417830717685593, 0.324298899988633, 0.124426125086254),
>         DF = c(NA, NA, NA, 3)), row.names = c(NA, -4L), class = c("tbl_df",
>     "tbl", "data.frame"))), list(form = "GMCT_mps ~ MHQ_Unintentional_Impacts_Category + Visit_age + AlcWeek_Category",
>     num = "n = 237, v = 675", table = structure(list(term = c("MHQ_Unintentional_Impacts_Category1",
>     "MHQ_Unintentional_Impacts_Category2+", "MHQ_Unintentional_Impacts_Category"
>     ), estimate = c(-0.0924725285404226, -0.138136822260117,
>     NA), std.error = c(0.0417633318646855, 0.0512559415739351,
>     NA), statistic = c(4.90269851299699, 7.26324159859129, 9.6376937050893
>     ), p.value = c(0.0268147618892612, 0.00703801424817208, 0.0080760946996254
>     ), DF = c(NA, NA, 2)), row.names = c(NA, -3L), class = c("tbl_df",
>     "tbl", "data.frame"))), list(form = c("GMCT_mps ~ MHQ_Heading_Male_Quartile + AHQ_Heading_Male_Quartile + ",  "
> Visit_age + AlcWeek_Category"), num = "n = 236, v = 671",
>     table = structure(list(term = c("MHQ_Heading_Male_Quartile6.01-15",
>     "MHQ_Heading_Male_Quartile15.01-53", "MHQ_Heading_Male_Quartile53.01+",
>     "AHQ_Heading_Male_Quartile435.01-861", "AHQ_Heading_Male_Quartile861.01-1964",
>     "AHQ_Heading_Male_Quartile1964.01+", "MHQ_Heading_Male_Quartile",
>     "AHQ_Heading_Male_Quartile"), estimate = c(0.0241593271669994,
>     -0.0666007869613449, -0.163074252422677, 0.0899012847935602,
>     0.013943559394045, 0.0129068865425143, NA, NA), std.error = c(0.0400941429467429,
>     0.0454138676752813, 0.0525343520680203, 0.0594829658990324,
>     0.0599283957918893, 0.0569649590196029, NA, NA), statistic = c(0.36308457688939,
>     2.15070944001326, 9.63571690455555, 2.28426542850776, 0.0541354806668636,
>     0.0513366359485237, 13.6061341648373, 2.67625170039888),
>         p.value = c(0.546798111190475, 0.142504028765413, 0.00190829707331652,
>         0.13069200532417, 0.8160174131795, 0.820753538274401,
>         0.0034933791389206, 0.444278166840459), DF = c(NA, NA,
>         NA, NA, NA, NA, 3, 3)), row.names = c(NA, -8L), class = c("tbl_df",
>     "tbl", "data.frame"))), list(form = c("GMCT_mps ~ MHQ_Heading_Male_Quartile + MHQ_Unintentional_Impacts_Category + ",  "
> Visit_age + AlcWeek_Category"), num = "n = 237, v = 675",
>     table = structure(list(term = c("MHQ_Heading_Male_Quartile6.01-15",
>     "MHQ_Heading_Male_Quartile15.01-53", "MHQ_Heading_Male_Quartile53.01+",
>     "MHQ_Unintentional_Impacts_Category1", "MHQ_Unintentional_Impacts_Category2+",
>     "MHQ_Heading_Male_Quartile", "MHQ_Unintentional_Impacts_Category"
>     ), estimate = c(0.0506591738689037, -0.0368468123937406,
>     -0.135753001850915, -0.0715855611314002, -0.0903056110998311,
>     NA, NA), std.error = c(0.0388141649113782, 0.0462112087176506,
>     0.053281910979695, 0.0407964595310706, 0.0537851643952648,
>     NA, NA), statistic = c(1.70347479852339, 0.63577755200643,
>     6.49141385729885, 3.07897325923329, 2.81906098378486, 12.9059982343006,
>     4.51930360662492), p.value = c(0.191834175517877, 0.42524395559654,
>     0.0108396733083503, 0.0793105790194146, 0.0931508839484695,
>     0.00484436297520366, 0.104386825574409), DF = c(NA, NA, NA,
>     NA, NA, 3, 2)), row.names = c(NA, -7L), class = c("tbl_df",
>     "tbl", "data.frame"))), list(form = c("GMCT_mps ~ AHQ_Heading_Male_Quartile + MHQ_Unintentional_Impacts_Category + ",  "
> Visit_age + AlcWeek_Category"), num = "n = 236, v = 671",
>     table = structure(list(term = c("AHQ_Heading_Male_Quartile435.01-861",
>     "AHQ_Heading_Male_Quartile861.01-1964", "AHQ_Heading_Male_Quartile1964.01+",
>     "MHQ_Unintentional_Impacts_Category1", "MHQ_Unintentional_Impacts_Category2+",
>     "AHQ_Heading_Male_Quartile", "MHQ_Unintentional_Impacts_Category"
>     ), estimate = c(0.0770481215334453, -0.0384079604240709,
>     -0.0330828295158344, -0.0832731659006525, -0.128526526482571,
>     NA, NA), std.error = c(0.059581121870144, 0.0583721373279554,
>     0.055587780366665, 0.041329484563662, 0.0510238930591962,
>     NA, NA), statistic = c(1.67227137942203, 0.432943575872345,
>     0.354198426884743, 4.05966478138409, 6.34509834630379, 4.34998309557224,
>     8.19191965566993), p.value = c(0.195954577939597, 0.510548103977062,
>     0.551746070310006, 0.0439192171347208, 0.0117706083633605,
>     0.226068166523714, 0.0166397673037754), DF = c(NA, NA, NA,
>     NA, NA, 3, 2)), row.names = c(NA, -7L), class = c("tbl_df",
>     "tbl", "data.frame"))), list(form = c("GMCT_mps ~ MHQ_Heading_Male_Quartile + AHQ_Heading_Male_Quartile + ",  "
> MHQ_Unintentional_Impacts_Category + Visit_age + AlcWeek_Category" ),
> num = "n = 236, v = 671", table = structure(list(term =
> c("MHQ_Heading_Male_Quartile6.01-15",
> "MHQ_Heading_Male_Quartile15.01-53",
> "MHQ_Heading_Male_Quartile53.01+",
> "AHQ_Heading_Male_Quartile435.01-861",
> "AHQ_Heading_Male_Quartile861.01-1964",
> "AHQ_Heading_Male_Quartile1964.01+",
> "MHQ_Unintentional_Impacts_Category1",
> "MHQ_Unintentional_Impacts_Category2+", "MHQ_Heading_Male_Quartile",
> "AHQ_Heading_Male_Quartile", "MHQ_Unintentional_Impacts_Category" ),
> estimate = c(0.0354548892345223, -0.0457638357151567,
> -0.128823991044636,
> 0.0846854973713492, 0.00976675574330686, 0.0171278350996467,
> -0.0649444583952458, -0.093681710240534, NA, NA, NA), std.error = c(0.0393200184837168,
> 0.046488462709375, 0.0537316384272413, 0.059698051462804, 0.0591007191370332,
> 0.0562996458832999, 0.0407618682647451, 0.0538668059654375, NA,  NA, NA), statistic = c(0.813064200251411, 0.969068474904697,
> 5.74821934903142, 2.01232337993008, 0.0273095863691144, 0.0925536647531394,
> 2.53849338793126, 3.02459459350198, 9.32561500035051, 2.34512015899218,
> 4.20409892096781), p.value = c(0.367215866960121, 0.324912608474423,
> 0.0165053786147409, 0.156026213082828, 0.868742392257686, 0.760955460383828,
> 0.111100752930363, 0.0820108149775128, 0.0252607520289589, 0.503932230891677,
> 0.122205715642826), DF = c(NA, NA, NA, NA, NA, NA, NA, NA, 3,  3, 2)), row.names = c(NA, -11L), class = c("tbl_df", "tbl", "data.frame" )))))

Comment: Can you please provide a sample of your data or data like it, preferably with `dput()`? That will make it easier for people to help you and to test if their answer actually works for your question.
Comment: I added the dput- it is a bit long unfortunately because I am not sure how to subset nested lists by rows...
Answer: I'm guessing what you are looking for is map and friends from purrr.
map(1:9, function(i) {
  map(1:7, function(j) {
    result <- tab_male[[i]][[j]]
    cat(result$form, result$num, sep = "\n")
    result_f <- xtable(result$table, digits = c(0, 0, 3, 2, 2, 3, 0))
    print(result_f, type = "html", include.rownames = FALSE)
  })
})

or, to be more tidyverse-y,
map(tab_male, function(list_i) { # list_i is an element of tab_male
  map(list_i, function(list_j) { # list_j is an element of list_i
    result <- list_j
    cat(result$form, result$num, sep = "\n")
    result_f <- xtable(result$table, digits = c(0, 0, 3, 2, 2, 3, 0))
    print(result_f, type = "html", include.rownames = FALSE)
  })
})

Comment: @hlinee The closest thing is `modify_depth(x, 2, fun)`, which is equivalent to `x[] <- map(x, ~ map(., fun))`
Comment: Is there no function that combines the two maps into one? I was also thinking maybe it's possible to use nest() and create a "list-column" data-frame 7x9, where each element is a list of 3?
Comment: I would think there'd be a way using `tidyr::crossing(i = 1:9, j = 1:7)` and then
  `purrr::walk2(...)`, but I haven't figured out the syntax right.
Comment: @Phil nice, i agree that's closer. wasn't aware of `modify_depth` before.

Tidyverse version of nested for loops


GitHub arquivos grandes ficam corrompidos

Question: Quando tento enviar um arquivo maior que 100 MB, tudo ocorre bem no Git. Inclusive na minha pasta do GitHub o arquivo está normal e com o tamanho correto. Mas quando eu tento baixá-lo em zip para testar, o arquivo grande fica com 1 KB.
Quando importo para o gitDesktop os arquivos estão com 1 KB também (os maiores que 100 MB).
Já tentei com arquivo Rar mas quando baixo só diz que o arquivo está corrompido. Alguma solução?
Comment: Ao meu ver o Git deveria ser para controlar a versão do software e como ele funciona e novas funcionalidades e organizar o trabalho entre equipes pequenas, médias e grandes ... Já os dados nem deveriam (com algumas exceções) ser "versionados", nem faz sentido isto, os dados devem fazer parte do ambiente usado e se precisa de um arquivo maior que 100MB é porque tem algo errado, a não ser que seja um outro software que recebe um "bind" da sua aplicação atual, mas ainda sim provavelmente tem alguma coisa má planejada no projeto em si.
Comment: Pode mandar o link do repositório por favor?
Comment: As vezes aqui tem algo que te interesse https://pt.stackoverflow.com/questions/432787/como-posso-subir-arquivos-no-git-com-mais-de-50mb-de-tamanho-por-commit
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo
Comment: Você não pontua suas perguntas, não tem interação com a galera, confira o [tour do site](https://pt.stackoverflow.com/tour)
Answer: O Git não foi criado para ser usado para manipular grandes arquivos. Isso está sempre nas desvantagens dele quando se compara om outros softwares de controle de versão. Não quer dizer que não funcione, mas não é ideal.
Para o Git tem um mecanismo apropriado para lidar com essa necessidade que é o Git Large File Storage (LFS) (agora foi comentado que está o usando, isso deveria estar na pergunta). Não resolverá para o Github, que é o que diz ter problema na pergunta.
Existe até uma alternativa que a Microsoft criou para poder trabalhar com o repositório do Windows, mas ela não está disponível para você usar no Github, pelo menos em contas normais e gratuitas.
E de fato o Github tem restrições para arquivos grandes conforme mostra o help deles. Esse tamanho em específico é proibido, então neste caso a solução é não tentar fazer isso.
Podem existir outras opções, mas teria que saber o exato contexto, tudo o que pode ou não fazer.
Comment: Então, eu estava usando o git lfs.
Enviei todos arquivos (70mb) e deixei o de 100 mb para enviar com o git lfs.
Apesar de ele enviar ok o arquivo fica com 1 kb quando baixa.
E mesmo compactando em rar e enviando tudo continua a mesma coisa :/
Comment: Na sua pergunta disse que está usando o Github
Answer: O GitHub tem uma limitação que não permite que arquivos com mais de 100 MB sejam versionados em seus repositórios.
A única maneira que o GitHub oficialmente indica para versionar arquivos com mais de 100 MB é usando o Git Large File Storage (Git LFS).
Basicamente, o Git LFS permite que os commits apenas apontem para estes arquivos grandes, que ficarão armazenados fora do seu repositório GitHub, mantendo dentro do commit apenas um apontamento para o arquivo que ficará em outro local.
A instalação e uso é muito transparente. Todo repositório no GitHub já tem uma conta gratuita para uso do Git LFS, que permite até 2 GB de armazenamento no plano gratuito.
Assim, após instalar o git lfs e fazer o track dos tipos de arquivo que deseja versionar no Git LFS:
git lfs track "*.war"

Todo push para o repositório do GitHub já enviará, automaticamente, o arquivo para o repositório do Git LFS:
git add app.war
git commit -m "Add war file"
git push origin master

O retorno do push mostrará algo parecido com isto:
Sending app.war
44.74 MB / 81.04 MB  55.21 % 14s

É possível alterar o repositório usado pelo Git LFS caso não queira usar o repositório gratuito do GitHub.