How to prove the 2nd & 3rd conditions of outer measure?

Question: I have this question on outer measure from Richard Bass' book:

Prove that $\mu^*$ is an outer measure, given a measure space $(X, \mathcal A, \mu)$ and define
$$\mu^*(A) = \inf \{\mu(B) \mid A \subset B, B \in \mathcal A\}$$
for all subsets $A$ of $X$.

Here are what I have gone so far:
(1) The first condition is the easiest one:
$$\begin{align}
\mu^*(\emptyset) &= \inf \{\mu(B) \mid \emptyset \subset B, B \in \mathcal A\}\\
&= \mu (\emptyset) \\
&= 0
\end{align}$$
(2) Now the second condition. Let $D, E \in X$ and $D \subset E$,
$$\begin{align}
\mu^*(D) &= \inf \{\mu(D') \mid D \subset D', D' \in \mathcal A\}\\
\mu^*(E) &= \inf \{\mu(E') \mid E \subset E', E' \in \mathcal A\}\\
\end{align}$$
Here I need to prove $\mu^* (D) \leq \mu^*(E)$. It looks to me so intuitive especially if I draw Venn diagrams of $D, E, D'$ and $E'$, but I don't know how to say it in math-speak. I would appreciate helps on this 2nd. condition.
(3) And this 3rd. condition is my major stumbling block: Given $(A_i)_{i \in \mathbb N} \subset X$, I need to arrive at
$$\mu^* (\bigcup _{i=1}^{\infty} A_i)\leq \sum_{i=1}^{\infty} \mu^* (A_i).$$
Here, I know for sure I need to  state this first: $\forall A_i, \exists B_i $ such that $ A_i \subset B_i, B_i \in \mathcal A$, but I don't think the next step is right:
$$\begin{align}
\mu^*(\bigcup_{i=1}^{\infty}A_i) &= \inf \{\bigcup_{i=1}^{\infty}\mu(B_i) \mid A_i \subset B_i, B_i \in \mathcal A\}\\
&= \ldots\\
\end{align}$$
I would appreciate any help on this 3rd. condition in addition to the 2nd. above. Thank you for your time and effort.

POST SCRIPT: After I posted this question, I found this proposition on the same text, perhaps this proposition holds key to the solution, in that I don't have to prove the 2nd and 3rd conditions? Thanks again.

Proposition: Suppose $\mathcal C$ is a collection of subsets of $X$ such that $\emptyset$ and $X$ are both in $\mathcal C$. Suppose $\mathscr l : \mathcal C \to [0, \infty]$ with $\mathscr l (\emptyset) = 0$. Define
$$\mu^* (E) = \inf \{ \sum_{i=1}^{\infty} \mathscr l (A_i) \mid A_i \in \mathcal C \text{ for each } i, \text{and }  E \subset \cup_{i=1}^{\infty} A_i \}.$$
  Then $\mu^*$ is an outer measure.
Answer: I do not see how the quoted proposition helps, although I may be missing something. Nonetheless, the exercise is easy to solve without it.
(2) Since $D\subset E$, $X_E:=\{E'\in\mathcal A\ :\ E\subset E'\}\subset X_D:=\{D'\in\mathcal A\ :\ D\subset D'\}$, so the infimum over the elements of $X_E$ is larger than the infimum over $X_D$. In other words,
$$
\mu^*(E)=\inf_{B\in X_E}\{\mu(B)\}\ge\inf_{B\in X_D}\{\mu(B)\}=\mu^*(D).
$$
(3) Let $(A_i)_{i\in\mathbb N}\subset X$. By definition of $\mu^*$, for each $\varepsilon>0$ and $n\in\mathbb N$, there exists $B_n\in\mathcal A$, $B_n\supset A_n$, such that
$$
\mu(B_n)<\mu^*(A_n)+\frac\varepsilon{2^n}.
$$
Then $\bigcup_nB_n\in\mathcal A$ and $\bigcup_nB_n\supset\bigcup_nA_n$, so again by definition of $\mu^*$,
$$
\mu^*\left(\bigcup_nA_n\right)
\le\mu\left(\bigcup_nB_n\right)
\le\sum_{n\in\mathbb N}\mu\left(B_n\right)
<\sum_{n\in\mathbb N}\mu^*\left(A_n\right)+\varepsilon,
$$
and you conclude since $\varepsilon$ is arbitrary.
Comment: Thanks for your response, it enhanced my knowledge, you have earned my up-vote and green check mark. I came up with my own solution at the same time I received yours, which I posted below. Do you think my logic make sense? I am curious to know, and to learn. I value yours for its elegance and brevity, but mine only for its originality (but clumsy and folksy.) Thanks again.
Answer: At the same time I received response from @Ian, I came up with my own solution, I am posting it here to let others see if its logic makes sense. If it does, then I would value @Ian's for its elegance and brevity, and mine for its originality (but folksy and clumsy.) Thanks again to @Ian for responding.

Here is my solution after some changes per @Ian's correction (see comment below):
(1) The firs condition:
$$\begin{align}
\mu^*(\emptyset) &= \inf \{\mu(B) \mid \emptyset \subset B, B \in \mathcal A\}\\
&= \mu (\emptyset) \\
&= 0
\end{align}$$
(2) The second condition: Let $D, E \subset X$ and $D \subset E$, then
$$\begin{align}
\mu^* (D) &= \inf \{ \mu (D') \mid D \subset D', D' \in \mathcal A\},
\\
\mu^* (E) &= \inf \{ \mu (E') \mid E \subset E', E' \in \mathcal A\}.
\end{align}$$
From $D \subset E$ we need to show that
$$\inf\{\mu (D') \mid D' \in \mathcal A, D \subset D'\} \leq \inf \{\mu(E') \mid E'\in \mathcal A, E \subset E'\}.$$
Suppose that by way of contraidiction, $D \subset E$ leads to $\inf \{\mu (D')\} > \inf \{\mu (E')\}$ instead. But this contradicts the definition of $D′$ being the infimum of all sets belong to $\mathcal A$ and containing $D$. Therefore $D \subset E$ has to lead to $\inf\{\mu (D′)\}\leq \inf \{\mu (E′)\}$.
Hence $\mu^* (D) \leq \mu^* (E)$.
(3) The third condition: Let $(A_i)_{i \in \mathbb N} \subset X$, and  $(B_i)_{i \in \mathbb N} \in \mathcal A.$
$$\begin{align}
\text{Given } \mu^* (A_i) &= \inf \{\mu(B_i) \mid A_i \subset B_i, B_i \in \mathcal A\}, \\
\text{therefore, } \sum_{i=1}^{\infty}\mu^* (A_i) &= \sum_{i=1}^{\infty}\inf \{\mu(B_i) \mid A_i \subset B_i, B_i \in \mathcal A\}.\\
\text{On the other hand, } \ \mu^* (\bigcup_{i=1}^{\infty}A_i) &= \inf \{\mu(\bigcup_{i=1}^{\infty} B_i) \mid \bigcup_{i=1}^{\infty} A_i \subset \bigcup_{i=1}^{\infty} B_i, B_i \in \mathcal A\}.\\
\end{align}$$
CASE-1: If $B_i$'s are pairwise disjoint, that is $B_i \cap B_j = \emptyset$ for all $i, j \in \mathbb N$, then
$$\sum_{i=1}^{\infty} \mu^* (A_i) = \mu^* (\bigcup_{i=1}^{\infty} A_i).$$
CASE-2: If $B_i \cap B_j \neq \emptyset$ for certain $i, j \in \mathbb N$, then
$$\sum_{i=1}^{\infty} \mu^* (A_i) < \mu^* (\bigcup_{i=1}^{\infty} A_i).$$
Therefore for all cases
$$\sum_{i=1}^{\infty} \mu^* (A_i) \leq \mu^* (\bigcup_{i=1}^{\infty} A_i),$$
hence $\mu^*$ is an outer measure. $\qquad \blacksquare$
Comment: Hi A.Magnus. Thanks for posting your answer, it will surely be useful for future users. There are some imprecisions. First in (2), you are implicitly assuming that the infimum is attained, i.e. that there exists $E'$ s.t. $\mu^*(E)=\mu(E')$, but I'm sure you know that an infimum is not necessarily attained! In (3), your definition of $\mu^* (\bigcup_{i=1}^{\infty}A_i)$ does not make sense since the union of measures is not defined. You should write $\mu^* (\bigcup_{i=1}^{\infty}A_i):=\inf\{\mu(B)\ :\ \bigcup_iA_i\subset B,\ B\in\mathcal A\}$, and then the rest does not make sense...
Comment: Thanks! I will stick to yours, I suffer from bruised ego but that is the price of learning :-) Thanks again.


treatment and sum contrasts, inconsistent results

Question: I am fitting a linear mixed effect models with two factors (mPair with 6 levels, and spd_des with 3 levels) and their interaction. I obtain inconsistent results depending on the contrasts that I choose, and I would like to understand why and how to deal with it.
If I use treatment contrasts, I obtain the following (I only copy the relevant info of the results)
> options(contrasts = c("contr.treatment","contr.poly"))
> linM1 <- lme(cc_marg ~ mPair*spd_des , random = ~mPair|ratID, data=dat_trf, na.action=na.omit, method = "ML", control=lCtr )
> summary(linM1)

Fixed effects: cc_marg ~ mPair * spd_des
                         Value  Std.Error DF   t-value p-value
(Intercept)          1.4628761 0.09618167 94 15.209511  0.0000
mPairRFVI           -0.8180718 0.10454920 94 -7.824754  0.0000
mPairVLRF           -0.7990828 0.13193991 94 -6.056415  0.0000
mPairVLVI           -0.6077804 0.13734253 94 -4.425289  0.0000
mPairVMRF           -0.7444267 0.13294167 94 -5.599649  0.0000
mPairVMVI           -0.4799995 0.12194383 94 -3.936234  0.0002
spd_des15           -0.0830016 0.07990370 94 -1.038771  0.3016
spd_des20           -0.0856339 0.08321984 94 -1.029008  0.3061
mPairRFVI:spd_des15 -0.1576193 0.13500809 94 -1.167481  0.2460
mPairVLRF:spd_des15  0.0866510 0.11385875 94  0.761039  0.4485
mPairVLVI:spd_des15  0.0083311 0.13500809 94  0.061708  0.9509
mPairVMRF:spd_des15  0.0184844 0.11385875 94  0.162345  0.8714
mPairVMVI:spd_des15 -0.0672286 0.13500809 94 -0.497960  0.6197
mPairRFVI:spd_des20 -0.1705514 0.14201095 94 -1.200973  0.2328
mPairVLRF:spd_des20  0.0899629 0.11949193 94  0.752879  0.4534
mPairVLVI:spd_des20 -0.0626845 0.14359174 94 -0.436547  0.6634
mPairVMRF:spd_des20 -0.0106400 0.11969131 94 -0.088895  0.9294
mPairVMVI:spd_des20 -0.0608750 0.14286017 94 -0.426116  0.6710

I interpret this as follows: Since the interaction terms are all non-significant, then the factor spd_des (also non-significant) does not influence the data at any level of the factor mPair.
On the other hand, using sum contrasts I obtain the following results.
> options(contrasts = c("contr.sum","contr.poly"))
> linM2 <- lme(cc_marg ~ mPair*spd_des , random = ~mPair|ratID, data=dat_trf, na.action=na.omit, method = "ML", control=lCtr )
> summary(linM2)

Fixed effects: cc_marg ~ mPair * spd_des
                     Value  Std.Error DF   t-value p-value
(Intercept)      0.8137433 0.04791890 94 16.981678  0.0000
mPair1           0.5929117 0.06609665 94  8.970373  0.0000
mPair2          -0.3341386 0.04969616 94 -6.723629  0.0000
mPair3          -0.1472874 0.07260892 94 -2.028503  0.0453
mPair4          -0.0328631 0.08993236 94 -0.365421  0.7156
mPair5          -0.1488959 0.06991733 94 -2.129600  0.0358
spd_des1         0.0743293 0.02315254 94  3.210416  0.0018
spd_des2        -0.0272358 0.02325774 94 -1.171043  0.2445
mPair1:spd_des1 -0.0181081 0.04414399 94 -0.410206  0.6826
mPair2:spd_des1  0.0912334 0.05726538 94  1.593168  0.1145
mPair3:spd_des1 -0.0769866 0.04518813 94 -1.703691  0.0917
mPair4:spd_des1  0.0000066 0.05743544 94  0.000114  0.9999
mPair5:spd_des1 -0.0207337 0.04518548 94 -0.458859  0.6474
mPair1:spd_des2  0.0004559 0.04558473 94  0.010002  0.9920
mPair2:spd_des2 -0.0478225 0.05730295 94 -0.834555  0.4061
mPair3:spd_des2  0.0282279 0.04525282 94  0.623781  0.5343
mPair4:spd_des2  0.0269011 0.05747689 94  0.468034  0.6408
mPair5:spd_des2  0.0163141 0.04525367 94  0.360503  0.7193

> anova.lme(linM2,type="marginal")
              numDF denDF   F-value p-value
(Intercept)       1    94 288.37740  <.0001
mPair             5    94  35.30799  <.0001
spd_des           2    94   5.17279  0.0074
mPair:spd_des    10    94   0.52159  0.8710

The results are now telling me that the first level of the factor spd_des is significant; i.e. the mean of the data at that level of spd_des is significantly different from the grand mean (Intercept), and since the interactions are all non-significant, this is true at all levels of mPair.
So, with treatment contrasts spd_des does not influence the data at any level of mPair, and with sum contrast spd_des influence the data at all level of mPair. How do I deal with this? What result should I trust? Thanks in advance for your help.
You can find this question also at this link. Any help is highly appreciated.
Comment: I have added the link as suggested
Comment: please don't cross-post (this was also posted to `email@example.com`, or, if you must, at least give links connecting the two posts ...
Comment: I am sorry! In the past, I was told to re-post to the other channel after I asked a question. That's why I posted to both this time. I can cancel if that bothers, and certainly not post to both in the future.
Comment: OK this time.  Maybe edit your question above with [this link to the r-sig-mixed post](https://stat.ethz.ch/pipermail/r-sig-mixed-models/2019q1/027613.html) ?
Comment: Although I understand that you can't show all of your data, could you at least say whether each of the 18 combinations of factor levels has the same number of observations? A quick look suggests that they don't, but I could be wrong. Also, how many `ratID` values are there? I haven't used the `type="marginal"` anova setting in R; is that supposed to be like the "Type III" tests in SAS?
Comment: The 18 combinations of factor levels do not have the same number of observations. That's why I am using "marginal", which is indeed type III sum of squares. There are 10 values of ratID. Thanks!
Comment: Note this is repeated measure analysis: each ratID has one data-point in each of the 18 groups, with some missing data (that's why I do not have the same number of observation for each group).
Comment: Your post is incomplete - can you post the output of the command anova.lme(linM1, type="marginal") below the summary of your linM1 model?
Comment: I did not run anova on linM1 on purpose actually, because the treatment contrasts are not orthogonal. Shouldn't they be to get a meaningful result from anova?
Answer: There is an interesting technical difference between the contrast codings for which I have some ideas without a definitive answer. But there are also some statistical issues that might make that difference less relevant to your application.
Technically, the standard errors of the fixed-effect coefficient estimates found with the sum contrasts are of substantially smaller magnitude than are those based on the treatment contrasts. This suggests that the random effects modeled with sum contrasts did a better job of controlling for inter-rat differences than did those developed with treatment contrasts.
Without seeing the data it is hard to say exactly why this might be.
First, there seems to be a large set of missing data, with 180 data points intended (18 combinations with 1 test each on 10 rats) but with many fewer data points collected. Perhaps the pattern of missing values allowed better estimation with the sum contrasts.
Second, you have allowed for random effects related to mPair but not related to spd_des; you clearly wouldn't be able to evaluate random effects for both factors with so few data points. It's not clear to me how that would play out in terms of the interaction terms or the missing-data patterns.
Third, you are getting close to trying to estimate as many values from the data as you have observations. There are 18 fixed effects including the intercepts and the interaction terms. For random effects with 6 levels of mPair and an intercept (as I understand this coding) and 10 rats, you are also trying to determine 70 random effects here for a total of 88 values you are trying to estimate with a little over 100 data points.
I think that you would have to look at the design matrices of both the treatment-contrast and sum-contrast formulations produced from your specific data set, and how this plays out in the modeling of the random effects, to identify the reasons for this difference.
In practice, however, statistical considerations might make it less important to grapple with this problem. You have no indication of significant interaction terms. Once you demonstrate that point you could proceed simply to analyze the model without interactions and probably have more power to define precisley the remaining fixed-effect coefficients. I suspect that the differences between the results with treatment and sum contrasts would diminish if the interaction terms were removed.
Sum contrasts are a good standard and they allow the Type-III ANOVA tests that you wish to perform despite their violation of the principle of marginality. So it might be safest to continue with the sum contrasts.
How much sense Type-III tests actually make, however, can be questioned. Type-II tests might be more defensible here and would be applicable to both the treatment- and the sum-contrast formulations. As John Fox has said about crossed two-way ANOVA like this (with factors named A and B):

The most powerful test for the A main effect is the type-II test: for A
  after B ignoring the AB interaction; (and continuing) for B after A ignoring
  AB; and for AB after A and B. These tests are independent of the contrasts
  chosen to represent A and B, which is generally the case when one restricts
  consideration to models that conform to the principle of marginality.

W.N. Venables has made similar points about Type-III tests.
One last thought: it looks like spd_des might have a natural ordering (with some reference value and further values of 15 and 20). If so, you should be treating it as an ordered factor that can capture similarly ordered responses. It would then be handled with polynomial contrasts under your selection of options.
Comment: @Cristiano in exploratory studies use statistical tests to protect _yourself_ from following up on false positives. Random effects can be tricky. See [this page](https://stats.stackexchange.com/q/4700/28500) for useful ideas. The scale of your study might limit how many predictors you can consider. Forward selection of predictors based on individual relations to outcome is [poor practice](https://stats.stackexchange.com/q/20836/28500). Starting with a full model based on subject-matter knowledge and then removing less useful predictors can, however, be OK. See the Harrell notes linked above.
Comment: Thanks! I am starting to think, as you suggested, that my problem may be related to the fact that the number of coefficients to be estimated is close enough to the number of observations. Would it make sense to use a random intercept only model (as opposed to random intercept and slope, as currently is) to reduce the number of parameters? I have the feeling that removing non-significant interactions  is controversial in the statistics community; see [here](https://stats.stackexchange.com/questions/350109/dropping-non-significant-interaction-terms). What do you think?
Comment: @Cristiano the inclusion of random slopes in addition to intercepts ideally should be based on your knowledge of the subject matter. If you don't have enough data fairly to assess the random slopes, then you can't. An advantage of Type-II ANOVA is that you test the main effects of both factors first in a principled way (regardless of contrast coding) and then see if their interaction still matters. If the interaction is insignificant, then you already have an estimate of the main-effect significance. If interactions are significant, then the main effects aren't easily interpretable anyway.
Comment: @Cristiano with respect to removing non-significant interactions, see for example Frank Harrell's [course notes](http://hbiostat.org/doc/rms.pdf), Section 4.12.1 on developing models: "Check additivity assumptions by testing pre-specified interaction terms. Use a global test and either keep all or delete all interactions." So if the global test for interactions is insignificant then it can be OK to remove them all to simplify the model. Note that your model may be already overfit with 18 predictors (with interactions) and only a bit >100 observations; see Section 4.4 of those course notes.
Comment: I have never really grasped the logic of how to choose the random effects. It sounds obvious to me that there is subject specificity, and therefore fitting a random slope model renders better predictions. And so, it does not sound fair to me to use fitting measures to do model selection. How do I then choose the random effects in exploratory studies like mine (i.e. I do not have previous knowledge on whether the slope should change consistently across subjects)?


Concatenate several rows into one row by column value, and split resulting dataframe into several dataframes based on number of concatinated rows

Question: I have a pandas dataframe where several rows share the particular column value. For those rows, I want to concatenate these rows into a single row. And single there are variations for the number of rows with the shared column value, I want to split these dataframes into their own separate dataframe, so a unique dataframe for a particular number of shared rows.
Here is an example of what I want.
import pandas as pd

data = [['tom', 2], ['ni2ck', 2], ['j3uli', 4] , ['nic4k', 4], ['jul5i', 4] , ['nic6k', 7], ['ju7li', 7] , ['nic8k', 7], ['ju9li', 7] , ['nic1k', 8], ['car', 8]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])
df

The code above generates what the original dataframe would look like
The result would be
Name    Age
0   tom 2
1   ni2ck   2
2   j3uli   4
3   nic4k   4
4   jul5i   4
5   nic6k   7
6   ju7li   7
7   nic8k   7
8   ju9li   7
9   nic1k   8
10  car 8

I want to put all rows the share the same Age column into one row, and then separate the dataframe based on the number of columns that are generated for each shared row. So the result would look like this
first result dataframe, which has two rows, since there are two lines that share the same number of columns.
Name    Name    Age
0   tom ni2ck   2
1   nic1k   car 8

second result dataframe
Name    Name    Name    Age
0   j3uli   nic4k   jul5i   4

third result dataframe
    Name    Name    Name    Name    Age
0   nic6k   ju7li   nic8k   ju9li   7

Answer: Here is one way
df['New']=df.groupby('Age').cumcount()
s=df.pivot(index='Age',columns='New',values='Name')
l=[ y.dropna(1) for _ , y in s.groupby(s.isnull().sum(1))]
l[0]
New      0      1      2      3
Age
7    nic6k  ju7li  nic8k  ju9li
l[1]
New      0      1      2
Age
4    j3uli  nic4k  jul5i
l[2]
New      0      1
Age
2      tom  ni2ck
8    nic1k    car

Answer: Using collections.defaultdict
from collections import defaultdict

d = defaultdict(list)

for age, df_ in df.groupby('Age'):
    d[len(df_.T.columns)].append(df_.reset_index(drop=True).T.loc[['Name']].assign(Age=age))

d = {k: pd.concat(v, ignore_index=True ) for k,v in d.items()}

Then, access the dataframes by the number of names they have. For example,
>>> d[2]

       0      1  Age
0    tom  ni2ck    2
1  nic1k    car    8

>>> d[3]

       0      1      2  Age
0  j3uli  nic4k  jul5i    4


Product of Bernoulli variates

Question: I am stuck with something that looks very simple but I am not able to find where I am wrong. Let $\xi_k$ with $k=1,...,n$ be $n$ iid Bernoulli random variables such that
$$
\mathbb{P}\left[\xi_k=1\right]=p,~~\mathbb{P}\left[\xi_k=0\right]=1-p.
$$
The product
$$
\psi = \xi_1\,\xi_2\,\cdot\cdot\cdot\xi_n
$$
is stil a Bernoulli variable with either $\psi=1$ or $\psi=0$. Clearly $\mathbb{P}\left[\psi=1\right]=p^n$, therefore $\mathbb{P}\left[\psi=0\right]=1-p^n$. Where I am wrong if I say
$$
\mathbb{P}\left[\psi=0\right]=\mathbb{P}\left[\{\xi_1=0\}\cup\{\xi_2=0\}\cup ...\cup\{\xi_n=0\}\right]=n\,\left(1-p\right) ?
$$
Comment: Union bound is not optimal in general, and our case is not an exception. More elementarily, probability splits primarily when events are disjoint (exclusive), and this is simply false for your events. Instead you may apply the inclusion-exclusion principle to reach the same conclusion.
Answer: We have that
$$
\Pr\{A\cup B\}=\Pr\{A\}+\Pr\{B\}-\Pr\{A\cap B\}=\Pr\{A\}+\Pr\{B\}-\Pr\{A\}\Pr\{B\}
$$
if $A$ and $B$ are independent events.
For example, if $n=2$,
\begin{align*}
\Pr\{\psi=0\}&=\Pr(\{\xi_1=0\}\cup\{\xi_2=0\})\\
&=\Pr\{\xi_1=0\}+\Pr\{\xi_2=0\}-\Pr\{\xi_1=0\}\Pr\{\xi_2=0\}\\
&=1-p^{2}.
\end{align*}
In general, we need to use the inclusion–exclusion principle.
Comment: thanks, now I realize is a typical mistake of mine: wrongly I assume that independence means $A\cap B=\emptyset$.

Product of Bernoulli variates


Do I need a Bonferroni correction?

Question: My study has me running several regression analyses to investigate my hypothesis, and I am struggling with the multiple comparisons problem. I have three separate metabolites as predictor variables, and four other covariates in each model. (Running each metabolite in separate models is typical for these metabolites.) I am running both logistic regression analyses and linear regression for each metabolite. The outcome variable is the same for the respective sets of regression analyses (it was dichotomized for logistic regression and left continuous for the linear regression).
I've been through every note I've ever taken, all my books, and a lot of the internet, and I'm still not sure about the Bonferroni correction. I know it's probably a simple problem, but I'll be grateful for any and all help with it. Thanks!
Comment: In my understanding if the underlying dataset is the same, you should apply Bonferroni correction.
Comment: It's all the same dataset, yes. Thank you for being so clear and to the point. Almost everything I've read so far has been clear as mud.
Answer: You may be disappointed or relieved to hear that the answer is it depends. If your study is a preliminary exploratory study intended to determine which of the metabolites are worthy of following up, then there is no need to perform any correction for multiple comparisons. To do so robs you of power to find a real effect. On the other hand, if your experiment is designed to give a decisive result that you will be declaring without confirmatory studies, then a correction for multiple comparisons will reduce the risk of you being embarrassed by a false positive finding.
Comment: @Sparks understood. However, alternatively you could refer to this really nice paper by Andrew Gelman about why multiple comparison tests are usually unnecessary. http://arxiv.org/pdf/0907.2478.pdf
Comment: @colin Absolutely true! Confirmatory experiments are by far a better way to gain confidence about the results than correcting for multiple comparisons. (At the cost of more effort and expense.)
Comment: I'm relieved to see someone say that, because that was exactly what I was getting from all my notes and reading. I'm glad it wasn't just my lack of understanding. I will do the correction. Thanks so much!
Comment: @michael lew "...will reduce the risk of you being embarrassed by a false positive finding". Yes. At the cost of an increased probability of being embarrassed by a false negative finding!
Comment: @MichaelLew I'm inclined to agree with you both; however, a reviewer has specifically asked for the multiple comparisons correction so... Rock-Sparks-Hard Place
Comment: @Sparks I've written more on the distinction between analyses intended to see what the data say and analyses that need to be corrected for multiple comparisons in my commentary on the recent ASA statement on P-values. You can get it as the 13th file here: http://amstat.tandfonline.com/doi/suppl/10.1080/00031305.2016.1154108

Do I need a Bonferroni correction?


Breath Marks (different symbols)

Question: Breath marks (related to caesurae) often appear in scores for woodwind instruments where it is acceptable to take a breath of air.  They are placed in a passage where the phrasing will not be disrupted.
A breath mark will necessarily mean that the note preceding it will have to be played slightly shorter than denoted (much is the same way a grace note will steal some time from the note preceding it).
Breath marks are usually engraved with a comma like symbol placed above the staff.
Alternatively a tick mark like symbol (or even an up bow symbol) is sometimes used instead.
When a breath mark is optional (for a player with a greater lung capacity), the breath mark can be placed in parentheses.

This excerpt from a piece of music (for descant and treble recorders) has be written with both the tick type and the comma type symbols (for breath marks?):

Are these different symbols supposed to represent different types of breaths (perhaps one is longer than the other)?
Is the the comma representing something else? (perhaps a breath mark with a fermata/pause?)
Is something else going on?
Answer: The comma is plainly called "breath mark" and is the most commonly used version in symphonic and vocal music.
The "tick" mark is called luftpause and is of German origin according to Oxford Music Dictionary and Dolmetsch. However, these are the only two references I could find specifically describing "a V mark above the staff." Other websites including Wikipedia use luftpause to describe the comma.
My opinion after reading these sources and the OP's example is that the "v" mark indicates where the musical phrase naturally breaks, and where bowed strings would lift [their bow] as an articulation, but no physical inhale. Whereas the comma is a proper breath mark indicating a full separation of both phrase and wind performance. Neither should affect tempo or the placement of the following downbeat, but the comma should result in a shortened duration and physical inhale.
This usage is supported by the "v" appearing within brackets indicating it is assumed, much like a complimentary accidental.
Comment: @RosieF The OP called it a "tick" mark. When I wrote my answer, "tick" became "check" in my head. In **British** English, the definition of "tick" is "a mark (✓) used to indicate that an item in a list or text is correct or has been chosen, **checked**, or dealt with; a check mark."
Comment: What do you mean by "check mark"? Are you referring to the V-like sign?
Comment: @RosieF: it seems safe to assume that; it's pretty much the symbol usually known as a [check-mark](https://en.wikipedia.org/wiki/Check_mark) in American English
Comment: @PLL This site is used by people outside America, too. That's why I dislike the use of Americanisms except when together with synonyms.
Comment: Luftpause is literally just the combination of "air" and "rest" so "rest to breath" or in other words just a synonym for a breath mark.
Answer: These symbols do indeed have slightly different meanings according to Elaine Gould's Behind Bars - The definitive guide to music notation [p. 436]:

When the time taken to breath is subtracted from the previous note, mark in a tick ✓.  Placed in brackets, the tick indicates an optional breath (✓).  When the note should be sung for its full duration, with extra time for the breath, add a comma above the stave – this adds a short pause to the bar in which it occurs.

Another source Essential Dictionary of Music Notation by Tom Gerou and Linda Lusk, defines the comma symbol as having two possible meanings [p. 44]

The breath mark (') has two similar uses:

an actual breath indication for instruments (including voice) requiring the breath to sound.
a small pause or break (as if taking a breath) for instruments not requiring breath to sound.

A breath mark may or may not interrupt the tempo.  If it does interrupt the tempo, the break or pause is shorter than that of a caesura or fermata.

This first definition of Gerou and Lusk corresponds to the meaning of the Gould's tick (and the definition given in the question).
Gerou and Lusk's second definition of the comma matches with Gould's, indicating a short interruption of the meter.
Comment: Yeah, your claim in the question that "A breath mark will necessarily mean that the note preceding it will have to be played slightly shorter than denoted (much is the same way a grace note will steal some time from the note preceding it)." did not match my experience interpreting apostrophe-shaped breath marks in clarinet music, but it matches this answer of yours instead.
Answer: Imagine you were playing that duet on two violins.
You'd probably ignore the tick marks (because breathing isn't integral to your violin phrasing) but you'd heed the comma just before the final bar. The effect is that nice lift you get just before the end of many baroque performances.
So the tick is a technique mark specifically for woodwind/brass instruments and the comma is a stylistic mark observable by all players.
Comment: The excerpt in the question is arranged for two recorders.  Why would there be instructions/symbols in it for other instruments?
Answer:
Is the the comma representing something else? (perhaps a breath mark with a fermata/pause?)

The comma is a breath mark:

https://en.wikipedia.org/wiki/Breath_mark
In this case (your example) the breath is above a rallentando and so it is altering the tempo.
The tick-sign or v appears in notation for strings or choirs.
This pause usually does not affect the overall tempo. For bowed instruments, it indicates to lift the bow and play the next note with a downward bow.
https://musicterms.artopium.com/b/Breathmark.htm
V
Theres no difference:
Luftpause: v and comma
A momentary interruption of the metre by silence, often indicated by a comma or 'V' above the staff.
Groove
Comment: How is the comma type breath mark, different to the tick type breath mark?
Comment: As the V sign looks like nose this means you can breath through the nose. ;)

Breath Marks (different symbols)


Reinforced.Typings can't find dotnet.exe on MacOS

Question: I'm working on a dotnet 5 solution on MacOS and Reinforced.Typings is giving me the following compile error. It's trying to run dotnet.exe, which I suspect is the core of the problem since it doesn't exist on MacOS. Any clues on how to fix it?
/Users/myuser/.nuget/packages/reinforced.typings/1.6.1/build/Reinforced.Typings.targets(3,3): Error MSB6003: The specified task executable "" could not be run. System.ComponentModel.Win32Exception (0x80004005): ApplicationName='dotnet.exe', CommandLine=' "/Users/myuser/.nuget/packages/reinforced.typings/1.6.1/tools/net5.0/rtcli.dll" profile "/var/folders/q3/zth_hlj12ts4w6zc9m42_ctr0000gn/T/tmp316575ae.tmp"', CurrentDirectory='', Native error= Cannot find the specified file
  at System.Diagnostics.Process.StartWithCreateProcess (System.Diagnostics.ProcessStartInfo startInfo) [0x0029f] in /Users/builder/jenkins/workspace/build-package-osx-mono/2020-02/external/bockbuild/builds/mono-x64/mcs/class/System/System.Diagnostics/Process.cs:778
  at System.Diagnostics.Process.Start () [0x0003a] in /Users/builder/jenkins/workspace/build-package-osx-mono/2020-02/external/bockbuild/builds/mono-x64/mcs/class/referencesource/System/services/monitoring/system/diagnosticts/Process.cs:2006
  at (wrapper remoting-invoke-with-check) System.Diagnostics.Process.Start()
  at Microsoft.Build.Utilities.ToolTask.ExecuteTool (System.String pathToTool, System.String responseFileCommands, System.String commandLineCommands) [0x000c9] in /Users/builder/jenkins/workspace/build-package-osx-mono-pullrequest/pr/external/bockbuild/builds/msbuild-15/src/Utilities/ToolTask.cs:711
  at Microsoft.Build.Utilities.ToolTask.Execute () [0x00433] in /Users/builder/jenkins/workspace/build-package-osx-mono-pullrequest/pr/external/bockbuild/builds/msbuild-15/src/Utilities/ToolTask.cs:1519  (MSB6003) (MyProject.Core)

My configuration class looks like this:
namespace MyProject.Core
{
    public static class ReinforcedTypingsConfiguration
    {
        public static void Configure(ConfigurationBuilder builder)
        {
            builder.Global(x => x.ExportPureTypings()
                                 .CamelCaseForProperties()
                                 .AutoOptionalProperties(true));

            builder.ExportAsInterfaces(TypesToExport);
        }

        private static List<Type> TypesToExport = new()
        {
            typeof(ProductDto)
        };
    }
}

My Reinforced.Typings.settings.xml looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<Project>
  <PropertyGroup>
    <RtForceTargetFramework>net5.0</RtForceTargetFramework>
    <RtTargetFile>$(ProjectDir)/contracts.d.ts</RtTargetFile>
    <RtConfigurationMethod>MyProject.Core.ReinforcedTypingsConfiguration.Configure</RtConfigurationMethod>
    <RtDivideTypesAmongFiles>false</RtDivideTypesAmongFiles>
    <RtBypassTypeScriptCompilation>false</RtBypassTypeScriptCompilation>
    <RtDisable>false</RtDisable>
  </PropertyGroup>
</Project>

Comment: Maybe [This link](https://stackoverflow.com/questions/41693683/ive-installed-dot-net-core-on-mac-but-didnt-find-dotnet-command) can help to you.
Answer: Checking the source code of Reinforced.Typings and it internally calls RuntimeInformation.IsOSPlatform(OSPlatform.Windows) to determine whether "dotnet.exe" or "dotnet" will be used.
Try to create a simple console app and check what RuntimeInformation.IsOSPlatform(OSPlatform.Windows) returns.
Source code: RtCli.cs
Comment: That's returning `True` for `OSPlatform.OSX` and `False` for `OsPlatform.Windows`, as expected. The if you're referring to is wrapped in a `#if NETCORE` preprocessor directive which I guess is making the code default to dotnet.exe.
Interestingly, the exact same code compiles and works fine with Rider, but not with Visual Studio Community edition for mac, so I guess they're passing in different params somewhere.
Answer: Reinforced.Typings works as expected from the command line by running dotnet build *.sln. It also works from Rider, which wraps the same build command.
Building from Visual Studio for Mac is a different story. It seems to be running an awful lot of stuff on build, but not dotnet build. Not entirely sure what command Visual Studio for Mac is running, but it looks like some sort of Target/Task related flow that somehow sets OsPlatform to OsPlatform.Windows even though it is clearly incorrect.
Answer: I've asked the same question 10 months ago and still no answer. My guess is that NETCORE was not defined at the time of building the nuget package.
Reinforced.Typings is looking for dotnet.exe on MacOS so it can't run


Remove "submitted by"

Question: How can I remove "submitted by"? I already try to remove it on admin/structure/types/manage/page, but i still see "Submitted by...".
Comment: Are you using a custom theme, any Views, or anything like that? Core Drupal definitely respects this setting as well as any of the base themes.
Answer: You need to check your node and page level twig templates to make sure it is not outputting the submitted by information, despite what the setting is here. There could also be a Views block outputting this information in one of the regions, which would ignore the setting as well.
Comment: i remove from the templates file. But still dosent work.
Comment: I try to remove all dates from  the cache and i resolved

Remove "submitted by"


Google Apps Scripts - MSWord to String

Question: When I attempt to run the following code (Output will be XML):
function doGet(e){
  return getFilesHtml();
}

function getFilesHtml() {
  //Create second to top level XML parent
  var xml = XmlService.createElement('response');

  try{
    var files = DriveApp.getFilesByName('ANNOUNCEMENTS.doc');

    //Iterate through files and push to an array
    var filesarray = new Array();
    while(files.hasNext()) {
      filesarray.push(files.next());
    }

    var file = getNewestFile(filesarray);

    //Create necessary XML elements and information
    var file_content = XmlService.createElement('content').setText(file.getBlob().getDataAsString('UTF-8'));
    xml.addContent(file_content);
  }catch(error){
    var stat_child = XmlService.createElement('status').setText('failure');
    var message_child = XmlService.createElement('message').setText(error.message);
    xml.addContent(stat_child);
    xml.addContent(message_child);
  }

  //Prepare and respond with XML
  var document = XmlService.createDocument(xml);
  var xml2 = XmlService.getPrettyFormat().format(document);
  //Return the XML
  return ContentService.createTextOutput(xml2).setMimeType(ContentService.MimeType.XML);
}

function getNewestFile(array){
  array.sort(function(a,b){
    return new Date(b.getDateCreated()) - new Date(a.getDateCreated());
  });
  return array[0];
}

I get the following failure response:
<response>
  <status>failure</status>
  <message>
    We're sorry, a server error occurred. Please wait a bit and try again.
  </message>
</response>

My ultimate goal is to get the contents of this file. I've tried .getAs('application/pdf'), but that works not, like this. Is there any other method or a method to correct this issue?
Answer: The error message "We're sorry, a server error occurred. Please wait a bit and try again." indicates that something went wrong deep within Apps Script. You'll have to troubleshoot the problem further before you can get help, and the Apps Script troubleshooting guide should help you do that.
Comment: I mostly likely should have mentioned this within my first post, but the error ONLY occurs when I attempt to obtain the data contained within the .docx file. Otherwise, the error does not occur. In this case, the .getDataAsString('UTF-8'); is the cause.

Google Apps Scripts - MSWord to String


Field property question

Question: It seems like there is a simple field property I'm missing.
If we look at the group $Z_n$ for any $ n>=3$ can we say that :
It is possible that $(1*2*3*....*(n-1))^2 = 0 $ ?
Can you please advise?
Guy
Comment: http://mathworld.wolfram.com/WilsonsTheorem.html
Comment: @lab bhattacharjee Thank you but I know Wilsons Theorem but I can't use it here.
Comment: Sadly, the abelian group $\Bbb{Z}_n$ does not extend to a field for arbitrary $n$. If we only consider the ones which do extend to fields, note that there are no nilpotent elements, so equivalently, we want to determine whether there exists $p$ such that $(p-1)!$ is divisible by p, a trivial result.
Comment: @peoplepower finding p such that (p-1)! is divisible by P gives me what?
Answer: Try it: if $n=3$ you get $(1\cdot 2)^2=1$ in $\Bbb Z_3$, not $0$, but if $n=4$ you get $(1\cdot2\cdot3)^2=0$ in $\Bbb Z_4$, so it clearly depends on $n$. Exercise: Prove that $\big((n-1)!\big)^2=0$ in $\Bbb Z_n$ if and only if $n$ is composite.
Of course this means that if $n$ is composite, then $\Bbb Z_n$ is not a field. If you're interested in fields, you want $n$ to be prime.

Field property question


Erro RuntimeException

Question: Quando inicio o Run do app a Build me da o seguinte erro
java.lang.RuntimeException: java.lang.RuntimeException: java.io.FileNotFoundException: C:\Users\murilo\AndroidStudioProjects\Prism\app\build\intermediates\instant_run_split_apk_resources\debug\instantRunSplitApkResourcesDebug\out\slice_7\resources_ap

Em um minuto estava funcionando no outro não, a unica coisa que eu fiz foi uma mudança de layout e então isso! Alguem tem alguma ideia do que pode estar acontecendo e como resolver
EDIT
Como me pediram aqui esta o xml da activity antes
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbarCS"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    </android.support.design.widget.AppBarLayout>
    <TextView
        android:id="@+id/nameItem"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_marginTop="40dp"
        android:layout_marginStart="40dp"/>
    <TextView
        android:id="@+id/timeCust"
        android:layout_width="180dp"
        android:layout_height="30dp"
        android:layout_marginTop="20dp"
        android:layout_marginStart="40dp"/>
    <TextView
        android:id="@+id/disponibilidade"
        android:layout_width="180dp"
        android:layout_height="30dp"
        android:layout_marginTop="20dp"
        android:layout_marginStart="40dp"/>
</LinearLayout>

E aqui esta o xml depois
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbarCS"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    </android.support.design.widget.AppBarLayout>
    <TextView
        android:id="@+id/nameItem"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_below="@id/appbar"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true"/>
    <TextView
        android:id="@+id/timeCust"
        android:layout_width="180dp"
        android:layout_height="30dp"
        android:layout_below="@id/nameItem"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"/>
    <TextView
        android:id="@+id/disponibilidade"
        android:layout_width="180dp"
        android:layout_height="30dp"
        android:layout_below="@id/timeCust"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

E aqui o código da activity
class ConfirmationScreen : BaseActivity() {

    private val unidade : Item by lazy { intent.getParcelableExtra<Item>("item") }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.confirmation_screen)
        setupToolbar(R.id.toolbarCS, "Confirmation", true)
        initView()
    }

    private fun initView() {
        nameItem.text = unidade.name
        timeCust.text = unidade.timeCust
        disponibilidade.text = unidade.delivery
    }

}

Eu mudei de Linear para um Relative e depois disso o erro começou, o código não mudou
Comment: Eu já tive problemas com `slices` do apk antes, na maior parte eu resolvi executando o **Build** > **Clean Project** e apos o termino executando **Build** > **Rebuild Project**
Comment: Já tentei e não resolveu
Answer: Manda o código completo de onde você alterou pois no Android Studio se você muda por exemplo o tipo de layout da Activity pode gerar um erro.
Vejo que criou um erro do tipo io quer dizer que ele pode ter tido um erro na entrada (in) ou saída (out) dos dados na execução. Para tratar você deverá fazer um try... catch pra tratar essa exceção ou delegar para "alguém" tratar por exemplo:
try {
      System.out.println("o que voce quer executar");
}catch(IOException e) {
      System.err.println("o que voce quer que apareça caso tenha um erro");
}

eu dei o exemplo em java tem que ver o que tem no seu código que tenha gerado esse erro

Erro RuntimeException


Need help calculating a simple inverse function

Question: Quick question.
$$y=\sqrt{2x-x^2}$$
I need the inverse function for some other problem, but I just can't find it.
Could you please point me the steps to solve this?
Thanks
Comment: You need to give the domain before we can find the inverse.
Comment: Remember that $y$ is nonnegative.
Comment: Graph demonstrating it isn't bijective -
 https://www.desmos.com/calculator/k2syqzflzq
Answer: You need to specify the domain of your function. If you just want $2x-x^2 \ge 0$, then you'll find that your function is not one-to-one and does not have an inverse.
You could restrict the domain to $0 \le x \le 1$ and that would then give a one-to-one function. You could also choose the domain $1 \le x \le 2$ to get a one-to-one function. In fact there are many others, e.g. $\frac{1}{3} \le x \le \frac{1}{2}$.
Let's choose the domain $0 \le x \le 1$. You can see that the function is one-to-one by sketching the graph or by computing the derivative and showing that it is always non-negative. If $0 \le x \le 1$ then $0 \le \sqrt{2x-x^2} \le 1$ gives the range.
Next we use the standard trick: write $y=\sqrt{2x-x^2}$ and solve for $x$. We get $x = 1 \pm \sqrt{1-y^2}$. We chose the domain $0 \le x \le 1$ and so we know that when $x=0$, $y=0$. This tells us that we need to chose $x=1-\sqrt{1-y^2}$. The $+$ solution does not work hold at $(0,0)$.
(We would choose $x=1+\sqrt{1-y^2}$ on the domain $1 \le x \le 2$.)
Finally we conclude that is $\mathrm f(x)=\sqrt{2x-x^2}$ for all $0 \le x \le 1$ then $\mathrm f^{-1}(x) = 1-\sqrt{1-x^2}$ for all $0 \le x \le 1$.
Alternatively, if $\mathrm g(x)=\sqrt{2x-x^2}$ for all $1 \le x \le 2$ then $\mathrm g^{-1}(x) = 1+\sqrt{1-x^2}$ for all $0 \le x \le 1$.
Answer: Steps towards an inverse function:

Figure out what values $x$ and $y$ can have. Since $y$ is a square root, it has to be positive. The thing under the root needs to be non-negative, so… (Or perhaps a domain and codomain were already given? I have to assume some context here.)
Solve for $x$ from the equation you have. Start by squaring the sides. Then the quadratic formula will help.
See that the formula you get makes sense: $x$ and $y$ need to satisfy what you found in step 1.
Answer: $$
y=\sqrt{2x-x^2}\\
x^2-2x+y^2=0\\
x=1\pm \sqrt{1-y^2}
$$
Comment: This answer is not quite right. You need to specify the domain of the function - it isn't one-to-one as written. Secondly, you need to use the choice of domain to decide on the $\pm$.
Answer: $y=\sqrt{2x-x^2}$
$y^2=2x-x^2$
$y^2-1=-1+2x-x^2$
$1-y^2=x^2-2x+1$
Becoming visible now?
$\sqrt{1-y^2}=x-1$
$x=1+\sqrt{1-y^2}$
But our INVERSE is obtained by switching $x$ and $y$ to get $\boxed{y=1+\sqrt{1-x^2}}$.
Comment: why am i doing this in my free time
Comment: This answer isn't quite right. If $y = \sqrt{2x-x^2}$ then $y\ge 0$ and so you need to restrict the domain of your final expression. Also, you need to explain why you ignore the $\pm$ when you square root.
Comment: @JoaquinBenitez the answer you choose is wrong. Flybynight's answer is perfect... :\
Comment: I understand the aspect of the domain commented by Fly by Night.
Despite that, this is the kind of mechanical answer I was looking for.
Thanks to all!
Comment: @JoaquinBenitez I'm glad you found an answer you like. But please remember that without considering the domain *you will often get the wrong answer!* Without a domain your function does not have an inverse. With a domain we need to decide between $1-\sqrt{1-x^2}$ and $1+\sqrt{1-x^2}$.
Answer: The domain of $f(x)=\sqrt{2x-x^2}$ is $$\mbox{dom}(f)=\{x\in\mathbb{R} \ | \ 0\le x\le 2\}$$ moreover its image is $$\mbox{Im}(f)=\{y\in\mathbb{R} \ | \ 0\le y\le 1 \}$$ Its graph is a semicircumpherence with centre $C(1,0)$ and radius $r=1$ infact
$\\ y=\sqrt{2x-x^2}\implies y^2=2x-x^2\implies \\ \\ \\  x^2+y^2-2x=0\implies \implies x^2+y^2-2x+1-1=0$
so graph of $f$ is a part of the circumpherence of equantion $(x-1)^2+y^2=1$ that lies in the first quadrant. This implies that $f(x)=\sqrt{2x-x^2}$ is not globally injective hence it can't be invertible on the domain.
but... consider the equation
$y=\sqrt{2x-x^2}$
square both side
$y^2=2x-x^2\implies y^2-2x+x^2=0\to (x-1)^2+y^2=1$
solve with respect of $x-1$
$(x-1)^2=1-y^2\to |x-1|=\sqrt{1-y^2}$
If $1\le x\le 2$ then $|x-1|=x-1$ so
$|x-1|=\sqrt{1-y^2}\implies x-1=\sqrt{1-y^2}\implies x=\sqrt{1-y^2}+1$
swap the variables
$y=\sqrt{1-x^2}+1$ is the inverse of $f(x)$ for $x\in [0,1]\wedge y\in [1,2]$
If $0\le x\le 1$ then $|x-1|=1-x$ so $|x-1|=\sqrt{1-y^2}$ becomes $$1-x=\sqrt{1-y^2}\implies x=1-\sqrt{1-y^2}$$
Swap the variables $y=1-\sqrt{1-y^2}$
Hence $y=1-\sqrt{1-x^2}$ is the inverse of $f(x)$ when $x\in [0, 1]\wedge y\in [0,1]$.
Comment: Sorry, I need to improve my english...


How to properly use `__attribute__((format (printf, x, y)))` for C11 U"unicode literals"?

Question: I'm porting an application from using char* for everything and everywhere to using UCS4 as it's internal Unicode representation. I use C11's U"unicode literals" for defining strings, which expand to arrays of char32_t, which are uint32_t essentially.
Problem is with properly annotating printf-like functions. As "format" is no longer char*, compiler refuses to compile it further, as well it won't be happy with char32_t * instead of char * for %s format, I suppose.
I don't depend on stdlib *printf family at all, so formatting is done purely by mine implementation.
What is correct solution for this, other than just disable this attribute altogether?
Comment: My application operates solely on codepoints, so there is really no point for me to consider grapheme clusters, user-perceived characters and such. UCS4 greatly simplifies string processing as for now, as I can reuse most of existing codebase, and I will migrate internal representation to UTF8 in next iteration.
Comment: A side-question: What benefit do you think to gain from using UTF-32 instead of UTF-8? And are you really sure that's worth it? (UTF-32 has multi-codepoint glyphs too.)
Comment: I also seem to miss the point of `U"..."` stuff, seems like a complicated step, in particular since C11 adds only minor support to handle these. You could just use the `"\u2002"` notation to implement all Unicode code points that you need as mbs. For the question itself, you should probably ask the gcc people directly. This is nothing very common, so you really need their expertise on the question.
Answer: There is currently no way to do this in GCC.  It is a known bug, see GCC bug 64862
Comment: Thank you very much for update! Any similar info on clang maybe?


Limitar a um clique por pessoa

Question: Eu quero limitar o clique de um botão a 1 clique por computador.
É possível?
Código até agora:

    I Like!

<? include "contador_arquivo.txt"; ?> People Enjoy it

Comment: Sei que você disse "por computador", mas não seria o caso de ser "por usuário?". Neste caso bastaria você criar um cadastro/login e pronto***.
Answer: Opa use esse javascript:
var createCookie = function(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

Fornecido por: SOen
Após isso você pode criar uma função no clique do link:
I Like!

depois criar uma função para validar:
function check(){
    check = getCookie('isclique');
    if(check){
       return false;
    }
    createCookie('isclique','true',100);
}

Algo do gênero. Fiz com pressa.
Mas essa validação não é 100%,  a "unica" maneira 100% que ainda da pra burlar mas é mais segura que essa, seria validar no backend.
Comment: Uma observação, aqui só funciona se você colocar `onclick="return check()"` ao invés de  `onclick="check()"`, que realmente faz mais sentido.
Comment: Igual o @Guerra mencionou, essa validação não é 100% porque ela fica limitado ao `navegador`, caso o usuário trocar de navegador ele poderá novamente clicar.
Comment: Eu não consegui. Em cada página coloco cada um dos códigos?

Limitar a um clique por pessoa


problemas ao submeter formulario

Question: Galera desenvolvi um formulário nesse site em php e javascript la tem um select multiple onde o usuário vai poder selecionar mais de um valor quando envio meu formulário ele chega com todas as informações porem onde existe select multiple ele não aparece nada essa e a linha aonde vai ter o array
 <select id="select-picker" class="selectpicker config" multiple
         name="config[]" id="config" data-selected-text-format="count > 3"
         title="Configurações do evento">

<select id="select-picker" class="selectpicker" multiple
         data-selected-text-format="count > 3" title="Selecione os equipamentos"
         name="equip[]" id="equip" required>

a questão aqui é que não sei como fazer a chamada dessas tags name="config[]" ou name="equip[]" por exemplo no meu código php ou javascript alguém poderia me ajudar segue os códigos do projeto:
HTML:
<form class="form-budget" id="form-elements" onSubmit="return false">

                                <input type="text" placeholder="Digite seu nome" name="name" id="name" required/>
                                <input type="text" placeholder="Digite seu Email" name="email" id="email" required/>
                                <input type="tel" placeholder="Digite seu Telefone" name="phone" id="phone" class="phone_with_ddd" required/>
                                <input type="text" placeholder="Data do evento" name="date" id="date" class="date" required/>

                                <select id="select-picker" class="selectpicker config" multiple
                                        name="config[]" id="config[]"
                                        data-selected-text-format="count > 3" title="Configurações do evento">
                                    <option value="Mesas-Cadeiras" selected>Mesas e cadeiras</option>
                                    <option value="Auditório" selected>Auditório</option>
                                    <option value="Lounge">Lounge</option>
                                    <option value="Galeria">Galeria</option>
                                </select>
                                <input type="text" placeholder="Quantidade de pessoas" name="quant" id="quant" class="quant" required/>

                                <select id="select-picker" class="selectpicker" multiple
                                        data-selected-text-format="count > 3" title="Selecione os equipamentos"
                                        name="equip[]" id="equip[]" required>
                                    <option value="Projetor">Projetor</option>
                                    <option value="Som">Caixa de som</option>
                                    <option value="Flip-Chart">Flip-Chart</option>
                                </select>
                                <button type="submit" class="btn btn-success" id="submit_btn">Enviar orçamento</button>

                        </form>

JS:
//Contact Us
$("#submit_btn").click(function() {
    //get input field values
    var user_name       = $('input[name=name]').val();
    var user_email      = $('input[name=email]').val();
    var user_phone      = $('input[name=phone]').val();
    var user_date       = $('input[name=date]').val();
    var user_config     = $('select[name=config] option:selected ').val();
    //console.log(user_config);
    var user_quant      = $('input[name=quant]').val();
    var user_equip      = $('select[name=equip] option:selected').val();
    //var user_message    = $('textarea[name=message]').val();

    //simple validation at client's end
    var post_data, output;
    var proceed = true;
    if(user_name==""){
        proceed = false;
    }
    if(user_email==""){
        proceed = false;
    }
    if(user_phone=="") {
        proceed = false;
    }

    if(user_quant=="") {
        proceed = false;
    }
    if(user_date=="") {
        proceed = false;
    }

    //everything looks good! proceed...
    if(proceed)
    {
        //data to be sent to server
        post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userDate':user_date, 'userConfig':user_config, 'userQuant':user_quant, 'userEquip':user_equip};

        //Ajax post data to server
        $.post('contact.php', post_data, function(response){

            //load json data from server and output message
            if(response.type == 'error')
            {
                output = '
'+response.text+'
';
            }else{
                output = '
'+response.text+'
';

                //reset values in all input fields
                $('#form-elements input').val('');
                $('#form-elements textarea').val('');
            }

            $("#result").hide().html(output).slideDown();
        }, 'json');

    }
});

PHP:
<?php
if($_POST)

{
    $to_Email       = "email@example.com"; //Replace with recipient email address
    $subject        = 'Orçamento do site'; //Subject line for emails

    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

        //exit script outputting json data
        $output = json_encode(
        array(
            'type'=>'error',
            'text' => 'Request must come from Ajax'
        ));

        die($output);
    }

    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userDate"]) || !isset($_POST["userQuant"]))
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Os campos de entrada estão vazios!  '));
        die($output);
    }

    //Sanitize input data using PHP filter_var().
    $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Phone =                  $_POST["userPhone"];
    $user_Date =                   $_POST["userDate"];
    $user_Config       =           $_POST["userConfig"];
    $user_Quant =                  $_POST["userQuant"];
    $user_Equip       =            $_POST["userEquip"];
    //$user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);

    //additional php validation
    if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'O campo nome não pode ficar vazio'));
        die($output);
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Por favor ultilize um e-mail válido'));
        die($output);
    }

    if(strlen($user_Phone)<5) //check emtpy phone
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Por favor insira um número de telefone'));
        die($output);
    }

    if(strlen($user_Date)<5) //check emtpy date
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Por favor insira uma data para o evento'));
        die($output);
    }

     if(strlen($user_Quant)<2) //check emtpy date
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Por favor insira a quantidade de pessoas para o evento'));
        die($output);
    }

    $message_Body = "Name: ". $user_Name ."
";
    $message_Body .= "Email: ". $user_Email ."
";
    $message_Body .= "Phone: ". $user_Phone ."
";
    $message_Body .= "Data do Evento: ". $user_Date ."
";
    $message_Body .= "Quantidade de pessoas: ". $user_Quant ."
";
    $message_Body .= "Configurações do evento: ". $user_Config ."
";
    $message_Body .= "Equipamentos: ". $user_Equip ."
";
    //$message_Body .= "Message: ". $user_Message ."
";

    $headers = "From: " . strip_tags($user_Email) . "\r\n";
    $headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

    //proceed with PHP email.
    $headers = 'From: '.$user_Email.'' . "\r\n" .
    'Reply-To: '.$user_Email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion(). "\r\n" .
    'Content-type: text/html;charset=UTF-8';

    $sentMail = @mail($to_Email, $subject, $message_Body, $headers);

    if(!$sentMail)
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Ocorreu um erro tente novamente'));
        die($output);
    }else{
        $output = json_encode(array('type'=>'message', 'text' => 'Olá '. $user_Name .' Obrigado pelo seu contato retornaremos em breve.'));
        die($output);
    }
}
?>

