How to determine the probability of a player getting 1st in a game, given win probabilities of head to head matchups of players?

Question: I have predicted the probability that player A beats player B in a head to head matchup in a game, for all combinations of players. I would like to convert this into the probability of a player winning the entire match, based on head to head predictions, and rank them.
Is this as simple as P(A beats B) * P(A beats C) * ... * P(A beats N - 1) for the N players?
Thanks for your help, much appreciated.
EDIT: Additional info: There is no elimination. This is a single trial/event. All players are competing against all other players at the same time, that is, all n players are on the "field" at once. In a tie, all t players that tied are ranked equally. There is no tiebreaker, they split the "winnings".
EDIT 2: My specific case is a race. The head to head probabilities are the probabilities that a player finishes ahead of the other player. So if P(A > B) = 0.6, there is a 60% chance Player A beats player B, but does not make a mention of their actual finishing position. Based on this info, I would like to rank players by probability of winning the entire race
Comment: It depends on how the tournament is conducted and the rules for resolving ties: please explain.
Comment: How are matches structured? Is it a round-robin tournament where everyone plays everyone and players are ranked on the total number of wins? Or is it a single-elimination bracket tournament? If it's the latter, that formula won't work - A might always lose to B, but if B gets eliminated by C in an earlier round, A can still win the tournament. In an elimination tournament with N players, the winner only plays log2(N) games, not N games. Who they play will make a big difference - do we assume random matchups?
Comment: You need to assume *something* about the relationship between this "all on the field at once" contest and the "head to head matchups" for which you actually have data.  Why not explain what's really going on, rather than asking us to guess based on this abstract description of the problem?
Comment: @whuber Sorry, I figured being general would be best and make answers the most helpful to others in the future. My specific case is a race. The head to head probabilities are the probabilities that a player finishes ahead of the other player. So if P(A > B) = 0.6, there is a 60% chance Player A beats player B, but does not make a mention of their actual finishing position. Based on this info, I would like to rank players by probability of winning the entire race.
Comment: @NuclearHoagie added some additional context info. Please let me know if you need anything else.
Comment: In an actual race, though, the chances of beating another contestant often depend on who else is in the race.  Thus, at a minimum, you have to postulate that the presence of other contestants does not appreciably alter the chances.  Then, you need to check that your estimated chances are *consistent* in the sense that there's a 100% chance *somebody* will win.  Note, too, that probabilities need not be transitive: it's quite possible for runner $A$ to be nearly certain to beat $B$ when they race, and for $B$ to beat $C,$ *and* for $C$ to beat $A$!  We need information about such possibilities.
Comment: @whuber Yes, the P(A > B) is likely slightly dependent on other competitors, so I know this will be an approximation as I do not have information on the size of that effect. As for the non-transitive nature, what kind of information do you need? In the event of P(A>B)=0.9, P(B>C)=0.7, P(C>A)=0.6, do you need to know how to resolve this cyclical match up? That is one of the things that has me scratching my head haha and why I came here.
Comment: @whuber And to answer your remark about 100% chance somebody will win, I am currently taking the product of all of a player's head to head probabilities and dividing them by the total probabilities. This gives me probabilities for each player getting 1st place that sums to 1.
Comment: The extra information is helpful, but I think we'd need joint probabilities, since a runner does not beat other runners in *independent trials*. Suppose runner A can either have a good day or bad day, and will either finish in 10s or 20s. Runners B and C are consistent and always finish in 15s. Runner A has a 50% chance of beating B and a 50% chance of beating C, but if they beat B they are guaranteed to beat C, and will come in first 50% of the time. It's impossible for A to beat B and lose to C, but that can't be captured with independent head-to-head probabilities.
Comment: @Nuclear Right.  And having only the probabilities does not suffice: we need quantitative information about absolute performances, too.  Jage: the fact that you have to normalize the probabilities in this way is a strong clue ("red flag") that something's amiss.
Comment: @whuber Is my need for normalization to get the probs to sum to 1 a red flag that my predictions are whack, or that the aggregation from head to head to 1st place probability is inaccurate? I would assume the latter right? My predictions of head to head win probabilities are obviously approximations due to my model and data's imperfections
Comment: Yes, the latter.  I'm not challenging your estimates of head-to-head win probabilities; I accept them as being accurate.  But when you have to renormalize probabilities, you ought to be able to appeal to a basic axiom of probability to justify that, and I don't see much of a prospect of that here.
Answer: This question is interesting but unanswerable.  I found it instructive to think about Efron's intransitive dice for the insight they give us into some subtle issues.
Let's model the "races" (head-to-head contests) between individuals $A,$ $B,$ and $C$ with ordinary fair dice that have been relabeled.  When two dice are thrown, the one with the larger value wins.  When all three dice are thrown, the one with the largest value wins.  To avoid dealing with ties, we will make sure that no two dice share a value.

Die $A$ has the numbers $2,2,4,4,9,9.$

Die $B$ has the numbers $1,1,6,6,8,8.$

Die $C$ has the numbers $3,3,5,5,7,7.$

Straightforward calculations establish that in any head-to-head matchup, die $A$ beats die $B$ with a probability of $5/9.$  We can do this by brute force with a table, if you like.  Since, in effect, each player is producing one of just three values (with equal probabilities), we only need to tabulate all  $3\times 3 = 9$ possibilities.  Here are the winners of all possible in a head-to-head matchups of $A$ (columns) against $B$ (rows):
$$\begin{array}{r|ccc} \text{B\A:}&2 & 4 & 9 \\
\hline
1 & A & A & A \\
6 & B & B & A \\
8 & B & B & A
\end{array}$$
Similar calculations establish that $B$ beats $C$ with a chance of $5/9,$ and also $C$ beats $A$ with the same chance.  This is a probabilistic rock-paper-scissors situation where each player tends to beat the next in a cyclic list $A\to B\to C\to A.$
A more complicated calculation, but still straightforward, tabulates all $3\times3\times 3 = 27$ (equiprobable) outcomes when all three players are "in the field together."  It turns out that $A$ and $B$ each have a $10/27$ chance of being the overall winner, while $C$ only has a $7/27$ chance of winning.
What differentiates $C$ from $A$ and $B$ to make $C$ inferior in this collective sense?  All three dice have the same mean value of $5,$ showing they get the same "score" on average.  (To continue the race metaphor, they are all equally strong runners.)  But the variance of $A$ is $((2-5)^2 + (4-5)^2 + (9-5)^2)/3 = 26/3$ and the variance of $B$ is the same (because the values of $B$ are $10$ minus the values of $A,$ which leaves the variance unchanged).  However, the variance of $C$ is only $((3-5)^2 + (5-5)^2 + (7-5)^2)/3 = 8/3,$ considerably smaller.
In short, $C$ gets far more consistent results.  Contestants $A$ and $B$ get their wins by being inconsistent: sometimes they greatly exceed their average and sometimes they fall far short.
Based on this little example, then, we might suppose that the shape of the distribution of head-to-head results -- especially its spread -- likely is an important factor in estimating the chances of any competitor being the overall winner.  It's not enough to suppose that all three outcomes are independent, nor does it suffice to know just the head-to-head probabilities.
Comment: I believe that's correct: comparing variances is just a little too crude to arrive at definite results.  But this does provide insight into why some dice emerge as better and others as worse when all are competing with each other, compared to head-to-head matchups.
Comment: I really like the concept of intransitive dice. Seems very interesting and applicable here. A question I have: The lower variance of C resulting in it losing more frequently than A and B is not strictly true in all cases right? Whether higher or lower variance is good or bad will depend on the distribution of head to head predictions correct?


The trade-off between p-value and sample size

Question: This question stems from an existing question, in which I tried to compute the p-value of some features over a large dataset (2,000,000 articles and 15-20 topics). Each article must belong to only one topic. I want to investigate whether articles with different topic have different levels of reading time. For example, whether users tend to spend more time on business articles than entertainment articles.
I found that when I included the whole population, the p-values were extremely low. Decreasing sample size led to higher p-values. So my question is (if I stick to use p-value) how large the sample size is better to be in my case? 200 articles in one topic?
Answer: I'm afraid statistics is not done that way. Sample size calculation involves three groups of component:

The designated chance of calling a statistical significance while in fact there isn't any, known as type I error. It's conventionally set at 5% and it's related to the p-value < 0.05 threshold. Additionally, the other is the designated chance of missing a statistical significance while in fact there is one, known as type II error. It's conventionally set at 20%. The chance of not committing a type II error is called "power" and if type II error rate is 20%, power is 80%.
The second component is called the "effect size." It comes in many shapes and forms but generally it's the strength of association or magnitude of difference you wish to use the statistics to show if such phenomenon is likely a fluke or not.
The third component is the sample size.

In order to make a decision on any one of these three, the other two need to be known (or assumed). So, generally a question on sample size would be something like:

How many samples do I need to detect a difference of 10 units or more (with a
  SD of 7.5 units) in total blood cholesterol between the mice fed with low-fat diet and the mice
  fed with control diet, with type I error rate set at 5% and power at
  80%? And I'd like the ratio of test to control be 1:1.

Then statisticians would be able to help you. Currently, your question does not have effect sizes. (What does "evaluate the significance of each topic" actually measure? Do you mean chance of being downloaded? Viewed? Cited? Funded?) And it does not have the declared error rates. So, it's unlikely for anyone to come up with a sample size.
Answer: If you "include the whole population" then it is arguable as to whether you need or should use p-values at all.  p-values are about inference.  Inference goes from a sample to a population.  If you have the whole population then I (and others) would argue that there is no inference to be done.
p-values on large samples are, as you've found, often small.  You need to estimate the effect size.


Counting the number of possible matchups for teams

