Hide/Show Label and Paragraph from select drop down

Question: I am trying to hide my label for gvw and the
 after it I only want it to show when Truck is chosen. Can someone please help me and explain to me how to do it using this code? The problem is the placement of them otherwise it could be easier with jQuery :/
http://jsfiddle.net/1xqbpLp1/

 function GVW(){
   var dropdown1 = document.getElementById('vehiclebody');
   var textbox = document.getElementById('gvw');
   // Array for storing whether the textbox is required
   var is_required = [false, false, false, false, true, false];

   if(is_required[dropdown1.selectedIndex]) {
       textbox.required = true;
       textbox.style.display = "inline-block";
   } else {
       textbox.value = "";
       textbox.required = false;
       textbox.style.display = "none";
   }

 }

<select name="vehiclebody" id="vehiclebody" required="yes" message="Please select body." size="1"  onChange="GVW();">
    <option value="">Choose a Vehicle</option>
    <option value="0">2Dr</option>
    <option value="1">Pickup</option>
    <option value="2">4dr</option>
    <option value="3">Truck</option>
    <option value="4">Convertible</option>
    <option value="5">Van</option>
</select>

Empty Weight:
         <input type="text" name="ew" id="ew" validateat="onSubmit" validate="noblanks" required="yes" message="Please enter empty weight." value="">

            Gross Vehicle Weight:*
         <input type="text" name="gvw" id="gvw" onfocus="this.select()" required="yes" message="Please enter gross vehicle weight." value="" style="display:none;">

*Gross Vehicle Weight is required for heavy trucks over 5000 lbs. Visit our website for more information. Heavy Truck Information and Fee Schedule based on GVW

Comment: can you give the `p` an id?
Answer: You need to use CSS to initially hide the elements:

And then use JavaScript to show/hide them depending on the selection. Here's a working jsfiddle: http://jsfiddle.net/kgajera/1xqbpLp1/1/
Answer: I'd take out your inline onchange="" and just go..
$("select").on("change", function() {
    if ($(this).val() =="3") {
        $("label[for='gvw']").toggle();
    }
});


C# & SQL Server query error: The multi-part identifier cannot be bound

Question: protected void btnSubmit_Click(object sender, EventArgs e)
{
    connectionString = ConfigurationManager.ConnectionStrings["LeaveMangementSystemCS"].ConnectionString;
    conn = new SqlConnection(connectionString);
    string sql = "UPDATE LeaveType  SET LeaveType.Type=@Type, LeaveType.Description=@Description, LeaveType.NumOfDays=@NumOfDays, LeaveCategory.Category=@Category FROM LeaveType INNER JOIN LeaveCategory on LeaveType.LeaveCategoryId = LeaveCategory.Id  WHERE LeaveType.Id=@id";

    try
    {
            cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@Type", tbType.Text);
            cmd.Parameters.AddWithValue("@Description", tbDescription.Text);
            cmd.Parameters.AddWithValue("@NumOfDays",tbNumOfDays.Text);
            cmd.Parameters.AddWithValue("@Category", ddlLeaveCategory.Text);
            cmd.Parameters.AddWithValue("@id", lblIdOut.Text);

            conn.Open();
            int rows = cmd.ExecuteNonQuery();

            if (rows > 0)
            {
                lblOutput.Text = " Updated successfully.";
            }
    }
    catch (Exception ex)
    {
        lblOutput.Text = "Error Message : " + ex.Message;
    }
    finally
    {
        if (conn != null)
            conn.Close();
    }
}

I have an error in my SQL query:

The multi-part identifier "LeaveCategory.Category" could not be bound.