Comment: Posso estar enganado, mas não me parece correto o uso de `[]` nos ids...
Comment: tente usar o $("#form-elements").serialize(); no lugar do post_data = {'userName... e veja o que chega de resultado no seu php, utilizando o var_dump ou print_r
Comment: obrigado pelo comentário eu já editei a pergunta estava realizando uns testes no código e esqueci de remover do id mais amigo você conseguiu entender minha dúvida na pergunta ? preciso terminar isso ainda hoje e nao tenho ideia de como fazer a chamada do name="config[]" no meu código js e php
Comment: é para eu colocar so esse código no lugar desse  post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userDate':user_date, 'userConfig':user_config, 'userQuant':user_quant, 'userEquip':user_equip};
Comment: exatamente. Ficará assim:  var post_data = $("#form-elements").serialize();
Comment: acredito que o seu erro seja na hora de pegar o valor do formulário e passar pra variável post_data e o ajax
Comment: @Kirito se o valor das variáveis config e equip aparecerem no var_dump do PHP, me avise para postar como resposta e explicar para alguém que possa vir a ter a mesma dúvida. abraços
Comment: @DiegoAndrade amigo eu comentei essa linha inteira post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userDate':user_date, 'userConfig':user_config, 'userQuant':user_quant, 'userEquip':user_equip}; e vou adicionar o código que vc mandou acima var post_data = $("#form-elements").serialize(); e vou ver o resultado
Comment: @DiegoAndrade se eu edito o código da forma que você me passou ele cai nesse erro aqui que está no php  $output = json_encode(array('type'=>'error', 'text' => 'Os campos de entrada estão vazios!  '));
Comment: Kirito, edite o php, coloque na primeira linha o seguinte trecho de código: var_dump($_POST); die; abra o seu console do navegador, olhe no console o que o php retornou e cole aqui
Comment: @DiegoAndrade coloca isso antes da abertura da tag do  string(21) "felipe henrique silva" ["userEmail"]=> string(29) "email@example.com" ["userPhone"]=> string(14) "(11) 43710-555" ["userDate"]=> string(10) "21/32/1231" ["userConfig"]=> array(2) { [0]=> string(14) "Mesas-Cadeiras" [1]=> string(10) "Auditório" } ["userQuant"]=> string(6) "555555" ["userEquip"]=> array(2) { [0]=> string(8) "Projetor" [1]=> string(10) "Flip-Chart" } }
Comment: no var dump que te mandei acima ele apareceu todas as infos porque no meu html na tag name="config[]" eu retirei esses conchetes e ao refazer o teste com os conchetes olha como ficou

