How can I link XML pages with layout, by clicking on buttons?

Question: Excuse the simplicity of this request - but is there a way for me to link onClick commands for buttons through the Layout rather than code. I am trying to create a simple app and I want to be able to make buttons and have clicks go from one "page" to the other.
If not, could someone please point me in the direction of the code needed for it?
Is there a site that might overview how to use the UI to code for droid?
Thanks!
Answer: Try using
< Button android:onClick="myClickHandler" />
myClickHandler is a method that must be defined in your activity liek so:
public void myClickHandler(View target) {
        // Do stuff
    }

Comment: That's the correct answer. With the mention that this only compatible with Android 1.6+. It is not available in Android 1.5.
Answer: So just to make sure I get what your asking, when the user clicks on a button, say, 'Juice', they will be brought to a page that displays Juice?
First make a new class, in my example, a Juice.
protected void onCreate(Bundle savedValues) {
    // Capture our button from layout
    Button button = (Button)findViewById(R.id.mButton);
    button.setOnClickListener(mJuiceClick);

    }
private OnClickListener mJuiceClick = new OnClickListener() {
    public void onClick(View v) {
      //create a new intent that will launch the new 'page'
      Intent i = new Intent(Main.this, Juice.class);
      startActivity(i);
    }
};

In most cases, you will make an xml layout for main, and one for juice, unless they display info in the same way.
Go here for more info: http://developer.android.com/guide/topics/ui/ui-events.html


Error in imports of eclipse - developing android

Question: I think I'm having troubles with Eclipse's imports, but I haven't been able to pinpoint the problem. I'm trying to implement a FragmentPagerAdapter but I'm getting the "The constructor FragmentPageAdapter(FragmentManager) is undefined". There's the exact same question here in SO at "The constructor FragmentPagerAdapter(FragmentManager) is undefined" but the answer in that post didn't work for me.
Any suggestions? thanks in advance! :)
(the offending line is super(act.getFragmentManager());)
import java.util.ArrayList;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MainFragmentsPager_Adapter extends FragmentPagerAdapter{
    ArrayList<ViewGroup> views = new ArrayList<ViewGroup>();

//  public MainFragmentsPager_Adapter(FragmentManager fm) {
//      super(fm);
//  }

    public MainFragmentsPager_Adapter(FragmentActivity act, Context context) {
        super(act.getFragmentManager());
        LayoutInflater inflater = LayoutInflater.from(context);
        View x = inflater.inflate(R.id.fragment_noticias, null);
    }

    @Override
    public Fragment getItem(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return 0;
    }

}

Answer: Try using act.getSupportFragmentManager() instead.
This should fix your problem as you  are using support library.
Cheers.


OG subscribe link rewrite

Question: How can I remove or rewrite "group/node" and "og_user_node" from url when user click on OG subscribe link ?
siteURL/group/node/63/subscribe/og_user_node
Is there any module like pathauto where I can use to make this url a custom look?
Thanks.
Answer: Well you know that all these requests are made using hook_menu.
Yes, you should use hook_menu_alter Create new module and add hook_menu_alter
function my_module_menu_alter(&$items) {
    // Unset core path
    unset($items['The_actual_menu_request']);
    $items['your_new_menu_request'] = array(
        'title' => 'OG subscribe',
        ...
      );
}

Just pass the same page callback and arguments as the menu request for og subscribe
EDIT
Well try this snippet and see if it works, for OG subscribe menu request
Create a custom module. If you do not know how to create a custom module read This
then in your .module file add this code. It should work, I do not know if the 'file' argument needs an absolute path to the file, but if it does not work you just have to change it for the real path in og '../og/og_ui/og_ui.pages.inc'
function my_module_menu_alter(&$items){
  //unset core path
  unset($items['group/%/%/subscribe']);
  //as an example (taking the example url you provided) I will call the new menu request community/node/63/sign-in
  $items['community/%/%/sign-in'] = array(
    'type' => MENU_CALLBACK,
    'file' => 'og_ui.pages.inc',
    'page callback' => 'og_ui_subscribe',
    'page arguments' => array(1, 2),
    'access callback' => 'user_is_logged_in',
    'title' => 'Join group'
  );
}

Greetings hope it helps you, do not forget to mark the answer.
Comment: Dear Sir, I am new to drupal (even not a coder), so if you give me more details then it help me to solve this problem. please write more if you have time. Thanks.
Comment: which version are you using? of Drupal? and OG ?
Comment: It is OG 7.x-2.7 and Drupal 7.31
Comment: check the answer again, I added an edit. Hope it helps you
Comment: it's not working when I build a custom module for this. It shows error like:

public_html//og_ui.pages.inc' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/public_html/includes/menu.inc on line 515

But if I change in OG module directly then it's working fine. Now tell me (if you have time) how can I rename "node/" in url?

Thanks
Comment: did you see What I said? if the url to og_ui.pages.inc does not work so change it to 'file' => '../og/og_ui_og_ui.pages.inc'

OG subscribe link rewrite


Bootstrap size and probability of drawing distinct observations

Question: Suppose we draw a sample of $k$ out of $n$ numbered balls without replacement and get a sample of $N_1$ (unique) balls. We then replace all the balls in the urn and repeat the drawing a second time to get again $N_2$ (unique) balls.
We are interested in the set of balls that end up being drawn exactly once (over the course of the two experiments).
It's clear that the probability, for one of the balls, of the event "being drawn exactly once" is
$$2k/n(1-k/n)$$
which is maximized at $k^*=n/2$.
Now consider the same experiment but with replacement and we look again for the value of $k$ (denoted now $\bar{k}^*$) that maximizes the frequency of the event "being drawn exactly once". Now, the expected number of distinct balls in each draw is $1-e^{-1}\approx0.632n$ and so I would have expected $\bar{k}^*=k^*/(1-e^{-1})\approx0.79n$. Running some simulations I get that the actual location of $\bar{k}^*$ seems to be much lower, probably between $0.65n$ and $0.7n$. I have a hard time understanding where is my mistake.
More generally (second question) I'm wondering what is the distribution function of the proportion of balls that are drawn exactly once in the second experiment (the one with replacements) as a function of $k$? Through numerical experimentations, I get the following curve ($n=100$):

EDIT
here is the R code to reproduce the example above:
fx02<-function(ll,n,k){
    a1<-matrix(0,n,2)
    a1[sample(1:n,k,replace=TRUE),1]<-1
    a1[sample(1:n,k,replace=TRUE),2]<-1
    sum(rowSums(a1)==1)/n
}

ss<-(1:60)*5   #The grid of values of k for which we'll compute the probability.
a4<-matrix(NA,length(ss),2)
for(i in 1:length(ss)){
    a2<-ss[i]
    a3<-c(lapply(1:1000,fx02,n=100,k=a2),recursive=TRUE);
    a4[i,]<-c(a2,mean(a3))
}
plot(a4,xlab="k",ylab="frequency of distinct draw")

Comment: In experiment #2, what is the chance a given ball is drawn exactly once? I am thinking it is $(2k)(1/n)(1-[1/n])^{2k-1}.$ Isn't this what you want to maximize?
Comment: Are you trying to maximize the chance of an individual ball being drawn exactly once or the number of balls being drawn exactly once?
Comment: @soakley: the function you propose is maximized @k=n/2 (with optimal value of $\approx.0.368$)...clearly we can do better than having $.37$ chance of being drawn exactly once --the max on the plot is around p(drawn exactly once)=.5.
Comment: Important point. The chance. How can I re-phrase my question to make this clear?
Comment: @soakley -- Yes, I agree. The probability of a ball being drawn once in the two samples in Experiment 2 is identical to the probability of its being drawn once in a single sample of twice the size. Less sure of this, but I believe the maximizing value of $k$ will again be $n/2$.
Comment: I think we have to consider all the balls. It might be revealing to work out a smaller example.
Answer: EDIT after seeing your code for the simulation
I think you did not consider the fact that a certain number can also occurr more than once within one sample. After accounting for that, we get the same results. Here is your modified code:
fx02<-function(ll,n,k){
  a1<-matrix(0,n,2)
  samp1 <- sample(1:n, k, replace=TRUE)
  samp2 <- sample(1:n, k, replace=TRUE)

  a1[sort(unique(samp1)), 1] <- as.numeric(table(samp1))
  a1[sort(unique(samp2)), 2] <- as.numeric(table(samp2))

  sum(rowSums(a1)==1)/n
}

ss<-(1:60)*5   #The grid of values of k for which we'll compute the probability.
a4<-matrix(NA,length(ss),2)
for(i in 1:length(ss)){
  a2<-ss[i]
  a3<-c(lapply(1:1000,fx02,n=100,k=a2),recursive=TRUE);
  a4[i,]<-c(a2,mean(a3))
}
plot(a4,xlab="k",ylab="frequency of distinct draw", pch=16, las=1)
abline(h=0.3697296, v=50)

max(a4[,2])
[1] 0.36971

Original answer
For the experiment 2 (with replacement), I think the probability that a certain number is drawn exactly once is:
$$
P_{\text{once}}=2k(n-1)^{(2k-1)}(1/n)^{2k}
$$
or
$$
P_{\text{once}}=2k(n-1)^{(2k-1)}n^{-2k}
$$
This can be checked by a simple example where $n=3$ and $k=2$. The probability to draw a certain number exactly once is in this case $2(4/9)^{2}\approx0.395$.
The maximum occurs of the formula above occurs for:
$$
k_{\text{max}}=\lfloor-\frac{1}{[2(\log(n + 1) + \log(1/n))]}\rceil
$$
or
$$
k_{\text{max}}=\lfloor-\frac{1}{[2(\log(n + 1) - \log(n))]}\rceil
$$
Where $k_{\text{max}}$ is rounded to the nearest integer. This is roughly $n/2$ for larger $n$, as already mentioned in the comments by @user603. For $n=100$, $k_{\text{max}}\approx 49.75$ so 50. The maximum probability for $n=100$ and $k_{\text{max}}=50$ would then be around $0.3697$ (as already worked out in the comments by @user603).
I set up a simulation to check this result in R:
prob.once <- vector()

draw.once <- function(n, k, sim=10000, repl=TRUE){

  for ( i in 1:sim ) {

    samp1 <- sample(1:n, size=k, replace=repl)
    samp2 <- sample(1:n, size=k, replace=repl)

    if ((is.element(1, samp1) & !is.element(1, samp2) & !is.element(1, samp1[duplicated(samp1)])) |
          (!is.element(1, samp1) & is.element(1, samp2) & !is.element(1, samp2[duplicated(samp2)])) ){
      prob.once[i] <- 1

    } else {
      prob.once[i] <- 0
    }
  }
  mean(prob.once)
}

krepl <- 1:300
probs.repl <- sapply(krepl, FUN=draw.once, n=100, sim=20000, repl=TRUE)

plot(probs.repl~krepl, pch=16, type="p", lwd=2, las=1, ylab="Probability", xlab="k", col="steelblue")

