Has a college team ever played against a professional team?

Question: This question is inspired by the recent debate[1][2][3][4] about whether the 2014-15 University of Kentucky men's basketball team (who had been undefeated until tonight's loss to Wisconsin) could defeat an NBA team.
Has an American college team ever played against an American professional team (either actual teams or all-star teams)?  If so, how did they fare?
Answer: Baseball
There is a long history of college teams playing against MLB teams in spring exhibition games.  This WSJ article has a good description of it:

Such was the unusual spectacle of the Phillies' 6-2 loss to the University of Tampa, a Division II school. It was a sight only possible in Major League Baseball, the lone major U.S. sport with a long-standing tradition of pro teams inviting college teams to play them in preseason exhibitions.
Typically, the college team arrives in the morning, tours the facilities, watches the pros go about their routines—and then gets pummeled. In 67 such games between 2006 and 2014, MLB teams went 63-3-1, combining to outscore the collegians 642-133.
Exhibitions between major-league and college teams date to the 19th century. In 1876, the team then called the Boston Red Stockings, which eventually became the Atlanta Braves, beat Harvard just days before playing the first game in National League history. For all that has changed since then, the purpose of the games for major-league teams has remained largely the same.
They usually play them just before the start of official spring-training games, after a week or two of workouts. By then, players are tired of practice drills, and executives are eager to see players in game situations. "It's a little bit of a warm-up for everybody," Phillies general manager Ruben Amaro Jr. said.

Basketball
In 1992, a team of college stars was formed to help the U.S. men's basketball team (the "Dream Team", with 11 NBA players) prepare for the Summer Olympics.  The team had the following players: Chris Webber (Michigan), Grant Hill (Duke), Bobby Hurley (Duke), Anfernee Hardaway (Memphis State), Allan Houston (Tennessee), Jamal Mashburn (Kentucky), Eric Montross (North Carolina), and Rodney Rogers (Wake Forest).
The college players defeated the Dream Team in their first 20-minute scrimmage by a score of 62-54.  This happened because the NBA players didn't take the college players seriously and hadn't developed any chemistry yet.  In addition, Coach Chuck Daly intentionally used poor strategies and didn't try to win the game because he wanted to deflate the NBA players' egos and show them that they could be beaten.
Here are some interesting quotes regarding that first scrimmage:

Charles Barkley: The first time we saw them, they looked like babies. We were like, "Hey, man, let's don't kill these little kids." And they were playing like it was Game 7. Before we knew it, they upset us.
Karl Malone: We took them for granted, and they kicked our butt.
Michael Jordan: We're so out of sync and so unsure about things that we feel comfortable with in normal situations. We don't have any continuity at all.
Scottie Pippen: These young kids were killing us.  We didn't know how to play with each other.
Bobby Hurley: I think they were searching. They weren't in sync or accustomed to playing as much, which happens when you're putting a team together and trying different combinations of players. [...] When you're playing a lot of guys, players who are used to playing a lot have trouble getting into a rhythm.
Assistant Coach Mike Krzyzewski: Chuck [Daly] wanted them to lose.  [...]  He threw the game.  [...]  If you look at how much Jordan played and how he subbed the guys in, not picking up, not making any adjustments; he knew what he was doing.

The next day the teams had another scrimmage, and the Dream Team destroyed the college players.  Here are some interesting quotes regarding that second scrimmage:

Chris Webber: We didn't score a point. Not one point. Not a point on a free throw, not a point in the game.
Grant Hill: The next day, we couldn't get the ball over half-court.
Bobby Hurley: The court shrank. There weren't opportunities to run, and in the half court we had no offense. [...] They were so long and quick, you couldn't go by them or create anything.  They beat us by 30 points in that next scrimmage, and it could have been more than that. We had 3-4 scrimmages the rest of the week, and all of them had similar outcomes.

Sources: GQ, CBS Sports, Lost Lettermen, NY Times, LA Times
From 2000 to 2003, the Harlem Globetrotters played 22 games against college teams.  The college teams lost 13 of those games (see the full list of results). In 2004, the NCAA banned teams from playing against the Globetrotters.  In 2006, the Globetrotters lost a game to the NABC College All-Stars.  The Globetrotters Wikipedia article mentions some of these games:

Five years later, following another 1,270 wins, they lost 72 to 68 to Michigan State University, the reigning men's collegiate champions, on November 13, 2000.
Two years later, they "set aside the hallmarks" for a "three-week, no-nonsense tour against college teams" from men's Division One. [...] On November 10 and 11 at Vanderbilt University and the University of Maryland, another defending champion, they lost close games to both teams, their first consecutive defeats since 1961. [...] On November 3, 2003, the Globetrotters had a streak of 288 consecutive victories snapped after suffering an 89–88 loss to the UTEP Miners, who had just six victories the season before. It was their only loss during an eight-game college tour wherein the Globetrotters had defeated Michigan State (97–83), UMass (77–68), and defending national champion Syracuse (83–70).
Their most recent loss came on March 31, 2006, when they went down 87–83 to the NABC College All-Stars.

Football
From 1934 through 1976, a preseason match called the Chicago Charities College All-Star Game was always played between the previous season's NFL champion and a team of the previous season's star college seniors.  Forty-two of these games were played, and the college all-star teams won 9 of them, lost 31 of them, and tied 2 of them.


A linear operator always has a cyclic vector