array(5) { ["userName"]=> string(21) "felipe henrique silva" ["userEmail"]=> string(29) "firstname.lastname@example.com" ["userPhone"]=> string(14) "(11) 43710-555" ["userDate"]=> string(10) "55/55/5555" ["userQuant"]=> string(3) "666" }
Comment: @Kirito caso a minha resposta esteja correta, se puder marcar como resposta correta eu agradeço! abraços e espero ter ajudado
Comment: @DiegoAndrade amigo eu comente em baixo da sua resposta você chegou a dar uma olhadinha ? ta dando um probleminha
Answer: Olha, no PHP não vai fazer a menor diferença como você chama o select, até porque você está fazendo um post com os dados deste formulário.
Se você der uma olhada no fiddle abaixo, basicamente eu repliquei o código de um dos seus selects e coloquei um JS bem simples para printar o que ele produz no final:

$('button').on('click', function(e) {
  console.log($('#select-picker option:selected'))
})

<select id="select-picker" class="selectpicker config" multiple name="config[]" id="config[]" data-selected-text-format="count > 3" title="Configurações do evento">
                                    <option value="Mesas-Cadeiras" selected>Mesas e cadeiras</option>
                                    <option value="Auditório" selected>Auditório</option>
                                    <option value="Lounge">Lounge</option>
                                    <option value="Galeria">Galeria</option>
                                </select>
