Probability of a 75% freethrow shooter making at least 5 shots in a row out of 10.

Question: What is the probability that a 75% free throw shooter, given the assumptions listed below, can make at least $5$ in a row of $10$ shots?  So in effect he must make $5$, $6$, $7$, $8$, $9$, or all $10$ in a row.  He only gets $10$ shots total.
The main difference of this question vs. others I've seen on this site is that mine asks for "in a row" which changes the math needed to solve it.  I can solve this using placeholders using a divide and conquer method but I was told a recurrence relation can be used so I would like to see that solution method please.
Some assumptions:
A) The 75% free throw (f.t.) percentage remains constant during the 10 shots.  So things like fatigue, distractions... are not of any concern for this question. The shooter is a professional and the 75% is his average over a long period of time as a professional so it can be considered a very accurate prediction of his future f.t. performance.
B) The shooter makes an honest attempt to make as many shots as he can (in other words, he doesn't intentionally miss any shots).
C) When I say at least $5$ in a row, I am talking about the longest streak only of the made shots so for example, using $M$ for make and $x$ for miss, this is NOT considered $5$ in a row $MMMxxxMMxx$ because the longest streak of makes is only $3$ in a row. However, $xxMMMMMxxx$ is $5$ in a row.  Note that $MMMMxMMMMx$, even though it is $8$ out of $10$ made shots, is only considered $4$ in a row for this question (kinda like in bowling, $2$ strikes in a row, then an open frame, then a single strike is not considered a "turkey" ($3$ strikes in a row)).
D) Note that when I ask for the "longest" streak of makes, it could actually be the only streak (such as all $10$ in a row) or it could be the longer streak (if there are only $2$ streaks of makes) so I wanted to clarify that.  Also cases such as $MMxMMxMMxx$ has no longest make streak (they are all of length $2$), but 2 is considered the "longest" in this case.
A bonus question related to this main question is which is the shooter more likely to get, $8$ in a row or all $10$ in a row?
Thank you.
Comment: My solution here http://math.stackexchange.com/questions/59738/probability-for-the-length-of-the-longest-run-in-n-bernoulli-trials/59749#59749 uses generating functions, not recurrences but it will give you the answer. For $n=10$, $p=3/4$, and $m=5$ we get the chance $2187/4096$ or about $.534$.
Comment: I noticed that $2187/4096$ is simply $3 * (3/4)^6$.  I wonder if this is a coincidence or if it has some significance to the solution to this problem.
Answer: We can get an explicit expression by considering the cases where the consecutive successful free throws occur between two immediately flanking failures, or they do not (as in the case where the shooter begins or ends the streak at the beginning or end of the 10 trials).
In the first case, we see that we must calculate the sum $$\sum_{m=0}^3 (4-m) p^{5+m} (1-p)^2 = p^5(4-5p+p^5).$$  In the second case, we must calculate $$p^{10} + \sum_{m=0}^4 2p^{5+m}(1-p) = p^5 (2-p^5).$$  Thus our desired probability for a general $p \in [0,1]$ is given by $$p^5(4-5p+p^5)+p^5(2-p^5) = p^5(6-5p),$$ which for $p = 0.75$ is $2187/4096$.

