Expected rolls to roll every number on a dice an odd number of times

Question: Our family has recently learned how to play a simple game called 'Oh Dear'. Each player has six playing cards (Ace,2,3,4,5,6) turned face-up, and take turns to roll the dice. Whatever number the dice rolls, the corresponding card is turned over. The winner is the player to turn all their cards face down first, but if you roll the number of a card that has been turned face-down, then that card is turned face-up again (and you say 'Oh Dear!').
I want to work out the expected length of a game (in rolls of the dice). I'm interested first in working this out in the case of a single-player playing alone, and then also in the question of how the answer changes with multiple players. This is equivalent to working out the expected number of times a player must roll the dice to have rolled every number on the dice an odd number of times. (I assume a fair six-sided dice, but again would be interested in a more general solution too).
It is simple to work out the odds of winning as quickly as possible from any position, but I'm not sure how to go about calculating the expected number of rolls before a player would win...
Comment: This is a beautifully symmetric Markov chain on the discrete $6$-cube $\{0,1\}^6$ and as such it's straightforward to derive the entire distribution, not just the expectation, and to do so from any position.  With the distribution in hand you can then immediately derive the distribution for any number of players, because it's just the minimum of their rolls to reach the goal. For an unfair die the same calculations apply but the symmetry is broken.
Comment: Well go on then @whuber :)
Comment: I don't need to--Stephan has done a beautiful job of it already :-).
Answer: You can think about your problem as a Markov chain, i.e., a set of states with certain transition probabilities between states. You start in one state (all cards face up) and end up in an absorbing state (all cards face down). Your question is about the expected number of steps until you reach that absorbing state, either for a single chain, or for the expected minimum number of steps across $n$ independent Markov chains running simultaneously.
And there are actually two slightly different ways to look at this. The first one, as whuber comments, is to consider the six cards as six different bits $\{0,1\}$ and consider the state as a six-vector in $\{0,1\}^6$, i.e., the six-dimensional discrete hypercube. We start out at the vertex $(0,0,0,0,0,0)$, and the absorbing state is $(1,1,1,1,1,1)$. A step can take us to an adjacent vertex, in which exactly one bit is flipped with respect to the original state. That is, transitions take us from one vertex to any neighboring one with Hamming distance exactly one, and each such neighbor has an equal probability of being the next state.
There is some literature on random walks and Markov chains on discrete cubes with Hamming distances, but nothing I could locate at short notice. We have a very nice thread on Random walk on the edges of a cube, which might be interesting.

The second way to look at this is to use the fact that all cards are interchangeable (assuming a fair die). Then we can use just seven different states, corresponding to the number of cards face down. We start in the state $i=0$, and the absorbing state is $i=6$. The transition probabilities depend on the state we are in:

From $i=0$ (all cards face up), we will flip one card down and end up with one card face down with certainty: we have the transition probability $p_{01}=1$ (and $p_{0j}=0$ for $j\neq 1$).
From $i=1$, we can reach $j=0$ with probability $p_{10}=\frac{1}{6}$ and $j=2$ with probability $p_{12}=\frac{5}{6}$.

Overall, we get the following transition matrix:
$$
T=\begin{pmatrix}
  0 & \frac{6}{6} & 0 & 0 & 0 & 0 & 0 \\
  \frac{1}{6} & 0 & \frac{5}{6} & 0 & 0 & 0 & 0 \\
  0 & \frac{2}{6} & 0 & \frac{4}{6} & 0 & 0 & 0 \\
  0 & 0 & \frac{3}{6} & 0 & \frac{3}{6} & 0 & 0 \\
  0 & 0 & 0 & \frac{4}{6} & 0 & \frac{2}{6} & 0 \\
  0 & 0 & 0 & 0 & \frac{5}{6} & 0 & \frac{1}{6} \\
  0 & 0 & 0 & 0 & 0 & 0 & 1
\end{pmatrix}
$$
We start with certainty in the state $i=0$. We can encode the probabilities for each state at a certain point with a vector $v\in[0,1]^7$, and our starting state corresponds to $v_0=(1,0,0,0,0,0,0)$.
Here is a fundamental fact about Markov chains (which is easy to see and to prove via induction): the probabilities for the state after $k$ transitions are given by $v_k=(T')^kv_0$. (That is $T$ transposed. You can also work with row vectors $v$, then you don't need to transpose, but "$v_0T^k$" takes a little getting used to.)
Thus, the probability that we have ended up in the absorbing state $i=6$ after $k$ steps is precisely the last entry in that vector, or $v_k[6]=((T')^kv_0)[6]$. Of course, we could already have been in the absorbing state after $k-1$ steps. So the probability that our Markov chain ends up in the absorbing state for the first time after $k$ steps is
$$ p_k := ((T')^kv_0)[6]-((T')^{k-1}v_0)[6]. $$
We can numerically calculate $p_k$ for a large enough number of $k\leq K$ such that $\sum_{k=0}^Kp_k\approx 1$, and there may even be a closed form solution. Then, given $p_k$, we can calculate the expectation as
$$ \sum_{k=0}^\infty kp_k \approx \sum_{k=0}^K kp_k. $$
Next, assume we have $n$ players, and we want to know after how many steps the game will end, i.e., when the first player has all their cards face down. We can easily calculate the probability $q_k^n$ that at least one player has all cards face down after $k$ or fewer steps by noting that
$$ \begin{align*}
  q_k^n &= P(\text{at least one player has all cards face down after $k$ or fewer steps}) \\
  &= 1-P(\text{all $n$ players need at least $k+1$ steps}) \\
  &= 1-P(\text{ONE player needs at least $k+1$ steps})^n \\
  &= 1-\bigg(\sum_{j=k+1}^\infty p_j\bigg)^n \\
  &= 1-\bigg(1-\sum_{j=0}^k p_j\bigg)^n.
\end{align*} $$
From this, we can derive the probability $p^n_k$ that a game of $n$ players ends after exactly $k$ steps:
$$ p^n_k = q_k^n-q_{k-1}^n = \bigg(1-\sum_{j=0}^{k-1} p_j\bigg)^n-\bigg(1-\sum_{j=0}^k p_j\bigg)^n. $$
And from this, in turn, we can again calculate the expected length of a game with $n$ players:
$$ \sum_{k=0}^\infty kp^n_k \approx \sum_{k=0}^K kp^n_k. $$

As I wrote above, there may be a closed form solution for the $p_k$, but for now, we can numerically evaluate them using R. I'm using $K=10,000$, so that $\sum_{k=0}^K p_k=1$ up to machine accuracy.
max_steps <- 10000
state_probabilities <- matrix(NA,nrow=max_steps+1,ncol=7,dimnames=list(0:max_steps,6:0))
state_probabilities[1,] <- c(1,0,0,0,0,0,0)
transition_matrix <- rbind(
    c(0,6,0,0,0,0,0),
    c(1,0,5,0,0,0,0),
    c(0,2,0,4,0,0,0),
    c(0,0,3,0,3,0,0),
    c(0,0,0,4,0,2,0),
    c(0,0,0,0,5,0,1),
    c(0,0,0,0,0,0,6))/6

for ( kk in 1:max_steps ) {
    state_probabilities[kk+1,] <- t(transition_matrix)%*%state_probabilities[kk,]
}

probs <- diff(state_probabilities[,7])
sum(probs)  # yields 1
sum(probs*seq_along(probs)) # yields 83.2

plot(probs[1:400],type="h",xlab="Number of steps",ylab="Probability",las=1)

Next, this is how we get the probabilities $p^4_k$ for $n=4$ players:
n_players <- 4

probs_minimum <- sapply(1:max_steps,
    function(kk)(1-sum(probs[1:(kk-1)]))^n_players-(1-sum(probs[1:kk]))^n_players)
head(probs_minimum)
plot(probs_minimum[1:400],type="h",xlab="Number of steps",ylab="Probability",
    las=1,main=paste(n_players,"players"))

Of course, four persons finish more quickly than a single person. For $n=4$, we get an expected value of
sum(probs_minimum*seq_along(probs_minimum))
[1] 25.44876

Finally, I like to confirm calculations like this using simulation.
n_sims <- 1e5
steps_minimum <- rep(NA,n_sims)
pb <- winProgressBar(max=n_sims)
for ( ii in 1:n_sims ) {
    setWinProgressBar(pb,ii,paste(ii,"of",n_sims))
    set.seed(ii)    # for reproducibility
    states <- matrix(FALSE,nrow=6,ncol=n_players)
    n_steps <- 0
    while ( TRUE ) {
        n_steps <- n_steps+1
        for ( jj in 1:n_players ) {
            roll <- sample(1:6,1)
            states[roll,jj] <- !states[roll,jj]
        }
        if ( any ( colSums(states) == 6 ) ) {
            steps_minimum[ii] <- n_steps
            break
        }
    }
}
close(pb)

The distribution of the numbers of steps needed in our $10^5$ simulated games matches the calculated $p^4_k$ rather well:
result <- structure(rep(0,length(probs_minimum)),.Names=seq_along(probs_minimum))
result[names(table(steps_minimum))] <- as.vector(table(steps_minimum))/n_sims
cbind(result,probs_minimum)[1:30,]
    result probs_minimum
1  0.00000    0.00000000
2  0.00000    0.00000000
3  0.00000    0.00000000
4  0.00000    0.00000000
5  0.00000    0.00000000
6  0.06063    0.06031414
7  0.00000    0.00000000
8  0.08072    0.07919228
9  0.00000    0.00000000
10 0.08037    0.08026479
11 0.00000    0.00000000
12 0.07382    0.07543464
13 0.00000    0.00000000
14 0.06826    0.06905406
15 0.00000    0.00000000
16 0.06409    0.06260212
17 0.00000    0.00000000
18 0.05668    0.05654555
19 0.00000    0.00000000
20 0.05180    0.05100393
21 0.00000    0.00000000
22 0.04570    0.04598101
23 0.00000    0.00000000
24 0.04078    0.04144437
25 0.00000    0.00000000
26 0.03749    0.03735245
27 0.00000    0.00000000
28 0.03241    0.03366354
29 0.00000    0.00000000
30 0.03026    0.03033861

Finally, the mean of the steps needed in the simulated games also matches the calculated expectation quite well:
mean(steps_minimum)
[1] 25.43862

Comment: Very nice!  One slight improvement would be to replace the expectation formula `sum(probs*seq_along(probs)) # yields 83.2` by `1 + sum(1 - probs)`. This provides an entry to obtaining a closed formula for the expectation, too.
Comment: n_players <- 4 needs some indentation to become `n_players <- 4` but I can't edit it because of the (IMHO pointless) min. edited character limit.
Comment: @mschilli: thanks for pointing that out - fixed!
Answer: I think I've found the answer for the single player case:
If we write $e_{i}$ for the expected remaining length of the game if $i$ cards are facedown, then we can work out that:
(i). $e_{5} = \frac{1}{6}(1) + \frac{5}{6}(e_{4} + 1)$
(ii). $e_{4} = \frac{2}{6}(e_{5} + 1) + \frac{4}{6}(e_{3} + 1)$
(iii). $e_{3} = \frac{3}{6}(e_{4} + 1) + \frac{3}{6}(e_{2} + 1)$
(iv). $e_{2} = \frac{4}{6}(e_{3} + 1) + \frac{2}{6}(e_{1} + 1)$
(v). $e_{1} = \frac{5}{6}(e_{2} + 1) + \frac{1}{6}(e_{0} + 1)$
(vi). $e_{0} = \frac{6}{6}(e_{1} + 1)$
(vi) and (v) then give us (vii). $e_{1} = e_{2} + \frac{7}{5}$;
(vii) and (iv) then give us (viii). $e_{2} = e_{3} + \frac{11}{5}$;
(viii) and (iii) then give us (ix). $e_{3} = e_{4} + \frac{21}{5}$;
(ix) and (ii) then give us (x). $e_{4} = e_{5} + \frac{57}{5}$;
(x) and (i) then give us $e_{5} = 63 $
We can then add up to get $e_{0} = 63 + \frac{57}{5} + \frac{21}{5} + \frac{11}{5} + \frac{7}{5} + 1 = 83.2$.
Now, how would one generalize this to find the expected length of game with $n$ players?
Comment: Good use of symmetry to simplify the problem, since it's irrelevant which cards are face up or down, only the number of face up/down cards matters. I suspect the problem gets a bit more complicated with an unfair die, since you now need to account for differences among the cards.


The linearization at an equilibrium point of a planar Hamiltonian system has eigenvalues that are either +-a or +-ai, a in R

Question: This is a proposition in our textbook, but it is never explained as to why (we take it as given), and it doesn't seem very intuitive.  Is there an elegant way to show this that I'm missing?
Answer: A planar Hamiltonian system looks like
$\dot q = \dfrac{\partial H(p, q)}{\partial p} = H_p, \tag 1$
$\dot p = -\dfrac{\partial H(p, q)}{\partial q} = -H_q. \tag 2$
The Jacobean matrix $J_H$ of (1)-(2) is
$J_H = \begin{bmatrix} H_{pq} & H_{pp} \\ -H_{qq} & -H_{qp} \end{bmatrix}. \tag 3$
If we allow that
$H \in C^2(U, \Bbb R), \tag 4$
where $U \subset \Bbb R^2$ is an open set on which $H(p, q)$ is defined, then
$H_{pq} = H_{qp}, \tag 5$
so it follows that the trace of $J_H$,
$\text{Tr}(J_H) = H_{pq} - H_{qp} = 0; \tag 6$
thus the characteristic polynomial $\chi_H(\lambda)$ of $J_H$ is easily seen to be
$\chi_H(\lambda) = \lambda^2 - \text{Tr}(J_H) \lambda + \det(J_H) = \lambda^2 + \det(J_H) = 0; \tag 7$
it follows that
$\det(J_H) \le 0 \Longrightarrow \lambda =\pm \sqrt {-\det(J_H)} \in \Bbb R,\tag 8$
and
$\det(J_H) > 0 \Longrightarrow \lambda =\pm i\sqrt {\det(J_H)} \in i\Bbb R, \tag 9$
as per request. $OE\Delta$


Split String into String array

Question: I have been playing around with programming for arduino but today i've come across a problem that i can't solve with my very limited C knowledge.
Here's how it goes.
I'm creating a pc application that sends serial input to the arduino (deviceID, command, commandparameters). This arduino will transmit that command over RF to other arduino's.  depending on the deviceID the correct arduino will perform the command.
To be able to determine the deviceID i want to split that string on the ",".
this is my problem, i know how to do this easily in java (even by not using the standard split function), however in C it's a totally different story.
Can any of you guys tell me how to get this working?
thanks
/*
  Serial Event example

 When new serial data arrives, this sketch adds it to a String.
 When a newline is received, the loop prints the string and
 clears it.

 A good test for this is to try it with a GPS receiver
 that sends out NMEA 0183 sentences.

 Created 9 May 2011
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/SerialEvent

 */

String inputString;         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
String[] receivedData;

void setup() {
    // initialize serial:
    Serial.begin(9600);
    // reserve 200 bytes for the inputString:
    inputString.reserve(200);
}

void loop() {
    // print the string when a newline arrives:
    if (stringComplete) {
        Serial.println(inputString);
        // clear the string:
        inputString = "";
        stringComplete = false;
    }
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
    while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read();
        if (inChar == '\n') {
            stringComplete = true;
        }
        // add it to the inputString:
        if(stringComplete == false) {
            inputString += inChar;
        }
        // if the incoming character is a newline, set a flag
        // so the main loop can do something about it:
    }
}

String[] splitCommand(String text, char splitChar) {
    int splitCount = countSplitCharacters(text, splitChar);
    String returnValue[splitCount];
    int index = -1;
    int index2;

    for(int i = 0; i < splitCount - 1; i++) {
        index = text.indexOf(splitChar, index + 1);
        index2 = text.indexOf(splitChar, index + 1);

        if(index2 < 0) index2 = text.length() - 1;
        returnValue[i] = text.substring(index, index2);
    }

    return returnValue;
}

int countSplitCharacters(String text, char splitChar) {
    int returnValue = 0;
    int index = -1;

    while (index > -1) {
        index = text.indexOf(splitChar, index + 1);

        if(index > -1) returnValue+=1;
    }

    return returnValue;
}

I have decided I'm going to use the strtok function.
I'm running into another problem now. The error happened is

SerialEvent.cpp: In function 'void splitCommand(String, char)':
SerialEvent:68: error: cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'
SerialEvent:68: error: 'null' was not declared in this scope

Code is like,
String inputString;         // a string to hold incoming data

void splitCommand(String text, char splitChar) {
    String temp;
    int index = -1;
    int index2;

    for(temp = strtok(text, splitChar); temp; temp = strtok(null, splitChar)) {
        Serial.println(temp);
    }

    for(int i = 0; i < 3; i++) {
        Serial.println(command[i]);
    }
}

Comment: `strtok` is depreciated. use `strsep` instead
Comment: Look at the `strtok()` function.
Comment: For future reference, AFAIK `strtok()` is _not_ deprecated (or depreciated). The MS Visual C++ compiler marks it as unsafe ad provides and alternative, as does GNU/POSIX (different alternatives though). Used properly and with awareness of its shortcomings, it will operate as intended.
Comment: `strtok` is not a good solution for this problem: it would consider any sequence of `,` to be a single separator. Furthermore it might not be available on the arduino platform.
Answer: This is an old question, but i have created some piece of code that may help:
 String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }

  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