<button type="button">
ok</button>

Veja que ele printa um array de objetos, cujos dois primeiros elementos são os elementos que você selecionou, então como você já tem um ID no seu elemento, então você pode só iterar pelos valores mais ou menos assim:

$('button').on('click', function(e) {
  var selected = $('#select-picker option:selected')

  for(var i = 0; i < selected.length; i++) {
    console.log(selected[i].value)
  }
})

    <select id="select-picker" class="selectpicker config" multiple name="config[]" id="config[]" data-selected-text-format="count > 3" title="Configurações do evento">
                                        <option value="Mesas-Cadeiras" selected>Mesas e cadeiras</option>
                                        <option value="Auditório" selected>Auditório</option>
                                        <option value="Lounge">Lounge</option>
                                        <option value="Galeria">Galeria</option>
                                    </select>
    <button type="button">
    ok</button>

Só que você monta um array com os valores e manda isso pelo post para o PHP, você vai receber um array do outro lado e pode tratar da forma que você quiser.
Answer: O erro está na definição da variável js "post_data" com os dados que vc enviara pelo ajax.
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userDate':user_date, 'userConfig':user_config, 'userQuant':user_quant, 'userEquip':user_equip};

após todas as validações que foram feitas acima disso, como você irá utilizar todos os campos do formulário para enviar para o ajax, vc pode utilizar o serialize(),
var post_data = $("#form-elements").serialize();