I had try using leavetype as a and leavecategory as b but still this error.
Comment: Possible duplicate of [The multi-part identifier could not be bound](http://stackoverflow.com/questions/7314134/the-multi-part-identifier-could-not-be-bound)
Answer: You can't update multiple tables in one statement! See on your sql variable:
UPDATE LeaveType
SET LeaveType.Type=@Type
,   LeaveType.Description=@Description
,   LeaveType.NumOfDays=@NumOfDays
,   LeaveCategory.Category=@Category
FROM LeaveType
INNER JOIN LeaveCategory on LeaveType.LeaveCategoryId = LeaveCategory.Id
WHERE LeaveType.Id=@id";

Here you try to update table LeaveType and one column from table LeaveCategory
Please see this asnwer
Comment: I tried too but my table will not be updated after i tried updating the status in html.
Comment: What do you mean? Are we talking about SQL or HTML???? In the question I do not see any information about HTML!
Comment: I meant this code is under my aspx.cs file using master page in c# microsoft visual studio which i launch into chrome and tried updating which where the error shows The multi-part identifier "LeaveCategory.Category" could not be bound.
Comment: Do you understand the answer? I wrote that you cann't use your `sql` variable as it is. You should click the link "Please see this answer" then read about possible solution and use it for your query. In the asnwer I've just showed your value of `sql` variable but with formatting to show where is an issue
Answer: You need to prepare two separate sql statements, you can not update two tables at once. You can wrap them in stored procedure, update them one after another and the call the proc from the C# code.
Comment: There may be (usually are, if you are updating them "at the same time") good reasons to also wrap them in a transaction.


I wrote a matrix into a file. How do I read this matrix from this file in Mathmatica11?

Question: for example,

m1.txt
1 2 3
4 5 6

now, I want to read this file, and get a matrix

m={{1,2,3},{4,5,6}}

What should I do?
Comment: `m = Import["m1.txt", "Table"]`
Comment: This can be closed because it is adequately answered by a comment
Answer: See Bill's comment about using Import, or you could literally have the line
m = {{1,2,3},{4,5,6}};

in m1.txt, and then use <<"m1.txt`"; to run the contents of m1.txt as Mathematica code.


If a proofreader catches 3 misprints on a page, what is the probability that there are still misprints that weren't caught on that page?

Question: Books from a certain publisher contain on average 1 misprint per page. Suppose those misprints occur according to a Poisson scatter, with a rate on 1 per page. One of the books from this publisher has 200 pages.
The probability that a proofreader catches each misprint is 0.7 (independently for different misprints). If a proofreader catches 3 misprints on a page, what is the probability that there are still misprints that weren't caught on that page?
Comment: I don't see how it would be possible to solve this without some model of how likely the proofreader is to catch each misprint.
Comment: I would assume the proofreader would catch all of the misprints so it becomes a probability of their occurrence.
Comment: I'm sorry. I've added the probability the proofreader is to catch each misprint. This question is actually part(d) of the question and I've already solve part (a) till (c) but I did not realized that part (c)'s statement is supposed to be used for part (d) too. My bad
Answer: \begin{eqnarray*}
\mathsf P(\text{$3$ misprints}\mid \text{$3$ misprints caught})
&=&
\frac{\mathsf P(\text{$3$ misprints}\land \text{$3$ misprints caught})}{\mathsf P(\text{$3$ misprints caught})}
\\
&=&
\frac{\mathrm e^{-1}\cdot0.7^3/3!}{\sum_{k=3}^\infty\mathrm e^{-1}/k!\cdot\binom k3\cdot0.7^3\cdot0.3^{k-3}}
\\
&=&
\frac1{\sum_{k=3}^\infty0.3^{k-3}/(k-3)!}
\\
&=&
\mathrm e^{-0.3}
\\
&\approx&
0.741\;,
\end{eqnarray*}
so the probability of there being further misprints is about $25.9\%$.
Note that the number $3$ of misprints dropped out of the calculation; the result depends only on the proofreader's accuracy; so no matter how many misprints she catches, there's always a one in four chance that there are more. Thus, the conditional probability of having caught all mistakes, given the number of mistakes caught, is simply the unconditional probability of catching all mistakes; the events of catching all mistakes and catching a particular number of mistakes are independent. As the proofreader's accuracy varies between $1$ and $0$, the probability of catching all mistakes varies between $1$ and $\mathrm e^{-1}$ (where the latter is simply the probability of there being no mistakes to catch).
Another way to view this is as a modification of the Poisson process: The proofreader is screening the mistakes with a probability of $0.7$ and thereby producing a process of uncaught mistakes with reduced rate $0.3$, whose probability of producing no uncaught mistakes is $\mathrm e^{-0.3}$. The original process is split into two independent sub-processes, of caught and uncaught mistakes, with rates $0.7$ and $0.3$, respectively, and the number of events in the process of caught mistakes provides no information about the number of events in the process of uncaught mistakes.


Construction of Set with required measure

Question: I have a Probability measure $P$ defined on $S = [0,1]$ satisfying $P({\{x}\}) = 0$ for any $x$ in $S$.
How can I construct a subset $A$ of $S$ such that $P(A)$ is exactly $\frac{1}{2}$?
Instead of $\frac{1}{2}$, can this construction be generalized to any $0 < k < 1$?
Comment: I have posted a detailed answer to your question. Please, let me know if you have any question regarding my answer. If my answer provides relevant / helpful information regarding your question, please, upvote it. If my answer actualy answers your question, accept it too, please. To upvote, click the triangle **pointing upward above the number** (of votes) in front of the question. To accept the answer, click on the check mark beside the answer to toggle it from greyed out to filled in.
Answer: If $P$ has no atoms, then the image of $P$ will be $[0,1]$.
See here and also here
The condition $P(\{x\})=0$ for any $x$ in $S$ is not enough to ensure that $P$ has no atoms.
For a counter-example, consider the probability space $([0,1],\mathcal{M}, P)$ where
$$\mathcal{M} =\{E\subseteq [0,1]: E \text{ or } E^c \text{ is countable} \}$$
and $P(E)=0$ if $E$ is countable and  $P(E)=1$ if $E^c$ is countable.
It is easy to check that $\mathcal{M}$ is a $\sigma$-algebra and that $P$ is a probability measure. In this case, the image of $P$ is just $\{0, 1\}$.
Remark 1: If you assume that

$P(\{x\})=0$ for any $x$ in $S$ and
For every $x \in [0,1]$, $[0,x) \in \mathcal{M}$

Then
$\mathcal{M}$ contains the Borel $\sigma$-algebra of $[0,1]$ and $P$ has no atoms. So the image of $P$ is $[0,1]$.
Remark 2: As remarked by GEdgar, in the special case presented in Remark 1, a nice way to see that the image of $P$ is $[0,1]$ is to note that the function $x \to P([0,x))$  is continuous , it has value $0$ at $0$ and value $1$ at $1$.
Answer: The function $\phi(t) = \mathbb P\big([0,t)\big)$ is continuous.  Therefore it achieves all values between $\phi(0) = 0$ and $\phi(1) = 1$.
As Ramiro remarked, we have to assume $[0,t)$ is $\mathbb P$-measurable for all $t$ to do this.

added: $\phi(t)$ is continuous.
Use countable additivity: since $\phi(t)$ is nondecresing, $$\lim_{h \to 0+}\phi(t+h)= \lim_{h \to 0+}P\big([0,t+h)\big) = \lim_{n \to \infty}P\left([0,t+\textstyle\frac{1}{n})\right) \\
= P\left(\bigcap_{n}[0,t+\textstyle\frac{1}{n})\right) = P\big([0,t]\big)=P\big([0,t)\big)+P\big(\{t\}\big) = \phi(t)$$ and similarly for $\lim_{h \to 0+}\phi(t-h) = \phi(t)$.
Comment: Proving continuity of  \phi would require lim h->0  P([t, t+h)) to be 0. Is this trivial? I am guessing one would do this by showing that this limit is equal to P({t}) which is zero by the condition given in the original question. Might be a stupid question, but can you help me prove this formally?


Estimating the distribution from percentile score, top 50 and curve

Question: I'm trying to estimate how many people participated in a game competition and what my percentile score is based on some public data provided by the host.
The data I have is:

Top 50 leaderboard (Let's say the 50th player scored 940.6)
top 5th (699.0), 20th(475.3), 40th(214.8) and 70th(107.0) percentile score
A (not that clear) curve Showing how many player have achieved a certain score (X axis is only partially annotated.)

(1) Assuming that the final score distribution is a normal distribution, is it possible to estimate the whole distribution?

Giving a score, is it possible to estimate the percentile score?
Is it possible to estimate the total entries?

(2) This curve doesn't look like a trivial normal distribution. What's the best guess of this distribution? Can it be two distributions added up? If this is the case, is it possible to separate them just using these data we have?
Edit: I'll give a bit more details how this data is formed.
Each player plays in a succession of 3-player match which yields a pre-adjustment zero-sum result (ex. +50, +5, -55 or +50, -15, -35). The final score of a player is generated by his or her best performance summed up in any consecutive 8 games, adding a bonus +60 to each game played (Which means that when a player didn't finish 8 games s/he still qualifies but get less bonus score).
A good simplification is that 3 players play in a poker-style game and got their earnings/lost at the end of the game summed up with an additional bonus/penalty based on their positions. Although players only carry certain chips into a game and when any one depleted their chips or had certain rounds finished the game concludes, negative chips do carry over so scores can be arbitrary large but 99% of the game won't have anything over +/-80. Players got randomly matched.
The game is actually 3 players japanese riichi mahjong. (https://en.wikipedia.org/wiki/Japanese_Mahjong)
Example 1: -50 +50 +50 +50 +50 +50 +50 +50 +50 => Total +400 (Best possible sum at Games 2-9; 1-8 only yields +300 and are not selected) +480 (Finished at least 8 games) = +880
Example 2: -50 +50 => Total +0 (Games 1-2) + 120(Finished 2 games) = +120
Players play minimum 1 game to qualify. The best guess to distribution of how many games a player played is a binomial distribution.
Comment: I was worried about that, because the apparent bump in the curve (within the red zone) is incompatible with your description: such a curve necessarily can never increase in height as you move from left to right.
Comment: What is this curve attempting to display?  What is being shown on its axes?  It doesn't seem to be even remotely related to a Normal distribution.
Comment: Y axis is "how many players achieved this score", and X axis is "the score". I will add more information to the topic to clarify this.
Comment: Can you explain more about the pre-adjustment zero-sum? Is this a random thing for a game? Does a player win one of the three or can there be more? Are scores related to difficulty? Is +50 a maximum score? Are the games between multiple players (making the scoring dependent)? In that case, how are players matched? What does best performance mean?
Comment: @MartijnWeterings A good simplification is that 3 players play in a poker-style game and got their earnings/lost at the end of the game summed up with an additional bonus/penalty based on their positions. Although players only carry certain chips into a game and when any one depleted their chips (Edit: Or certain rounds have been finished) the game concludes, negative chips do carry over so scores can be arbitrary large but 99% of the game won't have anything over +/-80. Players got randomly matched. The game is actually 3 players japanese riichi mahjong.
Comment: I still don't get the best performance part.
Comment: A player has best performance in a game when s/he earned the most chips (more than other 2 players, while one or both of the players actually lost chips); A player tops the board when s/he happens to get the highest adjusted earning in a sliding window of 8.
Answer:
The yellow curve looks like a probability distribution function (and it's shape is not that strange for these type of cases, e.g. scores).
We can check this by extracting the data (for instance https://apps.automeris.io/wpd/)
And we find:
<code># data for pdf
pdf = matrix(c(50.791730474732, 1.01010101010101,
               75.2695252679939, 0.869104521478181,
               101.560490045942, 0.728138970099154,
               107, 0.708029761628537,
               145.076569678407, 0.547063282132195,
               174.087289433384, 0.456649187123919,
               202.191424196018, 0.376320633594753,
               215.790199081164, 0.34624963262023,
               235.735068912711, 0.306185901898,
               256.5865237366, 0.25603662969666,
               281.970903522205, 0.236267730907854,
               302.822358346095, 0.216421489009544,
               327.300153139357, 0.186536111497827,
               354.497702909648, 0.166798149952821,
               384.415007656968, 0.157207604374526,
               411.612557427259, 0.13746964282952,
               442.436447166922, 0.137995575974137,
               475.073506891271, 0.138552446362554,
               508.617151607963, 0.159326805574891,
               542.160796324656, 0.159899144585209,
               571.171516079633, 0.170495150587034,
               596.555895865237, 0.170928272000248,
               623.753445635528, 0.151190310455241,
               653.670750382848, 0.161801785078968,
               676.335375191424, 0.152087490525469,
               699.906584992343, 0.142388664593871,
               722.571209800919, 0.122573359939363,
               757.021439509954, 0.102959147369561,
               781.499234303216, 0.0932757900598635,
               803.257274119449, 0.0734450167834548,
               824.108728943338, 0.0535987748851454,
               854.932618683002, 0.0541247080297616,
               891.196018376723, 0.0345414327037605,
               931.085758039816, 0.0150200318653611,
               992.733537519143, 0.0160718981545933,
               1058.00765696784, 0.00708462883041761),36,byrow=1)

pdf[,2] <- pdf[,2]-pdf[36,2]

# calculating cdf
cdf <- c(0,cumsum((pdf[-1,2]+pdf[-36,2])*(pdf[-1,1]-pdf[-36,1])))

# correction for not knwoing pdf values below 55
cdf <- cdf+50

# plot calculated cdf
plot(pdf[,1],cdf/cdf[36],ylim=c(0,1),log="x",xlab="score",ylab="cdf, percentile")
#points(pdf[,1],cdf/cdf[36],ylim=c(0,1),log="x")

# plot percentiles
points(c(107,214.8,475.3,699),c(0.30,0.60,0.80,0.95),pch=21,bg=2,col=2)
lines(c(940.6,940.6),c(0,1),col=2)
lines(c(823.15,823.15),c(0,1),col=1)

# plot what would have been if we interpret the extracted yellow curve as cdf
lines(pdf[,1],1-pdf[,2],col="yellow",lw=2)
</code>

Which strengthens the believe that the yellow curve in your image was a probability distribution function and not a cumulative distribution function.
There is still a difference between the plotted curve and the given CDF points (at top 5th (699.0), 20th(475.3), 40th(214.8) and 70th(107.0) percentile score) however if we would interpret the yellow curve as a CDF (instead of PDF) then the result is even further off (it has the dip which whuber mentions but also the yellow curve does not match the given percentiles).
In the given diagram you score as 824 at the 98th percentile.
Note: The distribution looks much like an exponential (at least the first part). You see this often in rankings of score boards (for instance: you could do the same with the reputation scores of the users on StackExchange). But also for instance in the wealth distribution of a given population. There are many variations possible, power law, Pareto, etcetera.
So, the assumption of a normal distribution would not be so good.
See the image of log(pdf)

And now your many questions:
(1)

Yes, you can estimate a percentile score based on a given score. This requires an estimate of the CDF. This can be done either based on the yellow curve and the construction of the cdf that I made (reasonably accurate), or based on a exponential distribution and the given percentile scores (less accurate since the distribution is not purely a single exponential distribution, and the bump seems difficult to cast in a simple distribution).
Yes, you can estimate the total entries using the previous answer. The top 50th at a score of 940.6 can be estimated by taking an average of the measurement points at 931 and 992, which is roughly 0.9984 and multiplying 50/(1-0.9983579) gives more or less 30k entries. This method is a bit problematic since errors (and we do make them with our simplistic data extraction from the image) tend to blow up for 1/(1-x) when x is close to one.

(2)

No definitely not normal distribution.
Exponential works but there is a discrepancy between 400 and 600. This is not a-typical for real life distributions.
Given your zero sum game mechanism with a bonus that only kicks in after 8 * 60 = 480 this seems to be the possible mechanism with a sum of two distributions.
Comment: Thanks for the detailed answer! Yes, I have strong belief that the bump around 500~600 is because of the bonus not increasing after +480. By the way even when a player didn't finish 8 games s/he still get discounted bonus point (60 per game) so it's not 0 or 480.
Answer: (1) Yes, given at least two percentile values (plus a normality assumption), you can uncover the whole distribution.  First note that the normal distribution is completely characterized by it's mean $\mu$ and standard deviation $\sigma$.  I'll use these data points:
5th percentile is 107
20th percentile 214.8
Let Z be standard normal, and X is the underlying (unknown) normal distribution, so that:
$$Z = \frac{X - \mu}{\sigma}$$
The 5th percentile of Z is -1.645 and the 20th percentile is -0.842.  Two equations, two unknowns:
$$-1.645 = \frac{107 - \mu}{\sigma}$$
$$-0.842 = \frac{214.8 - \mu}{\sigma}$$
Solving, we get $(\mu, \sigma) = (251.03, 43.02)$.
Edit: Of course, if you use two different percentiles, you'll get different $(\mu, \sigma)$ values, since this distribution is not normal, there's no reason the other data point should agree.
(2) Of course, as you pointed out, this is decidedly nonnormal.  Just eyeballing, it could be an exponential or gamma distribution.
Comment: You might want to review the answers at https://stats.stackexchange.com/questions/207403 and https://stats.stackexchange.com/questions/130156/estimate-normal-distribution-from-small-sample-with-rankings/130174#130174, and https://stats.stackexchange.com/questions/34882, which address the same question.  The present issue is well summarized by your point (2), which basically says to ignore these approaches because they will be wrong.
Comment: Yes. the point (2) hurts. I have provided a detailed description of the generation of the data, hope it helps. Is it that in this case a simulation actually helps?


Picking Cards and Probabilities

Question: If you have a regular deck of 52 cards, with Jack, Queen, King, and Ace defined as top cards, what is the probability that you will pick:

Two top cards and four non-top cards?
Three top cards in the same suit and any three cards in another suit?
Three top cards not all in the same suit, and any three non-top cards?
Six non-top cards all in the same suit? (For example 2, 4, 5, 6, 8, 10, all in spades)
Two different pairs of top cards (e.g. Q-Q, A-A) and any two cards each different
from both pairs? (The last two cards may be a pair, and they may be top cards.)

These are the answers I have, but I'm not very confident in them:

$$P=\dfrac{\binom{36}3\binom{16}3\binom{9}3\binom{4}3}{\binom{52}6}$$
$$P=\dfrac{(\binom{16}3-\binom{4}3)\binom{36}3}{\binom{52}6}$$
$$P=\dfrac{\binom{36}6\binom{9}6}{\binom{52}6}$$
$$P=\dfrac{\binom{4}2\binom{4}2\binom{4}2\binom{44}2}{\binom{52}6}$$
Any help you could give me at this point would be greatly appreciated.
Comment: Quite a lot of questions. What work have you done on them ? Are you stuck on all of them ?
Comment: Honestly, I don't even know where to begin. Any help - even just with starting - would be appreciated.
Comment: Are the answers you posted for problems 2, 3, 4, and 5 rather than 1, 2, 3, and 4?
Comment: Yes, sorry. I thought I had fixed that before posting
Answer: Well, let me do the first one, then you can try some more !
A deck will have $16$ top cards (choose $2$ from them), and $36$ others (choose $4$ from them)
Pr $= \dfrac{\binom{16}2\binom{36}4}{\binom{52}6}$
Comment: Thanks for the help. I'm just wondering if, for 3, you could help me specify that the top cards have to be in different suits?
Comment: @Doe Choose the three top cards, then subtract the number of selections in which they are all of the same suit.
Comment: @N.F.Taussig thanks for the help. I think I have the rest but I'm not sure about the last one. Would it be (13 choose 2)(4 choose 2)(4 choose 2)(11 choose 1)(4 choose 1)(36 choose 2) on the numerator?
Comment: @Doe  That is incorrect.  I suggest that you edit your question to include your proposed solutions so that you get feedback on them.  For the last question, you must choose two of the four ranks (Jack, Queen, King, Ace) of top cards, select two of the four suits for each of the selected ranks, then select two of the $44$ cards in the deck that have ranks different from the two pairs that you selected.
Comment: @N.F.Taussig thanks, I've given that a try, although I'm not sure if I've done it correctly.
Answer:
What is the probability that you will pick two top cards and four non-top cards?

true blue anil has provided you with a correct answer to the first question.

What is the probability that you will pick three top cards in the same suit and any three cards in another suit?

We must select one of the four suits from which to pick the top cards, select three of the four top cards in that suit, pick one of the three remaining suits, then select three of the thirteen cards in that suit.

  $$\binom{4}{1}\binom{4}{3}\binom{3}{1}\binom{13}{3}$$

from which you can calculate the probability.

What is the probability that you will three top cards not all in the same suit and any three non-top cards?

We must select three of the sixteen top cards.  From these selections, we must exclude those selections in which we pick three top cards from the same suit.
Those selections in which three top cards are selected from the same suit require selecting one of the four suits and three of the four top cards in that suit. Hence, the number of ways of selecting three top cards from the same suit is

 $$\binom{4}{1}\binom{4}{3}$$

Thus, the number of ways to select three top cards that are not all of the same suit is

 $$\binom{16}{3} - \binom{4}{1}\binom{4}{3}$$

We must also select three of the $36$ non-top cards.  Hence, the number of ways of selecting three top cards that are not all of the same suit and any three non-top cards is

 $$\left[\binom{16}{3} - \binom{4}{1}\binom{4}{3}\right]\binom{36}{3}$$

from which you can calculate the probability.

What is the probability that you will pick six non-top cards all in the same suit?

To select six non-top cards all in the same suit, we must select one of the four suits and six of the nine non-top cards in that suit.

 $$\binom{4}{1}\binom{9}{6}$$

from which you can calculate the probability.

What is the probability that you will pick two different pairs of top cards and any two cards different from both pairs?

You have answered this question correctly.
Comment: Thanks so much for all your help, it really makes more sense now.

Picking Cards and Probabilities


Noitifications about security updates keeps coming after the update is done

Question: I have updated to core version 7.52 and I also ran the database updates accordingly. So why do the notifications keep coming? I have set the update check to be done once a day, and every morning I get an email that states that a security update is available for my version of Drupal. When I click the link the page opens and says that Drupal core is up to date.
Comment: Check if the update notification is regarding Drupal Core or [Contributed modules](https://www.drupal.org/project/project_module)? Also make sure you've run [update.php](https://www.drupal.org/node/1223018) to make sure you've latest database changes.
Answer: I think this is the default behavior of the Update Status module, which is part of core. Unless you turn it off or reconfigure it, the modules will be checked daily and the site administrator will get email notices.
Comment: Smalution: But it is strange that the notifications keep saying that there are security updates, when there aren't any.


Como enviar dados de um formulário gerado pelo Ionic Framework para um arquivo PHP e retornar um JSON?

Question: Venho seguindo a documentação do Ionic Framework e vendo tutoriais na internet, mas não há detalhe de comunicação com o servidor. Gostaria de enviar dados de formulários e receber informações via JSON. Poderiam postar um exemplo simples de como enviar dados para o script PHP? Por exemplo: nome, e-mail e telefone. Acho que isso vai ajudar a todos que estão ingressando no uso do framework.
Answer: Você poderia estar utilizando $http do próprio angular para enviar esses dados, e no php retorna o json.
https://docs.angularjs.org/api/ng/service/$http
link para a documentação do $http, ali tem alguns exemplos de utilização
Comment: Obrigado. Acredito que isso me sirva. Infelizmente o pessoal negativou a pergunta. Sinceramente não entendo esses usuários.


Cross-mobile background service

Question: The goal is to record and analyze GPS tracks:

For iOS and Android devices with GPS it is required to record/analyze in the same time
For other devices (tablet - desktop) it is enough to analyze previously recorded tracks (in the browser)

It is OK to have some platform-specific code, but I'd like to share "analyze" part between iOS, Android and Web AND to be able to run this code while iOS/Android app is backgrounded.
I have some "analyze" code written in JavaScript, so I started looking for options in this order:

1) Do everything in a web app
iOS Safari stops running JavaScript when backgrounded.
No luck.

2) Use PhoneGap or alike
JavaScript stops when backgrounded. It is proposed to write ALL service code as native plugin.
No luck.

3) Use Titanium
Spent two weeks only to find that Android Service implementation in Titanium is incomplete. It lacks startForeground(..), which is used to ask Android to not kill the service. Someone tried to implement native module for this, but reports that while service itself is running, JavaScript don't.

4) Use Marmalade for mobile and compile C++ to JavaScript for Web
Quick googling said C++ code can't be run from service

5) Use MoSync for mobile and compile C++ to JavaScript for Web
Quick googling said they do not support services. On the other hand I saw startForeground(..) in their sources, so maybe worth rechecking.

7) Write in C: native for iOS, JNI for Android, compile to JavaScript for Web
Haven't checked yet

6) Use Codename One for mobile and compile Java to JavaScript for Web
Haven't checked yet