Question: A tournament has 16 teams. How many ways are there to match up the teams in 8 pairs? Is it (16 choose 2)(14 choose 2)(12 choose 2)(10 choose 2)(8 choose 2)(6 choose 2)(4 choose 2)(2 choose 2)?
Comment: You have counted the number of ways to pick teams to be labelled Team 1, Team 2, and so on. Overcount by a factor of $8!$.
Answer: No, it's not. It is only 15*13*...*1, or 15!!
We consider one of the teams. It has 15 choices for its partner
Then consider another of the remaining 14 teams. It has 13 choices
Continue doing this, until we only get 1 choice
so the answer is 15*13*...*1=15!!.
Comment: Thank you. Ah. That makes sense. Once the first two teams have been selected, the third team only has 14 other teams it can possibly play against. So, it would be 15 * 13 * 11 * 9 * 7 * 5 * 3 * 1 = 2,027,205.
Comment: I am just curious - what made you think that it is 16choose 2 times etc. ? I just wanted to know so maybe we could help you avoid those kind of mistakes again.
Comment: Since the question was from the same section that had the flag question (http://math.stackexchange.com/questions/1057136/different-flag-signal-questions), I thought the same solution would be the same.
Comment: The difference there is that one of the teams is already "set" when forming a pair. It is not like the other one where you are matching the flags with colors.
Comment: Thank you. I'm still trying to wrap my head around all of this. =)


about diatonic modes

Question: so is each mode a minor/major (opposite of what it naturally is) when played in one particular key in the staff?
if that doesn't make sense can you please explain what is going on in the scale degree names chart on this page: https://en.wikipedia.org/wiki/Degree_(music) ?
edit: column 3 tells us which mode can be played entirely in the corresponding key using only the diatonic scale, only the staff positions (this is how i see it). But i thought that a certain mode is either major or minor or just a different type. for eg: up until now i came across Ionian mode as the major & the Aeolian mode as the natural minor.
so my question is: what is the column 4th for(the 3rd column has a relation as stated above. what relation does the 4th one have?)? Is it that eventhough Ionian is a major scale, it sounds minor when compared to Phrygian mode(which has a reason of being there).
so: 1) what is Ionian doing next to Phrygian there?
    2) what makes it a minor?
Answer: I associate the scale degree names with solfege which I associate with the major scale first and then the minor scale as an alteration of major.
If someone says "dominant", I think solfege "sol." If someone says say "mediant", I think "mi" and if they then say "wait, I'm in minor" then I think "ma!"
I'm not thinking about modes when a scale degree is named.
I also associate scale degrees to certain chords. For example I associate the mediant with the tonic I chord. I associate the leading tone with the dominant V chord. Some degrees have multiple associations like the subdominant which can be used in the ii, IV, V and many other chords.
I don't associate scale degrees with modes in the way the chart suggests.
I don't find the "corresponding mode" columns on that wiki page to be helpful for anything.
If I am in a major key and play a scale from the supertonic up the octave to the higher supertonic I don't consider this to be playing the Dorian mode. It really depends on the idea that I'm in a major key. If I was playing in C major, and played the scale from D up the octave to D it doesn't make much useful sense to think about it as playing a D Dorian scale. Simply put, I'm not in Dorian, I'm in C major. I could be playing that scale over a ii6 or V6 chord (or many others), but the tonal context is C major not D Dorian.
It is technically true that the various permutations of the major scale give us various modes. So, the 2nd mode of the major scale is D Dorian, the 3rd mode is E Phrygian, etc. But so what? How does that information help us understand music in the major/mnior system. I don't think it helps.
But, there are ways in which I do associate scale degrees with modes and that is by alteration of scale degrees.
An easy example is the supertonic. When that degree is lowered by a half step (a fairly common thing in minor key music) it is associated with the Phygian mode. The reason is this: when you have the basic natural minor scale and then lower the second scale degree it produces the Phygian scale. Ex. C minor C D Eb F G Ab Bb C, lower the supertonic  and we have C Phrygian C Db Eb F G Ab Bb C. This kind of alteration happens with a Neapolitan chord which leads to V and in context makes the minor key music temporarily take on the flavor of the Phrygian mode.
Compare what I described above with the wiki page and what it lists about the supertonic and the modes. That chart tries to have you associate Phrygian with the dominant scale degree in minor key music. That isn't a helpful association in minor key music. It's more like a technical coincidence, but the handling of the dominant chord in minor key music will commonly not create the feeling of the Phrygian mode.
Beginners are often told about the modes of the major scale. Unfortunately that doesn't really explain much about function in the major/minor system. Alteration of scale degrees in the major/minor keys produces modes in a much more functional way.

EDIT

...what is Ionian doing next to Phrygian there?

Column 3
What this is trying to tell you is: the third scale degree is the starting point for the third mode of the major scale, and this third mode of the major scale is the Phrygian mode.
In C major:

 mediant
    |
C D E F G A B C (Ionian mode, major scale)
    ^
    third mode (E Phrygian mode) starts here:
    E F G A B C D E

Column 4
What this is trying to tell you is: the third scale degree is the starting point for the third mode of the minor scale, and this third mode of the minor scale is the Ionian mode.
The part that may not be clear about column 4 is assumes you understand the hypothetical "scale" described by the chart is changed from major to minor for column 4.
In C minor:

 mediant
    |
C D Eb F G Ab Bb C (Aeolian mode, natural minor scale)
    ^
    third mode (Eb Ionian mode) starts here:
    Eb F G Ab Bb C D Eb

The major and minor scales, plus the seven modes, are all just permutations of the diatonic series.
In C major

starting on C: Ionian (major scale)
starting on D: Dorian
starting on E: Phrygian
starting on F: Lydian
starting on G: Mixolydian
starting on A: Aeolian (minor scale)
starting on B: Locrian
starting on C: Ionian (major scale)

You can permute to any starting note. Nothing changes except the order.

starting on A: Aeolian (minor scale)
starting on B: Locrian
starting on C: Ionian (major scale)
starting on D: Dorian
starting on E: Phrygian
starting on F: Lydian
starting on G: Mixolydian
starting on A: Aeolian (minor scale)

You can also transpose to another key.
In Db major

starting on Db: Ionian (major scale)
starting on Eb: Dorian
starting on F:  Phrygian
starting on Gb: Lydian
starting on Ab: Mixolydian
starting on Bb: Aeolian (minor scale)
starting on C:  Locrian
starting on Db: Ionian (major scale)

All these scale and modes names really represent different starting points along one single diatonic series. They are all just part of one thing.
Answer: I don't understand the question, but I can explain the chart, which will hopefully answer your question.
Columns 1 and 2 simply list the scale degrees by number and name, respectively, in ascending order.

The 1st scale degree is called the tonic,
the 2nd scale degree is called the supertonic,
the 3rd scale degree is called the mediant, etc.

This is the case in any and all diatonic scales/modes.  This is simply a generic numbering/naming system.
Columns 6 and 7 show the note names which would correspond to these scale degrees in the keys of C major and C minor, respectively.

C is the tonic of both C major and C minor,
D is the supertonic of both C major and C minor,
E is the mediant of C major while Eb is the mediant of C minor, etc.

Column 5 gives a brief description of each scale degree's role in the scale.
Columns 3 and 4 seem unnecessary to me, and are probably the source of your confusion.  They show which mode starts on each scale degree, in major and minor respectively.  So for column 3,

the mode starting on the 1st scale degree of the major scale is Ionian (aka the major scale),
the mode starting on the 2nd scale degree of the major scale is Dorian,
the mode starting on the 3rd scale degree of the major scale is Phrygian, etc

For column 4,

the mode starting on the 1st scale degree of the minor scale is Aeolian (aka the natural minor scale),
the mode starting on the 2nd scale degree of the minor scale is Locrian,
the mode starting on the 3rd scale degree of the minor scale is Ionian, etc.

See how Ionian starts on the 1st degree of the major scale and 3rd degree of the minor scale?  To demonstrate this, consider a key signature with no sharps or flats, which is either C major or A minor.  The 3rd note in A minor is C.  The 6th note in C major (upon which the Aeolian mode begins) is A.
Comment: I agree that columns 3 and 4 are unnecessary and a source of confusion.

about diatonic modes


Mudar da segunda para a terceira Activity [Android Studio]

Question: Como eu mudo da segunda para a terceira tela??
Eu consegui mudar da tela1 para a tela2 (da Main para CadastroActivity)
Só que, usando o mesmo código, não consigo ir da tela2 para a 3 (de CadastroActivity para FormularioActivity).
Ele compila, mas quando clico no botão, o app dá erro e encerra
Como resolvo?
Quero clicar no botão btn_cadastrar (da CadastroActivity) e ir para FormularioActivity
Código java:
package com.example.vanessa.projetoinicial_vanessa;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class CadastroActivity extends AppCompatActivity {

//private Button botaoCadastrar; //da tela Cadastro

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cadastro);

    //Ao clicar no botão Cadastrar (da tela 2 Cadastro), deve ir para tela Formulario
    Button botaoCadastrar = (Button) findViewById(R.id.btn_cadastrar);
    botaoCadastrar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(CadastroActivity.this, FormularioActivity.class);
            startActivity(intent);
        }
    });

}

}

XML:

<LinearLayout
    android:layout_width="368dp"
    android:layout_height="624dp"
    android:orientation="vertical"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">

    <ListView
        android:id="@+id/lista_Madicamentos"
        android:layout_width="match_parent"
        android:layout_height="200dp" />

    <Button
        android:id="@+id/btn_cadastrar"
        style="?attr/buttonStyle"
        android:layout_width="match_parent"
        android:layout_height="39dp"
        android:background="?attr/colorPrimary"
        android:text="CADASTRAR"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="528dp" />

</LinearLayout>

</RelativeLayout>

Em LogCat:
10-13 01:09:24.954 17082-17082/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.vanessa.projetoinicial_vanessa, PID: 17082
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vanessa.projetoinicial_vanessa/com.example.vanessa.projetoinicial_vanessa.FormularioActivity}: java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.EditText
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
 Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.EditText
    at com.example.vanessa.projetoinicial_vanessa.FormularioActivity.onCreate(FormularioActivity.java:25)
    at android.app.Activity.performCreate(Activity.java:7009)
    at android.app.Activity.performCreate(Activity.java:7000)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Onde está o erro?
Muito obrigada
Comment: Qual o erro que dá ? Esse é sempre o primeiro passo a tomar. Coloque a mensagem de erro na pergunta.
Comment: Dá erro já no app rodando. Ele vai da primeira para a segunda tela. Na segunda tela, ao clicar no botão, aparece a mensagem "ProjetoInicial_Vanessa has stopped" "Open app again"
Comment: Você tem à sua disposição o log da aplicação. Ali tem tudo sobre o erro. Pegue-o e coloque na sua pergunta.
Comment: Pronto, é isso?
Answer: No log diz:
AppCompatTextView cannot be cast to EditText