que pega todos os campos do formulário e transforma em uma string com os nomes dos inputs e os valores em formato de objeto codificado. Assim, vc fará o envio pelo ajax e conseguirá trabalhar com as informações desejadas lá.
Edit:
Depois, alterando os nomes das variáveis para os nomes respectivamente enviados, tanto na validação, quanto na atribuição dos valores, deve funcionar.
Para transformar o array em string, faça da seguinte forma?
substitua as 2 linhas onde vc atribui as variáveis user_Config e user_Equip por isso:
$user_Config       =           implode(", ",$_POST["config"]);
$user_Equip       =            implode(", ",$_POST["equip"]);

abraços
Comment: exatamente. Deu certo?
Comment: skype diegosalamex
Comment: amigo ao fazer isso ele cai em um erro no meu php que está nessa linha if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userDate"]) || !isset($_POST["userQuant"]))
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Os campos de entrada estão vazios!  '));
        die($output);
    }

se eu editar meu JS assim no php tem alguma mudança?
Comment: acredito que essa seja a resposta mais so preciso saber agora porque so cai nessa condição quando edito meu código para  esse que você mandou ele so cai na condição mencionada acesse o site aonde esta o formulário que você vera o erro
Comment: adicionei um var dump logo abaixo do if(!isset($_POST["userName"] ....))
para ver oque aparece no console