Question: I'm trying to prove that given a linear operator $f$ on $\Bbb{K}^2$, where $\Bbb{K}$ is a field, any non-zero non-eigenvector is a cyclic vector for $f$. Then I'm asked to show show that $f$ either has a cyclic vector or it is a scalar multiple of $I _2$.
Here's what I did for the first part: Since we know $\dim(\Bbb{K}^2)=2$ it suffices to find a linearly independant set with cardinality $2$. Now, let $\mathbf{v}$ be a non-zero vector which is not a characteristic value of $f$ then $f(\mathbf{v})\neq\alpha \mathbf{v}$. This shows that $f(\mathbf{v})\notin <\mathbf{v}>$ hence $\{\mathbf{v},f(\mathbf{v})\}$ is LI.
I don't know what to do in the second part, however I'm guessing that the scalar will be the eigenvalue but what if all the vectors that make $f$ are zero or a zero and an eigenvector( That can't happen right?)
Out of curiosity, this does not hold in $\Bbb{K}^n$ right?
Answer: If $f$ doesn't have a cyclic vector then by what you have already shown we know that every non-zero vector is an eigenvector.  There are two cases:

Every non-zero vector is an eigenvector for the same eigenvalue $\alpha$.  In this case show that $T = \alpha I$
There are non-zero eigenvectors $v$ and $w$, with eigenvalues $\alpha$ and $\beta$, such that $\alpha \neq \beta$.  In this case show that $v + w$ is not an eigenvector, contradicting your assumption.

P.s. The general statement for $\mathbb K^n$ is as follows.  If $\mathbb K$ is algebraically closed then $T\colon\mathbb K^n \to \mathbb K^n$ has a cyclic vector if and only if the minimum polynomial and characteristic polynomial of $T$ are equal.
There are plenty of maps whose minimum and characteristic polynomials are not equal which are not of the form $\alpha I$, so when $n > 2$ the answer is no, it's not true that every $T$ either has a cyclic vector or is of the form $\alpha I$.
Comment: I don't understand "If $f$ doesn't have an eigenvalue then every non-zero vector is an eigenvector". Seems to me that if a linear operator doesn't have an eigenvalue then it doesn't have any eigenvectors, either.
Comment: @GerryMyerson you beat me to it.
Comment: Oops, I meant if $f$ doesn't have a cyclic vector.  I've fixed it.
Comment: @Jim do you by chance know a site which hosts a proof of the last statement so I could read it later when I learn more about field extensions?
Comment: I don't know of a source, when the time comes you could probably prove it yourself without too much effort.


MySQL auto increment does not start at 1

Question: My situation is similar to the one in this question. I am trying to insert value to DogName and set DogId to be auto_increment but it does not start at 1
Dog table
DogId DogName
3     Woofer
4     Kujo
5     Spike

I tried the solution in that question
alter table <tablename> auto_increment = <some_number>;

but did not work. I tried dropping the table and creating it again. But now the DogId starts at 6. Really appreciate any help
Comment: how do you insert data, can you post the insert statement
Comment: mysql keeps deleted ids, if you deleted some items it will continue count next id. the only way is reset id then it will contine with the first id like 1, 2, 3
Answer:
I tried dropping the table and creating it again. But now the DogId
starts at 6. Really appreciate any help

Try TRUNCATE instead.


Redimensionar um MDI Form sem bordas

Question: Já encontrei muitas dicas de como redimensionar um Form sem bordas, todas funcionais e boas, porém não funcionam quando se trata de um MDI Form.
Alguém tem uma dica funcional de como redimensionar um MDI Form?
Desde já meus agradecimentos.
Comment: O que você quer dizer com `MDI Form ` **`sem bordas`**?
Comment: o sem bordas é para o usuário não redimensionar... Se voce esta falando para redimensionar via código ai já é outra coisa.
Comment: Vamos lá amigo, deixa eu te explicar!   Como coloquei "Já encontrei muitas dicas de como redimensionar um Form sem bordas, todas funcionais e boas", sim, sem bordas, mas quanto ao que o usuário faz, é o que permito, então ele poderá redimensionar o form. Tudo funciona bem, porém para trabalhar com form abertos em um TabControl, necessariamente o main form precisa ser MDI, e aí é que está o problema, todos os controles ~de redimencionamento que implementei são desativados. O que preciso saber é como redimencionar um Form MDI, sem bordas, pelas quatro laterais e pelos 4 cantos!
Answer: Não sei se resolvi seu problema pois esta muito confuso sua pergunta...
No construtor do child form, adicione essas linhas de código:
this.Dock = DockStyle.Fill;

No evento Form_Load, Você deve adicionar essa linha de código:
this.WindowState = FormWindowState.Maximized;

Comment: Grato pelo retorno DaniloLoko! Bom vamos ver se eu explico melhor! Tenho um MainForm sem bordas que eu montei segundo minhas necessidades.Em fim, remodelei segundo a interface que eu precisava, inclusive podendo redimenciona-lo. Porém quando abro um form de cadastro, a exemplo, eu abro em um TabPageControl, para isto o MainForm tem que ser um MDI form e passando para MDI form, perde  a possibilidade de redimencionar o MainForm. E quero implementar isto e preciso de ajuda!

Redimensionar um MDI Form sem bordas


Is there a reason why we call $\mathrm{Hom}(A, -)$ covariant and $\mathrm{Hom}(-,B)$ contravariant?

Question: I have trouble remembering what it means to apply the covariant or contravariant Hom functor.
For example, when I see $\mathrm{Hom}(A, -)$, I always forget if I am going to reverse arrows or not.
For example: I used to have trouble remembering what a pushout and pullback was until someone pointed out that pushout diagrams have arrows going forward from the set that is going to dictate the gluing. Now I will never forget what a pushout diagram is.
Does anyone have any mnemonics to help me remember which is the covariant and contravariant hom functor?
Answer: Covariant means having the same "variance", or in other words going in the right direction. Here it means that if you apply $\hom(A,-)$ to an arrow $f:C\to D$, you get an arrow in the same direction $\hom(A,C)\to \hom(A,D)$; hence covariant.
If you apply $\hom(-,B)$ to the same arrow you get an arrow $\hom(D,B)\to \hom(C,B)$ so in the opposite direction, hence contravariant. I guess it's easier if your mother tongue is a latin language, because in those "contra" (or derivatives thereof) often indicates some notion of "opposite" or "against".
Answer: I am not sure what precisely you are asking, so I shall provide a blanket answer.
Notation of Hom-sets
Notationally, $Hom(A, B)$ has function from $A$ to $B$. I think of $Hom(A, B) \equiv \{ A \rightarrow B \}$. Given this notation, it's somewhat natural to see that $Hom(A, -) = \{ A \rightarrow - \}$, so we have applied $A$ to $Hom$, and we are waiting for the other argument. So, the set we are coming from is fixed ($A$). $Hom(A, -) \equiv \text{maps out of $A$}$.
Similarly, $Hom(-, B) \simeq (- \rightarrow B)$ has $B$ fixed, and the domain unfixed. So, $Hom(-, B)$ is maps into B.
Now, the co/contravariance is as follows:
Contravariance
Imagine we have a map $f: X \rightarrow A$, and $Hom(A, -)$ with us. Then, we can create $Hom(X, -) \equiv \{  h \circ f \vert h \in  Hom(A, -) \}$. That is, we get a mapping:
$$(f: X \rightarrow A) \rightarrow (h: Hom(A, -) \rightarrow Hom(X, -))$$
This mapping reverses the direction of the sets. We have $X \rightarrow A$, which flipped to become $(Hom(A, -) \rightarrow Hom(X, -))$. Hence, this is contravariant (as in, contrast / opposite).
Covariance
Once again, we have a map $f: X \rightarrow A$, and $Hom(-, X)$. We can convert this to $Hom(-, A) \equiv \{ f \circ h ~ \vert ~ h \in Hom(-, X) \}$. Hence, this gives us a function:
$$(f: X \rightarrow A) \rightarrow (h: Hom(-, X) \rightarrow Hom(-, A))$$
Comment: You have your compositions the wrong way around.
Comment: +1 I learned a lot from this answer, including a way to check my understanding of co/contra-variance if I were to forget the notation (which I will).
Comment: Fixed! thanks for the check.


Equivalence in distribution and almost sure equivalence

Question: Consider two random variables $X$ and $Y$ equivalent in distribution, i.e. $P(X\in A)=P(Y\in A)$ for any set $A$. I know that does not imply the almost sure equivalence $P(X=Y)=1$. For example, $X \sim U(0,1)$ and $Y=1-X \sim U(0,1)$ are equivalent in distribution but they are almost surely unequal.
What if we have $E\left(\frac{X}{Y}\right)=1$? Are they almost surely equivalent? Thanks a lot.
Comment: Your same example of $X$ and $Y$ seems to satisfy $\mathbb E[X/Y]=1$...
Comment: The integral $\int_{0}^{1}\frac{x}{1-x}dx$ does not converge.
Comment: @KangpingYan You're right, I've made a blunder. Deleted the incorrect answer, I'll see if I can find a fix.
Answer: Another counterexample:
We will design a density for a random variable $U$ such that $\mathbb{E}[U] \mathbb{E}[1/U] = 1.$ Then taking $X$ and $Y$ to be i.i.d. copies of $U$ does the trick - as long as $U$ is continuous, they are a.s. unequal, but $$\mathbb{E}[X/Y] = \mathbb{E}[X] \mathbb{E}[1/Y] = \mathbb{E}[U] \mathbb{E}[1/U] = 1.$$
Let us define $U$. For some $l > 0,$ to be chosen, consider the following density $$ f_U(u) := \frac{2}{1 + l^2} \cdot \begin{cases} |x| & x \in [-1,l] \\ \,\,0 & \textrm{otherwise}\end{cases}.$$
$f$ is indeed a density, since the area under $|x|$ over $[-1, l]$ is $(1 + l^2)/2$.
Next, \begin{align} \mathbb{E}[U] &= \frac{2 (l^3 - 1)}{3(l^2 + 1)} \\ \mathbb{E}[1/U] &= \frac{2(l - 1)}{l^2 + 1}\end{align}
So, the counterexample exists if there exists $l > 0$ such that $$ 4(l^3 - 1)(l-1) - 3(l^2 + 1)^2 = 0.$$
But such an $l$ exists by the intermediate value theorem since the above function is $1$ at $0,$ and $-12$ at $1$ (there's also a solution somewhere between $5$ and $6$).

An interesting point with this strategy is that $U$ must take both signs - otherwise, if for e.g. $U > 0$, then the strict convexity of $z \mapsto 1/z$ forces $\mathbb{E}[U] \mathbb{E}[1/U] > 1$ unless $U$ is a constant a.s. This also suggests a mechanism to make the conclusion you wanted hold - suppose $(X,Y)$ are exchangable - so $\mathbb{E}[X/Y] = \mathbb{E}[Y/X] = 1$ - and that $X/Y > 0$ a.s. Then, by the above reasoning, it follows that $X/Y$ is a constant a.s. (and that constant is $1$). Similarly if $X/Y < 0$ a.s. Note that in the above counterexample, $(X,Y)$ is exchangable, but $X/Y$ takes both signs.
Comment: The uniform density $\mathrm{Unif}\left(\epsilon, 1-\epsilon\right)$ is $\frac{1}{1-2\epsilon}$ so the expectation $\mathbb{E}[X/Y] = -1+\frac{1}{1-2\epsilon}\log\frac{1-\epsilon}{\epsilon}$, which is decreasing on $(0,1/2)$ and goes to $1$ as $\epsilon\rightarrow1/2$.
Comment: @KangpingYan new counterexample, hopefully no silly errors this time.


Show TextView corresponding to button tag

Question: I'm dynamically creating some buttons and some corresponding textviews underneath the buttons (button, textview, button, textview...) I want the textView to show when i press the button above it and hide again when i press the same button. I have given the same tags for the button and the matching textview.
I want it to work like this: Press button with tag1, show textview with tag1, press button again and it'll hide it.
Right now it only shows and hides the last created textview when i press any of the buttons.
UPDATED CODE:
<code>    private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {
    return readJSONFeed(urls[0]);
    }

    protected void onPostExecute(String result) {
        Button button1;
        TextView tv;
        try {
            JSONArray jsonArray = new JSONArray(result);
            Log.i("JSON", "Number of surveys in feed: " +
            jsonArray.length());

            LinearLayout news = (LinearLayout)findViewById(id.hello);
            //---print out the content of the json feed---
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                button1 = new Button(getApplicationContext());
                button1.setLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));
                button1.setId(i);
                tv = new TextView(getApplicationContext());
                tv.setLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));
                tv.setId(i);
                button1.setText(jsonObject.getString("title"));
                tv.setText(jsonObject.getString("text"));

                news.addView(button1);
                news.addView(tv);

                button1.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        v.isPressed();
                            if(v.getVisibility() == View.GONE) {
                                v.setVisibility(View.VISIBLE);
                        } else {
                            v.setVisibility(View.GONE);
                        }
                    }
                });

                Toast.makeText(getBaseContext(), jsonObject.getString("title") +
                        " - " + jsonObject.getString("text"),
                        Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
            e.printStackTrace();
            }
        }
    }
</code>
Now the problem is, how do i call the variable tv in the onClick method. It wont let me add another view to the parameter, and i View v, is the view of the button. How do i fix this?
Answer: It looks to me as if you the variables tv and myButton are class members. If that is the case they will be overwritten at each step of the for-loop. This means that once the on click listener triggers it will refer to the most recently set values for tv and myButton (ie the last step of the for-loop).
Change tv and myButton into variables within the method scope and either combine createButton() and createTextView() into a single method or let createTextView() return the created TextView and pass that to createButton()
I've made some changes to your code:

Moved the Button and TextView declarations inside the for-loop
Changed the onClick listener to use the local TextView reference.

PS I'm not sure why you called v.isPressed() inside onClick(). It does nothing.
<code>protected void onPostExecute(String result) {
    try {
        JSONArray jsonArray = new JSONArray(result);
        Log.i("JSON", "Number of surveys in feed: " +
        jsonArray.length());

        LinearLayout news = (LinearLayout)findViewById(id.hello);
        //---print out the content of the json feed---
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            final Button button = new Button(getApplicationContext());
            button.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            button.setId(i);
            button.setText(jsonObject.getString("title"));

            final TextView tv = new TextView(getApplicationContext());
            tv.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            tv.setId(i);
            tv.setText(jsonObject.getString("text"));

            news.addView(button);
            news.addView(tv);

            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    tv.setVisibility(tv.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
                }
            });

            Toast.makeText(getBaseContext(), jsonObject.getString("title") +
                    " - " + jsonObject.getString("text"),
                    Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
        e.printStackTrace();
        }
    }
}
</code>
Comment: Okay, I have added tv and myButton to the scope now and combined the two create methods. Now the problem is, how do I get the onClick method to include the textview. When I'm only allowed to have one view inside my onClick.


Variance explained of a mixed effects model in a new data set