Ou seja, o erro está na próxima tela. Você está tentando guardar um objeto do tipo AppCompatTextView em uma variável do tipo EditText (provavelmente com o método findViewById), e isto está causando erro no seu código.
Comment: Ahhh, muito obrigadaa. Realmente é na próxima tela... Comentei aqui e deu certo, agora vou arrumar isso. //Eu comecei a aprender agora, não sabia dessa tela de erros rs, valeu


match_parent layout parameter doesn't work?

Question: I'm trying to create a view for an ArrayAdapter. This is how I'm doing it:
FrameLayout rowView = new FrameLayout(context);
rowView.setBackgroundColor(Color.BLUE);
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.MATCH_PARENT,
    RelativeLayout.LayoutParams.WRAP_CONTENT);
lp2.setMargins(0, 0,
    context.getResources()
        .getDimensionPixelSize(R.dimen.activity_divider_small), 0);
lp2.addRule(RelativeLayout.LEFT_OF, R.id.textView1);

ImageView view = new ImageView(context);
int size = context.getResources().getDimensionPixelSize(
        R.dimen.image_avatar_size);
FrameLayout.LayoutParams lp0 = new FrameLayout.LayoutParams(size, size);
view.setBackgroundResource(R.drawable.va);
rowView.addView(view, lp0);

Button btn = new Button(context);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.MATCH_PARENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
btn.setBackgroundColor(Color.RED);
int padding = context.getResources().getDimensionPixelSize(
        R.dimen.activity_margin);
btn.setPadding(padding, padding, padding, padding);
btn.setText(okButtonText);
btn.setId(R.id.textView1);

RelativeLayout layout = new RelativeLayout(context);
layout.addView(rowView, lp2);
layout.addView(btn, lp);

My intent is to stretch the textView with OK caption vertically. For some reason button does not match its parent proeperly. Could anyone point me at my mistake?
EDIT Things are getting really weird. It is known that if we set both ALIGN_PARENT_TOP and ALIGN_PARENT_BOTTOM parameters, the view will be stretched vertically. In my case, the view is placed on bottom of layout (like if i set the ALIGN_PARENT_BOTTOM only).
This is what I get:
http://img13.imageshack.us/img13/3323/jqs.png
EDIT
Well, this issue looks kinda like the platform bug, so I had to add a listener that resizes OK button.
rowView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int height = rowView.getHeight();
        btn.setHeight(height);
    }
});

I am still looking for a better solution.
Comment: Why you didn't create an xml file ?
Comment: Actually I did, but there was the same issue, so I tried to do this manually.
Comment: Have you tried to `setBackground()` instead of? And in XML file should your to but with `android:background` instead of `android:src`.
Comment: @yugidroid I've just tried this - unsuccessfully.
Comment: Out of curiosity, can you try adding the `Button` before adding the `FrameLayout`?
Comment: @Luksprog Adding `Button` before `FameLayout` was one of my very first suggestions, but it didn't work.
Comment: The alignment relative to the parent bounds should work. Maybe you could try aligning the `Button` relative to the `FrameLayout` with the `RelativeLayout.ALIGN_TOP` and `RelativeLayout.ALIGN_BOTTOM` rules.
Answer: you should try layout.addView(btn,lp);
Comment: That's strange. Perhaps because you are in a listView. You could try align the button to the other view with RelativeLayout.ALIGN_BOTTOM porperty
Comment: Nope, nothing's changed.
Comment: And if you change TextView to Button ?
Comment: The button doesn't scale too.
Comment: could you post shape_background ?
Comment: I've added this XML to m post.
Comment: Try with a background color like btn.setBackgroundColor(Color.BLUE); in order to be sure of the size of your view. Are you still using a Button view ?
Comment: I've edited my post. And yes, I am using Button at the moment.
Comment: Ok, i tried by myself and has the same thing as you. The only woraround i found is to set tes size of your button : RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
          RelativeLayout.LayoutParams.WRAP_CONTENT,
          size);
Comment: Since rows in my real project could contain an arbitrary amount of text, setting the constant size is not a good idea. So I've added the listener as described in my post.


Como funciona os comados "extends" e "block endblock" do Jinja2?

Question: Estou usando o Jinja2 para criar os templates para minha aplicação. No entanto, eu fiquei confuso em relação a duas funcionalidades dele.
As funcionalidades são:
O comando extends:
{% extends 'pagina-exemplo.html' %}

e o comando block:
{% block content %}

{% endblock  %}

Eu não sei muito bem como elas funcionam, ou como o mecanismo de herança de template funciona no que diz respeito a esses dois comandos.
Pergunta

Como funciona os comados extends e block endblock do Jinja2?
Answer: As tags extends e block funcionam em conjunto e servem para construir templates com ideias de herança, sobreposição e reuso.
Em um template você pode definir inúmeras tags block, as quais podem posteriormente ser sobrepostas ou reutilizadas por templates "filhos". Os filhos tem a intenção de utilizar os templates "pais" através do block extends, que importa o template e agora o filho passa a "ver" os blocos do pai. Os filhos irão preencher as tags block com o conteúdo desejado, ou mesmo reutilizar o que já está no pai com o comando super.
Aqui abaixo um exemplo completo retirado da documentação do Jinja2:
Arquivo base.html que será utilizado como template (pai) para os outros filhos.
<!DOCTYPE html>

    {% block head %}
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}{% endblock %} - My Webpage</title>
    {% endblock %}

{% block content %}{% endblock %}

        {% block footer %}
        © Copyright 2008 by you.
        {% endblock %}

Arquivo child.html que "estende" o pai base.html, sobrescreve alguns block que deseja e também utiliza porções do código do pai usando super().
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
    {{ super() }}

{% endblock %}
{% block content %}

Index

      Welcome to my awesome homepage.

{% endblock %}

Perceba o uso do comando extends antes de iniciar os blocos. É importante salientar que os blocos devem ser únicos no arquivo, ou seja, você não pode definir múltiplos blocos de mesmo nome. Essa limitação existe para que o filho saiba exatamente qual porção de bloco preencher. Além disso, caso queira reutilizar o mesmo bloco várias vezes no seu template, basta utilizar o comando self.bloco() onde bloco() é o nome do bloco que deseja reaproveitar.


Tricky list manipulation inside a dictionary

Question: I have the following data in a file. I want to extract the time and the size from relevant lines and plot a timeseries graph.
    03/12 20:23:26.11: 04:23:26 L9 <Mx  Acc  Magnum All            XDV:00111A0000000117 00D3001200870172 01FF6000F01CFE81 3D26000000000300
    03/12 20:23:26.11: 04:23:26 L9 <Mx  Acc  MID 0x1500 Len 26   XDV:00111A0000000117 00D3001200870172 01FF6000F01CFE81 3D26000000000300
    03/12 20:23:26.11: 04:23:26 L8 <Mx  JK31 (Mx)                  JSP:18.104.22.168: Size = 166, Data: 00345C4101003031 E463EF0113108701 5A01FF6008F01CFE 81AB170000000003 EF01131087015A01 FF6008F01CFE81AB 170000000003EF01 131087015B01FF60 00F01CFE81701B00 00000003EF011310 87015B01FF6000F0 1CFE81701B000000 0003EF0113108701 5C01FF2000F01CFE 81CB240000000003 EF01131087015C01 57CC00F01CFE81CB 240000000003EF01 131087015D01FF20 00F01CFE815B2900 00000003EF011310 87015D01FF2000F0 1CFE815B29000000 0003EF0113108701 5E01FF6000F01CFE 819D280000000003 EF01131087015E01 FF6000F01CFE819D 0003
    03/15 20:23:26.11: 04:23:26 L8 <Kx  JK31 (Kx)                  JSP:220.127.116.11: Size = 163, Data: 00647741000030EF 01131087015A01FF 6008F01CFE81AB17 0000000003EF0113 1087015A01FF6008 F01CFE81AB170000 000003EF01131087 015B01FF6000F01C FE81701B00000000 03EF01131087015B 01FF6000F01CFE81 701B0000000003EF 01131087015C01FF 2000F01CFE81CB24 0000000003EF0113 1087015C01FF2000 F01CFE81CB240000 000003EF01131087 015D01FF2000F01C FE815B2900000000 03EF01131087015D 01FF2000F01CFE81 5B290000000003EF 01131087015E01FF 6000F01CFE819D28 0000000003EF0113 1087015E01FF6000 F01CFE819D280000 A6220000000003
    03/15 20:23:26.11: 04:23:26 L9 <Kx  JK31 (Kx)                  JSP:10.22.1.53:Size = 163, Data: 009D1141000030EF 01131087015A01FF 6008F01CFE81AB17 0000000003EF0113 1087015A01FF6008 F01CFE81AB170000 000003EF01131087 015B01FF6000F01C FE81701B00000000 03EF01131087015B 01FF6000F01CFE81 701B0000000003EF 01131087015C01FF 2000F01CFE81CB24 0000000003EF0113 1087015C01FF2000 F01CFE81CB240000 000003EF01131087 015D01FF2000F01C FE815B2900000000 03EF01131087015D 01FF2000F01CFE81 5B290000000003EF 01131087015E01FF 6000F01CFE819D28 0000000003EF0113 1087015E01FF6000 F01CFE819D280000 A6220000000003

I have the following program to do it.
from dateutil import parser

import matplotlib.pyplot as plt

match_list = ["L8 <Mx JK31 (Mx)", "L9 <Mx JK31 (Mx)"]  ## put all match strings in this list
with open("test.txt") as fin:
    print(' : {}', fin.name)
    time_data = {}  ## save data in dictionaries, with string keys and lists as values
    size_data = {}
    for line in fin:
        for match in match_list:
            if match in line:
               if match not in time_data:
                   time_data[match] = []  ## initialize empty list the first time this key is encountered
                   size_data[match] = []
               line = line.strip.split()
               time_str = line[2]
               t = parser.parse(time_str)
               time_data[match].append(t)
               size = int(line[9].strip(","))
               size_data[match].append(size)

    for match in match_list:
        plt.figure()  ## create a new figure for each data set
        plt.plot(time_data[match], size_data[match])
    plot.show()  ## simultaneously show all plots