In case one is interested, the following Mathematica code calculates the above polynomial via direct enumeration:
Total[Times @@ # & /@ Cases[Tuples[{p, 1-p}, 10],{___,p,p,p,p,p,___}]] // Simplify

And the subsequent command
% /. p -> 3/4

gives the probability for $p = 0.75$.  Note that the speed of this command scales poorly with the number of trials, since for each additional trial there is a doubling of the length of the list generated by Tuples[].  However, generalizing the above sums is easy.
Comment: Answers like this is why I changed from a math major to a computer major.  Solving this question on a computer is a "simple" simulation, just counting up the number of "good" events.  I wouldn't even have to know anything about probability.  I would just nest some loops, generating a string of length 10, and look for certain substrings of certain length and then just count 'em up.  Since today's computers are fairly fast, the simulation should only take a few seconds time to run I would think.  This math formula is rather "involved" for what seems to be a fairly "simple" question semantically.
Comment: @David It's ironic that you say that, since the way I evaluated the double sum, and checked it for accuracy, was with a computer.  The sum itself is not that hard to understand from a mathematical perspective, nor is it difficult to grasp the intuition behind it.  For instance, in the first case, regard a run of $5+m$ successes and the $2$ failures (one preceding, one following) as fixed, leaving $10-(5+m)-2 = 3-m$ random outcomes, which are binomially distributed.
Comment: I was just saying that a simple computer simulation using a string of length 10 is a simple way to solve this problem for someone that doesn't know much (or anything) about probability.  I would think that many college students would not get this correct unless maybe they were advanced math majors. Of course a computer simulation using simple loops to simulate all the outcomes is only practical if the number of outcomes is reasonable and 10 shots has a reasonable # of outcomes.  If I had instead said at least 50 out of 100, then a simple simulation described previously might not be practical.
Comment: My simple computer simulation would be 10 nested loops, each running from 0 to 3.   0 = miss and 1 thru 3 are makes.  This is an easy way for me to simulate the 75% f.t. make probability per shot. Then simply count up the maximum length run of non zeros in a row which represents the make streak.  If it is 5 or more then count that as a "good" event.  When all done counting, divide by 1,048,576 (the number of events and the number of total innermost loop iterations) and you should get the correct answer which is 559,872 out of 1,048,576 which is about 53.39%.
Comment: In statistics often this kind of simulation is used but how do you know how accurate your solution is? (yes, you can also calculate standard errors). In general one tries to get exact solutions and if it becomes too difficult then one resorts to simulations.
Comment: To me, solving a specific problem by using a computer simulation of it is reassuring and gives me a basis for crosschecking with some other method.  One can question any single method of computation so it helps to be able to crosscheck using 2 or more solutions to see if the answers match. My claim is that the computer simulation is rather simple and that checks can be put in place to help verify the correctness of the output.  In my simulation, the first "winner" of at least 5 makes in a row would be the string 0000011111 since 0 is a miss and 1..3 are all makes. The last would be 3333333333.
Comment: That derived formula of $p5(6−5p)$ is impressive because it seems to work for this problem and is very concise, especially when compared to the amount of work I had to do manually on a piece of paper.  Kudos to the person that came up with this formula.  I accepted the answer.  One interesting thing though is the answer comes as 2187/4096 but there are only really 1024 possible events since the shooter can either make or not make each of the 10 shots, however, if the denominator was 1024 which is 2^10, then the answer would have to be 546.75/1024 which is not an integer number of good events.
Comment: Continuation of previous comment... I guess that has something to do with 75% freethrow percentage whereas if it was 50% instead, perhaps the correct number would be an integer numerator over 1024 since then each shot is basically a coinflip equivalent and you would then be counting the equivalent of 5 or more heads in a row for example.
Comment: @David Loosely speaking, yes.  Even though there are only $1024$ elementary outcomes, they do not occur with equal probability when $p \ne 0.5$.  And since the probability of the desired event must take into account the individual probabilities of seeing each possible outcome, the result will not, in general, be an integer divided by $1024$.
Comment: I figured the non 50% freethrow percentage was the culprit for not having a 1024 denominator. In my calculations I made it so that the 75% freethrow percentage was simulated by having 3 make balls and 1 miss ball for each shot, thus giving 4 "virtual" outcomes for each actual shot (3 are always makes and 1 is always a miss). This then allows me to simply run a computer simulation and just count up the number of good outcomes. In this case 559,872/1,048,576 which simplifies to 2187/4096 which is the correct answer. I didn't actually run the computer simulation but I suspect it would work fine.
Comment: I did the calculations on paper and derived the same formula but there are a lot of intermediate results not show in the summation above. When done out on paper, the p^7, p^8, p^9, and p^10 terms cancel out and we are only left with p^5 and p^6 terms. Another way of expressing the answer is 6(p^5)-5(p^6) which is what I got on paper. It seems hard for the reader to see how the final expression is derived just from those 2 summations.  If I knew how to do the fancy formatting I would illustrate it here but I am a rookie so I don't.  Just break it into cases (5,6,7...) and it is easier to solve.
Answer: The probability of the shooter getting at least five in a row is the sum of the probabilities of getting 5, 6, 7, 8, 9, or 10 in a row. These probabilities assume that any shot that is not part of the make sequence is missed.  This is not what the original author asked so please be aware of that.
\begin{align*}
p_5 &= 6* (0.75)^5 * (0.25)^5 \\
p_6 &= 5* (0.75)^6 * (0.25)^4\\
p_7 &= 4* (0.75)^7 * (0.25)^3\\
p_8 &= 3* (0.75)^8 * (0.25)^2\\
p_9 &= 2* (0.75)^9 * 0.25\\
p_{10} &= (0.75)^{10}
\end{align*}
$P= p_5+p_6+p_7+p_8+p_9+p_{10} = 0.126$ or 12.6%.
Bonus: $p_8= 3*0.75^8 * 0.25^2= 0.018$ and
$p_{10}= 0.75^{10} = 0.056$.
So the probability of shooting 10 straight is higher
Comment: This assumes he misses any shot that is not part of the streak.
Comment: This seems correct but the author asks for a recursive proof (I think he implies that he already has found your ''divide and conquer method'').
Comment: These calculations are wrong.  Look at P(8) for example. To get 8 in a row, the shooter can actually sink 9 shots so the formula you use is wrong because you are assuming he will make exactly 8 and miss exactly 2 but that is not required.  For example, he can make the first 8 shots, miss the 9th shot, and make the 10th shot. There he made 9 shots total out of 10 but the longest streak of makes is 8 in a row. Also you have P(8) = 0.018 and P(10) = 0.056 so how could P(5) + (P6) + P(7) + P(8) + P(9) + P(10) = 0.07 if P(8) + P(10) is already 0.74? Your P(10) is right but the others seem wrong.
Comment: Yes this seems like you are calculating the probability of getting a streak of 5, 6... but missing all of the other shots.  That is not what the original question asked for. Note that even for 5 in a row, the shooter can sink (make) 9 shots out of the 10.  For example, make the first 5, miss the 6th, make the last 4. Another variation is miss the first 2 shots, make the next 5, miss the 8th shot, make the 9th, miss the 10th.  You solved a much simpler question but not the one I asked.
Answer: $P(5)=$Prob(hits 5 but misses the previous and following shots)
$=0.75^5*0.25+4*0.25*0.75^5*0.25+0.25*0.75^5\\=(\frac34)^5(\frac14+\frac4{16}+\frac14)=729/4096$
$P(6)=(\frac34)^6(\frac14+\frac3{16}+\frac14)$
and so on.
Answer: Let $p$ be the probability of scoring and let $P_{m,n}$ be the probability of making at least $m$ in a row from $n$ shots. Conditioning on the first throw,
$$
P_{m,n} = (1-p)P_{m,n-1} + p[(1-p)P_{m,n-2}+p(1-p)P_{m,n-3}+\ldots+p^{m-2}(1-p)P_{m,n-m}+p^{m-1}]
$$
with initial conditions
$$
P_{m,m} = p^m \qquad P_{m,m+1} = p^m +(1-p)p^{m}
$$
Hence when $p=0.75$, $m=5$, and $n=10$,
$$
P_{5,5} \approx 23.7\% \qquad
P_{5,6} \approx 29.7\% \qquad
P_{5,7} \approx 35.6\% \qquad
P_{5,8} \approx 41.5\% \qquad
P_{5,9} \approx 47.5\% \qquad
P_{5,10} \approx 53.4\%
$$
For bonus:
$$
P_{10,10} \approx 5.6\% \\
P_{8,8} \approx 10.0\% \qquad P_{8,9} \approx 12.5\% \qquad P_{8,10} \approx 15.0\%
$$
Answer: I also got the equivalent of 2187 / 4096 which is about 53.4% using a "brute force" placeholder divide and conquer method on paper.  I actually got 559,872 / 1,048,576 which simplifies to 2187 / 4096.  This problem (because of its small number of shots), can also be solved by using a computer simulation rather easily and quickly to help verify the correct answer.
For the bonus question, if my math is correct, getting 8 in a row is exactly as likely as getting all 10 in a row!  Someone might think getting all 10 in a row is harder than just getting 8 in a row but to me they seem exactly as likely.  I used a rather unusual math method to solve this in which I assume that since the f.t. % is 75%, that is kinda like having 4 basketballs, 3 orange ones and 1 multicolor (red, white and blue).  It can be assumed that he will always make the orange basketball shot and always miss the multicolored shot and that he is handed random basketballs.  By making this assertion, it is simpler for me to solve cuz I then don't have to work with fractions such as (3/4) and powers of them.
So using my "simplified" math, there are 4 possible outcomes for each shot... namely, he makes any of the 3 possible "orange shots" or he misses the "multicolored shot" so for 10 shots, the total number of possible outcomes is 4^10 = 1,048,576 although any of the 3 orange shots made can be interpreted as identical but they still count separately as part of the 1,048,576 possible total outcomes.
Now using this method, let's analyze what happens when we look for 10 makes in a row using placeholders and the following symbol placeholder definitions:

= make = 3 chances (out of 4 possible outcomes).

X = miss = 1 chance  (out of 4 possible outcomes).
_ = any outcome = don't really care = 4 chances (out of 4 possible outcomes).
P(10) = ********** but since there are 3 orange balls, we get (3^10) / 1,048,576 = 59,049 which is about 5.63% of 1,048,576.
P(8) I broke down into 3 subcases namely:
********X- which is make the first 8, miss the 9th, and dont care about 10th (it can either be a make or a miss but it doesn't change the fact that this is 8 in a row).
The math for this is (3^8) * 1 * 4 = 26,244
Case 2 is X********X which is miss the first and last only.
The math for this is 1 * (3^8) * 1 = 6,561.
Case 3 is -X******** which is the reversal of case 1.
The math for this is 4 * 1 * (3^8) = 26,244
26,244 + 6,561 + 26,244 = 59,049.  This is EXACTLY the same number of good outcomes as P(10) which is 3^10 so they are equally likely!
It just so happens that (3^10) = ((3^8) * 4) + 3^8 + ((3^8) * 4) because what you get on the right side of the equal sign is (3^8) * 9 but 9 is 2 additional powers of 3 so that is the same as 3^10.
It seems a little strange to me that getting 10 in a row and 8 in a row is equally likely but it kinda makes sense cuz he is much more likely to make a shot than to miss it but there is only one way to make all 10 but there are several ways to make 8 in a row so it "balances" out.  I must say it is a coincidence they are exactly equal.
Note this original question is not trivial at all such as probability of making any 5 shots of the 10.  By adding the "in a row" clause, it makes the math much more involved.
Also note that P(5), P(6), P(7), and P(9) can be computed using this same method and easily on a single sheet of paper (drawing out the placeholders helped me a lot in solving it).  Of course P(x) here means exactly x shots in a row made.
P(5) has 6 different subcases:
*****X----
X*****X---
-X*****X--
--X*****X-
---X*****X
----X*****
Remember a "-" is a placeholder meaning "don't care" so it can either be a make (*) or a miss (X).  Note that P(5) is about 17.8% and P(5) means 5 in a row (maximum make streak length).
Comment: I was wondering if someone could comment on my solution.  I tried to make it simple by breaking it into smaller subproblems (such as solve for P(5), P(6)...).  It is interesting to see that P(5) is the most likely and P(9) is the least likely. P(8) and P(10) are equally as likely which is also interesting.  One might think that making all 10 shots in a row is the "hardest" but in reality it is not.  Making 9 in a row is the hardest cuz there are only 2 ways to do it (miss the first or miss the last) and make all the others.  The chances of that happening are 2/3rds that of making all 10. Cool.
Comment: It looks okay but it's ad hoc (what would you do if instead of 10 shots and 5 in a row, you had 12 shots and 6 in a row?!). See my solution if you want to use a recursive formula like your teacher suggested that generalizes.
Comment: For the 12 shot 6 in a row variation, I would just recompute using my same simplistic method.  As long as the numbers are reasonably manageable, the "ad hoc" approach works.  If the problem was out of 100 shots, what are the chances of getting at least 50 in a row, my method would not be practical.  Sometimes a specific solution is all one needs but I agree a generic solution is more robust/flexible.
Comment: Yes, with small numbers you can just use your method but even with smaller numbers it is easy to miss a case.
Comment: Also, my "quadrupling" of the # of outcomes per shots works in this case because the f.t. % is 75% which can be simulated by changing one 75% outcome each shot to 4 outcomes, 3 that are makes and 1 that is a miss.  If it had been some "oddball" % like 74.5% I could not use that simplification to help remove fractions, however the other formulas here could be used with any probability so my technique is very restrictive that way.


Large Family of Subsets with small overlap

Question: Find upper and lower bounds on the cardinality of the largest family of subsets of an $n $ element set, $\mathcal{S}\subset \mathcal{P}(\{1,\dots ,n\})$ , if no pair of elements contain a third element that is
$A\not\subset B\cup C $ for any $A,B,C\in \mathcal{S}$.
Does anyone have any idea how to get nontrivial bounds for example if we take $\mathcal{S}=\{\{1\},\{2\},\dots \{n\}\}$ we get the lower bound of $n$ and you can easily get an upper bound of $2^{n-1}-1$. I know through so constructions  that one can get $c*n$ (for some $c>1$)but I want to know can one do fundamentally better than this for both the upper and lower bounds.
Comment: Presumably you want $A, B, C$ to be **distinct** elements of $\mathcal S$, otherwise $A=B$ is a counterexample whenever $C$ is not a subset of $B$.
Comment: Yes that is right
Comment: How do you get $c n$ for $c > 1$?  I can prove that the best lower bound is $n$ for $n \le 5$.
Comment: ... and now for $n \le 6$.
Comment: It was through construction a construction (on a ten point set) where I just choose sets in such a way that I got 11 sets... I thought that the idea could be generalized to higher $n$ but my office mate has since erased it off our chalkboard and I don't really remember what sets I picked. Also I could have just made a mistake about it.
Answer: Let $\mathcal T$ be the set of all unions of two distinct elements of $\mathcal S$.
Each $T \in \mathcal T$ contains exactly two distinct members of $\mathcal S$, and in particular $\mathcal T$ is an antichain.  By Sperner's theorem, the largest possible antichain in $\mathcal P(\{1,\ldots,n\})$ has cardinality ${n \choose \lfloor n/2 \rfloor}$, while $|\mathcal T| = |\mathcal S| (|\mathcal S|-1)/2$,
so
$$|\mathcal S| \le \dfrac{1 + \sqrt{1 + 8 {n \choose \lfloor n/2 \rfloor}}}{2} \sim \text{const} \dfrac{2^{n/2}}{n^{1/4}} $$
Comment: Thanks that is a real slick proof I hand no idea of the existence of Sperner's theorem.


Material UI Input aligned to Select

Question: I´m having some issues with how my elements are aligned on Material UI.
This is the code of my Input and Select elements:

    <form>
       <TextField
         label="Search"
       />
       <FormControl>
          <InputLabel htmlFor="age-simple">Age</InputLabel>
              <Select
                 value=""
                 onChange=""
                 inputProps={{
               >
                 <MenuItem value="">
                     None
                     </MenuItem>
                     <MenuItem value={10}>Ten</MenuItem>
                     <MenuItem value={20}>Twenty</MenuItem>
                     <MenuItem value={30}>Thirty</MenuItem>
               </Select>
        </FormControl>
     </form>

And this is the output that I get:
Answer: You can use flexbox to align multiple form fields. You just need to add display: flex to the parent element. In the following example I used inline styles, but you could use any of the supported style solutions.
There is also an error in your code: inputProps={{ is missing the closing brackets: }}

const { React, ReactDOM } = window
const { InputLabel, FormControl, TextField, MenuItem, Select } = window['material-ui']

const Form = () => (
  <form style={{ display: 'flex' }}>
    <TextField label="search" />
    <FormControl>
      <InputLabel htmlFor="age-simple">Age</InputLabel>
      <Select value="">
        <MenuItem value="">
          None
        </MenuItem>
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </Select>
    </FormControl>
  </form>
)

ReactDOM.render(<Form />, document.querySelector('#root'))

Comment: This is ok, but then the form is no longer responsive.

Material UI Input aligned to Select


What does $d\mathbb{P}(\omega)$ in integral mean?

Question: What does $d\mathbb{P}(\omega)$ under integral sign mean?
Like $$\int_B Xd\mathbb{\mathbb{P}}(\omega)$$
Can somebody explain? How can we integrate $X$ with respect to  $\mathbb{P}(\omega)$ where $\mathbb{P}$ is some prob. measure?
Comment: http://en.wikipedia.org/wiki/Lebesgue_integration

$X$ is an r.v. and as a function it is a measurable function with respect to the Probability measure.
Comment: This has been asked before. See the answers [here] (http://math.stackexchange.com/questions/916776/what-does-mathbbpd-omega-dw-actually-mean)
Comment: See also this post: http://math.stackexchange.com/questions/5230/notation-question-integrating-against-a-measure
Comment: **How can we integrate X with respect to ℙ(ω) where ℙ is some prob. measure?**  Perhaps first you should find out how we can integrate a function $f$ with respect to a measure $\mu$, that is $\int f\;d\mu$.  Then simply replace $f$ and $\mu$ by $X$ and $\mathbb P$.
Answer: The formula in your post is ill-formed. One can use one of the equivalent $$\int_B X(\omega)d\mathbb{\mathbb{P}}(\omega),\qquad\int_B Xd\mathbb{\mathbb{P}}.$$ One also finds the alternative $$\int_B X(\omega)\mathbb{\mathbb{P}}(d\omega).$$
Comment: @Snufsan I'm inclined to agree, but if OP is confused by the presence of the $\omega$ rather than by integrating with respect to a measure, then Did's answer is appropriate.  I guess it depends on how you read the original question.
Comment: Isnt that better as a comment?
Comment: Wouldn't this be improved by including the definition and perhaps a link, e.g. to [Lebesgue integration](https://en.wikipedia.org/wiki/Lebesgue_integration)?
Comment: @Snufsan Is it?
Comment: @Did actually, it is
Answer: A probability measure can be looked at as a function $\mathbb{P}:\mathcal{A}\rightarrow\left[0,1\right]$
where $\mathcal{A}$ is a $\sigma$-algebra. The function has some
nice properties like $\mathbb{P}\left(\bigcup_{n=1}^{\infty}A_{n}\right)=\sum_{n=1}^{\infty}\mathbb{P}\left(A_{n}\right)$
when the $A_{n}$ are disjoint elements of $\mathcal{A}$. There is
a one to one correspondence beween elements of $\mathcal{A}$ and
their characteristic functions $1_{A}$ so equally well we could look
at $\mathbb{P}$ as a function on characteristic functions. This opens
the door to expanding the domain of $\mathbb{P}$. We can make it a function on
so-called $\mathcal{A}$-measurable functions, that takes values in
$\mathbb{R}$. Again it has nice properties. If $X$ is such
a measurable function then $\mathbb{P}\left(X\right)$ could be practicized as a notation of its value under $\mathbb{P}$. However, the notation $\mathbb{P}\left(X\right)$
is (mostly) not practicized, and $\mathbb P$ is not looked at as a function on functions (why not?). Instead one uses notations like $\int Xd\mathbb{P}$
, $\int X\left(\omega\right)d\mathbb{P}\left(\omega\right)$ or $\int X\left(\omega\right)\mathbb{P}\left(d\omega\right)$, and speaks of integrals. Here $\int_{B}Xd\mathbb{P}$ is
a notation for $\int X.1_{B}d\mathbb{P}$.


array length using pointers

Question: Array length can be calculated using *(&arr+1)-arr which then simplifies to (&arr)[1]-arr which further simplifies to 1[&arr]-arr.
But when the length is calculated in a function different from where memory allocation has been done, wrong results are computed.
For instance,
#include <iostream>
#define ARRAY_SIZE(arr) (1[&arr]-arr)
using namespace std;

void func(int *arr)
{
    cout<<ARRAY_SIZE(arr)<<endl;
}

int main()
{
    int arr[]={1,2,3,4,5};
    cout<<ARRAY_SIZE(arr)<<endl;
    func(arr);
}

This gives the output:
5
8

What accounts for such strange behaviour?
Comment: "further simplifies" ??!!
Comment: I am truly curious about where it is that people find this stupid way of computing array sizes when learning C++.
Comment: It's not strange if you understand how your `*(&arr+1)-arr` trick works.
Comment: Does "arrays are not pointers" help?
Comment: Is that output from the actual code you posted, or the output from some similar code using `char *` instead of `int *`?
Comment: possible duplicate of [c++ - length of array inside class function](http://stackoverflow.com/questions/16618221/c-length-of-array-inside-class-function) or http://stackoverflow.com/questions/1328223/sizeof-array-passed-as-parameter
Comment: @MatsPetersson it is the actual code.
Comment: Because most C++ tutorials are C in C++ with brief mention of classes later on tutorials.
Comment: @Neil Even in C you can do better than that :( http://stackoverflow.com/a/12784339/46642
Comment: @CharlesBailey x[y]=*(x+y)=*(y+x)=y[x]. If the comment was sarcastic, i said simplifies because 2 parentheses are saved in this conversion.
Comment: @R.MartinhoFernandes I wouldn't use this method for daily purposes. It was something new with an interesting mechanism.
Comment: @sudeepdino008: I am surprised that you consider `1[&a]-a` simpler that `(&a + 1) - a`. But the explanation appears to be that you consider "simpler" == "fewer parentheses".
Comment: Simpler means easier to understand. 1[&a] is very obscure syntax that will confuse many people.
Answer:
Array length can be calculated using *(&arr+1)-arr

Only if arr is actually an array. Within func, arr is a pointer, so this dereferences a random word of memory to give undefined behavoiur.
There is no way to tell the size of an array given just a pointer to its first element. You could pass the array by reference:
template <size_t N>
void func(int (&arr)[N]) {
    cout<<ARRAY_SIZE(arr)<<endl;
    cout<<N<<endl;               // equivalent, and less weird
}

Using the same technique, we can reimplement ARRAY_SIZE without resorting to the preprocessor or any bizarre pointer arithmetic:
template <size_t N>
size_t ARRAY_SIZE(int (&arr)[N]) {
    return N;
}

Comment: In C++11, I would make that second one use a template T for the type, and make it constexpr to boot. C++03 can get the same effect (a constant expression that only works on arrays), but requires some `sizeof` [trickery](http://ideone.com/VzUndj).
Comment: @DaveS In C++11 you would use `std::array` instead
Comment: Actually, if `arr` is a pointer, what you get from the expression `*(&arr+1)-arr` is not its size but undefined behavior. The OP got the result of 8 which may seem a plausible value for the size of `int*`, but actually it is a mere coincidence. If the code was compiled without optimization and run on a x86, this is a very likely result because the expression `*(&arr + 1)` must have picked the caller's saved EBP.
Comment: @AndreyChernyakhovskiy: You're right; I didn't think too hard about what that nonsense would do to a pointer.
Answer: In main() the compiler knows that arr is an array of size 5 * sizeof(int). In func() all the compiler knows is that arr is a pointer to a block of memory - it has no information about how big the array is, or even that it is an array (it could just be a chunk of memory allocated via malloc(), for example).
Answer: When you pass your array to a function, it decays to a pointer and knowledge of its size is lost. func can take an array of any size, so how the size be determined? You must either pass the size of the array as an extra parameter, or use a data structure such as std::vector or (C++11) std::array, which keep track of their size.

array length using pointers


Why casting from int, double, float and decimal to char works, but when those same variables are beforehand casted to IConvertible, doesn't?

Question: Consider this code:
class Program
{
    static void Main(string[] args)
    {
        int intVal = 1;
        double doubleVal = 1;
        float floatVal = 1;
        decimal decimalVal = 1;

        Console.WriteLine((char)intVal);
        Console.WriteLine((char)doubleVal);
        Console.WriteLine((char)floatVal);
        Console.WriteLine((char)decimalVal);
    }
}

That code works. The code that doesn't work:
class Program
{
    static void Main(string[] args)
    {
        IConvertible intVal = 1;
        IConvertible doubleVal = 1d;
        IConvertible floatVal = 1f;
        IConvertible decimalVal = 1m;

        // System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.Char'.'
        Console.WriteLine((char)intVal);
        Console.WriteLine((char)doubleVal);
        Console.WriteLine((char)floatVal);
        Console.WriteLine((char)decimalVal);
    }
}

Why?
Comment: In addition to the two fine answers below, remember that `char` is considered an integral type. Your successful casts are just casts between different numeric types (all of which are Value types, unlike the Reference type `IConvertible`)
Answer: A boxed value type can only be unboxed to its type. Same reason why this doesn't work:
object o = 1;
var d = (double)o;

Answer: IConvertible intVal = 1; boxes the value to an object. What you're doing is similar to this:
object intVal  = 1;
Console.WriteLine((char)intVal );

You can't cast an object (of type Int32, in this case) directly to char. Since intVal is IConvertible, you can use intVal.ToChar(CultureInfo.InvariantCulture); if that is acceptable.
Comment: Even though the question was plain "Why?" and the other answer offers a straight answer to it (although a good one), I have accepted this one because this one offers more insight about the alternative ways to accomplish the given task.


JSF resource (JavaScript) not rendered using addComponentResource

Question: I'm on Mojarra 2.2.13 and my project uses PrimeFaces 6.0.
I'm writing my own JSF UIComponent. It requires a bit of JavaScript located in webapp/resources/js/charts.min.js. When I annotate my component using @ResourceDependency the script is rendered:
@ResourceDependency(name = "js/charts.min.js", target = "head")

But, I don't always need it to be rendered. So I was trying to conditionally add a component resource to the view root from within the encodeBegin(FacesContext context) method:
if (condition) {
  UIOutput js = new UIOutput();
  js.setRendererType("javax.faces.resource.Script");
  js.getAttributes().put("name", "js/charts.min.js");
  context.getViewRoot().addComponentResource(context, js, "head");

  writer.startElement("div", null);
  writer.writeAttribute("class", "myChart", null);
  // ... write chart data
  writer.endElement("div");
}

This does not render the script (myChart is rendered though). No errors appear in my log. Any ideas what I could check or improve?
I've also tested without PrimeFaces (not sure if its head renderer was causing this), but the result is the same.
Comment: Did you try the  jstl tag instead of the java code settings?
Comment: @TheBitman no. How is that helpful when creating a UIComponent?
Comment: I thought maybe you could filter js LINK in the JSF file instead of the component. But tell the truth I don't understand your question totally :)
Answer: So, encodeBegin(FacesContext context) is not the correct location to add resources. You are too late there.
I've moved the code to the constructor of the component and now the script is added. I'm not 100% this is the best location to do so, but I've seen component libraries doing it in the constructor as well. It also works together with PrimeFaces.
See also:

How to programmatically add JS and CSS resources to <h:head>?


Why does my midi device have a long delay (cool-down period) between consecutive key presses?

Question: When pressing a key on my midi device and monitoring it in Midi-OX, it takes a long time (about 5 seconds) before it registers another input. Note that I'm nót talking about the delay between pressing a key and midi-OX registering it, but the delay between it registers another key after pressing one. A "cool-down period" so to speak before it recognizes another input.
I have used both Cubase and Midi-OX as software to monitor, and both have the same problem and "cool-down" period of around 5 seconds. I have tried both a PSR550 keyboard and a Yamaha Clavinova piano - again same result on both.
I use a Logilink UA0037N Adapter USB to Midi (In-Out, 1,9 m) to connect the keyboard/elec piano to my Medion Erazer laptop.
What could be the problem?
EDIT:
As suggested I bought another cable: M-Audio USB Uno MIDI Interface 1 in/out. About twice as expensive (€30) and the best I could get. There is still the same delay. This cable does seem to be more sensitive for touch-sensitivity and pedals etc., but as soon as I press a key it will not react to another press (or release) for ~4 seconds.
The plot thickens though - anything other than the black-white keys on the Clavinova/PSR work perfectly fine. The pedals, buttons and pith-bender all work real-time.
Even stranger still - after any input óther than a key, the "cooldown" will reset and it will react to another key-press or release, at which point it stops reacting to any more key presses again.
So I've used different devices (PSR/Clavinova) different cables, different software (Cubase and Midi-OX) and different computers (tested everything with an old laptop as well that had usb2 instead of usb3 ports). I also looked in the PSR manual to set it to "midi output mode", which is apparently a specific mode for the keyboard when using it as a midi device. All setups and combinations have the exact same problem.
EDIT2:
Turns out it WAS the cable. I just took my entire setup to a place that had dozens of different cables lying around, and eventually one worked normally. It seemed to be completely random which ones worked and which didn't though; some really cheap cables worked and some high-end brand ones didn't (though cheaper cables had the problem way more often). I really hate midi now.
Comment: There might be something useful here: https://sound.stackexchange.com/questions/27743/midi-input-3-second-delay-lag
Comment: Hello, welcome here! Just a quick question: how big the delay? As you tried two different keyboard (and it would be surprising that a clavinova has this issue) and two different programs, it seems the culprit would be the USB-MIDI interface. There are a lot of different of these guys and some of them are known to be buggy…
Comment: Keep in mind that MIDI is an utterly crippled standard designed with the kind of digital circuits in mind that were available in the late 70s. It should have been obsolete by the 90s, but somehow nobody ever cared to replace it with something better. _That_ is the problem, really. The hacks they devised back then to allow keyboards of the time to be as responsive as possible despite their very primitive hardware are bound to lead to all kinds of funny incompatibilities. Most software works around it by interpreting the different ways notes can be ended, _guessing_ what the intention was.
Comment: It's about 5 seconds before it registers another input. I just bought the Logilink UA0037N Adapter (€14). If this is not a common/fixable problem (google didn't help at least) you suggest I buy a better cable.
Comment: Ourf, yeah, that's a long delay! I would suggest at least try another one, preferably another brand. It is the only part of your setup that is common in all your tests…
Comment: That is a latency/delay issue. I don't have a latency or delay issue - I have a "cool-down period" issue. The problem described there addresses the latency between pressing a key, and the computer registering it. My problem is the delay between two successive key presses.
Comment: What happens if you try to use the MIDI to trigger a software instrument in Cubase or even an external sound generator without monitoring the MIDI - does it work as expected or are you also seeing the delay? Does either keyboard have a USB MIDI output?
Comment: Duplicate of https://music.stackexchange.com/questions/100298/properly-set-up-midi-to-usb
Comment: @ToddWilcox Same delay. Bought a better cable, same problem. This cable does seem to be more sensitive for touch-sensitivity and pedals etc., but as soon as I press a key it will not react to another press (or release) for ~4 seconds. The plot thickens - anything other than the black-white keys on the Clavinova/PSR work perfectly fine. The pedals,buttons and pith-bender all work real-time. Even stranger still - after any input óther than a key, the "cooldown" will reset and it will react to another key-press or release, at which point it stops reacting to any more key presses again.
Comment: Turns out it WAS the cable. I just took my entire setup to a place that had dozens of different cables lying around, and eventually one worked normally. It seemed to be completely random which ones worked and which didn't though; some really cheap cables worked and some high-end brand ones didn't (though cheaper cables had the problem way more often).
Answer: 5 seconds is beyond anything reasonable in normal operation.  So we have to search for something outside of normal operation.  What is common between your experiments?  Obviously your computer.  Then we have

I have tried both a PSR550 keyboard and a Yamaha Clavinova piano

which does not look like a commonality until we realise that a PSR550 is also from Yamaha.  That makes it likely that both devices share the same kind of Midi interface and basic implementation.
Another commonality obviously is your USB-Midi interface.  Looking for images of this device, it appears to be a branded copy of the standard cause for Midi problems, an adapter with a mixture of violin and bass clef on one side.
This adapter is known to garble Sysex messages and it is known to garble running status bytes which are used (among other things) for compressing note-off events into shorter Midi sequences by broadcasting them as note-on events with velocity 0.
This is the reason this garbage MIDI adapter tends to fall apart under polyphony when a keyboard utilises this sort of compression for sending notes in tight sequence.
My guess would be that either the keyboard or the adapter changes use or interpretation of running status bytes when a longer delay to the last byte has been interposed.  It may well be that 5 seconds after the last note, the next note from the Yamaha keyboards will be sent without using running status byte compression (even though it would still be applicable) in order to avoid missing notes when someone replugs Midi connectors (which presumably tends to take at least 5 seconds, or at least people will not expect it to work immediately in case they are faster).
Either that, or the adapter has a timeout period after it got confused where it reverts to a sensible behavior.
It would appear that the Yamaha keyboards make the cheap adapter fall apart more conspicuously with even simpler use than what commonly makes it drop out.  I would not blame the keyboard, really.
There are actually good brands for USB Midi adapters (like Roland, Yamaha, M-Audio) and lots of vintage USB1.1 adapters from those brands which are plenty fast enough at 12Mbps for most purposes (depending on the hub, you might want to avoid sharing a hub with a mouse or keyboard or other slow device).  Get one of those preowned and forget about the cheap ubuquitous standard Chinese junk with the fantasy clef on it.
Comment: Can you add some reference — say, a link to an article — to back up that the adapter is known to have problems?
Comment: @Aaron Even without citations, the off-brand MIDI adapter is by far the most likely source of the trouble, whether it's the hardware or the driver or both.
Comment: @ToddWilcox I'm not questioning the answer, just letting the author know it would be even stronger with a citation or two.
Comment: I'll try buying an expensive Yamaha-brand cable then. I do hope that's the problem, because I can't just keep buying cables until one happens to work (or we find out that wasn't problem).
Comment: New cable, same problem. This better cable does seem to be more sensitive for touch-sensitivity and pedals and stuff, but still as soon as I press a key it will not react to another key (or release) for ~4 seconds. The plot thickens though - anything other than the black-white keys on the Clavinova/PSR work perfectly fine. From the pedals to the buttons to the pith-bender. They all work real-time. Even stranger still - after any input óther than a key, the "cooldown" will reset and it will react to another key-press or release, at which point it stops reacting to any more key presses again.
Comment: Turns out it WAS the cable. I just took my entire setup to a place that had dozens of different cables lying around, and eventually one worked normally. It seemed to be completely random which ones worked and which didn't though; some really cheap cables worked and some high-end brand ones didn't (though cheaper cables had the problem way more often).
Answer: I can only guess but it's probably your midi interface.
midi/usb interfaces can be cheap - but if they're cheap...  this'll happen.  or at least things like this.  you've tried another?
Comment: Have just returned this one and ordered a better one - will come back to this question if that's resolved it.
Comment: New cable, same problem. This better cable does seem to be more sensitive for touch-sensitivity and pedals and stuff, but still as soon as I press a key it will not react to another key (or release) for ~4 seconds. The plot thickens though - anything other than the black-white keys on the Clavinova/PSR work perfectly fine. From the pedals to the buttons to the pith-bender. They all work real-time. Even stranger still - after any input óther than a key, the "cooldown" will reset and it will react to another key-press or release, at which point it stops reacting to any more key presses again.
Comment: @Jerros dang and you've tried 2 different keyboards (as well as multiple software) and same problem?  I'm at a loss.  My next guess would be keyboard settings.  Like an autochord sort of thing where you hit a key and it plays a chord.  Look in your keyboard manuals for hardware reset.  And see if anything changes.  Then set the minimum # settings you can to try to get it to talk properly.  Good luck :/
Comment: Turns out it WAS the cable. I just took my entire setup to a place that had dozens of different cables lying around, and eventually one worked normally. It seemed to be completely random which ones worked and which didn't though; some really cheap cables worked and some high-end brand ones didn't (though cheaper cables had the problem way more often).
Comment: weirddd.  well, glad you're back to music-ing :)
Answer:
This cable does seem to be more sensitive for touch-sensitivity and pedals etc., but as soon as I press a key it will not react to another press (or release) for ~4 seconds. The plot thickens though - anything other than the black-white keys on the Clavinova/PSR work perfectly fine. The pedals, buttons and pith-bender all work real-time. Even stranger still - after any input óther than a key, the "cooldown" will reset and it will react to another key-press or release, at which point it stops reacting to any more key presses again.

What is the problem?

This actually points doubly strong to "running status byte" compression triggering the problem since interjecting a controller message will stop the opportunity for doing a running status byte.  If the cable does not mess up the reception of this message, either the driver (are there remnants from your last USB cable's driver?  Have you installed any drivers available for your current one? Usually no driver should really be necessary) or the application will be at fault.
Comment: Both cables installed their own drivers when plugged into the laptop. I tried ónly the second, better cable on a different laptop that never had any midi drivers installed on it before  - same problem occurs. Should I manually search for drivers on the web? Though I'm not sure what I'm looking for exactly.
Comment: Turns out it WAS the cable. I just took my entire setup to a place that had dozens of different cables lying around, and eventually one worked normally. It seemed to be completely random which ones worked and which didn't though; some really cheap cables worked and some high-end brand ones didn't (though cheaper cables had the problem way more often).
Answer: "Running Status" is nothing that can be represented via USB Midi.  If that is the source of the problem, it is the USB/Midi-Interface that messes this up.  If your USB device string (in Linux visible with lsusb and in Windows somewhere in the device manager or something) indicates an M-Audio device, then M-Audio needs to get crossed off the list of recommendable manufacturers.
If it doesn't, it depends on whether your cable is genuine (and M-Audio indeed reverted to using bad third-party chips) to decide whether M-Audio is at fault for marking up generic garbage to a premium price tag after putting a different case on it.
I'd return it and see whether I can get something like a Terratec Midi One (which is only unidirectional and so, while handy and reliable, mostly applicable to simple uses) or one of the older preowned interfaces in a metal case (and typically with a full-size USB B socket).


Constructor call must be the first statement in a constructor in super()

Question: I'm following a guide on how to create a working interface in Java and I've done the code according to the guide yet I get an error saying Constructor call must be the first statement in a constructor, even though it is the first statement.
I tried multiple solutions so I'm quite lost as none of them worked.
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class test extends JFrame {
    private JLabel item1;
    private void test () {
        super ("Title 1"); //error happens here
      }
}

Answer: You didn't create a constructor - constructors don't have return type of void. It should be
private test (){
    super ("Title 1");
}

but you actually should stick to Java naming conventions and rename your class to Test.
Comment: Thank you for your answers, I actually believe I've tried that but it did not work, removing 'void' fixed my issue however ^^
Answer: The constructor should not have a return value
private test () {
    super(); // This should do
}

Answer: You need to remove the void from your test function.
Your code must be like:
public test (){
    super ("Frame Title");
}


If $\varphi \in E'$ and $A$ is convex and open then $\varphi (A)$ is an open interval

Question:
Let $E$  be a real normed space and $\varphi \in E'$, $\varphi \neq 0$.
  Suppose that $A \subset E$ is an open convex not empty subset.
  Show that $\varphi(A)$ is an open interval.

Since $A$ is connected and $\varphi$ is continuous,  $\varphi(A)$ is an interval.
How could I show that $\varphi(A)$  is open?
I tried to apply the geometric form of Hahn Banach theorem but it didn't work.
I appreciate if you could give some hints. Thanks.
Comment: Is $E'$ the dual space of $E$, i.e. the set of linear functions from $E$ to $\Bbb R$?
Answer: Since $\varphi(A)$ is an $\mathbb{R}$-interval, it is of the form $(a,b)$, $[a,b]$, $(a,b]$, $[a,b)$, with $-\infty\le a,b\le\infty$. Supose $\varphi(A)$ is not open. Then, WLG we can assume $\varphi(A)=[a,b)$. Then, there is $x\in A$ such that $\varphi(x)=a$.
Since $A$ is open, there is $r>0$ such that if $\|x-y\|<r$ we have $y\in A$. Now, if $\|z\|<r$ we have $\|x-(x+z)\|<r$ and thus $a\le \varphi(x+z)=a+\varphi(z)$. Therefore $\varphi(z)\ge 0$ for all $z$ with $\|z\|<r$.
Fix $z_0$, $\|z_0\|<r$. Then $\|-z_0\|<r$. We have $0\le\varphi(-z_0)=-\varphi(z_0)\le 0$. Thus, $\varphi(z)=0$ for all $z$ with $\|z\|<r$.
But the last implies, by linearity of $\varphi$, that $\varphi=0$ (cause every element of the space is a scalar multiple of an element of norm $<r$). This contradiction shows $\varphi(A)\neq [a,b)$ for all $a$.


Update UI lists modules/themes that are already updated

Question: I have a D7 (7.69) site. On both dev and production, I can update a module (using the web UI - /admin/modules/update), apparently successfully, yet afterwards, that module stays listed as requiring an update with Installed Version and Recommended Version exactly the same.
e.g.

Adminimal - Responsive Administration Theme (Theme)
  Installed version 7.x-1.26
  Recommended version 7.x-1.26

(I've seen it with themes, such as the one above, and modules such as Views).
I've tried:

clearing the cache
downloading a clean latest version to a new directory, and comparing the md5hashes of all files between the two (as well as simpler checks like the module .info file.)
wiping the module/theme directory and replacing with a freshly extracted .tar.gz
checking if any database updates are pending (they're not)

Is there anything else that could be causing it to get stuck?
I've looked at the system table - specifically the system.info field - but nothing looks "wrong".
Comment: @NoSssweat just FYI, caused by another module changing the status in a hook, as per my answer.
Comment: `wiping the module/theme directory` when you do this, does the message disappear? just wondering if perhaps you have duplicate modules/themes under the /core folder or somewhere else in your code base.
Comment: @NoSssweat - good suggestion, but yes (e.g. deleting /sites/all/modules/views clears it from the Update list, and it reappears as soon as it's downloaded and extracted again, same if I also delete the row from the system table).
Answer: This was caused by the Update Status Advanced Settings (update_advanced) module.
I didn't know this module was installed or what it was, so here's how I traced it back:
modules/update/update.compare.inc is where the core update module checks versions of each module and theme, beginning with update_calculate_project_data() - this creates a $project array that contains current/recommended versions, plus a numeric 'status' key.
'status' is a constant, set in modules/update/update.module, with values including:
define('UPDATE_CURRENT', 5); // project is up to date
define('UPDATE_NOT_CHECKED', -1); // Project's status cannot be checked.

I used Xdebug on update_calculate_project_data(), specifically tracking the modules that were stuck on the update screen.
They all had a status of UPDATE_CURRENT initially (as expected/desired), but that changed to UPDATE_NOT_CHECKED after the call to the hook in line 363:
drupal_alter('update_status', $projects);

Searching the code base, found this hook is implemented in sites/all/modules/update_advanced/update_advanced.module:50 by update_advanced_update_status_alter()
If you've got this module, the settings page is /admin/reports/updates/settings; you can instruct it to not warn you about specific modules.
The side effect is that by changing the status to anything other than UPDATE_CURRENT, a module/theme will always be listed in the Update UI (modules/update/update.manager.inc:94), including if the module is "current" really.
Comment: Worth filing a bug report.


groovy regular expression not working as I'd hoped

Question: I'm trying to get the regular expression from valid to match and println Testing for each... the valid form of data should be schedules[##]    (# being a number)
    def valid = ~/^('schedules')('[')[0-9]{2}(']')$/

    params.entrySet().findAll {
        valid.matcher(it.key).matches()
    }.each {

        println("Testing")

    }

I've also tried  ~/^('schedules[')[0-9]{2}(']')$/
anyone see what I'm doing wrong? cheers
Answer: Try this:
def params = [ 'schedules[32]'  : 'pass 1',
               'schedules[tim]' : 'fail 2',
               'schedules[4]'   : 'fail 3',
               'schedules[09]'  : 'pass 4',
               'invalid'        : 'fail 5' ]

params.entrySet().findAll {
    // Look for start of line then 'schedules[' then 2 chars 0-9, then ] and EOL
    it.key ==~ /^schedules\[([0-9]{2})]$/
}.each {
    println it.value
}

Because we have grouped the [0-9]{2} bit, we can get a bit more complex:
params.entrySet().findResults { entry ->
    ( entry.key =~ /^schedules\[([0-9]{2})]$/ ).with {
        matches() ? [ key:entry.key, value:entry.value, num:it[0][1] ] : null
    }
}.each {
    println "param $it.key with number $it.num = $it.value"
}

Which prints:
param schedules[32] with number 32 = pass 1
param schedules[09] with number 09 = pass 4


How to insert [Spatial Point] values with a query in MySQL in Laravel

Question: I have a table with a column of type Spatial point ,,
I want the query to insert the values of that column with laravel
and if there a queries to get items within a specific range ?
any help here ??
That's my table here :
public function up()
{
    Schema::create('markers', function(Blueprint $table)
    {
        $table->integer('marker_id')->primary();
        $table->string('marker_name', 45);
        $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
    });
    DB::raw("ALTER TABLE markers ADD COLUMN location POINT");
}

Comment: insert single value?post your table and code
Comment: I edited my question with the table ,,
Answer: You can insert data as follows:
ModelName::firstOrCreate(
    array(
        ..//other fields
        'location' => DB::raw("(GeomFromText('POINT(37.774929 -122.419415)'))")
    )
);

To retrieve data:
SELECT X(`location`), Y(`location`) FROM markers;

I too was stuck here & got help from: Spatial Point functions using Laravel Eloquent ORM. Hope this helps.
Comment: As a side note. I got the error `GeomFromText does not exist`. So I had to change it to `ST_GeomFromText`


Validity of different explicit forms of an arbitrary element of SO(3)

Question: The usual generators of SO(3) are given in the "Lie Algebra" section of this wikipedia article: https://en.wikipedia.org/wiki/3D_rotation_group. I will denote the generators $L_x, L_y, L_z$.
Using the exponential mapping, one would should be able to write an arbitrary element of SO(3) with $R(\theta, \varphi, \phi) = \exp(\theta L_x + \varphi L_z + \phi L_z)$ where $\theta, \varphi, \phi$ are parameters. Computing this exponential will give you an explicit form for an arbitrary element of SO(3).
However, wikipedia also writes under the "Mobius transformations" section that an arbitrary element of SO(3) may be written as $R(\theta, \varphi, \phi) = \exp(\theta L_x)\exp(\varphi L_y)\exp(\phi L_z)$.
We know that $[L_i, L_j] \neq 0$ for $i \neq j$. So the first explicit form is not equal to the second explicit form.
My question then is: are both of these explicit forms of an arbitrary element of SO(3) valid?
Comment: The answer is yes as you can convince yourself intuitively, but you're right that one does not follow trivially from the other. I don't know what the significance of both being true is. Is this a general property of (connected, compact) lie groups? I don't know.
Answer: I like this version, familiar from quaternions; all rational special orthogonal matrices occur  by taking $a,b,c,d$  integers, not all zero.
The more familiar appearance is   with the sum of the squares equal to one so the fraction disappears.
This is formula (10)  in Pall 1940
$$
\frac{1}{a^2 + b^2 + c^2 + d^2} \;
\left(
\begin{array}{ccc}
 a^2 + b^2 - c^2 - d^2 &   2(-ad+bc)  &  2(ac +bd  \\
 2(ad+bc) &  a^2 - b^2 + c^2 - d^2 &  2(-ab +cd)  \\
  2(-ac +bd)  & 2(ab +cd)  & a^2 - b^2 - c^2 + d^2 \\
\end{array}
\right)
$$


PHP REST API Token Expiration Flow

Question: I am creating a REST API in PHP, and I am having some problems to understand the concept of what I have to do with the expired tokens. I have MYSQL and Json Web Tokens for the authentication part.
DB STRUCTURE
CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(35) CHARACTER SET utf8 NOT NULL,
  `lastname` varchar(35) CHARACTER SET utf8 DEFAULT NULL,
  `password` text CHARACTER SET utf8 NOT NULL,
  `email` varchar(50) CHARACTER SET utf8 NOT NULL,
  `gender` enum('male','female') CHARACTER SET utf8 DEFAULT NULL,
  `description` text CHARACTER SET utf8,
  `email_verification` enum('unverified','verified','','') CHARACTER SET utf8 NOT NULL DEFAULT 'unverified',
  `updated` datetime NOT NULL,
  `created` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `device_tokens` (
  `id` int(11) NOT NULL,
  `device_id` tinyint(4) NOT NULL,
  `device_version` varchar(10) DEFAULT NULL,
  `user_id` int(11) NOT NULL,
  `token` text NOT NULL,
  `update` datetime NOT NULL,
  `created` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

LOGIN
I create a POST Request with the user and password, and if the validation is correct I return an access token (Json Web Token), that contains the following data:

email
name
user_creation_date
expiration time

LOGOUT
I create a POST Request with the access_token, device_type and user_id. But what happened if the token is already expired? I just deleted?
ANOTHER END POINT
for example
/pets?id=1

I create a GET Request with the access_token, user_id, and xx_id, so before I return the data. I verify if the token is correct, and if the token corresponds to the user that is makeing the request. But, what happened if the token has expired? I create another one?. In the case that I have to return another unexpired token, should I logout the user and ask the password and email again?
I don't understand what is the best way to do this. In other posts that I created about authentication, many users recommended me to use a third party authentication system, but I want to develop it myself.
Thanks for all
Answer: Usually if the token is expired you should remove it from database and logout the user. However, if the user is active it should be possible to extend the life time of the his access-token during his requests to your service. However, there is another approach when an additional parameter refresh-token is introduced. In this case the flow can look like:

User logins to your system. Two tokens access and refresh are generated.
User requests different endpoints and send only access-token.
Access-token is expired. User sends a refresh-token to extend life time of his session.
Refresh-token is invalid or expired then your system logouts the user.
Refresh-token is valid then access-token life time is extended.
User is happy and can continue using your service.
Comment: First of all, thanks for the help. So I create an access token and a refresh token and I send it to the client. The client stores both fields and when a request is made and the access-token is expired, the client must made another request with the refresh-token ?
Comment: Yes, you are right. However, you use different response codes in case the access-token is expired or it's invalid. If it's expired the client should send refresh-token. If it's invalid an user has to login again. @JIFT

PHP REST API Token Expiration Flow


Storing elements in an array at each iteration of a foreach on PHP

Question: I have a foreach that checks the number of sessions in my php site and for each session it fetches from a db the name of an item.
I would like to store the names sequentially in variables so I could use them after, so I don't have to make a second call to the database.
Here is the foreach:
foreach ($_SESSION['cart'] as $item)
{
    $pid = $item['itemId'];
    $q = $item['qty'];
    $query2 = $con -> prepare("SELECT * FROM item_descr WHERE id_item = :idItem");
    $query2-> bindValue (':idItem',$pid);
    $query2->execute();
    $row2 = $query2->fetch(PDO::FETCH_ASSOC);
}

Let's say there are 3 sessions, how could I keep saving $row2['name'] in different variables that I could use later?
Thanks!
Answer: Before the foreach define an array to store results in:
$mySessions = array();

Then after the $row2 = .... line:
$mySessions[] = $row2;

Then you will have the array populated so you can use it after your loop is completed.


Workaround for __getattr__ special method breaking inspect.getmembers() in Python 3.x

Question: The inspect.getmembers function breaks when used with a class that defines the __getattr__ method (in Python 3.x):
import inspect

class C:
    def __getattr__(self, name):
        def wrapper():
            print("For MCVE purposes, this does nothing useful.")
        return wrapper

print(inspect.getmembers(C()))

The resulting error looks like this:
Traceback (most recent call last):
  File "tmp.py", line 9, in <module>
    print(inspect.getmembers(C()))
  File "/usr/lib/python3.7/inspect.py", line 330, in getmembers
    for base in object.__bases__:
TypeError: 'function' object is not iterable

It seems that the problem lies in the fact that inspect.getmodule relies on the easier to ask for forgiveness approach and assumes that the __bases__ attribute either does not exist (which throws the AttributeError exception) or contains the base classes.
I could fix this by explicitly throwing AttributeError in C.__getattr__; however, I want to use inspect.getmembers with objects of classes that I have no control over. My question is this: Is there a workaround for this problem that works without any modification of the class C or its instances?
Comment: The only solution I can think of would be to monkeypatch such classes when you find one... But most `__getattr__` implementations I've seen so far restrict the available names (usually delegating to another object) instead of unconditionnally return something whatever the name.
Answer: You asked for a workaround that works without modification of the class C or its instances. Here is a solution that does the job, although it involves rewriting the long getmembers() function, which may not be convenient either. Perhaps this is more appropriate for a Pull Request on the library.
(source code from https://github.com/python/cpython/blob/3.7/Lib/inspect.py)
import inspect

def getmembers(object, predicate=None):
    """Return all members of an object as (name, value) pairs sorted by name.
    Optionally, only return members that satisfy a given predicate."""
    # Line below adds inspect. reference to isclass()
    if inspect.isclass(object):
        # Line below adds inspect. reference to getmro()
        mro = (object,) + inspect.getmro(object)
    else:
        mro = ()
    results = []
    processed = set()
    names = dir(object)
    # :dd any DynamicClassAttributes to the list of names if object is a class;
    # this may result in duplicate entries if, for example, a virtual
    # attribute with the same name as a DynamicClassAttribute exists
    try:
        for base in object.__bases__:
            for k, v in base.__dict__.items():
                if isinstance(v, types.DynamicClassAttribute):
                    names.append(k)
    # Line below edited to catch TypeError
    except (AttributeError, TypeError):
        pass
    for key in names:
        # First try to get the value via getattr.  Some descriptors don't
        # like calling their __get__ (see bug #1785), so fall back to
        # looking in the __dict__.
        try:
            value = getattr(object, key)
            # handle the duplicate key
            if key in processed:
                raise AttributeError
        except AttributeError:
            for base in mro:
                if key in base.__dict__:
                    value = base.__dict__[key]
                    break
            else:
                # could be a (currently) missing slot member, or a buggy
                # __dir__; discard and move on
                continue
        if not predicate or predicate(value):
            results.append((key, value))
        processed.add(key)
    results.sort(key=lambda pair: pair[0])
    return results

Now if you run your new getmembers():
class C:
    def __getattr__(self, name):
        def wrapper():
            print("For MCVE purposes, this does nothing useful.")
        return wrapper

print(getmembers(C()))

You should get the result you're after:
[('__class__', <class '__main__.C'>), ('__delattr__', <method-wrapper '__delattr__' of C object at 0x1155fa7b8>), ('__dict__', {}), ('__dir__', <built-in method __dir__ of C object at 0x1155fa7b8>), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of C object at 0x1155fa7b8>), ('__format__', <built-in method __format__ of C object at 0x1155fa7b8>), ('__ge__', <method-wrapper '__ge__' of C object at 0x1155fa7b8>), ('__getattr__', <bound method C.__getattr__ of <__main__.C object at 0x1155fa7b8>>), ('__getattribute__', <method-wrapper '__getattribute__' of C object at 0x1155fa7b8>), ('__gt__', <method-wrapper '__gt__' of C object at 0x1155fa7b8>), ('__hash__', <method-wrapper '__hash__' of C object at 0x1155fa7b8>), ('__init__', <method-wrapper '__init__' of C object at 0x1155fa7b8>), ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x7fd01899e4c8>), ('__le__', <method-wrapper '__le__' of C object at 0x1155fa7b8>), ('__lt__', <method-wrapper '__lt__' of C object at 0x1155fa7b8>), ('__module__', '__main__'), ('__ne__', <method-wrapper '__ne__' of C object at 0x1155fa7b8>), ('__new__', <built-in method __new__ of type object at 0x1008b0c48>), ('__reduce__', <built-in method __reduce__ of C object at 0x1155fa7b8>), ('__reduce_ex__', <built-in method __reduce_ex__ of C object at 0x1155fa7b8>), ('__repr__', <method-wrapper '__repr__' of C object at 0x1155fa7b8>), ('__setattr__', <method-wrapper '__setattr__' of C object at 0x1155fa7b8>), ('__sizeof__', <built-in method __sizeof__ of C object at 0x1155fa7b8>), ('__str__', <method-wrapper '__str__' of C object at 0x1155fa7b8>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x7fd01899e4c8>), ('__weakref__', None)]

Answer: Try setting c.__bases__ = () before calling inspect.getmembers(c).
Edit: safer and more elaborate version in response to comment:
object.__setattr__(c, '__bases__', ())
try:
    members = inspect.getmembers(c)
finally:
    object.__delattr__(c, '__bases__')

This will fail if:

C defines __slots__ or doesn't allow setting __bases__ for some other reason, which will raise an exception.
c already has an actual __bases__ attribute that shouldn't be overwritten. This can be checked for with some extra code.
Comment: I don't want to modify the inspected object. Besides, C may have also defined __setattr__ and that line might not work as intended.
Comment: @NikolaBenes how's the edit? Otherwise I might suggest monkeypatching `__getattr__`.


Linux journalctl not synced with systemctl status / Journalctl not updating

Question: I am running my custom service, let's call it "foo.service".
It's a gunicorn python process which logs a few things.
I used to be able to get a real-time log overview using journalctl -u <service> -f but now the journal seems to be stuck at some past logs. When I use systemctl status <service> it does show the latest logs though. So my logging does work, but journalctl seems to be stuck and doesn't show any updates.
Example:
journalctl -u foo.service -f
Nov 25 16:19:09 <name> systemd[1]: Started Instance to load up the program and its endpoints.
Nov 25 16:19:09 <name> gunicorn[28267]: 2019-11-25 16:19:09,844 [INFO]: Connecting to localhost:9773
Nov 25 16:19:09 <name> gunicorn[28267]: 2019-11-25 16:19:09,845 [INFO]: Connecting to localhost:9771
Nov 25 16:19:09 <name> gunicorn[28267]: 2019-11-25 16:19:09,846 [INFO]: Connected
Nov 25 16:19:09 <name> gunicorn[28267]: 2019-11-25 16:19:09,846 [INFO]: Connected

systemctl status foo.service
Nov 26 11:39:53 <name> systemd[1]: Started Instance to load up the program and its endpoints.
Nov 26 11:39:53 <name> gunicorn[29117]: 2019-11-26 11:39:53,458 [INFO]: Connecting to localhost:9773
Nov 26 11:39:53 <name> gunicorn[29117]: 2019-11-26 11:39:53,459 [INFO]: Connecting to localhost:9771
Nov 26 11:39:53 <name> gunicorn[29117]: 2019-11-26 11:39:53,460 [INFO]: Connected
Nov 26 11:39:53 <name> gunicorn[29117]: 2019-11-26 11:39:53,460 [INFO]: Connected

The latter is logging that was just created, so that works like a charm, but from my understanding the journalctl seems to be updated as well. This did work in the past, I am encountering these problems since the day before yesterday.
I tried restarting journalctl but that didn't seem to work.
Thanks in advance.
EDIT:
When I restart my service I notice gunicorn threw an exception when I look at the status of the systemctl service, I cannot scroll up so I have no clue as to what the cause of the error is (systemctl status):
Nov 26 15:08:27 <name> gunicorn[29390]:     self.log.info("Shutting down: %s", self.master_name)
Nov 26 15:08:27 <name> gunicorn[29390]:   File "/opt/my-program/venv/lib/python3.5/site-packages/gunicorn/glogging.py", line 271, in info
Nov 26 15:08:27 <name> gunicorn[29390]:     self.error_log.info(msg, *args, **kwargs)
Nov 26 15:08:27 <name> gunicorn[29390]: Message: 'Shutting down: %s'
Nov 26 15:08:27 <name> gunicorn[29390]: Arguments: ('Master',)
Nov 26 15:08:27 <name> systemd[1]: Started Instance to load up the program and its endpoints.

My foo.service configuration file:
[Unit]
Description=Instance to load up the program and its endpoints
After=network.target

[Service]
User=root
Group=www-data
WorkingDirectory=/opt/my-program/my-program-thing
Environment="PATH=/opt/my-program/venv/bin"
ExecStart=/opt/my-program/venv/bin/gunicorn --workers 1 --threads 12 --bind unix:foo.sock -m 007 app:app --bind 0.0.0.0:8085 --access-logfile '/var/log/foo.info.log' --error-logfile '/var/log/foo.err.log'
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

Answer: Try adding these lines to your service file under the [Service] tag

StandardOutput=journal
StandardError=journal

Then do a systemctl daemon-reload, then do a systemctl restart your_service.service
I edit the answer for others to see it easily. Problem was lack of space on /var filesystem so journalctl was not able to save logs to disk and read afterwards, that is why there was a difference between systemctl status and journalctl -fu .
Comment: You can add -n 30 to systemctl status your_service.service to see more lines, like this: systemctl status your_service.service -n 30 --no-pager
Comment: Glad that you got it fixed. I've edited the answer so others can identify the solution next time.
Comment: Tried it, I do not notice any differences. I updated my original post!
Comment: Yes, thank you! I received an IOError telling me the disk was full. After checking it with 'du h' I noticed the /var/ directory was 100% full. I cleared some logs and it solved the issue.


Multiple slideshows on a page

Question: On the home page of a site I want to list each node as an individual slideshow. Each node shown will be of the same content type. I am using views slideshow and panels if it helps.
Comment: What do you mean by "individual slideshow"?  Views Slideshow takes a series of nodes and turns them into one slideshow.  So I don't know what an "individual slideshow" would be in this context.
Comment: Ok, then you should use Field Slideshow (which does slideshows for a multi-value field of a single node) or a similar module, not Views Slideshow.
Comment: @PatrickKenny Lets say I have a content type called projects. Each project contains a series of images to be shown in a slideshow format. on a page I want to show:

Project 1 slideshow
Project 2 slideshow
Project 3 slideshow
etc
Answer: Yes it is possible to achieve this, You have to use views along with Scrollable Content
It provides a scrolling functionality for your content. Scrollable Content will give you a nice content slider preview of your site's nodes, and provides some display options.

The basic use is via blocks page, you'll find a block called
  "Scrollable Content" and if you want more control & you know how to
  use Views, you should use the Views style for Scrollable Content.

or you can check Scrollable Views , I'm using this in my website, but it no longer supported.
Answer: This has been achieved using the Fields Slideshow module.
https://drupal.org/project/field_slideshow
In views you can then select the image format for the field as slideshow, similar to colorbox.

This seems to be working fine for me but I am open to other suggestions
Comment: Could you please add a link and explanation why this module and how to use it?
Answer: I recently had this problem while having multiple views slideshow block from same view on same page the following link may help
http://crudpixel.com/content/drupal-multiple-slideshow-blocks-same-view-same-page
Answer: first of all you need to create extra field and add some node images to that field and after that you can call a function from home page and in that function you have to write
<code>$query = db_select('node', 'n');
  $query->join('field_data_field_slider_actve', 'sa', 'sa.entity_id = n.nid');
  $query->fields('n', array('nid'));
  $query->range(0, 5);
  $query->condition('n.type', 'home_slider');

  $results = $query->execute()->fetchAll();
</code>

Multiple slideshows on a page


Does ( P(B|A) - P(B|~A) ) / P(B|A) have a name?

Question: Without going into the details, which are unnecessary here, this morning I found uses for the quantity
$$ S = \dfrac{P(B|A) - P(B|\overline A)}{P(B|A)} , $$
something like the amount of "probabilistic specialness due to a condition". Like likelihood ratio, it's a comparison of P(B|A) and P(B|not A), but perhaps in some ways even more natural.
For instance, if today has a 30% chance of rain given that it's spring, and would have a 20% chance of rain otherwise (given not spring), then the difference is 10%, which we then divide by 30%, giving 33%. So 33% of spring's rain chances are correlated with it being spring instead of another season.
If, instead, we imagine the spring chances were 1%, and non-spring were 0%, then S would be (.01 - 0) / .01, or 100%. In this way, values are normalized to 100%.
My current feeling is that this might be a natural way to associate conditions with events. If S is high, then we would be prone to saying, "It's raining, S(rain|spring) is close to 100%, therefore rain is characteristic of spring, and it's probably spring". Something like logical abduction.
I'd like to know if this has a name in probability theory (and just generally how it might appear).
Comment: there is https://en.wikipedia.org/wiki/Relative_risk_reduction
Comment: I think that's it exactly. Please write a solution (copying text from Wiki instead of linking), and I'll mark it as the answer. Thank you
Answer: At least in epidemiology, the term is
Relative Risk reduction:

the relative risk reduction (RRR) or efficacy is the
relative decrease in the risk of an adverse event in the exposed group
compared to an unexposed group. It is computed as ${\displaystyle
(I_{u}-I_{e})/I_{u}}$, where $I_e$ is the incidence in the exposed
group, and $I_{u}$ is the incidence in the unexposed group.
If the risk of an adverse event is increased by the exposure rather than decreased, term relative risk increase (RRI) is used, and computed as ${\displaystyle (I_{e}-I_{u})/I_{u}}$.
If the direction of risk change is not assumed, a term relative effect is used and computed as ${\displaystyle (I_{e}-I_{u})/I_{u}}$

Dictionary of Epidemiology - Oxford Reference
Comment: (And the more general term "relative effect")
Comment: This term is also called the "avoidable risk" is epidemiology.


"Very Large Numbers"

Question: A couple days ago I was bored and thought of the following problem and am hoping someone can either answer my question or point me in the right direction.
Is there an easy way to compute the number of digits of the following? Follow up is, can the number of digits be presented in an easily presentable/human readable way?
googolplex knuth's up-arrow googolplex
References:

https://en.wikipedia.org/wiki/Googolplex
https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation
Comment: No, not if you want to write it out fully.
Comment: With uparrows it is easy to make numbers that have so many digits that the log is inadequate to attack it.  More uparrows is much more powerful than big numbers between the arrows.  You might see my answer [here](http://math.stackexchange.com/questions/547259/logarithms-of-logarithms-of-grahams-number-is-the-result-ever-handy/547321#547321) where I count the number applications of log it takes to get a number handy and find that even that is inadequate for even $3 \uparrow \uparrow \uparrow 3$, which is much larger than your number.
Comment: Another two applications of the log will bring the number of digits down to about $100$
Comment: Please clarify how many arrows you want by the way.  As is, I'll have to close it for being unclear.
Comment: You might also enjoy [this question](http://math.stackexchange.com/questions/72646/help-me-put-these-enormous-numbers-in-order-googol-googol-plex-bang-googol-s) which deals with how powerful different ways to make large numbers are.
Answer: At the risk of being snarky, there is a simple way to write out the number of digits:
$$ 1 + \lfloor \log_{10}\left( \text{googolplex} \uparrow \uparrow \text{googolplex}\right) \rfloor $$
Comment: Up voted because its true and funny. But curious if a way to represent it without referencing itself :)
Comment: @VenomFangs Its how you get to it, but as I've said, you cannot write it out fully.
Comment: OP only used one uparrow, which is just regular exponentiation.
Answer: If you just mean a single up arrow, then this is the same as computing a googol plex to the power of a googol plex. If I let $g$ denote the ordinary googol ($=10^{100}$), and $G$ denote the googol plex ($=10^{10^{100}}$), then the number of digits is the log base $10$ of $G^G$ plus $1$ (since both $g$ and $G$ are powers of $10$):
\begin{align}
\mathrm{Num\ Digits} &= 1 + \log_{10} \left(G^G \right) \\
&= 1 + G \log_{10} G \\
&= 1 + G \log_{10} \left[10^\left(10^{100} \right) \right] \\
&= 1 + G \cdot 10^{100} \\
&= 1 + Gg
\end{align}
So the number of digits is a googol plex times a googol, plus $1$.
Or to put it another way: the number of digits is one plus $1$ followed by a googol zeros and another hundred zeros.
Answer: One uparrow in Knuth's notation is just regular exponentiation, so you are asking about $N=(10^{10^{100}})^{10^{10^{100}}}=10^{(10^{100}\cdot {10^{10^{100}}})}$ which has $10^{100}\cdot {10^{10^{100}}}+1$ digits.
This is actually not such a large number.  If we take  $\log_{10} (\log_{10} (\log_{10} N)))$ we get about $100$.  In this answer I consider $3 \uparrow \uparrow \uparrow 3$ and find it takes $7625597484985$ applications of the $\log$ to make the number handy.  We define $\log^*$ as the number of applications of $\log$ to make a number handy, so we have $\log^* N=4$, but $\log^*3 \uparrow \uparrow \uparrow 3=7625597484985$ so it takes $\log \log^*3 \uparrow \uparrow \uparrow 3$ to get handy.  Bigger numbers will need $\log^{**}$, the number of times you need to apply $\log^*$ and so on.
Comment: But isn't that googol to the googol, not googolplex to the googolplex?
Comment: @WB-man:  you are right.  Fixed.

"Very Large Numbers"


Python start from beginning of file if first file is not last line

Question: with open(args.identfile) as indetifierfile, \
 open(args.elementtxt) as elementfile:
 for identifier_line, element_line in izip(identifierfile, elementfile):
    ident_split = identifier_line.split(".")
    el_split = elementfile_line.split(".")
    print ident_split[0]
    print ident_split[1]
    print el_split[0] //print for debug, bad programming practice apparently. I know.
    print el_split[1]
    if el_split is None: //tried to use this to start from the beginning of the file and continue loop? I don't know if it's valid.
        el_split.seek(0)

So I tried to read and process these two files. Where the print statements are I was going to put some code to put the stuff from the files together and output it to a file. The stuff in the element file doesn't have as much as identifier files. I would like to start from the beginning of the element file everytime it reaches end of file? I'm not sure how to go about this I tried the .seek
But that's not working. How do I go about doing this? To continue the loop and reading identifier file but start from the beginning of the element file.
Answer: I think the code below will do what you want. Get the length of the element file. Add to your counter every pass of the for loop. Once the counter reaches the length of the element file minus 1 (because arrays start at 0), it will reset the counter to 0 and start from the beginning of the elementfile while still going on the identifierfile.
count = 0
elementLength = len(elementfile)
for i in range(len(identifierfile)):
    ident_split = identifierfile[i].split(".")
    el_split = elementfile[count].split(".")
    print ident_split[0]
    print ident_split[1]
    print el_split[0]
    print el_split[1]
    if count < (elementLength-1):
        count = count + 1
    else:
        count = 0

Answer: You can try using itertools.cycle:
from itertools import izip, cycle

with open(args.identfile) as indetifierfile, \
 open(args.elementtxt) as elementfile:
 for identifier_line, element_line in izip(identifierfile, cycle(elementfile)):
    ident_split = identifier_line.split(".")
    el_split = elementfile_line.split(".")
    print ident_split[0]
    print ident_split[1]
    print el_split[0]
    print el_split[1]

Comment: You're a beautiful creature.


Imprimir somente uma parte de uma página HTML

Question: Estou tentando imprimir somente a parte de uma página HTML que possui um código de barras.
HTML:

            <svg id="barcode"
                 jsbarcode-textmargin="0"
                 jsbarcode-fontoptions="bold"
                 style="width: 30%; height: 30%;">
            </svg>

CSS:
@media print {
body * {
    visibility: hidden;
}

#barcode, #barcode *{
    visibility: visible;
}

#barcode
{
    position: fixed;
    left: 0px;
    top: 0px;
}

Vi em muitos lugares soluções semelhantes a essa, mas fazendo isso o meu código de barras aparece duas vezes, ou mais, na página de impressão.
Imagem:

Como solucionar esse problema?
Comment: Eu tentei da forma que dizer lá, e obtive esse problema da imagem
Comment: Testa a resposta do Gabriel. Ele pega o conteudo de uma determinada div, escreve num doc em branco e só imprime ele. é isso que tu precisa. =)
Comment: Não funcionou também, fazendo do jeito que ele disse a imagem nem aparece
Answer: var conteudo = document.getElementById('barcode').innerHTML;
var telaImpressao = window.open('about:blank');

telaImpressao.document.write(conteudo);
telaImpressao.window.print();
telaImpressao.window.close();

Esta resposta está disponível aqui
Você copia o conteúdo da sua div para uma página nova e a imprime.
Comment: Eu estava tentando só com a imagem, com a div inteira funcionou :)


On the sharpness of the Harada-Sai lemma

Question: Let $A$ be a finite dimensional $\mathbb{K}$-algebra, where $\mathbb{K}$ is an algebraically closed field. The following result is a well known (see for example Assem & Coelho - Basic representation theory of algebras):

Lemma (Harada-Sai). Let $m>0$ and
$$M_1\xrightarrow[]{f_1} M_2\xrightarrow[]{f_2} \dots \xrightarrow[]{f_{2^m-1}} M_{2^m}$$
be a radical path where each $M_i$ has composition length at most equal to $m$. Then, $f_{2^m-1}\dots f_2 f_1=0$.

Another well known result is that this bound on the length of non-zero radical paths is a sharp bound (see exercise VI.1.2 of Assem & Coelho).

My question is the following : Is the bound given by Harada-Sai's lemma sharp when we restrict ourselves to representation finite algebras? The exercise pointed out above gives an example of the sharpness for the algebra $\mathbb{K}[t_1,t_2]/\langle t_1^2,t_2^2\rangle$ which is representation infinite.
More precisely, I am looking for an example of a representation finite algebra $A$ such that the composition of $2^{m}-2$ radical morphisms (from modules which the lengths are bound by $m$) is non-zero.
Answer: Bongartz gives an example, for any $m$, in Section A.1 on page 326 of
Bongartz, Klaus, Treue einfach zusammenhaengende Algebren. I, Comment. Math. Helv. 57, 282-330 (1982). ZBL0502.16022.
The algebra is given by the quiver
$$
1
\begin{array}{c}
\xrightarrow{a}\\
\xleftarrow[b]\\
\end{array}
2
\begin{array}{c}
\xrightarrow{a}\\
\xleftarrow[b]\\
\end{array}
3
\cdots
m-1
\begin{array}{c}
\xrightarrow{a}\\
\xleftarrow[b]\\
\end{array}
m
$$
with relations $ab=ba=0$.
As an example I'll list the modules in a chain of $14$ morphisms for $m=4$. Arrows to the right indicate the action of $a$; arrows to the left indicate the action of $b$.
$$1\to 2\to3\to4$$
$$1\to2\to3$$
$$1\to2\to3\leftarrow4$$
$$1\to2$$
$$1\to2\leftarrow3\to4$$
$$1\to2\leftarrow3$$
$$1\to2\leftarrow3\leftarrow4$$
$$1$$
$$1\leftarrow2\to3\to4$$
$$1\leftarrow2\to3$$
$$1\leftarrow2\to3\leftarrow4$$
$$1\leftarrow2$$
$$1\leftarrow2\leftarrow3\to4$$
$$1\leftarrow2\leftarrow3$$
$$1\leftarrow2\leftarrow3\leftarrow4$$


Devise Invitable LoadError

Question: Problem:
m@m-Lenovo-IdeaPad-Y470:~/Dropbox/software/Rails/CIRCAR_CP_NEW$ rails s
Initialize SymmetricEncryption module.
=> Booting Thin
=> Rails 3.2.6 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/home/m/Dropbox/software/Rails/CIRCAR_CP_NEW/config/initializers/registrations.rb:1:in `<top (required)>': cannot load such file -- devise_invitable/controllers/registrations (LoadError)
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:245:in `load'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:245:in `block in load'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:236:in `load_dependency'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:245:in `load'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/engine.rb:588:in `block (2 levels) in <class:Engine>'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/engine.rb:587:in `each'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/engine.rb:587:in `block in <class:Engine>'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/initializable.rb:30:in `instance_exec'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/initializable.rb:30:in `run'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/initializable.rb:55:in `block in run_initializers'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/initializable.rb:54:in `each'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/initializable.rb:54:in `run_initializers'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/application.rb:136:in `initialize!'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/railtie/configurable.rb:30:in `method_missing'
from /home/m/Dropbox/software/Rails/CIRCAR_CP_NEW/config/environment.rb:7:in `<top (required)>'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `require'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `block in require'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:236:in `load_dependency'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `require'
from /home/m/Dropbox/software/Rails/CIRCAR_CP_NEW/config.ru:3:in `block in '
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/rack-1.4.5/lib/rack/builder.rb:51:in `instance_eval'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/rack-1.4.5/lib/rack/builder.rb:51:in `initialize'
from /home/m/Dropbox/software/Rails/CIRCAR_CP_NEW/config.ru:in `new'
from /home/m/Dropbox/software/Rails/CIRCAR_CP_NEW/config.ru:in `'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/rack-1.4.5/lib/rack/builder.rb:40:in `eval'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/rack-1.4.5/lib/rack/builder.rb:40:in `parse_file'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/rack-1.4.5/lib/rack/server.rb:200:in `app'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/commands/server.rb:46:in `app'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/rack-1.4.5/lib/rack/server.rb:304:in `wrapped_app'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/rack-1.4.5/lib/rack/server.rb:254:in `start'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/commands/server.rb:70:in `start'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/commands.rb:55:in `block in <top (required)>'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/commands.rb:50:in `tap'
from /home/m/.rvm/gems/ruby-1.9.3-p194@proof/gems/railties-3.2.6/lib/rails/commands.rb:50:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `'

If I run any rake commands, the same thing happens. All my other rails applications work just fine. It's just this one (the one I didn't write) that won't start.
I see that the problem is here: CIRCAR_CP_NEW/config/initializers/registrations.rb:1
CIRCAR_CP_NEW/config/initializers/registrations.rb
module DeviseInvitable::Controllers::Registrations
  def self.included(controller)
   controller.send :around_filter, :keep_invitation_info, :only => :create
  end

 ...

    yield
    reset_invitation_info
  end if resource_invitable
  puts "Keep Invitation Info End"
  puts "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
end

I just have no idea what to do about it. My understanding is that Rails is looking for something in this directory
devise_invitable/controllers/registrations

but is not finding it because that directory does not exist. Apparently the code works for the developers in India but they don't feel inclined to help me figure out why it's not running on my machine.
I'm running Ubuntu 12.04
Gemfile:
gem 'devise'
gem 'devise_invitable'

Bundle Install
m@m-Lenovo-IdeaPad-Y470:~/Dropbox/software/Rails/CIRCAR_CP_NEW$ bundle install
Using rake (10.0.4)
...

Using devise (2.2.4)
Using devise_invitable (1.1.8)

...

Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

Comment: is the team in India running RVM?
Answer: Are you certain that you have the devise gems are:
e.g.
bundle install

EDIT: If we know that the gems have been downloaded, there may be a problem with the Gem's configured load paths.

Within irb or pry run Gem.path
Check each of the returned paths for the devise libraries.  If the devise directory structure is not found, we have found your problem.
Comment: Thanks! It turns out the structure of the devise_invitable gem changed in newer versions. Your clue would have lead to this discovery.
Answer: It was a gem compatibility issue.
After version 1.1.4, the structure of devise_invitable changed.
devise_invitable/controllers/registrations

no longer exists. Therefore
module DeviseInvitable::Controllers::Registrations

needed to change to
module DeviseInvitable::RegistrationsControllers

to reflect the structure of the updated gem.
The other solution would be to add the version number to the gemfile and make sure I am using a compatible version so that things are being referenced as expected.
The server and rake commands now run, but there are a number of other issues I have to figure out now :P

Devise Invitable LoadError


Hide blocks in node page using context

Question: i am new to context module and based on some tutorial i have used context. Now my problem is,
Currently, I have created one context which will show default header logo in all the pages. Now got new requirement to show different logo on the node pages with selected taxonomy terms.
For this i created one more context and used taxonomy conditions with selected taxonomy terms for the different header logo. when i visit the page, i got two logos in the header section, so i edited the first context and added the taxonomy condition and selected those taxonomy terms and set the "No" to "Set on node form" option.
You know whats happens, the default logo gets disappear from all the pages but still showing two logos in the node pages with the selected Taxonomy terms pages.
I am not sure what condition to set to show in all the pages except in those selected taxonomy terms pages. Could you please someone guide me on this.
Answer: This should work... Context allows contexts to be fired based on the presence of other contexts. So in your "global" context, you can add the condition 'Context(all)' and then add ~[taxonomy_context_id]. Where taxonomy_context_id is the id of the taxonomy context. Make sure that "Require all conditions" is checked. And save.
Now the "global" context should only show when the the other isn't available.
Recommendation: If you are looking to switch logos based on taxonomy term, you can use template_preprocess_page() to switch out the path of the logo based on the current menu_object that is loading. This allows for you to have a global context that persists and doesn't duplicate the work/blocks and provides an override to the page.tpl.php variables instead of multiple possibly conflicting context.
Comment: Thank you so much...:) Taxonomy_context_id means context name, right? is there any id related to context.
Comment: Yep, it means the context name.
Comment: I set the context as you said, its working fine in the node pages but in all other pages the global logo is not displaying...anything need to set...
Comment: You could try to put a star (*) in the "Context (all)". That will fire on all contexts except the taxonomy context. Also, in the global did you set you "global"
Comment: yeah i have set site wide contexts to active. Do you want me to only add star (*) in the second context or in the global context itself?

Hide blocks in node page using context


Getting P value with mixed effect with lme4 package

Question: I have problem with getting p value from my mixed model,
library(lme4)
DWR<-lmer(DWRm2~Growth.stage+Se.application+Growth.stage:Se.application+(1|Block),data=Sub1)
summary(DWR)

before I used this model and I got p value with summary my model but now I can't get it, I have just t value
Comment: `library(lme4); help(pvalues)` gives some discussion.
Comment: @Smilig In spite of the similar titles the content seems to be completely different, since the other question seems to be focused on `memisc` not `lmer`; further, the answer there would be useless for this Q.
Answer: I'm pasting the information from help("pvalues",package="lme4") here.
Users who need p-values have a variety of options. In the list below, the methods marked MC provide explicit model comparisons; CI denotes confidence intervals; and P denotes parameter-level or sequential tests of all effects in a model. The starred (*) suggestions provide finite-size corrections (important when the number of groups is <50); those marked (+) support GLMMs as well as LMMs.

likelihood ratio tests via anova (MC,+)

profile confidence intervals via profile.merMod and confint.merMod (CI,+)

parametric bootstrap confidence intervals and model comparisons via bootMer (or PBmodcomp in the pbkrtest package) (MC/CI,*,+)

for random effects, simulation tests via the RLRsim package (MC,*)

for fixed effects, F tests via Kenward-Roger approximation using KRmodcomp from the pbkrtest package (MC)

car::Anova and lmerTest::anova provide wrappers for pbkrtest: lmerTest::anova also provides t tests via the Satterthwaite approximation (P,*)

afex::mixed is another wrapper for pbkrtest and anova providing "Type 3" tests of all effects (P,*,+)

arm::sim, or bootMer, can be used to compute confidence intervals on predictions.
When all else fails, don't forget to keep p-values in perspective.
Answer: p-values in lme4 are deliberately not listed by default, see:

Bates (author of lme4) on p-values in linear mixed models
or here
see also:
How to get an "overall" p-value and effect size for a categorical factor in a mixed model (lme4)?

There are some "approximations" but better just forget about p-values in lmm (or generally forget about them because they "measure" mostly the sample size).
Comment: Could you briefly summarize the points made? Links can die, which would render an otherwise valuable answer almost useless.
Comment: (I do realize that might be quite a difficult task, but it would make your answer substantially more useful, particularly if both links were lost. The links should of course remain; the extensve discussion is highly valuable.)