array(7) { ["name"]=> string(21) "felipe henrique silva" ["email"]=> string(29) "email@example.com" ["phone"]=> string(14) "(11) 43710-555" ["date"]=> string(10) "23/45/4235" ["config"]=> array(2) { [0]=> string(10) "Auditório" [1]=> string(6) "Lounge" } ["quant"]=> string(6) "666666" ["equip"]=> array(2) { [0]=> string(8) "Projetor" [1]=> string(3) "Som" } }
Comment: opa, desculpa @Kirito, não tinha visto. Vc deu var_dump($_POST) e ele retornou estes dados a seguir?? array(7) { ["name"]=> string(21) "felipe henrique silva" ["email"]=> string(29) "email@example.com" ["phone"]=> string(14) "(11) 43710-555" ["date"]=> string(10) "23/45/4235" ["config"]=> array(2) { [0]=> string(10) "Auditório" [1]=> string(6) "Lounge" } ["quant"]=> string(6) "666666" ["equip"]=> array(2) { [0]=> string(8) "Projetor" [1]=> string(3) "Som" } }
Comment: se foi isso, confira o nome das variáveis que vc está enviando, com os nomes das variáveis que estão na condição. Eles devem ser idênticos: if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userDate"]) || !isset($_POST["userQuant"]))
Comment: amigo no caso as variaveis que estão dentro do meu if tem que ser iguais as que deu no vardump
Comment: ficando assim if(!isset($_POST["name"]) || !isset($_POST["email"]) || !isset($_POST["phone"]) || !isset($_POST["date"]) || !isset($_POST["quant"]))
Comment: Amigo posso te adicionar no facebook ou skype para você dar uma ultuima olhada? ele paraou de cair naquela condição  e ta enviando normal mais ainda não recebo no email os campos que tem o selectpicker
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/59647/discussion-between-kirito-and-diego-andrade).
Comment: Ja vou adicionar
Comment: já enviei a solicitação

problemas ao submeter formulario


Java method stuck in endless loop while validating input