I am using two dictionaries above, time_data and size_data. Each of the data contains the elements of match_list as their key. The values are a list that contains datetime objects.
The above was done so that it would be easy to plot using matplotlib.
Now I want to do the following.
As you can see in the sample data above for the same key L8 <Mx JK31 (Mx) you have two values that has the same time (04:23:26).
I want to modify the data structure (i.e the list inside my dictionaries) in such a way that I want the size values (i.e values in the list inside dictionary size_data) to be summed up every minute.
Suppose there are 5 values as below
04:23:26   56
04:23:26   60
04:23:43   70
04:23:46   80
04:23:56   90
I want the above to be replace with 04:23:00 and 356. How do I go about doing this.
Comment: Does the file by any chance contain only tab separated values? If so, use the `csv` module.
Comment: @ReutSharabani - I don't think so.It does seem to contain spaces.
Comment: Spaces are there inside values, but what separates **values**?
Comment: @ReutSharabani - I am not sure. How do I check?
Comment: See this: http://stackoverflow.com/questions/767545/does-notepad-show-all-hidden-characters
Comment: @ReutSharabani - That is not the case
Answer: I believe your question is a bit easier than it seems at first, because the extra overhead of the parsing of the file. I assume that the parsing works, and you end up with a list tuples, dicts...
Now you want to perform an kind of aggregation on that list, right?
so, starting from
[
['10:10:01', 45],
['10:10:11', 135],
['10:10:50', 21],
['10:10:57', 4],
['10:11:01', 2],
['10:11:11', 8]
]

you want to get
[
['10:10:00', 205],
['10:11:00' 10]
]

if so, you could easily use a defaultdict and datetime.replace(seconds=0) for that.
This code is not be plug-and-play, but you should be able to fit it into your situation quite easily
input = # your parser function
output = defaultdict(int)

for date, value in input.items():
  output[date.replace(seconds=0)] += value

If you want a list again you could use output.items()
Good Luck!
Comment: My list isn't like this. I mean, I have two separate lists in two dictionaries. They are related by a common `key`


How to open mailto links in new tab using on firefox

Question: I need to open href mailto links in new tab on firefox. I tried target _blank it doesn't help me.
Comment: Can you show us the code that you tried? The Operating system of the user usually decides how to handle mailto links, you cannot change that behavior using an HTML attribute as far as I know.
Comment: Contact Us
Answer: This appears to be a bug in Firefox.
https://bugzilla.mozilla.org/show_bug.cgi?id=646552
Comment: They have put this bug on the back burner due to nobody to work on it. Sad to say after being reported 8 years ago it will likely never be fixed. If anyone comes up with a workaround, It would be great to post it on this question since it comes up at the top of google results.
Answer: I think, you want to open web-mail client for this. But, this won't be a href mailto link.
Check this similar thread here
Comment: Will popup blockers block window.open() ?
Comment: well, there is a chance, but not too sure about the behaviour :(


How can you show that $f$ is one-to-one without horizontal line test?

Question: $f(x) = \sqrt{4x^2 + 1}$ for $x \in [0, \infty)$
I know that typically I can just do the horizontal line test, but I'm confused about how one would do this algebraically.
Comment: @AndreaMarino the "*horizontal line test*" involves graphing the function, imagining a horizontal line, sliding that line up or down and seeing if there are any such positions for the horizontal line such that it intersects the graph in more than one position... a graphical way of noting where there exist $x,y$ such that $x\neq y$ yet $f(x)=f(y)$
Comment: Strictly increasing functions are one-to-one. Can you show that it is strictly increasing?
Comment: What do you mean by horizontal line test?
Comment: Show the derivative is nonzero.
Comment: @JMoravitz: well yes it was a rethorical question for the OP, since formalizing the horizontal line test gives a direct solution :) sorry for the misunderstanding
Answer: Algebraic method: for one-one functions, show that $f(x_1) = f(x_2) \implies x_1 = x_2$:
\begin{align}
\sqrt{4(x_1)^2 + 1} &= \sqrt{4(x_2)^2 + 1} \\
4(x_1)^2 + 1 &= 4(x_2)^2 + 1 \\
4(x_1)^2 &= 4(x_2)^2 \\
(x_1)^2 &= (x_2)^2 \\
x_1 &= \pm \sqrt{(x_2)^2} \\
&= \pm x_2.
\end{align}
But because $x \geq 0$, we reject the negative root.
So $x_1 = x_2$, thus the function is injective.
Comment: Nice answer! I added parentheses around the variables with subscripts (I think that makes things more readable). If you don't like this however then feel free to roll back my edits.
Comment: @Joe ah, didnt consider that the subscripts and superscripts were stacked on top of one another. I agree the parentheses makes it easier to read.
Answer:
The function $x\mapsto \sqrt{x}: [0,\infty) \to [0,\infty)$ is one-to-one
The function $x\mapsto 4x+1: [0,\infty) \to [0,\infty)$ is one-to-one
The function $x\mapsto x^2: [0,\infty) \to [0,\infty)$ is one-to-one

Call these functions $f_1, f_2, f_3$. Then your function $f(x)=\sqrt{4x^2+1}$ is equal to
$$f(x) = f_1(f_2(f_3(x)))$$
Can you take it from here?
Answer: Hint: you can just show that the function is monotone, then this suffices for the function to be injective.
Hint 2: you have to show that the function doesn't change from positive to negative or to negative to positive, then the function will be monotone.
Answer: A kind of horizontal line test would be this:
$f(a)=f(b)$ iff $\sqrt{4a^2+1} = \sqrt{4b^2+1}$ iff $4a^2+1 = 4b^2+1$ iff $4a^2 = 4b^2$ iff $a^2=b^2$.
The latter means $a=b$ or $a=-b$. But the domain is nonnegative and so $a=b$.


Criar tabelas em um banco mysql hospedado no Locaweb

Question: Preciso adicionar uma tabela no meu banco de dados.
Como faço pra adicionar uma tabela a este banco hospedado na locaweb? Tem de ter algum software ou posso subir algum arquivo?
Comment: `create table nome_da_tabela` ?
Comment: Então é bom começar por aqui: https://dev.mysql.com/doc/
Comment: Você está com dúvida no script pra criar a tabela ou em como conectar pra poder ter acesso a execução de scripts?
Comment: Mas eu devo colocar no meu arquivo sql pronto e subir pro servidor ou fazer um novo arquivo?
Comment: eu não sei como criar a tabela, já que já uso o banco de dados.
Answer: Você deve entrar no cPanel do domínio em questão, clicar no ícone referente ao phpMyAdmin e na barra de menu superior clicar na aba SQL. Irá abrir uma área de texto onde você digitará o comando para adicionar uma tabela.
Seguindo esse modelo:
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);

Um exemplo:
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)

Comment: vou tentar aqui. Obrigada


Load thousand of values from json

Question: I want to hit an api where i will get lots of values and want to show on the listview.
Showing the data on listview i can do that but problem is the i can not load full data in my android app. when i hit the api in response only i get few data or can say only few line but the data is in thousands of line.
When i hit the api from web browser it shows all the data but when i use it on my android app on the button hit is only gives limited data.
Thanks in Advance :)
Code for my getting data on button hit
try {
                 String url = "my url";

             HttpHandler sh = new HttpHandler();

                // Making a request to url and getting response
                String jsonStr = sh.makeServiceCall(url);

                Log.e("Response from url:", "" + jsonStr);

        }

+++++++++++++++++++++++++
HttpHandler class code
public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}
Comment: How do you know it's giving limited data on your device? Have you printed the length of the response? Because the debugger cuts off data when it's too long
Comment: put your json parsing code.
Comment: @Denny i i have log the values of response. It showed only 40-50 line data only.
Comment: thanks everyone for your concern :) and @Denny thanks for the information about debugger i was printing the response directly show it was showing limited but by printing one by one i got all the values.
Comment: @pskink it was showing only 40-50 lines data i didnt knew that debugger only show limited lines of data. now its working
Comment: Possible duplicate of [Android - Set max length of logcat messages](http://stackoverflow.com/questions/8888654/android-set-max-length-of-logcat-messages)
Answer: Seems like a debugger issue cutting off messages that are too long
See Android - Set max length of logcat messages for more

Load thousand of values from json


C# Passing lock objects to generic cache access method

Question: I've got a generic cache access method inside a singleton class that takes three parameters.

a delegate (void return type with no parameters)
a cache label
a lock object designed to stop concurrent cache setting

See below:
protected delegate T GetDataMethod<T>();

protected override D GetCachedData<D>(GetDataMethod<D> dataAccessMethod, string cachelabel, object lockObject)
    {

        if (MemoryCache.Default[cachelabel] == null)
        {
            lock (lockObject)
            {
                //Inside the lock, test once again in case the cache object has been set already
                if (MemoryCache.Default[cachelabel] == null)
                {
                    umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, -10, cachelabel + " inside lock, cache empty");

                    D data = default(D);

                        try
                        {
                            data = dataAccessMethod();
                        }
                        catch (Exception ex)
                        {

                          //Logging
                        }

                    MemoryCache.Default.Add(cachelabel, data, GetCacheItemPolicy());
                }
            }
        }

        return (D)MemoryCache.Default[cachelabel];
    }

I've got separate lock objects for each of the data collections that get cached set as static readonly objects. However, by passing them to the method their scope only exists within the method so the lock becomes irrelevant.
I can't use 'ref' as you can't pass a static object by ref, given that the surrounding class is a singleton, will it matter if I make the lock objects non static? If it will, can anyone recommend a better way of handling it without using a switch statement based on the cacheLabel?
EDIT:
Just for clarity the method footprint:
 protected override D GetCachedData<D>(GetDataMethod<D> dataAccessMethod, string cachelabel, ref object lockObject)

won't work as the lock objects are static. I guess the question really is - Inside a singleton, do lock objects need to be static to be threadsafe? (Yes, it's a thread safe singleton)
Comment: Using a ConcurrentDictionary for your cache would relieve you http://msdn.microsoft.com/en-us/library/dd287191.aspx  unless of course your question is just a thought exercise.
Comment: `their scope only exists within the method`:: your lock objects are reference types aren't they? If so, can you explain what you mean any more?
Comment: Thanks for the comments so far guys. You can't pass a static object by ref, if I remove the static declaration, doesn't that negate the point of the lock object? Or, given the fact that the method is in a singleton negate that negation...