This function returns a single string separated by a predefined character at a given index. For example:
String split = "hi this is a split test";
String word3 = getValue(split, ' ', 2);
Serial.println(word3);

Should print 'is'. You also can try with index 0 returning 'hi' or safely trying index 5 returning 'test'.
Hope this help!
Comment: This is great. Thanks. Just a warning, it only splits by a single character.
I was using a string with `~` to split items and `~~` for new line and it wasn't working.
Comment: please post where do I send the beers! great solution, works perfect
Answer: Implementation:
int sa[4], r=0, t=0;
String oneLine = "123;456;789;999;";

for (int i=0; i < oneLine.length(); i++)
{
 if(oneLine.charAt(i) == ';')
  {
    sa[t] = oneLine.substring(r, i).toInt();
    r=(i+1);
    t++;
  }
}

Result:
    // sa[0] = 123
    // sa[1] = 456
    // sa[2] = 789
    // sa[3] = 999

Comment: Welcome to SO. Please omit code only answers by providing some context and explanation. See http://stackoverflow.com/help/how-to-answer
Comment: Not sure what is the problem, I see a valid implementation and a really simple example on how to split a string based on a separator and store the values.
The only issue here was that he missed to add ".toInt()" (considering that we want to store the values into an int array). Everything looks nice.
Good job @Jan
Answer: For dynamic allocation of memory, you will need to use malloc, ie:
String returnvalue[splitcount];
for(int i=0; i< splitcount; i++)
{
    String returnvalue[i] = malloc(maxsizeofstring * sizeof(char));
}

You will also need the maximum string length.
Comment: You don't necessarily need `malloc()`.  If the string is not going to change in between the split operation and the data transmission, it's perfectly safe to keep a set of pointers to various positions in the original string.  It's also faster, uses less memory, and leaves fewer potential memory leaks.
Comment: Yes, that could work, you would just have to keep manual track of the length/end of each string to avoid overlapping, as there would not be a `'\0'` termination character on any but the last one.
Answer: The C way to split a string based on a delimiter is to use strtok (or strtok_r).
See also this question.
Comment: `strtok` is depreciated. use `strsep` instead
Comment: Deprecated by whom? Ten minutes googling only turned up the deprecation in Microsoft Visual Studio C++.  The OP is programming an Arduino, which uses its own version of C, so whether a function is deprecated in Windows is utterly irrelevant.
Answer: I think your idea is a good start point. Here is a code that i use (to parse HTTP GET REST requests with an Ethernet shield).
The idea is to use a while loop and lastIndexOf of and store the strings into an array (but your could do something else).
"request" is the string you want to parse (for me it was called request because.. it was).
    int goOn = 1;
    int count = -1;
    int pos1;
    int pos2 = request.length();

    while( goOn == 1 ) {
        pos1 = request.lastIndexOf("/", pos2);
        pos2 = request.lastIndexOf("/", pos1 - 1);

        if( pos2 <= 0 ) goOn = 0;

        String tmp = request.substring(pos2 + 1, pos1);

        count++;
        params[count] = tmp;

        // Serial.println( params[count] );

        if( goOn != 1) break;
    }
    // At the end you can know how many items the array will have: count + 1 !

I have used this code successfully, but i thing their is an encoding problem when i try to print params[x]... i'm alos a beginner so i don't master chars vs string...
Hope it helps.
Answer: I believe this is the most straight forward and quickest way:
String strings[10]; // Max amount of strings anticipated

void setup() {
  Serial.begin(9600);

  int count = split("L,-1,0,1023,0", ',');
  for (int j = 0; j < count; ++j)
  {
    if (strings[j].length() > 0)
      Serial.println(strings[j]);
  }
}

void loop() {
  delay(1000);
}

// string: string to parse
// c: delimiter
// returns number of items parsed
int split(String string, char c)
{
  String data = "";
  int bufferIndex = 0;

  for (int i = 0; i < string.length(); ++i)
  {
    char c = string[i];

    if (c != ',')
    {
      data += c;
    }
    else
    {
      data += '\0';
      strings[bufferIndex++] = data;
      data = "";
    }
  }

  return bufferIndex;
}

Comment: Are you sure this works? In the split function `c` is a parameter and a local variable. Also, comma isn't dynamically used.

Split String into String array


A Question about JTextField in Java

Question: I met a small problem when running a Java class that I wrote, though the design is pretty straightforward. I've created a JPanel, and I've added four JTextFields onto it and I've attached a button to this JPanel, too. Then, I've associated an ActionListener to this button being pressed. The code is like:
okButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
       if (imageIdField.getText() == "" &&
           captionField.getText() == "" &&
           creditField.getText() == "" &&
           titleField.getText()== "")
           {
              mediaXML = "";
              results.clear();
              results.put("error1", "more");

           }
           else
           { ....
           }
    }

The strange thing is after I've pressed the OK button, and I did input text in those four JTextFields, still it will fall in the IF branch as if I didn't input any text in any of these four fields.
I've been debugging this for a while, but no clue. Could anyone give me some hint like whether .getText() == "" is a valid way for testing no input?
Thanks in advance!
Comment: See: http://stackoverflow.com/questions/971954/difference-between-equals-and
Answer: As has been mentioned, using == is not correct. For readability, try:
field.getText().isEmpty()

or
field.getText().trim().isEmpty()

Answer: Generally a bad idea to use == on Strings, or most other things. It checks that the objects are exactly the same instance, not that they have the same value. "" != new String("").
field.getText().equals("")

Or possibly better:
field.getText().isEmpty()

Answer: Use getText().equals("") instead of ==
Answer: Use == to check if it is the same object in memory, and .equals("YOUR STRING") to check if the content of the object is the same.
Answer: You should use .equals. Also, you might want to do something like this:
imageField.getText().trim().length() == 0  //The same for the others

or
imageField.getText().trim().isEmpty() //The same for the others