Question: Somehow I am getting some funny play here and I just cant see why.
This method is supposed to make sure that the input is either y or n, and is NOT blank.
I should note this is for school, and the 2 separate error outputs are required.
When I enter a blank line, I get exactly  that at the console- a blank line.
After that point, or after a time where I purposely enter bad data, such as x, the very next time I enter a valid data, like y or n, I continue to get the bad data in an endless loop.
What have I done wrong?
public static boolean getContinue(Scanner sc)
   {
   boolean decision = false;
   System.out.println("Continue? Y/N: ");
   String userChoice = sc.next();
   boolean isValid = false;
   while (isValid == false)
   {
       if (userChoice.equalsIgnoreCase("y"))
       {
           decision = true;
           isValid = true;
       }
       else if (userChoice.equalsIgnoreCase("n"))
       {
           decision = false;
           isValid = true;
       }
       else if (userChoice.equals(""))
       {
       System.out.println("Error! This entry is required. Try again.");
       userChoice = sc.next();
       }
       else if (!userChoice.equalsIgnoreCase("y") | (!userChoice.equalsIgnoreCase("n")))
       {
        System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
        userChoice = sc.next();
       }
   }
   return decision;
   }

NOTE:
Code was amended to include
New console outputs(Still wrong)
FORMATTED RESULTS
Loan amount:          $5.00
Yearly interest rate: 500%
Number of years:      5
Monthly Payment:      $2.08
Continue? Y/N:
b
Error! Entry must be 'Y' or 'N'. Try again.
y
Error! Entry must be 'Y' or 'N'. Try again.
y
Enter loan amount:
Answer: You don't set the variable userChoice to the new value. Change your last if clause to
System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
userChoice = sc.next();

Comment: u r doing wrong using `bitwise OR` (|), rather u have to use `logical AND` (&&)
Comment: @user3175451 this is about logic. just think about the case what inputs to go into this `else-if`; those which are neither 'y' nor 'n'.  let, A = caseY, B = caseN. so, we need something like this: `!(A || B)`. according to Morgans law, it implies `!A && !B`.
Comment: this somewhat worked, but when I DO enter Y for valid data, i have to do it twice back to back now. Also, my blank scenario is not working still. I will amend the question to show the console outputs
Comment: @WasifHossain, how do you figure? It cannot be both values, why would I use &&?
Comment: What happens is this: First you get to your first if clause which evaluates true, because you entered "y". Second you get to your last if clause which ALSO evaluates true because !userChoice.equalsIgnoreCase("n") evaluates true and then you get another prompt.
Answer: Because userChoice never changes inside the loop (which is because you don't change it).
Answer: Please look at else if part:
else if (!userChoice.equalsIgnoreCase("y") | (!userChoice.equalsIgnoreCase("n")))

here you have done 2 errors:

you have used |, which is bitwise operator, not logical
the logic requires logical AND (&&) to get the cases when the input is not either y or n

SO the correct else-if:
else if (!userChoice.equalsIgnoreCase("y") && (!userChoice.equalsIgnoreCase("n")))
{
    System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
    userChoice = sc.next();
}

Comment: This makes a whole lot of since now. Thank you. I am still wondering why my blank input line isn't working?
Comment: blank input line indicates `\n`. so i think you require `\n`. So instead of `else if (userChoice.equals(""))`, u have to use `else if (userChoice.equals("\n"))`
Comment: still nothin on this one. NetBeans noticed the newline char but testing it showed up same as before
Answer: You have to use sc.nextLine() in order to catch the Empty Blank Line. So replace all the instances of sc.next() with sc.nextLine()


Squeez the words in c - Basic C Language

Question: I am not sure what I am doing wrong in the following code,
That is what I want to achieve

User Input: aaaaaadsssssc
Output: a6ds5c

My program was working fine until this morning I was being stupid enough to overwrite the whole file. Oh well, welcome to Linux! Since I rewrite the program it is giving me Segment Fault Error, and I have no clue what I am doing wrong here and my mind is stop working at this point.
<code>#include <stdio.h>
#include <string.h>

int main(){
        int i, j, k, count;
        char str[1000];

        printf("Enter: ");
        scanf("%[^\n]s", str);
        printf("You have typed: %s\n", str);

        printf("length: %d\n", strlen(str));
        for (i = 1; i < strlen(str); i++){
                count = 2;

                if (str[i] == str[i-1]){
                        j = i;
                        while (str[i] == str[i+1]){
                                if (k != strlen(str)){str[k] = str[k+1];}
                                else{str[k] = '\0';}
                                i++; k++; count++;
                        }
                str[j] = count;
                k++;
                }
        }
        str[k] = '\0';
        printf("output: %s\n", str);
}
</code>
I have this due in few days and I screwed up so bad. Could someone please point out the mistake I am making? A big thanks in advance!
Comment: You haven't initialized `k`. What are you expecting its value to be when you compare it with `strlen(str)` in the innermost loop?
Comment: Unrelated to the segfault, but I suggest using `%zu` instead of `%d` to print the `size_t` returned by `strlen()`.
Comment: @squeamishossifrage I did initialized `k`, I think I don't need to compare `k` with `strlen(str)` because `k` will never be equals to `strlen(str)`. Just to be on a safe side I decided to add `NULL` character to avoid having garbage values in the string.
Answer: This will work:
<code>    #include <stdio.h>
    #include <string.h>

    int main(){
            int i, count;
            char str[1000];

            printf("Enter: ");
            scanf("%s", str);
            printf("You have typed: %s\n", str);

            //used strlen() only once because strlen() takes O(n) time
            int len = strlen(str);
            printf("length: %d\n", len);

            //iterate through the string
            for (i = 0; i < len - 1; i++){

                    //every char appears at least once
                    count = 1;

                    //print the char regardless of it repeating
                    printf("%c", str[i]);
                    for (int j = i; str[j] == str[j+1]; ++j, ++i)
                            ++count;

                    //print the count if it's greater than 1
                    if (count > 1) printf("%d", count);
            }

            //print the last char if it's different from the second last
            if (str[len - 1] != str[len - 2]) printf("%c", str[len - 1]);

            //print new line
            printf("\n");
    }
</code>


Well/Ill posedness on Generalized heat equation

Question: Suppose we have the following one dimensional generalized heat equation:
$$u_t(x,t)=g(x,t)\Delta u(x,t) \ \ \ x\in\mathbb{R},t\in(0,\infty)$$
I need to prove that this equation is ill posed, for some initial data and some particular g(x,t). Is there any literature on such equation? I have found loads on equation like
$$ u_t= \Delta u(x,t) + f(x,t)$$
which different f(x,t), but no one where the Laplacian is multiplied by another function.
Thanks a lot guys!
Answer: If you are free to pick the function $g$ to show ill-posedness, just take $g=-1$. Then, the ill-posedness for that case will follow from the smoothing effect when $g=1$.


Keyboard focus being stolen by Flash

Question: Performing a search, I noticed several questions dedicated to how to steal/trap the keyboard focus of the visitor. Considering this site is dedicated to programming that's not suprising. I was wondering if anyone can advise me on how to prevent this type of behavior. Losing keyboard focus to flash basically removes my browser's functionality until I use the mouse to click elsewhere (I use Mozilla Firefox). Anyone know of some kind of plugin or greasemonkey script that will prevent my keyboard focus from being stolen? Normal browser "shortcuts" are rendered useless by having to use the mouse to return keyboard focus to the browser.
Edit: Reply to the post below, I do have flashblock / noscript and some other things. My issue is flash that I want to see/interact with stealing my focus. Basically looking for something I can toggle that will prevent flash from getting keyboard focus or a way to force my firefox keyboard commands to the browser
Comment: HELP! Mee Too! Drives me batty as I am heavily keyboard driven.
Comment: The OP is not looking to program something, they are looking for a plugin.  This belongs on superuser.
Comment: migrate to superuser please!
install [Focus Retainer addon](https://addons.mozilla.org/en-US/firefox/addon/focus-regainer/) and press `ctrl`+`f12`
Answer: Unfortunately, it is almost a decade old well known FF bug (and now in Chrome too), which is not present in IE. All the Ctrl+T, Ctrl+Tab, Ctrl+W etc. keys just stop working when the focus is on a flash object.
The worse thing is, no one seems to know the fix for it yet (see the thread above). Some IBM people made a hack fix for Linux, but there is none for Windows. It is really really annoying.
[update Mar 2013: In google chrome Version "24.0.1312.52 m" and I assume higher versions, the  Ctrl+Tab key does not loose focus to flash]
Comment: I got this horrible hack working in Chrome with jQuery, where `this` is some element of the page we're fine if the viewport scrolls to: $("").css({opacity: 0}).appendTo(this).focus().remove();
Comment: cool, this really works!!! Thanks Henrik, it must be the correct answer and not a comment
Answer: There seems to be no CTRL or ALT combination that would release the focus. The only ones working are that of operation system's. It does not help you to go to another window, the focus still stays, and no, you can not change tab, close it or do anything else either you normally would with keyboard.
I was using my computer without a mouse for a while and this was the first actual problem I had (in addition to missing drag'n'drop features for some sites and facing unreachable button like icons). So those of you who face the same dilemma and don't wish to close the Firefox altogether, you can still use ALT to focus on toolbar of the application (at least in Windows). However, there is no option for closing the tab but you can select any other site from History (e.g. your home page which comes first with h letter) and then finally close the tab.
So (at least in Windows using FF5) e.g. in English version of Firefox you could type:
ALT+S+H
and then go back using ALT← (or close the tab with CTRL+W or CTRL+F4).
Answer: Similar question:
Flash steals browser focus
The (not accepted but looks promising) answer of:
<code> document.body.focus();
</code>
may work for you. That can easily be greasemonkeyed. Probably.
Answer: On Mac OSX 10.6 using Firefox 4, if the plugin (flash) has focus and your tabbing does not work by using Cmd+1, or Cmd+T for a new tab, etc..
Use Cmd+L first to give the browser address bar focus, and then do Cmd+1, etc...
Answer: Alt-Tabbing to your current app will return focus.
Comment: In a browser running multiple tabs this does not move focus from flash content when you return to the browser.
Answer: First, check to make sure you are using a flash player higher than version 6.0.  Also, another responder was correct.  FireFox should not automatically take focus of inline flash content...it isn't designed that way.
Secondly, This is not just an annoyance, this is an accessibility concern.  Those users who can only navigate with a keyboard or assistive device like a screen reader will not be able to escape...because they don't/cant't use a mouse.
To avoid flash in keyboard navigation, or to hide unimportant Flash content from both web browser and screen readers, add the wmode option with a value of opaque to both the object and embed tags of the web page containing the Flash movie or swf.
Example of code:
<code><object ...>
<param name="wmode" value="opaque">
<embed wmode="opaque" ...>
</embed>
</object>
</code>
This will effectively hide the Flash movie from the screen reader/assistive device and the keyboard. It will still appear visibly within the page, but while navigating through the page, the keyboard will bypass the Flash content and the screen reader will act as if it isn't even there.
HOWEVER!!!!
If the movie/swf DOES contain important information, either display the Flash movie in a page by itself or include the link to download the latest version of the Flash player and inform users that they need to use this version. -- Of course, you should then make your flash piece keyboard navigable.
DOWNFALL OF FLASH:  Natively keyboard navigable flash is ONLY -- I repeat ONLY available in Internet Explorer...BECAUSE Adobe/Macromedia designed "Accessible Flash" to work with MSAA (Microsoft Active Accessibility) technology and the only browser that supports MSAA technology is Internet Explorer.

Keyboard focus being stolen by Flash


Why have pointer parameters?

Question:
Possible Duplicates:
Why use pointers?
Passing a modifiable parameter to c++ function

Why would I want to have pointer parameters? The only reason I can see is for small functions to attempt to reduce confusion and a smaller memory footprint.
Comment: It's entirely possible the OP has never heard of references and from his perspective it's the debate between "regular" parameters and parameters that are pointers.
Comment: For clarification: Are you talking about pointers as parameters to functions?
Comment: Possible duplicate: http://stackoverflow.com/questions/162941/why-use-pointers
Comment: @greyfade: When you create a function with pointer arguments. Why would you want to do this?
Comment: As opposed to _what_?  Do you question the use of any indirect reference or just pointers vs references?
Comment: @Matt Greer: I know what passing by reference, value, and pointer is. I know how to do it; I just don't know why would I ever want to pass by pointer vs. reference. I know why I would want to pass by value vs reference but not by pointer.
Answer: In Passing a modifiable parameter to c++ function I answered when to use a reference instead of a pointer.
Conversely, prefer a pointer to a reference when any of the following are true:

It can be null
It can be changed (to point to something else)
It must be deleted

Some people also prefer a pointer when the thing that's being pointed at should be mutated, saying that the difference between a const reference and a non-const reference isn't obvious enough to the reader.
Answer:
Compatibility with C code where references aren't available.
Variable sized arrays.
Option to have a missing parameter, i.e. NULL.
Comment: Variable sized arrays aren't in C++. (Or were you referring to dynamically allocated arrays?)
Comment: @Billy Oneal, It's variable to the function, not to the caller. I.e. `void Foo(int* array, int count); int first[10]; int second[20]; Foo(first, 10); Foo(second, 20);` You could declare instead `void Foo(int array[], int count);` but it would be exactly the same thing, just a pointer in disguise.
Answer: Pointers are the only way to accept C-style strings and arrays. They're also the only way to share data between multiple threads (besides global objects, which... ew).
Answer: There are many reasons to have pointers as parameters. A major reason is polymorphism. The pointer can point to a base class object or a subclass, and will call methods on that object accordingly.
I recommend Accelerated C++ by Koenig, he does a good job of explaining how polymorphism works in C++ via pointers (and references).
Comment: Note that polymorphism works correctly with references as well.
Comment: Your first reason doesn't require pointers.
Comment: Yeah, I said "and references". C++ happens to have two ways of invoking polymorphism. Pointers being one of them.
Answer: Two reasons:

A pointer on a 32-bit platform is only 4 bytes.  If the data you're passing to the function is more than 4 bytes, you save some call time by passing the structure by reference instead of by value.  (You may give up this performance advantage in indirection costs later, but that's where profiling comes in.)
You can pass a non-const pointer to let the function modify the passed data.
Comment: Point 2 can also be accomplished with references. Point 1 is totally moot today - moving a few bytes is extremely fast, getting speed-ups is better done in more efficient algorithms and protocols, not shaving 10 bytes off a function call.
Comment: Point 2 is a question of syntactic preference: some like to make it explicit that they're passing an address, not a value.  Point 1 is not "moot".  That would mean it doesn't matter how big your data structure is.  Try passing a 10 MB linked list by value some time.
Comment: @iconiK point 1 can be accomplished with references, but it's definitely not moot because of the reason you stated.  Objects are frequently much bigger than 10 bytes. Evaluating and passing the address of an object can be a huge speed up over copying the object, especially when it's a frequently called function.
Comment: @Graphics Noob, which is why pimpl and implicit sharing are excellent ways to speed up copying.
Answer: Other than the standard uses for a pointer parameter (that others have already stated), one reason that I can think of is to implement callbacks. You can have a function that accepts a function pointer as a parameter.
Answer: I assume you mean as opposed to references?  The thing that you can do with pointers is set them to NULL, which allows you to specify an uninitialized state. This can sometimes be useful, but the corollary to that is that if you want to enforce that NULL cannot be passed to your function then using a reference makes that clear.
Answer: if you pass a simple variable to a function, the function creates a copy of that variable for use within the function's scope. When the function completes execution, any changes made to the passed simple variable won't be shown. This is because the variable itself was never altered within the function only a copy of it was. Passing a pointer to the variable to a function solves this problem.
<code>int some_function(int num) {
   return num++;
}

int num1 = 15;

std::cout << some_function(num1) << std::endl; //prints 16

std::cout << num1 << std::endl; //prints 15
</code>
Comment: Yes but I can just pass by reference instead. Why would I want to have pointers?
Answer: IMO, pointers are made out in a lot of C++ documentation to be far more important than they actually are, whereas references are rarely discussed in introductory material (other than brief mentions in terms of parameters).
While pointers certainly have value (arrays, string, dynamic memory, etc.), a lot of their functionality can be implemented more simply with references. The only time I really use pointer parameters regularly is when I am using a third-party library which has such a use built into it.
Using references removes the copy-assignment step implicit in straight class parameters while not requiring tiresome pointer dereferencing (using * or ->) over and over again. In addition, learning to use references is important for applications such as operator overloading, which is vital for precision control of your code.
Answer: Plenty of reasons, but references should be the "standard". Use pointers only if a reference won't do. Some pros and cons:

Pointers can have NULL values, something that's extremely useful
Pointers can be of generic types and be reinterpreted as other types (though don't you dare use void *)
Pointers can be used to pass huge arrays without a huge memory footprint
In the case of generic types,
compiler optimizations can operate
better with references, because the
compiler has more information on used
types
References arguably make code
more readable, more in-line with java
and c# and thus better readability by
other types of developers
References do not actually pass the
entire object, but rather a pointer
to it, however more type information
is available to the compiler.
Answer: There is one more difference between pointer and references:
 -pointer can be a NULL-pointer
 -reference references always an real object [f(T &v); f(NULL); isn't really good idea]

Why have pointer parameters?


Add class to image in view

Question: Is there a way to add a specific class to the img tag in a view? I'd prefer to use a template to perform it. I can see how I can change what classes the image is wrapped in, but I don't see a way to edit the classes of the img tag itself.
I see there's a way to edit the image field using views-view-field--field-image.tpl.php however the only variable I can see that is available is $output.
Answer: If .myclass img { your code goes here } is not good enough and you must have the class inside the img tag, then:
1) Download and enable the Image URL Formater Module
2) On your view's picture field, select url as format.
3)
Option A) In the rewrite results field type
Option B) if you want to use the .tpl.php file, put this inside it.
<img src='<?php print $fields["field_image"]->content; ?>' class='yay-we-did-it'>
Comment: I edited my answer to provide a tpl answer.