And my questions:
Q1. Can you confirm for each above option if it can or can not be used for such an app
Q2. I specifically interested in Titanium (as already invested in it). I'm thinking of a native Android module with dummy Service that does nothing but asks Android to not kill its process where real Titanium service is running along side with an Activity.
Will it work?
Q3. Other options / general advice?
Thank you.
Answer:
When we met the "super-duper" framework limitations I came with native knowledge: add a plugin for Phonegap learn how to link it, write for both platforms.
Titanium no experience, sorry.  I don't think I would even open they page to read they hello word.
Back to your original task,  just look again outside of your shoes ( as I would ask it and you should respond)

"The goal is to record and analyze GPS tracks:
I'd like to share "analyze" part between iOS, Android and Web AND to be able to run this code while iOS/Android app is backgrounded."
Suggestion 1: Just re-write the code in C / C++. Compile the .so Link with Android SDK / NDK and iOS.
Suggestion 2: "I have some "analyze" code written in JavaScript, so I started looking for options " Move the code to server side, where you will run a node.js and your existing code. Your apps will get a notification with result.
Suggestion 3: Write the real platform specific app finally and use the hardware + OS capabilities fully. The JavaScript purpose it is other then do hard maths.

Cross-mobile background service


Return all relationships

Question: Is it possible to get all relationships in a graph without the nodes?
I'm trying
MATCH [r:MEMBER]
RETURN r

But it gives me the error
Invalid input '[': expected whitespace, comment or a pattern (line 1, column 7 (offset: 6))
"MATCH [r:MEMBER] reTURN r"
       ^

Answer: You need to match a relationship pattern:
MATCH ()-[r:MEMBER]-()
RETURN r

Comment: thought I could just do something similar to `MATCH (n:Node)`
Answer: Since Neo4j's relationships always have a direction, this is the fastest.
MATCH ()-[r:MEMBER]->()
RETURN r

Neo4j's browser will not display a graph, but just return the property maps of the relationships.

Return all relationships


Bash Menu - Return to Main Menu from SubMenu?

Question: I've got a simple Bash Menu here. Everything seems to work great, except I can't figure out how to get back to the Main Menu from my SubMenu. Upon executing the script, I select "3" to go into the "SubMenu" from there, I press "3" again to go back to the "Main Menu" but instead it just keeps showing me the "SubMenu" options.
I tried replacing "break" with "./menu.sh" which is the name of my script, which does seem to work, however, I'm certain that's probably not the most ideal way to handle this issue.
#!/bin/bash
clear

while true
do
clear

echo "######"
echo " Menu"
echo "######"
echo ""

PS3='Select an option: '
options=("Option1" "Option2" "SubMenu" "Exit")

select opt in "${options[@]}"
do
    case $opt in
        "Option1")
            echo Option1
            read -p ""
            break
            ;;
        "Option2")
            echo Option2
            read -p ""
            break
            ;;
        "SubMenu")
            while true
            do
            clear
            echo "#########"
            echo " SubMenu"
            echo "#########"
            echo ""
            PS3='Select an option: '
            options=(
              "SubMenu Option1"
              "SubMenu Option2"
              "Main Menu"
            )
            select opt2 in "${options[@]}"
            do
              case $opt2 in
                  "SubMenu Option1")
                      echo "Sub-Menu Option1"
                      read -p ""
                      break
                      ;;
                  "SubMenu Option2")
                      echo "Sub-Menu Option2"
                      read -p ""
                      break
                      ;;
                    "Main Menu")
                      "./menu"
                      ;;
                  *) echo "invalid option";;
            esac
          done
        done
            ;;
        "Exit")
            exit
            ;;
        *) echo "invalid option"
           ;;
    esac
  done
done

Answer: First of all, break will break out of select. To leave the submenu while loop, you need to break 3 (to leave the inner select, the submenu while, and the outer select).
Type help break for more information.
A short note on your other approach, calling your script again: You should not launch a new child process with each iteration. Bash has an elegant way of "restarting" a program:
exec "$0"

This will execute the given executable (in this case $0 – the current script) in the current process. See the exec() system call for more information or type help exec to read the Bash specifics.
Comment: I was hesitant to make this post as I'm one of those people who HATES asking for help. But I'm so glad that I did because not only did you solve my issue, but you also went above and beyond to give me the tip about restarting my script using exec "$0"

So Thank You very much for this excellent answer. I really appreciate it. =).
Comment: @XenonKilla I know what you mean, glad I could help.
Comment: Michael, I ran across something else I was hoping you might have a solution for. While at the Main Menu, if I type in any value that doesn't exist, I will get an "Invalid Option" prompt. But what I can't figure out is where I can modify the script so that I can change the behavior of when the user just hits "Enter" without typing a value. I want to be able to add the "exec "$0" so that it restarts the script rather than the current behavior of just reprinting the menu on top of the original menu. Any ideas?


Understanding probabilistic neural networks

Question: I would like to understand the basic concepts of probabilistic neural networks better. Unfortunately so far I have not found a resource which answers all the questions I have. So far my understanding and my questions are as follows:

The first layer ("input layer") represents each feature as a node
The next layers are the hidden layers: Here we calculate the distance from the data sample (vector) we want to classify, to the average data vector of each class
"Summation layer": ?? What exactly happens here? Do the hidden layers calculate the distance of the new data vector to each of the training vectors, and the summation layer sums up all the distances for each of the classes..? Or..?
If I understand it correctly, the data from each class is modeled by a gaussian distribution, and the parameters of the gaussians are fit during training. Is it not enough then to calculate the probability of a new vector as coming from either gaussian? How does the distance calculation is important here?

Many thanks
Answer: PNN are easy to understand when taking an example. So let's say I want to classify with a PNN points in 2D and my training points are the blue and red dots in the figure:
I can take as base function a gaussian of variance, say 0.1. There's no training in a PNN as soon as the variance $\sigma$ of the Gaussian is fixed, so we'll now get to the core of your questions with this fixed $\sigma$ (you could of course try to find an optimal $\sigma$...).
So I want to classify this green cross ($x=1.2$, y=$0.8$). What PNN does is the following:

