Why do we talk about "everybody vs nobody" scenarios in causal inference?

Question: Researcher A and researcher B survey mothers in Germany and ask them:
$T =$ Whether they smoked during their pregnancy
$Y =$ The birthweight of their baby
$\boldsymbol{X} =$ All kinds of things that should be controlled for when estimating a causal effect from $T$ to $Y$
(1) Researcher A reports that "If every pregnant woman in Germany smoked, the average birthweight in Germany would be lower by 200g than if none of them smoked". Anyone you ask will tell you this is a correct interpretation of the ATE estimate.
(2) Researcher B reports that "Smoking during pregnancy causes lower birthweights. On average, 200g lower." Anyone you ask will tell you this is also a correct interpretation of the ATE estimate.
However:
(3) Since the statement in (1) is about an average, the correct take-away of this statement for a pregnant woman in Berlin debating whether to smoke or not is obviously not that her baby will be exactly 200g lighter if she smokes.
(4) But! Even if she understands this, it is still unclear how the statement should influence her decision, because she does not live in a Germany where every pregnant woman will magically follow her lead in smoking or not smoking. If she decides to smoke, the real Germany where she will do so is a very different place from the theoretical Germany in (1), where every pregnant woman smokes and gives everyone a nice dose of second-hand smoke everywhere the go.
(5) The statement of researcher B, on the other hand, refers unambiguously to the real-world Germany.
The statement in (1) is mathematically correct and comes from the definition $ATE = E[Y(1)] – E[Y(0)]$.
I think the statement in (2) follows from the fact that (under ignorability): $E[Y(1)] – E[Y(0)] = E[Y|T=1, \boldsymbol{X}] - E[Y|T=0, \boldsymbol{X}]$. Estimates for $E[Y|T=1, \boldsymbol{X}]$ and $E[Y|T=0, \boldsymbol{X}]$ then tell the German woman unambiguously that, controlling for all other relevant factors, the average baby from a smoker is lighter than the average baby from a non-smoker in real-world Germany.
Question: why do so many papers talk like Researcher A in interpreting results, when that is just how the math works and not the question anyone was hoping to answer?
Disclaimer: I can see that in some studies, the everybody/nobody could be the actual research question. For example, everyone gets free school lunch vs no one gets free school lunch. My question is about using the language of Researcher A when it does not seem to match the research objective. No medical researcher is sitting in their office thinking "Hmmmm... I wonder what would happen if every pregnant woman in the world smoked".
Comment: Wording of Statement 2 is more natural interoperation of ATE. Not sure if we can use everybody or nobody qualifiers: intuitively I think they would actually invalidate or rule out existence of control group. There is also personalised approaches,  Mueller & Pearl: [Personalized Decision Making -- A Conceptual Introduction](https://arxiv.org/abs/2208.09558)
Answer: Discussion of aggregate effects is common in population health studies
Most academic research on human behaviour aims to be useful to inform decision-making.  This can occur at different levels of influence, from informing the decisions of individuals in how they act in their own personal lives, to informing the decisions of policy-makers, regulators, professionals, etc.  A study on the effects of smoking on pregnancy could potentially inform the behaviour of pregnant mothers, but it could also potentially inform the behaviour of doctors, medical boards, public health bodies, cigarette-advertising regulators, corporate executives, politicians, etc.  The latter are typically concerned with the aggregate effects of a behaviour on a larger segment of society than a single individual.
One reason that researchers choose to frame their results in the way illustrated by Researcher A is that they wish to couch the issue in social terms and thereby appeal to people who can influence large-scale behaviour in their society, not just individual mothers who get to choose whether or not to smoke during pregnancy.  This type of framing feeds naturally into policy questions that are informed by consideration of the aggregated effects of behavioural change in a whole society or a large segment of society.  An individual mother might find the statement by Researcher B more useful, but a person working in population health research or policy is likely to find the statement by Researcher A more useful.
Now ask yourself, who is most likely to pay attention to an academic study on smoking and pregnancy (or derivative works that incorporate this information)?  An individual woman-on-the-street who smokes and falls pregnant, or a medical board?  An individual woman-on-the-street who smokes and falls pregnant, or a public health body that gives advice on cigarette regulation?  Etc.
From a mathematical perspective, the statement by Researcher B is giving the inferred causal effect on an individual and the statement by Researcher A is then extrapolating this to a "large population" via the law of large numbers.  The first is giving you a counterfactual statement based on smoking or not smoking for a single person and the latter is giving you a counterfactual statement for smoking or not smoking for a large group of people ("everybody vs nobody").  The latter is approximately correct so long as the population in question is large (as is the case for the population of Germany) and the individual effects can be considered to be either independent or close to independent.  (Here I set aside the question of adequacy of the model, discussed in the other answer here.)  Either of these methods of presentation capture an important aspect of the inferred causal effect, but one frames this as an individual effect and the other frames it as an aggregated effect in a larger society.  Both will have their uses, but the latter is typically more useful in communicating with certain influential classes of people who have the power to influence behavioural-change at a social level.
Comment: This is a fantastic answer (+1). For individual decision-making, other causal analyses can be used (e.g., estimating conditional ATEs).
Answer: I think the distinction you're not making is for model correctness. Posit a probability model for child's weight. In simplest terms, statement 1 and 2 are equivalent only if:
(1) $$ \text{Weight}_i = \vec{\alpha}_m \mathbf{X}_i + \beta_m \text{ Maternal Smoking} + \epsilon$$
Where $\mathbf{X}_i $ represents the baseline (non-smoking characteristics) risk factors for low birth weight including features such as maternal age, polybirth, maternal parity, maternal weight, etc. $\epsilon$ is a random error term. Here $\beta$ is the value of -200g with Maternal Smoking = 1 represents a mother who smokes. Subscript (m) denotes marginal effects.
A more complex model may have:
(2) $$ \text{Weight}_i = \vec{\alpha}_c\mathbf{X}_i + \beta_c \text{ Maternal Smoking} + \gamma_i \mathbf{X}_i \text{ Maternal Smoking} + \epsilon$$
Where the effect $\gamma_i \mathbf{X}_i \text{ Maternal Smoking}$ represents interactions between the smoking risk factors and baseline characteristics - high maternal weight and smoking may not have additive effects due to synergistic mechanisms like poor placental development, incidence of preeclampsia, etc. Subscript (c) denotes conditional effects.
In this case, if one fits model 1 when in fact model 2 is true, it is possible through the balance of covariates that $\beta_m$ is estimated to be 200, and further it is true that the average gestational birth weight will increase 200g. It is not true, however, that any given mother who discontinues smoking will gain exactly 200g in counterfactual birthweight. She may only gain 50g due to the predisposition of baseline traits and their interactions, whereas another woman may gain 400g of birthweight by evading emergent delivery (i.e. preeclampsia). The average individual treatment effect of smoking discontinuation is given by $-\beta_c \text{ Maternal Smoking} - \gamma_i \mathbf{X}_i \text{ Maternal Smoking}$.
$\beta_c = \beta_m$ only if the matrix of characteristics is centered.
This case is completely distinct from the notion that a mother, having all measured baseline characteristics held constant would, in a counterfactual reproduction, have a randomly distributed birthweight whose distribution is given by that of $\epsilon$.
Answer: This ended up longer than I originally intended and I am kind of strapped for time, so apologies if I misunderstood your questions or answered sloppily!
I might be misunderstanding how you are interpreting statements (1) and (2), but to me it seems like (1) expresses:
$$ E[Y^{T=1}] - E[Y^{T=0}] $$
While (2) expresses:
$$ E[Y^{T=1} - Y^{T=0}] $$
Both are valid ways of expressing the ATE. Notice that estimating the ATE is inherently about contrasting counterfactual worlds. Essentially, if we (hypothetically) had a copy of our universe, we could give our study population treatment $T=0$ in one world, treatment $T=1$ in the other world, and then contrast the mean outcome in each world to calculate a sample causal effect. The same identifiability conditions apply to both researcher A and researcher B and both have the issue that they would need a second world to observe all potential outcomes for study participants. This applies regardless of how potential outcomes are assigned in each world. You can communicate the definition of the ATE either way depending on preferences or your research question.
Let me jump to point (4): What you are outlining here is a violation of the stable unit treatment value assumption (usually abbreviated SUTVA and also known as no interference). Essentially, if your study participant's potential outcomes depend on the treatment assigned to other participants, potential outcomes do not immediately translate to a causal effect. If some participant $i=1$ smokes a lot around other participants, such that $i=2$ and $i=3$ have their baby's birthweight caused in part by $i=1$, an individual causal effect cannot easily be defined, which means that the ATE cannot easily be defined. You are asking a very good question here, but the unfortunate answer is that this would be a problem in any study, including in a (hypothetical) randomized trial addressing smoking and birth weight. The reason that the causal effects defined by researchers A and B appear to differ is therefore just an unfulfilled identifiability condition.
About statement (3): Yes, you cannot know that an estimated causal effect will exactly apply to you, but interpreting it this way would be a mistake in other settings too. The ATE defines an operation on sample means. I do not expect an ATE to apply to me the same way I (obviously) do not expect to be the same average height or age as people in Germany.
Let us say we perform a randomized controlled trial to assess whether or not smoking influences birth weight in pregnant people. To avoid SUTVA violations, we only sample participants living far away from each other, such that they are not exposed to each other's second-hand-smoke. We then randomly either force people to smoke ($T=1$) or to not smoke ($T=0$). If there is no loss to follow-up, $E[Y|T=1]-E[Y|T=0]$ estimates the sample ATE, defined as $ E[Y^{T=1}] - E[Y^{T=0}] $. A 95% confidence interval around this estimate will contain the true sample ATE in 95% of studies, had we repeated the experiment many times. The same interpretations apply (under the identifiability conditions) to observational studies in causal inference, if they intend to estimate the ATE. In every randomized controlled trial we therefore have the issue that we only have an estimate of a difference in sample means (observational studies have the additional burden of being unable to guarantee exchangeability). Whether estimated ATE's apply to individuals depends on expert knowledge and the generalizability/transportability of study results. Not smoking during pregnancy is unambiguously good. In medical settings, a new drug that shows superiority over previous treatments might not be superior for everyone, but we expect it to be an improvement over current treatments on average and can make individual treatment decisions informed by the literature.
Comment: You are the first person in this copy of the universe to agree with me that (4) seems like a SUTVA violation. And I still struggle with the fact that Researcher A gets to make nobody vs everybody statements, AND ALSO make a prediction for the woman in Berlin using whatever model was estimated. It seems to me they can have their cake (i.e., imagine worlds with 100% and 0% prevalence, where SUTVA will likely be violated) and eat it too (i.e., assume SUTVA in their research). I still don't get that part.


is this an appropriate way to close a page for updates?

Question: I wanted an easy block of code that i could just drop in my main files to shut certain sites down easily while keeping a way for me to still access them, I'm just worried if the way I am doing it is appropriate to keep access for myself while shutting out everyone else.
<?php
if (  isset($_GET['access']) && $_GET['access'] !== 'bypassed' || ( empty($_GET) )  ) {
    echo 'Sorry this area is under updates.
 We may be down for a week or 2
';
    die('We are sorry but we are going have to stop you there!
A link to Google.');
}
?>

Answer: That'll work, but it's more reliable to lock down the site so only your IP address can access it. If you have logins on your site, you can also lock it down so that only if the user is logged in as you (and any testers you have) then they can access.
Comment: But just for concerns sake, to get past it you would need to know the "access" and "bypassed" words in that order and there would be no other way around it?
Comment: That is true, but it leaves a fair amount to chance. It's better to have a proper login.
Comment: But would this be fit for purpose assuming there may be database connection issues or files could be partially damaged?
Comment: We were wrong! I just realized my security concerns... if any other get was sent i.e `url.php?woops=imin` would bypass the if. I added `|| $_GET['access'] == false` to fix it, but is that enough?
Answer: check ip address is a proper way use SERVER['REMOTE_ADDR'];
e.g
if (SERVER['REMOTE_ADDR'] != your ip ) {
    echo 'Sorry this area is under updates.
 We may be down for a week or 2
';
    die('We are sorry but we are going have to stop you there!
A link to Google.');

}

or you can create a array for valid ip address for allowed.
Comment: how would I check each array item? something like this? `$allowed = array("127.0.0.1","220.127.116.11"); if ( $_SERVER['REMOTE_ADDR'] !== $allowed ) { die(); }`?
Comment: create a array for ip address and check it with in_array()


Convergence of a Formal Series Involving the Mobius Function

Question: Let $\mu: \mathbb{N} \to \{0, \pm 1\}$ be the Mobius function.
It is not hard to show that, formally,
$$ \prod_{n \geq 1} (1 - x^n)^{-\mu(n) / n} = e^x $$
by taking logarithms and expanding using the power series of log. My question is, when does the left hand side actually converge to $e^x$?
Answer: Note first that if $|x|>1$ then you run into branch-cut issues for even $n$.  In the case of $|x| = 1$, the left-hand side is zero and the right-hand-side is not, so there's no convergence there.
We thus can restrict to the case of $|x| < 1$.  Taking $\log$, we're looking to see if the series $\sum_{n \geq 1} -\frac{\mu(n)}{n}\log(1 - x^n)$ converges.  In fact, it's not too hard to show that this converges absolutely for $|x| < 1$; to do this, note that $|\log(1 - y)| < 2 |y|$ for $|y|$ sufficiently small.  This then allows us to eventually bound the series above by a geometric series.  Since it converges absolutely, we're free to make the manipulations to show that $$\sum_{n\geq 1} -\frac{\mu(n)}{n}\log(1 - x^n) = x\,.$$


Set server wide ssl configuration

Question: Background  I have a simple server with only one site.  I want to force ssl.  I previously did this with a self signed certificate, but now I have got a letsencrypt cert.  I have used the auto set up, but when I access my site it uses the old certificate.
I think my question is similar to: default apache index.html shows up even though i have a sites-enabled file
In this answer: https://serverfault.com/a/690668/226403 one of the options is "If you want this as your default/only host, then don't even bother with VirtualHost tags, and apply your configuration at the server level".
Question How do I change the server wide configuration?  I think this server wide configuration is what is using the old certificate, but I cannot fathom how to change it?
Thanks!
(My set-up is a Ubuntu VM using apache)
Edit:  In /etc/apache2/ssl there are old .key and .pem files, if I move these everything breaks horribly and apache won't start!
Solution (For me at least).  Apparently you can set things up in sites-available and in conf-available.  Lets Encrypt automatically sets up sites-available for you, but not conf-available.  I performed a recursive search (using https://stackoverflow.com/questions/16956810/finding-all-files-containing-a-text-string-on-linux):
$ grep -rnw '/etc/apache2/' -e 'SSLCertificateFile'.  Found the incorrect files in conf-available and rebooted apache: sudo service apache2 reload.
Answer: If you have an existing, working https configuration in /etc/apache2/ssl you should only need to change the values for the relevant configuration files to point to the new files supplied by letsencrypt.
For example, example.com files would be stored in
/etc/letsencrypt/live/example.com/

The configuration settings you need to change are
SSLCertificateFile      /etc/letsencrypt/live/example.com/cert.pem
SSLCertificateKeyFile   /etc/letsencrypt/live/example.com/privkey.pem
SSLCertificateChainFile /etc/letsencrypt/live/example.com/fullchain.pem

save the file and restart apache2.

Set server wide ssl configuration


What's the difference between $|\nabla f|$ and $\nabla f$?

Question: what's the difference between $|\nabla f|$ and $\nabla f$ for example in :
$$\nabla\cdot{\nabla f\over|\nabla f|}$$
Comment: The vertical bars.
Comment: Thank you. I edited the question
Comment: You might want to have a look [here](http://en.wikipedia.org/wiki/Del), for the different uses of the _del_ operator.
Answer: $|\nabla f|$ is the magnitude of the $\nabla f$ vector. The expression $\frac{\nabla f}{|\nabla f|}$ is thus a unit vector.
$\nabla$ (gradient) acts on a scalar to give a vector, and $\nabla\cdot$ (divergence) acts on a vector to give a scalar.


What is the Fourier transform of $f(t)=1$ or simply a constant?

Question: Wolfram alpha gives the answer to be
$$F(\omega)=\sqrt{2\pi}\delta(\omega)$$
Does that mean that the function is valued $\sqrt{2\pi}$ at all points in the frequency domain? I think this is reasonable because such function i.e. $f(t)=1$ in the time domain would be sum of all the harmonics of a sinusoid and hence would contain all the frequencies. Maybe no, the function isn't varying at all and hence the frequency is $0$. But then the Fourier transform should have been $\delta(0)$ instead of $\delta(\omega)$.
Someone please shed some light on this!
Comment: There is something mentioned as "Dirac Comb" which represents the way I think DiracDelta(w) should be represented. The only difference is that it is defined at discrete points. Now this has made me even more confused ;___;
Comment: Here's another way of putting it. The Dirac delta distribution $\delta(x)$ has a spike whenever $x = 0$. That means that $\delta(\omega)$ has a spike only at the single point $\omega = 0$. On the other hand, $\delta(0)$ (if there were such a thing) would have a spike whenever $0 = 0$; it would have a spike *everywhere*! We want it to spike only at $\omega = 0$, so we use $\delta(\omega)$ instead of $\delta(0)$.
Comment: "Does that mean that the function is valued 2π−−√2π at all points in the frequency domain?" No, completely different.
Comment: Okay then what is the right answer?
Comment: If you think that dirac or delta function is discrete, an imaginary situation, then it will have a value on 0 and it will be zero for the other points. In fact, the continuous form of the delta function has no definite value at zero. I think you may want to have a look on delta function definition.
Comment: I agree on what you are saying but all I want to know is what would DiracDelta(w) look like?
Comment: It would look like an impulse. Consider a pulse, a step function, with a very short width. https://en.wikipedia.org/wiki/Dirac_delta_function
Comment: Rule of thumb: extension in time domain will translate to contraction in frequency domain and vice versa.
Comment: It is a function of frequency, w. So if you are plotting it against w, wouldn't it take all values of w?
Comment: Yes, but it will have a value on zero. For the rest of the points, it will be zero.
Comment: $\delta(w)$ is not, technically, a function. It can be thought of as a "distribution." Or as a kind of abstract limit of spike functions at $0$.
Comment: @ThomasAndrews I just wanted to make it more simple.
Comment: Wasn't replying to you, just the post. @Cardinal
Comment: I am not able to digest the fact that it will be 0 for every point except w=0. Then why isn't the Fourier transform of 1 simply DiracDelta(0). Why put a variable inside it if it can only be spiked at a single point?
Comment: Did you read the wikipedia page that I posted above?
Comment: "Why put a variable inside it if it can only be spiked at a single point?" Imagine the function $d(x) = 1$ if $x = 0$, $d(x) = 0$ otherwise. Then the function $d(x)$ will be 0 for every point except $x = 0$ (because that's how we defined it). But if we define the function $f(x) = d(0)$, this function is 1 *everywhere*. We have to put a variable inside it **because** we only want it to spike at a single point.
Answer: I think the clearest way to see this is by noting that we have (depending on your convention for the placement of $2 \pi$ in Fourier transforms) that
$$\mathcal{F}(\mathcal{F}(f(x))) = 2 \pi f(-x)$$
Taking the convention that
$$\tilde{f}(k) = \int_{-\infty}^\infty e^{-ikx} f(x) \; dx$$
so
$$f(x) = \frac{1}{2\pi} \int_{-\infty}^\infty e^{ikx} \tilde{f}(k) \; dk$$
We get
$$f(-x) = \frac{1}{2\pi} \int_{-\infty}^\infty e^{-ikx} \tilde{f}(k) \; dk = \frac{1}{2\pi} \mathcal{F(\tilde{f}(k))} = \frac{1}{2\pi}\mathcal{F}(\mathcal{F}(f(x)))$$
Note we have
$$\mathcal{F}(\delta(x)) = \int_{-\infty}^\infty e^{-ikx} \delta(x) \; dx = 1$$
So then
$$\mathcal{F}(1) = \mathcal{F}(\mathcal{F}(\delta(x))) = 2 \pi \delta(-x) = 2 \pi \delta(x)$$
For other constants, by linearity, we have
$$\mathcal{F}(c) = c \mathcal{F}(1) = 2 \pi c \delta(x)$$
Answer: You can derive the answer very easily with the general formula for the fourier series of a complex exponential:
$\mathcal F(e^{jw_0 t}) = 2\pi \delta(w-w_0)$
This identity is very intuitive: Since a complex exponential only has one frequency ($w_0$), its fourier transform only has one pulse at that frequency[1].
Set $w_0 = 0$ and you get:
$\mathcal F(e^{0}) = \mathcal F(1) = 2\pi \delta(w-0) = 2\pi \delta(w)$
[1] Here is a proof: https://staff.fnwi.uva.nl/r.vandenboomgaard/SignalProcessing/FrequencyDomain/CTNP.html#complex-exponential
Answer: I know that this has been answered, but it's worth noting that the confusion between factors of $2\pi$ and $\sqrt{2\pi}$ is likely to do with how you define the Fourier transform in the first place.
Wolfram Alpha seems to be taking the definition that involves placing a factor of $1/\sqrt{2\pi}$ on both the transform and the inverse transform (as is sometimes done in physics), rather than placing the factor $1/2\pi$ entirely on the inverse transform.
If you take the former approach, I believe you end up with the desired result, $\mathcal{F}(1)=\sqrt{2\pi}\delta(k)$, since (compare LtSten's answer) then $\hat{f}(k)$ will originally contain a factor of $1/\sqrt{2\pi}$ (i.e. $\mathcal{F}(\delta(x))=1/\sqrt{2\pi}$), meaning that $\mathcal{F}(1)=\sqrt{2\pi}\delta(x)$ is consistent with
$\mathcal{F}(\mathcal{F}(f(-x)))=2\pi f(x)$.
Answer: Just use the definition. $F(w) = \int_{-\infty}^\infty e^{-iwt}dt =\delta(w)$ by how the dirac delta is defined. This is normalized to 1at zero and 0 otherwise.
Comment: I don't think anyone defines $\delta(\omega) $ as the limit in the sense of (tempered) distributions $\lim_{T \to \infty}\frac1{2\pi} \int_{-T}^T e^{-i\omega  t}dt=\lim_{T \to \infty} \frac{\sin(\omega T)}{\pi \omega }$, which is a theorem equivalent to the Fourier inversion theorem for tempered distributions.
Comment: See https://math.stackexchange.com/questions/1343859/why-does-integrating-a-complex-exponential-give-the-delta-function
Comment: Yes, all of this can be made very rigorous using distribution theory. But most people who use the FT in the "real world" (whatever that actually is) don't bother with that much rigor. Statics has a good answer on the linked question which explains the reasoning behind this definition in a simple way.
Comment: This is a math forum ... people come here to understand what is the good rigorous explanation
Comment: Not necessarily. Many people come just wanting the answer to or a way to think about a math problem they don't understand, and a rigorous answer by current standards might just make things more obscure. Many of the most useful results in mathematics were not discovered or first presented in a "rigorous" way. In the current case, an actually rigorous answer would require the first few chapters of a distribution theory book, which is probably not what the asker was looking for.


TextView height is different depending on text when textSize it's the same. Why?

Question: I noticed, that a TextView with the same textSize can have a different height depending on the String it is displaying.
I disscovered it when paiting a simple TableLayout which has some TableRow items with some cells, each cell is a TextView.
Those cells doesn't have top margin, and they are being painted perfectly in Android 8.0 and upper devices, but in Android 7.0 and lower versions, some of the cells are adding a top margin between them, and this is because the height of the TextView is different. I can't understand how is that happening, it's very frustrating.
In this case, it's happening in the TextView called player and only when the name is too much long and it's using ellipsize to truncate it.
The code is very simple:
public void populateGoalscorersTable(ArrayList<Player> players){
    goalscorersTableLayout.removeAllViews();

    for (int i=0; i<players.size() && i<30; i++){
        TableRow row = new TableRow(this);
        row.setLayoutParams(goalscorersRowParams);

        TextView position = new TextView(this);
        position.setGravity(Gravity.CENTER);
        position.setLayoutParams(goalscorersPositionParams);
        position.setText(""+(i+1));
        position.setBackgroundResource(R.drawable.table_cell_background);
        position.setMinHeight((int) getResources().getDimension(R.dimen.cell_height));
        row.addView(position);

        TextView player = new TextView(this);
        player.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
        player.setLayoutParams(goalscorersPlayerParams);
        player.setText(players.get(i).getName());
        player.setBackgroundResource(R.drawable.table_cell_background);
        player.setMaxLines(1);
        player.setEllipsize(TextUtils.TruncateAt.END);
        player.setPadding((int) getResources().getDimension(R.dimen.spacing_small),0,(int) getResources().getDimension(R.dimen.spacing_small),0);
        player.setMinHeight((int) getResources().getDimension(R.dimen.cell_height));
        row.addView(player);

        TextView team = new TextView(this);
        team.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
        team.setLayoutParams(goalscorersTeamParams);
        team.setText(players.get(i).getTeam().getName());
        team.setBackgroundResource(R.drawable.table_cell_background);
        team.setMaxLines(1);
        team.setEllipsize(TextUtils.TruncateAt.END);
        team.setPadding((int) getResources().getDimension(R.dimen.spacing_small),0, (int) getResources().getDimension(R.dimen.spacing_small),0);
        team.setMinHeight((int) getResources().getDimension(R.dimen.cell_height));
        row.addView(team);

        TextView goals = new TextView(this);
        goals.setGravity(Gravity.CENTER);
        goals.setLayoutParams(goalscorersPositionParams);
        goals.setText(""+players.get(i).getLeagueGoals());
        goals.setBackgroundResource(R.drawable.table_cell_background);
        goals.setMinHeight((int) getResources().getDimension(R.dimen.cell_height));
        row.addView(goals);

        if (players.get(i).getTeam() == Manager.getInstance().getTeam()){
            player.setTextColor(getResources().getColor(R.color.player_team));
            player.setTypeface(null, Typeface.BOLD);

            team.setTextColor(getResources().getColor(R.color.player_team));
            team.setTypeface(null, Typeface.BOLD);
        }

        goalscorersTableLayout.addView(row);
    }
}

It's not the only way to make this errorneal top margin appearing (caused by a incorrect text height), I can see it for example when i have a row whith TextView cells with only one character and others with more than one character. The TextViews with more characters get's the margin. Also i can see this error happening when some TextViews are aligned to left and others centered. Very frustrating.
How can this be avoided?
Comment: have you tried https://stackoverflow.com/questions/4768738/android-textview-remove-spacing-and-padding-on-top-and-bottom
Comment: @Pawel checking that post I disscovered that if I put android:includeFontPadding to false and maxLines to 1, the problem is solved, but then, the text is not center vertically, is too much aligned to up, so android:includeFontPadding  seems to be necessary to get a centered text...
Answer: If the font is not monospaced, different text can have different sizes and needs of space for letters that venture down the line such as j or p or q.
Comment: In monospaced fonts each character has the same width. It doesn't affect the height.


SQL statement to return IP addresses that run 2 specific protocols

Question: I have a CSV file that is a little over a half million lines long by ten columns wide.
I need to take out common IP addresses that have two specific protocols (UDP and IGMP) and filter out all other IP addresses that only have one associated protocol. Here is an example of the data in my table:

So, this query would run and output:

It returns the IP/server that has BOTH UDP and IGMP and NOT the server that only has UDP. How can I do this? This needs to be run against 510,000+ lines with about 11,000 unique IPs.
Answer: One method is to use window functions:
select t.*
from (select t.*,
             sum(case when protocol = 'UDP' then 1 else 0 end) over (partition by sourceIP) as num_udp,
             sum(case when protocol = 'IGMP' then 1 else 0 end) over (partition by sourceIP) as num_igmp
      from table t
     ) t
where num_udp > 0 and num_igmp > 0;

EDIT:
If you only want exactly those protocols:
select t.*
from (select t.*,
             sum(case when protocol = 'UDP' then 1 else 0 end) over (partition by sourceIP) as num_udp,
             sum(case when protocol = 'IGMP' then 1 else 0 end) over (partition by sourceIP) as num_igmp,
             sum(case when protocol not in ('UDP', 'IGMP') then 1 else 0 end) over (partition by sourceIP) as num_other
      from table t
     ) t
where num_udp > 0 and num_igmp > 0 and num_other = 0;

If you just want to filter the protocols, then add where protocol in ('UDP', 'IGMP').
Comment: Thank you! This is almost exactly what I need, but my results still have some TCP  connections included. Any idea?
Let me clarify a bit too. This sheet has UDP, TCP, ICMP, IGMP, and PIM type protocols, we're trying to strip all those out and keep only addresses with communication on both UDP and IGMP inclusively.
Answer: select * from table
where SourceIP in (select DestIP from table where Protocol = 'IGMP')
This assumes the if a IGMP record exist then a UDP would also have to exist. (I't really a cheap answer)
Answer: I believe Gordon has already given a good answer using the window functions ... Another alternative could be ...
Select * from [tablename]
where SourceIP in
(

Select t2.SourceIP,count(SourceIP) from
    (
      Select SourceIP,Protocol,count(*) from [tablename] where Protocol in ('UDP','IGMP') group by SourceIP,Protocol
    ) as t2
group by SourceIP having count(SourceIP)=2

)

Note: I haven't run this query yet...


Usar tags HTML5 como seletores CSS3 é uma boa prática?

Question: Usar os nomes de tags HTML5 como a maioria dos seletores CSS é uma boa pratica? Seja por eu não ser criativo para dar nomes para ids ou classes, ou por querer deixar o código HTML mais limpo possível, deixando apenas a estrutura e semântica das tags.
Desde o meu aprendizado, sempre usei e abusei das tags pelo fato de sua semântica, por exemplo no lugar de um
 usar apenas um  e coisas desse tipo (, ,
,  e por ai vai...).
Em alguns fóruns e posts em sites de nome (Caelum), li algo que deu a entender que praticar isso deixa seu CSS menos versátil e com grande chances de sua manutenção ser precoce, pois está totalmente preso à estrutura HTML.
Tenho que sempre usar classes e ids, optar sempre por tags quando for possível ou se existe um meio termo?
Comment: "sites de nome" nesse caso não sei se é uma coisa boa, principalmente por que me parece que seu raciocínio está sendo sensato, e o do site no mínimo duvidoso (agora, pode ser que eles tenham dito outra coisa e sido entendido errado, só lendo o original mesmo). Obviamente que se você tem um `` é desnecessário criar um `#cabecalho` sem motivo. Vá pelo mais simples, curto e objetivo. Complique só se precisar. Quase sempre você vai conseguir deixar o site em ordem com poucas classes e IDs. Normalmente quem enche de identificação à toa em tudo quanto é tag não domina o assunto.
Comment: Já estranhei a primeira frase "Bons programadores aprendem boas práticas de código desde criancinhas.". Não vou falar bem ou mal do site aqui, por mera questão de ética, mas acho que o pessoal pega muita receita de bolo quando deveria explicar as verdadeiras razões de se fazer desse ou daquele jeito. E o mais importante: não tem solução que sirva pra todos os casos, por isso o importante é entender (assim como você fez, perguntando para saber mais) do que comprar idéias prontas de terceiros que a gente nem sabe ao certo quem são.
Comment: ah sim, aqui esta o link (http://blog.caelum.com.br/seu-codigo-css-pode-ser-mais-limpo-flexivel-e-reaproveitavel/) da uma lida ve o que acha, mas é esta a ideia, ser o mais simples, por isso fui sensato.
Answer: Objetivamente não tem que usar. O uso só se faz necessário quando ele tem um motivo técnico, tem um objetivo em por ele aí. Para entender melhor tem algumas leituras:

Qual é a finalidade das propriedades "id" e "name" de uma tag HTML?
Qual a prioridade do HTML? "id" ou "class"?
Quando devo usar o atributo class nos elementos HTML?
Boas práticas usando CSS
O que devo usar no CSS, id ou class?

O id é quando você precisa de uma estilização específica daquele elemento. E a classe é para um grupo qualquer de elementos, muitas vezes seria todos que usam uma determinada tag, aí não tem porque usar.
Então eu vou no meio termo, não use até que precise usar. Não tem como estilizar apenas um elemento pela tag, a não ser que tenha certeza que nunca terá outro elemento com a mesma tag, aí é risco. É muito comum que o estilo se aplique a todos os elementos daquela tag, pelo menos dentro daquela área do documento. Exemplo:

Brinquedos

No CSS só precisa:
#produtos h3 { ... }

E não há confusão com outros h3 do documento fora desta div.
Coloquei no GitHub para referência futura.
O Bacco já comentou o que eu acho, quanto mais simples, melhor.
O único caso que talvez usaria id ou class onde pode ser resolvido com a tag é quando vai fazer algo para terceiros estilizarem como quiserem. Mesmo assim pensaria muito antes de fazer e tentaria evitar. Ainda dá para deixar as pessoas estilizarem pelas tags, mas nem sempre será tão prático.
Não gosto da fonte que consultou isso, acho que lá há muita coisa errada ou com opiniões de complicam demais o desenvolvimento.
Existe um princípio importante que é o YAGNI. Não faça algo até precisar. Só tenha certeza que está fácil mudar se preciso.
Considero uma escolha correta. Há quem discorde.
Comment: legal cara, curti bastante sua resposta e entendi, não vou mais me atender muito a coisas que estas fontes falarem daqui em diante. Tambem penso como você, só usar quando for necessário !
Answer: Não. Não é uma boa prática. É um erro.
Não estilize por tags.
Você pode por exemplo precisar de 2  num mesmo documento, ai se estilizar:
header {

}

Vai ter que ficar "brigando" e sobrescrevendo coisas desnecessárias.
Estilize sempre por classe ou id, mas nunca pelo nome da tag.
Quando vc estiliza pelo nome da tag vc está fazendo um "css reset global", em que todas as tags daquele nome terão aquele estilo.
E você pode sim, ter mais de um , ,  numa mesma página, e cada um ter um posicionamento e estilo diferente do outro.
Comment: Se a pessoa tem esses problemas, nem deveria estar mexendo com CSS pra começo de conversa. Saber resolver ambiguidades e usar os seletores é necessidade básica de qualquer um que se meta a mexer com estilização, e as identificações só devem ser usadas quando realmente fazem sentido semântico. Vide a outra resposta. Claro que em sites caseiros, gastar 400 bytes a mais à toa com estilo redundante não faz diferença, mas em qualquer aplicação mais séria o uso somente no contexto certo prevalece.
Comment: Sinceramente, eu não repetiria certas tags em meu código, e pra estas foi que perguntei, eu sei disto, que se eu jogar apenas na tag repete e tal, mas a questão que coloquei é, até quando ids e classes são necessárias mesmo, e acho q ja entendi qual é o meio termo nisso
Comment: Até porque, caso eu tenha `Titulo` por exemplo, no meu css eu estilizaria: `span.boxTitulo h2{ font-size: 18px; }` e não interferiria em mais nenhum `` na pagina. Isso seria para evitar sair colocando id e class em tudo!
Comment: Sugiro a leitura de arquiteturas CSS, como o SMACSS
https://smacss.com/


How to test for differential privacy on multiple choice data?

Question: I apologize I am new to statistics so I do not know all terms and concepts.
My current algorithm for adding noise to multiple-choice favorite color data is this:
<code>x = rand(1)
if x > .5:
    return original_color
if x < .5:
    y = rand(1)
    if y > .67:
        return "blue"
    else if y > .33:
        return "red"
    else:
        return "green"
</code>
From this I get a "private" dataset and will calculate how many people's favorite color is red.
My question is: how can I calculate whether this is differentially private? I know I need to calculate the chance that this algorithm yields any given number of reds, and the chance that a dataset with one changed row would have the same number of reds. I keep getting stuck.
Assume the original dataset has 100 rows: 50 red, 30 blue, 20 green. Then for each row there is a
.5 (chance of red) x .5(chance noise is added) x .66 (chance noise added is not red) probability that a red will be subtracted and a
.5 (chance of not red) x .5(chance noise is added) x .33 (chance noise added is red) probability that a red will be added.
How do I synthesize this information to calculate whether the algorithm is differentially private? Can anyone point me in the right direction? Furthermore, is my algorithm completely naive? Thank you!
Answer: You're adding noise to each data point, so you're doing local differential privacy. This means you need to consider, for each data point $i$, each output color $c$ and each pairs of colors $c_1$, $c_2$ what is the maximum ratio of:
$$
\frac{P(\text{noised_color}(i)=c|\text{original_color}(i)=c_1)}{P(\text{noised_color}(i)=c|\text{original_color}(i)=c_2)}
$$
In your case, the numerator is maximized when $c=c_1$ (it's $\frac{1}{2}+\frac{1}{2}\times\frac{1}{3}=\frac{2}{3}$ — the probability of returning the true answer directly plus the probability of returning the correct answer at random), and minimal when $c\neq c_1$ (it's $\frac{1}{2}\times\frac{1}{3}=\frac{1}{6}$ — the probability of returning $c$ at random). The maximal value of the ratio is thus $4=e^{2\ln(2)}$, so your scheme is $\varepsilon$-differentially private with $\varepsilon=2\ln(2)$.


why no-blocking node reduce I/O total time?

Question: There was a node tutorial point out:

node is a no-blocking I/O system. if there were a task consuming time m, another task consumeing time n(m'<'n).then,the total consuming time wound be 'm+n' in a blocking I/O system.but it will be n in node.

However, since javascript is a single-thread language. I think it wouldn't reduce the time even the so-call event-loop there for the tasks, right?
Under the hood, is it all because node is using C/C++ multi-threads to accomplish this.

all right .My main confusion is I mess I/O consuming-time was included in javascript calculation .
Comment: So your question is if documentation is correct?
Comment: Under the hood I/O tasks don't run inside node. They run in other processes or even other servers in other countries/continents
Comment: @John Ironically, this makes node behave in ways that is sometimes counter-intuitive. If you want to cache something large like a generated html page or an image node is much faster if you cache them to file than to RAM. This is because variable/object/array access is synchronous so reading a 1MB value from a variable will pause the interpreter while streaming a 1MB file from disk will not. Thus you can easily stream multiple 1MB files from disk in parallel but you will slow down trying to write a 1MB variable to a socket
Comment: nope,I ask this cause I don't understand it as a total beginner
Comment: @slebetman yeah.I understand a little bit, the I/O time is consumed outside program developed by node.the blocking system would just wait for the return.node would step over to the next
Comment: can I think it as this: cache something to RAM is totally  by javascript to calculate . cache large files is hand it over to OS, or not OS,is C/C++ code to parse file,that's why it's  faster?
Answer: Node, basically won't play the major role in reducing the time of executing the single task but it is like a parallel processing. That means it would not wait for the other task to complete and multiple tasks can be executed at time. The concept is as you known about the multiple threads executing at the same time to utilise maximum cpu and memory ( time in milli seconds ) so we will feel that all executed concurrently
Answer: Yes. Javascript is a single threaded but with a non blocking IO implementation. The above line means something like this think you have to get a HTTP response from a server, which is a IO using the network interface of your computer, So while the HTTP response comes the thread is free (no calculations happens on your CPU, by means your CPU thread is free), so it can continue doing other tasks maybe rendering your page.
The only way that a Javascript thread is hanged is a higher execution rate. Think you are doing some kind of massive calculations. In this case yeah, your process is blocked. But this is not a IO (Input or Output).
So you are confused between IO non blocking and CPU thread blocking


Knex NodeJS and inserting into the database

Question: I am new to nodejs and was trying to set up an API server, here is my first attempt. I wanted to use mysql instead of mongo db.
My problem is that 'knex('user').insert({email: req.body.email});' doesn't seem to want to save to the database.
var dbConfig = {
  client: 'mysql',
  connection: {
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'db_nodeapi'
  }
};
var express = require('express');                       // call express
var bodyParser = require('body-parser');                // call body-parser
var knex = require('knex')(dbConfig);                   // set up database connection
var app = express();                                    // define our app using express
app.use(bodyParser.urlencoded({ extended: true }));     // configure app to use bodyParser()
app.use(bodyParser.json());                             // this will let us get the data from a POST
var router     = express.Router();                      // get an instance of the express Router
router.use(function(req, res, next) {                   // middle ware for authentication
    console.log(' -Logging- ');
    next();                                             // continue to next route without stopping
});
router.get('/', function(req, res) {                    // listen for a post on root
    res.json({ message: ' -Success- ' });
});
router.route('/user')                                   // set up user route
    .post(function(req, res) {                          // listen for a post on user
        console.log(' -Post -');                        // report a post
        knex('user').insert({email: req.body.email});   // insert user into user table
        res.json({ success: true, message: 'ok' });     // respond back to request
    });
app.use('/api', router);                                // register routes beginning with /api
var port = process.env.PORT || 8080;                    // set server port number
app.listen(port);                                       // setup listener
console.log('Magic happens on port ' + port);           // report port number chosen

Problem is I can't get knex to add to the database!
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL,
  `email` varchar(255) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

Here is the database
Comment: 1) are you sure an email is getting posted? What happens if you change the line console.log(' -Post -') to console.log(' - Post - ' + req.body.email) ?
2) Are you sure that's the syntax for insert? It doesn't look like the current documentation, which uses something more like knex.insert(info).into('user')
Comment: req.body.email is set to the posted value of email, I have checked. body-parser takes care of this I am led to believe.
Comment: Ok, so far so good. Now what about knex? Are you sure that query syntax works? For example, if you remove the code from the route and add a quick line after you require knex (something like): knex('user').insert({email:'email@example.com'}); what happens? And then what happens if you add a second line like knex.insert({email: 'email@example.com}).into('user') does that work?
Comment: knex.insert({email: req.body.email}).into('user'); tried nothing, not even an error. Also tried knex('user').insert({email:'firstname.lastname@example.com'}); after var knex = ... line. nothing. Tried knex.insert({email: 'firstname.lastname@example.com}).into('user') ... nothing. Tried both ... nothing.
Comment: Hmm. It could be that knex is not connecting to the database at all, or it could be that it's failing silently. id is specified as not null - is it tied to a sequence or an auto-increment or something? Or is it possible thats a point of failure? BTW - you can add 'debug: true, ' to your dbConfig to have the SQL syntax and parameter bindings output to the console. That would be helpful as well.
Comment: I removed the id completely, thought that would help ... debug: true will try. Code too long to post.
Comment: Tried setting up a user account for the table just in case the password can't be blank. - nothing.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/72520/discussion-between-stephen-brown-and-gojirademonstah).
Answer: The problem in your code is that you are missing the ".then" statement, which causes the actual execution of the code.
   knex('user').insert({email: req.body.email})
      .then( function (result) {
          res.json({ success: true, message: 'ok' });     // respond back to request
       })

That should work. Since knex.js's insert function is a promise, you need to call .then() to actually call it.
Comment: Yes. Knex needs a .then() for it to execute.
Comment: Does knex use some kind of lazy promises? The insert *should* be executed regardless of whether or not the result is handled (assuming `insert` returns a regular promise).
Comment: doesn't work with await either.. they should instead do something like knex(...).insert(...).execute() which retrieves and executes a promise, thus working with await AND one can add .then if wanted
Comment: what if I want to add more than just and email, or multiple objects?
Comment: I'm no longer using knex, but I believe they have a mass insert function that you can use. You can check on their documention on batch insert: https://knexjs.org/#Utility-BatchInsert
Comment: Or an `await` will get it to run
Answer: Someone has already given a solution. I am here to talk about why adding a then statement can solve this problem.
In fact, then, catch statement are both ok. Please refer to the knex documentation(http://knexjs.org/#Interfaces-then), which mentions:

Coerces the current query builder chain into a promise state.

So select, update, insert, etc. are just the query statement builder, you have to use then or catch to convert it to promise state.
Examples are as follows:
knex('user').insert({email: req.body.email}) //not working
knex('user').insert({email: req.body.email}).then(()=>{}) //working
knex('user').insert({email: req.body.email}).catch(()=>{}) //working

.then(()=>{
    knex('user').insert({email: req.body.email}) //not working
    knex('user').insert({email: req.body.email}).then(()=>{}) //working
    knex('user').insert({email: req.body.email}).catch(()=>{}) //working
    return knex('user').insert({email: req.body.email}) //working
})

Answer: Solved try this I think there should be some after hook in knex where we can do this automatically but till then this should works.
 knex('users')
      .insert(data)
      .then(async () => {
        const result = await knex.raw('select LAST_INSERT_ID() as id');
        const id = result[0][0].id;
        const user = await knex.from('users').where('id', id);
        res.json({ success: true, message: 'ok', user: user[0] });
      });

Answer: Had similar issue once, try this:
//...
router.route('/user').post(function(req, res) {
  knex('user').insert({email: req.body.email}).then(function(ret){
    res.json({ success: true, message: 'ok'/*,ret:ret*/});
  });
});
//...

Answer: So I was seen the above solutions all are good if you want to add more than one field without mentioning each field you can go with the below syntax:
knex('students').insert(req.body).then((newUser) => {
  res.json({newUser});
}).catch((e)=>console.log(e));

So here your input tag names should be equivalent to the database table field names


Mudar background a partir do horario (Problema)

Question: Preciso mudar o background a partir de um certo horário, porém o site já estava meio feito então o carregamento do background está sendo feito no jquery com essa função
<code>    $(".intro").backstretch("img/" + images[Math.floor(Math.random() *
    images.length)] ,   { centeredX:true, centeredY:true});
</code>
ai basicamente tentei fazer isso
<code>   $(window).on('load', function () {

    var today = new Date()
    var curHr = today.getHours()

    /*HORARIO Menor que 12 horas*/
    if (curHr < 12) {
    var images = ['london.png'];

$(".intro").backstretch("img/" + images[Math.floor(Math.random() *
images.length)] ,   { centeredX:true, centeredY:true});
}
else{
var images = ['outra imagem'];

$(".intro").backstretch("img/" + images[Math.floor(Math.random() *
images.length)] ,    { centeredX:true, centeredY:true});
}
 }
</code>
Alguém sabe porque não funciona? ah e se precisarem da classe .intro está aqui
<code> .intro {
  display: table;
  width: 100%;
  color: #fff;
  text-shadow: 0 1px 3px rgba(0,0,0,.2);
  height: 100%;
  background: #000 url(../img/5.jpg)  no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
   background-size: cover;
   }
</code>
Se alguém souber o porque não funciona agradeço, obs: se for para fazer por css
chamando uma classe e passando o horario chamar outra eu consigo, mas quero desse modo, porquê já está estilizado, obs não entra dentro dessa função.
Comment: Remove o background do css..
Comment: removi, mas nada...
Comment: Creio que seria somente uma imagem por período certo? Se sim não precisa do random, é só definir data imagem por período ( em alguma var ) e usar a função já criada:

$(".intro").backstretch("img/"+imagem_selecionada,  { centeredX:true, centeredY:true});
Answer: Consegui galera, foi erro meu desculpe, ja tinha um load la em cima então acho que estava em conflito, perdão mesmo obrigado


RDP Over Mobile Satellite Internet

Question: I am planning a vacation to a destination that will not allow me to have cell or Internet service. I play a role in my organization such that in an emergency situation, my availability is of some importance. As such, I'm considering renting a BGAN satellite for the week. Like this one (http://allroadsat.com/inmarsat-satellite-internet)
Has anybody out there done this? I'm looking for a little help figuring out bandwidth requirements. I'd like to plan for 4 hours of use with an RDP connection over an IPSEC tunnel.
I'm thinking 50MB might be cutting it a little close. What do you guys think?
Answer: If my math is right, 50MB of usage over a 4 hour period works out to about 27.8Kbps of usage, which is in the general range for an RDP session (albeit a little on the low side in my opinion). My suggestion would be to find out what the overage penalties\fees are first, then if you have to use it make sure to set the RDP client Experience settings to Modem (56Kbps) and make sure to disable local resource redirection (printers, drives, clipboard, etc.) unless you absolutley need to have them enabled. I would also recommend installing a bandwidth meter on your laptop (I'm assuming you're taking a laptop) and launch it whenever you connect to the internet to keep tabs on your usage.
Answer: As joeqwerty says, using a dial-up modem will probably be a lot les painful - and you can try it out today.
I've no experience with the service you are looking at just now, but I've known several people who have been very disappointed with satellite internet access due to:

very high latency (which is a big issue for RDP)
only allowed connections to DNS, HTTP, HTTPs, SMTP and POP

If you can, try before you buy - or at least specify your requirements as a condition of the order.
There are alternatives to RDP, tightVNC badwidth usage tends to be about the same IME, despite the different approach. OTOH Nomachine NX is a lot better on low bandwidth links - and has significantly better security. But there's no way of solving latency with software / protocols.

RDP Over Mobile Satellite Internet


Queuing Theory M/M/1 utilization factor

Question: I am learning the basics for queuing theory for a M/M/1 queue. One thing I do not understand is to do with utilization factor $ρ$.
Assuming that:
$λ$ = arrival rate, exponentially distributed
$μ$ = service rate, exponentially distributed
$ρ$ = utilization factor
Therefore $ρ = \dfrac{λ}{μ} < 1$.
$ρ$ needs to be less than one for it to work, but why? What if a have a problem where $λ$ is greater than $μ$ therefore $ρ$ > 1. For example $λ = 4$ and $μ = 2$ then $p = 2$. What to do then?
Answer: The problem is that there is no equilibrium in such a situation.  Customers are going into the system faster (e.g., $\lambda = 4$) than they can be served (e.g., $\mu = 2$), so the queue increases without bound.  All of the usual formulas that go with the M/M/1 system (average queue length, average waiting time, etc.) apply only to systems in equilibrium.

Queuing Theory M/M/1 utilization factor


How do I solve this limit $\lim_{x\to \infty}\left(x-\sqrt{\frac{4x^3+3x^2}{4x-3}}\right)$?

Question: I need to find the limit of $$\lim_{x\to \infty}\left(x-\sqrt{\frac{4x^3+3x^2}{4x-3}}\right)$$
I did rooting like this:
$$\frac{\left(x-\sqrt{\frac{4x^3+3x^2}{4x-3}}\right)*\left(x+\sqrt{\frac{4x^3+3x^2}{4x-3}}\right)}{x+\sqrt{\frac{4x^3+3x^2}{4x-3}}} = \frac{x^2-\frac{4x^3+3x^2}{4x-3}}{x+\sqrt{\frac{4x^3+3x^2}{4x-3}}}$$
but I got stuck. How can I continue from here? Thanks in advance.
Comment: Put the numerator over a common denominator
Answer: Putting the terms in the numerator over the common denominator one obtains:
$$\begin{align}\frac{x^2-\frac{4x^3+3x^2}{4x-3}}{x+\sqrt{\frac{4x^3+3x^2}{4x-3}}}&=\frac{-6x^2}{(4x-3)x\left(1+\sqrt{\frac{4x+3}{4x-3}}\right)}\\
&=\frac{-6}{(4-\frac3{x})\left(1+\sqrt{\frac{4x+3}{4x-3}}\right)}.
\end{align}$$
Can you get it from here?
Comment: Not really. I can see that i can simplify with x. But after that if I replace x with infinity i get critical limits. And if I divide by x, I get 0 as a denominator.
Comment: @WAT Can you take it now after I divided both numerator and denominator by $x^2$?
Comment: Sorry but still no. I don't see how could I get to somewhere wher the limit wouldn't be $\infty$ or 0. Do I multiply it with the conjugate? $$\frac{1-\sqrt{\frac{4x+3}{4x-3}}}{1-\sqrt{\frac{4x+3}{4x-3}}}$$
Comment: @WAT What happens if your substitute $x=\infty$ into the denominator? For me it turns into $8$.
Comment: Oh, yes, I see now. Thank you.


If $\tan x=\sin x/\cos x$ then what is $\tan 3x$ equal to?

Question: Would $\tan 3x$ be equal to $\sin 3x/\cos x$? Or perhaps $\sin 3x/\cos 3x$?
Regards, Tom
Comment: It is the latter one.
Comment: @ThomasWinkworth Yes.
Answer: If some function is written as $f(x)$, then the value of that function at $3x$, written as $f(3x)$, is obtained by replacing every appearance of $x$ with $3x$. To make it easier, perhaps write your function like
$$\tan(y) = \frac{\sin y}{\cos y}$$
Now, set $y=3x$, and you get:
$$\tan(3x) = \frac{\sin(3x)}{\cos(3x)}$$
Comment: I was writing an answer with the same idea.  This is better. +1
Answer: $\tan(X) = \sin(X)/\cos(X)$ now let $X = 3x$ and we obtain $\tan(3x) = \sin(3x)/\cos(3x)$
Comment: When writing in LaTeX, it's better to write `$\tan$` (resulting in $\tan$ and not `$tan$` (resulting in $tan$). I edited your answer now, but in future, I advise you to use the versions with the backslashes.


Is recursion a loop

Question: "1. The program will calculate the values using repetitive execution (loops)."
Recursion is repetitive execution but, i do not think it's a loop, do you think if I used recursion it would follow the guideline above?
Comment: Thanks david, wasn't exactly sure where to put this.
Comment: The term "loop" can be used abstractly ( a cycle in the execution path of your program) or concretely (a syntactic construct to guide such a cycle). The question implies the latter usage.
Answer: No. In fact, it looks like the assignment is specifically asking for the "opposite" of recursion, iteration.
Answer: Loops are fundamentally about iteration, which is different to recursion. The main difference is that an iteration uses a constant amount of space, whereas recursion uses more space the deeper the recursion goes. For example, here are iterative and recursive procedures to compute the sum of the numbers from 1 to n
def sum_iter(n):
  x = 0
  for i in range(1,n+1):
    x += i
  return x

def sum_recursive(n):
  if n == 0:
    return 0
  else:
    return n + sum_recursive(n-1)

If you run these with a very large argument, you will run out of stack space (a "stack overflow") on the recursive version, but the iterative version will work fine.
There is a special kind of recursion called tail recursion, which is where the function doesn't have to do anything with the value from a recursive call except pass it to the caller. In this case you don't need to keep track of the stack - you can just jump straight to the top. This is called tail call optimization. A tail recursive function to calculate the sum of the integers 1 to n looks like
def sum_tailrec(n):
  def helper(s,i):
    if i == 0:
      return s
    else:
      return helper(s+i, i-1)
  return helper(0, n)

In this case people often refer to the function helper as an  iterative recursion, because (with tail call optimization) it is only using a constant amount of space.
This is all a bit moot, because Python doesn't have tail call optimization, but some languages do.

Is recursion a loop


Dialog not centered on window height, but on document height instead

Question: Using primefaces 6.2 now, I experienced this issue already when using 6.0 so I thought it was time to investigate. When the content height of the page (the document) is larger then the window (the viewport of the browser), then you can clearly see that instead of centering on the window, the dialog is centered on the document. When having very large pages, the dialog is still centered on the page level, and not on the window level. It means that if the page is at least twice as high as the window, the dialog falls of the window. To test this i made a sample page:

<h:head>

</h:head>

<h:body>

    <h:form id="show">

    </h:form>

        <h:form id="refresh">

        </h:form>

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

</h:body>

In this sample page, it will trigger the dialog. When using on most laptops, it will show dialog nicely in the center because the screen resolution is big enough. Now, resize the browser screen untill a scrollbar appears. It means some 'test' lines should fall off the window. Now trigger again the dialog. In my case it is not centered anymore. Resizing the browsers has also no effect...
The odd thing is, when testing this on the Primefaces showcase, and resizing the screen, the dialog is always centered! Conclusion is there is something different, but I only use base configuration for primefaces. I noticed though that everything is wrapped in layout container on the primefaces site. Also tried to wrap everything in a layout container, but it doesn't help.
Anybody has an idea why this happens. Is this a bug I should report? Is this as designed, and the dialog will ALWAYS center on the document (and for a strange reason the showcase doesn't follow this logic...).
Comment: I would try and create a reprodcible test case using the small PrimeFaces Test project and submit it as a defect if you can reproduce it. The Test project is here: https://github.com/primefaces/primefaces-test
Answer: I found the solution: a doctype declaration needs to be added: <!DOCTYPE html>.
Although the declaration is not mandatory with XHTML5 documents; for using primefaces it is mandatory in fact. If not, some components may have unexpected behavior, like this dialog.
More info: https://github.com/primefaces/primefaces/issues/4115


Outlook 2010 OWA cannot delete emails

Question: I have an Exchange Server 2010 setup Version: 14.03.0382.000.
Through the outlook web access OWA the send/receive email works but all move mail operations and deletions fail with the following error:
the action you tried to perform couldn't be completed because there's a configuration problem
https://community.spiceworks.com/topic/1446907-exchange-2010-owa-error-when-trying-to-delete-items
Mentioned solutions don't help with the problem.
Answer: Open IIS manager, right-click Default Web Site and select Edit Bindings, then check if the correct certificate is assigned to the HTTPS service on port 443.
Also check the EWS VD settings: Get-WebServicesVirtualDirectory | fl

Outlook 2010 OWA cannot delete emails


In this problem, A(x) and B(x) are two predicates over the same domain.

Question: For each of the statements below, state whether it is true or false. If true, explain why each of its directions → and ← is true. If false state which direction is false and give a counterexample.
(a) ∀x (A(x) ∨ B(x)) ↔ ∀xA(x) ∨ ∀xB(x)
(b) ∀x (A(x) ∧ B(x)) ↔ ∀xA(x) ∧ ∀xB(x)
(c) ∃x (A(x) ∨ B(x)) ↔ ∃xA(x) ∨ ∃xB(x)
(d) ∃x (A(x) ∧ B(x)) ↔ ∃xA(x) ∧ ∃xB(x)
I am stuck on this question. From reasoning it out via sentences, I believe that the correct (or true) arrows for each of the statements are:
(a) Left
(b) Left
(c) Right
(d) Both
How should I be approaching this problem?
Answer: For b and c both directions hold true ...
b: if everything has both properties $A$ and $B$, then obviously everything has property $A$, and everything has property $B$, ... and vice versa.
c: if there is something that has either property $A$ or $B$, then if that thing has property $A$, then there is something with property $A$, and if that thing has property $B$, then there is something with property $B$. So, either there is something with property $A$, or there is something with property $B$
Going the other way around: Assume that either there is something with property $A$, or something with property $B$. Well, in both cases there would then be something woth either property $A$ or $B$
For a, you are right: only the left direction holds: assume that either everything has property $A$, or everything has property $B$. In both cases, everything has either property $A$ or property $B$. For a counterexample against going right: take as the domain all integers, and let $A(x)$ be '$x$ is even', and let $B(x)$ be '$x$ is odd'
For d, going to the right holds: if there is something with both properties $A$ and $B$, then gclearly there is something (namely that very thing) with property $A$, and there is something (again, that very thing) that has property $B$. For a counterexample going left, see above counterexample.
Comment: Thanks. For clarification on (c) you said that both directions hold true. However, and please correct me if I am wrong, the statement says, for example, "there is a student that passed class A, or class B", which does not sound the same as "there is a student that passed class A, and there is a student that passed class B". Can you clarify this for me please?
Comment: @Maxxie Right .. there is a disjunction on both sides, so you dealing with "or", rather than "and" .... so what are you trying to say?
Answer:
How should I be approaching this problem?

You should have a reason for the answers you have given.  You just need to express your rational.
Eg: you have stated you believe $∀x\,(A(x) ∨ B(x)) ↔ ∀x\,A(x) ∨ ∀x\,B(x)$ is only valid for a Left conditional ($\gets$).   However, why do you think this is so?

If all are one or all are the other, then anything is one or the other.
However, it is possible to have all be one or the other without everything being one, or everything being the other.

The first can be demonstrated with a simple proof by cases, but you were not asked for this.
The second can be justified with a counter example. An interpretation where the conditional is not true.  vis:

 Consider the domain of natural numbers with $A$ interpreted as "is odd" and $B$ as "is even".

 Well every natural number is either odd or even, but not all natural numbers are odd and not all natural numbers are even.

 So $\forall x~(A(x)\vee B(x)$ does not entail that $\forall x~A(x)\vee\forall x~B(x)$.


How to Invoke ICorDebug

Question: In "MDbg Sample.zip" projects, invoke the function from COM Module as:
[ComImport, Guid("3D6F5F61-7538-11D3-8D5B-00104B35E7EF"), InterfaceType((short) 1)] public interface ICorDebug { ... } The question is where to find the Guid("3D6F5F61-7538-11D3-8D5B-00104B35E7EF"), i can not find it in the regedit, but how to connect the ICoreDebug interface with the COM module?
Answer: It's not in the registry. That guid is the IID, ICorDebug doesn't support remote access so there is no reason to register a stub/proxy against the interface.
How you get an instance depends on what versions of the runtime are installed, but these days "everyone" has CLRv4 installed, so you access via the ICLRMetaHost.

Use CLRCreateInstance to get an implementation of ICLRMetaHost
Use ICLRMetaHost to find the ICLRRuntimeInfo for the desired version of the runtime.
Use ICLRRuntimeInfo.GetInterface to request an implementation of ICorDebug using CLSID_CLRDebuggingLegacy.
Comment: Hello @Brian Reichle, I have programed according to your prompts: hr = pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_PPV_ARGS(&pRuntimeHost));  hr = pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (LPVOID*)&pRuntimeHost);   But when I debug the code ,there is notification as:There is no type information available in the symbol file for . Do you know how to solve this problem? Thanks a lot.
Comment: I'm not really sure what you mean, but `CLSID_CLRRuntimeHost` looks out of place. (ICLRRuntimeHost is what you use to host a runtime in your process, it's not normally used to create an ICorDebug)
Comment: Thank you. Actually what  I really want  to do  is  to find  a way to read out  the detail  information such  as Guid etc from CLR. If I use new version CLR, I hope  I can invoke such  as  Icoredug by myself.

How to Invoke ICorDebug


Comparing all column names of multiple Pandas Dataframes

Question: I am looking for an easier way to compare multiple column names with a similar output to the code below or a way to make this function more concise. I get the errors "IndexError: list index out of range" or "function takes 0 positional arguments but 1 was given" every time I try to use *args or **Kwargs to simplify the function. Any advice is greatly appreciated.
'''
application_df = pd.read_csv("application_train.csv")
bureau_df = pd.read_csv("bureau.csv")
bureau_balance_df = pd.read_csv("bureau_balance.csv")
previous_application_df = pd.read_csv("previous_application.csv")
POS_CASH_balance_df = pd.read_csv("POS_CASH_balance.csv")
installments_payments_df = pd.read_csv("installments_payments.csv")
credit_card_balance_df = pd.read_csv("credit_card_balance.csv")
sample__submission_df = pd.read_csv("sample_submission.csv")

def column_compare(df1, df2, df3, df4, df5, df6, df7, df8):
    alist = []
    blist = []
    clist = []
    dlist = []
    elist = []
    flist = []
    glist = []
    hlist = []

    name1 =[x for x in globals() if globals()[x] is df1][0]
    for a in df1:
        alist.append(a)

    name2 =[x for x in globals() if globals()[x] is df2][0]
    for b in df2:
        blist.append(b)

    name3 =[x for x in globals() if globals()[x] is df3][0]
    for c in df3:
        clist.append(c)

    name4 =[x for x in globals() if globals()[x] is df4][0]
    for d in df4:
        dlist.append(d)

    name5 =[x for x in globals() if globals()[x] is df5][0]
    for e in df5:
        elist.append(e)

    name6 =[x for x in globals() if globals()[x] is df6][0]
    for f in df6:
        flist.append(f)

    name7 =[x for x in globals() if globals()[x] is df7][0]
    for g in df7:
        glist.append(g)

    name8 =[x for x in globals() if globals()[x] is df8][0]
    for h in df8:
        hlist.append(h)

    dfs = {name1: alist, name2: blist, name3: clist, name4: dlist, name5: elist, name6: flist, name7: glist, name8: hlist}
    df = pd.DataFrame.from_dict(dfs, orient='index')
    df=df.transpose().replace(np.nan,'')
    return df

pd.set_option("max_rows", None)
column_names = column_compare(application_df, bureau_df, bureau_balance_df, previous_application_df, POS_CASH_balance_df, installments_payments_df, credit_card_balance_df, sample__submission_df)
column_names

'''
Answer: Not sure if this is what you are interested in, but column names can be access through df.columns, so:
import pandas as pd

df1 = pd.DataFrame(columns=list('abc'))
df2 = pd.DataFrame(columns=list('abefg'))
df3 = pd.DataFrame(columns=list('bfkm'))

cols1 = pd.DataFrame(index=df1.columns).assign(df1=1).T
cols2 = pd.DataFrame(index=df2.columns).assign(df2=1).T
cols3 = pd.DataFrame(index=df3.columns).assign(df3=1).T

df_cols_compare = pd.concat([cols1, cols2, cols3]).fillna(0).astype('int')

#      a  b  c  e  f  g  k  m
# df1  1  1  1  0  0  0  0  0
# df2  1  1  0  1  1  1  0  0
# df3  0  1  0  0  1  0  1  1


Java Regex Find Characters In Any String

Question: I'm trying to program a Minecraft Bukkit plugin using Java that will find when an IP is placed in the chat, so I'm using regex for it. What I need is regex to find anywhere in the string, a character followed by a period followed by another character, such as 127.0.0.1 being valid, but it also needs to be able to find it with any characters surrounding it such as This IP: 127.0.0.1 is your localhost IP. This is my current code:
Pattern p = Pattern.compile("[a-z1-9]" + "." + "[a-z1-9]");
Matcher matcher = p.matcher(message);
if(matcher.matches()){
    player.sendMessage(plugin.prefix + "§7You cannot advertise an IP address!");
    event.setCancelled(true);
}

This code will only search for something like 127.0 and only that, but as I said above I need it to find any amount of [letter/number].[letter/number] in any string, if that made sense.
Comment: You should read some [regex tutorial](http://www.regular-expressions.info/tutorial.html) or at least try to search [regex for IP](http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address) before asking question. `.` is special character, it means "any character except new line mark" and `[a-z1-9]` would match *one* character in range `a-z` or `1-9` so you would need to add quantifiers. Also if you want to match IPv4 then what `a-z` is doing in your regex?
Comment: @Pshemo Read my comment for plsgogame's answer.
Comment: If you want to also find hostname like `jointhis.server.com` then you definitely should read answer in question I linked in my previous comment.
Comment: Possible dupplicate: [regular-expression-to-match-hostname-or-ip-address](http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address).
Answer: Read please this: link
PADDRESS_PATTERN =
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])";

Comment: @DonkeyTeeth2013 what you are describing is not an IP address, but a hostname. The regex to find hostnames can be found in the link plsgogame posted in this answer. You should upvote and accept this answer as it actually answers your question correctly and provides working code for it.
Comment: Only issue is `^` and `$` at the beginning and end that will stop it from finding IP addresses for the OP's application. Other than that, this is a very good answer.
Comment: I really like this answer, it mostly works, but I also need it so that it can be found inside a string with that randomly thrown in there somewhere, and for it to work with letters too, because some IPs can use a custom IP such as jointhis.server.com or something
Answer:
What I need is regex to find anywhere in the string, a character followed by a period followed by another character. I need it to find any amount of [letter/number].[letter/number] in any string, if that made sense...

What you can do here is use a word boundary \b to match for these patterns in larger text.
For a simple solution, you can use something like this.
\\b((?:(?:[0-9]{1,3}\\.){3}[0-9]{1,3}|(?:[a-z0-9]+(?:-[a-z0-9]+)*\\.)+[a-z]{2,4}))\\b

Example:
import java.util.regex.*;

class rTest {
  public static void main (String[] args) {
    String in = "Let's match 127.0.0.1 being valid, or this IP: 127.0.0.1 and joinTHIS.server.com or build 1.2";
    String re = "\\b((?:(?:[0-9]{1,3}\\.){3}[0-9]{1,3}|(?:[a-z0-9]+(?:-[a-z0-9]+)*\\.)+[a-z]{2,4}))\\b";
    Pattern p = Pattern.compile(re, Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(in);
    while (m.find()) {
      System.out.println(m.group(1));
    }
  }
}

Output
127.0.0.1
127.0.0.1
joinTHIS.server.com

Comment: Awesome! I changed the regex a little bit (added a couple .*'s) and it works perfectly for IPs, hostnames, and in any string surrounding it that I tried. Thanks :)
Answer: Try this:
Pattern.compile("(\\d{1,3}\\.){3}\\d{1,3}");

This will simply find any sequence of 4 3-digit numbers separated by periods.
Edit: plsgogame's answer contains a better pattern for finding an IP address (which may only contain numbers between 0 and 255).
Answer: Your regex matches any string of length 3 starting and ending with [a-z0-9] because you're not escaping the '.' which stands for any character. Moreover, the set of character in parenthesis should be repeated. For example you could use something like:
[\d]*\.[\d]*\.[\d]*\.[\d]*

which matches one or more digits followed by a period three times and finally one or more digits. This means you'll get a match for any string of the form '123.456.789.101' but also stuff like '122533252.13242351432142.375547547.62463636', so that's not completely helpful.
An improvement, but not perfect, is the following:
[\d][\d][\d]\.[\d][\d][\d]\.[\d][\d][\d]\.[\d][\d][\d]

which will match groups of three digits separated by a dot.
If you want to fast forward to something much more interesting and effective but also more difficult to understand if you are a beginner, you can use the example found on this page, that is:
\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

which does exactly what you need.
Moreover, the matches() method tries to match all of the input, not a section of it, so you could add a '.*' at the beginning and end of the regex and run it from java code like this:
Pattern p = Pattern.compile(".*\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b.*");
Matcher matcher = p.matcher(message);
if (matcher.matches()) System.out.println("It's a match");

If you want to find all the IPs you can do instead:
Pattern p = Pattern.compile("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
Matcher matcher = p.matcher(message);
while (matcher.find()) System.out.println("Match: " + matcher.group());

Regexes are wonderful although the learning curve is steep. So good luck learning!


Bypass Redirect Rule which acts on user login, while logging through one time login link

Question: I have a redirect rule in place which takes user to home page after login, I need to bypass this rule when a user logs in with one time url login link which is sent in account creation email.
I am assuming there should be condition I need to put in the redirect on user login rule,but I am not finding it.I tried by putting a condition that if the site current page url is account one time login url then rule should not trigger,but its not working as the condition does not satisfy.
Answer: Got answer for it https://drupal.org/node/480584 #25.
In brief the key was text comparison in the current page url to match if user/reset exists.
<code>{ "rules_am_redirect_user_logins" : {
"LABEL" : "AM redirect user logins",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "user_login" ],
"IF" : [
{ "NOT text_matches" : { "text" : [ "site:current-page:path" ], "match" : "user\/reset" } }
],
"DO" : [ { "redirect" : { "url" : "user-home" } } ]
}
}
</code>


How to know how many concurrent users jMeter can start?

Question: There is a place in jMeter where you can specify the number of users you want to start concurrently. I assume you can't put a number where it exceeds the limitation on your hardware & OS.
http://jmeter.apache.org/usermanual/build-web-test-plan.html

If you set the value to 0, then JMeter will immediately start all of your users.

But given a specific hardware and OS, let say windows 7, i5 CPU, 8GB RAM. How do I know or calculate the number of users I can put to start all the users concurrently? Although I can trial & error to find out the numbers, I hoping if there is a way to pre-calculate it.
Comment: To clarify my question:
What I am trying to figure out here is let say I put number of threads = 500, and ramp-up time = 0. How do I know jMeter actually starts all 500 threads in zero seconds. Because I am sure each thread will take certain amount of hardware resources (e.g. memory, CPU). Because I assume if hardware is busy, some of the threads might not start immediately?
Answer: The ramp-up time is not really important except for special cases, so they recommend in the same paragraph to keep it at the default value of 1 sec, which means all threads you enter in the number of threads field will be started within 1 second. Also, for the local OS it doesn't matter at all if you start all threads at once or with a ramp-up time, the limiting factor will be the number of threads alone.
How large you can select the number of threads value on the client machine is dependend on many factors and you have to test it yourself, but since the purpose of JMeter is to see how your server handles X concurrent connections, I assume in many cases the server or the network connection to the server will be the limiting factor, not the local machine itself.
Comment: Thanks for your feedback. What I am trying to figure out here is let say I put number of threads = 500, and ramp-up time = 0. How do I know jMeter actually starts all 500 threads in zero seconds. Because I am sure each thread will take certain amount of hardware resources (e.g. memory, CPU). Because I assume if hardware is busy, some of the threads might not start immediately?
Comment: I am sure here is no general metric to calculate this, but I doubt this will be relevant at all, except you have a very large number of threads to start and you really need an instant ramp-up, but why would you?
Comment: I am hoping to test how the server can handle sudden surge of traffic. But the test might not be accurate if I am not sure if jMeter can or cannot start X number of concurrent users within 0 seconds?
Answer: To check all threads were started simultaneously use listeners. For instance View result in table, see 'Start time' column


How to search in a two tables with RLIKE where one table can be empty

Question: I have the following query:
SELECT p.partid, pp.partno, p.descr
FROM part p, partcreditor pc, partcreditor_partno pp
WHERE p.partid = pc.partid
AND pc.creditorid = pp.creditorid
AND p.partid = pp.partid
AND (p.partid RLIKE '$val' OR pp.partno_search RLIKE '$val' OR p.descr RLIKE '$val')

For each seperate search term that the user inputs another line like the last line in the query gets added.
This query works very fast but the problem is that table partcreditor does not have a record for table part so than nothing gets returned. So I tried rewriting the query with left joins but this made the query very slow.
Any solutions?
Answer: Theres no getting around it... You need left joins.
However, try moving the criteria up into the join condition, like so:
SELECT p.partid, pp.partno, p.descr
FROM part p
JOIN partcreditor pc ON p.partid = pc.partid
LEFT JOIN partcreditor_partno pp ON p.partid = pp.partid
  AND pc.creditorid = pp.creditorid
  AND pp.partno_search RLIKE '$val'
WHERE p.partid RLIKE '$val'
OR p.descr RLIKE '$val'

It's a little odd that you're doing an RLIKE on an id column.
Since you're doing text searching, you will find that using a FULLTEXT index will improve performance astoundingly.
Comment: Thanks, this is a lot faster. I have one input in php where I let the user type in search terms this can either be the id or the descr that's why I use this method.
Comment: @bart then you don't need rlike on id. Use `p.partid = '$val'
OR p.descr RLIKE '$val'`
Comment: It automatically starts searching with ajax as soon as you type so input '12' could show id '123'


Magento Product pag - displaying related products that are out of stock

Question: I'm not too experienced in PHP but my goal here is to have related product swatches not display on the page if they are out of stock.(highlighted in screenshot)
Related product swatches are highlighted
Here is the PHP code:

    <?php foreach($this->getItems() as $_item): ?>

            <?php if(!$_item->isComposite() && $_item->isSaleable()): ?>
                <?php if (!$_item->getRequiredOptions()): ?>
                    <input type="checkbox" class="checkbox related-checkbox" id="related-checkbox<?php echo $_item->getId() ?>" name="related_products[]" value="<?php echo $_item->getId() ?>" />
                <?php endif; ?>
            <?php endif; ?>

                <a href="<?php echo $_item->getProductUrl() ?>" title="<?php echo $this->escapeHtml($_item->getName()) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_item, 'thumbnail')->resize(50) ?>" width="50" height="50" alt="<?php echo $this->escapeHtml($_item->getName()) ?>" />

<a href="<?php echo $_item->getProductUrl() ?>"><?php echo $this->escapeHtml($_item->getName()) ?>

                    <?php echo $this->getPriceHtml($_item, true, '-related') ?>
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                        <a href="<?php echo $this->getAddToWishlistUrl($_item) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?>
                    <?php endif; ?>

    <?php endforeach ?>

And here is the related jQuery/JS:

Any help would be appreciated, thank you!
Answer: Are you sure that you have the option Display out of stock products set to No? (System -> Configuration -> Inventory)
You can also try to add $_item->isAvailable() to if statement.
Comment: Adding the $_item->isAvailable() to if statement worked PERFECT, out of stock products will not display as a related product swatch! :D.  To answer your question "Display out of stock Products" is set to "no" which is what we want, so that out of stock product pages are view able to customers who might share the page link or google the product but don't show up on category pages.  Thanks for your help!
Comment: I'm looking for the same type of functionality for "related product colors" checkout this link to my question-> http://stackoverflow.com/questions/38316719/magento-related-product-color-swatches
Answer: The Solution I ended up going with:  adding $_item->isAvailable() to if statement gives the desired effect of related products that are out of stock will not display as a related product swatch on the product page.


Multiple values in creating a new field instance

Question: This is the code I actually have:
$instance = array(
    'field_name' => FIELD_PROJECT_TAGS,
    'entity_type' => 'node',
    'label' => $vocabulary->name,
    'bundle' => 'portfolio_project',
    'required' => true,
    'widget' => array(
        'type' => 'taxonomy_autocomplete',
        'behaviors' => array(
            'multiple values' => FIELD_CARDINALITY_UNLIMITED,
        ),
    ),
    'display' => array(
        'default' => array(
            'type' => 'taxonomy_term_reference_link',
            'weight' => 10,
        ),
        'teaser' => array(
            'type' => 'taxonomy_term_reference_link',
            'weight' => 10,
        ),
    )
);
field_create_instance($instance);

What's wrong with this? Why does the portfolio module allways install this field with allowing only one value?
Hope somebody can help. I'm bit frustrated.
Answer: Hopefully this will prove useful: To create a field that allows multiple values, you set the cardinality to -1 when using field_create_field.  Then all instances will allow multiple values (provided the widget supports that).
Example:
field_create_field([
  'cardinality' => -1,
  'field_name' => 'field_unlimited',
  'type' => 'special_content',
  'entity_types' => ['node'],
]);

Comment: This is good, but actually rather than using -1, the constant FIELD_CARDINALITY_UNLIMITED should be used: `'cardinality' => FIELD_CARDINALITY_UNLIMITED,`
Answer: As reported in Field API, the array indexes used for the widget array are the following ones:

type (string) The type of the widget, such as text_textfield. Widget types are defined by modules that implement hook_field_widget_info().
settings (array) A sub-array of key/value pairs of widget-type-specific settings. Each field widget type module defines and documents its own widget settings.
weight (float) The weight of the widget relative to the other elements in entity edit forms.
module (string, read-only) The name of the module that implements the widget type.

It is hook_field_widget_info() that defines the behaviors of the field widgets.
function hook_field_widget_info() {
  return array(
    'text_textfield' => array(
      'label' => t('Text field'),
      'field types' => array('text'),
      'settings' => array('size' => 60),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
    'text_textarea' => array(
      'label' => t('Text area (multiple rows)'),
      'field types' => array('text_long'),
      'settings' => array('rows' => 5),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
    'text_textarea_with_summary' => array(
      'label' => t('Text area with a summary'),
      'field types' => array('text_with_summary'),
      'settings' => array(
        'rows' => 20,
        'summary_rows' => 5,
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

The module you are writing should implement that hook, in order to allow the field to use multiple values.
The taxonomy widget allows to enter multiple values by entering them separated with a comma; if you are expecting the widget to appear more than one time on the page, then it is not how that widget works. Other widgets can probably use more form fields to contain multiple values.
Comment: I think you misunderstand my question. Your answer is great and there are a few things that will help me in the future. But ... the taxonomy plugin allready provide a taxonomy_autocomplete widget which I use. I wonder about the constant **FIELD_BEHAVIOR_CUSTOM** which means that the widget is allowed to deal with one or more values. Look in the API for [taxonomy_field_widget_info()](http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy_field_widget_info/7). What am I doing wrong? Thanks in Advanced again!
Comment: @Johnny: The `behaviors` array index is not passed to `field_create_instance()`, as reported in the documentation I linked to.
Comment: Okay, apart from that (thats my mistake in understanding the architecture of Drupal): The default `taxonomy_autocomplete` widget seems to dissallow multiple values. But why?


Real Analysis - Riemann Integral

Question: I am having some difficulty with this problem:
Let $I := [a,b]$ and let $f: I\to\mathbb ℝ$ be continuous on $I$. Also let $J := [c,d]$ and let $u: J\to\mathbb ℝ$ be differentiable on $J$ and satisfy $u(J)\subseteq I$. Show that if $G: J\to\mathbb ℝ$ is defined by
 $$ G(x) :=\int_a^{u(x)} f(t)\,dt $$
for $x$ in $J$, then $G'(x) = (f \circ u)(x)u'(x)$ for all $x\in J$.
Should I use the Leibniz rule to approach this problem?
Answer: Hint: $f$ is continuous, so $F(x) = \int_a^x f(t)\,dt$ is differentiable with $F' = f$. Now apply the chain rule to compute $G' = (F \circ u)'$.
Edit (in response to comment): The first claim follows from the fundamental theorem of calculus. That $G(x) = F(u(x))$ is true by definition - just plug $u(x)$ into $F$. That $G$ is differentiable follows from the fact that's it's the composition of two differentiable functions and the derivative is computed with the chain rule: $G'(x) = F'(u(x))u'(x) = f(u(x))u'(x)$.
Comment: I am not sure how to show this explicitly. I guess I just keep thinking I am not showing enough work. Could you help show me what you mean?
Comment: Can we use the FTC since our limits are constants?

Real Analysis - Riemann Integral


What trig. identity would help solve $2 + \cos(2x) = 3\cos(x)$?

Question: I need help with a homework question that has me puzzled. I need to solve the following equation:
$$2 + \cos(2x) = 3\cos(x)$$
I don't see a good trig identity to apply. I tried $\cos(2x) = 2\cos^2(x) - 1$ but that did not seem to help. What would be a good identity to try instead?
Answer: You have the right trig identity. Let $u=\cos(x)$. Then, using $\cos(2x)=2\cos^2(x)-1$ we have a quadratic equation $2+2u^2-1=3u$. To finish, solve this quadratic equation and substitute back $\cos(x)$
Comment: So obvious once you show it! Thanks!


Is it possible that $(ab)^{-1}$ is defined although $a^{-1},b^{-1}$ are not?

Question: I wish to enquire about the properties of units in abstract algebra.
In a ring $R$, a unit $u$ is an invertible element. Let $u=ab$. Is it possible that $a$ and $b$ are not units? Is it possible that they're prime?
Motivation: If $u=ab$, then $(ab)^{-1}$ exists. We know that if the inverses of $a$ and $b$ exist, then $(ab)^{-1}=b^{-1}a^{-1}$. However, if the inverses of $a$ and $b$ don't exist, I feel $ab$ can still be a unit. However, I'm not sure of this.
Thanks in advance!
Comment: If you're interested in commutative rings, you should say so.
Answer: Let $R = L(\ell^2)$ the linear continuous operators on $\ell^2$. Define $a,b \colon \ell^2 \to \ell^2$ by
$$ a(x_1, x_2, \ldots) = (x_2, x_3, \ldots) $$
and $$ b(x_1, x_2, \ldots) =(0, x_1, x_2, \ldots) $$
Then $ab = 1$ is the identity, hence invertible, but neither $a$ nor $b$ are units as $a$ is not one to one, where $b$ is not onto.
Comment: The endomorphism ring of an infinite dimensional vector space is a common source for counterexamples showing that something true in commutative rings is not necessary true in the noncommutative case.
Comment: @egreg In this case, we can forget about rings and just talk about semigroups. Then every semigroup is a subsemigroup of a semigroup of endomorphisms under function composition, as above. So all counter-examples lie in this world! (Of course, the question is about rings, but if you want to put in in terms of rings then every semigroup is a subsemigroup of the semigroup underlying this ring...)
Answer: It is not possible in commutative rings. In general, if $ab$ is a unit then there exists, $v\in R$ such that $(ab)v=1$. Thus $a(bv)=1$. So, $a$ is a right unit. S Similarly it can be shown that $b$ is a left unit.
Comment: But only in commutative rings! Let $R = L(\ell^2)$, and $b : e_n \mapsto e_{n+1}$ the right shift, $a \colon e_n \mapsto e_{n-1}$, $ae_1 = 0$ the left shift. Then $ab = 1$ is a unit, but neither $a$ or $b$ are.
Comment: @ Martini: Yeah, you are right. I am sorry, let me rectify. If $ab$ is a unit, then $a$ is a right unit and $b$ is a left unit.
Answer: If $ab$ is invertible, then there is an $x\in R$ with $x\cdot ab = ab\cdot x = 1$.
From $(xa)b = 1$ we get that $b$ is left-invertible, and from $a(bx) = 1$ we get that $a$ is right-invertible.
The example in the answer of martini shows that a left-invertible element is not necessarily right-invertible.
Rings with the property "left-invertible iff right-invertible" are called Dedekind finite.
So in Dedekind finite rings, your property is true.
Special cases of Dedekind finite rings are commutative rings (answer of Anupam) and finite rings.


Why is are unbiased statistics used more commonly than statistics with lower MSE?

Question: I understand the difference between consistency and bias; one converges as the sample size increases, and the other converges as the number of estimates increases, respectively.
But, I don't understand why people generally prefer the unbiased version of sample variance to estimate population variance.  Using simulation, it can be shown that a biased estimator of the population variance can have lower MSE than an unbiased estimator.
So, why do we use the unbiased version of sample variance if the MSE can be higher?
Another question might be how to accurately estimate the MSE without using simulation, since a big component of MSE is Variance of the estimator, and simulation is often not possible since it requires knowing the true value of the parameter/estimand (in this case, the estimand is the poulation variance).
http://www.johndcook.com/blog/bias_consistency/
Answer: This might sound like a pun, but it is really about bias - variance trade offs. Use the biased version, and you have less variance but bias. Use the unbiased one, and you have no bias but more variance.
I think another, perhaps less valid reason, is that many people - when the learn statistics, tend to think of unbiasedness as an (very) important property. Hence they pick this version.
I any case, if you wish to do inference you will most likely need to apply some form of asymptotic result - in this case both estimators should do the trick equally well (or bad, as some might put it). And the choice is less important.
Comment: This skips the question of why is unbiasedness taught or taken as a very important property. In some specific contexts, as in meta-analysis, I could see how unbiasedness might be more attractive as precision can be increased, but I do not see this as a general case.


Expected value of a sample

Question: I am unsure of how to solve this question. I know from examples questions that expected value of a sample is usually very close to the population mean. However, it says to compute the expected value and I don't know how to do that or how to find the sample's standard deviation. I have tried going through various statistics textbooks, but I cannot find an example to solve this question:
Answer: HINT: You know that $X\sim N(2.835,0.15^2)$, assuming that $X_1,...X_{100}$ is a random sample of $X$ then
$$E[\overline{X}]=\frac{1}{n}\sum_{i=1}^{100}E[X_i]$$
$$Var(\overline{X})=\frac{1}{n^2}\sum_{i=1}^{100}Var(X_i)$$
I do not know what you've learned but if $X\sim N(\mu,\sigma^2)$ then $\overline{X}\sim N(\mu,\frac{\sigma^2}{n})$
If you are learning about inference, I recommend to take a look at some of these 2 books
Statistical Inference
Introduction to the Theory of Statistics
EDIT:
$E[\overline{X}]=\frac{1}{100}\sum_{i=1}^{100}E[X_i]=\frac{1}{100}(E[X_1]+E[X_2]+\cdots+E[X_{100}])=\frac{1}{100}100*E[X_1]=2.835$ where the last equality comes from the fact of the independence of the variables
Comment: I hope you don't mind me asking, but I keep seeing this notation N(something, something2) in my book and I don't understand what it is. You used 2.835 there, so how did you come up with it or what is that?
Comment: @Kelbe $X\sim N(2.835,0.15^2)$ is a notation for Normal random variable with $\mu=2.835$ and $\sigma^2=0.15^2$
Comment: Thank you John. I'll check out the books you mentioned.
Comment: How would I use the formula to compute the expected value? I don't know Xi or the average for each sample.
Comment: @Kelbe Take a look at my latest edition, you can do like this to find the variance $Var(\overline{X})$

Expected value of a sample