It's more than a thought exercise, the setters for the MemoryCache object aren't thread safe (as I found out to my own pain), and the data request takes quite a bit of time through EF so I need to lock the setter method to prevent multiple threads filling the various cache items (hence the two stage check - once before the lock, and once inside the lock)
Comment: @TimRogers I've edited the original question for clarity.
Answer: I think you're missing the point of the ref keyword - you don't need it. You're passing an object which is already a reference type. Adding the ref keyword will make it a reference to a reference.
Comment: Apologies for this question, notenough coffee, and too much time spent looking at the same 8 lines of code turned off my brain...


Override default drupal_set_message() on node creation

Question: I am creating a simple basic module that alters the text of a submit button and should change the default creation message with drupal_set_message().
I've found an example about changing the message, and changed the code a little.
 function ask_admin_form_alter(&$form, $form_state, $form_id) {
   if ($form_id == "vragen_node_form") {
     $form['actions']['submit']['#value'] = 'Stel Uw Vraag';
     $form['buttons']['submit']['#submit'][0] = 'ask_admin_node_form_submit';
   }
 }

 function ask_admin_node_form_submit($form, &$form_state) {
   global $user;

   $node = node_form_submit_build_node($form, $form_state);
   $insert = empty($node->nid);
   node_save($node);
   $node_link = l(t('view'), 'node/'. $node->nid);
   $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
   $t_args = array('@type' => node_get_types('name', $node), '%title' => $node->title);

   if ($insert) {
     watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
     drupal_set_message(t('Uw vraag is met succes ontvangen en zal zo spoedig mogelijk beantwoord worden.', $t_args));
   }
   else {
     watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
     drupal_set_message(t('U heeft uw vraag met succes gewijzigd.', $t_args));
   }
   if ($node->nid) {
     unset($form_state['rebuild']);
     $form_state['nid'] = $node->nid;
     $form_state['redirect'] = 'node/'. $node->nid;
   }
   else {
     // In the unlikely case something went wrong on save, the node will be
     // rebuilt and node form redisplayed the same way as in preview.
     drupal_set_message(t('Er ging iets mis bij het verzenden van uw vraag.'), 'error');
  }
}

Although the form button is indeed changed to my own text, the message won't change when the node is created.
When I copy and paste the whole tutorial, my node messages won't change, but I also get no error messages.
Does anyone knows what is wrong, or how I can change the message using other code?
Answer: Change $form['buttons']['submit']['#submit'][0] to $form['actions']['submit']['#submit'][0] in your HOOK_form_alter().
I don't know why that tutorial has you modifying the $form['buttons'] array. Very few forms will put something as important as the primary Submit button outside of $form['actions'], and certainly not a core form.
Comment: Thanx man!!! Worked like a charm. To bad i can't accept the answer yet(someone else can?) neither can i vote up. So if anyone reads this, please give eclecto some points.
Answer: This: $form['buttons']['submit']['#submit'][0] = 'ask_admin_node_form_submit';
Should be this: $form['#submit'] = array('ask_admin_node_form_submit'); if you want to completely override default form processing.
Answer: You can suppress the message with https://www.drupal.org/project/disable_messages with a regex rule like:
Vraag .*? has been created.

or if translated
Vraag .*? is aangemaakt.

Then add your own custom message with Rules or with drupal_set_message() in a HOOK_form_alter()


Expressing $\mathbb{E}[X_1X_2 \ldots X_n]$ as their pairwise correlations

Question: Let's say we have a sequence of almost surely bounded random variables $X_1,\ldots,X_n$, and their pairwise correlation is given by some covariance structure
$$ \mathbb{E}[X_i X_j] = K_{ij}. $$
Is it possible now to express $\mathbb{E}[X_1 X_2\ldots X_n]$ in terms of $(K_{ij})_{i,j}$? Preferably I'd like to say something along the lines of
$$ \mathbb{E}[X_1 X_2 \ldots X_k] = K_{12} K_{23} \ldots K_{k-1k}, $$
but I don't even know if this is possible! I can't seem to find anything on expectations of products involving multiple correlated random variables.
EDIT: If we restrict ourselves to the case where the $X_i$ are symmetric random variables, then $X_i \stackrel{d}{=} -X_i$, so for odd $k$ we can at least say:
$$ \mathbb{E}[X_1X_2\ldots X_k] = (-1)^k \mathbb{E}[X_1X_2\ldots X_k], $$
implying that $\mathbb{E}[X_1 X_2 \ldots X_k] = 0$.
Comment: For Gaussian variables this is the "Isserlis theorem"
 https://math.stackexchange.com/q/2353878/532409