the input layer is the feature vector ($x=1.2$, y=$0.8$);
the hidden layer is composed of six nodes (corresponding to the six training dots) : each node evaluates the gaussian centered at its plot, e.g. if the first node is the blue one at ($x_0=-1.2$, $y_0=-1.1$), then this node evaluates $G_0(x,y)\approx \exp(-((x-x_0)^2 + (y-y_0)^2)/2\sigma^2)$. At the end each of the nodes output the value of his gaussian for the green cross (often you threshold when the value is too low).
the summation layer is composed of $\#(labels)$ nodes. Each real value output of step 2 is sent to the correponding node (the three red node send their values to the summation red node and the three blue nodes send their values to the summation blue node). Each of the label node sums the guassian values they received.
the last node is just a max node that takes all the outputs of the summation nodes and outputs the max, e.g. the label node that had the highest score.

Here you can see that every blue point will have a gaussian (with variance $\sigma=0.1$) equal to 0 whereas the red ones will have quite high values. Then the summation of all the blue gaussians will be 0 (or almost) and the red one high, so the max is red label : the green cross is categorized as red.
As you pointed out, the main task is to find this $\sigma$. There are a lot of techniques and you can find a lot of training strategies on the internet. You have to take a $\sigma$ small enough to capture the locality and not to small otherwise you overfit. You can imagine cross-validating to take the optimal one inside a grid! (Note also that you could assign a different $\sigma_i$ to each label e.g.).
Here's a video which is well done!
Comment: wow one of the best answers I've ever received here - thanks for the explanation, you made everything so clear :-)


Visual studio i think heap error

Question: I am on a project with C++ and WinApi32 . There Are 3 classes , each of them is about 150
lines code .
In my main window , below code will be ran frequently :
<code>wc.cbClsExtra=0;
wc.cbWndExtra=0;
wc.hbrBackground = CreateSolidBrush(BkColor);
wc.hCursor = LoadCursor(NULL,IDC_HAND);
wc.hIcon = NULL;
wc.hInstance = hInstance;
vertex_hInstance = hInstance;
wc.lpfnWndProc = VertexProc;
wc.lpszClassName = Vertex_Class;
wc.lpszMenuName=NULL;
wc.style = CS_HREDRAW|CS_VREDRAW;
RegisterClass(&wc);
hWnd = CreateWindow(Vertex_Class,L"",WS_CHILD|WS_BORDER,getx(),gety(),getw(),geth(),parent_HWND,NULL,hInstance,0);
</code>
It's in a function of a class which I have defined early. Running Program : There is no error , everything is good. Closing Program : gives me error :Windows Has Triggered a Breakpoint, to see picture :
Visit Error
Comment: The image is an arabic (or something like that)
Comment: Why is that code run frequently?  You only need to register that class once...
Comment: @Alf - I opened the page and translated it with google translate - it only makes me upload some file and shows what are the limitations of the file, that I can upload. Nothing else.
Comment: @Alf: Coming from a site in Iran, I suggest it's rather more likely to be Persian than Arabic.
Answer: The code you have shown is not sufficient to say what causes the problem that you describe.
However, you should not register the same window class more than once.
I don't know the effect of "frequently" registering the same window class, because it's just not something that one does (so I have no experience with that), but conceivably it might be gobbling up resources, which in turn might have a very detrimental effect…
The usual solution is register a window class only the first time, or before you create any windows of that class.
E.g. you can use a singleton to achieve this.
Cheers & hth.,

Visual studio i think heap error


What are name and other examples for the type of break/tempo change near the end of "Be our guest"

Question: My 5 year old daughter is obsessed with the new (2017) version of "Beauty and the Beast" and we are listening to the music non stop for weeks and albeit being a musical grouch it really grew on me.
One thing keeps nagging on me though and drives me insane. In the quiet fantastic "Be our guest" even I get a lot of influences from older Big Band Jazz and Broadway tunes. There is one particular sequence near the end of the song where after a chorus crescendo(?) the tempo suddenly winds down and then immediately start rising again with very punctuated vocal and orchestra strikes. Here you can hear the exact piece in question:

I'm absolutely sure I have heard this type of break many times before but I can't find another instance nor do I really know what to look for.
After this long explanation here my actual question. Has this musical construct a name? What are other (famous) songs that use it? In addition I would be thankful for pointers to other musical reference in this song.
Comment: I feel like I've heard that in the Simpsons. Maybe a **Ritardando** followed by an **Accelerando**? Don't know an actual name for the break, but I also feel I heard a quick Perfect Authentic Cadence as well. I'm thinking out loud here
Comment: I don't know the answer. But it is nice to hear some real music featured in contemporary entertainment. +1
Answer: It's for a big kick line finale. Here's an example with choreo:

(The kick line starts at about 3:10)
The score actually calls for a more dramatic slowdown (and speed up afterwards) than they did in the original Broadway run.


Como armazenar vários valores lidos do usuário?

Question: aluno = int(input('Qual o numero de alunos ? '))
for i in range(aluno):
    nota = float(input('Insira a nota de cada um dos alunos: '))