Add class to image in view


Cannot solve this SQL query results

Question: I cant seem to work out why:
SELECT `Title`.`Title`, `FirstName`, `LastName`, `Address1`, `Address2`, `Town`.`Town`, `County`.`County`, `PostalCode`, `Phone1`, `Solo`
FROM `Person`
JOIN `Title` ON `Person`.`Title` = `Title`.`id`
JOIN `Town` ON `Person`.`Town` = `Town`.`id`
JOIN `County` ON `Person`.`County` = `County`.`id`
WHERE `Person`.`Solo`='1'
ORDER BY `LastName` ASC;

Returns 0 results, (which it shouldn't, there are at least 5 results where Solo='1')
And if I modify it, to take out all the JOINS:
SELECT `Title`, `FirstName`, `LastName`, `Address1`, `Address2`, `Town`, `County`, `PostalCode`, `Phone1`, `Solo`
FROM `Person`
WHERE `Person`.`Solo`='1'
ORDER BY `LastName` ASC;

I get Results? If I modify it to take out the WHERE Person.Solo='1' It gives me results too, but only 2; where surley it should return ALL the rows?  Can someone explain?
:)
note: Solo is a tinyint, it equels either 0 or 1 in all the records!
Answer: Your joins are strict, it means that if Person doesn't have Title or Town or Country then it wouldn't be returned. You don't get any results even if you remove whole WHERE clause.
Try LEFT JOIN instead.
This is good explanation of how different type of joins work: A Visual Explanation of SQL Joins
Comment: Aah that was it! Thank you for your help, I will read up again on LEFT RIGHT and JOIN ! :)
Comment: @Chud37, you are welcome) I've added link to article about join types.
Answer: There are some common conventions, that makes your code more readable to others. First, always use id for the (autoincrement) -primary-key. Then use xxxxx_id in related tables. Second, you should use a more precise JOIN-declaration: LEFT JOIN or INNER JOIN. Thats more easy to read. Third: Normally there is no need to use ``. In addition to that, you can use a table-alias, to reduce the amound of SQL-code.
SELECT ti.title, firstname, lastname, address1, address2, to.town, county.county, postalcode, phone1, solo
FROM person AS p
LEFT JOIN title AS ti ON p.title = ti.id
LEFT JOIN town AS to ON p.town_id = to.id
LEFT JOIN county AS c ON p.county = c.id
WHERE p.solo=1
ORDER BY lastname ASC;

Just a recommendation...

Cannot solve this SQL query results


How to use libxml2 validate a xml with a schema in version 1.1?

Question: I use libxml2 to validate xmls with a schema, and because of some
   reasons I must use schema version 1.1, so I began my schema header
   like this:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" elementFormDefault="qualified" attributeFormDefault="unqualified" vc:minVersion="1.1">

and I wrote a compleType like this:
<xs:complexType name="test-type">
    <xs:all>
        <xs:element name="test"></xs:element>
        <xs:element name="test1" minOccurs="0" maxOccurs="4"></xs:element>
    </xs:all>
</xs:complexType>

It's valid in version1.1, but invalid in version1.0. When I used my program to parse this schema:
xmlSchemaParseCtxtPtr ctxt;
xmlLineNumberDefault(1);
ctxt=xmlSchemaNewParserCtxt("schema.xsd");
_xmlSchema* _schema = xmlSchemaParse(ctxt);

I got a null-pointer in _schema.
But if i removed that upper complexType, everything was OK. So I thought may be the root cause was libxml2 only supported schema version1.0 "in my code". So is there any solution to make libxml2 work with schema version1.1? I must use some of its new features.
Any suggestion will help! Thanks!
Answer: libxml2 has not been updated to support XSD 1.1. As far as I am aware there is no active development on the product so this is unlikely to happen. You will need to find a different schema processor.
Comment: Complex types are an XSD 1.0 feature and should work fine. Asserts are an XSD 1.1 feature and are not supported in libxml2.
Comment: Hmmm can you give some link ? because I was able to validate the xml with complex types in libxml2. I got stuck at asserts because it is throwing an  error while validating it.
Comment: In 2024 (February 7), with current libxml2 from their master (13962b0), still no support for 1.1: "parser warning : Unsupported version '1.1'".
Comment: While there is a fair bit of "tinkering" activity attempting to improve libxml2, there is no sign of any serious attempt to implement modern W3C standards such as XPath 3.1 or XSD 1.1. Which is not surprising, these are major projects that cannot be done in someone's spare time.