if you want to make sure that the user has actually written some characters instead of just white spaces.
Comment: it removes all white space at both ends of the string
Comment: Yeah, in most cases you want to avoid having the user provide a bunch of white spaces as input. For instance for user names, you might want to have alpha numeric characters instead of a bunch of white spaces.
Answer: == only checks whether the left hand side and the right hand side refer to the exact same instance of an object. And since "" translates to something like new String(""), it will always return false, if you compare it with a string that already exists.
If you want to compare whether two instances of a class have the same state you need to use equals(). In your case *.getText().equals(""). A more elegant method would to use the isEmpty() method of the String class.

A Question about JTextField in Java


What is the distribution of the predictions in linear regression?

Question: As the question states, what is the distribution of the predicted $y$ values in linear regression? I'm sure this question has been answered somewhere before but I can't seem to find it for some reason.
Edit: forgot to mention that I'm making standard homoskedastic normal residual assumptions.
Comment: Welcome to Cross Validated! Do you mean the conditional distribution or the pooled (marginal) distribution of all predictions combined together? Also, you've tagged this with [tag:normal-distribution]. Why? The normal distribution could come up in this discussion but does not have to.
Comment: @Firebug, this sounds fine like a shorthand to be used by experts that know the context, but taken literally it can be confusing for beginners – that's all.
Comment: Edited post - forgot to mention assumptions. I'm looking for the conditional distribution given $X$, if that's what you mean.
Comment: By linear regression, do you mean a maximum likelihood model where you assume that the conditional distribution of $y$ given $X$ is Normal?
Comment: @Firebug, maximum likelihood is a type of estimator, not a model.
Comment: @RichardHardy by 'maximum likelihood model' I refer to models that are estimated using maximum likelihood. This is quite commonplace as far as I'm aware.
Answer: Assume a traditional linear regression and that the data follow the model, i.e, given $X$ the corresponding value $Y|X$ will be distributed as $\mathcal{N}(X \beta, \sigma^2)$ for some true values of $\beta$ and $\sigma$. In this case,  the least squares estimator (and the MLE) for $\beta$, $\hat{\beta} = (X^\top X)^{-} X^\top Y$ is just a linear transformation of multivariate normal random variables $Y$ and thus has the distribution $\mathcal{N}(\beta, (X^\top X)^{-} \sigma^2)$. (See this answer)
Then the prediction for a new $X_j$ is given by $\hat Y_{j} = X_j (X^\top X)^{-} X^\top Y $ which again is a linear transformation of a multivariate normal so
$$\hat Y_{j}| X_j \sim  \mathcal{N}(X_j\beta, X_j(X^\top X)^{-} X_j^\top \sigma^2)$$
This neglects any uncertainty about the predictors $X$ and $X_j$ and what values they will have and treats them as deterministic quantities. If you assume some distribution for $X$ and $X_j$ then the distribution of $\hat{\beta}$ and thus $\hat Y_{j} | X_j$ will also change.
Comment: While correct, this perspective does not seem to be practically relevant. In regression applications, we do not have the true values $\beta$ but only the estimates $\hat\beta$. That makes the distribution of the predictions much more involved. Stephan Kolassa's answer goes in that direction.
Comment: In my context I do have the true values $\beta$ so this was the answer I was looking for.
Comment: @mrepicfoulgermrepic1123, if you know $\beta$ and use $X_j \beta$ instead of $X_j \hat{\beta}$, then the predictions are just deterministic and not normally distributed.
Answer: The precise answer will depend on whether your errors are normally distributed (and homoskedastic, and independent). If so, future observations follow a t distribution, see section 3.5 in Faraway (2002), "prediction of a future value", although I would have called the intervals "prediction intervals" rather than "confidence intervals".
If your errors are non-normal, you can often assume a t or normal distribution by arguing asymptotics, but I don't have a reference at hand.
Comment: @Dave: prediction intervals in standard linear regression, as asked in the question, usually assume a t distribution, *conditional on predictors*, which I assumed was intended. I don't quite understand what your example should be telling us, to be honest. Yes, *unconditional* predictions may be bimodal. But how often are we interested in unconditional predictions - especially if we don't know anything about the distribution of the predictors?
Comment: The distribution of estimates and predictions is Gaussian. But for the computation of confidence intervals or prediction intervals we use a t-distribution. The question asks for the former.
Comment: This does not give t-distributed predictions: `set.seed(2023); N <- 1000; x <- rbinom(N, 1, 0.5); y <- 7*x + rnorm(N); plot(density(y))`. The predictions are bimodal. I think you are addressing a different question.
Comment: As I read the question it is just about the sampling distribution of $\hat{Y}_j$ in relation to the true parameters. The more relevant/interesting deviation $Y_j - \hat{Y}_j$ follows a t-distribution when assuming homoskedastic residuals with linear regression, so in this sense one could say the predictions follow a t-distribution centered on the hypothetical "actual" value of $Y_j$ (which is a random variable).
Comment: The *predictions* are t-distributed?
Comment: Edited post - forgot to mention assumptions.
Comment: Reading this answer and taking it literally, I share Dave's confusion. At the same time I also understand Stephan's explanation in the comment. For clarity, why not make the conditioning explicit in the answer?


Creating or exporting an image of an LVM filesystem that is portable.