Question: I'm using the following function to calculate Edwards R^2 (formula 19 in Edwards et al. 2008) of a mixed effects model (I hope the implementation is correct):
<code>r2lmer <- function(model) {
   require(aod) # need the aod package for wald.test function
   if (class(model) != "mer") stop("mer object expected")
   n <- model@dims[['n']] # the number of observations
   p <- model@dims[['p']] # number of parameters
   df.mod <- n - p

   wald.model <- wald.test(b = fixef(model), Sigma = vcov(model), df = df.mod, Terms = 2:p)
   wald.F <- as.numeric(wald.model$result$Ftest[1])
   ( (p - 1) * 1 / df.mod * wald.F ) / (1 + (p - 1 ) * 1 / df.mod * wald.F )
}
</code>
In order to internally valdiate a mixed effects model, I would like to estimate the variance explained when the model is applied to a new data set, that is, when only the data changes, but not the parameter estimates. I'm not sure if it's even theoretically possible. Any help is highly appreciated.
Edit
If it's not a good idea to use an R^2 statistic for LMM, what other performance measures could one use to internally validate LMM? I have a LMM with just one random effects factor (varying intercept due to repeated measures) and several fixed effects factors. I'am primarily interested in the fixed effects and it is my understanding that Edward's R^2 is a good measure for the variance explained by the fixed effects. Edward's R^2 is also recommended for cross-validation in this paper:
Cheng et al. Real longitudinal data analysis for real people: Building a good enough mixed model. Statistics in Medicine. 2010, 29 504-520
Answer: I tend to be more and more convinced that this just generally isn't a good idea because the meaning the R^2 isn't really exactly the same as in a conventional linear regression.  As such, one always runs into interpretation issues and it often distracts from the meat of the story. Time spent writing a good description of the fit of model is time better spent... but I could be wrong.
[A good answer to a question on how to write up the fit of an LMM model would be really handy (which a cursory search didn't show me).]
Comment: Douglas Bates seems to agree, at least with respect to the hazy mapping of R-square definitions in mixed models to their non-mixed analogs: https://stat.ethz.ch/pipermail/r-sig-mixed-models/2010q1/003363.html
Answer: You could always just calculate try to calculate R^2 from the squared covariance of Ypred and Ynew over the product of their variances: http://www.stator-afm.com/image-files/r-squared.gif
This works for any continuous model, regardless of how the parameters are estimated.
Comment: in your posted image, which is pred and new (ie true Y on the new data set)?
Comment: It doesn't matter.
Comment: Link is broken, so this answer doesn't really contributes any longer


Find the probability of a full given that the first 2 cards are the 10 of diamonds and the 10 of hearts

Question: A 5 card hand is dealt from a well-shuffled deck of 52 poker cards. If the first two cards are the 10 of diamonds and the 10 of hearts, what is the probability of having been dealt a full?
This is what I did:
Let $A$ be the event the first two cards are the 10 of diamonds and the 10 of hearts.
We want to compute
$P(full|A)=\frac{P(A|full)P(full)}{P(A)}$
Yet I don't know how to compute $P(A|full)$. It this the right path? How could I solve this problem?
Answer: By "full" I take it you mean a full hand?
You don't need Baye's rule for this.
The probability of being dealt a full hand when it is given that you have been dealt those two tens is the probability of also being dealt (among the 3 other cards drawn from the remaining 50) either:

another ten (1 of 2 suits) and a pair of something else (1 of 12 faces, 2 of 4 suits), or
a triple of something else (1 of 12 faces, 3 of 4 suits).

$$\mathsf P(F_{house}\mid 10\diamondsuit,10\heartsuit) =
\frac{{2\choose 1}{12\choose 1}{4\choose 2}+{12\choose 1}{4\choose 3}}{{50\choose 3}}$$
Answer: Given that you have already been dealt the two tens, you have two potential scenarios for a full house. The first scenario would be to get one more ten and a pair, and the second scenario would be to get three of a kind. We can compute these the probabilities of these two scenarios separately and sum them.
First, the probability of one more ten and another pair. The probability of the third card being a ten is $\frac{2}{50}$. The probability of the fourth card being something other than a ten is $\frac{48}{49},$ since there is now only one ten left. The probability of the last card being the same as the fourth card is $\frac{3}{48}.$ All together, the probability of the first scenario is $\frac{2}{50}*\frac{48}{49}*\frac{3}{48} \approx 0.00245.$
Now, the probability of three of a kind. The probability of the third card being something other than a ten is $\frac{48}{50}.$ The probabilities of the fourth and fifth cards being the same as the third are $\frac{3}{49}$ and $\frac{2}{48},$ respectively. All together, the probability of the second scenario is $\frac{48}{50}*\frac{3}{49}*\frac{2}{48} \approx 0.00245.$
The total probability is the sum, or 0.0049.
Comment: In the first scenario, you're missing a factor of $3$ because the ten could come as any of the three cards.


c# random numbers always same

Question: Hy I want to create simple 3x3 matrice that contains only 0 and 1 elements. However, when I create 2D array 5x5 of my matrice object Racunalo that contains that 3x3 matrice, all 25 matrices have 0 and 1 elements on exact same positions, but I want that all matrices are different. How to make that? If there is some good soul who knows soultion, I would appreciate your help. Here is my code:
public class Racunalo
{
    public int[,] informacija = new int[3, 3];
    public void popuniInformacijuRacunala()
    {
        Random rand = new Random(Guid.NewGuid().GetHashCode());
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                informacija[i, j] = rand.Next(0,2);
            }
        }
    }
}

public class Resetka
{
    public static Racunalo[,] resetkaRacunala = new Racunalo[5, 5];

    public void popuniInformacijeSvihRacunala()
    {
        Racunalo rac = new Racunalo();
        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                rac.popuniInformacijuRacunala();
                resetkaRacunala[i, j]=rac;
            }
        }

    }
}

Answer: Your problem is that all Randoms are created with the same seed.
every Racunalo have the same guid as it is an object identifier.
try creating a new random with no parameters
Random rand = new Random();
or seeding every random with a different value (maybe use system clock time)
Comment: I tried all possible solutions, including your `Random rand = new Random();` and I always get same results. Also with system clock it's same problem.
Comment: Try making that Random object static and creating it only once
so that all instances of Racunalo will use the same random

c# random numbers always same


Let $f,g$ be continuous such that $\int^b_a{f(x)dx} = \int^b_a{g(x)dx}$. Show that there exists $x_0 \in [a,b]$ such that $f(x_0) = g(x_0)$

Question: Let $f,g : [a,b] \rightarrow \mathbb{R}$ be continuous such that $\int^b_a{f(x)dx} = \int^b_a{g(x)dx}$. Show that there exists $x_0 \in [a,b]$ such that $f(x_0) = g(x_0)$
is the idea that using Fundamental Theorem of Calculus: there exists some $x_0 \in [a,b]$ such that $\int^b_a{f(x_o)dx} = f(b) - f(a)= g(b) - g(a) = \int^b_a{g(x_0)dx}$?
Comment: You want the Integral Mean Value Theorem.
Comment: That is not quite the Fundamental Theorem of Calculus. It is the anti-derivative
Answer: Hint: We then have
$$
\int_a^b(f(x)-g(x))=0.
$$
If $h(x):=f(x)-g(x)$ never equals $0$ on $[a,b]$, then, as it is a continuous function, it must be either always positive or always negative on that interval. But could its integral be $0$, then?
Comment: One could also just appeal to Rolle's theorem...
Comment: i'm following so far, how do we use $x_0$ to show that this is a point in which the integral is $0$?
Comment: @Jayant.M What do you mean? You want to show that such an $x_0$ exists. What I propose is to show that the non-existence of such an $x_0$ would lead to a contradiction.
Answer: Let $F$ be an anti derivative of $f$. By the mean value theorem, there exists some $\xi \in (a,b)$ such that
$$
F'(\xi) = \frac{F(b) - F(a)}{b-a}.
$$
In integral form, this is
$$
f(\xi) = \frac{\int_a^b f(x) \, dx}{b-a}.
$$
Now as @Guest suggests, replace $f$ in the above by $h = f - g$, with $f,g$ as in the original post.


I am trying to create a calculator using react hooks. I was trying to get the current number and send it to the displayInput

Question: For some reason, it doesn't show the input on the first click. It shows the first input on the second click. What am i doing wrong? Here is a snip of the code below.
import React, {useState} from 'react';

function Calculator() {
  const [displayInput, setDisplayInput] = useState('')
  const [currentNumber, setCurrentNumber] = useState('')
  const [previusNumber, setPreviusNumber] = useState('')

  function handleNumber(e){
    setCurrentNumber(currentNumber + e.target.value)
    setDisplayInput(currentNumber)
  }

  return (

{displayInput}

      <button value = {1} onClick = {handleNumber}>1</button>
      <button value = {2} onClick = {handleNumber}>2</button>
      <button value = {3} onClick = {handleNumber}>3</button>

  );
}
export default Calculator;

Comment: Can you make the text smaller? Please remove `#` from the beginning of first line.
Answer: because setState is asynchronous, so when you call setDisplayInput(currentNumber) in the first time  currentNumber still is initialState ''. So you can update setDisplayInput as setCurrentNumber:
setCurrentNumber(currentNumber + e.target.value)
setDisplayInput(currentNumber + e.target.value)

Answer: Reason for bug=> setState is asynchronous
const [displayInput, setDisplayInput] = useState('')
  const [currentNumber, setCurrentNumber] = useState('')
  function handleNumber(e){
    setCurrentNumber(currentNumber + e.target.value)
  }
  useEffect(()=>{
    setDisplayInput(currentNumber)
  } , [currentNumber])

OR
const [displayInput, setDisplayInput] = useState('')
  function handleNumber(e){
    setDisplayInput(displayInput + e.target.value)
  }

OR
 function handleNumber(e){
        setCurrentNumber(currentNumber + e.target.value)
        setDisplayInput(currentNumber + e.target.value)
    }


Backup SQLite database to email?

Question: I have an app with SQLite database. I want to add an oportunity to do backup/restoration of database. I see a lot of answers about backup to SD card. But what if a device has no SD card? How to implement backup? Or maybe I can send database.db file to email, that user pointed, and download it from there when it's needed and add to application?
What can you advice?
Answer: I'm not aware of any way that can help you do that. however you can do a select on all your tables, put them in a CSV,XML or JSON file and then compress them.

Backup SQLite database to email?


Hypothesis testing for comparative data

Question: I'm currently planning a study to prove my software is comparable to humans at some task. The setup is that I take an input $I$, and have both a human and a computer modify $I$ in th same way, producing $M_H$ and $M_C$. Later, I will present various experiment participants both $M_C$ and $M_H$, and ask them which is better according to some qualitative metric, or if they're the same. I then repeat this for many possible inputs.
At the end of the day, my data is: I have a set of labels representing various inputs, and, for each label, I have a set of judgments about whether a participant preferred the human or the computer output. My goal is to show that, for a random input, the probability of a random judge preferring the computer output is at least $0.5$ (or some slightly lower number).
How do I analyze this? The closest thing I found in my search was stuff on "ipsative" data, but I didn't find anything on how to analyze it, and those tests seem to all be trying to measure the human subject instead of the two choices in the question.
Comment: I am not sure if I understood question correctly, so I am not sending this as an answer, but sounds like a work for chi squared test: "Pearson's chi-squared test (χ2) is a statistical test applied to sets of categorical data to evaluate how likely it is that any observed difference between the sets arose by chance."
Comment: But....I'm trying to show that they're the same!
Comment: Yes. Your null hypothesis is that they are the same and alternative hypothesis is that they are different, you will do χ2 to test the difference, found insignificant results and conclude, that you don't have enough evidence to say that the results are indeed different.
Comment: Uhhh.....no. The easiest way to do that is just to collect very few samples. Proving they're the same is different from failing to prove they're different.
Answer: What you are looking for is a test of equivalence or test of non inferiority. you don't have to get evidence against H0 stating your groups are the same, but your H0 can be that the difference in your groups is at least 10 percent (for example), and then you are trying to disprove this hypothesis. Nice introduction is in this chapter http://ncss.wpengine.netdna-cdn.com/wp-content/themes/ncss/pdf/Procedures/PASS/Non-Inferiority_Tests_for_Two_Means_using_Differences.pdf
and some other resources in this post How to test hypothesis of no group differences?