abline(h=0.3697296)
abline(v=50)

The simulated result seems to confirm the above considerations.
Comment: @JoshO'Brien I took the first derivative of the $P_{\text{once}}$ and set it to zero and solved it. I used my calculator to do this though. The first derivative is: $2(n-1)^{2k-1}(1/n)^{2k}(1+2k(\log(n+1)+\log(1/n)))$. Sorry that I can't give you more details.
Comment: @JoshO'Brien You could use [WolframAlpha](http://www.wolframalpha.com/) to do such calculations online. It's free. Look at [that](http://www.wolframalpha.com/input/?i=first+derivative+of+2k%28n%E2%88%921%29%5E%7B%282k%E2%88%921%29%7D%281%2Fn%29%5E%7B2k%7D+for+k).
Comment: @COOLSerdash Terrific! I had been able to work out the first derivative using the chain rule, but was then completely stuck. I guess WolframAlpha is the calculator I was wishing for!
Comment: I can't run your code as I get an error message: "Error in prob.once[i] <- 0 : object 'prob.once' not found".
Comment: @user603: Sorry, I forgot to add the initializer for that vector. Please try again. Tell me if it doesn't work again.
Comment: @user603, Thanks. I'm impressed with your algorithm, very effective and clever.
Comment: @COOLSerdash -- Just out of curiosity, how did you arrive at the analytical expression for $k_{\textrm{max}}$?
Comment: @COOLSerdash -- Thanks. That makes sense, and is enough detail for me. Sounds like I need to get a better calculator ;).
Comment: @JoshO'Brien Do you know wxMaxima? It's a free computer algebra system (CAS) that can do *a lot.* It's similar to Mathematica and Maple. You can download it [here](http://andrejv.github.io/wxmaxima/). There are a lot of tutorials online (e.g. [this one](http://www-com.physik.hu-berlin.de/~bunk/kurs/maxima/maxima.html)). Just Google "wxMaxima" + "Tutorial" or "Introduction". That should get you started.
Comment: @COOLSerdash Good to know of a well-supported open source CAS. I'll look into that if I find myself needing to use WolframAlpha more than a couple of times a day.


Find the value of an integral using Monte-Carlo method

Question: I have a task in a subject called "Monte-Carlo methods" with which I'm a bit stuck and therefore I'm asking for your help.

The task is as follows: Describe in detail one specific option how to find approximately a value of the integral using Monte-Carlo methods and using ONLY independent random variables
from uniform distribution with parametres (0,1):

$$\int_{2}^{4}\left(\int_{1}^{\infty} e^{x+y-xy} dx\right)  dy$$
What I've thought so far is that Importance Sampling Method might be a good idea to solve it. So I would choose a suitable density functions for X ja Y. For X it would be a uniform distrbution with parametres (2,4) since it's values are bounded and for Y I would choose exponential distrbution with rate 1 (Exp(1)).
But the main problem relies in the second part of the question - how to use ONLY values from uniform distribution (0,1). I know that I have to use the inverse of a density function, but I'm not able to write it down as requested.
I hope you understand my question and can help me with this one!
Comment: I suspect the (easily demonstrated) fact that the log of a uniformly distributed random variable has an exponential distribution might be very useful for this problem.
Answer: Hint #1:
\begin{align*}\int_{2}^{4}\int_{1}^{\infty} e^{x+y-xy} \text{d}x  \text{d}y&=\int_{2}^{4}\int_{0}^{1} e^{y+z^{-1}-z^{-1}y} \,  z^{-2}\text{d}z\text{d}y\\&=\int_{0}^{1}\int_{0}^{1} e^{2(w+1)+z^{-1}-2z^{-1}(w+1)} \,  z^{-2}\text{d}z2\text{d}w\end{align*}
Hint #2:
\begin{align*}\int_{2}^{4}\int_{1}^{\infty} e^{x+y-xy} \text{d}x  \text{d}y&=\int_{2}^{4}y^{-1}e^{y}\,\left\{\int_{0}^{\infty} e^{x}\,ye^{-xy}\text{d}x\right\}  \text{d}y\\
&=\int_{0}^{1} (2[w+1])^{-1}\exp\{2[w+1]\}\underbrace{\mathbb{E}^X[\exp(X)|Y=y]}_{X\sim\cal{E}xp(y)}2\text{d}w\\
&=\int_{0}^{1} (2[w+1])^{-1}\exp\{2[w+1]\}\underbrace{\mathbb{E}^U[\exp(-\log(U)/2[w+1])]}_{X=-\log(U)/2[w+1],\ U\sim\cal{U}(0,1)}2\text{d}w\\
&=\int_{0}^{1} (2[w+1])^{-1}\exp\{2[w+1]\}\,\mathbb{E}^U[U^{-1/2[w+1]}]\,2\text{d}w\end{align*}


Active directory to ldap synchronization

Question: I have two LDAP servers. First is Active Directory and second is openLDAP. I need setup between these servers.
Is here anybody, who know, how to do it?
I tried to use this link for tutorial, but I found problem. When I started migration with the command, i got response this:
<code>Error: java.util.MissingResourceException: Can't find bundle for base name javax.xml.bind.Messages, locale en_US
</code>
java.util.MissingResourceException: Can't find bundle for base name javax.xml.bind.Messages, locale en_US
at java.base/java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:2055)
at java.base/java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1689)
Answer: lsc works only with jdk8, By installing openjdk-8-jdk should fix the issue.


What is the (Practical) theory behind applying chords for a Song?