Comment: Not in general, but in [certain specific situations, it can be done.](https://en.wikipedia.org/wiki/Isserlis%27_theorem)
Comment: @Raskolnikov in the Gaussian case only... this is what I was worried about... Thanks anyway.
Answer: Example 1: Let $X_1,X_2,X_3$ are i.i.d. $\text{Bernoulli}(\tfrac{1}{2})$ random variables.
Then, $K_{ij} = \mathbb{E}[X_iX_j] = \begin{cases}\tfrac{1}{2} & \text{if} \ i = j\\ \tfrac{1}{4} & \text{if} \ i \neq j\end{cases}$, and $\mathbb{E}[X_1X_2X_3] = \tfrac{1}{8}$.
Example 2: Let $X_1,X_2,X_3$ be random variables such that $(X_1,X_2,X_3)$ takes on the values $(0,0,0), (0,1,1), (1,0,1), (1,1,0)$ each with probability $\tfrac{1}{4}$.
Then, $K_{ij} = \mathbb{E}[X_iX_j] = \begin{cases}\tfrac{1}{2} & \text{if} \ i = j\\ \tfrac{1}{4} & \text{if} \ i \neq j\end{cases}$ (just as in Example 1), but $\mathbb{E}[X_1X_2X_3] = 0$.
So in general, you need more information than just the covariances $K_{ij} = \mathbb{E}[X_iX_j]$ to compute $\mathbb{E}[X_1X_2 \cdots X_n]$.


Como mudar projeto padrão no FIrebase via terminal?

Question: estou tentando hospedar um website no firebase, segui corretamente os passos que me foram orientados pela plataforma.
Eu defini um projeto padrão na etapa do "firebase init" e agora quero definir outro, mas não faço ideia de como fazer.
Nem a documentação, nem o "firebase deploy help" informam isso claramente, e estou começando a perder as esperanças. help!!
Comment: Você quer iniciar outro projeto do firebase?
Comment: Você definiu o projeto padrão em um diretório. Se você quiser criar outro projeto, abra um outro diretório e faça o `firebase init`
Answer: poderá usar o comando do Firebase seguinte: Firebase use < alias >
Onde está alias, será o nome do projeto que você criou.


How to decode nvarchar to text (SQL Server 2008 R2)?

Question: I have a SQL Server 2008 R2 table with nvarchar(4000) field.
Data that stores this table look like
'696D616765206D61726B65643A5472'
or
'303131' ("011").
I see that each char is encoding to hex.
How can I read those data from table? I don't want write decoding function, I mean that simpler way exists.
P.S. Sorry for my English.
Answer: SQL Server 2008 actually has a built-in hex-encoding and decoding feature!
Sample (note the third parameter with value "1" when converting your string to VarBinary):
DECLARE @ProblemString VarChar(4000) = '54657374'
SELECT Convert(VarChar, Convert(VarBinary, '0x' + @ProblemString, 1))

Ref: http://blogs.msdn.com/b/sqltips/archive/2008/07/02/converting-from-hex-string-to-varbinary-and-vice-versa.aspx
The advantage of this approach is that you don't need the "Exec" call, which you generally try to avoid, for fear of injection among other things. The disadvantage is that it only works in SQL Server 2008 and later.
Answer: You will need a decoding function I think, the simplest:
declare @fld nvarchar(4000) = '696D616765206D61726B65643A5472'

exec('SELECT CONVERT(varchar(max),0x' + @fld + ')')

---------------
image marked:Tr

Comment: declare @fld nvarchar(4000)

set @fld = '696D616765206D61726B65643A5472'
exec('SELECT CONVERT(varchar(max),0x' + @fld + ')')      I think this will be more precise
Comment: True, although for what its worth `declare @v type = value` is supported in sql 2k8


What is a "second generation tracker"? (or first or third)

Question: I'm looking at the MilkyTracker application description and it claims that

"MilkyTracker is and will stay a 2nd generation tracker. There are already several good 3rd generation trackers out there"

What do these "generations" of tracker software refer to?
so that can assess whether I need to search out one of these 3rd (or 1st?) generation trackers.
Answer: It refers to the batch of tracking software that would have been out at the time.  It considers itself a second generation tracker probably because it's now quite old.
Think of it as similar to generations of consoles.  If the N64 and Playstation were second generation consoles, then the GameCube and PS2 would be third generation consoles, while the sega genesis/megadrive and snes would be first generation.
There are often blurred lines between generations, but each generation generally refers to a feature set or way of working that would have defined that generation of consoles, or in this case trackers.
When they say they won't become a third gen what they really mean is that they're not going to update/overhaul the system, so don't expect them to(in marketing speak).
There's a great description on the history of trackers at http://en.wikipedia.org/wiki/Music_tracker.
The answers you look for are there, with MSDOS trackers being first generation, and trackers released past 2010 being third generation(roughly).
Hope that helps!
Comment: I was always under the impression that the generation of a tracker was based on the generation of programming languages used: http://en.wikipedia.org/wiki/Programming_language_generations

Do you have a source to back up what you say so that I can be confident that you're right before taking this as correct?
Comment: something more concrete would be helpful here. If Milkytracker is a 2nd gen tracker, then is something like Reason a 3rd gen tracker? Where is the list of 3rd gen trackers for mac?


How to split jQuery plugin over multiple files

Question: I'm writing a small CMS as a jQuery AJAX plugin and though it's by no means excessively long (currently about 500 lines) I can see it would be nice to be able to split it into separate files, one for each "subclass":
<code>(function($) {
    $.fn.myCMS = function() {
        this.classOne = function() {
        ...
        }
        this.classTwo = function() {
        ...
        }
    }
})(jQuery);
</code>
In the example above, I would like to put the code for classOne in one file, classTwo in another and the myCMS "baseclass" in a third. Is it possible to achieve this with with something like this (in each of the "subclass" files)?
<code>$.extend(myCMS,classOne = function() {
...
})
</code>
Many thanks,
JS
Answer: You want to add to the "plugin" with a private scope / separation of concern.  This can be important for maintenance and long-term extensibility of your plugin-based web application, regardless of whether everything will be built into one file or multiple files.
You can create a private scope and extend an existing jQuery.fn method by attaching methods directly or by adding to the jQuery.fn.foo method's prototype
<code>(function ($) {

     // instance method attached to the constructor function
     $.fn.myCMS.classOne = function () {

     };

     // or "shared" method attached to prototype
     $.fn.myCMS.prototype.classOne = function() {

     };

})(jQuery);
</code>
You can use jQuery.extend(), which in this case is really a "shorthand" for adding a method to the constructor instance as the first method above.  You have to encapsulate whatever you're adding into an object (typically this would be an anonymous object):
<code>$.extend($.fn.myCMS,{ classOne: function () { } });
</code>
From a design perspective if you have "classes" that need to get at the same closured variables frequently they should probably be part of the same function scope/closure, or you should expose getters and setters for those closured variables (perhaps with the _foo convention that shows they are intended to be used only by your code).
<code>(function ($) {

    var foo = "foo!";

    // combined getter/setter
    // could also check arguments.length
    $.fn.myCMS._foo = function (value) {
          if (typeof(value) != "undefined") {
               foo = value;
          } else {
               return foo;
          }
    };

)(jQuery);
</code>
If you want to be a hacker and you need to get at closured variables from a different scope, I believe you can do so by executing these new methods with their own scope using .call() or .apply() from the other scope.  I can try to whip up some samples of how this works, but it will be a good idea if you do your own research into how scope resolution works in these kinds of scenarios.
I believe you can "borrow" the scope from the original "plugin" method by using a with ($.fn.myCMS) {  } construction but I am not 100% positive about that because I haven't done it myself, only read about it.
Answer: It will help to also look at jQuery ui code. For example, the progressbar plugin requires three files ui.core, ui.widget and ui.progressbar. Download the jQuery UI source bundle and look at the progressbar example under demos directory. (I couldn't find the simplified version hosted anywhere, but the source bundle has simplified examples)


xpath XML parser is not parsing anything, neither does give any debug info

Question: Mappings:
https://www.evernote.com/shard/s61/sh/3e900019-a2c7-4a10-bc1c-0868341c4d9d/a735396d74047a86da8668c34c7a9f7d
Source feed:
https://www.monosnap.com/image/BmKv9p9ao4hua1wvWpRh2pl85
For some reason I can't get it to import anything. What am I missing?
Tried also context: //channel/item.
Feed path: http://poliisi.fi/poliisi/kanta-hame/home.nsf/feedrss.xml
This is very simple and basic feed which is giving me a major headache currently. Maybe a fresh pair of eyes is smarter than mine.
Answer: Solved. Module had some odd bug. Cloning earlier working importer and changing it identical to above worked.


MS RMS SQL Server Database error

Question: We have had an issue with our RMS_Headquarters(front end application to access database) database running on SQL Express 2005.
After checking all the event log on server, I came across few errors related to hard disk and sqlserver.
disk error snapshot
sqlexpress error
I have executed two commands as follows to find out any error in disk or on sql database.
chkdsk  : System found bad sectors on hard disk I ran this code without /f to just get the information.
DBCC CHECKDB with ALL_ERRORMSGS, NO_INFOMSGS    and the outcome was as below.
I ran chkdsk /f to resolve the disk error. This command helped to get hq database up and running (application was working fine from this point). I also ran DBCC CHECKDB with ALL_ERRORMSGS, NO_INFOMSGS on sql server to check database status. DBCC executed with few errors, please see below.
<code>Msg 8928, Level 16, State 1, Line 1
Object ID 1429580131, index ID 1, partition ID 72057598907908096, alloc unit ID 72057598960730112 (type In-row data): Page (1:235150) could not be processed.  See other errors for details.
Msg 8941, Level 16, State 2, Line 1
Table error: Object ID 1429580131, index ID 1, partition ID 72057598907908096, alloc unit ID 72057598960730112 (type In-row data), page (1:235150). Test (sorted [i].offset <= m_freeData)
failed. Slot 0, offset 0xffff is invalid.
Msg 8976, Level 16, State 1, Line 1
Table error: Object ID 1429580131, index ID 1, partition ID 72057598907908096, alloc unit ID 72057598960730112 (type In-row data). Page (1:235150) was not seen in the scan although its
parent (1:306430) and previous (1:235149) refer to it. Check any previous errors.
Msg 8978, Level 16, State 1, Line 1
Table error: Object ID 1429580131, index ID 1, partition ID 72057598907908096, alloc unit ID 72057598960730112 (type In-row data). Page (1:235151) is missing a reference from previous page
(1:235150). Possible chain linkage problem.
CHECKDB found 0 allocation errors and 4 consistency errors in table 'TenderEntry' (object ID 1429580131).
CHECKDB found 0 allocation errors and 4 consistency errors in database 'RMS_Headquarters'.
repair_allow_data_loss is the minimum repair level for the errors found by DBCC CHECKDB (RMS_Headquarters).
</code>
System Information:

OS:         Windows Server 2003 R2
SQL Server:         SQL Server 2005 (9.0.4035)

I have a backup from Sunday(20th April 2015) evening, that backup doesn't report any error.
Please advise me what should be done in this matter:
(a) restore the database from a backup dated 20th April 2015 (what data from 21st onwards will be lost)
(b) continue with this database and ignore the 'tenderentry' table errors
Your help will be appreciated.
Regards
Pratik
Comment: it did not allow me to post images
Comment: **chkdsk : System found bad sectors on hard disk** This means you need to replace or fix your disk before you bother trying to restore the database.
Answer: (a)restore the database from a backup dated 20th April 2015 (what data from 21st onwards will be lost)
Yes Data will be lost because your backup was last updated on 20 April 2015.
(b)continue with this database and ignore the 'tenderentry' table errors
Personally I will not suggest this because it might be possible that you will have a bigger corruption issues in future. Fixing corruption as an earlier stage should be on priority. It helps to maintain database health.
And please not run DBCC CHECKDB with repair_allow_data_loss without knowing the effect of it.

MS RMS SQL Server Database error


How to calculate the user's average rating on all his/her nodes with Fivestar?

Question: On my website, users can rate each other's nodes via a Fivestar field called Stars in a comment. I'd now like to calculate the overall average score of a user. That means, I'd like to display the user's average score for all his/her nodes.
For example. Let's say a user created 2 nodes: Node 1 and Node 2. Some people rated his content:

Scores of Node 1: 4/5, 5/5, 3/5
Scores of Node 2: 4/5, 4/5

The overall average would then be (4+5+3+4+4)/5=4.
Preferably, this result should also be displayed as stars.
How can I do that?

Edit 1: Working with the Computed Field module seems to be a general idea to solve this matter. It looks fine to me and I think it's best to store the users' average score in a user field, in order to make it easily accessable. (Working with a view is also fine.) I'm planning to display the average score on their profile page, but perhaps I'm going to use it elsewhere on the website in the future too.
Can you please help me with (a scetch) of the code I'm supposed to use?

Edit 2: I created a user field called Gemiddelde and pasted @Thomas4019's code in my custom module hiderating (the module's title refers to an earlier question), but it gave me the following error:

Warning: Missing argument 5 for    computed_field_field_gemiddelde_display(), called in C:\wamp\www\mysite\sites\all\modules\computed_field\computed_field.module
  on line 341 and defined in computed_field_field_gemiddelde_display()(line 24 of
  C:\wamp\www\mysite\sites\all\modules\hiderating\hiderating.module).
Notice: Undefined variable: entity in    computed_field_field_gemiddelde_display() (line 30 of C:\wamp\www\mysite\sites\all\modules\hiderating\hiderating.module).
Notice: Trying to get property of non-object in computed_field_field_gemiddelde_display() (line 30 of C:\wamp\www\mysite\sites\all\modules\hiderating\hiderating.module).

The Gemiddelde field in the view on my profile page has the following value:

0

No votes yet

Edit 3: After reinstalling the Computed Field module and clearing caches, the error messages are gone, but the Gemiddelde field in my view still displays the following CSS code:

3

Average: 3 (1 vote)

What went wrong?
Comment: How strange! Could you post the line 341 from C:\wamp\www\mysite\sites\all\modules\computed_field\computed_field.module? I imagine your using computer field  version 7.x-1.0 right?
Comment: @Thomas4019: Yes, that's the version I'm using. Line 341 is the default one, I didn't change the code in the files. `$display_output = $display_func($field, $entity_field_item, $entity_lang, $langcode);` The bounty is yours if you can fix this.
Comment: Line 341 for me is $display_output = $display_func($field, $entity_field_item, $entity_lang, $langcode, $entity); I have no idea why they would be different. Maybe try redownloading computed field?
Comment: @Thomas4019: I redownloaded the module and now the `$entity`is there again! Very odd... After clearing caches, the *Gemiddelde* field in my view still displays CSS code. You can find the code in **Edit 3**. Did you test your code? It would be quite strange if it worked on your website and not on mine...
Comment: Usually what is documented in [Fivestar 7.x: Creating a User Comment/Rating and Average Rating for a Content type](https://www.drupal.org/node/1308114), should be all you need. It provides detailed instructions about: 1. Setting Up the Content Type (node-type)
2. Setting Up the Comments/Ratings
Answer: I know that something like this can be done with computed field. It will require some PHP code though. See some discussion here
Here's what you need to do:

Install Computed Field and Fivestar
Go to admin/config/people/accounts/fields and create a computed field on the user entity type. In my case I named it "field_computed_rating". On the settings form for the field make sure the checkbox "Store value in the database" is unchecked.
Click on "Manage Display" for the content type you created the field on. Then make sure the format for that field is set to "Unsanitized".
(if you already have a custom module you can skip this step) In your code base within sites/all/modules, create a new folder titled fivestar_user_aggregate. Within that folder you will need to create  fivestar_user_aggregate.info with the following contents.
name = Fivestar User Aggregate
description = Assign users an aggregate rating based on all their nodes
core = 7.x
package = Custom

Add this custom php function to your module file or create fivestar_user_aggregate.module within fivestar_user_aggregate with the following contents. If you named your field differently then you will need to modify the function name accordingly.
<?php

function computed_field_field_computed_rating_display($field, $entity_field_item, $entity_lang, $langcode, $entity) {
    $result = db_query("SELECT n.uid, n.nid, vote1.value AS count, vote2.value AS average FROM {node} n
INNER JOIN {votingapi_cache} vote1 ON n.nid = vote1.entity_id
AND vote1.function =  'COUNT'
INNER JOIN {votingapi_cache} vote2 ON n.nid = vote2.entity_id
AND vote2.function =  'average'
WHERE n.uid = :uid", array(':uid' => $entity->uid));

    $rating_count = 0;
    $rating_total = 0;

    $nodes = $result->fetchAll();
    foreach ($nodes as $node) {
        $rating_count += $node->count;
        $rating_total += $node->average * $node->count;
    }

    if ($rating_total == 0) {
        $weighted = 0;
    } else {
        $weighted = $rating_total / $rating_count;
    }

    $variables = array(
        "rating" => $weighted,
        "average_rating" => $weighted,
        "votes"  => $rating_count,
        "stars" => 5
    );
    $variables["widget"]["name"] = "basic";
    $variables["widget"]["css"] = "sites/all/modules/fivestar/widgets/basic/basic.css";
    drupal_add_css(drupal_get_path('module', 'fivestar') .'/css/fivestar.css');
    return theme('fivestar_static', $variables) . theme('fivestar_summary', $variables);
}

Enjoy! You should now see a weighted average of all a user's node's ratings on their page.
Comment: Thanks for your answer, Thomas. The discussion you refer to only handles a solution for computing the average score for multiple votes on the *same* nodes. Just to make sure you've interpret my question correctly: I'd like to compute the average score of *multiple* node. Anyway, thank you for the link: it might come in handy in the future.
Comment: It's not a simple problem. You can see someone else's [similar question](http://drupal.stackexchange.com/questions/16293/combine-multiple-fivestar-rating-fields-into-an-average). With computed field you can put in arbitrary PHP code so you can put in code that does the necessary SQL query to pull the ratings of all a users nodes and then calculates an average.
Comment: Your idea of working with Computed Field sounds doable. Can you perhaps help me a bit with the PHP code?
Comment: First of all, thanks a lot for working this out for me! Your update looked very promising, but unfortunately, it doesn't work yet. I pasted the error messages I get in an **Edit 2**.
Comment: GREAT NEWS! I found the solution! There's nothing wrong with your code, but the *Gemiddelde* field's formatter in my view was incorrect. It was switched on *Plain text* instead of *Unsanitized*. You really deserved my bounty: THANKS A LOT!
Comment: Awesome! Thanks for mentioning that last step. I added it to the answer for future viewers. I'm glad it all worked out!
Answer: Jeroen,
Firstly, where do you want this info to show up? If this is a user page, go ahead with Computed Field, else, if this is something like a listing page, or a view, then you can use Views PHP. In both cases, you will have to code to fetch the results.
You will have to fetch the nodes of the user, sum up all the ratings on all the nodes, and then take an average. This would be your result.
Comment: I've updated my question in order to give you some more information.
Answer: Did you try Views Aggregation ? I think with a little work it can do what you need.
Comment: Can you be a little bit more specific? The screencast in the link you mention doesn't handle calculating average results, neither do any of the related videos about aggregation.
Comment: In a view with your field, gather all values and activate aggregation and set 'average'.
Answer: Yet another approach, as per the "Working with a view is also fine" in the question:

Create some view that contains the relevant data, filters, sorting, etc.
Use the Views_calc module to have the average displayed below the views result.

Here is a typical screenprint of such table:

Refer to my answer to the question about "How can I show average votes of fivestar nodes?" for more details on this.
Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
Answer: I have recently stumbled upon this problem again and I solved it with Views Aggregation myself in a couple of minutes without thinking about this old question. I would like to add my solution as an alternative answer for people who are not (yet) into programming. The View is set as follows:

Create a new unsorted View that displays comments.
Check that there is already a relation to the content, i.e. the node that received the comment, in the advanced settings.
Add a contextual filter to the author uid of the content. In my case, I display the View on the user pages, so I set the default value to the uid in the URL.
Next, enable Aggregation in the Other section of the advanced settings.
Add the field Stars, display the value as stars and change the aggregation settings to average (type) and rating (group).
Add additional filters if necessary. For example, I filtered on approved comments with a non-zero vote on published nodes of a specific type.

Done! If you are reading this as a Drupal beginner, you can interpret this story as a kind of reassurance: don't give up and you will make enormous progressions, even if you don't believe it yet.


SQL And Drupal skips admin set up

Question: I filled out the Database name, Database username, password, and port number within the Drupal set up. I selected continue, then the page loads for a long time. Next, I was leaded to another page saying, Drupal already installed. Next, I clicked on View your existing site, displaying the log in for the admin. Drupal literally skipped the admin set up, resulting in not allowing me to log in as admin. Anyone is familiar with this error? Is this even an error, or the norm for Drupal (since I seen other users experiencing this errors, but no answers)?
Drupal explain the the error is the following

The website encountered an unexpected error. Please try again later.
  Drupal\Core\Config\UnmetDependenciesException: Configuration objects
  (automated_cron.settings, block.block.bartik_account_menu,
  block.block.bartik_branding, block.block.bartik_breadcrumbs,
  block.block.bartik_content..

If anyone that knows this, feel free to provide some input.
Answer: You are asking a lot of questions at the same time, but I assume your main question is How to recover from this failed installation?
You are seeing an UnmetDependenciesException, which means Drupal requires stuff (has a dependency) that has not been loaded... So probably several system modules did not install properly.
That would also explain the behavior you are experiencing, your Drupal installation is broken...
Best would be to start over from scratch, remove all the files and the database tables and try again. Also verify if you have met all of the web server requirements (Drupal 7 & 8).
Comment: Thanks, however all files are loaded according to the tutorial (there is only one tutorial on the internet that displays how to connect sql with drupal)  http://www.drupalonwindows.com/en/blog/installing-drupal-8-windows . Therefore this has to be either drupal, or microsoft driver itself. Strange enough, on Chrome, it went from the page saying "already installed" to the install bar, installing, however when I re did it, I was unable to get to the install bar (unable to install again). Basically Drupal and MSSQL is broken. Otherwise, it would work.

SQL And Drupal skips admin set up


Problemas ao organizar uma struct em C

Question: Estou tendo problema ao organizar os dados de uma struct, os dados até estão organizando, mais acabo sempre recebendo lixo de memoria na primeira posição, as demais são organizadas normalmente sem erros. A estrutura deve ficar em ordem decrescente de acordo com o dado int pont da struct classificados.
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

   typedef struct concurso
  {
  char nome[30];
  int matri;
  int prov1;
  int prov2;
  int prov3;
}con;

typedef struct clasificados
{
  char n[30];
  int m;
  int pont;
}cla;

void ordena(con* co,int tam)
{
  cla *conc=(cla*)malloc(sizeof(cla)*tam);
  cla aux;
  int i,j=0;
  for(i=0;i<tam;i++)
  {
  if((co[i].prov1>40)&&(co[i].prov2>40)&&(co[i].prov3>40)&&(co[i].prov1+co[i].prov2+co[i].prov3>=150))
  {
    conc[j].pont=co[i].prov1+co[i].prov2+co[i].prov3;
    strcpy(conc[j].n,co[i].nome);
    conc[j].m=co[i].matri;
    j++;
  }
  }
//O PROBLEMA ESTA DAQUI PARA BAIXO, AQUI QUERO ORDENAR OS DADOS DA STRUCT CLASSIFCADOS, ATE QUE ORDENA, MAIS O PRIMEIRO ELEMENTO SAI COMO LIXO DE MEMORIA
    for( i=0; i<j; i++ )
    {
      if( conc[i].pont < conc[i+1].pont )
      {
        aux.pont = conc[i+1].pont;
        conc[i+1].pont = conc[i].pont;
        conc[i].pont = aux.pont;

        strcpy(aux.n,conc[i+1].n);
        strcpy(conc[i+1].n,conc[i].n);
        strcpy(conc[i].n, aux.n);

        aux.m = conc[i+1].m;
        conc[i+1].m = conc[i].m;
        conc[i].m = aux.m;
        i=-1;
      }
    }

    printf("\n\t\t------Classificados-------\n");
    printf("\nPOSICAO\t\tMATRICULA\tCANDIDATO\tNOTA\n");
    for( i=0; i<j; i++ )
    {
      printf("%d\t\t%d\t\t%s\t\t%3d\n",i+1,conc[i].m,conc[i].n,conc[i].pont);
    }
    free(conc);
}

int main()
{
  int i,j;
  int tam;
  printf("Digite o numero de candidatos: ");
  scanf("%d",&tam);
  con *c=(con*)malloc(sizeof(con)*tam);

  for(i=0;i<tam;i++)
  {
    printf("Digite o nome do candidato %d: ",i+1);
    scanf(" %[^\n]s",c[i].nome);

    printf("Digite a matricula do candidato %s: ",c[i].nome);
    scanf("%d",&c[i].matri);

    printf("Digite a nota 1 do candidato %s: ",c[i].nome);
    scanf("%d",&c[i].prov1);

    printf("Digite a nota 2 do candidato %s: ",c[i].nome);
    scanf("%d",&c[i].prov2);

    printf("Digite a nota 3 do candidato %s: ",c[i].nome);
    scanf("%d",&c[i].prov3);
  }
  ordena(c,tam);

  free(c);

 return 0;
}

Comment: Testei de uma forma rápida o seu código, e pareceu-me funcionar corretamente. [Confirme aqui no Ideone](https://ideone.com/Gc9VtK) se não era o resultado que esperava. Por isso convido-o a detalhar melhor o problema. Quais as entradas que utilizou para que não funcione ? Lembro que quando gera os classificados se apenas um se qualificar tem um problema no `if` que testa logo dois elementos do array.
Comment: Então, nos compiladores on-line o código não apresenta problemas, mas nos locais como code blocks, dev; acontece esse erro que mencionei de imprimir lixo de memória na primeira posição.
Comment: Nao entendi  esse problema do "if", poderia me exemplificar melhor. Obrigado
Comment: Eu executei no codeblocks e correu igual ao que aparece no Ideone. Quais os valores exatos que está a usar como entrada? E o problema vem neste `if` => `if( conc[i].pont < conc[i+1].pont )` que de acordo com o `for` anterior não ha garantia que `i+1` seja um elemento valido
Comment: Obrigado, vou verificar sobre o if.
Comment: Sobre os valores, estou usando valores aleatórios, ja fiz vários testes, sempre tenho o mesmo erro, mas agora com seu depoimento vou verificar meus compiladores, e testar em outro pc, ai volto aqui, obrigado
Comment: Aproveite e teste com os valores que o link que eu passei no Ideone utiliza. E coloque aqui os valores que está a testar e que diz que falham, para que eu possa testar também e perceber se existe de facto algum problema.
Answer: Cara basicamente o seu erro está no for, o seu for está da seguinte maneira, for( i=0; i<j; i++ ), desta maneirai quando você faz o seu vetor no índice i + 1, quando seu for, chegar no ultimo loop ele irá dar buffer overflow, e estourar a posição de memória pertencente ao seu vetor.
Para arrumar este erro basta na condição do seu for você colocar, i < j - 1, fiando da seguinte maneira for( i=0; i<j-1; i++ ).
Sem mais delongas aqui está a resposta completa:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct concurso
{
    char nome[30];
    int matri;
    int prov1;
    int prov2;
    int prov3;
} con;

typedef struct clasificados
{
    char n[30];
    int m;
    int pont;
} cla;

void ordena ( con* co, int tam )
{
    cla* conc = (cla*)malloc(tam * sizeof(cla));
    cla aux;
    register int i , j;

    for ( i = 0, j = 0 ; i < tam; ++i ) {
        if ( (co[i].prov1 > 40) && (co[i].prov2 > 40) && (co[i].prov3 > 40) && (co[i].prov1 + co[i].prov2 + co[i].prov3 >= 150) )
        {
            conc[j].pont = co[i].prov1 + co[i].prov2 + co[i].prov3;
            strcpy(conc[j].n, co[i].nome);
            conc[j].m = co[i].matri;

            ++j;
        }
    }

    /*  O PROBLEMA ESTA DAQUI PARA BAIXO,
        AQUI QUERO ORDENAR OS DADOS DA STRUCT CLASSIFCADOS,
        ATE QUE ORDENA, MAIS O PRIMEIRO ELEMENTO SAI COMO LIXO DE MEMORIA   */
    for ( i = 0; i < j - 1; ++i ) {
        if ( conc[i].pont < conc[i+1].pont )
        {
            aux.pont = conc[i+1].pont;
            conc[i+1].pont = conc[i].pont;
            conc[i].pont = aux.pont;

            strcpy(aux.n,conc[i+1].n);
            strcpy(conc[i+1].n,conc[i].n);
            strcpy(conc[i].n, aux.n);

            aux.m = conc[i+1].m;
            conc[i+1].m = conc[i].m;
            conc[i].m = aux.m;

            i = -1;
        }
    }

    printf("\n\t\t------Classificados-------\n");
    printf("\nPOSICAO\t\tMATRICULA\tCANDIDATO\tNOTA\n");

    for ( i = 0; i < j; ++i )
        printf("%i\t\t%i\t\t%s\t\t%3i\n", i+1, conc[i].m, conc[i].n, conc[i].pont);

    free(conc);
}

int main()
{
    register int i,j;
    int tam;
    con* c;

    printf("Digite o numero de candidatos: ");
    scanf(" %i", &tam);

    c = (con*)malloc(tam * sizeof(con));

    for ( i = 0; i < tam; ++i ) {
        printf("Digite o nome do candidato %d: ", i+1);
        scanf(" %[^\n]s", c[i].nome);

        printf("Digite a matricula do candidato %s: ", c[i].nome);
        scanf(" %i", &c[i].matri);

        printf("Digite a nota 1 do candidato %s: ", c[i].nome);
        scanf(" %i", &c[i].prov1);

        printf("Digite a nota 2 do candidato %s: ", c[i].nome);
        scanf(" %i", &c[i].prov2);

        printf("Digite a nota 3 do candidato %s: ", c[i].nome);
        scanf(" %i", &c[i].prov3);
    }

    ordena(c,tam);

    free(c);

    return 0;
}

Espero ter ajudado ;).
Comment: obrigado cara, tinha solucionado o problema fazendo outra função, mas ajudou muito, muito obrigado

Problemas ao organizar uma struct em C


Dummy variable trap in survival models

Question: I am familiar with the dummy variable trap in normal OLS, in which we should include one less dummy variable than the total of categories to avoid the problem of multicollinearity.
However, I was wondering if it is also the case in duration models. Specifically, I am running a Weibull survival model with six dummy variables, exhaustive and mutually exclusive, and there is no sign of multicollinearity (Even if all the coefficients of the dummy variables are negative, which makes it a bit harder to interpret as I'm not sure what the dummies are measuring themselves against).
So the question is: does the dummy variable trap also occur in survival/duration models?
Comment: Should be the same as in OLS...
Comment: Are you also fitting an intercept?
Comment: Very trusting of you! Check the condition number of $X^\mathrm{T}X$ (where $X$ is the design matrix). Or try changing the order in which coefficients are input to the model (I've just experimented with the `survfit` function in R - fitting a Weibull model when the design matrix isn't full rank also gives one of the infinity of possible solutions without warning; it gives different solutions when you vary the order of the predictors).
Comment: Yes, there is also an intercept. Also the AIC is (slightly) higher when I exclude one of the dummy variables, which implies that the model fit is better with all the dummies.
Comment: How are you determining that you don't have perfect collinearity in the design matrix?
Comment: No variables are excluded because of collinearity. I'm using STATA, so in the case of OLS the program warns when I include all dummy variables.
Comment: You're right, I tested for it and the variables are collinear. Thanks for the help!
Comment: @Not Fisher: You're welcome! Think about it: the dummy variable trap only involves the specification of predictors, so is relevant to any linear model. I'll add an answer with more detail if no-one else does, or if those who've already answered don't expand theirs.
Answer: Dummy Variable trap usually occurs in proportional hazards models/semi-parametric models very well.
and yes! you should check significant improvement of each dummy variable you add.
Comment: But *why* can it also occur in these models? And what of the OP's assertion that in their model there isn't perfect collinearity in the model matrix?
Comment: I studied these models are good to test/judge by dummy variables & Yes! Semi-parametric is good for such.
Comment: As @Scortchi said, there is no multicollinearity in the regression output, so that's why I'm not exactly sure it occurs in survival models...
Comment: You know Cox hazard model.
Comment: Very strange second part of the answer.

Dummy variable trap in survival models


Java find and compare members by string (maybe JPA feature?)

Question: I've got alot of beans with attributes, which are derived from database tables with JPA. The users shall be able to enter any column name and a value as a string, and the app shall automatically find the correct member in the one of the beans.
I must use JPA, otherwise I would use some JDBC meta data to put all columns and values into a normal map. Is something like this possible with JPA? It only has to work from database to beans, I don't want to persist changes.
If this doesn't work, can I somehow analyze member names programmatically at runtime?
Answer: The EntityManagerFactory has a getMetamodel() method, which returns its MetaModel. From this MetaModel, you may ask for the MetaModel of every entity class, and discover all its attributes, their types, etc.
Answer: In case the JPA part doesn't work, you can access class members (fields, methods) of your class as follows:
<code>Field[] fs = YouClass.class.getDeclaredFields();
</code>
Details for accessing different members are on this link


How do i change the ETH name?

Question: I have an ubuntu server (meerkat) that I had to replace a NIC since it is failing. So I removed the failing NIC and replaced it with two NICs inserted into two PCI slots on my server.
Everything's well except that one of the NICs name is eth1-eth3. Please see ifconfig -a result below:
eth1      Link encap:Ethernet  HWaddr xx:xx:xx:xx:50:a5
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:16

eth2      Link encap:Ethernet  HWaddr xx:xx:xx:xx:50:a4
          inet addr:xxx.xxx.xxx.98  Bcast:xxx.xxx.xxx.255  Mask:255.255.255.0
          inet6 addr: fe80::204:23ff:fec8:50a4/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:18746 errors:0 dropped:0 overruns:0 frame:0
          TX packets:25886 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:3423836 (3.4 MB)  TX bytes:3148479 (3.1 MB)

eth3      Link encap:Ethernet  HWaddr xx:xx:xx:xx:xx:51
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:24 Base address:0xe800

eth1-eth3 Link encap:Ethernet  HWaddr xx:xx:xx:xx:xx:63
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:28 Base address:0xec00

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:116 errors:0 dropped:0 overruns:0 frame:0
          TX packets:116 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:8124 (8.1 KB)  TX bytes:8124 (8.1 KB)

I googled on how to change the NICs name via 70-persistent-net.rules but I got the following:
# PCI device 0x1186:0x1300 (8139too)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="xx:xx:xx:xx:xx:56", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"

# PCI device 0x8086:0x1076 (e1000)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="xx:xx:xx:xx:xx:a4", ATTR{type}=="1", KERNEL=="eth*", NAME="eth2"

# PCI device 0x11ab:0x4361 (sky2)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="xx:xx:xx:xx:xx:a5", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"

# PCI device 0x1106:0x3106 (via-rhine)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="xx:xx:xx:xx:xx:63", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth3"

# PCI device 0x1106:0x3106 (via-rhine)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="xx:xx:xx:xx:xx:51", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth3"

How do I change eth1-eth3 to just eth4? And why did linux label my new NIC eth1-eth3?
Answer: Change the NAME argument of the second eth3 interface to eth4 in 70-persistent-net.rules, then restart your networking.
Comment: That is only 1/2 right. You have to restart udev (or reboot) to get the new names to take affect.
Comment: I will try to do this later and will update this thread if it solved the problem... Thanks!
Comment: this worked for me. I had to reboot the server to restart udev. I still don't know why linux named the NIC to eth1-eth3 though...
Answer: Take a look at ifrename. I remember it to be very easy to use.
$ aptitude show ifrename

Description : Rename network interfaces based on various static criteria
 Ifrename allow the user to decide what name a network interface will have.
 Ifrename can use a variety of selectors to specify how interface names match
 the network interfaces on the system, the most common selector is the interface
 MAC address.
Site : http://www.hpl.hp.com/personal/Jean_Tourrilhes/Linux/Tools.html

It uses a config file which be used to tell udev how to name the interfaces.

How do i change the ETH name?