Hypothesis testing for comparative data


Confusion matrix not giving the whole data for Neural Network sklearn Python

Question: I'm just trying to get confusion matrix for my whole data set.
import pandas as pd

from sklearn.model_selection import train_test_split
from sklearn import metrics
from neupy import algorithms

df = pd.read_csv('my_data.csv', header=None)

df = df.rename(columns={0: 'season_at_test',
                        1: 'age',
                        2: 'child',
                        3: 'trauma',
                        4: 'surgery',
                        5: 'fever',
                        6: 'alcohol',
                        7: 'smoking','
                       })

df['smoking'] = df['smoking'].map({'N': 1, 'O':0})

data = df.iloc[:, :-1]
target = df['diagnosis']

X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=303)

pnn = algorithms.PNN(std=10, verbose=False)

pnn.train(X_train, y_train)

y_pred = pnn.predict(X_test)

print("Accuracy:",metrics.accuracy_score(y_test, y_pred))

pnn = algorithms.PNN(std=10, verbose=False)

pnn.train(X_train, y_train)

y_pred = pnn.predict(X_test)

print("Accuracy:",metrics.accuracy_score(y_test, y_pred))

metrics.confusion_matrix(y_test, y_pred)

And it gives me;
Accuracy: 0.7
array([[ 0,  1],
       [ 5, 14]], dtype=int64)

This output. Also i need to run 2 times to work it gives me an error at the first run.
My confusion matrix should be something like the below result because i have 100 sample not 20.
[ 58,  30]
[ 5, 7]

And if i try to add something like
y_pred = pnn.predict(X_test)
x_pred = pnn.predict(data)

metrics.confusion_matrix(x_pred, y_test)

It gives me "ValueError: Found input variables with inconsistent numbers of samples: [100, 20] "
How can i make this work for all of my data? I want a confusion matrix for all of my 100 samples.
Answer: When you perform train_test_split on data which has 100 entries you split the data into two (train and test). With 20% going into the test set as defined by test_size=0.2 so y_test will have 20% of data which equals 20 entries. This is expected behaviour.
If you want to get the confusion matrix on the entire dataset you should do:
y_pred = pnn.predict(data)
metrics.confusion_matrix(target, y_pred)

This approach is not recommend as it will not represent the true performance of the model on unseen data.


How can I improve the agogic qualities of my midi playback?