Question: I love playing Guitar. I can play the lead for any song by listening to it. But often in our prayer meeting people sing different songs in different keys. I can track the major they sing, but I am poor in applying chords as they sing.
So what is the Practical theory behind applying chords? I know about the theory behind chords based on the lead. ie  eg ( a C Major Song when it hits the notes C or E or G apply C chord). But how will I know that by listening? Is there any theory like start a song in C Major, if the next pitch goes up go to F or if it goes low G7 or lower than that go to F..   something like that?
I am eager to learn this.
PS. I can clearly find myself if I played a wrong chord and I can immediately switch to the right one.
Comment: Just a point of vocabulary: When you say "major", you probably mean "key".  As in, "people sing different songs in different keys."  Sometimes those keys are major, as in C-Major; sometimes those keys can be minor, as in A-Minor.
Comment: You've got causation precisely backwards. Chords aren't determined by the melody. The melody is determined by the chords.
Comment: This may be a question of practice and experience.
Comment: "I can play the lead for any song by listening to it." That's quite a statement. I expect you're in constant demand from cover bands.
Answer: No, if there was then good music would be easy to create. Part of some composers methodology is to do the unexpected. But if there is unexpected things then there are expected things. But there are many possibilities.
In the common practice period(CPP)(think of Bach, Beethoven, Mozart, etc...) there were very common progressions and a "theory" for some things. There is also a psychological factor involved. If I play something in Cmajor then abruptly cadence on a C#/Db chord you will hear that as unexpected. You may or may not like it but almost surely you will think it stands way out. Beethoven actually does something like this in I think the 7th or 9th symphony(can't recall) but it actually sets up a modulation down the line so what you think is unexpected you actually later on feel as if it was meant to be. (this is because he sets it up and makes you feel like it should happen because he was a genius composer)
Haydn did something similar with dynamics,
Symphony No. 94 (Haydn)
The thing is, it doesn't matter too much. USE YOUR EARS! In C major, if it jumps to a Dbmaj chord even the best musician will miss it if they are not familiar with the song or possibly the style(there are some idioms that exist that they might use to know that a specific chord is coming up).
But, in C major, you only have a 50% chance of getting it wrong if you just randomly play chords. Am = C, Em = G, and Dm = F. So even if you play a C chord over an Am chord it will "work" because it turns that chord into an Am7. It might not work as well as an Am chord but it won't sound terrible.
So just by probability you got a good shot of getting it right if the song is not too complicated.
In any case you simply must learn the progressions either from the sheet music/tab or by ear. There are no tricks for this because there are no rules to compose. There are some common features such as in the CPP you try to resolve 7ths of a chord down. So G7 will resolve to Am or C because the 7th must resolve to E and the leading tone B must resolve to C.
So G7 sets up the tendencies to resolve to Am or C. All notes in a scale have tendencies to move because of the dissonances they create and because of we want them to resolve to consonances. You can use these tendencies to help you a little but for the most part your probably just as likely to get it wrong as right.
In any case in CPP music there is a common statistical pattern where chord's tend to move in 4ths. G moves to C, C to F, Dm to G, Am to D, etc... and Dm and F seem to be interchangeable.
Also, say you know the song but forget a chord and play a wrong one... if you've gotten most of the song right and you know how to fake it chances are most people won't know.
In any case learn the progressions of the songs and you'll be much better off. Eventually when you learn enough songs of that style you'll be able to predict better but if you try to rely on predicting and you get it wrong big time people will notice that much more(and it will happen cause you can't be right 100% of the time or probably even upwards of 95% using that method).
e.g., if you have a 95% chance of predicting the chord progression of a song you have never heard then that means every 1 out of 20 chords you'll screw up. If a song contains 200 chord changes that means you've screwed up 10 chords in the song which is 10 times people will potentially hear that you've screwed up.
But if you know the song well chances are you won't screw up any or if you do it will be minor.
If you can find the right chord when you play the wrong when, then that is good... that helps a lot when you forgot part of the progression. Just learn the songs!! There's no simple way around it!
Comment: The middle section in your answer has some helpful advice in it, and I would recommend franklins to look into that, combined with the answers from [Alex Basson](http://music.stackexchange.com/questions/2080/what-is-the-practical-theory-behind-applying-chords-for-a-song/2082#2082) (good theory on chord progression) and [todd](http://music.stackexchange.com/questions/2080/what-is-the-practical-theory-behind-applying-chords-for-a-song/2083#2083) (great overview of the chords).
Answer: The basic foundation behind Western harmony and chord progressions is called Diatonic Harmony.  I wrote a brief overview of Diatonic Harmony that you may want to check out.  Once you understand the numbers, it becomes much easier to play in different keys, because you will probably begin to recognize the same chord progressions happening over and over.
Just for example: say the chord progression for a certain song in the key of C is C-F-G-C.  Then this is a I-IV-V-I chord progression, because in C Major, C is I, F is IV and G is V.
So now, suppose a different song is in a different key, say A, but the chords sound as if they have the same relationship to each other.  Then the song probably also uses a I-IV-V-I progression.  In A, the I chord is A-Major, the IV chord is D-Major, and the V chord is E-Major, so the chords are A-D-E-A.  And now you know the chords to the song!
The best thing to do is to take songs you already know the chords to and analyze them to figure out their roman numeral patterns.  Two well-known examples:

"You Are My Sunshine" goes I-I-IV-I-IV-I-V-I.
A 12-bar blues song uses I-I-IV-I-IV-IV-I-I-V-IV-I-I/V or some variation on that pattern.

You will probably notice a lot of the same patterns occurring over and over, and you will learn to recognize those patterns just by hearing them.  So when a new song comes along, you will recognize the pattern it uses, and you will be able to figure out what specific chords to use based on your knowledge of Diatonic Harmony.
Answer: You might find a key chart that lists the chords that go along in each key. This is helpful for transposing. I printed that one out and stuck it on my whiteboard, altho, its a little small and on my to-do list is to blow it up and print it again. Then if you know a few of the chords, you can look on the chart to help identify the rest of (likely) chords.
More importantly,if you are playing on a worship team, this kinda thing should be taken care of in the practice sessions, so there won't be any surprises at the meetings. Personally, I wouldn't be playing on a worship team that wasn't committed to practicing at least 3 or 4 hours during the week and preferably every day or 2. But that is just me.


Which of the following processes are Markov chains?

Question: A dice is thrown an infinite number of times. Which of the following procsses are Markov chains or not? Justify your answer. For those processes that are Markov chains give the transition probabilities. For $n\in\mathbb{N}$ consider
(1) $U_n$ to be the maximal number shown up to time $n$.
(2) $V_n$ to be the number of times a 6 appears within the first $n$ throws.
(3) $X_n$ to be the time which has passed since the last appearance of a $1$.
(4) $Y_n$ to be the time which will pass until the next $4$ appears.

A complete edit of my ideas
In my opinion all are Markov processes.
(a) is a Markov provess with state space $E=\left\{1,2,3,4,5,6\right\}$, because the Markov property is fullfilled:
In order to predict $U_{n+1}$ I only need to know the maximal number shown up to time $n$, i.e. $U_n$, because then I know that $U_{n+1}$ is either one of the numbers that are $> U_{n}$ or it is equal to $U_n$. I do not have to know $U_1,...,U_{n-1}$.
The transition matrix is
$$
P=\begin{pmatrix}1/6 & 1/6 & 1/6 & 1/6 & 1/6 & 1/6\\0 & 1/3 & 1/6 & 1/6 & 1/6 & 1/6\\0 & 0 & 1/2 & 1/6 & 1/6 & 1/6\\ 0 & 0 & 0 & 2/3 & 1/6 & 1/6\\ 0 & 0 & 0 & 0 & 5/6 & 1/6\\ 0 & 0 & 0 & 0 & 0 & 1\end{pmatrix}
$$
(b) is a Markov chain with state space $E=\mathbb{N}\cup\left\{0\right\}$; the Markov property is fullfilled:
In order to predict $V_{n+1}$ I only have to know the number of times a 6 appears within the first $n$ throws, i.e. I have to know $V_n$, because then I know that $V_{n+1}$ is either $V_{n}+1$ or remains $V_n$.
Here the transition probabilities are
$$
p_{ij}=\begin{cases}1/6, & j=i+1\\5/6, & i=j\end{cases}.
$$
(c) is a Markov chain with state space $E=\mathbb{N}\cup\left\{0\right\}$. Again the Markov property is fullfilled:
If I want to predict $X_{n+1}$ (which I do understand as the time at throw number $n+1$ that has passed since the last 1 appeared), I only need to know the time that has passed at throw number $n$ since the last 1 appeared. Then I can predict that $V_{n+1}=0$ (if I throw a 1 at throw number $n+1$) or $V_{n+1}=V_n+1$.
So to my opinion the transition probabilities are given by
$$
p_{ij}=\begin{cases}1/6, & j=0\\5/6, & j=i+1\end{cases}.
$$
(d) Here I am not that sure. But I think here we have a Markov chain, too. Because I think here we do not need the past throws at all, because the time to the next throw of a $4$ does not depend at all from the past throws. So it makes no difference if we conditional on the whole past or only on $Y_n$ in order to predict $Y_{n+1}$. So the Markov property is fullfilled.
To my opinion the transition probabilities are
$$
p_{ij}=\begin{cases}1/6, & j=1\\5/6, & j=i+1\end{cases}.
$$
Would be really nice to hear from you, if I am right or not.
Greetings
Comment: Aren't your results and drawing past the horizontal line about the third process, and not the fourth?
Comment: If (a,b,c,d)=(1,2,3,4), the current answers are correct. The *justification* of answer d/4 is bogus, though, a full answer requires to make explicit the filtration for which Y is Markov. Let me suggest to think again about the transition matrix in case d/4.
Answer: You say "because the future depends on the past," but this is not the correct characterization of a Markov Chain: for a Markov chain if you condition on the past, it only depends on the last value. So for $(2)$, $V_n$ conditioned on $V_{n-1},\cdots,V_1$, clearly depends only on $V_{n-1}$. Afterall, the number of 6's that occur in n throws satisfies $V_n=V_{n-1}+T_n$, where $T_n=1$ if the n'th throw is a 6 and 0 otherwise. Since dice throws are independent, $T_n$ is independent of $V_{n-1},\cdots,V_1$, making $P(V_n|V_{n-1},\cdots,V_1)=P(V_n|V_{n-1})$.
The same goes for (3). Since your throws are independent, this is what's called a renewal process: every time you throw a 1, it resets and is indepedent of everything prior. If i tell you that 20 minutes have passed since the last 1, then you don't need to know what happened 19 minutes ago, because the next throw is independent of the entire past, so if you want the new time passed since the last throw, you need only the last time update. In math language, the time $\tau_n$ since the last 1 was thrown has the following property: $\tau_n-\tau_{n-1}$ is independent of all $\tau_{i}-\tau_{i-1}$ for $i=1,2,\cdots,n-1$.
Comment: Thank you, you are right. I did not use the Markov property correctly. Now I see that (2) is a Markov chain, too. And then (3) is a Markov chain, too. If I condition on the past I only need the last value. Right? But am I right, that (3) and (4) do have the same transition probabilites?
Comment: Ok, I edit my post. Pls have a look on it then.
Comment: I changed my opinion, I think (1) is a Markov chain, too. Because i only need the last maximal number shown up to time n, i.e. $U_n$, to predict $U_{n+1}$. Right?
Comment: Please have a look on my edited question/ ideas. They changed.


Javascript not working in IE, but all other browsers are working fine

Question: I've got some testimonials that cycle on my home page and the code seems to be working just fine in Firefox, Chrome, and Safari but not in IExplorer.  I'm running IE 9.  I'd appreciate any help or insights.
Here's the code I'm using:

Comment: What does "not working" mean? What's it doing?
Answer:

is NOT a valid JavaScript comment.  Use /*  */ instead.
Answer: Your comment markup is not valid for javascript.  Revise your script as follows, and it works properly in IE:
var quote=new Array();
  quote[0]="An essential tool in preparation for any show. Valuable time is saved, refining vocals much earlier in the process.";
  quote[1]="Invaluable for learning vocal lines! A brilliantly simple and easy to use interface that saved me hours of time.";
  quote[2]="MixMyPart saved us almost a week of rehersal time. A brilliant invention. Singers come in less nervous and more focused.";
// quote[3]="An invaluble tool for learning vocal lines! Brilliantly simple and easy to use interface that saved me hours of time.";

var quoteperson=new Array();
  quoteperson[0]="Bob Foster, Music Director";
  quoteperson[1]="Liam Tobin, Actor";
  quoteperson[2]="Shawn Wright, Actor";
// quoteperson[3]="Liam Tobin, website.org";


Dropdown aberto

Question: Gostaria de saber se existe alguma propriedade para que eu possa deixar um dropdown aberto no carregamento da pagina, só fechando se o usuario clicar na aba.
Obs: estou usando bootstrap.

    &nbsp &nbspApólices

            Cadastrar Apólice

            Visualizar Apólice

            Editar Apólice

            Excluir Apólice

            Exportar como PDF

Answer: Adicione essa classe (.stay-open)

Depois aplique no css !important
.stay-open {display:block !important;}

Dropdown aberto


Sampling from the normal-gamma distribution in R

Question: Does anyone know of a way to sample from the normal-gamma bivariate distribution or the normal-inverse-gamma bivariate distribution in R?
I could create the distribution myself as a function, but then I would not know what to do to sample from it.
Comment: The wikipedia page [gives an algorithm](http://en.wikipedia.org/wiki/Normal-gamma_distribution#Generating_normal-gamma_random_variates)
Answer: Sampling from normal-gamma distribution is easy, and in fact the algorithm is described on Wikipedia:

Generation of random variates is straightforward:

Sample $\tau$ from a gamma distribution with parameters $\alpha$ and $\beta$
Sample $x$ from a normal distribution with mean $\mu$ and variance $1/(\lambda \tau)$

What leads to the following function:
rnormgamma <- function(n, mu, lambda, alpha, beta) {
  if (length(n) > 1)
    n <- length(n)
  tau <- rgamma(n, alpha, beta)
  x <- rnorm(n, mu, sqrt(1/(lambda*tau)))
  data.frame(tau = tau, x = x)
}

Comment: Sorry, for `x<-rnorm(n, mu, sqrt(1/(lambda*tau)))`, why is it `sqrt()`? Here $x\sim N(\mu, 1/(\lambda T))$, right?
Comment: Because `rnorm` is parametrized by standard deviation, not variance.
Answer: Use the rigamma() function from the pscl package on CRAN. You can also take a look at the ghyp package.
Comment: Sorry, I meant I'm looking for a way to contain vector samples from a bi-variate normal-gamma/normal-inverse-gamma distribution in R. I looked at those packages and they are focused mainly on the regular inverse gamma or the normal inverse gaussian.
Answer: Ok this is very late, but did you can approximate samples from the normal inverse gamma bivariate distribution using a Gibbs Sampler where the two alternating sampling distributions would be the normal distribution and the inverse gamma distribution. Did you look into that?
Comment: the gibbs sampler does the following to approximate f(x,y): step1. intitalize x, x=x1 (arbitrary) , step2. simulate y1=f(y|x=x1), step3. simulate x2=f(x|y=y2), step4. simulate y2=f(y|x=x2),etc...., this is a markov chain, which after a "burn-in" period will become stationary and be an approximation of f(x,y).
Comment: The bivariate normal-inverse-gamma, has special relevance in bayesian statistics as it  is the posterior distribution for f(mu,sigma | sample), the parameters of the normal distribution,  assuming you choose conjugate priors for sigma  (the inverse gamma ) and mu (the normal distribution) for mu. This means that you can approximate  f(mu,sigma| sample), by simulating from f(mu | sigma, sample)~Inverse-Gamma and f(sigma | mu, sample)~Normal.
Comment: I wrote an example of how you can do it: http://rpubs.com/emdiazsal/6194
Comment: its not actually a gibbs sampler. I realize the gibbs sampler would be overkill in this situation. Let me know if it helps!


Dynamically adding controls to the page with ASP.NET Ajax library

Question: Is it possible, with the ASP.NET Ajax library (Sys....) to add controls to the page. For example in JQuery I would perform
<code>$("#mydiv").append($("#anotherdiv input"));
</code>
Or something similar. I want to do this without wrapping everything in an UpdatePanel if possible, preferably through clientside scripting. But I have a feeling this will confuse the ViewState.
N.B. This isn't a dupe of this post, which is about something different.
I'm closing this as it is possible, however it's fiddly. Chapter 10 of ASP.NET AJAX in Action covers it a little. Without partial postback though it's impossible
Answer: Your correct--it would confuse the viewstate as all the controls need to be on the page during or before the OnInit() method, as far as I can remember.
Yet, you may still be able to use some jQuery/Ajax to pull back the rendered control.  Say, for instance, you had a "helper" page, "MyControlsOutput.aspx", and on that page, you had your control embedded into it, ie "".  Then, you could, in theory, use jQuery to query the MyControlsOutput.aspx page, and return the responsetext to your page.  Again, it would not be in your ASP.Net page's control collection, nor would it have any clue about your viewstate. So, this is probably not what you're looking for, but, it was just a thought.
...While writing the above, I did a quick Google search for "asp.net ajax load control". See if this may help (you may have already seen this, sorry if that's the case):
http://weblogs.asp.net/sanjeevagarwal/archive/2008/07/22/Dynamically-create-ASP.NET-user-control-using-ASP.NET-Ajax-and-Web-Service.aspx
It's a similar concept, but it looks like they are using ASP.Net's ajax calls, and loading it into the page's control collection, and letting it use the page's viewstate as well.  Couldn't hurt, eh? :)
Hope that helps a little bit. Good luck.


Display time signature as single number above the staff

Question: Sometimes, when a piece of music has a frequently-changing time signature, the time signature is printed above the staff. In the following example, only the numerator is printed (the denominator is 4 throughout):

I know that this could be achieved in LilyPond by hiding the usual time signatures and manually displaying the numbers. Is it possible to do this by modifying the time signature engraver instead?
Answer: You can use a variation of this snippet and use a dynamics context to display the time signatures, like in the following example:
<code>\version "2.18.2"

\score {
  <<
  \new Dynamics {
    \time 2/4 s2
    \time 3/4 s2.
    \time 4/4 s1
  }
  \new Staff \relative c' {
    \key es \major
    \clef treble
    << { g'8[-3^\markup { \italic "sempre legato" } a b] s } \\
       { es,[-3\pp f g <b, d>] } >>
    << { es[-2 f-1 g a <g-1 b-4> <as-2 c-5>] } \\
       { c,[-4 d es f] s s } >>
    << { s es[-2 f g-1 a b c d]-5 } \\
       { <b,-5 d>[ c d es f g-3 a b] } >>
  }
  >>

  \layout {
    \context {
      \Score
      \override SpacingSpanner.base-shortest-duration = #(ly:make-moment 1/32)
    }
    \context {
      \Dynamics
      \consists "Time_signature_engraver"
      \override TimeSignature.style = #'single-digit
      \override TimeSignature.break-align-symbol = ##f
      \override TimeSignature.X-offset = #ly:self-alignment-interface::x-aligned-on-self
      \override TimeSignature.self-alignment-X = #CENTER
      \override TimeSignature.after-line-breaking = #shift-right-at-line-begin
    }
    \context {
       \Staff
       \remove "Time_signature_engraver"
    }
  }
}
</code>
The above should render as:

If you only want to change one single Dynamics context, you can also use
[...]
<code>  \new Dynamics \with {
    \consists "Time_signature_engraver"
    \override TimeSignature.style = #'single-digit
    \override TimeSignature.break-align-symbol = ##f
    \override TimeSignature.X-offset = #ly:self-alignment-interface::x-aligned-on-self
    \override TimeSignature.self-alignment-X = #CENTER
    \override TimeSignature.after-line-breaking = #shift-right-at-line-begin
  } {
    \time 2/4 s2
    \time 3/4 s2.
    \time 4/4 s1
  }
</code>
[...]
And delete the stuff from <code>\layout</code>.
Comment: This is great, but settings in \layout { \context { \Dynamics } } affect every Dynamics context in this score-block. What should be done to get this effect if there is another unrelated Dynamics context, e.g. one containing dynamics or one containing piano-pedalling?
Comment: You are right. You can directly put the directions into the relevant Dynamics context with `\with`. See my edit.


Node.js double console.log output

Question: I'm learning Node.js and I'd like to understand the "why" when code spits out duplicated console.log outputs but only a single response.write outputs.
Heres my simple code example:
var http = require('http');

http.createServer(function(request, response){
    response.writeHead(200, {'Content-type': 'text/plain'});
    console.log('hello 1');
    response.write('Hello world');
    console.log('hello 2');
    response.end();
}).listen(8000);

And on my console/terminal I get:

hello 1
hello 2
hello 1
hello 2

Thanks.
Answer: Some browsers also send a request to locate the favicon.ico file. Since the file isn't present by default, a browser(Chrome in particular) will always send two requests: one for the originally requested file and another for favicon.ico. This is a known bug in Chrome and has been fixed in version 29. Firefox, however, requests for favicon.ico only for the first request. If you console.log the request URI path, you must see a request to localhost:8000/favicon.ico.
var http = require('http');

http.createServer(function(request, response){
    response.writeHead(200, {'Content-type': 'text/plain'});
    if(request.url === '/favicon.ico') {
        console.log('Favicon was requested');
    }
    console.log('hello 1');
    response.write('Hello world');
    console.log('hello 2');
    response.end();
}).listen(8000);

Comment: @JDillon522 there are chrome extensions to disable it.
Comment: Weird. Is there a way to override that? Or is it a matter of "suck it up buttercup"?
Comment: You can `response.end()` to prevent your request handler from being executed on requests to favicon.`if(request.url === '/favicon.ico') { response.end(); }` Not sure if any other way exists.
Answer: I've had the same problem myself, and I found out that using something like
var http = require('http');
http.createServer(function(req,res) {
    if(req.url === '/favicon.ico')
    {
        //everything here is ignored
    }
    res.writeHead(200,{"Content-Type": "text/plain"});
res.write("Hello World\n");
res.end();
console.log("Connection made");
}).listen(1337, "127.0.0.1");
console.log("Server running at http://127.0.0.1:1337/");

is enough to avoid that behaviour. For some reason, when I check req.url and compare it to '/favicon.ico' nothing is sent to console, in fact, everything in that block is ignored. I don't know if this behaviour is expected, but you sure could try it.
Comment: Surely all this does is _additionally_ execute the block containing 'everything here is ignored' on a favicon request (and also do everything else)? It won't fix the OP's problem unless you use an _else_ block to contain the remaining logic...
Comment: Well, it's been 6 years, so I'm not sure why I wrote what I wrote or what I was working on then, but yes, I think your comment makes sense. Being a request made for favicon or not shouldn't have an influence on the described behavior, I guess. c.P.u1's answer seems like the best bet on a "fix" here
Answer: If you output the header you're telling the server that you found favicon, hence the response is processed and no matter what you get that double console.log(). Instead, end it before sending a writeHead() or send a 404.
var http = require('http');

http.createServer(function (req, res) {
    if(req.url === '/favicon.ico') {
        res.writeHead(404);
        res.end();
    } else {
        res.writeHead(200, {'Content-Type': 'text/plain'});
    }
    //code here...

    res.end();
}

Comment: I have tried your answer and it seems to be correct in my version of node (v6.12.0) except that I had to pass a `' '` argument to the end method. This prevents the double console.log output.
Comment: Thank you so much! :). I removed "res.end();" in "if", add var url = require('url'); and modified "req.url" == var path = url.parse(request.url).pathname;. It's worked with me.
Answer: i think that this problem still persists in chrome Version 67.0.3396.87 (32-bit) because when i ran my nodeJS script i saw 2 console.log() statements one was able to print out the query the other was not, so i corrected my code so as to see console.log() statements only once, it was simple all i had to do was add a return statement if the request.url was == (equal to)"/favicon.ico" in the beginning of the code and everything worked fine
previous code
var http = require('http');
var url = require('url');
http.createServer((request,response)=>{
var q = url.parse(request.url,true).query;
console.log(request.url);
console.log('hey there! we got a request from '+q.name+' !');
}).listen(8080);

and the output was :
/?name=harshit
hey there we got a request from harshit !
/favicon.ico
hey there we got a request from undefined !

code after debugging :
var http = require('http');
var url = require('url');
http.createServer((request,response)=>{
if(request.url == "/favicon.ico"){
return ;
}
var q = url.parse(request.url,true).query;
console.log(request.url);
console.log('hey there! we got a request from '+q.name+' !');
}).listen(8080);

output :
/?name=harshit
hey there we got a request from : harshit !

Comment: great answer bro !
Answer: in a nutshell the duplication as it is mentioned before is a result of the favicon request so to avoid this problem, I propose you this simple snipet:
var pathname = url.parse(request.url).pathname;
if(pathname != '/favicon.ico')
console.log('hello 1');

Answer: It can also be a Chrome plugin like JSONView. I was just trying to figure it out until I tried incognito and realized it was no longer causing the problem. Also was requesting a JSON file.

Node.js double console.log output


Erro ao implementar botão de login do Facebook

Question: Estou tentando implementar um botão personalizado do Facebook para login.
Mas acontece o seguinte erro:

C:\mala_App\mala_App\mala_App\app\src\main\res\layout\activity_new_login.xml
  Error:(117) No resource identifier found for attribute 'login_text' in
  package 'mala.mala_app'
  C:\mala_App\mala_App\mala_App\app\build\intermediates\res\merged\debug\layout\activity_new_login.xml
  Error:(117) No resource identifier found for attribute 'logout_text'
  in package 'mala.mala_app' Error:(117) No resource identifier found
  for attribute 'login_text' in package 'mala.mala_app' Error:(117) No
  resource identifier found for attribute 'logout_text' in package
  'mala.mala_app'

XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@color/fundo_1"
    xmlns:android="http://schemas.android.com/apk/res/android"
    tools:context="mala.mala_app.activity.NewLoginActivity">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_new_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/fundo_1"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    >

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/logobranca" />
    </FrameLayout>

    <ProgressBar
        android:id="@+id/progressBar2"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/frameLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="45dp"
        android:background="@color/accent" />

    <RelativeLayout
        android:id="@+id/relative_new_login_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/progressBar2">

        <LinearLayout
            android:id="@+id/linear_layout_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txt_titlle_login"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="2dp"
                android:fontFamily="sans-serif-condensed"
                android:text="@string/txt_email_title_login"
                android:textColor="@color/branco"
                android:textSize="18dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/txt_subtitlle_login"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:fontFamily="sans-serif-condensed"
                android:text="@string/txt_sub_login"
                android:textColor="@color/branco"
                android:textSize="16dp" />

            <TextView
                android:id="@+id/txt_login"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dp"
                android:fontFamily="sans-serif-condensed"
                android:text="@string/txt_new_email"
                android:textColor="@color/branco"
                android:textSize="10dp" />

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/StyledTilEditText">

                <AutoCompleteTextView
                    android:id="@+id/email"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:focusableInTouchMode="true"
                    android:fontFamily="sans-serif-condensed"
                    android:hint="@string/type_your_email"
                    android:inputType="textEmailAddress"
                    android:maxLines="1"
                    android:singleLine="true"
                    android:textColor="#D3D3D3"
                    android:textSize="12dp"
                    android:layout_marginBottom="30dp"/>

            </android.support.design.widget.TextInputLayout>

            <Button
                android:id="@+id/email_sign_in_button"
                android:layout_width="match_parent"
                android:layout_height="30dp"
                android:layout_marginRight="15dp"
                android:layout_marginLeft="15dp"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="15dp"
                android:text="@string/btn_next"
                android:textStyle="bold"
                android:textSize="11dp"
                android:fontFamily="sans-serif-condensed"
                android:background="#D3D3D3"/>
            <com.facebook.widget.LoginButton
                xmlns:fb="http://schemas.android.com/apk/res-auto"
                android:id="@+id/facebook_login_button"
                android:layout_width="match_parent"
                android:layout_height="30dp"
                android:layout_marginRight="15dp"
                android:layout_marginLeft="15dp"
                android:layout_gravity="center_horizontal"
                fb:login_text="Sign in with Facebook"
                fb:logout_text="Sign in with Facebook"
                />
        </LinearLayout>

    </RelativeLayout>
</RelativeLayout>
</ScrollView>

Answer: Na hora de declarar o seu botão do Facebook, tem alguns pequenos erros:
Esse é o seu:
<com.facebook.widget.LoginButton
     xmlns:fb="http://schemas.android.com/apk/res-auto"
     android:id="@+id/facebook_login_button"
     android:layout_width="match_parent"
     android:layout_height="30dp"
     android:layout_marginRight="15dp"
     android:layout_marginLeft="15dp"
     android:layout_gravity="center_horizontal"
     fb:login_text="Sign in with Facebook"
     fb:logout_text="Sign in with Facebook" />

Assim seria da forma correta:
<com.facebook.login.widget.LoginButton
     xmlns:fb="http://schemas.android.com/apk/res-auto"
     android:id="@+id/facebook_login_button"
     android:layout_width="match_parent"
     android:layout_height="30dp"
     android:layout_marginRight="15dp"
     android:layout_marginLeft="15dp"
     android:layout_gravity="center_horizontal"
     fb:com_facebook_login_text="Sign in with Facebook" />

Tente compilar novamente dessa forma.
Comment: Obrigado, tinha visto uma resposta com estes 2 texts e o coloquei e deu este problema, mas, deixando somente o login, deu certo sim!


Fit regression model from a fan-shaped relation, in R

Question: I get a fan-shaped scatter plot of the relation between two different quantitative variables:

I am trying to fit a linear model for this relation. I think I should apply some kind of transformation to the variables in order to unify the ascent variance in the relation before fitting a linear regression model, but I can't find the way to do it. Or maybe, there is a better model to use in these cases, I can't either find it.
I have tried rlm, but the residuals still have heteroscedasticity. I have also tried to apply a SD ratio calculated from all the y of each x and other similar erratic approaches.
My questions:

Is there any typical way of fitting a model for a fan-shaped relation or a typical model to use in these cases?
Is there any typical transformation that could be applied to the variables in order to reduce its variance?
Comment: This looks suspicious. I think there is an important covariate that isn't considered in your model or you even have repeated measures. Also, I see that your response variable is in the interval [0, 1]. Is it by chance a probability? You might need a generalized linear model. Anyway, function `gls` in package nlme allows specifying a heteroscedasticity structure.
Comment: Can you say anything more about the data? The functional relationship appears to be about equal on average, and the heteroscedasticity only biases the standard errors. Is there some sort of functional dependence for the two variables? Is there a potential omitted variable that interacts with the X axis variable?
Comment: Thanks! @AndyW It is the a relation between two ways of measure media audience. @Roland The variables are [0,1] because I've scaled them just to show it simpler, but both are quantitative variables. I am trying to fit a model for prediction purposes. I've tried weights with `lm`, but I don't know how to take advantage of them. I'll try `gls`, too, thanks @Roland.

The relation is weaker for higher values of the predictor, but I don't know how to figure out the heteroscedasticity structure in order to apply it to the `weights` or pre-transform the data. I am really lost with this.
Comment: Cf. also your post at http://stats.stackexchange.com/questions/156661/fix-fan-shaped-scatter-plot-in-r It's not the same data, but is it in essence the same question?
Comment: @Nick Yes, my mistake. I'll try to remove that one, sorry.
Answer: Here's two fan-shaped plots generated by different methods:

(Click here for a larger version.)
These in turn suggest two different approaches for modelling data that looks more or less like this:

Take logs, and fit a linear model with the coefficient restricted to 1 (also called an offset)
divide $y$ by $x$ and then fit a constant-only model.

There will be other ways to generate data like this, and other ways to fit data like this. For example, some other possibilities are:

fit a gamma glm with identity link (and perhaps without an intercept)
since the variance is proportional to $x^2$, use this fact to construct a weighted regression using weights proportional to $1/x^2$. [For a simple straight line through the origin, this should give the same result as 2.]

--
[AndyW's comment about a possible missing covariate is important. However, I'm just going to deal with the question of modelling fan-shaped relationships since it's an interesting topic on its own; in practice you would want to investigate his suggestion that there appears to be potential missing covariates as well.]
Comment: +1 - The reason I mentioned a missing covariate in a comment is because of the visible ray at the top of the point cloud that separates from the main cloud at around `x = 0.3` - which looks like a it might be a separate mixture to me. Reminds me a bit of the scatterplot in [this project of mine](https://andrewpwheeler.wordpress.com/2014/11/19/using-the-google-distance-api-in-spss-plus-some-eda-of-travel-time-versus-geographic-distance/).
Comment: WIth a fan-shape that converges to a point at the origin, the spread is increasing in proportion with $x$; if the shape of the distribution of $Y|X=x$ doesn't change with $x$, then the standard deviation (a specific measure of spread) will also be proportional to $x$.  Its square, the variance, must then be proportional to $x^2$.
Comment: @AndyW It's certainly a possibility, though it's also possible to get one or more rays without a missing covariate; for example like this: `x2 = sqrt(runif(5000)); y2 = x2*(6-sqrt(rpois(5000,3))); plot(x2,y2,cex=.5,pch=21)`
Comment: @Glen_b There's a lot of useful information in that few lines. I am trying to understand and test everything, and I'll be back with the result. Thanks so much!
Comment: @AndyW Yes, there is some kind of mixture here that I also need to analyze. The link to your project seems very useful, too, and I'll expend some more time on it later. Thanks!
Comment: This is probably a naive question, but I just can't see it from your plots: in point 4, how did you know that the variance is proportional to $x^2$?


Debugging ping pong game in Python

Question: I'm tired, and I've tried to run this all day. IT's a game of pong where the ball bounces off the wall and comes into contact with the user's "Slab" or paddle. I've treid to debug for a while, and turns out my iCollide and the iGet_Velocity parts have been causing a lot of issues.
from livewires import games, color
games.init (screen_width = 640, screen_height = 480, fps = 50)

class Ball (games.Sprite):
    def update (self):
        if self.right>544:
            self.dx = -self.dx
        if self.top > 11 or self.bottom > 470:
            self.dy = -self.dy
        if self.left < 0:
            self.iLost()

    def iLost (self):
        games.Message (screen = self.screen,
                       x = 340,
                       y = 240,
                       text = "Game Over",
                       size = 90,
                       color = color.red,
                       lifetime = 250,
                       after_death = self.screen.quit)

    def ihandle_collision (self):
        new_dx, new_dy = Slab.iVelocity()
        self.dx += self.dx + new_dx  #For handling collision, must take velocity of the mouse object and put add it to the velocity of the ball.
        self.dy += self.dy + new_dy

class Slab (games.Sprite):
    def update (self):
        self.x = games.mouse.x
        self.y = games.mouse.y
        self.iCollide()

    def iCollide (self):
        for Ball in self.overlapping_sprites:
            Ball.ihandle_collision()

    def iVelocity (self):
        self.get_velocity()

def main():
    #Backgrounds
    pingpongbackground = games.load_image ("pingpongbackground.jpg", transparent = False)
    games.screen.background = pingpongbackground
    #Ball: Initializing object and setting speed.
    ballimage = games.load_image ("pingpongball.jpg", transparent = True)
    theball = Ball (image = ballimage,
                    x = 320,
                    y = 240,
                    dx = 2,
                    dy = 2)
    games.screen.add(theball)
    #Paddle: Initializing ping pong object and setting initial poisition to the initial mouse position
    slabimage = games.load_image ("pingpongpaddle.jpg", transparent = True)
    theslab = Slab (image = slabimage,
                    x = games.mouse.x,
                    y = games.mouse.y)
    games.screen.add(theslab)
    games.mouse.is_visible = False
    games.screen.event_grab = True
    games.screen.mainloop()

main ()

Comment: can you provide some details on the specific issues you're seeing? otherwise it's less of a question and more of a code review
Comment: Sorry. Upon contact with the paddle, the game freezes.
Answer: These two lines look sketchy:
    self.dx += self.dx + new_dx
    self.dy += self.dy + new_dy

Try:
    self.dx += new_dx
    self.dy += new_dy

Comment: I fixed that earlier, forgot to save it when I did though. I'm more concerned with whether the objects are logically communicating with one another...
Comment: That still won't work though.  The ball would pass right though a stationary cursor.
Answer: Well, without having some more data, I can't say for certain what is wrong.  But it looks like your collision response code is a bit screwy.  For example, in the first section you should do this to handle your boundary conditions properly:
def update (self):
    if self.right>544 and self.dx > 0:
        self.dx = -self.dx
    if (self.top > 11 and self.dy < 0) or (self.bottom > 470 and self.dy > 0):
        self.dy = -self.dy
    if self.left < 0:
        self.iLost()

Also your collision response code is a bit wonky.  This is untested, but it does approximately the right thing:  (EDIT: Rewrote this with more comments so that it would be more clear)
def iCollide (self):
    for Ball in self.overlapping_sprites:

        #Extract the components of the slab's velocity
        slab_vx, slab_vy = self.iVelocity()

        #Compute relative components of slab velocity
        rel_vx, rel_vy = Ball.dx - slab_vx, Ball.dy - slab_vy

        #Determine the time of intersection and the normal direction
        #This is done to compute which face the ball hits
        #Initially suppose that the objects intersect at t=infinity
        t, nx, ny = 100000, 0, 0

        #Check left/right faces
        if rel_vx != 0:
            #Check if ball hits left face
            toi = (self.left - Ball.right) / rel_vx
            if toi < t:
                t, nx, ny = toi, -1, 0

            #Check if ball hits right face
            toi = (self.right - Ball.left) / rel_vx

            if toi < t:
                t, nx, ny = toi, 1, 0

        #Check top/bottom faces:
        if rel_vy != 0:

            #Check if ball hits top face
            toi = (self.top - Ball.bottom) / rel_vx
            if toi < t:
                t, nx, ny = toi, 0, -1

            #Check if ball hits right face
            toi = (self.bottom - Ball.top) / rel_vx
            if toi < t:
                t, nx, ny = toi, 0, 1

        #Check if impact force properly corrects velocity
        if Ball.dx * nx + Ball.dy * ny < 0:

            #Reflect the ball's position
            Ball.dx += Ball.dx * nx * 2.0
            Ball.dy += Ball.dy * ny * 2.0

        #Check if cursor movement is not pushing ball into paddle:
        if slab_vx * nx + slab_vy * ny < 0:
            Ball.dx += slab_vx
            Ball.dy += slab.vy

What you should try to do is find which face of the slab the ball intersects, then reflect the balls velocity according to that direction.  Now this code is by no means tested, since I couldn't get your example to run.  However it should give you an idea of what the correct solution ought to do.
Comment: Hey, would you mind explaining the compute time part? And shouldn't it be slab.iVelocity as we'd want the ball to have the speed that the slab hits it with?
Comment: Great, great answer. I find it fascinating that you were able to type that function as quickly as you did earlier. It doesn't execute to perfection yet, there are a few other bugs in other functions, but I understand the logic behind it now. Thanks a lot!

Debugging ping pong game in Python


Probability of tail event using Kolmogorov's 0-1 law

Question: If $X_1,X_2,... $ are independent random variables and $X=\sup_nX_n$ then $P(X<\infty)$ is either 0 or 1.
I think that if we prove the event to be a tail event then the result will follow. But I just don't know how to prove it to be a tail event.
Answer: Observe that for each $n$, $\{X<\infty\} = \{\sup_{k\ge n}X_k <\infty\}$.


Does this sharp under the chord mean to play a major chord?

Question: The source is p.95 in...
Plain-Song (Helmore, Thomas)
https://imslp.org/wiki/Plain-Song_(Helmore%2C_Thomas)
...and the particular sharp is this one highlighted in yellow...

It confusing, because all the other accidentals under the score match up with an accidental in the chord above, and IF the sharp means play a D major chord, that would raise the second degree in Phrygian, which seems to un-do the Phrygian-ness of the music. (It sounds nice to me either way D major or minor.)

EDIT
I didn't mention musica ficta specifically, but I think this should be added.
https://en.wikipedia.org/wiki/Musica_ficta#Modern_editions
In the Renaissance accidentals were not written in the notation, but in performance they were used and the practice was called musica ficta. Modern notation shows where those accidentals go above notes not on the staff.
This accidental below the note looks similar to the modern notation for musica ficta. The confusing things is how some of those accidentals are given both on the staff and below. This particular sharp is not on the staff, only below.
If I treat it like a kind of modern notation of musica ficta, I would apply the sharp.
Figured bass
http://robertkelleyphd.com/home/figured-bass/
It probably is more obvious to say the accidentals below the staff are in the same place as the figured bass symbols. A sharp alone in figured bass means to play a major third.
Comment: Oddly written anyway - repeated accidentals in the same bar. And why underneath when there's room in the traditional place.
Comment: The truly confusing thing is that the sharp coincides with an F natural in the melody.
Answer: I suspect it's a typo, and the # sign in basso continuo was supposed to be under the consecutive chord, the last one in the first system.
Accidental under the bass note means the chord contains a note third above the bass note and it has that accidental w.r.t. diatonic note.
The notation as it is contradicts itself. In the marked chord the top note is F, which is diatonic in E-phrygian, while raised third from the bass note D is F#. There shouldn't be # mark below the chord. In the consecutive chord the bass note is E, above which there is a non diatonic third G#. There is a missing # sign below the chord.
Comment: I rewrote the answer, I hope it is more clear now. It's been a while since I studied basso continuo, so perhaps you should review some textbooks about it. Yes, the sharp should be under the last chord. The sharp corresponds to an accidental in the chord, but not any accidental, but specifically note that is third above the bass note.
Comment: This must be the correct answer.  Every other accidental in the figured bass corresponds with an accidental in an upper part, except for these two chords.
Comment: Any chance someone has a different edition?   When available, that's a good way to check out oddities like this
Comment: I'm not sure I follow you. Are you saying the typo is the sharp should have been on the last chord rather that second to last chord?
Comment: @MichaelCurtis - Yes--as far as I can tell, that is what user1079505 means.


Open all text files in given folder

Question: I am trying to open all text files in a folder and subfolder I give to program as parameter and search text in them. Now if I use . instead of path, it open files like I want to. But as soon as I give any other folder in my computer as parameter (not the one the object file is), it will not open files. How can I fix it? I have Windows, and I am using MinGw as compiler.
#include <iostream>
#include <cstdlib>
#include "boost/program_options.hpp"
#include "boost/filesystem.hpp"
#include <iterator>
#include <fstream>
namespace po = boost::program_options;
using namespace std;
using namespace boost;
using namespace boost::filesystem;

int main (int argc, char* argv[]) {

    // Declare the supported options.
    po::options_description desc("Allowed options");
    desc.add_options()
    ("folder", po::value<std::string>(), "find files in this folder")
    ("text", po::value<std::string>(), "text that will be searched for");

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    filesystem::path current_dir (vm["folder"].as<string>());
    filesystem:: recursive_directory_iterator end_itr;//recursive lisatud

    for ( filesystem::recursive_directory_iterator itr( current_dir );
         itr != end_itr;
         ++itr )
    {
        //cout << itr->path ().filename () << endl;
        if(itr->path().filename().extension()==".txt"||itr->path().filename().extension()==".docx"||itr->path().filename().extension()==".doc"){
            ifstream inFile(itr->path().filename().string());
            //ifstream inFile("c:\\somefile.txt"); //this would open file

            cout<<itr->path().filename().string()<<endl; //this prints out all the file names without path, like  somefile2.txt for example
            while ( inFile )
            {
                std::string s;
                std::getline( inFile, s );
                if (inFile){
                    std::cout << s << "\n";
                    if(s.find(vm["text"].as<string>())!= string::npos){
                        cout<<"found it"<<endl;
                        }
                    }
            }
        }
    }

    return EXIT_SUCCESS;
}

Comment: "_it will not open files_" is not a very informative problem descruption, and "a folder" and "any other folder" are not very useful descriptions of your test data, either. Perhaps you could elaborate?
Comment: "it will not open files" - it will not go inside to loop while(inFile){} - a folder, and any other folder - a folder is a path I give to the program, it can be any path in my computer, and other folders are subfolders of that folder
Comment: You should check the value of `itr->path().filename()`. Because if the part to a file is `some/directory/foo.txt`, but `.filename()` is just returning `foo.txt`, you'll not be able to open it because the path is missing. Its an easy mistake to make with other filesystem libraries, certainly.
Comment: You are corrext .filename() is returning just foo.txt without path. And I believe it is the main problem I have, but how can I get the whole path?
Answer: Here's the problem:
ifstream inFile(itr->path().filename().string())

or more specifically, itr->path().filename() merely returns the name of the file, rather than the complete path to that file. If the file isn't in the program's current working directory, you'll have problems opening it: either no file by that name will be found, or a local file will be found with the same name, which won't be the file you actually wanted!
Whilst you're performing a recursive directory iteration, your current working directory won't change.
itr->path() returns instances of boost::filesystem::path when dereferenced... the docs for that class may be found here. I believe what you want to do is
ifstream inFile(itr->path().c_str());

This may not be the canonical or most efficient way, however.
Comment: native gets the whole path this far very good, but ifstream inFile(itr-> path().native()) gives me an error: no matching function for call to 'std::basic_ifstream :: basic_ifstream(const string_tyoe&). Adding .string() at the end of the row doesn't work either.
Comment: My bad. You may use `itr->path().c_str()` to get a plain old C-string version which should work for you. Answer updated.
Comment: I dont know if I am making some complete rookie mistakes, but it still doesn't work. The error is basicly the same no matching function, only the ending changed to (const value:type*)
Comment: Running out of ideas, I'm afraid. I don't have any machines handy with boost available on them. Maybe `itr->path().string()` or `itr->path().string().c_str()`? If that doesn't work, I can only suggest that you read through the docs yourself, as I can't really provide any more concrete help this weekend ;-) I note that both VS2013 and GCC 4.7 are both happy to construct an `ifstream` from a `std::string` path.

Open all text files in given folder


Não consigo fazer o backup do link

Question: Do site Openload e Streamanho funciona perfeitamente, mais desse site nao consigo fazer o backup link. Alguem me ajuda a resolver esse problema por favor?
<?php
require "config.php";

error_reporting(0);
ini_set('display_errors', 0);

if (isset($_GET["id"])) {
    $id = $_GET["id"];

    $query = $db->prepare("SELECT * FROM videos WHERE uuid = :id");
    $query->execute(array("id" => $id));
    $video = $query->fetch(PDO::FETCH_ASSOC);

    if ($video) {
        if (isVideoRemoved($video['link'])) {
            if (!isNullOrEmptyString($video["backup_link"])) {
                if (!isVideoRemoved($video["backup_link"])) {
                    $query = $db->prepare("UPDATE videos SET link = :link, backup_link = '',status = 1 WHERE uuid = :id");
                    $update = $query->execute(array("link" => $video["backup_link"], "id" => $id));
                    if ($update) {
                        addVideoBackup($id, $video["backup_link"], $verystreamLogin, $verystreamKey);
                        redirect($video["backup_link"]);
                    }
                } else {
                    $query = $db->prepare("UPDATE videos SET status = 0 WHERE uuid = :id");
                    $update = $query->execute(array("id" => $id));
                    die("KAYNAK SORUNLU, DİĞER KAYNAKLARI DENEYİNİZ");
                }
            } else {
                $query = $db->prepare("UPDATE videos SET status = 0 WHERE uuid = :id");
                $update = $query->execute(array("id" => $id));
                die("KAYNAK SORUNLU, DİĞER KAYNAKLARI DENEYİNİZ");
            }
        } else {
            if (isNullOrEmptyString($video["backup_link"])) {
                addVideoBackup($id, $video["link"], $verystreamLogin, $verystreamKey);
            }
            $query = $db->prepare("UPDATE videos SET status = 1 WHERE uuid = :id");
            $update = $query->execute(array("id" => $id));
            redirect($video['link']);
        }
    } else {
        die("KAYNAK SORUNLU, DİĞER KAYNAKLARI DENEYİNİZ");
    }
} else {
    die("KAYNAK SORUNLU, DİĞER KAYNAKLARI DENEYİNİZ");
}

function addVideoBackup($id, $url, $login, $key)
{
    global $db;
    $uploadId = addVideoRemoteDownloadReq($url, $login, $key);
    if ($uploadId) {
        $newLink = checkVideoRemoteDownloadReq($uploadId, $login, $key);
        if ($newLink && !isNullOrEmptyString($newLink)) {
            $newLink = str_replace("verystream.com", "verystream.com", $newLink);
            $newLink = str_replace("/e/", "/e/", $newLink);

            $query = $db->prepare("UPDATE videos SET backup_link = :link, status = 1 WHERE uuid = :id");
            $update = $query->execute(array("link" => $newLink, "id" => $id));
            if ($update)
                return $newLink;
        }
    }
    return false;
}

function checkVideoRemoteDownloadReq($videoId, $login, $key)
{
    $resp = request("https://api.verystream.com/remotedl/status?login=$login&key=$key&id=$videoId");
    $respArray = json_decode($resp, true);
    if ($respArray["status"] == 200) {
        if ($respArray["result"][$videoId]["status"] == "finished")
            return $respArray["result"][$videoId]["url"];
    }
    return false;
}

function addVideoRemoteDownloadReq($url, $login, $key)
{
    $resp = request("https://api.verystream.com/remotedl/add?login=$login&key=$key&url=$url");
    $respArray = json_decode($resp, true);
    if ($respArray["status"] == 200) {
        return $respArray["result"]["id"];
    }
    return false;
}

function isVideoRemoved($url)
{
    $html = request($url);
    if (strpos($html, 'File blocked! Much sorry!') !== false) {
        return true;
    } else {
        return false;
    }
}

function isNullOrEmptyString($question)
{
    return (!isset($question) || trim($question) === '');
}

function redirect($url, $statusCode = 303)
{
    header('Location: ' . $url, true, $statusCode);
    die();
}

Answer:

<?php
require "config.php";

error_reporting(0);
ini_set('display_errors', 0);

if (isset($_GET["id"])) {
    $id = $_GET["id"];

    $query = $db->prepare("SELECT * FROM videos WHERE uuid = :id");
    $query->execute(array("id" => $id));
    $video = $query->fetch(PDO::FETCH_ASSOC);

    if ($video) {
        if (isVideoRemoved($video['link'])) {
            if (!isNullOrEmptyString($video["backup_link"])) {
                if (!isVideoRemoved($video["backup_link"])) {
                    $query = $db->prepare("UPDATE videos SET link = :link, backup_link = '',status = 1 WHERE uuid = :id");
                    $update = $query->execute(array("link" => $video["backup_link"], "id" => $id));
                    if ($update) {
                        addVideoBackup($id, $video["backup_link"], $verystreamLogin, $verystreamKey);
                        redirect($video["backup_link"]);
                    }
                } else {
                    $query = $db->prepare("UPDATE videos SET status = 0 WHERE uuid = :id");
                    $update = $query->execute(array("id" => $id));
                    die("KAYNAK SORUNLU, DİĞER KAYNAKLARI DENEYİNİZ");
                }
            } else {
                $query = $db->prepare("UPDATE videos SET status = 0 WHERE uuid = :id");
                $update = $query->execute(array("id" => $id));
                die("KAYNAK SORUNLU, DİĞER KAYNAKLARI DENEYİNİZ");
            }
        } else {
            if (isNullOrEmptyString($video["backup_link"])) {
                addVideoBackup($id, $video["link"], $verystreamLogin, $verystreamKey);
            }
            $query = $db->prepare("UPDATE videos SET status = 1 WHERE uuid = :id");
            $update = $query->execute(array("id" => $id));
            redirect($video['link']);
        }
    } else {
        die("KAYNAK SORUNLU, DİĞER KAYNAKLARI DENEYİNİZ");
    }
} else {
    die("KAYNAK SORUNLU, DİĞER KAYNAKLARI DENEYİNİZ");
}

function addVideoBackup($id, $url, $login, $key)
{
    global $db;
    $uploadId = addVideoRemoteDownloadReq($url, $login, $key);
    if ($uploadId) {
        $newLink = checkVideoRemoteDownloadReq($uploadId, $login, $key);
        if ($newLink && !isNullOrEmptyString($newLink)) {
            $newLink = str_replace("verystream.com", "verystream.com", $newLink);
            $newLink = str_replace("/e/", "/e/", $newLink);

            $query = $db->prepare("UPDATE videos SET backup_link = :link, status = 1 WHERE uuid = :id");
            $update = $query->execute(array("link" => $newLink, "id" => $id));
            if ($update)
                return $newLink;
        }
    }
    return false;
}

function checkVideoRemoteDownloadReq($videoId, $login, $key)
{
    $resp = request("https://api.verystream.com/remotedl/status?login=$login&key=$key&id=$videoId");
    $respArray = json_decode($resp, true);
    if ($respArray["status"] == 200) {
        if ($respArray["result"][$videoId]["status"] == "finished")
            return $respArray["result"][$videoId]["url"];
    }
    return false;
}

function addVideoRemoteDownloadReq($url, $login, $key)
{
    $resp = request("https://api.verystream.com/remotedl/add?login=$login&key=$key&url=$url");
    $respArray = json_decode($resp, true);
    if ($respArray["status"] == 200) {
        return $respArray["result"]["id"];
    }
    return false;
}

function isVideoRemoved($url)
{
    $html = request($url);
    if (strpos($html, 'File blocked! Much sorry!') !== false) {
        return true;
    } else {
        return false;
    }
}

function isNullOrEmptyString($question)
{
    return (!isset($question) || trim($question) === '');
}

function redirect($url, $statusCode = 303)
{
    header('Location: ' . $url, true, $statusCode);
    die();
}

Não consigo fazer o backup do link


Array of objects always has same random number for each item

Question: Started to try c++ again with a simple card game. I made a class for each card with two constructors, one with no values creates the card randomly and one that takes in values.
#include <string>
#include <iostream>
#include <stdlib.h>     /* srand, rand */
#include <ctime>
#include <sstream>

class Card
{

private:

char suit;
int value;
public:

Card();
Card(char suit, int value);

void SetSuit(char suit);
void SetValue(int value);

...

std::string GetCard() ;

};

Card::Card(char suit, int value)
{
suit= toupper(suit);
this -> suit=suit;
this -> value=value;
}
Card::Card() //create random card
{

srand (time(0));
char suits [4] = {'D','S','H','C'};
int randNum = (rand() % 4);
SetSuit(suits[randNum]);
randNum = (rand() % 12)+2;
SetValue(randNum);

...

std::string Card::GetCard(){

...

return card.str();

}

If I create an array of card objects and then output it every card in the array has the same suit and value. I'm not sure how to get each card to be random the array.
Comment: **Wall of code, shrug!** Could you narrow that and get more specific about your actual problems please.
Comment: @user3803703: It's simple, don't call `srand()` in a loop. Only use it ONCE in your program to set the start of the sequence generated by `rand()`. If you repeatedly reset the random number state you will get the same stream of numbers.
Comment: You just get the same value generated. See [this answer.](http://stackoverflow.com/a/7343853/115272)
Comment: This class at first seems to work, if you use the class without an array, it creates random values, i think when he creates a regular array (`Card card[5]`) and loops through it, the constructor for the class Card is for some reason making every card have the same value in the array.
Comment: Ive seen that before. The way I understand it working is that everytime a new object is created srand is called again which should create new random numbers so I don't understand why if I create an array of 50 it is creating 50 of the same values and not generating a new random number each time?
Comment: @user3803703 This is actually a rather decent question, if you corrected it to a good, minimal code example those downvotes should reverse and you'll see the question reopened.
Answer: The problem is with:
srand (time(0));
int randNum = (rand() % 4);

Probably on your system, time(0) returns the number of seconds this epoch.  So when you call this code multiple times without a second elapsing, it gets the same value. Therefore you get the same random number every time.
You're supposed to do srand just once per program run.  And if you need any serious sort of randomness then you need more entropy than just time(0).  Even if you fix this, you could still execute your program several times and get the same card sequence every time, if all the runs begin within the same second.
The way that rand() typically works is to generate a long sequence of numbers which is predictable if you know the seed, but hard to predict just from a subset of the number. The srand function says "start the sequence at this point".  If you start at the same point each time , you get the same random numbers each time. Further reading
Comment: Ok. I think I get get that. srand is being called to quickly that it keeps giving the same seed. I took srand out of the class and added it to main then created the array and looped through it and it still creates every card as the same card. Maybe I'm misunderstanding how rand works?
Comment: maybe you added it inside a loop in `main` or something.. or you're doing something else wrong, hard to say without being able to see the code. Try to post a [MVCE](http://stackoverflow.com/help/mcve).
Comment: I'm pretty sure what Matt said is right, I just removed srand() from your class and put it at the start of main and these are the last three runs `D - 9D - 10S - 5D - 5D - 4` & `H - 6S - 8H- JackS - 6D - 8` & `S - 10S - 7C - 8H - 8C - 7`, assumming that's what is expected, i just looped the array and called GetCard()
Comment: Oh yeah it is working correctly with an array now. I was using vector at first, that's still not working but I guess that's a different issue.
Answer: Call srand(time(0)) only once when your application starts, e.g., at the main() function, not whenever any card is created.


Rails 4 - Controller test error, Active Record association issue

Question: I will post all files below the question. I am very new to testing. I'm trying to write a controller test for my app. The model is Ownerships. Ownerships is owned by Team. I'm using the paperclip gem to attach a logo to each team.
When I run the test, I get the follow error:
 1) Error:
 OwnershipsControllerTest#test_Should_retrieve_results:
 ActionView::Template::Error: undefined method `logo_file_name' for  nil:NilClass
 app/views/ownerships/round1.html.erb:23:in `block in _app_views_ownerships_round__html_erb___2932533286089946925_70246915278440'
app/views/ownerships/round1.html.erb:18:in `each'
app/views/ownerships/round1.html.erb:18:in `_app_views_ownerships_round__html_erb___2932533286089946925_70246915278440'
test/controllers/ownership_controller_test.rb:12:in `block in <class:OwnershipsControllerTest>'

It's complaining about how I'm dealing with a missing logo in the view. This is the portion of the round1.html.erb it doesn't like:
    <% if ownership.team.logo_file_name == nil %>

    <% else %>
        <%= image_tag ownership.team.logo.url(:medium) %>
    <% end %>

The problem is not the paperclip attachment itself. ANY reference to the Team model throws an error. If I remove the code related to the logo, the following also generates the same error:
<%= ownership.team.name %>
Whats really perplexing is the my test for the index method doesn't throw an error. The code for the index and round1 views are the same! How can I setup my test so that the attributes from the associated models are recognized?
ownership_controller_test.rb
 require 'test_helper'

 class OwnershipsControllerTest < ActionController::TestCase
 test "Should retrieve index" do
 get :index
 assert_response :success
 end

 test "Should retrieve results" do
 get :round1
 assert_response :success
 end
 end

ownerships.yml
 one:
 round: 1
 pick: 1
 team_id: 1
 player_id: 1

 two:
 round: 1
 pick: 1
 team_id: 1
 player_id: 1

teams.yml
 one:
 name: Browns
 division: East
 logo_file_name: logo.jpg

 two:
 name: Chargers
 division: West
 logo_file_name: logo.jpg

Models
 class Ownership < ActiveRecord::Base
 belongs_to :player
 belongs_to :team

 validates :round, :pick, :team_id, presence: true
 end

class Team < ActiveRecord::Base
has_many :ownerships
has_many :players, through: :ownerships

validates :name, presence: true
validates :division, presence: true

has_attached_file :logo , :styles => { :small => '10>', :medium => '40>', :large => '60>' }
validates_attachment_content_type :logo, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end

The relevant parts of ownerships_controller.rb
class OwnershipsController < ApplicationController

def index
@ownerships = Ownership.all.select { |t| t.player_id == nil}
Rails.application.config.counter = (256 - Ownership.all.select{ |t| t.player_id == nil}.count)
end

def round1
@ownerships = Ownership.all.select { |m| m.round == 1}
end

private
def ownership_params
params.require(:ownership).permit(:round,:pick,:team_id,:player_id)
end

Comment: This is because the `Ownership` has no `Team` that's what the error is saying. It says I don't know how to call `logo_file_name` on `nil` because `ownership.team #=> nil`
Answer: You need to add references to team in your ownership fixture.  You can reference by label.
one:
  round: 1
  pick: 1
  team: one
  player_id: 1

Or, your current approach would also work, just add the primary key to the team
Ownership
one:
  round: 1
  pick: 1
  team_id: 1
  player_id: 1

Team
one:
  id: 1
  name: Browns
  division: East
  logo_file_name: logo.jpg

See also: More info about relations in fixtures
Comment: Thanks Swards. I eventually figured it out. I had read the documentation, but their example was not the best.


Maximizing $x^4+y^4+z^4 + p(xy+xz+yz)$ on a sphere

Question: What values of $x,y,z$ maximize $f(x,y,z,p) = x^4+y^4+z^4 + p(xy+xz+yz)$ with constant $p \geq 0$ with the constraint $x^2+y^2+z^2=1$?
Some preliminary studies in Mathematica showed that the behavior of the solution changes around $p=1$. For $p>1$, the problem seems solved by $x=y=z=\frac{1}{\sqrt 3}$. For $0 \leq p \leq 1$ it appears the solution (up to permutations of x,y,z) looks like x > y = z. These solutions appear to favor one or the other of the two terms in $f$, and I find the $p>1$ behavior striking and would appreciate a proof that $x=y=z=\frac{1}{\sqrt 3}$ indeed maximizes.

UPDATE

For at least $p>4/3$, one can show that $x=y=z=\frac{1}{\sqrt 3}$ maximizes f.
The proof for $1<p<4/3$ evades me currently (the left bound, as mentioned in comments, may be slightly higher than 1).
I'll assume without loss of generality that $x,y,z$ are all positive. Note that $f(\frac{1}{\sqrt 3},\frac{1}{\sqrt 3},\frac{1}{\sqrt 3}, p) = p+\frac{1}{3} $, so if we show that for some $p$ we enjoy $f(x,y,z,p) \leq p+\frac{1}{3}$, we've shown $x=y=z=\frac{1}{\sqrt 3}$ maximizes $f$.
Now consider that via the constraint, $$f(x,y,z,p) = 1-2(x^2y^2+x^2z^2+y^2z^2) + p(xy+xz+yz)$$
  The root mean square compared to arithmetic mean inequality tells us that for nonnegative $a,b,c$ we enjoy $\sqrt{\frac{a^2+b^2+c^2}{3}} \geq \frac{a+b+c}{3},$ so $-(a^2+b^2+c^2) \leq -\frac{(a+b+c)^2}{3}$. Then $$f(x,y,z,p) \leq 1 + p(xy+xz+yz) -\frac{2}{3}(xy+xz+yz)^2.$$
  Now, let's call $(xy+xz+yz)=q$. Note that it is easy to prove with our constraints that $0\leq q \leq 1$.
  Then we can bound the maximum of $f(x,y,z,p)$ by finding the maximum of $g(q) = 1+pq-\frac{2}{3}q^2$ on $0\leq q \leq 1$.
  The derivative $g'(q) = p-\frac{4}{3}q$, so $g(q)$ increases up to $q=\frac{3}{4}p$. Then on $0\leq q \leq 1$, we have $q_{max} = min(\frac{3}{4}p, 1)$.
  Thus for $p \geq \frac{4}{3}$ we have $q_{max}=1$, so $$ f(x,y,z,p) \leq 1+p*1-\frac{2}{3}*1^2 = p + 1/3$$
  Thus since $f(\frac{1}{\sqrt 3},\frac{1}{\sqrt 3},\frac{1}{\sqrt 3}, p) = p+\frac{1}{3}$, we have for $p \geq \frac{4}{3}$ that $x=y=z=\frac{1}{\sqrt 3}$ maximizes $f$.

I have attempted the method of Lagrange multipliers, which led me to three cubic equations:

I set out to maximize
  $4(x^3+y^3+z^3)+p(xy+xz+yz)+\lambda(x^2+y^2+z^2-1)$.
This yielded
  $$4x^3+2x\lambda + p(y+z)=0$$
$$4y^3+2y\lambda + p(x+z)=0$$
$$4z^3+2z\lambda + p(y+x)=0$$
  But now I feel a little at a loss on how to solve this system of equations.
  One can verify that $x=y=z=\frac{1}{\sqrt{3}}$ solves these equations at any p with the right choice of lamda. I'm unsure about pairing Hessian techniques to verify the local nature of the critical point when using lagrange multipliers.

I have also tried incorporating the constraint by writing $z=\cos(\theta)$, $x=\sin(\theta)\cos(\phi)$ and $y=\sin(\theta)\sin(\phi)$.

This yields
  $$f(\theta, \phi, p) = \cos(\theta)^4+(\sin(\theta)\cos(\phi))^4+(\sin(\theta)\sin(\phi))^4+p(\cos(\theta)\sin(\theta)\sin(\phi)+\cos(\theta)\sin(\theta)\cos(\phi)+(\sin(\theta))^2\sin(\phi)\cos(\phi) ) $$
  which I am unsure how to maximize. However, with motivation from Michael Behrend, I've found that studying $\phi=\frac{\pi}{4}$ shows interesting critical point behavior slightly above p=1 where three critical points undergo some sort of bifurcation leaving just a single critical point at the eternal $x=y=z=\frac{1}{3}$  .
Answer: Lagrange function is
$$L=x^4+y^4+z^4+p(xy+xz+yz)+\lambda(x^2+y^2+z^2-1).$$
Solving system
$$L'_x=0,\;L'_y=0,\;L'_z=0,\;L'_x=0,\;L'_\lambda=0$$
 we get that if $p\ge1$ global maximum is
$$f_{max}=p+\frac13$$
 Maximum points is:
if $p>1$ then $[x=\frac{1}{\sqrt{3}},y=\frac{1}{\sqrt{3}},z=\frac{1}{\sqrt{3}}]$ or
$[x=-\frac{1}{\sqrt{3}},y=-\frac{1}{\sqrt{3}},z=-\frac{1}{\sqrt{3}}]$
if $p=1$ then $[x=\frac{\sqrt{6}}{3},y=\frac{1}{\sqrt{6}},z=\frac{1}{\sqrt{6}}],[x=-\frac{\sqrt{6}}{3},y=-\frac{1}{\sqrt{6}},z=-\frac{1}{\sqrt{6}}],[x=\frac{1}{\sqrt{6}},y=\frac{\sqrt{6}}{3},z=\frac{1}{\sqrt{6}}],[x=\frac{1}{\sqrt{6}},y=\frac{1}{\sqrt{6}},z=\frac{\sqrt{6}}{3}],[x=-\frac{1}{\sqrt{6}},y=-\frac{\sqrt{6}}{3},z=-\frac{1}{\sqrt{6}}],[x=-\frac{1}{\sqrt{6}},y=-\frac{1}{\sqrt{6}},z=-\frac{\sqrt{6}}{3}],[x=\frac{1}{\sqrt{3}},y=\frac{1}{\sqrt{3}},z=\frac{1}{\sqrt{3}}],[x=-\frac{1}{\sqrt{3}},y=-\frac{1}{\sqrt{3}},z=-\frac{1}{\sqrt{3}}]$
If $p=0$ then
$$f_{max}=1,$$
$[x=\pm1,y=0,z=0],[x=0,y=\pm1,z=0],[x=0,y=0,z=\pm1]$.
If $0<p<1$ we can't exact solve system.
Comment: After trying to prove that the crossover is at p = 1, I'm coming to the conclusion that this isn't true. The crossover seems to be somewhere between 1.01 and 1.02. Hope to post more later.
Comment: Sorry, my previous comments were wrong. There is a local maximum at the "pole" $(1/\sqrt3, 1/\sqrt3, 1/\sqrt3)$, and for $p < p_0 = 1.014829\ldots$ there are local maxima at three other points (all three with the same function value). For $p < 1$ these three maxima are greater than the maximum at the pole, for p = 1 all four maxima are equal, and for $p > 1$ the maximum at the pole becomes greater. So the crossover is $p = 1$ as originally stated. The change at $p = p_0$ is that the three other local maxima disappear.
Comment: I appreciate the answer. Could you explain how you solved the system of equations for p>1, and why you think that we cannot exactly solve the system for p between 0 and 1?
Comment: @MichaelBehrend I've been working a bit more with the trigonometric functions under the assumption that phi is pi/4. In that special case, I see interesting behavior with the critical points in theta. No matter the value of p, the equivalent to the x=y=z critical point remains, though whether it's a global maximum or even a local maximum changes with p. In particular, it seems just slightly above 1 that the three critical points become just 1 critical point. If you can find the value of p where that occurs, a 2nd derivative test should show that x=y=z maximizes above that. Thanks for the help!
Comment: The crossover point is the larger real root of
$$9x^4 + 10x^3 + 12x^2 - 24x - 8$$
which according to http://www.akiti.ca/PolyRootRe.html is 1.0148293664019847 (to 16 d.p.)
This was found by a rather lengthy method and checked empirically by a computer program. If I can find a better proof I'll post it as an answer.


Is there a continuous extention at $(0,0)$ $f(x,y)= \frac{x^{2021} *e^y}{1+x-e^y}$

Question: $$f(x,y)= \frac{x^{2021} *e^y}{1+x-e^y}$$
i said that domain is {$(x,y) \in R^2 : x+e^y \neq -1$}
I tried to show that yes then no but i did not succeed
Comment: @ShubhamJohri Firstly i tried to show that there is a continuous extension but I stucked , then i tried to show that there isn't
Comment: "I tried to show that yes then no but i did not succeed" What does this mean?
Answer: Hint: $|f(\frac 1  n , \ln (1+\frac1  n+\frac 1 {n^{2022}})| \to \infty$ as $ n \to \infty$.
Comment: thank you for your help