Question: There is an important machine in my department which must be backed up. It uses lvm2 to span its various partitions over two 80G PATA hard drives (lvm tools output: http://pastebin.com/Wh3h9PVz). I have tried using clonezilla to image the drives, but it is being difficult. I may have gotten a good image of it by using the "use dd only" option, however I am having difficulty restoring that image to a new machine. How can I make an image of these partitions such that the filesystem can be recreated on a new machine? Ideally, the solution would include being able to put the filesystem on SATA hard drives rather than PATA.
Comment: If you can stop all services that write to the drive even rsync/tar would get you a good snapshot that should be easy to restore.
Comment: Is there a reason it must be an image? Why not just make a backup, since you're using LVM to join together drives? Your best option may be creating a real backup with something like Amanda or Bacula.
Comment: There is not enough detail here about what you've done, and how it has failed, to have a hope of providing a useful answer.
Comment: There is not enough information in your comment for me to rectify this. I thought it was pretty straightforward. I need a way to export this filesystem to another drive or combination of drives. None of the clonezilla options worked for creating a backup except the force dd option. None of the clonezilla restore options worked, including the force dd option. Perhaps if I had some idea as to what additional information was required to get an answer, I could provide it.
Comment: Make your question of the form "when I do , I get .  I expect ".  `` should be sufficiently detailed that an interested reader can reproduce your outcome (typically, a set of commands run, option boxes ticked, whatever).  Y'know, "Asking questions 101" stuff.
Answer: Because you're using LVM set up on those specific drives, I'm not sure I'd want so much a clone of the system as just a straight backup. Otherwise you might restore to a system that doesn't take kindly to the drive configuration you restore to. Personally the only time I clone things now is if I'm making a workstation image to roll out to labs or if I'm doing something with virtual machines. Plus you said right in the question that you're hoping to change drive configurations and I've been there with some cloning; a slight change in drive geometry can result in major headaches with many cloning options. Many of the ones I've used do NOT like it when you change the underlying hardware in a cloned restore.
What you might want instead is to look into Amanda or Bacula, backup solutions that you can save your system to another media and restore parts as needed.
Alternatively, depending on how this server is used, we rolled out a VMWare ESXi system and put several servers on it. To do a poor man's cloning of a server we can (because of our environment; business production systems that are needed 24/7 wouldn't have this particular solution available) shut down the server and copy the hard drive image to another ESXi system or network storage system then start the VM back up. To "recover," we can put the drive images on another ESXi system and fire up the VM there.  Slow compared to VMWare's pay-for options featuring livemotion and such but if you can afford the extra management and time overhead, it can work.
Alternatively in a VM environment you can just back up the the guest VM with regular Windows/Linux backup tools (so there's no need to take the VM offline) and if something goes wrong restore to another blank VM on another VM host as if it were a "clean" restore.
There are tools for doing a physical to virtual migration if you think this may be an option for your situation. From your description, though, cloning may not be the best option.
Another alternative would be to use utilities like tar or dump or even rsync to capture a snapshot of your filesystem to a network share or other media. You would have to examine your particular usage case, though, since some of these utilities don't like busy filesystems and/or open file handles.


Insert character without entering insert mode?

Question: Sometimes I want to insert a  # to comment out a line and test it quickly. Currently I do:
i#ESC:w
Is there something shorter I can do?
Comment: There are many comment scripts. I use commentary.vim: https://github.com/tpope/vim-commentary
Comment: As others have said, you might want to try a plugin for comments. More generally, though, if you have a simple action that you need to do often or repetitively, you can easily create a mapping or macro.
Comment: possible duplicate of [What's a quick way to comment/uncomment lines in Vim?](http://stackoverflow.com/questions/1676632/whats-a-quick-way-to-comment-uncomment-lines-in-vim)
Comment: using neovim 0.5 in 2021, i make little todo items in readme files and i often have `- [ ] ` in markdown, and i'd like to add a `x` to signify i've completed my item. so i use,

`r` to go into replace char mode and then type `x` to fill in the empty char (if you will)

seems to work quite well.
Answer: Although I agree with others that there are better ways to comment and uncomment code, it seems that people have gotten distracted and forgotten to actually answer the question.
This is my approach to inserting a single character:
:noremap <key> i <Esc>r

I tend to find that I need to replace, remove, or add single characters very often if I'm correcting typos, so (resp.) r, x, and whatever is chosen for <key> in the above become very handy.
Note that . is also particularly handy for this sort of task. It repeats the previous action.
Personally though, I only map this function to a valuable key when I'm doing a task where I use it frequently enough to justify occupying a prime spot on the keyboard (such as correcting typos), because really, it only saves one keystroke per use and that's only when <key> is not a combination, which of course limits availability.
Comment: maybe it only saves one key stroke, but it also saves the mental overhead of switching modes, which should feel significant in vim.
Comment: This mapping [doesn't work](https://vi.stackexchange.com/questions/5176/is-there-a-way-to-insert-a-single-character-and-then-exit-insert-mode#comment9880_5177) with `.`
Answer: I map a couple of things to my <leader> key (\ by default):
" # comment the current line
nnoremap <leader>d I#<ESC>

" block comment in visual mode
vnoremap <leader>c <ESC>'<O/*<ESC>'>o*/<ESC>V'<k

If you want to add a # to the start of a group of lines, then do this:

<ctl-v>
j (as many times as necessary
I#
<esc>
Answer: You could use a recording. From normal mode, type:
qlml0i#<press escape>`lq

Then to comment out a line, just press @l
Answer: Mapping in vim is so easy that I might do something like
:nmap CC I#<Esc>:w<CR>

on the fly.  If I get used to it, then I will add it to my vimrc file.
:help key-mapping
:help usr_40.txt

Answer: Actually there is a plugin you might wanna take a look at:
http://www.vim.org/scripts/script.php?script_id=1218
It is specifically designed for that purpose.
Answer: I'm particularly fond of the tComment plugin. gcc to comment a line, repeat to uncomment, multiple lines, motions, etc.


What proportion of the positive integers satisfies $\gcd(n^2,\sigma(n^2))>\sigma(n)$, where $\sigma$ is the sum-of-divisors function?

Question: The title says it all.

What proportion of the positive integers satisfies $\gcd(n^2,\sigma(n^2))>\sigma(n)$, where $\sigma$ is the sum-of-divisors function?

I tried using Sage Cell Server to search for positive integers $n$ satisfying the said inequality, in the range $1 \leq n \leq {10}^6$, but it was unable to find any.
I dare to conjecture that the proportion in question is zero, but I have no proof.
Updated November 28 2018
I got the same output as Julian, after running the following (presumably correct) GP code in Sage Cell Server:
for (x=1, 1000000,if(gcd(x^2,sigma(x^2))>sigma(x),print(x)))

Updated November 29 2018
The number $n=1$ satisfies
$$\gcd(n^2,\sigma(n^2))=\sigma(n)$$
while almost all integers $n>1$ (except for the $111$ numbers less than ${10}^6$ mentioned by Julian in his answer below) satisfy
$$\gcd(n^2,\sigma(n^2))<\sigma(n).$$
Therefore, I think it might indeed be possible to prove that the set
$$\bigg\{n \in \mathbb{N} \mid \gcd(n^2,\sigma(n^2)) > \sigma(n)\bigg\}$$
has asymptotic density $0$.  But then again, as I have already mentioned, I have no proof.
Comment: There are $111$ integers below $10^6$ satisfying the inequality. The smallest is $693$.
Comment: How often does it happen that $\gcd(n,\sigma(n^2))\gt1$?
Comment: Note that $n$ must be composite.
Comment: Blimey! @Julian, please write out your comment as an actual answer so that I may be able to accept it.
Comment: @BarryCipra, very often, I must say!  Why do you ask?
Answer: Using Mathematica I found that there are $111$ integers below $10^6$ satisfying the inequality. They are
\begin{align}
&693, 1386, 1463, 1881, 2379, 2926, 4389, 4758, 8778, 9516, 11895, \\
&13167, 16653, 18018, 19032, 23790, 24180, 25641, 26169, 26334, 33306, \\
&37271, 40443, 43890, 45201, 52668, 54717, 57057, 61380, 65835, 73150, \\
&78507, 105336, 109725, 111813, 114114, 131670, 157014, 166530, \\
&169959, 171171, 183183, 185801, 210672, 214830, 218085, 219450, \\
&223626, 223839, 230763, 233142, 238887, 250173, 263340, 291555, \\
&294996, 302841, 316407, 329175, 342342, 366366, 368745, 371602, \\
&380737, 381843, 392535, 405384, 408177, 421344, 429660, 447252, \\
&447678, 461526, 477774, 487179, 497211, 500346, 526680, 530439, \\
&539847, 549549, 557403, 559065, 566181, 570570, 605682, 611403, \\
&615660, 618849, 632814, 637032, 658350, 684684, 692289, 697851, \\
&737490, 763686, 766038, 776853, 782691, 803187, 809424, 816354, \\
&855855, 882189, 894504, 901641, 923052, 934857, 961191, 974358
\end{align}
The sequence is now in OEIS.
Code:
Select[Range[10^6], GCD[#^2, DivisorSigma[1, #^2]] > DivisorSigma[1, #] &]

Comment: The sequence has been submitted to [OEIS](http://oeis.org/A322154) and is currently pending for review.
Comment: [OEIS sequence A322154](http://oeis.org/A322154) has already been approved.


Closed ball minus a point is connected

Question: Could someone help me to prove that if $B\subset\mathbb{R}^n$ ($n>1$) is a closed ball, then $B\setminus \{p\}$ is a connected set for all $p\in B$?
Comment: @Clayton You are're right, but how to prove it?
Answer: HINT: Let $x$ and $y$ be any two points of $B\setminus\{p\}$. If $p$ is not on the line segment $\overline{xy}$, then that line segment is a connected set in $B\setminus\{p\}$ containing both $x$ and $y$. If $p$ does lie on the line segment $\overline{xy}$, let $z$ be any point of $B$ that is not on the line through $x$ and $y$, and show that $\overline{xz}\cup\overline{zy}$ is a connected subset of $B\setminus\{p\}$ that contains both $x$ and $y$. (This actually shows that $B\setminus\{p\}$ is not just connected, but path connected.)
Comment: I've tried do this, but I can't finish (see my comment here: http://math.stackexchange.com/questions/446947/how-to-prove-that-any-ball-minus-a-point-is-a-path-connected-set). How can we get $z$?
Comment: @Perguntador, draw a picture! I cannot believe you cannot see how to get $x$...
Comment: @Perguntador: You can take **any** point of $B$ that is not on the line through $x$ and $y$: they **all** work. Draw a picture of what happens in the plane containing $x,y$, and $z$.
Answer: You can solve this problem by reducing to dimension $2$. Firstly, any closed ball in $R^n$ is homeomorphic to the unit closed ball in $\mathbb R^n$, so it suffices to prove that the unit closed ball has the property you mention. Now, in the $\mathbb R^2$, you can draw the argument to see that the closed unit ball minus any point is path connected.
Now, for the general case, given the closed unit ball $B$ in $\mathbb R^n$, with $n\ge 2$, a point $p$ that is removed from $B$, and two points $x,y\in B-\{p\}$, let $V$ be any plane that contains the origin as well as $x$ and $y$ (this is where $n\ge 2$ is used). The intersection $V\cap B$ is homeomorphic to the unit ball in $\mathbb R^2$. Thus, the intersection $V\cap (B-\{p\})$ is homeomorphic either to the unit ball in $\mathbb R^2$ or to the unit ball with a point removed. In either case, $x$ and $y$ can be connected by a path in the intersection (by the two-dimensional argument) and thus also in $B-\{p\}$.
This argument shows that the property is essentially two-dimensional.
Answer: Let $C = B \setminus \{p\}$. Let's asssume that $C$ is not connected, and show that this leads to a contradiction.
If $C$ is not connected, then we can find two closed sets $X$ and $Y$ such that $X \cap Y = \emptyset$ and $X \cup Y = C$. Let $Z = Y \cup \{p\}$. Then $Z$ is closed, $X \cap Z = \emptyset$, and $X \cup Z = B$. But this implies that $B$ is not connected, which is false, so our original assumption must have been wrong.
Caveat: the last time I wrote anything like this was about 40 years ago, so it's quite possible that I've forgotten a few things about topology. As always, you shouldn't necessarily believe the things you read on the internet.
Comment: "As always, you shouldn't necessarily believe the things you read on the internet." +1
Comment: $X$ and $Y$ are closed relative to $B\setminus\{p\}$. There is no reason for them to be closed relative to $B$.
Comment: Aha! Thanks. I was having misgivings, myself, because my argument applies when $n=1$, in which case the result is obviously false. I left the answer because I wanted to know where it goes wrong and whether it can be repaired.

Closed ball minus a point is connected


Referencing UITextFields in a custom cell in a UITableView

Question: I have a static UITableView that has 5 cells like below:

When the user selects the top row I need to execute a method which will populate data into the second row.
When de-queing the cell's I added a target action like so:
[cell.upperTextField addTarget:self action:@selector(upperTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

I get notified of the event. How do I reference the second text view (find the CellForRowAtIndexPath) to enter data into it?
I can't use the didSelectRow since I have disable selection - the user can only tap into one of the provided TextFields.
Comment: one cell has one textfield or one cell has 5 textfields?
Comment: each cell has 2 textFields and 2 labels - the labels are on the right side.
Comment: may be this method help you to notify [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldBeganEditing)
                                             name:UITextFieldTextDidBeginEditingNotification object:nil];
Answer: Add tag values to your UITextFields:
textField1.tag = 1;
textField1.tag = 2;

In your upperTextFieldDidChange: get reference to your superview of your textField and find view by tag:
-(void)upperTextFieldDidChange:(id)sender
{
    UITextFields *tf = (UITextFields*)sender;
    int currentTag = tf.tag;
    // Do any validation if needed
    //Get reference to text field superview
    UIView *v = [tf superview];
    // Get reference to your second text field
    int tfTag = currentTag == 1 ? 2 : 1;
    UITextField *anotherTextField = (UITextField*)[v viewWithTag: tfTag];
    // Execute your method do other stuff here
}

Hope this help
Comment: Thank you very much. I was missing the jump at UIView *v = [tf superview] and the the viewWithTag :)
Answer: Use a custom cell for that and find your cell object using CellForRowAtIndexPath method and now you can easily find your textfield like below.
MyCellView myCell = [myTableView cellForRowAtIndexPath:<your index path>];
myCell.firstTextField

or
myCell.secondTextField

If you want to change the text. You can easily change the text of textField.
Comment: I don't know the index path - upperTextFieldDidChange:(id)sender would only send me the textField - maybe I'm missing something there?
Comment: Den by using this id you can use id.superiew to get the current cell. Dont forget to check if it same class or not.
Comment: Thanks! Yea, I got it to work this way too. I like it a bit better since I don't have to use numeric tags.
Answer: if think it would be easier by subclassing UITableViewCell and handle that internal in that cell. Then you could directly access the correct textfield.
Create a .h and .m wth
@interface YourCell : UITableViewCell

Then name that class in the interfacebuilder inspector section for your storyboard cell.
Then you call the cell in cellForRowAtIndexPath
YourCell *tempCell = (YourCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

Comment: hmm. Can you explain a bit more? How would I call the subclass?


How to find the MLE for two Dirichlet distributions with same mean

Question: I have samples from two groups. Samples from each group follow a Dirichlet distribution. The two Dirichlet distributions have the same mean but different precision. How to find the MLE of mean and two precisions?
Comment: are the group information of the observations known? Also specify the dirichlet distribution (K)
Comment: Have you googled 'Estimating a Dirichlet distribution'? [Tom Minka has a technical note](http://research.microsoft.com/en-us/um/people/minka/papers/dirichlet/minka-dirichlet.pdf) discussing a technique for doing this.
Comment: The group information of the observations is known.

I read Tom Minka's note. It does not address this situation.
Comment: @user20094, I dont know what you mean by "group information of the observations is known". Can you clarify?
Answer: I wrote how to do this in my dissertation work.  Minka's notes are actually quite helpful.  If you take a look at the procedures to obtain the mle of the mean and precision parameters in an iteratice way, it can be modified slightly to obtain the mle under the null hypothesis that the means of two ind. Dirichlet are equal while having seperate precisions. Just tack on an extra likelihood with the appropriate parameterization and follow Minka's steps.


Is there an equivalent word for '3/4?'

Question: It's already known that the most of the quarter fractions have a single word equivalent that correspond with its numerical counterpart, such as '1/4' is a quarter, '1/2' is half, and '4/4' is the same as a whole. I want to know is there an equivalent single word for '3/4' without reading it as 'three-fourths' or 'three-quarters?' I don't know for which community this should be posted under, so correct me to suggest otherwise.
Comment: Most of the quarter fractions have a single word because they are also *one* of something: one quarter, one half, one whole.  Three quarters is not *one* of anything in the same way.
Comment: I was surprised to learn, while looking in to this, that other languages do have words for fractions that aren't reducible to "one over" something.
Comment: you can say "three quaters" but that's not a single word.
Comment: This question *may* be appropriate for the English Languagee SE. But I don't this this is a very good question here or there. What's wrong with just using the word *three-quarters*?
Comment: I believe some languages have a word for 2/3.  But not English.
Comment: @MikePierce It's primarily out of curiosity. As I have said in my question, all of those fractions that were mentioned have a single word equivalent except for 3/4, which is a compound word. Another reason why I asked that, the word 'three-quarters' seems kind of cumbersome in comparison. There's really not much wrong with using 'three-quarters.'
Answer: I don't think there is a single correct answer to your question, so instead here is a list of possibilities.

triquarter
triplequarter
subquarter
shortquarter
quartershort
pacman $\bbox[5ex]{} $
Comment: Since @Joffan added *pacman*, I'm now seriously doubting my claim that there is no single correct answer. :)
Comment: Although the 'pacman' is not as old as the word 'half', it's a nice suggestion though.
Comment: I was quite pleased with it :-)
Comment: I literally call it pacman now, this should become an official naming of 3/4

Is there an equivalent word for '3/4?'


Why do I get this warnings under Cython?

Question: I try to reproduce some examples on the Cython tutorial to learn Cython:
http://docs.cython.org/en/latest/src/tutorial/external.html
I think the two following warnings are not related. Therefore two qestions:
(1)
Using this as input to

python setup.py build_ext --inplace -c mingw32

from libc.math cimport sin

cdef extern from "math.h":
    cdef double sin(double x)

cpdef double f(double x):
    return sin(x*x)

cpdef test(double x):
    return f(x)

I get:
D:\python\cython>python setup.py build_ext --inplace -c mingw32
Compiling primes.pyx because it changed.
[1/1] Cythonizing primes.pyx
warning: primes.pyx:4:19: Function signature does not match previous declaration
running build_ext
building 'primes' extension
C:\MinGW\bin\gcc.exe -mdll -O -Wall -IC:\Python34\include -IC:\Python34\include -c primes.c -o build\temp.win32-3.4\Release\primes.o
writing build\temp.win32-3.4\Release\primes.def
C:\MinGW\bin\gcc.exe -shared -s build\temp.win32-3.4\Release\primes.o build\temp.win32-3.4\Release\primes.def -LC:\Python34\libs -LC:\Python34\PCbuild -lpython34 -lmsvcr100 -o D:\python\cython\primes.pyd

D:\python\cython>

Why is the warning "Function signature does not match previous declaration" ?
(2)
When I declare
cdef extern from "math.h":
    cpdef double sin(double x)

I get the additional warning
warning: primes.pyx:4:20: Function 'sin' previously declared as 'cpdef'

However, it is given exactly in the same way as example in the chapter "External declarations" of the linked page. In a python module where the module is imported, sin is not known under the package. Where is the problem?
The description in the tutorial is:
Note that you can easily export an external C function from your Cython module by declaring it as cpdef. This generates a Python wrapper for it and adds it to the module dict.

Comment: _"I think the two following warnings are not related. Therefore two qestions:"_ One question per question please
Answer: the different parts of the tutorial show different manners to call C functions.
For some functions for which a Cython .pxd header is provided, you can use from libc.math import sin. For all libraries, you can use the lengthier method of .h header and re-declaration.
You cannot mix the two however, as it creates two definitions of the same function even though they are identical.
Comment: I understand. Is the second issue related to that ?
Comment: Very probably :-) `Function 'sin' previously declared as 'cpdef'` is also about multiply defined names. You should try anyway for yourself. Just an additional note: if you want to iteratively test Cython programming, you can do so using Jupyter notebooks http://docs.cython.org/en/latest/src/quickstart/build.html?highlight=ipython#using-the-ipython-notebook


useState não atualiza - ReactJS

Question: Estou iniciando no mundo do ReactJS. Tenho um front que está consumindo uma API de rastreamento, para isso ele me retorna um objeto com status, responseMessage e object, um array de objetos. Faço a desestruturação da requisição e ele realiza o print normalmente no console. Porém no momento em que tento alterar o estado, ele não acusa nenhum erro mas também não altera o estado do componente.
  const dispatch = useDispatch();
  const [dados, setDados] = React.useState([]);

  React.useEffect(() => {
    async function loadData(){
      await dispatch(signInRequestMultiportal());
      const response = await apiMultiportal.request({
        url: 'posicoes/ultimaPosicao',
        method: 'post',
        headers: {
          token: store.getState().auth.tokenMultiportal,
        }
      });

      const { object } = response.data;
      console.log(object)
      setDados(object);
      console.log(dados);
    }
    loadData();
  }, [])

{
 "status": 'OK',
 "responseMessage": "Requisição concluida",
 "object": [{
 }]
}

Print do objeto, o de cima é o console.log(object) o de baixo o console.log(dados)
Comment: se está falando que não altera também na tela ou so no console.log? `console.log(dados);`?:
Comment: No console.log aparece os dados, mas no useState não
Comment: seu object ta vindo nada, tipo um array com 0 posições! se viu isso?
Comment: No `console.log(object)` aparece todos os dados, porém no `console.log(dados)` simplesmente aparece um [  ]
Comment: se está confundindo as bolas, o console.log(data) não tem dados ainda levo um tempo para atualizar seguinte segue o exemplo abaixo que vou criar
Comment: Deu certo, muito obrigado!
Comment: se deu certo assinale como resposta do sua pergunta
Answer: A variável de estado precisa ser monitorada para que tenha as suas alterações e isso é fácilmente resolvido com a utilização de useEffect com um paramento de array contendo a sua variável a ser monitorada, um exemplo simples:

function App() {
  const [data, setData] = React.useState([]);

  const loadData = () => {
    let item = [];
    for(let i = 0; i < 10; i++) {
      item.push(i);
    }
    setData(item);
  }

  React.useEffect(() => {
    loadData();
  }, []);

  React.useEffect(() => { // esse é responsável em pegar as alterações
    console.log(data);
  }, [data]); // pela configuração no `array` com o nome da variável

  return (

      {data.map((i,k) => (
{i}
))}

  )
}
ReactDOM.render(<App/> , document.getElementById('root'));

do jeito que você fez como a alteração não é percebida porque é assíncrona e por isso o uso o useEffect é necessário
Answer: Lucas, o useEffects é bem interessante, porém, se você não colocar nada no array do segundo argumento, ele vai executar uma única vez, colocando uma propriedade ali, ela vai executar toda vez que tiver uma alteração naquela variável.
const dispatch = useDispatch();
  const [dados, setDados] = React.useState([]);

  React.useEffect(() => {
    async function loadData(){
      await dispatch(signInRequestMultiportal());
      const response = await apiMultiportal.request({
        url: 'posicoes/ultimaPosicao',
        method: 'post',
        headers: {
          token: store.getState().auth.tokenMultiportal,
        }
      });

      const { object } = response.data;
      console.log(object)
      setDados(object);
      console.log(dados);
    }
    loadData();
  }, [dados]) // Apenas colocar a propriedade para ficar sendo observada

Fiz um exemplo no JSFiddle para melhor exemplificar caso ainda tenha ficado dúvida.
https://jsfiddle.net/gabrielgstein/4hwvo0Lj/3/
Answer: O que está acontecendo nesse caso é que quando useEffect é executado o valor de estado da variavel data é o valor inicial, se você adicionar a variavel data no array de dependencias o codigo vai executar como você espera.
React.useEffect(function loadData(){....}, [data])
porém a função loadData() sera executada duas vezes o que não é ideal.
então você pode separar os console.log() em outro useEffect()
React.useEffect(()=>{console.log(data)}, [data])

useState não atualiza - ReactJS


Xpath error related to "nbsp"

Question: Got this error when parsing my html page using XPATH.. i am also using HTMLcleaner

If it is not clear i can even post my java code and html code
Comment: This problem stems from treating HTML as XML and is unrelated to xpath.
Comment: XPath traverses an XML Infoset or XDM. It doesn't parse anything.
Answer: The original input is HTML and you're treating it as XML. XML has less predefined entities than HTML has. Either use an HTML parser, or declare the entity   in your XML parser, or textually replace   with   in the original input.

Xpath error related to "nbsp"


Como criar um projeto no GitLab utilizando o git?

Question: Podemos facilmente criar um projeto no GitLab e "sincronizá-lo" pelo git:
$ git clone email@example.com:user/teste.git

Mas e para fazer o contrário?
Criar a pasta e o projeto local, e enviar como um "novo" no GitLab?
Comment: No Github, eu faço o repositório local e o remoto, e depois mando um primeiro commit
Comment: @mutlei Mas o commit é só local. Ele não envia para o GitLab...
Comment: Sim. Depois você dá o push pra enviar o commit pro remoto.
Answer: Eu acho que você está falando de enviar definir um repositório remoto para um projeto existente.
Repositório Local do Zero
Eu costumo fazer assim:

Crio a pasta do projeto
Inicializo o repositório local dentro da pasta que acabei de criar.O comando é git init
Depois disso, adicione os arquivos que serão enviados no primeiro commit. Rode git add . para selecionar todos os arquivos (opcional, se quiser fazer um por um você pode, é apenas um exemplo)
Faça o commit. git commit -m "primeiro commit"
Adicione o local de origem. git remote add origin firstname.lastname@example.com:user/teste.git
Faça o push inicial para o seu servidor: git push -u origin master

Prontinho, você está enviando os dados do local a partir de um repositório já existente na sua máquina.
Resumo do que fiz acima, através do BASH:
>>> mkdir projeto
>>> cd projeto
>>> git init
>>> git add .
>>> git commit -m "primeiro commit"
>>> git remote add origin firstname.lastname@example.com:user/teste.git
>>> git push -u origin master

Repositório local com origem existente
Caso você esteja tentando usar um repositório já existente que tenha outra origem, você não vai conseguir usar o comando git remote add origin.  Nesse caso, use git remote set-url origin email@example.com:user/teste.git, mas apenas se você já tiver um repositório com origin, e não se tiver criando um do zero.
Depois basta fazer o git push -u origin master.
Explicando os comandos
git-init
Inicia um repositório git. Ao rodar esse comando, você está dizendo que, a partir de agora, aquela diretório terá o controle de versão do GIT.
git-add
Adiciona o conteúdo de um ou mais arquivos para o índice de mudança. Quando você faz git add readme.txt, está dizendo que as mudanças feitas em readme.txt irão ser salvas no próximo commit.
Eu gosto de usar git add e ir adicionando as mudanças que fiz de acordo com um tópico.
Por exemplo:
Eu criei um botão na página de cadastro de usuários que verifica se o e-mail é válido. Para isso, criei o botão em criar-usuario.html e em criar-usuario.js fiz a chamada ajax que vai fazer essa consulta.
Você pode fazer assim pra processar as modificações:
 >>> git add views/criar-usuario.html js/criar-usuario.js

Em seguida, quando você fizer o commit, apenas os dois arquivo serão adicionados à lista de modificações.
Quando se usa o ponto (git add .), você está dizendo que todos os arquivos serão adicionados.
git commit -m
Processa as mudanças informadas em git add e adiciona ao histórico de mudança. No caso acima, a flag -m indica que você está informando a mensagem de commit diretamente na chamada do comando. Se você usar apenas git commit, uma janela que geralmente usa o vim ou o nano (editor de código comuns no Linux) se abrirá pra você colocar a mensagem do commit.
As mensagens do commit precisam descrever o que você fez.
Usando o exemplo anterior:
>>> git add js/cadastro-usuario.js views/cadastro-usuario.html
>>> git commit -m "Adicionando botão de consulta de e-mail"

git remote add origin url_do_repostiório
Você está dizendo que o lugar onde ficará salvo as mudanças do GIT remotamente será a url informada.
Esse comando é usado geralmente quando você cria um repositório com git init, pois o mesmo apenas adiciona o controle de versão. O git remote add origin informa o servidor onde você salvará as mudanças.
git push -u origin master
O git push envia as informações dos commits que você criou para o servidor.
Os commits vão sendo adicionados à fila e é possível ver quais não foram enviados através do comando git status.
O -u geralmente é usado no primeiro commit e o origin master indica que o branch de origem será o master. O master geralmente é o branch padrão do GIT.
Não vou me alongar demais sobre Branchs. Dê uma lida sobre isso aqui:

Qual é a diferença entre um branch e uma tag?
Comment: Faltava o remote add! Cara, o que é esse `origin`? Seria a pasta que estou?
Comment: @rbz `origin` é o repositório remoto.
Comment: @rbz dá uma olhadinha no resumo (os comandos)


Using Fetch in JS to call a server-side method (ASP.NET)

Question: I have an ASPX page, called default.aspx and default.aspx.cs being my code on the server side running on IIS 7, something really simple, written in VS Code. In addition to the JS, CSS and IMG folders (these last two have no relevance to the problem in question).
In the JS file I have a function that makes an HTTP request to the server and it should execute a certain method:
fetch('default.aspx/Enviar_Indicador_Novo',{
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({Data: data_Atualizacao, Pilar: pilar})
})
.then(response => console.log(response))
// .then(message => {console.log(message)})
.catch(error => {
    console.log(error)
})

and:
[WebMethod]
public string Enviar_Indicador_Novo(string Data, string Pilar){
    ... metodo a ser executado e retornar uma string de "sucesso" ou "falha""
}

At the beginning of my ASPX file, I put the tag: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs" Inherits="Buscar_SQL.Index" %>
Busca_SQL is my namespace and Index is my partial class.
the response to this request is this: Response {type: 'basic', url: 'http://xxx.xxx.xxx.xxx/xxxx/default.aspx/Enviar_Indicador_Novo', redirected: false, status: 200, ok: true , …}
The issue is, it does not execute the method on the server side, it only reports the response with status 200, even though it does not execute the method.
Can you help me? Is it some config in my IIS? The only thing I did with it was host and configure it to run ASPX pages.
I checked the request route and it is correct, I put the method with public static string ... and it didn't work either.
Answer: I not (yet) used fetch, but what you have does look correct.
Keep in mind that since you are NOT using a asmx page, but a regular aspx page with a webmethod?
Then your web method has to be static, since a whole instance of the page (code behind) class is not being created.
Hence, try this:
[WebMethod]
 public static string Enviar_Indicador_Novo(string Data, string Pilar)
 {
    ... metodo a ser executado e retornar uma string de "sucesso" ou "falha""
  }

You also don't show in your JavaScript code where and how you set the two variables, but we have to assume they are ok, and have been setup correctly.
In addition to the above, I do suggest you check your settings in RouteConfig.cs, since you want to turn off AutoRedirect mode:
        settings.AutoRedirectMode = RedirectMode.Off;


can it be said that $ a<a $ where a is a real?

Question: can it be said that $a<a $ where a is a real number? i think so but i wanna clarify.i had a fight over this with a junior who thinks otherwise. what does "or" mean in the law of trichotomy.I may be wrong.But I remember being told by a teacher.
I think so because in case of sets A can be said be a subset of A.
Comment: No, the answer is no. The notation $x-1) is true to programmer. now consider x must be less than 1 or x must be greater than -1, then there is no number that fits the 2nd criteria of usual language usage of "or".
Comment: Could you explain why you think it's possible?
Comment: @Arjang I'm sorry I still don't get it. In my programming, 'or' has always meant either A or B or both are true. And I'm still not sure how this relates with $a < a$.
Comment: @DSeita : so consider it to the law of trichotomy, then you can have more than one of the criteria being true, where only one criteria can be true. There are 3 mutually exclusive cases, it really has something to do with misinterpretation of meaning, the confusion that arises is not based on logical understanding, having suffered the same problem I can understand the op's problem. If you don't get then that only means you are logically better wired.
Answer: "Or" is often a confusing word for people first encountering it in mathematics, as much of the time it means something different from the colloquial use of "or." Mathematically, $X$ or $Y$  means "either $X$ or $Y$ or both," unless more information is given. The statement of trichotomy does not use or in this way: we have a slightly different statement.
Trichotomy: For any two numbers $a,b\in\mathbb{R}$, exactly one of the following is true:

$a < b$
$b < a$
$a = b$.

Taking your two numbers to be the same, we find that since $a = a$, $a\not< a$ and $a\not > a$. The "exactly one" part of this statement is the reason you cannot have $a < a$.


How can I use generate elements to only fill the screen using Mui Grid in React?

Question: I am using Mui Grid and want to generate fixed size grid elements to fill the screen (both height and width) but I don't know how to do that.
Here is a CodeSandbox link of something basic I am working with. In this example, I hard coded it to render 20 elements. I instead want it to account for the screen size, padding, margin, etc. to programmatically determine how many elements to render. Is this possible?
Comment: There is no way for MUI Grid to auto stretch all element to fill your screen. You may want to make a function to calculate fluid grids and spacing depend on your array length.
Answer: I'm not sure it's possible using Grid, but with plain JavaScript, you should be able to calculate the number of elements to render to fill a page and an event listener on "resize" to continually calculate the proper number of elements to render to completely fill the page width.
CodeSandbox Example
const itemWidth = 100;
const gridGap = 10;

const Item = styled(Paper)(({ theme }) => ({
  textAlign: "center",
  width: `${itemWidth}px`,
  height: "100px"
}));

export default function ResponsiveGrid() {
  const [numOfEl, setNumOfEl] = useState(
    Math.floor(window.innerWidth / (itemWidth + gridGap))
  );

  function getNumberOfElements() {
    setNumOfEl(Math.floor(window.innerWidth / (itemWidth + gridGap)));
  }

  useEffect(() => {
    window.addEventListener("resize", getNumberOfElements);
    return () => window.removeEventListener("resize", getNumberOfElements);
  }, []);

  return (
    <Grid container sx={{ gap: `${gridGap}px` }}>
      {Array.from(Array(numOfEl)).map((_, index) => (
        <Grid key={index}>
          <Item>{index}</Item>
        </Grid>
      ))}
    </Grid>
  );
}

Edit: I only calculated the number for the width, but you get the idea.


Pointwise limit of $f_n(x) =x^2 - \frac{x^n}{n}$

Question: I want to find the (pointwise) limit of $f_n = x^2 - \frac{x^n}{n}$. So, $\lim_{n \to \infty} x^2 - \lim_{n\to \infty} \frac{x^n}{n}$. I know that the latter is limit $0$ if $|x|<1$, but otherwise it is $\infty$. So what should I say about the pointwise limit of $f_n$?
Answer: Let $f = \displaystyle \lim_{n \to \infty} f_n \Rightarrow f(\pm 1) = 1, f(x) = x^2, |x| < 1 \to f(x) = \begin{cases} 1&: x = \pm 1 \\  x^2&: |x| < 1 \\ \text{does not exist}&: |x| > 1\end{cases}$


Tweaking seaborn.boxplot

Question: I would like to compare a set of distributions of scores (score), grouped by some categories (centrality) and colored by some other (model). I've tried the following with seaborn:
plt.figure(figsize=(14,6))
seaborn.boxplot(x="centrality", y="score", hue="model", data=data, palette=seaborn.color_palette("husl", len(models) +1))
seaborn.despine(offset=10, trim=True)
plt.savefig("/home/i11/staudt/Eval/properties-replication-test.pdf", bbox_inches="tight")

There are some problems I have with this plot:

There is a large amount of outliers and I don't like how they are drawn here. Can I remove them? Can I change the appearance to show less clutter? Can I color them at least so that their color matches the box color?
The model value original is special because all other distributions should be compared to the distribution of original. This should be visually reflected in the plot. Can I make original the first box of every group? Can I offset or mark it differently somehow? Would it be possible to draw a horizontal line through the median of each original distribution and through the group of boxes?
some of the values of score are very small, how to do proper scaling of the y-axis to show them?

EDIT:
Here is an example with a log-scaled y-axis - also not yet ideal. Why do the some boxes seem cut off at the low end?
Comment: Have you tried [log-scaling](http://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_boxplot.html) the y variable?
Comment: The blue outliers are a matplotlib bug, and they can be avoided by updating your seaborn. But I certainly wouldn't just remove the outliers!
Comment: @mwaskom Yes, but that "compresses" the bars of larger values very much at the top of the plot. Is there a compromise, i.e. log-scaling for just a part of the axis?
Comment: And sometimes the groups are hard to distinguish, e.g. if the boxes do not touch. Is it possible to draw vertical lines separating the groups?
Answer: Outlier display
You should be able to pass any arguments to seaborn.boxplot that you can pass to plt.boxplot (see documentation), so you could adjust the display of the outliers by setting flierprops. Here are some examples of what you can do with your outliers.
If you don't want to display them, you could do
seaborn.boxplot(x="centrality", y="score", hue="model", data=data,
                showfliers=False)

or you could make them light gray like so:
flierprops = dict(markerfacecolor='0.75', markersize=5,
              linestyle='none')
seaborn.boxplot(x="centrality", y="score", hue="model", data=data,
                flierprops=flierprops)

Order of groups
You can set the order of the groups manually with hue_order, e.g.
seaborn.boxplot(x="centrality", y="score", hue="model", data=data,
                hue_order=["original", "Havel..","etc"])

Scaling of y-axis
You could just get the minimum and maximum values of all y-values and set y_lim accordingly? Something like this:
y_values = data["scores"].values
seaborn.boxplot(x="centrality", y="score", hue="model", data=data,
                y_lim=(np.min(y_values),np.max(y_values)))

EDIT: This last point doesn't really make sense since the automatic y_lim range will already include all the values, but I'm leaving it just as an example of how to adjust these settings. As mentioned in the comments, log-scaling probably makes more sense.
Comment: `flierprops` is nice. I tried passing `sym='+'` to `seaborn.boxplot` and it doesn't have any effect.
Comment: @ zyxue instead of writing sym = '+' , write marker = '+'
Comment: There is no "y_lim" parameter in seaborn.boxplot https://stackoverflow.com/questions/44970932/setting-ylim-on-seaborn-boxplot
Answer: It has been a while since this answer has activity, but I'll answer OP's question regarding the weird looking lower-bounds for any people that need help in the future.
Once you set your y-axis to logarithmic scale, it becomes impossible to represent y=0, since log(0) tends to -inf.
Therefore, when the values regarding the lower part of your boxplot are either zero or very close to it the box has that look of seeming to be 'cut in half'.
Needless to say that it's also impossible to represent negative y values in a logarithmic scale.

Tweaking seaborn.boxplot


Add div after each field of a certain name

Question: I'm trying to display a div container after each field item with the name additional_content of my page content type. Right now im trying to preprocess my field but i can't go down to the real field item i want to proprocess...
Is it better to override the template? And how would that work? i have a field called additional_content integrated into my page content type. After this has been printed i want to add a div container to each of this items.
Any help with that?
Comment: So you want to wrap entire field content with `` and ``?
Comment: @user11153 no i just want to append a  Thanks for asking
Answer: Copy modules/field/theme/field.tpl.php file into sites/all/themes/YOUR_THEME/templates
Rename it to field--additional_content--YOURCONTENTTYPENAME.tpl.php
(or only field--additional_content.tpl.php if you want to change its template for all content types)
Edit its template like this:
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

    <?php endforeach; ?>

Comment: you are right...its just that simple...i tried that but always foot to add the tpl. grrr


problema com select case

Question: estou fazendo select com case comparando status diferentes de um mesmo campo e contabilizando-os em colunas separadas. O problema é que a primeira coluna fica NULL até a lista da segunda terminar a contagem. Depois isso é invertido.
Minha query é a seguinte:
select
    case when cor.status = 35 then count(cor.uid) end as finalizadas,
    case when cor.status = 50 then count(cor.uid) end as canceladas_motorista,
    mot.nome || ' ' || mot.sobrenome as nome,
    mot.celular,
    mot.email
from motoristas mot, corridas cor
where...

segue exemplo de resultado:

Alguma ajuda, por favor?
Comment: *"O problema é que a primeira coluna fica NULL até a lista da segunda terminar a contagem. Depois isso é invertido"* João, não entendi, pode explicar melhor? Como assim terminar a contagem? O resultado vem todo de uma vez, não entendi o que quis dizer
Comment: Eu ajustei a postagem ali com uma foto. Acabei não me expressando corretamente no início, mas acho que com a imagem vai ficar mais fácil de entender.
Comment: agora sim entendi :)  você quer na mesma linha finalizadas  e canceladas né?
Comment: exatamente! Esse é o ponto. Vou tentar ser mais objetivos nas próximas
Comment: só uma dúvida, não está no seu select, mas joins estão sendo feitos certo? Se não for por `inner join`, você está fazendo no `where` certo? Senão o resultado vai sair errado
Comment: sim, estou fazendo no where!
Answer: Você pode também fazer uma subquery para calcular cada status por motorista, assim:
select
  (select count(cor.uid)
     from corridas cor
    where cor.idMotorista = mot.idMotorista
     and cor.status = 35) as finalizadas,
  (select count(cor.uid)
     from corridas cor
    where cor.idMotorista = mot.idMotorista
     and cor.status = 50) as canceladas_motorista,
mot.nome
from motoristas mot

Veja o exemplo funcionando: http://sqlfiddle.com/#!17/29af1/28
Comment: Consegui a resolução em outra resposta já. Mas agradeço a ajuda. Estou tentando descobrir como e encerra tópico ou algo do tipo.
Comment: Encerrar tópico? Não precisa, basta escolher uma resposta :)
Answer: Você pode transformar esta consulta em uma subconsulta, agrupando o retorno pelos campos que não são somatórios; assim, trará para o usuário o resultado final.
select sum(finalizadas), sum(canceladas_motorista), nome, celular, email
(select
    case when cor.status = 35 then count(cor.uid) end as finalizadas,
    case when cor.status = 50 then count(cor.uid) end as canceladas_motorista,
    mot.nome || ' ' || mot.sobrenome as nome,
    mot.celular as celular,
    mot.email as email
from motoristas mot, corridas cor
where ...) as tabela_subconsulta
group by nome, celular, email

Comment: Vou tentar isso e respondo na sequência. Obrigado
Answer: Só tem que ir incrementando o resultado de ambas as colunas:
SELECT      SUM(CASE WHEN cor.status = 35 THEN 1 ELSE 0 END)    AS finalizadas
        ,   SUM(CASE WHEN cor.status = 50 THEN 1 ELSE 0 END)    AS canceladas_motorista
        ,   mot.nome || ' ' || mot.sobrenome                    AS nome
        ,   mot.celular
        ,   mot.email
FROM        motoristas mot, corridas cor
WHERE       ...
GROUP BY    mot.nome || ' ' || mot.sobrenome
        ,   mot.celular
        ,   mot.email

Comment: Voltei pra responder e a resposta já estava aqui. Fiz exatamente isso e solucionou meu problema! Agradeçço muito, de qualquer forma.
Comment: De nada, sempre às ordens! Aproveite e dê um UP nas respostas que você considerou úteis! Obrigado.

problema com select case


Boundedness of Solutions of Differential Equation

Question: I have the differential equation $y''+by=\cos(t)$. The general solution is
$y(t)=\begin{cases}c_1\cos(\sqrt{b}t)+c_2\sin(\sqrt{b}t)+\frac{1}{b-1}\cos(t), b>0, b\neq 1 \\ c_1\cos(t)+c_2\sin(t)+\frac{1}{2}t\sin(t), b =1 \\ c_1t+c_2+\frac{1}{b-1}\cos(t), b=0 \\ c_1 e^{\sqrt{|b|t}}+c_2e^{-\sqrt{|b|t}}+\frac{1}{b-1}\cos(t), b<0\end{cases}$
How do I determine if the solutions are bounded on the interval $[0,\infty)$?
Comment: You have three options (depending on $b$), so you should check if each one is bounded or not.
Comment: How do I check if they are bounded? Do I simply use what I know about the boundedness of the constituent functions?
Comment: What does bounded mean?
Comment: $\exists M s.t. f(x) \leq M$ for all x
Comment: There is an absolute value you're missing, but yes.
Comment: Can you prove that if $f$ and $g$ are bounded, $f+g$ is as well?
Comment: Suppose $|f(x)|\leq M$ and $|g(x)|\leq L$. Then $|f(x)+g(x)| \leq |f(x)| + |g(x)|$ by the Triangle Inequality, which implies that $|f(x)+g(x)| \leq M+L$
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/77066/discussion-between-cbjork-and-blargen).
Answer: This is a very informal answer, but you can expand on it if you wish.

First, let's identify which functions are bounded and which are not.

A constant solution like $f(t)=c$ is obviously always bounded
A linear combination of trig functions is always bounded, since $|\sin t|, |\cos t| \le 1$.
A decaying exponential is bounded on $[0,\infty)$ since $0< e^{-t} \le 1 $
A growing exponential is unbounded on $[0,\infty)$ since $\lim_\limits{t\to\infty} e^t = \infty$
Polynomials of degree $1$ and higher are never bounded, since $\lim_\limits{t\to \infty} t^n = \infty$

Let's look at the cases

$b > 0 \ne 1$ is a linear combination of bounded functions, so is it always bounded. More formally
$$ \big|y(t)\big| \le |c_1|\big|\cos(\sqrt{b}t)\big| + |c_2|\big|\cos(\sqrt{b}t)\big| + \frac{1}{|b-1|}|\cos t| \le |c_1| + |c_2| + \frac{1}{|b-1|} $$
$b=1$ grows without bounds, since it contains the term $ \frac{1}{2}t\sin t $
which has no bound over $[0,\infty)$

For the remaining cases, the particular solution is always bounded, while the general solutions both contain one unbounded term. Therefore, they will either be bounded or unbounded under certain conditions.

$b=0$ contains a linear term, so it will be bounded if $c_1 = 0$. For example, when $y'(0) = 0$
Similarly, $b < 0$ will be unbounded if $c_1 = 0$. For example, when $\lim_\limits{t\to\infty}y(t)=0$
Comment: The last equality in your equation for $b>0$ should also be an inequality, as you replace oscillating functions by constant bounds. $x\sin x$ has no limit, usually $\lim_{x\to\infty} u(x)=\infty$ means that $u(x)>N$ for $x>x_N$ for all $N>0$, which is a formalization of "grows over all boundaries". Of course, maximizing over the oscillations works again, $\lim_{x\to\infty}\max_{t\in [0,x]}t\sin t=\infty$.
Comment: Thanks for the corrections. That first equal sign was a typo, my bad. The limit was meant to be for $|y(t)|$
Comment: But even $|y(t)|$ oscillates between $0$ and $t$ (at $t=(k+0.5)\pi$), so there is no real convergence there, the symbol $\lim$ is not really applicable since its use implies the existence of a limit. You can say $\lim |y((k+0.5)\pi)|=\infty$ and that proves unboundedness.
Comment: Hmm you're right. I'm just going to keep it vague


Prove that if $(ab)^i = a^ib^i \forall a,b\in G$ for three consecutive integers $i$ then $G$ is abelian.

Question: I've been working on this problem listed in Herstein's Topics in Algebra (Chapter 2.3, problem 4):

If $G$ is a group such that $(ab)^i = a^ib^i$ for three consecutive integers $i$ for all $a, b\in G$, show that $G$ is abelian.

I managed to prove it, but I'm not very happy with my result (I think there's a neater way to prove this). Anyway, I'm just looking to see if there's a different approach to this.
My approach:
Let $j=i+1, k=i+2$ for some $i\in \mathbb{Z}$.
Then we have that $(ab)^i = a^ib^i$, $(ab)^j = a^jb^j$ and $(ab)^k = a^kb^k$.
If $(ab)^k = a^kb^k$, then $a^jb^jab =a^jab^jb$.
We cancel on the left and right and we have $b^ja = ab^j$, that is $b^iba = ab^j$.
Multiply both sides by $a^i$ on the left and we get $a^ib^iba = a^jb^j$, so $(ab)^iba = (ab)^j$. But that is $(ab)^iba = (ab)^iab$.
Cancelling on the left yields $ab=ba$, which holds for all $a,b \in G$, and therefore, $G$ is abelian.
Thanks!
Comment: That's also the way I did it. It would be less confusing, though, if you wrote $i+1$ and $i+2$ in full.
Comment: I think you actually have the most obvious way of doing this
Comment: This problem is notorious, and well-known to be considerably harder than the other exercises.
Comment: I'd be curious if there is some way to use the fact that $a^kb^k=(ab)^k$ means that the function: $\phi(a)=a^k$ is an endomorphism of $G$, and that being abelian coincides with the fact that $\lambda(a)=a^{-1}$ is an automorphism...
Comment: I think this is the only way. What motivates you that there could be an another proof of this.
Comment: I don't know if there's another way; I just wanted to check if there was a simpler way because the other exercises from this unit were relatively straightforward and this one took me some time, so maybe I was overlooking a simpler solution.
Comment: The only touch up I'd add is to extend the sentence "Let $j=i+1$...for some $i \in \mathbb{Z}$", *such that* $(ab)^i = a^ib^i$, ..., and $(ab)^k = a^kb^k$. At that point, you can move on to "Given $(ab)^k = a^kb^k, then...[rest of your proof]. You want to state the premise of the problem in full. As your proof now stands, you simply assume there are three consecutive integers. And then you proceed to argue: Then [it follows that] (ab)^i = a^ib^i....and....and...But that doesn't "follow" from the existence of three consecutive integers, alone. Are you following me?
Comment: Yes, I was just naming the three integers that follow from the _premises_ of the exercise.
Comment: Perhaps I'm just nit-picking...I tend to like a clear explication of the premises, and a clean distinction between those premises and the arguments which the follow from those premises. Ah...just caught your comment: I usually prefer, personally, make my proof self-contained (not dependent on information embedded in the exercise's statement).
Comment: Don't get me wrong: your approach to this proof is "spot-on!"...The integer portion of your premise is great...but were it not for having the exercise to look back to, I wouldn't have known, given three consecutive integers, why I should accept that $(ab)^k = a^kb^k$  (So what I would have liked to see in your proof was an expanded "Let..." statement, keeping what you already have, but adding something to the effect "...such that [given those three consecutive integers we're naming i, j, k], it is also true that $(ab)^n = a^nb^n$ for $n = i, j, k$
Answer: A very similar solution, but maybe slightly shorter: again let $i$, $i+1$ and $i+2$ be the three consecutive integers that work for $a$ and $b$.  From $a^{i+1} b^{i+1}  = (ab)^{i+1} = (ab)(ab)^i = aba^i b^i$ we get $a^i b = b a^i$.  The same proof with $i$ replaced by $i+1$ gives
$a^{i+1} b = b a^{i+1}$. Now $a b = a b a^i a^{-i} = a a^i b a^{-i} = a^{i+1} b a^{-i} = b a^{i+1} a^{-i} = b a$.
Comment: How do you find a way or intuition for such approaches :)
Answer: I was writing this as a comment, but it's going to be extensive; I suspect most of the commenters might be interested, so here goes as a community wiki.
A group $G$ is said to be $n$-abelian if $(ab)^n = a^nb^n$ for every $a,b\in G$.
Alperin proved (The classification of $n$-abelian groups, Canad. J. Math. 21 (1969) 1238-1244, MR0248204 (40 #1458)) that the variety of $n$-abelian groups is the join of the variety of abelian groups, the variety of groups of exponent $n$, and the variety of groups of exponent dividing $n-1$ (so a group is $n$-abelian if and only if it is a quotient of a subgroup of a direct product of groups that are either abelian, of exponent $n$, or of exponent dividing $n-1$).
More recently,  Primož Moravec (Schur multipliers and power endomorphisms of groups. J. Algebra 308 (2007), no. 1, 12–25. MR2290906 (2007j:20047)) proved that a finite $p$-group is $n$-abelian if and only if $n\in p^{e+r}\mathbb{Z}\cup(1+p^{e+r})\mathbb{Z}$, where $p^e$ is the exponent of $G/Z(G)$ and $r$ is an integer that can be computed, called the "exponential rank of $G$".
A closely related class of groups are the $n$-Bell and the $n$-Levi groups. A group is $n$-Bell if and only if $[x^n,y]=[x,y^n]$ for all $x,y\in G$, where $[a,b]$ is the commutator of $a$ and $b$. A group is $n$-Levi if $[x^n,y] = [x,y]^n$ for all $x,y\in G$. (Note that since $[a,b]=[b,a]^{-1}$, $n$-Levi implies $n$-Bell). A result I noted in passing some years ago was that if a group is $i$-, $i+1$-, and $i+2$-Levi for some integer $i$, then it is $n$-Levi for all $n$ (and hence nilpotent of class at most $2$), very similar to the problem at hand here. Also, $2$-Levi and $(-1)$-Levi imply $n$-Levi for all $n$, just like $(-1)$-abelian and $2$-abelian imply abelian (i.e., $n$-abelian for all $n$).
A nice paper on this subject is L-C Kappe's On $n$-Levi groups.
Arch. Math. (Basel) 47 (1986), no. 3, 198–210, MR 0861866 (88a:20048). For a group $G$, let
$$\begin{align*}
\mathcal{E}(G) &= \{n\mid (xy)^n = x^ny^n\text{ for all }x,y\in G\}\\
\mathcal{L}(G) &= \{n\mid [x^n,y]=[x,y]^n\text{ for all }x,y\in G\}\\
\mathcal{B}(G) &= \{n\mid [x^n,y] = [x,y^n]\text{ for all }x,y\in G\},
\end{align*}$$
called, respectively, the "exponent semigroup", the "Levi semigroup", and the "Bell semigroup" of $G$ (the sets are closed under multiplication, so they are multiplicative semigroups of the integers). Kappe proves that if $W$ is a set of integers, then the following are equivalent:

$W=\mathcal{E}(G)$ for some group $G$.
$W=\mathcal{B}(H)$ for some group $H$.
$W=\mathcal{L}(K)$ for some group $K$.

She also gives conditions for a set of integers to be an exponent semigroup, reminding readers that F.W. Levi proved, in Notes on Group Theory VII. The idempotent residue classes and the mappings $\{m\}$. J. Indian Math. Soc. (N.S.) 9 (1945), 37-42, that if $M$ is the smallest positive integer in $\mathcal{E}(G)$ for which $G^M$ is abelian, then there exist pairwise relatively prime integers $q_i$, $M=q_1\cdots q_t$, $2\lt q_i$, such that $\mathcal{E}(G)$ consists precisely of the integers that are congruent to either $0$ or $1$ modulo $q_i$ for $i=1,\ldots,t$; and that if $q_1,\ldots,q_t$ are pairwise relatively prime integers, $2\lt q_i$ for each $i$, and $S$ is the set of all integers that are congruent to either $0$ or $1$ modulo $q_i$ for each $i$, then there exists a group $G$ such that $\mathcal{E}(G)=S$.
Comment: @ogerard: Multiplication; for example, if $n$ and $m$ are in the exponent semigroup, then so is $nm$, since $(xy)^{nm} = ((xy)^n)^m = (x^ny^n)^m = (x^n)^m(y^n)^m = x^{nm}y^{nm}$.
Comment: thanks a lot for these references. We speak of Exponent semigroup, Levi semigroup, etc.  What is the operation on these sets?
Answer: Preliminary comment: There is ambiguity in the statement of the problem, an ambiguity that I am told traces back to the original.  I interpret the problem to mean that there exist consecutive integers $i$ such that $(ab)^i=a^ib^i$ for all $a$ and $b$.  But the informal language of the problem permits the weaker interpretation that for every $a$ and $b$, there exist three consecutive integers $i$ such that $(ab)^i=a^ib^i$.
I will prove the result under the stronger "uniform $i$" condition.  The arguments of the OP and of Robert Israel, proved under weaker assumptions, are therefore clearly "better."  The reason for the argument below is that my parsing of the wording interprets the condition as uniform.  And the stronger assumption permits a more structured, symmetric approach.
Let our exponents be $n$, $n+1$, and $n+2$.
Note that by associativity,
$$(ab)^{n+1}=a(ba)^nb.$$
Thus
$$a^{n+1}b^{n+1}=(ab)^{n+1}=a(ba)^{n}b=ab^{n}a^{n}b.$$
Cancellation now gives
$$a^nb^n=b^na^n$$
from which we conclude that
$$(ab)^n=(ba)^n.$$
A similar calculation with $n+1$ and $n+2$ yields
$$(ab)^{n+1}=(ba)^{n+1}$$
and now division gives the desired result.
Comment: Careful: the way I read the problem, it's not clear that the $n$ for which $a^n b^n = (ab)^n$ are the same ones for which $b^n a^n = (ba)^n$.  (I'm disappointed with Herstein for being sloppy with quantifiers here: my interpretation is "for all $a, b \in G$ there are three consecutive integers $i$ ...", not "there are three consecutive integers $i$ such that for all $a, b \in G$ ...").
Comment: In fact, the exercise may be restated as saying "Let $a$ and $b$ be fixed. If there exist three consecutive integers $i$ such that $(ab)^i = a^ib^i$, then $a$ and $b$ commute." Since a group is abelian if and only if every $2$-generated subgroup is abelian, the full problem follows from this.
Comment: @Robert Israel: I do not have the book, so need to go by the OP.  It would be a *very* unusual reading of the words to interpret them as meaning "for all $a$ and $b$, there exist consecutive integers".  I think of my answer as being proved under the hypotheses of the problem, and of yours and the OP's as being proved under weaker hypotheses.
Comment: The OP wrote the problem exactly as it appears in Herstein.  If Herstein wanted your interpretation, I think it would have been more natural to write "$(ab)^i = a^i b^i$ for all $a,b \in G$, for three consecutive integers $i$".
Answer: Hint $\ \ \ (ab)^n = b^{-1}(ba)^{n+1}a^{-1}$
$\quad\Rightarrow\ \ \  a^nb^n = b^{-1}(b^{n+1}a^{n+1})\,a^{-1} =\ b^n a^n $
Answer: Let $i$ be any integer.
By assumption, we can write
$$(ab)^i = a^i b^i \tag 1$$
$$(ab)^{i+1} = a^{i+1} b^{i+1} \tag 2$$
$$(ab)^{i+2} = a^{i+2} b^{i+2} \tag 3$$
From $(1)$ and $(2)$, we can write
$$(ab)^i ab = a^{i+1} b^{i+1}$$
$$a^i b^i ab = a^{i+1} b^{i+1}$$
Using cancellation property, we are left with
$$b^i a = a b^i \tag 4$$
Similarly from $(2)$ and $(3)$, we are left with
$$a b^{i+1} = b^{i+1} a \tag 5$$
From $(4)$ and $(5)$
$$ab = ba$$
which is what is required
Note that the minimum number of consecutive number to hold this property is $3$.
This need not be true in the case of $2$ consecutive powers.
Answer: I am reading "Topics in Algebra 2nd Edition" by I. N. Herstein.
This problem is Problem 4 on p.35.
I solved this problem as follows:
$(ab)^i=a^ib^i$.
$(ab)^{i+1}=a^{i+1}b^{i+1}$.
$(ab)^{i+2}=a^{i+2}b^{i+2}$.
$(ba)^i=a^{-1}(ab)^{i+1}b^{-1}=a^{-1}(a^{i+1}b^{i+1})b^{-1}=a^ib^i$.
So, $(ab)^i=(ba)^i$.
$(ba)^{i+1}=a^{-1}(ab)^{i+2}b^{-1}=a^{-1}(a^{i+2}b^{i+2})b^{-1}=a^{i+1}b^{i+1}$.
So, $(ab)^{i+1}=(ba)^{i+1}$.
Let $c:=(ab)^i=(ba)^i$.
$(ab)c=(ab)(ab)^i=(ab)^{i+1}=(ba)^{i+1}=(ba)(ba)^i=(ba)c$.
So, $ab=ba$ by cancellation law.


Why is there no equivalent in C# to Ada generic parameters?

Question: Please note that I am not talking about Generic Type parameters.
For example in Ada I can write a package that needs to be initialized using a value instead of a type. e.g.
generic
  Size : Positive;
package Sudokus is

   subtype Values is Positive range 1..Size*Size;
   type Choice is private;
   type Sudoku is private;

   procedure Fill(S : out Sudoku);
   procedure Init(S : out Sudoku);
   procedure Solve(S : in out Sudoku);
   procedure Print(S : Sudoku);

   Unsolvable_Grid_Error : exception;

And this is how to use it :
package My_Sudoku is new Sudokus(3); -- 3 for 9x9 solver, 4 for 16x16 solver, etc.

I guess there is no equivalent but I find it quite useful.
Is there a reason for this absence ?
Comment: Isn't that something you can generally pass on a constructor instead?
Comment: Could you provide an example that could not easily be solved by a constructor call?
Comment: @Jim: one example would be tagged enumerable types, e.g. SI units, giving you the ability to use strongly-typed, unit-tagged numbers (e.g. `weight w = 1 kg`) with automatic support for conversion, since all SI unit types can be expressed as a single six-dimensional vector where each dimension stands for the exponent of one base unit.
Comment: A Vector struct. But that one is probably better off with one time for each dimension from 2 to 4.
Answer: The general answer to "why does C# not have feature X" revolves around the benefits of such a feature versus the costs. Benefits are usually obvious, but costs include:

Increased complexity of language specification
Increased complexity of code using the language to the full
Increased educational requirement - developers have to know more in order to understand their colleagues' code
Cost of designing the feature
Cost of implementing the feature
Cost of testing the feature
Increased difficulty in adding more features later - because often features will interact with each other, often in awkward ways

Basically, it shouldn't be a case of asking why a particular feature isn't present: it should be a matter of arguing that the benefits of the feature are enormous compared with the costs. Features have to earn their place in the language, and the language designers have set the bar pretty high. (As Anders has put it in the past, every feature starts out with a score of -100, and has to work its way up.)
Answer: Why don't you simply pass the size to the constructor and initialize the array with it?
class Sudokus
{
  char[] field;
  public Sudokus (int size){ field = new char[size*size]; }
}

The only advantage I could see with a "generic parameter" is if you had a fixed size array, which could allow for faster access, but that isn't supported in C# anyway (at least not as non-local variable).
I know this kind of templating is supported in C++, which templating is far superior to templating in C# or Java.
Comment: C# generics aren't templating to start with, and shouldn't be regarded that way. Superiority depends on context - in some situations C++ templates are more useful, and they're *usually* more powerful; in other situations C# generics are just as useful and simpler to understand. In some cases C# generics provide abilities which as far as I'm aware aren't available with C++ templates - such as creating the generic type when the type argument is only known at execution time. The ability for generics to be provided in solely binary form is also potentially handy.
Comment: @Jon: you are correct. Although it's entirely possible to *instantiate* template types in C++ – roughly equivalent to the `new` constraint in C# – this is still resolved at compile-time and there truly is no equivalent to `Activator.CreateInstance` which C#'s `new T()` resolves to.
Comment: @Konrad: I was more meaning the equivalent of using reflection to create a `List` where `T` is only known at execution time, for example. (Using `Type.MakeGenericType`.)
Comment: @Jon: oh. Ah well, the same applies. ;-) All due to C++' lack of reflection.
Comment: in this specific Ada case, it allows me to define a custom type at compile time ... but there is also no equivalent to that in C#, maybe for the reason Jon exposed.