Question: In my quest for ever more realistic midi modelling, I keep coming up against questions and issues relating to the subtle rhythmic and tempo changes involved in good musical phrasing. After quite a search, I've discovered that such issues are dealt with in a separate theoretical discipline called agogics. (As in agogic accent.)
How can I improve the agogic qualities of my midi output? Besides that, I would like to deepen and broaden my theoretical understanding of rhythm and meter and the nuances thereof in musical performance. The musical style period under consideration is of secondary importance, by the way. I suppose that the basic principles underlying good phrasing are applicable across a wide timespan of musical history.
Edit: rephrased question so as to avoid direct literature requests.
Comment: Actually we don't give answers to questions asking for software or books. But you can edit your question avoiding *books*. Then I  can answer that I've found right the other day some interesting literature. Your title should be: How can I improve my agogic playing?
Comment: @AlbrechtHügli: Respectfully, what is the rationale behind the policy of declining literature requests?
Comment: Basically, this site is about helping with music *practices and theory*. Not about recommending literature, as that tends to be subjective, and we discourage personal tastes. That apart, we'd be inundated with similar requests otherwise.
Comment: I fully agree with you. This was not my decision. I'm afraid they will vote to close your question. In my opinion this is not purposeful. Let's wait and see.
Comment: Can you explain more about the midi relation? Basic agogic accent to confirm a meter would be like `|long short|long short|` to put the accent on beat one. How does that quality not come out in a midi file? In terms of dynamics and tempo the midi playback will of course be super rigid and non-human, but the basic agogic quality should come out if it's in the writing.
Comment: @MichaelCurtis: I mean the subtle agogic accent over and above the notated one, i.e., the kind of agogic accent that's entirely up to the performer. In the French Baroque they called it jeu inégale I believe.
Comment: So, you want to know how to get the midi file to playback with subtle tempo changes that mimic a human player who would do that to accentuate the notated agogic accent? Is that the midi part of the question?
Comment: @MichaelCurtis: Yes, that's correct. The notation program that I use, Dorico, has a built- in midi editor, and one of the parameters that I can change is the tempo. These changes can even be implemented on tiny fractions of every beat. So, it would seem in principle to be fully possible to implement things like rubato, jeu inégale, or even very minute prolongations of the notated agogic accent. But being a non-performer, on any instrument, I would like some explicit guidance on how performing musicians handle such things.
Answer: I assume you know that some midi and notation programs have an inbuilt humanizer to make the music less static, metrical exact and also varying the attack. But this is probably not what you are looking for.
As you're asking for books I'll post here the link with the book of Breithaupt
natural piano technic
(I haven't read it). There are lots of examples in his German edition:
Large edition in German (700 p.)
Edition in German, English and French  (short)
Another most important book is the book of Bach's son about the real art of piano playing.
C.P.E. Bach has given many good advices also about the agogic for musicians:
The influence of C.P.E. Bach's Essay on Keyboard Instruments was unsurpassed for two generations. Haydn called it "the school of schools." Mozart said, "He is the father, we are the children." Beethoven, when teaching the young Karl Czerny, wrote, "be sure of procuring Emanuel Bach's treatise." It is, indeed, one of the essential sourcebooks for understanding the style and interpretation of 18th-century music. It is comprehensive on thorough bass, on ornaments and fingering, and is an authentic guide to many other refinements of 18th-century performance.
Carl Philip Emanuel Bach
For mor information of his ideas read and listen to this:
C.P.E. and his music
Comment: Many thanks, Albrecht. I had heard about both books you mention, but read neither. I will do that now. Yes, I know about humanizing algorithms etc., and these usually do a decent job nowadays. But I want to take my playback to the next level of musicality.
Answer: I just found this quote from Vince Clarke of Depeche Mode and Erasure, which I remember reading when it was first published in August 1992. It was the word mush that stuck in my mind. (See http://www.muzines.co.uk/articles/in-clarkes-shoes/2339 for the full article).
Clarke, talking about using hardware sequencers and modular gear instead of MIDI, says this:

"The reason I wanted to do this was actually the timing discrepancies you get with MIDI, which are really bad. I came to the conclusion that there hasn't been an album recorded in five years that's been in time. Although you can get it quite close with MIDI, as you build up tracks everything becomes a tiny bit out, and you get a mush. We even started using an oscilloscope to compare timings, and with the MC-4 the timing was so close that, with the bass drum on one track, and a snare on the same beat, the snare would disappear behind it; it would not be visible on the 'scope."

Clarke was actually nudging the timing back and forth a few milliseconds to get all the attacks to line up.
It may be that you're dealing with timing issues that are beyond what midi can deal with, and you might be better off dealing with audio instead, which has much better timing resolution.


How should I upgrade Python on CentOS 5.5 (64-bit)

Question: I believe I am running CentOS 5.5 (64-bit) on CA AppLogic 3.0.
uname -a says
Linux LINUX64 2.6.18-194.32.1.el5xen #1 SMP Wed Jan 5 18:44:24 EST 2011 x86_64 x86_64 x86_64 GNU/Linux

I have upgrade with yum upgrade, but my Python is still in version 2.4.3.
yum info python says
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.5ninesolutions.com
 * extras: mirrors.cmich.edu
 * updates: mirror.5ninesolutions.com
Installed Packages
Name       : python
Arch       : x86_64
Version    : 2.4.3
Release    : 46.el5
Size       : 72 k
Repo       : installed
Summary    : An interpreted, interactive, object-oriented programming language.
URL        : http://www.python.org/
License    : PSF - see LICENSE
Description: Python is an interpreted, interactive, object-oriented programming
           : language often compared to Tcl, Perl, Scheme or Java. Python
           : includes modules, classes, exceptions, very high level dynamic data
           : types and dynamic typing. Python supports interfaces to many system
           : calls and libraries, as well as to various windowing systems (X11,
           : Motif, Tk, Mac and MFC).
           :
           : Programmers can write new built-in modules for Python in C or C++.
           : Python can be used as an extension language for applications that
           : need a programmable interface. This package contains most of the
           : standard Python modules, as well as modules for interfacing to the
           : Tix widget set for Tk and RPM.
           :
           : Note that documentation for Python is provided in the python-docs
           : package.

I think I read once somewhere that yum depends on python so I shouldn't remove that. So should I download python version 2.7.x as a source and compile it? Or is there a way to upgrade Python with yum (somehow)?
I am planning using the latest version 2.x of Python for Django.
Answer: There's python26 package available from epel repo. It should be better and easier option then installing manually.
However, please note that you probably won't be able to replace default python with 2.6 or any other version, as there are a lot of stuff build for 2.4 and upgrading it would require you to rebuild lots of packages and resulting system would not be really CentOS 5. I think it's easier to upgrade to CentOS 6 then to rebuild so much packages.
Answer: Yea compile it from source:
yum install gcc gcc-c++.x86_64 compat-gcc-34-c++.x86_64 openssl-devel.x86_64 zlib*.x86_64

install python 2.7
wget http://www.python.org/ftp/python/2.7/Python-2.7.tar.bz2
tar -xvjf Python-2.7.tar.bz2
cd Python*
./configure --prefix=/opt/python27
make
make install
vi ~/.bash_profile

replace PATH=$PATH:$HOME/bin
with PATH=$PATH:$HOME/bin:/opt/python27/bin

reload .bash_profile
source ~/.bash_profile
echo "/opt/python27/lib" > /etc/ld.so.conf.d/python27.conf
ldconfig


How can i load existing project in eclipse?

Question: I downloaded the project from web , now i extracted it. How can i load this project into eclipse environment ?  do i need to use import and then existing android code into workplace ?
Answer: Use File -> Import -> General -> Existing Project Into Workspace and then find your zip file.


What protocol does SAP HANA studio use in order to communicate with a HANA database?

Question: I would just like to know how HANA Studio communicates with a HANA DB? What kind of protocol does it use? Does it use JDBC or SQLDBC?
Answer: SAP HANA Studio uses JDBC for the majority of all communication with a SAP HANA server.
Features like the sapstartsrvc connection for starting/stopping the system or the landscape management use http-based protocols.


How can a SMART normalised value be lower (worse) than the worst value?

Question: I'm seeing output from smartctl where the VALUE is much less than WORST for some attributes. Does this make sense? What does it mean?
Everything I have read indicates that:

The raw value (RAW_VALUE in smartctl output) is manufacturer specific but sometimes useful
The normalised value (VALUE in smartctl output) is normalised to the range 0..254 with higher always meaning better, but in a manufacturer specific way
The worst value seen by the drive is tracked (WORST in smartctl output)
If the current / worst value drops below the threshold (THRESH in smartctl output) and the attribute is a pre-fail attribute, it's a bad sign

I have a (believed healthy, if a little old) drive that has:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
1 Raw_Read_Error_Rate     0x000f   200   200   051    Pre-fail  Always       -       0
3 Spin_Up_Time            0x0003   185   181   021    Pre-fail  Always       -       3725
4 Start_Stop_Count        0x0032   100   100   000    Old_age   Always       -       38
5 Reallocated_Sector_Ct   0x0033   200   200   140    Pre-fail  Always       -       0
7 Seek_Error_Rate         0x000f   200   200   051    Pre-fail  Always       -       0
9 Power_On_Hours          0x0032   076   076   000    Old_age   Always       -       17851
10 Spin_Retry_Count        0x0013   100   253   051    Pre-fail  Always       -       0
11 Calibration_Retry_Count 0x0012   100   253   051    Old_age   Always       -       0
12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       36
190 Airflow_Temperature_Cel 0x0022   073   043   045    Old_age   Always   In_the_past 27
194 Temperature_Celsius     0x0022   120   090   000    Old_age   Always       -       27
196 Reallocated_Event_Count 0x0032   200   200   000    Old_age   Always       -       0
197 Current_Pending_Sector  0x0012   200   200   000    Old_age   Always       -       0
198 Offline_Uncorrectable   0x0010   200   200   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x003e   200   200   000    Old_age   Always       -       0
200 Multi_Zone_Error_Rate   0x0009   200   200   051    Pre-fail  Offline      -       0

Which I interpret as everything's fine, although the drive got slightly too hot once (190 Airflow_Temperature_Cel).
My question is what's going on with lines 10 and 11 enter code herewhere WORST > VALUE?
Answer: In SMART normalized values (range: 1 .. 253), highest value is better, lower is worse. Manufacturers choose the initial normalized value, be it 253 (the maximul allowed value), 200, 100 (round numbers) or another number that suits them.
Therefore 253 is better than 100. It would have made more sense to set both at 100 or 253, I guess the manufacturer didn't get picky about those details when ho wrote the firmware.
Comment: Yup I think it's a programming inconsistency and since "it works that way" nobody fixes a cosmetic issue because it involves a great deal of trouble retesting the firmware. We are not talking about some piece of software that is ok to crash.
Comment: So you mean the manufacturer chose 100 for the initial value of VALUE and 253 for the initial value of WORST even though this is inconsistent? Presumably if the current value dropped to 99 so would the WORST value?


Accessing extracted zip file in Colab

Question: Some case study here. I am trying to play with PIL library in Google Colab, and can't get ImageFont to read my originally zipped file. The code:
import requests, zipfile, io
r3 = requests.get('https://sources.archlinux.org/other/community/ttf-roboto/ttf-roboto-hinted-2.138.zip')
z3 = zipfile.ZipFile(io.BytesIO(r3.content))
z3.extractall()

So far so good, and if I browse my directory with ls, it shows me the elements:
ls

Shows:
LICENSE                          RobotoCondensed-Regular.ttf
__MACOSX/                        Roboto-Italic.ttf
Roboto-BlackItalic.ttf           Roboto-LightItalic.ttf
Roboto-Black.ttf                 Roboto-Light.ttf
Roboto-BoldItalic.ttf            Roboto-MediumItalic.ttf
Roboto-Bold.ttf                  Roboto-Medium.ttf
RobotoCondensed-BoldItalic.ttf   Roboto-Regular.ttf
RobotoCondensed-Bold.ttf         Roboto-ThinItalic.ttf
RobotoCondensed-Italic.ttf       Roboto-Thin.ttf
RobotoCondensed-LightItalic.ttf  sample_data/
RobotoCondensed-Light.ttf

Now let's import ImageFont
from PIL import ImageFont

How do I read the file? If I try this:
# how do I make it work if I read it from the extracted files?
font = ImageFont.truetype(open("Roboto-BlackItalic.ttf"), 72)

It fails with an error:

'utf-8' codec can't decode byte 0x80 in position 7: invalid start byte

I know that I can pass a direct link to requests, and it will work:
# it works if we pass a direct link to requests like this:
req = requests.get("https://github.com/googlefonts/roboto/blob/master/src/hinted/Roboto-Regular.ttf?raw=true")
font = ImageFont.truetype(io.BytesIO(req.content), 72)

But how do I read the file from the local memory?
Full image for easier review:
Answer: You only need to provide the filename to ImageFont.truetype(), so change this line:
font = ImageFont.truetype(open("Roboto-BlackItalic.ttf"), 72)

to
font = ImageFont.truetype("Roboto-BlackItalic.ttf", 72)

Comment: I am speechless :D Thank you, Mark!

Accessing extracted zip file in Colab


What is the best way to initialize listjs with divs

Question: I am attempting to make a searchable database with list.js but the search function is not working. I am not sure if I initialized it correctly or what I am doing wrong. I am sure it is something obvious but I would love another set of eyes.
Here is my HTML

<input class="search" placeholder="Search for a member..."/>

Lucille Ball

2018

Jeremy Jacobs

2018

Russell Salvatore

2018

John Albright

2017

Lousie Bethune

2017

Glenn Curtis

2017

John Oishei

2018

Mary Burnett Talbert

2017

Here is my script
var options = {
  valueNames: ['name', 'year']
};

var hoflist = new List('hof-list', options);

Comment: Try to set `hof-list` as an id, according to documentation: `new List(id/element, options, values);`
Comment: Thank you so much. I knew it was something simple like that! Very much appreciated!
Answer: According to docs it expects the following parameters: new List(id/element, options, values); where id/element is

id or element *required Id the element in which the list area should be initialized. OR the actual element itself.

So you should pass there an actual id (so you need to change it in your html), or, you can pass there an element with
new List(document.querySelector('.hof-list'), options)


How to formulate the requirements that a counterexample must satisfy?

Question: Let $p_1, p_2$ and $p_3$ be three statements.
Suppose now we know that if $p_1$ is true, then $p_2$ and $p_3$ are equivalent. That is, if $p_1$ and $p_2$ are true, then $p_3$ is true, and if $p_1$ and $p_3$ are true, then $p_2$ is true.
Now I want to know if the reverse is true. That is, if $p_2$ and $p_3$ are equivalent, must $p_1$ be true?
One way to disprove this is to find a counter example. How shall I formulate the requirements that a counterexample must satisfy? I have trouble understanding how to satisfy the requirement that $p_2$ and $p_3$ imply each other, although I know it means either both $p_2$ and $p_3$ are true, or neither is true. Is an example where $p_1$ is false, $p_2$ and $p_3$ are true a counterexample?
Note that $p_1, p_2$ and $p_3$, more accurately $p_1(x), p_2(x)$ and $p_3(x)$ ,  are given statements about some changeable object $x$, and can't be changed except the object $x$ they are talking about. For example, in Does $X ⊥ Y \leftrightarrow X ⊥ Y | Z$ implies $(X,Y) ⊥ Z$?, to construct an example, we have to choose the three random variables $X$, $Y$ and $Z$, but can't change the three statements about them.
Thanks.
Comment: Replace "$p_2\leftrightarrow p_3$" by just $q$.  You are now asking if $p\to q$ implies $q\to p$.
Comment: what is to look for when searching for a counterexample?
Comment: @Tim: HINT: Remember that $p\to q$ is always true if $p$ is false.
Comment: @Tim: Yes, that would be a counterexample. A very simple way is to take $p_2$ and $p_3$ to be the same statement.
Comment: @Tim: You're constructing a counterexample, so you get to choose $p_1,p_2$, and $p_3$. To construct the counterexample, let $p_1$ be any false statement, and let $p_2$ and $p_3$ be the same true statement. Then $p_2$ and $p_3$ are certainly equivalent, and neither implies $p_1$.
Comment: @Tim: If they're given statements, then your question makes no sense: either $p_1$ is true, or it's not true, and whether this has anything to do with the truth of $p_2$ and $p_3$ depends entirely on the specific statements involved.
Comment: @Tim: In other words, you changed the statements. They aren't specific statements until $X,Y$, and $Z$ are specified.
Comment: @Brian: Thanks. Is this a counterexample: $p_2$ and $p_3$ both are true, but $p_1$ isn't? How shall we find a counterexample that satisfies the requirement that $p_2$ and $p_3$ imply each other, although I know it means either both $p_2$ and $p_3$ are true, or neither is true.
Comment: @Brian: what do you mean by " take p2 and p3 to be the same statement"? p1, p2 and p3 are supposed to be given statements which can't be changed.
Comment: @Brian: I should have added that $p_1, p_2$ and $p_3$ are given statements, which can't be changed. For an example, http://math.stackexchange.com/questions/1416468/does-x-%E2%8A%A5-y-rightleftarrow-x-%E2%8A%A5-y-z-implies-x-y-%E2%8A%A5-z
Comment: @Brian. In the linked post, to construct an example, we have to choose what the three random variables $X$ $Y$ and $Z$ are, though the three statements about the random variables are given and not changeable.
Answer: \begin{align}
p_1 & = \Big(\ell \in \{ a,b,c,d,e,f,g \}\Big) \\
p_2 & = \Big(\ell \in \{a,b,c,w,x,y,z\}\Big) \\
p_3 & = \Big(\ell \in \{a,b,c,t,u,v,w\}\Big)
\end{align}
It is easy to see with the above statements that if $p_1$ is true then $p_2$ and $p_3$ are either both true or both false.
Now suppose we don't know whether $p_1$ is true but we learn that $t=x$, $u=y$, and $v=z$.  Learning that suddenly makes $p_2$ and $p_3$ equivalent, but it does not mean that $p_1$ must be true.
Comment: Thanks. I am not looking for a concrete example, but a general formulation of a counterexample in terms of $p_1$, $p_2$ and $p_3$. (For a concrete example, see http://math.stackexchange.com/questions/1416468/does-x-%E2%8A%A5-y-rightleftarrow-x-%E2%8A%A5-y-z-implies-x-y-%E2%8A%A5-z)


Shooting Compound bow on a Crossbow Range?

Question: The archery range near my place has two areas. One for Compound/Traditional bows and one for compound bows. The crossbow range has a tower for practicing shooting from elevation. When it's empty and not occupied by crossbowers, I'd like to try shooting from that tower instead.
My only concern is respect for the equipment on the ranges. Are there any issues with shooting crossbow targets with a compound? e.g. am I going to damage the targets shooting my compound on crossbow targets?
Comment: Could you clarify this question, please? As it's currently worded, you say they have areas for "Compound/Traditional bows and one for compound bows", but in the next sentence talk about "the crossbow range". Perhaps just a little confusion with the labels?
Answer: First, when in doubt ask an employee not a stranger on the internet. Second, I'd say without explicit permission you should never shoot a compound bow or crossbow at a traditional bow target, details below.
Compound bows and crossbows generally need their own special targets which are much more dense and heavy than a normal bow target would require. They can shoot clean through some types of traditional targets which can be dangerous depending on the range setup. (IE going straight through and ricocheting dangerously back towards people).
The fact that they have a compound/traditional range implies they use targets where it wouldn't be an issue, however your question wording is confusing. You mention two areas, but three types of weapons, crossbow, compound bow, and traditional bow. If they had a range for traditional only I would definitely not use a compound bow or crossbow there.


Issue when trying to get the delegate associated to a Control's event

Question: I am trying to serialize controls to XML and I want to serialize their events' handler.
I am using this bit of code:
Control childCtrl = ....

if (childCtrl.GetType() == typeof(Button)) {
    EventInfo baseEventInfo = childCtrl.GetType().GetEvent("Click");

    EventHandlerList events =
        typeof(Control).GetProperty("Events",
                                    BindingFlags.Instance |
                                    BindingFlags.Public   |
                                    BindingFlags.Static   |
                                    BindingFlags.NonPublic).GetValue(childCtrl, null)
                                      as EventHandlerList;
    object eventField = typeof(Control).GetField("Event" + baseEventInfo.Name,
                                                 BindingFlags.NonPublic |
                                                 BindingFlags.Static).GetValue(childCtrl);
    Delegate aDel = events[eventField];

    xmlSerialisedForm.WriteElementString("Click", aDel.Method.ToString());
}

if (childCtrl.GetType() == typeof(CheckBox)) {
    EventInfo baseEventInfo = childCtrl.GetType().GetEvent("CheckedChanged");

    EventHandlerList events =
      typeof(Control).GetProperty("Events",
                                  BindingFlags.Instance |
                                  BindingFlags.Public   |
                                  BindingFlags.Static   |
                                  BindingFlags.NonPublic).GetValue(childCtrl, null)
                                    as EventHandlerList;
    //Error here: GetField returns null
    object eventField = typeof(Control).GetField("Event" + baseEventInfo.Name,
                                                 BindingFlags.NonPublic |
                                                 BindingFlags.Static).GetValue(childCtrl);
    Delegate aDel = events[eventField];
    xmlSerialisedForm.WriteElementString("CheckedChanged", aDel.Method.ToString());
}

Now I know that the checkbox has a handler bound for the event CheckedChanged; when using the debugger I can see that method in the EventHandlerList:

Now the same code actually works when dealing with a Button (when I want to get the delegate associated to the Click event). Why is it not working for the CheckBox? What am I missing here?
EDIT: my current workaround (very ugly) that I deduced from calling GetFields on typeof(CheckBox) and looking in the array:
if (childCtrl.GetType() == typeof(CheckBox)) {
    EventHandlerList events =
      typeof(Control).GetProperty("Events",
                                  BindingFlags.Instance |
                                  BindingFlags.Public   |
                                  BindingFlags.Static   |
                                  BindingFlags.NonPublic).GetValue(childCtrl, null)
                                    as EventHandlerList;

    object eventField =
      typeof(CheckBox).GetFields(BindingFlags.NonPublic |
                                 BindingFlags.Static)[0].GetValue(childCtrl);
    Delegate aDel = events[eventField];
    xmlSerialisedForm.WriteElementString("CheckedChanged", aDel.Method.ToString());
}

Answer: Rather infuriatingly, the CheckedChanged event seems to have been written in an entirely different fashion to the rest of the Events on the .NET framework. So was CheckStateChanged. Here they are.
typeof(CheckBox).GetField("EVENT_CHECKEDCHANGED",
      BindingFlags.NonPublic |
      BindingFlags.Static|
      BindingFlags.Instance |
      BindingFlags.FlattenHierarchy);
typeof(CheckBox).GetField("EVENT_CHECKSTATECHANGED",
      BindingFlags.NonPublic |
      BindingFlags.Static|
      BindingFlags.Instance |
      BindingFlags.FlattenHierarchy);

Just to make it more special, you can't treat everything as a CheckBox or those are the only two events you will get.


Jenkins - environment variable not setting up from pipeline

Question: Here is my script. Im trying to set up variables in pipline shell script:
node {

  anyconnect = docker.image('anyconnect:1').run("--cap-add NET_ADMIN --cap-add SYS_ADMIN --device /dev/net/tun:/dev/net/tun -e VPN_USER=${env.USER} -e VPN_PASS=${env.PASS} --name anyconnect")

  sh 'echo "Startig anyconnect and setting route"'

  sh """
    IPADDRESS = \$(docker inspect -f "{{ .NetworkSettings.IPAddress }}" anyconnect)
    echo $IPADDRESS
    ip route replace xx.xx.xx.xx. via $IPADDRESS
    """

  anyconnect.stop()

}

But im getting:

groovy.lang.MissingPropertyException: No such property: IPADDRESS for
  class: groovy.lang.Binding

I was trying to export it and other things like useing ${env.VARIABLE} or just ${VARIABLE} still not helping to set up variable in pipeline. How it should be done with Jenkins pipelines?
Answer: Replace your double quotes with single quotes to prevent $IPADDRESS from being interpreted as a Groovy variable:
  sh '''
    IPADDRESS = \$(docker inspect -f "{{ .NetworkSettings.IPAddress }}" anyconnect)
    echo $IPADDRESS
    ip route replace xx.xx.xx.xx. via $IPADDRESS
    '''

Alternatively, escape the dollar sign:
  sh """
    IPADDRESS = \$(docker inspect -f "{{ .NetworkSettings.IPAddress }}" anyconnect)
    echo ${'$'}IPADDRESS
    ip route replace xx.xx.xx.xx. via ${'$'}IPADDRESS
    """


Tips for beginner guitar technique

Question: I just started learning the guitar and given that I'm the ultimate beginner my instructor thought its best to start with tabs solo and only for the first 4 frets. Now I've been doing this for the past couple of days and I've a feeling that the next progression would be to play without looking at the guitar but here are my biggest challenges
1- given that my hands are small I have a hard time playing the fourth fret with my pinky (as my instructor told me) so I'm wondering would it be better to play it by moving my hand and use other fingers, or is it a bad habit to get into?
2- I'm playing using a pick and finding it hard to feel to which string I'm playing unless I look, so I'm thinking about using my fingers where for example I play the 3rd string with my index and 2nd with my middle finger and such, is that a good idea?
Comment: Is it - electric, acoustic, classical ?- all are subtly different.
Comment: Don't forget you're still in the very beginning stages, all of that gets easier with practice, especially when muscle memory kicks in and you don't have to watch your hands so much.
Answer: Fingerings are about playing stuff in the most natural and easy way, but what is the most natural and easy way can be changed with practice.  Playing with the pinky is an important asset so it makes sense to integrate it in your practice even though you might be able to work around it.
The most important thing for pinky playing (not just on the guitar) is to avoid "snapping" action.  One part of that is not to the last joint bend the other direction than the others.  That takes strength and training.  The problem with the snapping is that it makes you imprecise and slow.
The pinky will remain the weakest finger realistically, so even when you are good, you'll avoid things like trilling on it in concert.  But weaker or not, when the melody runs there, it has to take its part and not let you down.
So be careful with working around it too much while you practise.
Answer: The second part of your question on playing with pick or fingers has to be determined by what style and guitar you are using. I suggest to learn with a pick first. Fingerpicking can get complicated and frustrating for a beginner. You should learn chords and strumming.
If you want to play classical or folk, expect a lot of practice with fingerpicking which will take some time to perform a song. You are on the right track with the finger placement, but get some lessons, videos or a good book to discipline the fingerpicking technique. I would use Travis picking first to get an idea of using the fingerpicking technique.
Keep you expectations realistic and don't over think things. It's ok to look at the guitar while playing.
Answer: If you're having trouble playing with the little finger, try using a capo and moving it up the neck.  That way, you can get practice with good technique in a position where you don't have to stretch as far.  After you've got that working, move the capo a few frets closer to the nut and work out your exercises there.  Eventually, you'll have the finger movement under control and can remove the capo.

Tips for beginner guitar technique


Assign Tooltip to cell of selected row in Infragistics WebDataGrid

Question: I have an Infragistics WebDataGrid of group names. I would like to add a tooltip to the group cell that lists the doctors associated with this group when the user selects it.
I created a row selected event that gets the doctor's names when the group row is selected. The method is below and returns the names when the row is selected.  When I assign the string to the tooltip, the tooltip does not show when you mouse over the cell.
protected void wdgMedGrp_RowSelected(object sender, Infragistics.Web.UI.GridControls.SelectedRowEventArgs e)
        {
            Infragistics.Web.UI.GridControls.SelectedRowCollection selectedRows = e.CurrentSelectedRows;
            int iMedicalGroupID = Convert.ToInt32(selectedRows[0].Items.FindItemByKey("ID").Value.ToString());

            //Get Doctor names for this group
            DataTable dtDoctors = new DataTable("Doctors");

            SqlConnection SqlConn = null;
            string strSqlConnection = ConfigurationManager.ConnectionStrings["CAP06"].ConnectionString;
            using (SqlConn = new SqlConnection(strSqlConnection))
            {
                using (SqlCommand SqlCmd = new SqlCommand("phyadmGetPhysicianNames", SqlConn))
                {
                    SqlCmd.CommandType = CommandType.StoredProcedure;
                    SqlCmd.Parameters.Add("@MedicalGroupID", SqlDbType.Int).Value = iMedicalGroupID;
                    SqlConn.Open();
                    using (SqlDataAdapter dataReturned = new SqlDataAdapter(SqlCmd))
                    {
                        dataReturned.Fill(dtDoctors);
                    }
                }
            }

            string strPhysicianNames = string.Empty;
            foreach(DataRow row in dtDoctors.Rows)
            {
               strPhysicianNames += row["PhysicianFullName"].ToString() + "\r\n";
            }

            selectedRows[0].Items.FindItemByKey("Name").Tooltip = strPhysicianNames;
        }

This is my markup:
<ig:WebHierarchicalDataGrid runat="server" height="600px" width="875px"
AutoGenerateBands="False" AutoGenerateColumns="False" DataKeyFields="ID"
DataMember="SqlDataSource3_DefaultView" StyleSetName="Windows7" ID="wdgMedGrp"
DataSourceID="WebHierarchicalDataSource2" Key="SqlDataSource3_DefaultView"
OnRowAdded="wdgMedGrp_RowAdded" OnRowSelectionChanged="wdgMedGrp_RowSelected">
<Columns>
    <ig:BoundDataField DataFieldName="ID" Key="ID" Hidden="true">

    </ig:BoundDataField>
    <ig:BoundDataField DataFieldName="Name" Key="Name" Width="68%">

    </ig:BoundDataField>
    <ig:BoundDataField DataFieldName="IsVisible" Key="IsVisible" Width="22%">

    </ig:BoundDataField>
</Columns>
 <Behaviors>
    <ig:Filtering>
    </ig:Filtering>
    <ig:RowSelectors EnableInheritance="True" RowSelectorCssClass="groupRowSelectorWidth">
    </ig:RowSelectors>
    <ig:Selection RowSelectType="Single" Enabled="true" CellClickAction="Row">
        <AutoPostBackFlags RowSelectionChanged="true" />
    </ig:Selection>
 </Behaviors>

Why will the tooltip not display?
Thanks.
Answer: I had a somewhat similar need. I solved it by creating another hidden column containing the tooltip I wanted for each row, and then set the tooltip in the InitializeRow event, something like this:
Protected void wdgMedGrp_InitializeRow(object sender, RowEventArgs e)
{
    try
    {
       e.Row.Items[1].Tooltip = e.Row.Items[2].Value.ToString();
    }
    catch (Exception){} // ignore any exceptions
}

It worked great. The down side is that I had to do it for each record, one at a time, which meant I could not use the .Fill() method from the SQL call.
Comment: Thanks for responding.  I decided to go in a different direction and put this information on a different page that did not require a tool tip.  In case, this would probably work.  I would have to create a database call of the value string.  Assigning a tooltip in this method does show the information.


Change video source with Javascript in html without refreshing the page just the video

Question: My team and I are making a custom html video player and I'm working on a setting panel
And the first option we are mainly worried about so I'm adding first is the video quality option.
<video id="video" class="nm" poster="the poster url">
  <source src="video source url of the video at 480p" type="video/mp4" size="480">
  <source src="video source url of the video at 720p" type="video/mp4" size="720">
  <source src="video source url of the video at 1080p" type="video/mp4" size="1080">
</video>

And now what we want to do is when the user toggles on an option it will change the video source to the source that has the quality specified by the size attribute
Image reference here

PS: We are making a video player from scratch as It is on its own built with no APIs (e.g. Video.js, JWPlayer, Plyr) We are making all the things needed from scratch with pure javascript and html... and as we're making a website for streaming, and my team and I want to make a video player made by us for the website, and "maybe" later for distribution but for now we want to make a brand new video player and were just been putting this part off as we aren't sure of the best way to do this!

Edit
Also, we want the video to pause and change the quality and pick up off where it was paused
Answer: Note that for the native video the browser will decide which <source> to show and choose the first element it supports/understands (e.g. the first supported video file format): https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#Usage_notes
To circumvent that and force the browser to show a certain video source url, put in only one <source> element and manipulate the source property with javascript.
To pause and play the video in the native HTML5 video player you may use the API of the HTMLMediaElement: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
It has the play and pause functions you're looking for.


What ways (using stdio) can I print a vertical histogram

Question: I'm doing all the K&R exercises and I have finally been able to print a horizontal histogram. It look awful too, but I'll let you judge it. I have not been able to print a histogram of the lengths of words in its input vertically.
How can I modify my program to do this?

Question: Write a program to print a histogram of the lengths if words
  in its input. It is easy to draw the histogram with the bars
  horizontal; a vertical orientation is more challenging.

histogram.c
#include <stdio.h>
#define MAX 10
#define IN 1
#define OUT 0

int main()
{
    int c, len, state;
    int nlength[MAX];
    c = len = 0;
    state = 1;

    for(int i = 0; i < 10; ++i)
        nlength[i] = 0;

    while ((c = getchar()) != EOF) {
        ++len;
        if (c == ' ' || c == '\n' || c == '\t') {
            --len;
            state = OUT;
        }
            if(state == OUT) {
                if(len != 0 && len <= MAX)
                    ++nlength[len];

            len = 0;
            state = IN;
        }
    }
    for (int i = 0; i <= MAX; ++i) {
        printf("%d ", i);
        for (int a = 0; a < nlength[i]; ++a)
            printf("*");

        printf("\n");
        }
    return 0;
}

OUTPUT:
./histogram < histogram.c
0
1 *************************************
2 *************************
3 **************
4 ************
5 *****
6 ******
7 ****
8 **
9 *
10 ***

Comment: Use `printf("%2d ", i);` to left-align your `*`s in the current program.
Answer: First you need to know the height of the histogram which is the maximum value. Then you print each row and you decide to put a * or a  according to the value.
int h_max = 0;
for (int a = 0; a < MAX; a++) {
  if (h_max <= nlength[a]) h_max = nlength[a];
}

for (int i = h_max; i >= 0; i--) {
    for (int a = 0; a < MAX; ++a) {
      if (nlength[a] > i) {
        printf("*");
      } else {
        printf(" ");
      }
    }
    printf("\n");
}

Another solution is to print horizontally into an array and print the array in the direction you want.
Comment: +1. I didn't think of your second point, I'll try to implement for a challenge!
Answer: Let the number of rows be equal to the highest bin value (or some other suitable function of the bin values). Print the histogram one row at a time, for each column make a decision on whether to print a * in this column on this row or not, based on the bin value corresponding to that column.
Comment: I've taken this approach in one of my earliest BASIC programs. I was way too proud of myself for having been able to figure it out. :D
Answer: //vertical HISTOGRAM2
#include<stdio.h>
#include<stdlib.h>
int main()
{
int c,i,j,arr[10],height=0;
system("clear");

for(i=0 ; i<10 ; i++)
    arr[i]=0;

 while( ( c=getchar() ) != EOF)
  {
     if(c >= '0' || c <='9')
     ++arr[c-'0'];
     if( arr[c-'0'] > height )
      {
      height = arr[c-'0'];
      }
  }
printf("\n");
for(j=height ; j>0 ; j--)     // row
 {
  printf("%2d|",j);
  for ( i=0 ; i<=9 ; i++)  // column

    {
    if( j == arr[i] )
     {
     printf(" *|");
     arr[i]--;
     }
     else
         printf("  |");
    }

    printf("\n");
}
  printf("  |");
 for ( i=0 ; i<=9 ; i++)
     printf(" %d|",i);
     printf("\n  ------------DIGITS-------------");
     printf("\n");
return(0);
}

Answer: #include <stdio.h>
#define MAX 10
#define IN 1
#define OUT 0

int main(void){
    int c, len, state;
    int nlength[MAX];

    c = len = 0;
    state = IN;

    for(int i = 0; i < MAX; ++i)
        nlength[i] = 0;

    while ((c = getchar()) != EOF) {
        ++len;
        if (c == ' ' || c == '\n' || c == '\t') {
            --len;
            state = OUT;
        }
        if(state == OUT) {
            if(len != 0 && len <= MAX)
                ++nlength[len-1];

            len = 0;
            state = IN;
        }
    }
    int max = 0;
    //horizontal
    for (int i = 0; i < MAX; ++i) {
        if(max < nlength[i]) max = nlength[i];
        printf("%2d ", i+1);
        for (int a = 0; a < nlength[i]; ++a)
            printf("*");

        printf("\n");
    }
    printf("\n");
    //vertical
    for (int i = max; i > 0; --i){
        for (int j = 0; j < MAX; ++j)
            if(nlength[j]>=i)
                printf("%c ", '*');
            else
                printf("%c ", ' ');
        printf("\n");
    }
    for(int i=1;i<=MAX;++i)
        printf("%-2d", i);

    return 0;
}

Answer: I know this is an old question but I realize that your code had been wrong about the lengths of words.
The result which I run your code is showed below
The result after trying your code
I typed in five characters with 1 length, two chars with 2 lengths.... The problem here is your code keep adding while the program actually get to the end of word.
With this problem I also manipulated to fix it. My solution is showed
len=setst=0;
state=OUT;
while((c=getchar())!=EOF)
{
    if(c==' '||c=='\n'||c=='\t')
    {
        state=OUT;
        if(setst==1)
            {
            if (len!=0 && len<=MAX)
                ++nlength[len];
            len=0;
            setst=0;
            }
    }
    else if (state==OUT)
    {
        ++len;
        setst=1;
    }
}

The result is clear now.
Hope that illustration is clear

Any way thanks a lot about your question. I feel excited about solved something fun and hard.
Answer: #include <stdio.h>

#define MAX_WORDS   10

//Prints a histogram of the lengths of words in its input
int main()
{
    int c, numberOfCharacters, numberOfWords, wordLengthsIndex, largestWordLength;
    c = numberOfCharacters = numberOfWords = wordLengthsIndex = largestWordLength = 0;
    int wordLengths[MAX_WORDS];

    //Read the words
    while ( ((c = getchar()) != EOF) && numberOfWords < MAX_WORDS)
    {
        if (c == ' ' || c == '\n' || c == '\t') //no longer in a word
        {
            if (numberOfCharacters > largestWordLength)
            {
                largestWordLength = numberOfCharacters;
            }
            wordLengths[wordLengthsIndex] = numberOfCharacters;
            numberOfCharacters = 0; //reset for the next word
            numberOfWords++;
            wordLengthsIndex++;
        }
        else //treat anything else as a character in a word
        {
            numberOfCharacters++;
        }

    }

    //Print the histogram horizontally
    for (int numberOfWordsIndex = 0; numberOfWordsIndex < numberOfWords; ++numberOfWordsIndex)
    {
        for (int numberOfCharactersIndex = 0; numberOfCharactersIndex < wordLengths[numberOfWordsIndex]; ++numberOfCharactersIndex)
        {
            putchar('*');
        }
        putchar('\n');
        putchar('\n');
    }

    //Print the histogram vertically
   for (int character = largestWordLength; character > 0; --character) //cycle each row
   {
       for (int word = 0; word < numberOfWords; ++word) //cycle each column
       {
           if (wordLengths[word] >= character) //this particular word length falls within the current row
           {
               putchar('*');
               putchar('\t');
           }
           else
           {
               putchar(' ');
               putchar('\t');
           }
       }
       putchar ('\n');
   }

    return 0;
}


Different Image on each Mainmenu entry in Drupal 7

Question: there is a Logo and a variable picture in the header of my design. This picture depends on the current page.
Is there a plugin or even a build in setting, where i can configure this behavior?
Answer: You may try this module, which seems to do exactly that.
Comment: Ok this seems nice, but do i have to set a new image on every node?
Comment: It depends on what you're trying to achieve. The module supports wildcard, so you should be able to set images for several nodes based on path.
Comment: Ok. Thank.
Is there a open issue with the Textfield? My image is only displayed if i fill in the textfield.
Comment: Well, you'll have to go to the modules documentation and/or issue queue to know about specifics concerning its usage. Good luck.


Microsoft Translator widget doesn't translate buttons

Question: I use Microsoft Translator widget on my site, and it generally works. However, some items on my page are not translated:
Item1
<asp:FileUpload />, which becomes:
<input type="file" />, which is displayed as untranslated English:
* Chrome: "Choose a File..." | No file chosen
* IE: Browse...
I guess this one depends on the browser's display language.
Item2
<asp:Button Text="Submit something", which becomes:
<input (...) type="submit" value="Submit something",
in which "Submit something" is not translated.
Is there any way I can get Microsoft Translator to translate these? I guess I could do the widget's work, call MT API myself and update the value (in the second case), but I'd really rather not.
Answer: Microsoft Translator only supports <Button id="Button1" runat="server">My Button</ Button> translations.  It doesn't translate the input type=button, asp:Button or telerik:Button nor any other flavor of buttons that you don't place the text for the button in between the tags.  Check this article out.
http://social.msdn.microsoft.com/Forums/en-US/a840884b-4efe-4cd4-a598-0ca81842404c/widget-does-not-translate-button-text
I have been looking for a solution similar to what you are but I have found nothing.
So outside of changing all your buttons to this type I am assuming that we would need to use the api to do the translations.


Finding probability assuming null hypothesis is true

Question:
Candidates 1,2 and 3 are running for a position in a company. Candidate 1 claims 38% favourability among all the voters. Assuming this is true, what is the probability that in a random sample of 500 laborers,

less than 33% will vote for candidate 1?
more than 40%?
Between 35% and 45%?

I haven't done statistics in awhile, but I'm guessing:

the lack of a specified distribution is problematic.
38% thing is the null hypothesis

If I assume normality, is this how I shall proceed?

Let $X$ be proportion of voters in favour of candidate 1.
Then under $H_0$, we have
$\mu = E[X] = 0.38$ and $\sigma^2 = Var[X] = 0.38(1-0.38)$
We want to compute
$$P(X < 0.33 | H_0)$$
$$ = P(X < 0.33 | \mu = 0.38, \sigma^2 = 0.38(1-0.38))$$
$$ = P(\frac{X - 0.38}{\frac{\sigma}{\sqrt{500}}}  < \frac{0.33 - 0.38}{\frac{\sigma}{\sqrt{500}}})$$
$$ = P(Z < \frac{0.33 - 0.38}{\frac{\sqrt{0.38(1-0.38)}}{\sqrt{500}}}) \tag{*}$$
Then I just look up $$\frac{0.33 - 0.38}{\frac{\sqrt{0.38(1-0.38)}}{\sqrt{500}}}$$ in the z-table, and that's it?

$(*)$
We are allowed to assume normality of $X$ because $np = 500(0.38) \ge 5$ right?
Comment: Cross-posted at http://math.stackexchange.com/q/1853868/59351. Please don't cross-post.
Answer: There's no null hypothesis in this problem, because you aren't doing significance testing. In fact, this isn't even a problem of statistical inference. It's more of a probability problem.

the lack of a specified distribution is problematic

My guess is that the assumption "38% favourability among all the voters" means that votes are IID Bernoulli random variables.

38% thing is the null hypothesis

No, but it does tell you the parameter of the Bernoulli distribution, namely .38.

We are allowed to assume normality of $X$

There's no need to.
As for the three questions stated in the problem, they can be answered directly by using the cumulative distribution function or the probability mass function of the binomial distribution. Since this is a self-study problem, I'll leave the details to you.
Comment: What alternative do you have in mind? Individual votes for candidate 1 can't be normally distributed, since they're either 0 or 1.
Comment: Besides what I mentioned above, you got a *z* of about -1,750, implying a probability around log(-1.5e6), much smaller than the correct answer of .0089.
Comment: Suppose we don't use bernoulli
Comment: Kodiologist, well what's wrong with my solution please?
Comment: (+1) But the calculation for the normal quantile shown in the q. doesn't come to -1750


Drush with a dockerized Drupal install

Question: I'm trying to setup a development environment for Drupal using docker.
I've already succeeded on creating a PostgreSQL container and a Drupal container using official images for both, and I can replicate the production environment.
How do I get drush to detect my Drupal install?
I've tried both https://hub.docker.com/r/drush/drush/ and https://github.com/DockerDemos/appstack-drush (had to build that last one) but when I run drush inside the containers they don't see the Drupal install.
I run "docker run --volumes-from <my-drupal-container> --link <my-db-container>:postgres -it drush/drush dd" and it shows nothing, "drush cc" finds no caches.
Comment: You have to specify a working directory `-w`. See Docker docs.
Answer: There are 2 things you can do here:

Use Docker as external container like you are doing. You need to pass the --net parameter too to make that work, see example below. You will always use this drush container as a running command, not a container that is up and running with your stack all the time.

docker run --net={your_container_network_name} --rm -it -v $(pwd):/app drush/drush sqlc

Simply add drush to your Drupal container and connect to that container to run drush commands:

Dockerfile:
ENV DRUSH_VERSION 8.1.2
RUN curl -L --silent https://github.com/drush-ops/drush/releases/download/${DRUSH_VERSION}/drush.phar \
  > /usr/local/bin/drush && chmod +x /usr/local/bin/drush

Connect to your container and then run any drush command inside it:
docker exec -it {container_id} bash

root@{container_id}:/var/www/html# drush status

Comment: Option 2 worked well for me.
Comment: `docker exec -it -w /var/www/html {container_id} drush status` in one line. `docker exec -it -w /var/www/html {container_id} bash -c "drush status"` probably works, too.
Answer: For the --uri parameter, pass in whatever URI you use to access your site from your local web browser.  In addition to --uri, you must also specify --root, which should contain the full path to the Drupal root inside your container.
Answer: To have a very convenient way to use drush / drupal console / composer in Docker, I use zsh with autoenv and a little function for each command.
In each drupal project folders, create a .autoenv.zsh file the following settings:
autostash DRUSH_IN_DOCKER=1
autostash DOCKER_PHP_CONTAINER=myproject_fpm_1
autostash PROJECT_URL=http://www.mydomain

Then creates a small zsh function:
drush() {
    if [ "$DRUSH_IN_DOCKER" == "1" ]; then
        docker exec -it ${DOCKER_PHP_CONTAINER} /var/www/vendor/bin/drush --root=/var/www/web --uri=${PROJECT_URL} "$@"
    else
        drush "$@"
    fi
}

Be sure to replace the provided paths with the one of your drupal project in docker.
Answer: Run:
docker-compose exec php sh
drush cc all

Comment: Hi and welcome. Rather than just giving 2 commands, could you explain what these commands do?
Comment: The exec command executes a program on the passed container (php). 'sh' is just a basic (non-bash) shell, which is available on most containers. So this comment is just telling you to connect to the container, which is no different than Karel's comment, except with less explanation.

Drush with a dockerized Drupal install


Validation with only one dataset

Question: I am performing multiple linear regression and multivariate analyses on a dataset (~600 samples). I would ideally use a second, independent dataset to validate my findings, but there is no suitable independent dataset available. How should I handle validation? Should I perform 5-fold cross validation on the one dataset that I have? Will that be sufficiently robust?
I am using R, in case anyone has suggestions for packages.
Answer: Given the small number of samples you have, you should definitely make use of cross-validation (5 fold should be fine). You should still have a holdout/test set to establish some form of generalization error.
All this said, without more data, you will most likely have to accept a simpler model (running a more complex model, e.g. one with higher number of variables risks serious overfitting) and consequently higher bias.
Comment: Thank you for your answer! I will do cross-validation  :)

Validation with only one dataset


ion-slides, each overlap with ng-repeat

Question: I'm real newbie in ionic, html, angular and java script. I have an app that take some JSON data and display it with ng-repeat.
But when I tried to switch to the next slide, it overlap. and I have an $interval that refresh JSON each 5 sec, it reset to the first slide also.
here html:
<ion-view title="home">
<ion-content ng-controller="temperatureCtrl">

    <ion-slides  options="options" slider="data.slider" >
        <ion-slide-page ng-repeat="channel in channels">

canal# {{channel.canal}}

              <button class="button button-stable" ng-click="switchChannel(channel, channel.canal)" ng-model="channel.status">
                {{channel.status}}
              </button>

                <input type="text" style="text-align:center;" placeholder="Channel name" ng-model="channel.name" ng-focus="stopRefresh()" ng-blur="restartRefresh()">

{{channel.temperature}}ºC

Setpoint= {{channel.setPoint}}

                <input type="range" name="setpoint" min="5" max="30" step="0.5" value="33" ng-model="channel.setPoint" ng-focus="stopRefresh()" ng-blur="restartRefresh()">

            <centrer>
              <button  class="button button-dark button-block padding " ng-click="channelsClk(channel, channel.setPoint)">ok</button>
            </centrer>

              {{channel.permission}}

              {{channel.percentOut}}%

        </ion-slide-page>
    </ion-slides>
</ion-content>

and the controler:
main.controller("temperatureCtrl", ["$scope", "$interval", "ArduinoService", function($scope, $interval, service) {
  var autoRefresh;
  $scope.channels = [];

  $scope.options = {
  loop: false,
  effect: 'fade',
  speed: 500,
  }
  $scope.data = {};
  $scope.$watch('data.slider', function(nv, ov) {
    $scope.slider = $scope.data.slider;
  })

  function startRefresh(){
    autoRefresh = $interval(function() {
    updateAjax();
    }, 5000);
  }

  function updateAjax() {
    service.getChannels(function(err, result) {//get json data
      if (err) {
        return alert(err);
      }
      // puis les mets dans le scope
      $scope.channels = result.channels;
    })
  };

  $scope.init = function() { //on load page first get data
    updateAjax();
    startRefresh()
  }

  $scope.switchChannel = function($scope, channel) { // change name function
    var switchCh = {canal : $scope.canal, status : $scope.status}
    service.switchChannel(switchCh, function() {
    });
    updateAjax();
  };

  $scope.channelsClk = function($scope, channel) {
      var chanObj = {setPoint : $scope.setPoint, name : $scope.name, canal :         $scope.canal
      };
      service.putChannels(chanObj, function() {
    });
  }

 $scope.stopRefresh = function() { //ng-mousedown
     $interval.cancel(autoRefresh);
  };

  $scope.restartRefresh = function() {
    startRefresh();
  };

$scope.$on('$destroy', function() {
    // Make sure that the interval is destroyed too
    $scope.stopRefresh();
  });

}]);

Answer: remove option fade solve the problem.
$scope.options = {
  loop: false,
 //effect: 'fade', /*   <--  */
speed: 500,
}

ion-slides, each overlap with ng-repeat