Preciso saber como armazeno as notas dos alunos para somar e dividir pela quantidade de alunos digitados no programa
Comment: Já conhece a estrutura [lista](https://docs.python.org/3.7/tutorial/datastructures.html#more-on-lists) do Python?
Answer: Você pode utilizar uma lista.
notas = []
aluno = int(input('Qual o numero de alunos ? '))
for i in range(aluno):
    nota = float(input('Insira a nota de cada um dos alunos: '))
    notas.append(nota)

E para calcular a média, basta calcular a soma, sum(), e dividir pelo número de notas, len():
media = sum(notas) / len(notas)  # Pode ser "aluno" no lugar do "len"

Ou utilizar o pacote statistics:
from statistics import mean

media = mean(notas)

Veja o código funcionando.


Set back default floating point print precision in C++

Question: I want to control the precision for a double during a comparison, and then come back to default precision, with C++.
I intend to use setPrecision() to set precision. What is then syntax, if any, to set precision back to default?
I am doing something like this
std::setPrecision(math.log10(m_FTOL));

I do some stuff, and I would like to come back to default double comparison right afterwards.
I modified like this, and I still have some errors
std::streamsize prec = std::ios_base::precision();
std::setprecision(cmath::log10(m_FTOL));

with cmath false at compilation, and std::ios_base also false at compilation. Could you help?
Comment: Is your answer [here](http://stackoverflow.com/a/554134/1019491)?
Answer: You can get the precision before you change it, with std::ios_base::precision and then use that to change it back later.
You can see this in action with:
#include <ios>
#include <iostream>
#include <iomanip>

int main (void) {
    double pi = 3.141592653590;

    std::streamsize ss = std::cout.precision();
    std::cout << "Initial precision = " << ss << '\n';

    std::cout << "Value = " << pi << '\n';

    std::cout.precision (10);
    std::cout << "Longer value = " << pi << '\n';

    std::cout.precision (ss);
    std::cout << "Original value = " << pi << '\n';

    std::cout << "Longer and original value = "
        << std::setprecision(10) << pi << ' '
        << std::setprecision(ss) << pi << '\n';

    std::cout << "Original value = " << pi << '\n';

    return 0;
}

which outputs:
Initial precision = 6
Value = 3.14159
Longer value = 3.141592654
Original value = 3.14159
Longer and original value = 3.141592654 3.14159
Original value = 3.14159

The code above shows two ways of setting the precision, first by calling std::cout.precision (N) and second by using a stream manipulator std::setprecision(N).

But you need to keep in mind that the precision is for outputting values via streams, it does not directly affect comparisons of the values themselves with code like:
if (val1 == val2) ...

In other words, even though the output may be 3.14159, the value itself is still the full 3.141592653590 (subject to normal floating point limitations, of course).
If you want to do that, you'll need to check if it's close enough rather than equal, with code such as:
if ((fabs (val1 - val2) < 0.0001) ...

Comment: Should this also work using setprecision() from ? I tried it, and the precision doesn't seem to go back down to the original value after I increase it.
Comment: @Mike, that should work as well, as per my updated answer. Have a read over the changes and, if you still can't get it to work, you may want to open up a question here.
Comment: Is there any difference in how this would work if I'm pushing to ofstream rather than cout? I actually haven't tested it with cout---I'm writing to a file instead. Maybe that's the problem.
Comment: @Mike, no difference, should work exactly the same. In fact, I've just tested that. Replace `` with ``, do `std::ofstream ofs("output.txt", std::ofstream::out);` as first statement of `main`, do `ofs.close();` just before `return`, and change all `std::cout` into `ofs`. The `output.txt` file will then hold exactly what you saw on the screen with the code in the answer.
Comment: @Mike, try to do the same (with my code) on your system and, if you don't get the same results, post a question with your code. You'' get a much wider response that way.
Comment: Thank you, it's working for me now. I was forgetting to replace `std::cout` with the `ofstream` identifier. Thanks a lot!
Comment: @paxdiablo always Quality explanation as usual. Thanks
Answer: Use C++20 std::format and {:.2} instead of std::setprecision
Finally, this will be the superior choice once you can use it:
#include <format>
#include <string>

int main() {
    std::cout << std::format("{:.3} {:.4}\n", 3.1415, 3.1415);
}

Expected output:
3.14 3.145

This will therefore completely overcome the madness of modifying std::cout state.
The existing fmt library implements it for before it gets official support: https://github.com/fmtlib/fmt Install on Ubuntu 22.04:
sudo apt install libfmt-dev

Modify source to replace:

<format> with <fmt/core.h>
std::format to fmt::format

main.cpp
#include <iostream>

#include <fmt/core.h>

int main() {
    std::cout << fmt::format("{:.3} {:.4}\n", 3.1415, 3.1415);
}

and compile and run with:
g++ -std=c++11 -o main.out main.cpp -lfmt
./main.out

Output:
3.14 3.142

See also:

How do I print a double value with full precision using cout?
std::string formatting like sprintf

Pre C++20/fmt::: Save the entire state with std::ios::copyfmt
You might also want to restore the entire previous state with std::ios::copyfmt in these situations, as explained at: Restore the state of std::cout after manipulating it
main.cpp
#include <iomanip>
#include <iostream>

int main() {
    constexpr float pi = 3.14159265359;
    constexpr float e  = 2.71828182846;

    // Sanity check default print.
    std::cout << "default" << std::endl;
    std::cout << pi << std::endl;
    std::cout << e  << std::endl;
    std::cout << std::endl;

    // Change precision format to scientific,
    // and restore default afterwards.
    std::cout << "modified" << std::endl;
    std::ios cout_state(nullptr);
    cout_state.copyfmt(std::cout);
    std::cout << std::setprecision(2);
    std::cout << std::scientific;
    std::cout << pi << std::endl;
    std::cout << e  << std::endl;
    std::cout.copyfmt(cout_state);
    std::cout << std::endl;

    // Check that cout state was restored.
    std::cout << "restored" << std::endl;
    std::cout << pi << std::endl;
    std::cout << e  << std::endl;
    std::cout << std::endl;
}

GitHub upstream.
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

Output:
default
3.14159
2.71828

modified
3.14e+00
2.72e+00

restored
3.14159
2.71828

Tested on Ubuntu 19.04, GCC 8.3.0.
Answer: You need to keep track of your current precison and then reset back to the same once done with your operations with required modified precison. For this you can use std::ios_base::precision:
streamsize precision ( ) const;
streamsize precision ( streamsize prec );

The first syntax returns the value of the current floating-point precision field for the stream.
The second syntax also sets it to a new value.
Answer: setprecision() can be used only for output operations and cannot be used for comparisons
To compare floats say a and b , you have to do it explicitly like this:
  if( abs(a-b) < 1e-6) {
  }
  else {
  }

Answer: You can use cout << setprecision(-1)
Comment: Hm, it works but not documented.


How to perform Poisson regression with known scaling factor for mean at each value of explanary variables in R?

Question: The following webpage shows how to do Poisson regression.
https://stats.idre.ucla.edu/r/dae/poisson-regression/
summary(m1 <- glm(num_awards ~ prog + math, family="poisson", data=p))

The mean of the Poisson distribution is linked with the linear transform (X) of the explanatory variable b (here prog and math) via some function f().
mu = f(X b)
I would like to have a slightly modification to the relation by multiplying a known constant that is dependent on b.
mu = c(b) f(X b)
This should be trivial to do if one had code the regression from scratch. But it is non trivial to customize an existing piece of code that was not designed to do so.
I haven't found a R package that can do this. But I'd expect that somebody might have done it before.
Could anybody let me know whether there is a R function that can do this for Poisson regression?
Answer: Assuming that you wish to use a logarithmic link function (which is the default for what the glm function is implementing here), your proposed linking equation is:
$$\mu_i = c(\boldsymbol{\beta}) \exp(\boldsymbol{\beta}^\text{T} \mathbf{x}_{(i)}),$$
which can also be written as:
$$\log(\mu_i) = h(\boldsymbol{\beta}) + \boldsymbol{\beta}^\text{T} \mathbf{x}_{(i)}
\quad \quad \quad
h \equiv \log c.$$
Since the first term in the regression equation is an unspecified function of the coefficient vector $\boldsymbol{\beta}$, this is a complicated nonlinear model form that is going to have a different estimator for the coefficient.  The log-likelihood function for the model is:
$$\begin{align}
\ell_{\mathbf{y}, \mathbf{x}}(\boldsymbol{\beta})
&= \sum_{i=1}^n \log \text{Pois}(y_i | \mu_i) \\[6pt]
&= \sum_{i=1}^n \log \text{Pois}(y_i | \exp(h(\boldsymbol{\beta}) + \boldsymbol{\beta}^\text{T} \mathbf{x}_{(i)})) \\[6pt]
&= \sum_{i=1}^n y_i [h(\boldsymbol{\beta}) + \boldsymbol{\beta}^\text{T} \mathbf{x}_{(i)}] - \sum_{i=1}^n \exp(h(\boldsymbol{\beta}) + \boldsymbol{\beta}^\text{T} \mathbf{x}_{(i)}) + \text{const}. \\[6pt]
\end{align}$$
Assuming that $h$ is differentiable you then have partial derivatives:
$$\begin{align}
\frac{\partial \ell_{\mathbf{y}, \mathbf{x}}}{\partial \beta_k} (\boldsymbol{\beta})
&= \sum_{i=1}^n \bigg( \frac{\partial h}{\partial \beta_k}(\boldsymbol{\beta}) + \mathbf{x}_{(k)} \bigg) \bigg( y_i - \exp(h(\boldsymbol{\beta}) + \boldsymbol{\beta}^\text{T} \mathbf{x}_{(i)}) \bigg), \\[6pt]
\end{align}$$
which lead to an alternative form for the estimated coefficients in the model.
Answer: Poisson regression is usually using the log link (default in R, so the link used with the code example you gave.)  So your function f is the exponential function.  Applying that to mu = c(b) f(X b), we obtain log(mu) = log(c(b))+ X b, so that first term have the form off an offset, a known term included in the linear predictor.
The difference here is that this "known" constant depends on b, but in a known way. That cannot be estimated with the glm function, but in principle it can be done the same way. In each iteration of the IRLS algorithm used for estimation. In each iteration there is a provisional value of b, and that value can be used to adjust the offset term for the next iteration.
I cannot find an R package that does this, but you can probably write it yourself, piecing together calls to model.matrix, glm.fit and glm.control, the last have a maxit argument you can use.
Comment: Since the term being added is a function of the parameter, it is not known, so I don't think it's an offset --- please have a look at other answer and see what you think.


How to pass multiple selected checkbox from one page to another?

Question: How to pass multiple selected checkbox from one page to another? I am a beginner, sorry for that. Thank you in advance for those who'll help me out with this problem.
Comment: you can do with `php` or `ajax` choice is your
Answer: You can pass data from one page to another through :

SESSION
COOKIE
GET and POST

<form method="post" action="page2.php">
   <input type="hidden" name="var1" value="value1">
   <input type="submit">
</form>

page2.php

<select>
<option value="value1" <?php if($_POST['var1'] == 'value1'){ ?><?php selected ?>>value1</option>
<option value="value1" <?php if($_POST['var1'] == 'value2'){ ?><?php selected ?>>value2</option>
<option value="value1" <?php if($_POST['var1'] == 'value3'){ ?><?php selected ?>>value3</option>
</select>


What is the relationship between $[\Sigma X, Y]$ and $[X \times I, Y]$?

Question: If $X,Y$ are pointed spaces in $\text{hTop}_*$, then what is the relationship between $[\Sigma X, Y]$ and $[X \times I, Y]$, where $\Sigma$ means the reduced suspension and the brackets mean the set of all continuous functions from $()$ to $()$?
Indication suggests that there's a bijection between them but I can't see how this could be since quotient spaces aren't in one-to-one correspondence to the spaces they're derived from.
Comment: Instead of all continuous functions, the brackets denote the set of pointed continuous functions modulo pointed homotopy (i.e. base-point preserving homotopy classes of maps).
Answer: As $X\times I$ is homotopy equivalent to $X$ relative basepoints, $[X\times I, Y] = [X, Y]$. There is a natural map $i : X \to \Sigma X$, given by $x \mapsto [(x, \frac{1}{2})]$, which induces a map $[\Sigma X, Y] \to [X, Y]$ given by precomposition with $i$. However, there is no stronger relation between the two. For example, if $X = S^n$, then $[X\times I, Y] = \pi_n(Y)$ and $[\Sigma X, Y] = \pi_{n+1}(Y)$. In particular, the map $[\Sigma X, Y] \to [X, Y]$ need not be injective nor surjective.
Comment: I just want to include $X$ as a slice in the cylinder, but not at the bottom or top as the bottom and top are crushed to points when forming the suspension.
Comment: So say that $\tau : [\Sigma X, Y] \rightarrow [X, \Omega Y]$ is a bijection via $[F] \mapsto [F^{\text{#}}]$.  Then since $F^{\text{#}}: X \rightarrow \Omega Y$ we should have $F : X \times I \rightarrow Y$ but we have $F : \Sigma X \rightarrow Y$.  But since there's no particular relationship between $[X \times I, Y]$ and $[\Sigma X, Y]$ how can this bijecton be justified?
Comment: How can there be an inclusion $i:X \rightarrow \Sigma X$?  If $\Sigma X = X \times I / ( X \times \dot I \cup \{x_0\} \times I)$ then isn't $X$ not a subset of $\Sigma X$ and therefore is not an inclusion?
Comment: @OliverG: I mean the map $X \to X\times I$, $x \mapsto (x, \frac{1}{2})$ composed with the quotient map. As for your first comment, how is $F^{\#}$ defined?
Comment: Why is the map $f:X \rightarrow X \times I$ by $x \mapsto (x, \frac{1}{2})$ defined with $\frac{1}{2}$ particularly?  And what map is $f$ replacing in your answer?
Comment: And $F^{\text{#}}$ is defined by $F^{\text{#}}: X \rightarrow \Omega Y$ as the associate function of $F$, but the trouble lies in the fact that $F$ shouldn't have an associate function since it's a map from $\Sigma X$ to $Y$ and not a map $X \times I$ to $Y$.
Comment: I don't know what you mean by the associate function. Maybe you should ask a new question.
Comment: From Rotman's Algebraic Topology with $X,Y,Z$ sets:

If $F : Z \times Y \rightarrow X$ is a function, then its associate is the function $F^\text{#}:Z \rightarrow \text{Hom}(Y,X)$ defined by $F^\text{#}(z)=F_z$ (where $F_z: y \rightarrow F(z,y)$)


want to make user-login before view contain

Question: i am making a online tutorial site where a user can view can different contain but i want then to go through login.
For example: you have a home page. after login, user get redirected to the video page. but i dont want to display video page at the homepage.
Comment: Do you want to protect the content from someone getting to it without logging in? Or just a simple redirect after login?
Answer: you can go for LoginToboggan module .
<code> The LoginToboggan module offers several modifications of the Drupal login system
 in an external module.

    Allow users to login using either their username OR their e-mail address.

    Allow users to login immediately.

    Provide a login form on Access Denied pages for non-logged-in (anonymous) users.

    Customize the registration form with two e-mail fields to ensure accuracy.

    Optionally redirect the user to a specific page when using the 'immediate login' feature.

    Optionally redirect the user to a specific page upon validation of their e-mail address.

    Optionally display a user message indicating a successful login.

    Optionally combine both the login and registration form on one page.
</code>


Can we add user into group by editing group file in /etc folder

Question: I would like to add a user(sachin) into a group(mqm). I would like add user by editing group file. Is it okay to add user name by editing group file like below
mqm:x:1000:clasic,gtcj,fgmmin,fddmin,sachin

when i fire command groups sachin i am getting output like below.
sachin : unix-sachin-g mqm

So adding user id sachin into mqm group is done ?
Comment: I'd recommend you use something like `usermod(8)`. Safer than messing with system files by hand.
Comment: @Noufal Ibrahim :Yes i understand, but i have already done this. So I just want to confirm if it works or not. Is it added or not
Answer: Yes it's ok to add user to /etc/group directly, but the common way is to use something like usermod:
sudo usermod -a -G mqm sachin

Note, group membership changes do not take effect for current user login sessions, requiring the user to reconnect to be affected by the changes.
Comment: How to add if user is not there on that server?
Comment: Sorry, what do you mean? The usermod and similar operates only on local passwd and group files, so the user should exist on this server, and if authentication is provided through, for example, LDAP, then groups should be configured there.


Will existing expat related questions from Travel.SE get migrated?

Question: There are some topics that were not closed on Travel.SE, but clearly belong here. For example questions related to H-1B visas, J-1 visas etc.
Are there any plans to migrate these topics or individual questions to Expats.SE?
Answer: Presumably we'd need to get the Travel.SE mods involved, as they'd be the ones to do it. If they believe them to be on topic on Travel.SE, then there's no reason to migrate them.
Answer: Out of the 12 questions you link to, 10 are definitely on-topic on Travel. They aren't going to be migrated here just because they also may be on-topic here (and even that part isn't clear for all of them).
Only questions that are off-topic where they are (or at least borderline, and clearly on-topic elsewhere) may be migrated elsewhere.
Answer: To the best of my knowledge this wasn't done elsewhere in StackExchange.  Stackoverflow still have old UNIX, Magento, Ubuntu questions even though they may not be related to programming within those environments.
So I don't see a reason to migrate the questions out of travel.SE that existed prior to the existence of this site.
Comment: I think migrating ones that got closed on travel for being off topic should still be on the table though. They might finally get answers.
Answer: There's no reason to send them over here - there's not much for folks here to do with them other than notice that they exist. We strongly discourage 'bucketing' of content simply for the sake of it, or for content generation.
We have no problems when it comes to generating our own great questions, so we don't really need them. Additionally, it usually ends up with just a bunch of gray 'anonymous' faces attached to the posts.
If you think a great question was asked there that would be nice to have here, then put your own spin on it and just ask it here, let this community answer it and make it your own.
Additionally, mods on any site can't migrate questions over 3 months old. The migration system is in place to give the question author a better experience. Please don't migrate things when it's doubtful that the person that wrote the question has any interest in it any longer.
For new stuff, yes, the mods on both sites can work that out. If it's a week or less old, then we might just get a new contributor along with a great question, so it's a clear win. Otherwise, it's more of an archival thing, and not really all that helpful.
Comment: It's 60 days, not 3 months. (Also, that's a stupid rule: the criterion should be topicality, not age.)


How to get substring from a part of string while searching from the back

Question: I have a string with code from another JAVA class and i am extracting Doc comments. I have a string with the following content:
"public static String[] scanread() throws Exception{"

I need to get the "scanread()" how can i extract that? I was hoping something that looks for ")" and continues reading right to left until it reaches white space, then extracts it. I am not too sure how would i do that.
Also with this i am worried if there is a space between "scanread" and "()" that might not work.
Any help would be awesome.
Thanks
Comment: With a Java code parser.
Answer: Use the below regex along with Pattern and Matcher classes.
"\\S+\\)"

OR
"\\S+\\s*\\(\\)"

\S+ matches one or more non-space characters , so this matches all the non-space characters which exists before to ) bracket, including the bracket.
DEMO
String s = "public static String[] scanread() throws Exception{";
Matcher m = Pattern.compile("\\S+\\)").matcher(s);
while(m.find()){
System.out.println(m.group());
}

Output:
scanread()

Comment: or `"\\S+\\s*\\([^()]*\\)"`
Comment: `\\(([^)]*)\\)` use this regex and get the part you want from group index 1.
Comment: This seems to work so far, but it doesn't work if there is a whitespace between scanread and (). Is there a way to bypass that?
Comment: This has been a great help! If i may ask so, lets assume there is random stuff inside the ( ) arguments and such. Is there a way to select that too as it can have any number of spaces or any number/types of characters? for example: "scanread(String a, int z, String[] b)"


D3.js bug on Android vs iOS

Question: If you try going to this animated bezier curve D3.js animation website (https://www.jasondavies.com/animated-bezier/), you can move the control points to change the trajectory of the curve. This works if you go to the website with iOS but you cannot move the control points on Android. Does anyone know why this is? Maybe a bug or implementation shortcoming for Android's WebView?
I'm trying to figure out if programming with Phonegap/Cordova is worth it and things like this make me think that the technology is not mature yet...
Comment: The issue you will have with hybrid apps is that all webviews are non-standard and (until recently) do not update independently from the OS. This is not a Cordova issue, this is a general issue with hybrid dev.
Comment: Yes, that's correct. But at the end of the day, this breaks the app for the user. Bugs like this could be real "gotchas" against hybrid dev in general, including Cordova.
Comment: try the crosswalk plugin to get a good webview based on chromium for all android devices, android webview isn't very good on devices below 4.4
Comment: I'm on Android 5.0.1 and the bug is still there. There's another bug in that if I try to click a control point too much, one of the control points disappears and the app breaks even more because there is no longer any curve at all :(
Answer: I found a cause of this problem is compatibility of the drag event with touch screen, and it is fixed in D3.js v3. Here shows a demo snippet mirroring the website, and the only change is loading a newer version of D3.js.
Since I'm using an emulator and only changing a specific little part without examining how the website actually works, this answer may not fully covering your problem.

var w = 250,
    h = 300,
    t = .5,
    delta = .01,
    padding = 10,
    points = [{x: 10, y: 250}, {x: 0, y: 0}, {x: 100, y: 0}, {x: 200, y: 250}, {x: 225, y: 125}],
    bezier = {},
    line = d3.svg.line().x(x).y(y),
    n = 4,
    stroke = d3.scale.category20b(),
    orders = d3.range(2, n + 2);

var vis = d3.select("#vis").selectAll("svg")
    .data(orders)
  .enter().append("svg")
    .attr("width", w + 2 * padding)
    .attr("height", h + 2 * padding)
  .append("g")
    .attr("transform", "translate(" + padding + "," + padding + ")");

update();

vis.selectAll("circle.control")
    .data(function(d) { return points.slice(0, d) })
  .enter().append("circle")
    .attr("class", "control")
    .attr("r", 7)
    .attr("cx", x)
    .attr("cy", y)
    .call(d3.behavior.drag()
      .on("dragstart", function(d) {
        this.__origin__ = [d.x, d.y];
      })
      .on("drag", function(d) {
        d.x = Math.min(w, Math.max(0, this.__origin__[0] += d3.event.dx));
        d.y = Math.min(h, Math.max(0, this.__origin__[1] += d3.event.dy));
        bezier = {};
        update();
        vis.selectAll("circle.control")
          .attr("cx", x)
          .attr("cy", y);
      })
      .on("dragend", function() {
        delete this.__origin__;
      }));

vis.append("text")
  .attr("class", "t")
  .attr("x", w / 2)
  .attr("y", h)
  .attr("text-anchor", "middle");

vis.selectAll("text.controltext")
    .data(function(d) { return points.slice(0, d); })
  .enter().append("text")
    .attr("class", "controltext")
    .attr("dx", "10px")
    .attr("dy", ".4em")
    .text(function(d, i) { return "P" + i });

var last = 0;
d3.timer(function(elapsed) {
  t = (t + (elapsed - last) / 5000) % 1;
  last = elapsed;
  update();
});

function update() {
  var interpolation = vis.selectAll("g")
      .data(function(d) { return getLevels(d, t); });
  interpolation.enter().append("g")
      .style("fill", colour)
      .style("stroke", colour);

  var circle = interpolation.selectAll("circle")
      .data(Object);
  circle.enter().append("circle")
      .attr("r", 4);
  circle
      .attr("cx", x)
      .attr("cy", y);

  var path = interpolation.selectAll("path")
      .data(function(d) { return [d]; });
  path.enter().append("path")
      .attr("class", "line")
      .attr("d", line);
  path.attr("d", line);

  var curve = vis.selectAll("path.curve")
      .data(getCurve);
  curve.enter().append("path")
      .attr("class", "curve");
  curve.attr("d", line);

  vis.selectAll("text.controltext")
      .attr("x", x)
      .attr("y", y);
  vis.selectAll("text.t")
      .text("t=" + t.toFixed(2));
}

function interpolate(d, p) {
  if (arguments.length < 2) p = t;
  var r = [];
  for (var i=1; i<d.length; i++) {
    var d0 = d[i-1], d1 = d[i];
    r.push({x: d0.x + (d1.x - d0.x) * p, y: d0.y + (d1.y - d0.y) * p});
  }
  return r;
}

function getLevels(d, t_) {
  if (arguments.length < 2) t_ = t;
  var x = [points.slice(0, d)];
  for (var i=1; i<d; i++) {
    x.push(interpolate(x[x.length-1], t_));
  }
  return x;
}

function getCurve(d) {
  var curve = bezier[d];
  if (!curve) {
    curve = bezier[d] = [];
    for (var t_=0; t_<=1; t_+=delta) {
      var x = getLevels(d, t_);
      curve.push(x[x.length-1][0]);
    }
  }
  return [curve.slice(0, t / delta + 1)];
}

function x(d) { return d.x; }
function y(d) { return d.y; }
function colour(d, i) {
  stroke(-i);
  return d.length > 1 ? stroke(i) : "red";
}
body{font-size:1em;font-weight:400;word-spacing:normal;letter-spacing:normal;text-transform:none;font-family:Verdana, Myriad Web, Syntax, sans-serif;font-size-adjust:.58;color:#000;background:#FFF;line-height:1.58em;border-top:0;border-left:0;border-bottom:0;border-right:0;width:auto;margin:1.58em 5% 1.58em 8%;padding:0}small{font-size:.92em}big{font-size:1.17em}pre{font-family:Monotype.com, Courier New, monospace;border-top:0;border-bottom:0;line-height:1.25em;border-left:0;border-right:0;margin:.75em 0;padding:0}ol li{list-style-type:decimal}ol ol li{list-style-type:lower-alpha}ol ol ol li{list-style-type:lower-roman}table,tbody,tr,td{font-size:1em;word-spacing:normal;letter-spacing:normal;text-transform:none;font-family:Verdana, Myriad Web, Syntax, sans-serif;font-size-adjust:.58}h1{font-family:Myriad Web, Arial, Helvetica, sans-serif;font-size-adjust:.48;font-size:2em;font-weight:700;font-style:normal;text-decoration:none;word-spacing:normal;letter-spacing:normal;text-transform:none;border-top:0;border-bottom:0;border-left:0;border-right:0;text-align:left;margin:1.33em 0 .33em;padding:0}h2{font-family:Myriad Web, Arial, Helvetica, sans-serif;font-size-adjust:.48;font-size:1.75em;font-weight:500;font-style:normal;text-decoration:none;word-spacing:normal;letter-spacing:normal;text-transform:none;border-top:0;border-bottom:0;border-left:0;border-right:0;text-align:left;margin:1.75em 0 .33em;padding:0}h3{font-family:Myriad Web, Arial, Helvetica, sans-serif;font-size-adjust:.48;font-size:1.58em;font-weight:500;font-style:normal;text-decoration:none;word-spacing:normal;letter-spacing:normal;text-transform:none;border-top:0;border-bottom:0;border-left:0;border-right:0;text-align:left;margin:1.58em 0 .33em;padding:0}h4{font-family:Myriad Web, Arial, Helvetica, sans-serif;font-size-adjust:.48;font-size:1.33em;font-weight:500;font-style:oblique;text-decoration:none;word-spacing:normal;letter-spacing:normal;text-transform:none;border-top:0;border-bottom:0;border-left:0;border-right:0;text-align:left;margin:1.33em 0 .33em;padding:0}h5,dt{font-family:Myriad Web, Arial, Helvetica, sans-serif;font-size-adjust:.48;font-size:1.17em;font-weight:500;font-style:normal;text-decoration:none;word-spacing:normal;letter-spacing:normal;text-transform:none}h6{font-family:Myriad Web, Arial, Helvetica, sans-serif;font-size-adjust:.48;font-size:1em;font-weight:500;font-style:normal;text-decoration:none;word-spacing:normal;letter-spacing:normal;text-transform:none;border-top:0;border-bottom:0;border-left:0;border-right:0;text-align:left;margin:1em 0 .33em;padding:0}tfoot,thead{font-size:1em;word-spacing:normal;letter-spacing:normal;text-transform:none;font-family:Myriad Web, Arial, Helvetica, sans-serif;font-size-adjust:.48}th{vertical-align:baseline;font-size:1em;font-weight:700;word-spacing:normal;letter-spacing:normal;text-transform:none;font-family:Myriad Web, Arial, Helvetica, sans-serif;font-size-adjust:.48;text-align:left}hr{visibility:visible;color:#000;border-top:0;border-bottom:0;height:1px;border-left:0;border-right:0;text-align:left;width:100%;margin:.75em 0;padding:0}a,address,blockquote,body,cite,code,dd,del,dfn,div,dl,dt,form,h1,h2,h3,h4,h5,h6,iframe,img,kbd,li,object,ol,p,q,samp,small,span,strong,ul,var,applet,big,center,dir,font,hr,menu,pre,abbr,acronym,bdo,button,fieldset,ins,label{word-spacing:normal;letter-spacing:normal;text-transform:none;text-decoration:none;border-color:#000;border-style:none}strong{font-style:italic;background:#FFF;font-weight:700;color:#000}em strong,strong em{text-transform:uppercase;font-style:normal;font-weight:bolder;background:#FFF;color:red}b{font-weight:700}.warning{text-transform:none;font-style:normal;font-weight:bolder;background:#FFF;color:red}del{text-decoration:line-through;background:#F66}ins{text-decoration:underline;background:#FF0}address{font-style:normal;letter-spacing:.1em;border-top:0;border-bottom:0;border-left:0;border-right:0;margin:1.58em 0;padding:0}acronym{font-variant:small-caps;letter-spacing:.1em}h1,h2,h3,h4,h5,h6,dt,th,thead,tfoot{color:#000;background:#FFF}#colophon{display:none}col,colgroup,table,tbody,td,tr{color:#000;text-decoration:none;background:#FFF;border-color:#000;border-style:none}a:link{text-decoration:none;font-weight:700;color:#C00;background:#ffc}a:visited{text-decoration:none;font-weight:700;color:#999;background:#ffc}a:active{text-decoration:none;font-weight:700;color:red;background:#FC0}a:hover{text-decoration:none;color:#C00;background:#FC0}a.offsite{text-decoration:none;font-weight:400;color:#C00;background:#ffc}a,address,blockquote,cite,code,dd,del,dfn,div,dl,dt,em,form,h1,h2,h3,h4,h5,h6,iframe,img,kbd,li,object,ol,p,q,samp,small,span,strong,ul,var,applet,b,big,center,dir,font,hr,i,menu,pre,s,strike,tt,u,abbr,acronym,bdo,button,fieldset,ins,label{border-top:0;border-bottom:0;vertical-align:baseline;border-left:0;border-right:0;text-align:left;float:none;clear:none;list-style-position:outside;margin:0;padding:0}h5{border-top:0;border-bottom:0;border-left:0;border-right:0;text-align:left;margin:1.17em 0 .33em;padding:0}p{border-top:0;border-bottom:0;border-left:0;border-right:0;text-indent:0;margin:.75em 0;padding:0}dd{border-top:0;border-bottom:0;border-left:0;border-right:0;margin:0 0 .75em 1.58em;padding:0}li{border-top:0;border-bottom:0;border-left:0;border-right:0;margin:0 0 0 3.16em;padding:0}div,center{margin-top:0;margin-bottom:0;padding-top:0;padding-bottom:0;border-top:0;border-bottom:0}.stb{margin-top:2.17em;margin-bottom:.75em;padding-top:2.17em;padding-bottom:0;border-top:0;border-bottom:0;border-style:solid}.mtb{margin-top:3.08em;margin-bottom:.75em;padding-top:3.08em;padding-bottom:0;border-top:.1em;border-bottom:0;border-style:solid}.ltb{margin-top:4.34em;margin-bottom:.75em;padding-top:4.34em;padding-bottom:0;border-top:.25em;border-bottom:0;border-style:solid}col,colgroup,table,tbody,td,tfoot,th,thead,tr{border-top:0;border-bottom:0;border-left:0;border-right:0;float:none;clear:none;margin:0;padding:0}address,blockquote,dl,fieldset,form,ol,p,ul,dir,hr,menu,pre{margin-left:0;margin-right:0;padding-left:0;padding-right:0;border-left:0;border-right:0}blockquote{margin-left:1.58em;margin-right:0;padding-left:0;padding-right:0;border-left:0;border-right:0}center{margin-left:0;margin-right:0;padding-left:0;padding-right:0;border-left:0;border-right:0;text-align:left}i,var,cite,dfn,.note{font-style:italic}div > p:first-child,body > p:first-child,td > p:first-child,h1 + p,h2 + p,h3 + p,h4 + p,h5 + p,h6 + p,div + p,p.initial{border-top:0;border-bottom:0;border-left:0;border-right:0;text-align:left;text-indent:0;margin:.75em 0;padding:0}h1,h2,h3,h4,h5,h6,td,th{line-height:1.33em}blockquote,fieldset,form,ul,ol,dl,dir,menu,.subhead{margin-top:.75em;margin-bottom:.75em;padding-top:0;padding-bottom:0;border-top:0;border-bottom:0}dt,ul ul,ol ol,li address,li dl,li ol,li p,li ul,li dir,li hr,li menu,li pre,li h1,li h2,li h3,li h4,li h5,li h6,dd address,dd dl,dd ol,dd p,dd ul,dd dir,dd hr,dd menu,dd pre,dd h1,dd h2,dd h3,dd h4,dd h5,dd h6{border-top:0;border-bottom:0;border-left:0;border-right:0;margin:0;padding:0}table,td,caption{text-align:left}
#adsense {
  margin-top: 1em;
}

<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Animated Bézier Curves - Jason Davies</title>
    <link rel="stylesheet" href="../media/style.css">

    <meta name="author" content="Jason Davies">

Animated Bézier Curves

Play with the control points to modify the curves!

    These animations illustrate how a parametric Bézier curve is constructed.
    The parameter t ranges from 0 to 1.
    In the simplest case, a first-order Bézier curve, the curve is a straight line between the control points.

    For a second-order or quadratic Bézier curve, first we find two intermediate points that are t along the lines between the three control points.
    Then we perform the same interpolation step again and find another point that is t along the line between those two intermediate points.
    Plotting this last point yields a quadratic Bézier curve.
    The same steps can be repeated for higher orders.

    Written using the D3 visualisation library.
    Suggested by Mike Bostock and inspired by a similar animation on Wikipedia.

Requires a SVG-capable browser e.g. Mozilla Firefox, WebKit (Google Chrome, Safari &c.) or Internet Explorer 9+.

© Jason Davies | Privacy Policy.

D3.js bug on Android vs iOS


How to combine two different type variables?

Question: I have two functions, the body is exactly same, only the parameter is different:
int setCustomerUser(struct userCustomer *user, struct profile *data) {
        user->type = data->type;
        // ....  A
}

int setAdminUser(struct userAdmin *user, struct profile *data) {
        user->type = data->type;
        // ....  B
}

A and B are same.
userCustomer and userAdmin are basically same, except some different.
struct userCustomer {
    int type;
    char *name;
    char *mail;

    int gender;
    char *address;
    int point;
    // ....
}

struct userAdmin {
    int type;
    char *name;
    char *mail;

    int dept;
    // ....
}

So I would like to combine the two functions into one, something like this:
int setUser(void *user1, struct profile *data, int userType) {
        if(userType == 0) {
                struct userCustomer *user = (struct userCustomer *)user1;
        } else {
                struct userAdmin *user = (struct userAdmin *)user1;
        }

        user->type = data->type;
        // ...
}

But as you know C is not Python, it does not work. How can I achieve this?
Comment: What's the `struct` definition for both? What other things are done inside that function?
Comment: Updated, other things inside the function are exactly same: set common vars
Comment: This might be a case for a macro.
Comment: What do you mean it doesn't work? What error message or output do you get?
Comment: Does `A, B` access `user->` in any way?
Answer: Extract the common fields into a common struct.
struct userCommon {
    int type;
    char *name;
    char *mail;
};

struct userCustomer {
    struct userCommon c;
    int gender;
    char *address;
    int point;
};

struct userAdmin {
    struct userCommon c;
    int dept;
};

int userCommon_setType(struct userCommon *c, struct profile *data) {
      c->type = data->type;
      return 62;
}

int userCustomer_setType(struct userCustomer *user, struct profile *data) {
      return userCommon_setType(&user->c, data);
}

int userAdmin_setType(struct userCustomer *user, struct profile *data) {
      return userCommon_setType(&user->c, data);
}

Answer: You could use a union member in the struct like this:
struct user {
    int type;
    char *name;
    char *mail;

    union {
        struct {
            int gender;
            char *address;
            int point;
            // ....
        } customer;

        struct {
            int dept;
            // ....
        } admin;
    };
};

To distinguish values of both types, it makes sense to store the "type" right inside the struct. That's what type already does, even though I would use an enum.
You access the common parts like before:
user->type = ...;

And the special part like this (but you probably know this):
user->customer.gender = ...;

user->admin.dept = ...;

Answer: I suggest using the prototype with 2 parameters are 2 struct instead of using userType
The example:
int setUser(userCustomer *user, userAdmin *admin, struct profile *data)
{
    if(user != NULL)
    {
        user->type = data->type;
    }
    if (admin != NULL)
    {
        admin->type = data->type;
    }
            // ...
}


C# ANTLR4 right-associative warning

Question: Given my simple grammar in the C# build target:
grammar Expr;

prog: stmt+ EOF;
stmt: expr NEWLINE+;

expr:
    expr '^' <assoc=right> expr # Power
|   expr ('*'|'/') expr         # Mult
|   expr ('+'|'-') expr         # Add
|   REAL                        # Real
|   '(' expr ')'                # Paren
;

NEWLINE : '\r\n';
REAL     : [0-9]+'.'[0-9]+ ;

I continue to get a C# compiler warning stating that "Warning   1   rule 'expr' contains an 'assoc' terminal option in an unrecognized location"
Can anyone suggest where I'm supposed to indicate right-associativity for exponentials?  This is the way I've seen it done in numerous examples.
Comment: Perhaps this helps:  http://stackoverflow.com/questions/23359363/antlr-4-2-2-output-to-console-warning-157/23359897
Comment: Yes, works perfectly and tests perfectly.  Thank you.   Now, being new to this site, how do I mark help as the answer?  ;)
Comment: Well, it was not an answer but a clue to resolver your problem.  You could add the answer yourself to help other people.  :-)
Answer: The answer is placing the tag hint to the left of the rule, not right after the operator as I've seen in many examples:
expr:
<assoc=right> expr '^'  expr    # Power
|   expr ('*'|'/') expr         # Mult
...
;

Comment: Relevant documentation: https://github.com/antlr/antlr4/blob/master/doc/left-recursion.md

C# ANTLR4 right-associative warning


Execution failed for task ':app:processDebugResources'. in Ionic/Cordova

Question: IONIC INFO
@ionic/cli-utils  : 1.19.1
ionic (Ionic CLI) : 3.19.1

global packages:
cordova (Cordova CLI) : 8.0.0

local packages:
@ionic/app-scripts : 3.1.6
Cordova Platforms  : android 7.0.0 ios 4.5.4
Ionic Framework    : ionic-angular 3.9.2

System:
Node : v7.10.1
npm  : 4.2.0
OS   : Windows 10

Environment Variables:
ANDROID_HOME : not set

Misc:
backend : pro

The following error is occurring
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugResources'.
> Failed to execute aapt

Comment: `ANDROID_HOME : not set` have you set the environment variable?
Comment: I haven't set the environment variable. Will adding it resolve the issue ? @SurajRao
Comment: looks like it.. go through the logs and try
Answer: This seems to be a recent Cordova issue.
Adding this plugin solved the issue in my case:
https://github.com/dpa99c/cordova-android-support-gradle-release


Mongoose - find matching array values

Question: I'm creating a REST API with Node.js using Mongoose to access my backend MongoDB database. I have an array (variations) inside of one of my collections (also variations) and need to retrieve the object in the array that matches a provided value.
So far I've got this which returns an empty value...
//Get variation by ID
app.get('/v1/:id', async (request, response) => {
    try {
        var result = await variationsModel.find({ 'variationID': request.params.id }).exec();
        response.send(result);
    } catch (error) {
        response.status(500).send(error);
    }
})

And here's the model I've defined in the API...
const variationsModel = mongoose.model("variations", {
    "variations": [
        {
        "variationID": String,
        "custID": String,
        "projID": String,
        "variationTitle": String,
        "variationDesc": String,
        "variationStatus": String,
        "variationChargeable": String,
        "variationCost": String,
        "requireMaterial": String,
        "variationRequestor": String,
        "variationCreationDate": String,
        "variationImages": [
            {
            "imageId": String
            }
        ],
        "variationCategory": String
        }
    ]
});

Anyone point me in the right direction?
Thanks!
Answer: The query should be
variationsModel.find({ 'variations.variationID': request.params.id }).exec();

Comment: Course it is! Thanks for your help!

Mongoose - find matching array values


Erro função de enviar e-mail

Question: Estou com o seguinte codigo para mandar um email no delphi, mas ele da um erro (em anexo) no final do codigo após o ultimo end.
Estou usando a versão mais recente do delphi e ele me informa se os begins, try ends estão fechados.
O que pode causar isso?
procedure TForm1.Button1Click(Sender: TObject);
var
  // variáveis e objetos necessários para o envio
  IdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL;
  IdSMTP: TIdSMTP;
  IdMessage: TIdMessage;
  IdText: TIdText;
  sAnexo: string;
begin
  // instanciação dos objetos
  IdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create(Self);
  IdSMTP := TIdSMTP.Create(Self);
  IdMessage := TIdMessage.Create(Self);

  try
    // Configuração do protocolo SSL (TIdSSLIOHandlerSocketOpenSSL)
    IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23;
    IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient;

    // Configuração do servidor SMTP (TIdSMTP)
    IdSMTP.IOHandler := IdSSLIOHandlerSocket;
    IdSMTP.UseTLS := utUseImplicitTLS;
    IdSMTP.AuthType := satDefault;
    IdSMTP.Port := 465;
    IdSMTP.Host := 'smtp.gmail.com';
    IdSMTP.Username := 'firstname.lastname@example.com';
    IdSMTP.Password := 'senha';

    // Configuração da mensagem (TIdMessage)
    IdMessage.From.Address := 'email@example.com';
    IdMessage.From.Name := 'Nome do Remetente';
    IdMessage.ReplyTo.EMailAddresses := IdMessage.From.Address;
    IdMessage.Recipients.Add.Text := 'firstname.lastname@example.com';
    IdMessage.Subject := 'Assunto do e-mail';
    IdMessage.Encoding := meMIME;

    // Configuração do corpo do email (TIdText)
    IdText := TIdText.Create(IdMessage.MessageParts);
    IdText.Body.Add('Corpo do e-mail');
    IdText.ContentType := 'text/plain; charset=iso-8859-1';

    // Opcional - Anexo da mensagem (TIdAttachmentFile)
    sAnexo := 'C:\Anexo.pdf';
    if FileExists(sAnexo) then
    begin
      TIdAttachmentFile.Create(IdMessage.MessageParts, sAnexo);
    end;

    // Conexão e autenticação
    try
      IdSMTP.Connect;
      IdSMTP.Authenticate;
    except
      on E:Exception do
      begin
        MessageDlg('Erro na conexão ou autenticação: ' +
          E.Message, mtWarning, [mbOK], 0);
        Exit;
      end;
    end;

    // Envio da mensagem
    try
      IdSMTP.Send(IdMessage);
      MessageDlg('Mensagem enviada com sucesso!', mtInformation, [mbOK], 0);
    except
      On E:Exception do
      begin
        MessageDlg('Erro ao enviar a mensagem: ' +
          E.Message, mtWarning, [mbOK], 0);
      end;
    end;
  finally
    // desconecta do servidor
    IdSMTP.Disconnect;
    // liberação da DLL
    UnLoadOpenSSLLibrary;
    // liberação dos objetos da memória
    FreeAndNil(IdMessage);
    FreeAndNil(IdSSLIOHandlerSocket);
    FreeAndNil(IdSMTP);
  end;
end;

end.

Comment: Como estão as clausulas Uses de sua Unit?
Answer: Clique após o end. e Pressione simultaneamente as teclas CRTL+SHIT+T e pressione a tecla DELETE.
Segure CTRL e aperte 9 e veja se deu algo!
\win32\Debug\unit1.DCU
Remove essa unit unit1 do projeto (Project -> Remove from project) e adiciona novamente(Project -> Add to project).
A IDE não conseguiu criar este arquivo que faz parte de seu projeto (Se estiver usando Windows 8(ou superior), verifique as permissões de Pasta de onde o seu projeto esta sendo Compilado!), acesse a pasta e crie manualmente o arquivo mencionado!
Comment: A solução foi remover a unit e adiconar.

Erro função de enviar e-mail


20 % of patients are female. Is that enough to include it as a factor?

Question: About 18 % of the patients in a study are females. Is that enough for us to use Gender as a factor?
More generally, how does one decide whether there are enough observations such that the factor should be included?
What if it was only 10 %? 5 ? 2?
Answer:
More generally, how does one decide whether there are enough observations such that the factor should be included?
What if it was only 10 %? 5 ? 2?

It depends on everything from the sample size, to how much you expect a priori for the feature to be important, to how many other features are in the model, to how variable the dependent variable is, to the purpose of the model.
In general, if a feature is almost always constant, you should remove it. If you're in doubt (and it's not so close to being constant that it threatens identifiability), use your favorite model-selection method to decide.


Golang cmd.Output() of exec.Command() throws error in systemd service (ubuntu)

Question: I have a go binary that gets display information using cmd := exec.Command("xdpyinfo") then calling cmd.Output().
The program runs as expected in the terminal. However, when I run this as a systemd service there's no output from cmd.Output().
I'm program is running as a service, but calling cmd.Output() is returning an error.
I've tried to make this as easy to reproduce as possible:
I have a executable go binary named test at /home/myusername/Projects/test
The binary was built using go build from a single main.go file containing the following code:
package main

import (
        "fmt"
        "log"
        "log/syslog"
        "os/exec"
)

func main() {
        logwriter, e := syslog.New(syslog.LOG_NOTICE, "testprog")
        if e == nil {
                log.SetOutput(logwriter)
        }

        cmd := exec.Command("xdpyinfo")

        out, err := cmd.Output()
        if err != nil {
                log.Print(fmt.Errorf("ERROR: %v", err))
        }

        log.Print(string(out))
}

The logging is just for test purposes as the real code is part of a larger app.
When I run the test binary in the terminal I see the expected output from xdpyinfo in the logs.
However, when try to run the same binary in a service it outputs ERROR: exit status 1.
Steps I took to run the service:

Create a unit service file at /etc/systemd/system/TestProg.service:

[Unit]
Description=Test service
ConditionPathExists=/home/myusername/Projects/test/test
After=network.target

[Service]
Type=simple

Restart=on-failure
RestartSec=10
startLimitIntervalSec=60

WorkingDirectory=/home/myusername/Projects/test
ExecStart=/home/myusername/Projects/test/test

[Install]
WantedBy=multi-user.target

Enable the service:

sudo systemctl enable TestProg.service

Start the service:

sudo systemctl start TestProg.service
I've also tried locating the unit service file at /lib/systemd/system/TestProg.service and adding the User=username under Type=simple.
I've tried several different configurations to try and get this working. I've also tried setting the user using SysProcAttr (with actual uid and gid):
cmd := exec.Command("xdpyinfo")

cmd.SysProcAttr = &syscall.SysProcAttr{
  Credential: &syscall.Credential{
    Uid:         uint32(uid),
    Gid:         uint32(gid),
    NoSetGroups: true,
  },
}

out, err := cmd.Output()
if err != nil {
        log.Print(fmt.Errorf("ERROR: %v", err))
}

I'm now starting to think I'm missing something more fundamental.
Comment: Try cmd, err := exec.Command("xdpyinfo").Output(). Can't see any obvious issues.
Answer: You have to run it in your user session (which also started you X11 session):
systemd-run --user -t  xdpyinfo |head
Running as unit: run-u1614.service
Press ^] three times within 1s to disconnect TTY.
name of display:    :0
version number:    11.0
vendor string:    The X.Org Foundation

You exampe without golang:
sudo systemd-run -t  xdpyinfo
Running as unit: run-u2876.service
Press ^] three times within 1s to disconnect TTY.
/usr/bin/xdpyinfo:  unable to open display "".


Common application property file for multiple microservice

Question: I want to use a common application properties file for multiple microservices which will have some common configuration like DB Source config etc..I have use the config Server with Eureka server and zull Proxy.
Issue:
When using configServer we need to provide the spring.application.name = 'xyz'
which in turn find the xyz.properties for this microservice configuration.
The same way when we register the service with zuul proxy also need the same application name for configure the service path as zuul.routes.xyz.path = /iii/*.
Now I want that multiple service will share the same property file(xyz.properties) but need to register the zuul route as well so I have to provide the different name for each service. If I will provide the different name to each service they will not be able to locate the same property file.
I am new to spring boot micro services.
Comment: As part of spring cloud config, it is possible to provide multiple config names. ex. xyz.properties, common.properties. configure spring.config.client.name=xyz,common. Now you can use common as part of any service
Comment: @Barath.. I have commented the spring.application.name=xyz and add  spring.config.client.name=xyz,common... Now application is not getting up as it is not able to find the start-up properties(DB property)..
Comment: Possible to share your project?
Comment: I shared an example here [multiple-config-client](https://github.com/BarathArivazhagan/spring-cloud-multiple-config-client)
Comment: Thanks @Barath... Got it...
Answer: spring.config.client.name supports multiple names separated by commas to load the configuration properties.
In this case, store the common properties in common.yml and xyz properties in xyz.yml. Finally, mention spring.cloud.config.name: xyz,common
spring:
  cloud:
    config:
      uri: http://localhost:8888
      name: xyz,common

Output:
Fetching config from server at : http://localhost:8888
Located environment: name=xyz,common, profiles=[default], label=null, version=91edcf96c6a88707bf39014a16ad5d301d6b4575, state=null
Located property source: CompositePropertySource {name='configService', propertySources=[MapPropertySource {name='configClient'}, MapPropertySource {name='https://github.com/BarathArivazhagan/config-server-repository/common.yml'}, MapPropertySource {name='https://github.com/BarathArivazhagan/config-server-repository/xyz.yml'}]}

Answer: I would like to point out that the provided solution leverages the "spring.config.client.name" client side property semantics to achieve a config server behavior of serving properties files from multiple files other than application[-profile].* and {appname}[-profile].*
However, note that for a simple case and considering a root dir, the config server serves properties from files defined in this root dir or under a folder with the name of the application, that the property files under it correspond to, i.e. */{appname}/application[-profile].** or */{appname}/{appname}[-profile].**
The "spring.config.client.name" environment property instructs the config server which application names the requesting app matches with. This means that given a spring.config.client.name=a,b , the config server will assume serving properties defined for app (with name) a and b to the requesting app! This is not the exact same thing as I want my properties been served from file names a and b! Therefore we are abusing the property semantics for managing our config server serving from the file names we would like it to.
However, due to the actual semantics of spring.config.client.name the config server will serve everything applicable from

/a[-profile].*
/b[-profile].*
/a/{applicable names}
/b/{applicable names}

The caveat here is that we achieve what we want only for the root directory and, moreover, if we have a configserver that serves multiple springboot apps we loose the ability to have all our properties under our application's name-folder.
Even worse, if there exists another app (or -attention!- will exist in the future) with the same name as one of our desired property file names, the config server will start serving to our app ALL the configuration defined for that other app!!! This could end up in wrong and even harmful served configuration!
(I repeat it will serve everything applicable under /{other-app-name-that-i-happened-to-use-as-filename-and-defined-it-through-spring.config.client.name}/*!!!)
So beware when pirsuiting this approach!
I have issued a pull request for spring-cloud-config-server 1.4.x, that supports defining additional file names, through a spring.cloud.config.server.searchNames environment property, in the same sense one can do for a single springboot app, as defined in the Externalized Configuration.Application Property Files section of the documentation, using the spring.config.name enviroment property. I hope they review it soon