Help with probabilities on a game I am making

Question: I am working on making a RPG and am trying to understand the statistics of the core mechanic so I can determine how effective leveling and bonuses will be.
Right now the core mechanic is a skill die based mechanic where you roll a d4, d6, d8 or d10 based on your skill opposed by either a DC set by the story teller (1-10) or the result of another die via an opposed roll. (a DC is the number that the die must roll at least, for example if the die need to roll a 6 or higher then the DC would be 6)
I am experimenting with rolling two dice and picking the higher of the two, however I don't know how to make a statistical model for this. Especially due to the fact that I am planning on using exploding dice. (Exploding dice occur when you roll the highest possible number on the die. If this occurs you roll the die again, adding it to the total value of the die roll. This can continue an infinite number of times theoretically.)
I would very much appreciate some help on coming up with a formula for this. I want to set up an excel sheet to compare different bonus methods so I would really like something where I can put the formula in and tweak it instead of just probabilities listed.
Comment: On that note, I encourage you to keep asking question as you encounter specific issues in your game development endeavors. As Phil mentions sometimes the math might get out of scope for this site and [stats.se] or [math.se] might be better places to ask, but most specific questions regarding rpg development are on topic here and we'd love to help!
Comment: this might be better answered on the stack exchange maths site http://math.stackexchange.com/
Comment: Welcome! Excited to hear that you're working on a game. However, I've voted to close this question. The reason for this is that questions here should be specific and answerable. Right now all we can do with this question is refer you to an outside source. Perhaps a better tack would be to begin creating your statistical model and ask us if you run into any issues. You've told us very little about your system and even less about what you're trying to accomplish with your mechanics. Short of linking you to anydice or similar there isn't much more we can give you.
Answer: AnyDice has a lot of tools for dice probability. Check out the documentation.
For instance, output d4 > d4 gives the probability of one players d4 beating another. There's a 37.5% chance that the first player will win the roll in that situation.
Comment: This answer was pre-migration and is for game designers who want to understand the probability curves quickly without having to learn the statistics terms.
Comment: This doesn't appear to answer the question, which asks for a "formula."
Answer: There are three questions posed here.  In all but one (unusual) case, we can derive closed formulas or answers that require a small, fixed number of sums: no double, triple, or even quadruple loops are necessary.  I will restate and then answer each question in turn, providing worked examples in each case.
(As an aside: why should we care about efficiency in these calculations? Because these dice are the building blocks of what might become extremely complex game scenarios. It can be attractive to study many variations of the game, which may require considering millions of slightly different dice.  Such analysis becomes possible when the basic probability calculations are very fast.)
Several variations of each question are considered, depending on whether the dice are fair or not and, when contestants are competing head-to-head, whether they are using the same dice or not.  Considering unfair dice is very general, because it includes situations where players sum the values on two or more independent throws of dice.
Only a few basic rules of probability are needed to address almost all these situations. First, the chances of mutually exclusive outcomes are added.  When these outcomes exhaust all possibilities, the chances must sum to $1$.  Second, the chances of independent outcomes are multiplied. In one case (at the very end), a fundamental rule of conditional probability is needed: the chance of an event $A$ equals the chance of some other event $B$ times the conditional probability of $A$ given $B$.

What is the chance that a $d_n$ will equal or exceed a DC?  For example, what is the chance that a $d_8$ will equal or exceed $5$?
If the die is fair, the chance of each outcome is $1/n$ and $n-DC+1$ of those outcomes equal or exceed $DC$, whence the chance is $(n-DC+1)/n$.  For example, a $d_8$ has a $(8-5+1)/8$ = $50$% chance of equaling or exceeding $5$.
If the die is loaded (or is constructed by summing other dice), let $p_i$ be the chance it shows the value $i$.  The chance of equalling or exceeding $DC$ is obtained by summing over those mutually exclusive outomes, $\sum_{i\ge DC}p_i$.  The chance of falling below the $DC$ is, similarly, $p_1+p_2+\ldots+p_{DC-1}$, which I will call $P_{DC}$ (with a capital $P$). These numbers (which are cumulative chances) show up again below.
What is the chance that a $d_n$ will equal or exceed a $d_m$?
When the dice are the same, then $n=m$ and the chance they are both $i$ equals $p_i^2$.  Thus, considering the mutually exclusive outcomes of two $1$'s, two $2$'s, etc., the chance of a tie is $\Pr(tie)=\sum_{i=1}^n p_i^2$.  Because the players are evenly matched, they split the chances of winning outright, whence the chance of a win equals $(1 - \Pr(tie))/2$.  For example, the chance of a tie between two $d_8$'s is $\sum_i (1/8)^2$ = $1/8$ and (therefore) the chance of a win is $(1-1/8)/2$ = $7/16$ and the chance of a loss also is $7/16$.
When the dice are different, there's usually no other option than looking at all possibilities.  But this does not require $m n$ calculations.  Let's assume--without any loss of generality--that $m \le n$.  Let the probabilities for the $d_n$ be $p_1, p_2, \ldots, p_n$ and let the probabilities for the $d_m$ be $q_1, q_2, \ldots, q_m$.  The chance that the $d_n$ shows $i$ and the $d_m$ shows $j$ is therefore $p_i q_j$.

The chance of a tie is computed much as before, but the sum must stop at the highest possible common value: $\Pr(tie) = \sum_{i=1}^m p_i q_i$.  That takes $O(m)$ calculations (specifically, $m$ multiplications and $m-1$ additions).
The chance that the $d_m$ wins can be found by imagining a table of all outcomes, with the $d_n$ designating the rows and the $d_m$ the columns.  The $d_m$ wins in all the above-diagonal cells.  Those can be thought of as comprising $m-1$ vertical strips.  The strips form a staircase: there is just one cell in the strip for an outcome of $2$ (because only a $1$ is smaller), there are two cells for $3$, and so on.  Let $P_i = p_1 + p_2 + \cdots + p_{i-1}$  be the chance that the $d_n$ is less than $i$. Summing over the strips gives $\sum_{i=2}^m P_i q_i$ for the chance that the $d_m$ wins.  Computing the $P_i$ requires only $O(m)$ work ($m-2$ additions) and computing the sum is again $O(m)$ ($m-1$ multiplications and $m-2$ additions).  Finally, the chance the $d_n$ wins is obtained by noting the three chances--win, tie, lose--must sum to 1.  Thus, we obtain all the desired probabilities with $2m-1$ multiplications, $3m-4$ additions, and a subtraction--and $m$ is the size of the smaller die.

Example
Let's pit a fair $d_4$ against a sum of a $d_2$ and a $d_3$, which is a form of a loaded $d_5$.  Here $n=5$ and $m=4$.  We can work out the chances for this $d_5$ easily; they are $p_1=0$, $p_2=p_5=1/6$, and $p_3=p_4=1/3$, which can be abbreviated by the vector $(0,1/6,1/3,1/3,1/6)$.  Thus the cumulative sums $P_i$ are $(0,1/6,1/2)$ (we stop at $1/2$ because that is all we will need; the next two cumulative sums are $5/6$ and $1$).  The probabilities for the fair $d_4$ are, of course, $(1/4,1/4,1/4,1/4)$.  Thus the chance of a tie is $(0(1/4) + (1/6)(1/4) + (1/3)(1/4) + (1/3)(1/4)$ = $5/24$.  The chance of a $d_4$ win is $(0)(1/4) +(1/6)(1/4) + (1/2)(1/4)$ = $1/6$.  Therefore the chance that the $d_5$ wins equals $1 - (5/24 + 1/6)$ = $5/8$.  We did not have to compute all $6\times 4=24$ cases to get these answers.
How do we deal with exploding dice?
Let's consider only two equivalent dice (although they do not have to be fair), say with probabilities $(p_1,p_2,\ldots,p_n)$.  The only time an "explosion" might make a difference is when both dice roll an $n$; then the procedure repeats.  Let $z$ be the chance of a tie.  Then either a tie occurs at a value less than $n$--which has a chance of $\sum_{i=1}^{n-1}p_i^2$ of happening--or else both dice roll $n$ (which has a chance $p_n^2$ of happening) and a tie subsequently occurs, with chance $z$.  Solving this equation gives $z = \sum_{i=1}^{n-1}p_i^2 / (1 - p_n^2)$.  Because the dice are equivalent, then--reasoning as before--the two players split the remaining chances equally between winning and losing.
(The case of two inequivalent exploding dice--especially when each has a different maximum value at which it explodes--can be solved, but because infinitely many outcomes are possible, efficient solutions require manipulating the probability generating functions and, ultimately, making numerical approximations.)
Example
Let the two players use a sum of two fair $d_6$'s, exploding on the maximum value of $12$.  The chance vector for one roll is $(0,1/36,2/36,3/36,4/36,5/36,6/36,5/36,4/36,3/36,2/36,1/36)$.  Then $\sum_{i=1}^{12-1}p_i^2$ = $0^2 + (1/36)^2 + \cdots + (2/36)^2$ = $145/1296 \approx 0.11188$ and $1 - p_n^2$ = $1 - (1/36)^2$ = $1295/1296$.  Therefore the chance of a tie is $(145/1296) / (1295/1296)$ = $29/259 \approx 0.11197$.  The chance of a win equals $(1 - 29/259)/2$ = $115/259 \approx 0.444015$.  Evidently the explosion is of little consequence.  In fact, our general formula makes it evident that when $p_n^2$ is small, the explosion will hardly affect the chances of winning or tying (although of course it can appreciably affect the expected value of the die).  For instance, if $p_n$ is as large as $1/5$, explosion will multiply the chance of a tie by about $0.96$, hardly any reduction at all.
Answer: Tabular method
For two dice, the simplest way to do it is to do a 2-dimensional grid, then count the number of results.
   A 1 2 3 4   Chances
 B ----------- Of 24
 1 | 1 2 3 4 | 1
 2 | 2 2 3 4 | 3
 3 | 3 3 3 4 | 5
 4 | 4 4 4 4 | 7
 5 | 5 5 5 5 | 4
 6 | 6 6 6 6 | 4

One can unwrap such a table into a second table...
   AB 1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 6 6 6 6   Chances
 C   -------------------------------------------------- of 4*5*6
 1 |  1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 6 6 6 6 | 1 (1-0)
 2 |  2 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 6 6 6 6 | 7 (8-1)
 3 |  3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 6 6 6 6 | 19 (27-16)
 4 |  4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 6 6 6 6 | 37 (64-27)
 5 |  5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 | 36 4*(25-16)
 6 |  6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 | 44 4*(36-25)
 7 |  7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 | 24
 8 |  8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 | 24
   ---------------------------------------------------

Formulaic method
Given A ≤ B, and any N ≤ A, odds of N on higher of 1dA and 1dB are (N^2)-((N-1)^2)/(A*B), and any A

For 3d, where N ≤ A ≤ B ≤ C, odds of N are ((N^3)-((N-1)^3))/(A*B*C).
IIRC, Where A < N ≤ B ≤ C, odds of N are A*((N^2)-((N-1)^2))/(A*B*C).
IIRC, where A ≤ B < N ≤ C, odds of N are A*B/(A*B*C)
For 4d, it should be...
N ≤ A ≤ B ≤ C ≤ D, chance(N)= ((N^4)-(N^3))/(A*B*C*D)
A ≤ N ≤ B ≤ C ≤ D, chance(N)= A*((N^3)-(N^2))/(A*B*C*D)
A ≤ B ≤ N ≤ C ≤ D, chance(N)= A*B*((N^2)-(N^1))/(A*B*C*D)
A ≤ B ≤ C ≤ N ≤ D, chance(N)= A*B*C/(A*B*C*D)
And so on...
Programmatic method
It's possible to use nested for/next loops. I'll provide a python example, because it's cheap, easy, and has nifty tools like .sort()...
T = 0
R = [0,0,0,0,0,0,0,0,0,0,0]
' R needs one more "0," than the largest number of sides
' we set up a for line for each die, with the possible results in the entries.
For A in [1,2,3,4]:
    for B in [1,2,3,4,5,6]:
        for C in [1,2,3,4,5,6,7,8]:
            for D in [1,2,3,4,5,6,7,8,9,10]:
                ' now we do actual work...
                temp = [0,0,0,0]
                ' reset temp
                temp[0]=A
                temp[1]=B
                temp[2]=C
                temp[3]=D
                ' we've just loaded the current die's values into array Temp
                temp.sort()
                ' we've just put them into order
                n = temp[3]
                ' we get the high die
                R[n] += 1
                ' we increment the count for a result of n
                T += 1
                ' we count the total iterations.
X = 0
' we're setting our output loop next, and it uses X as a counter
for Y in R:
    print X, Y
    ' print current entry labeled.
    X += 1
    ' increment X

Similar methods can be used in many languages, but for this kind of calculation I use Python for its really robust arrays.
Comment: Probably you wrote it that way for a reason, but anyway, the Python code could be [simplified somewhat](http://codepad.org/on8azo8W) or [totally rewritten without the nesting](http://codepad.org/EiKMHKB3)
Comment: @Stuart Human intelligibility is why. Your reduction is, while slick, much less intelligible to non-hard-core programmers, and that's counter productive.
Comment: using `max(A, B, C, D)` is less intelligible than making a temporary list of zeroes, changing the zeroes to the loop variables, sorting the list and taking the highest value from it?
Comment: @stuart: It is if you need "keep 2". Your method is less intelligible *and less useful* for a broad spectrum of potential situations.


Extrended hex address in visual basic

Question: I'm having trouble implementing an extended hex value onto my project. When I type &H000007F0 into my Visual Basic project, Visual Studio goes and shortens it to &H7F0.  In a normal situation, that would be fine but I need the preceding 0's to be included as a parameter for a function on an API.
I've tried creating it as a string Dim MastID As String = "000007F0" and then converting to a hex Convert.ToUInt32(MastID, 16), but that didn't work like I thought it would. Are there any other methods I can try or a VS17 setting I can turn off/on that will allow me to have the full &H000007F0?
I'm doing this to try to connect to a slave device on a CAN bus. I'm using an API that has it's own functions to control the CAN device and initialize a CAN channel. If I am able to pass the extended ID, &H000007F0, then the API would initialize the CAN channel with those parameters.
Parameters being set for slave data:
SlaveData.BroadcastID = &H18DAA1E1
SlaveData.MasterID = &H7F0
SlaveData.SlaveID = &H7F2
SlaveData.IncrementalIdUsed = False

Function being used:
Public Shared Function Connect(
   ByVal Handle As UInt32,
   ByVal Mode As Byte,
   ) As Result ' Returns no errors
End Function

Analyzing the CAN BUS, the device ID being used is 7F0h, therefore the slave device does not respond with an acknowledge message. It does however work when I send the same function with the extended master ID my making my own byte array.
Comment: You don't need the "preceding zeros".  Ask the real question, show your code.
Comment: *The IDs have to be UInt32*. So, explicitly declare and send `UInt32` values. How is this related whith the value representation *on paper*?
Comment: &H00000H7H0 might be a value, but it sure isn't hexidecimal - that only goes up to 'F', not 'H'.
Comment: If you're communicating with a CAN Bus, why aren't you sending it a byte array? This is pretty much impossible to answer without seeing your code.
Comment: @Comintern True, I fixed it! My mind is playing tricks on me...
Comment: @HansPassant I'm trying to connect to a slave device on a CAN Bus and I need to use the extended address to connect to it. With out it, the slave device cannot discern that commands sent out arte meant for it.
Comment: Gosh, I wish! I'm using an API that has its own functions. I'm only able to supply the input variables, such as the Master ID/Slave ID, and it takes care of the channel initialization for me. The IDs have to be UInt32 for the functions to work.
Comment: As others have said, please [edit] your post to include a [mcve].
Comment: If you really believe those preceding zeroes matter, go to the Tools Menu->Select Options.  From there, select Text Editor->Basic->Advanced.  Under the _Editor Help_ category, uncheck "Pretty listing (reformatting) code".  You can also ctrl-Z (undo) immediately after VS _corrects_ it.
Comment: Could it be that the endian-ness of the api somewhere is different to your code? I presume that entering 7F00000 doesnt work either?
Answer: As has been pointed out you do not need the leading zeros.  Here is some food for thought...
    Dim foo As UInt32 = &H7F0 'note missing 0's

    '  or
    Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.CurrentCulture
    Dim styles As Globalization.NumberStyles = Globalization.NumberStyles.HexNumber
    Dim bar As UInt32
    Dim s As String = "000007F0" 'note leading 0's
    If UInt32.TryParse(s, styles, provider, bar) Then
        If foo = bar Then
            Stop ' <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        End If
    End If

Extrended hex address in visual basic


Proof Check for a Theorem on Cyclotomic Polynomials and Connection with Eisenstein's Criterion.

Question: The main help I need is with proof-check of a theorem on divisors of cyclotomic values.
IF: For $\Phi_n(a) \equiv 0 \pmod{p}$ where $p$ is any prime and $n \in \mathbb{N}$ and $a$ is any integer.
To prove: $n \vert p-1$ or $p \vert n$
Proof: If $\Phi_n(a)$ is divisble by $p$ $\implies p \vert a^n-1$ as $\Phi_n(a) \vert a^n-1$.
$$a^n \equiv 1 \pmod{p}$$
Case 1: If $n$ is the order of $a$ under moduli prime $p$ or $n = \text{ord}_p(a)$ then we say $n \vert p-1$.
Case 2: If $m$ is the order of $a$ under moduli prime $p$ or $m = \text{ord}_p(a)$ then $$a^m-1 = \prod_{d|m} \Phi_d(a) \equiv 0 \pmod{p}$$ as $m \vert n$ and $\Phi_n(a) \equiv 0 \pmod{p}$
$$a^n-1 \equiv 0 \pmod{p^2}$$
If $l$ is the order of $a$ under moduli prime $p^2$ or $l = \text{ord}_{p^2}(a)$.
$$a^l-1 = \prod_{d|l} \Phi_l(a) \equiv 0 \pmod{p^2}$$
and as once again $l|n$ and $\Phi_n(a) \equiv 0 \pmod{p}$
We get $$a^n-1 \equiv 0 \pmod{p^3}$$
The same result is found if $l=m$ by repeating the process.
But if $v_p(a^n-1) = x $,
$$a^n-1 \equiv 0 \pmod{p^x}$$
Is max it can go,
Therefore, at $\pmod{p^x}$ the order should hit $n$ to stop this increment of $p$ power.
Later Addition for Clarification:
This is because: If the order is some other number $t(p^x|a^t-1)$, then $t|n$.So, $a^t-1|a^n-1$ and p also divides $\Phi_n(a)$, this means $a^n-1$ is divisble by $p^{x+1}$ which can not happen.So, $t = n$ to prevent this.
$$n|p^{x-1}(p-1), x \geq 2$$
If we prove that $n$ Does not divide $p-1$, We can guarantee that $p|n$.
Now, for the sake of contradiction let us assume $n|p-1$.
By Lifting the Exponent Lemma, this can be easily shown.
$$v_p(a^{p-1}-1) = v_p(f)+v_p(a^m-1),p-1 = f\cdot m$$
$$v_p(f) = 0$$
P-adic valuation of $a^{p-1}-1$ and $a^m-1$ is same.
Let us say that $v_p(a^m-1) = i$, this means that $p^i| a^m-1$,
with $p|\Phi_n(a) $, $p^{i+1}|a^{p-1}-1$ but the p adic valuations were same.
This is a contradiction.
Hence, $n$ does not divide p-1.
This means $p$ will divide $n$
Hence, Proved.
Question_1:
My friend said that I proved Eisenstein's criterion's, I cannot make any sense of it, what does it mean?
Is there any connection, I did not know about Eisenstein's criterion, did some search and figured what It meant. Still unable to see any connection.
Question_2
A better proof?
Comment: Related question: https://math.stackexchange.com/questions/2009052/prove-that-nth-cyclotomic-polynomial-has-no-roots-modulo-p
Comment: Hmmm Can someone please check this?
Comment: @Threeaggies This method is given in the source I am refering
to for cyclotomic polynomials, but I am very uncomfortable with derivatives in modular arithmetic and I have no idea or experience of it, so I tried to make my own proof and searched for other proofs but failed.
Comment: @Kevin I do not follow, how exactly would it be infinity?
As $n \equiv 0 \pmod{p}$ does not mean n  = 0.
Answer: I'm going to first have a look on your proof, and write a connection with Eisenstein's criterion, and then write my proof which uses lifting the exponent lemma.

But if $v_p(a^n-1) = x $, $$a^n-1 \equiv 0 \pmod{p^x}$$ Is max it can go,Therefore, at $\pmod{p^x}$ the order should hit $n$ to stop this increment of $p$ power.
$$n|p^{x-1}(p-1), x \geq 2$$

It seems to me that you think the following claim is true :
Claim 1 : If $v_p(a^n-1) = x $, then $ \text{ord}_{p^x}(a)=n$.
The claim 1 is not true. Take $a=2,n=12,p=3$ for which we have $x=2$ and $\text{ord}_{p^x}(a)=6\not=n$.
Added 1 :
I forgot to consider the condition $\Phi_n(a)\equiv 0\pmod p$.
Your claim is the following :
Claim 2 : If $\Phi_n(a)\equiv 0\pmod p$ and $v_p(a^n-1)=x$, then $\text{ord}_{p^x}(a)=n$.
I can see that claim 2 is true (you might want to add a proof of your claim in your proof).
In conclusion, I have not found any error in your solution, so I think your proof is correct.

Eisenstein's criterion gives a sufficient condition for a polynomial with integer coefficients to be irreducible over the rational numbers.
The contraposition of
Our claim : "If there is an integer $a$ such that $\Phi_n(a)\equiv 0\pmod p$, then $n\mid p-1$ or $p\mid n$"
is
"If $n\not\mid p-1$ and $p\not\mid n$, then there is no integer $a$ such that $\Phi_n(a)\equiv 0\pmod p$"
which gives a sufficient condition for $\Phi_n(x)\pmod p$ to be irreducible.
Maybe this is what your friend's comment meant.

Finally, I'm going to write my proof which uses lifting the exponent lemma.
Our claim : If there is an integer $a$ such that $\Phi_n(a)\equiv 0\pmod p$, then $n\mid p-1$ or $p\mid n$.
Proof :
For $a=1$, the claim follows since, by induction, we have $$\Phi_n(1)=\begin{cases}0&\text{if $n=1$}\\p&\text{if $n=p^e$ with $e\ge 1$}
\\1&\text{otherwise}\end{cases}$$
In the following, $a\ge 2$.
Let $n=p^em$ where $m,e$ are integers such that $\gcd(p,m)=1,m\ge 1,e\ge 0$.
For $p=2$, suppose that $m\gt 1$. Then, we have $\frac{a^{2^em}-1}{a^{2^e}-1}=\sum_{i=0}^{m-1}(a^{2^e})^i\equiv m\equiv 1\pmod 2$, so $2\not\mid \Phi_n(a)$ which is a contradiction. Since we have $m=1$ and $n=2^e$ with $e\ge 0$, the claim follows.
In the following, $p\ge 3$. Let $g:=\text{ord}_p(a)$.
We have $p\mid (a^{n}-1)$, so $g\mid n$. Since $g\mid p-1$, we get $\gcd(p,g)=1$, and so $g\mid m$ which implies $m\ge g$.
By lifting the exponent lemma,
$$v_p(a^n-1)=v_p(a^{p^eg}-1)=v_p(n)+v_p(a^g-1)\tag1$$
Suppose that $m\gt g$. From $(1)$, we have $p\not\mid \frac{a^{p^em}-1}{a^{p^eg}-1}$, so $p\not\mid \Phi_n(a)$ which is a contradiction. Since we get $m=g$ and $n=p^eg$ with $e\ge 0$, the claim follows.$\ \blacksquare$

Added 2 :
Claim 3 : If $\Phi_n(a)\equiv 0\pmod p$ with $a\ge 2$ and $p=2$, then $a$ has to be odd.
Proof : We have $a^n\equiv 1\pmod 2$. Since $a^n$ is odd, we see that $a$ has to be odd.$\ \square$
Claim 4 : If $\Phi_n(a)\equiv 0\pmod p$ with $a\ge 2$ and $p\ge 3$, then $v_p(a^n-1)=v_p(a^{p^eg}-1)=v_p(n)+v_p(a^g-1)$.
Proof : Let $k:=\frac mg$. For $\ell=0,1,\cdots, e-1$, we have $a^{p^{\ell}g}\equiv 1\pmod p$. Let $a^{p^{\ell}g}=Ap+1$. Then, $$\begin{align}\frac{a^{p^{\ell+1}g}-1}{a^{p^{\ell}g}-1}&=\sum_{i=0}^{p-1}(a^{p^{\ell}g})^i
\\\\&=\sum_{i=0}^{p-1}(Ap+1)^i
\\\\&=\sum_{k=0}^{i}(Ap)^k\sum_{i=0}^{p-1}\binom ik
\\\\&=p+\frac{A(p-1)}{2}p^2+(Ap)^2\sum_{i=2}^{p-1}\binom i2+\cdots
\\\\&\equiv p\pmod{p^2}\end{align}$$ So, we have  $v_p\bigg(\frac{a^{p^{\ell +1}g}-1}{a^{p^{\ell}g}-1}\bigg)=1$ and $v_p\bigg(\frac{a^{p^eg}-1}{a^{g}-1}\bigg)=e$. So, we have $$v_p(a^{p^eg}-1)=v_p(a^g-1)+e\tag2$$ Since $\frac{a^{n}-1}{a^{p^eg}-1}=\frac{a^{p^egk}-1}{a^{p^eg}-1}=\sum_{i=0}^{k-1}(a^{p^eg})^i\equiv k\pmod{a^{p^eg}-1}$, we have $\gcd\bigg(\frac{a^n-1}{a^{p^eg}-1},a^{p^eg}-1\bigg)\mid k$. Since $p\not\mid k$, we have $$v_p(a^n-1)=v_p(a^{p^eg}-1)\tag3$$From $(2)(3)$, the claim 4 follows.$\ \square$
Comment: But is not my claim subject to the condition $\Phi_n(a) \equiv 0 \pmod{p}$.
For example.
Let $\Phi_n(a) = \Phi_6(5)$, which is divisble by both 3 and 7.
$v_3(5^6-1) = 2$
so according to my claim, for $\mod{9}$,the order should be 6.
Which is true.
Same for $p=7$.
Comment: You forgot to consider this while testing it.
Comment: Can you explain how $a^{2e}$ is congruent to 1 $\mod{2}$?
And how $v_p(a_n−1)=v_p(a^{p^eg}−1)=v_p(n)+v_p(a^g−1)$ this holds?
Comment: @Krave37 : I added more explanations. See **Added 2**.
Comment: Thanks, I can now udnerstand how you reached there.
I have one doubt where did you use $l$ and how do we get this $v_p\bigg(\frac{a^{p^eg}-1}{a^{g}-1}\bigg)=e$
Comment: @Krave37 : I used $\ell$ to get $v_p\bigg(\frac{a^{p^eg}-1}{a^g-1}\bigg)=e$ as follows : For every integer $\ell$ such that $0\le \ell\le e-1$, we have $v_p\bigg(\frac{a^{p^{\ell +1}g}-1}{a^{p^{\ell}g}-1}\bigg)=1$, so we have $v_p\bigg(\frac{a^{p^eg}-1}{a^g-1}\bigg)=v_p\bigg(\frac{a^{pg}-1}{a^{g}-1}\times\frac{a^{p^{2}g}-1}{a^{pg}-1}\times\cdots\times\frac{a^{p^{e}g}-1}{a^{p^{e-1}g}-1}\bigg)=e$.


Making list of pairs from the numbers

Question: Given numbers $1,2,...,10$ we need to make a list of $5$ pairs from these numbers. Pairs don't contain repeated numbers and the order of digits in the pair doesn't matter (nor does the order of pairs in the list). What is the probability that a pair with both digits $\leq 5$ would appear in our list?
Is the total number of all possible "pairing" lists $C_{10}^2 \cdot C_8^2 \cdot C_6^2 \cdot C_4^2$ ? Thank you.
Comment: What do you mean by 'pairs don't contain repeated numbers'? Do you only mean that a pair cannot be of the form $(a, a)$ or that the numbers cannot repeat in the whole list?
Comment: Right, pairs of the form $(a,a)$ cannot appear and in the whole list numbers don't repeat.
Comment: I do not think your calculation is correct. It counts permutations of the pairs as well as pairs in the list. I think it'll be $\frac{10!}{2^5 \cdot 5!}$
Answer: We can permute the $10$ digits in $10!$ ways. Let the permutations represent a list by pairing two subsequent numbers. Now, a same list can be represented by $2^5 \cdot 5!$ permutations. So, are a total of $\frac{10!}{2^5 \cdot 5!}$ such lists.
As for the case you seek, let us consider the compliment. Then, there must be at least one number $>5$ in each of the pairs. As there are only $5$ of them, there'll be only one. We can assign a pair with those numbers (as order doesn't matter) and the other number can be selected in $5!$ ways. So, the probability of such a case would be $\frac{5! \cdot 2^5 \cdot 5!}{10!}=\frac{8}{63}$.
So, the probability of the case you need would be $1-\frac{8}{63}=\frac{55}{63}$.
Comment: Side note: for the sake of computing probability, you don't need to take the "orderless" aspect into consideration (i.e., you don't need to divide by $2^5\cdot5!$).
Comment: @barakmanos His other question was to calculate the total number of lists. So, I thought it'd be best. Moreover, I think it's clearer to picture.

Making list of pairs from the numbers


derive sufficient statistic from a random independent sample from a weibull distribution

Question: Suppose $X_i$ is a random independent sample from a Weibull distribution
$$ f(x) = \frac{\beta}{\theta^\beta}x^{\beta-1}\exp\big(-(\frac{x}{\theta})^\beta\big)$$
Find a sufficient statistic for parameter $\theta$.
SOLUTION:
I have used fisher factorisation criterion $f(x;\theta)=g(T(x);\theta)h(x)$
in this case:
$$h(x)=\beta x^{\beta-1}$$
$$ g(T(x);\theta) = \frac{1}{\theta^\beta}\exp \Big(-(\frac{x}{\theta})^\beta \Big)= \frac{1}{\theta^\beta} \Big(- \exp (x^\beta)+\exp(\theta^\beta \Big) $$
therefore
$$ T(x) = -\exp(x\beta)$$
is sufficient statistic for parameter $\theta$.
Is this correct?
Answer: Due to independence, joint density of the sample $\mathbf X=(X_1,X_2,\cdots,X_n)$ is
\begin{align}
f_{\theta}(\mathbf x)&=\prod_{i=1}^n \frac{\beta}{\theta^{\beta}}x_i^{\beta -1}e^{-x_i^{\beta}/{\theta}^{\beta}}\mathbf1_{x_i>0}
\\&=\frac{e^{-\frac{\sum x_i^{\beta}}{\theta^{\beta}}}}{\theta^{n\beta}}\beta^n \left(\prod_{i=1}^n x_i\right)^{\beta-1}\mathbf1_{x_1,\cdots,x_n>0}\quad,\theta,\beta>0
\\&=g(\theta,t(\mathbf x))h(\mathbf x)
\end{align}
, where $g(\theta, t(\mathbf x))= \frac{e^{-\frac{\sum x_i^{\beta}}{\theta^{\beta}}}}{\theta^{n\beta}} $ depends on $\theta$ and on $x_1,x_2,\cdots,x_n$ through $t(\mathbf x)=\sum_{i=1}^n x_i^{\beta}$ and $h(\mathbf x)=   \beta^n \left(\prod_{i=1}^n x_i\right)^{\beta-1} $ is independent of $\theta$.
Assuming $\beta$ is known, by the Factorization theorem, a sufficient statistic for $\theta$ would be
$$T(\mathbf X)=\sum_{i=1}^nX_i^{\beta}$$
Your answer is not quite right. But we can say that $e^{-T}$ is also sufficient for $\theta$, being a bijective function of $T$.


Replace CSV delimiter by pipe character

Question: I need to change CSV delimiter -> ',' (comma) to '|' (pipe).
I'm not able to blindly replace all comma characters by pipe character since some values contain comma characters.
Any ideas?
Answer: Use csvkit, you can change your delimiter safely:
https://csvkit.readthedocs.io/en/latest/
csvformat -D '[your delimiter here]' [file name]

Replace CSV delimiter by pipe character


How can I hear what a mathematical function sounds like?

Question: I'm working on differential equations homework right now, and I just came across a solution to a problem that has the form:

I graphed the function with my computer and it has an interesting waveform that I want to hear. Is there a way I can do this?
Comment: You don't need to do a Fourier analysis - it's a linear combination of cosines. The Fourier coefficients are `16/15` and `-1/15`, right there in the equation, and all of the other coefficients are zero. You could re-create this in any addative synth, e.g. ZynAddSubFX, or operator in Ableton. It will sound like a sine wave with a quiet second-octave harmonic.
Comment: The [frequency is too low to hear](https://www.wolframalpha.com/input/?i=play+(16%2F15)cos(0.5t)-(1%2F15)cos(2t)).
Comment: @Dom that depends on the units of _t._  It could be milliseconds, microseconds, hours, nanoseconds...
Comment: You could try doubling the frequency once or twice or three times, then do a Fourier analysis of it to get its spectra, and then re-create it with an additive synth. I feel like somewhere out there, there must be a synth that will accept an equation for a waveform, but I don't know for certain. I wonder if you would get a good answer at the software recommendations stack exchange.
Comment: @sova: Yes, the numbers outside the `cos`s are basically scaling factors. The number inside the brackets defines the frequency. Try putting `*cos(b*x)` (replace `a` and `b` with real numbers) into https://www.desmos.com/calculator, and mess around with the values for a and b. You'll quickly understand how those two coefficients affect the plot. Then try something like `cos(x) + cos(2*x)` to see how the addition works.
Comment: You can feed **any** vector of values to various DAC-like tools which will convert the data into audio output.  People have done this with the digits of pi, among other wacky things.
Comment: @naught101 thank you for your excellent insight!  Would you be so kind as to elaborate on how you know the 2nd octave harmonic is softer?  Is it the -1/15 term ? or does it have to do with the .5t and 2t
Comment: Some DAWs come with a built-in instrument that interprets math functions. In [LMMS](https://lmms.io) 1.3, an Xpressive instrument and with the function `16/15 * sinew(t/2) + -1/15  * sinew(2t)` realizes this function, where `t` is the time since the start of a note played times that note's frequency.
Comment: Use my simple web app: [Equation Audio](https://zaz.github.io/equation_audio/#.2%20sin(t*440*pi*2)*exp(-(t-1.1)%5E2*exp((t-1.1)%5E2))%20+%20.2%20sin(t*554.365*pi*2)*exp(-(t-3.0)%5E2*exp((t-3.0)%5E2))%20+%20.2%20sin(t*659.225*pi*2)*exp(-(t-5.0)%5E2*exp((t-4.9)%5E2)))
Answer: As naught101 says, your particular case here is a sinusoidal wave with a quiet third harmonic. To hear what this sounds like at an audible frequency, go to http://meettechniek.info/additional/additive-synthesis.html in a browser that supports the Web Audio API (like Firefox or Chrome), turn the audio on, and set it like this:

H1 there represents your (16/15)cos(½ t), although as the default frequency of this online synthesizer is 440, we've effectively scaled it to cos(440 × 2π × t), and (16/15) has just been normalised to '1.000'. H3 represents the -(1/15)cos(2t) bit, again scaled up in frequency - ideally the volume would be 0.0625, which is 1/16 of the volume of the fundamental (H1), but 0.065 is close enough.
You may not find it sounds that interesting after all! In fact all waveforms that are strictly periodic with no variation tend to sound quite boring (to me at least) - they'll all just be a static hum or buzz. It's usually the variation in the shape of the waveform over time that makes it sound interesting.
Because of the nature of that particular equation it's easy to reproduce its output in an additive synthesizer. In the more general case, one way to hear an equation is to sample its output - generate the 'y' for certain values of 't' (at a certain sample rate such as 44.1 kHz, which would generate 44100 samples per second) - and play back the list of y values as PCM digital audio data.
As an example, one audio editor I use to do this is the (quite old) Adobe Audition 1.5, that can load in a text file, interpret each line as a sample value, and play the resulting waveform back like a WAV or any other audio file. To do this, it wants the y values scaled to fit within the range of 8-bit or 16-bit data (e.g. within −32,768 to 32,767 for 16-bit) and rounded to the nearest integer, so the text file would look like (e.g.)
3917
4587
5387
4645
3024
1911
791
-632
-1901
-2554
-2124
-1234

You could ask on https://softwarerecs.stackexchange.com/ to see if there's any newer / free audio editor that can import textual sample data like this.
If you can do any coding at all, it should be fairly easy to find a library that can write audio files (e.g. the Python language has the 'wave' module) once you have generated a list of sample values, so you can easily write an audio file in a common format from your program.
This kind of sampling is likely to be what Dom's excellent wolframalpha suggestion will be doing internally, though I couldn't get it to work in my browser! To get your equation into the audible range, you could scale it - e.g. using (16/15)cos(250 * 2π * t)-(1/15)cos(1000 × 2π × t) will give you a wave with a fundamental frequency of 250Hz (assuming t is in seconds).
One thing to watch for when sampling is aliasing - to avoid this, you need to sample at a rate of at least double the value of any frequency component of the waveform generated by the function.
Answer: You don't need any specific audio software to generate audible waveforms. Here's a simple C program that will generate the required data on standard output:
#include <stdint.h>
#include <stdio.h>
#include <math.h>

double y(double t) {
  return (16 * cos(t/2) - cos(t*2)) / 15;
}

double pitch = 440 * 2*3.14159;  // so the base pitch will be a standard A note

int main() {
  int16_t v;
  char* p = (char*) (&v);  // "buffer" for standard output
  double t=0;

  while (t+=1./44100) {
    v = (int16_t) ( y(t*pitch) * (2<<12) );
    putchar(p[0]);putchar(p[1]);  // disclaimer: this is NOT good programming
    putchar(p[0]);putchar(p[1]);  // style, just a quick hack to output data
  }
  return 0;
}

Save a signal.c, and execute
gcc signal.c -lm && ./a.out | aplay -f cd

This should work right out of the box, in a normal Linux install (e.g. Ubuntu).
Comment: Well yeah... but the physics units are a bit messed up anyway here; it doesn't really make sense to consider cos(2 ⋅ _t_) if _t_ is a time.
Comment: `You don't need any specific audio software`, when you write your own software...
Comment: maybe `double pitch = 440; double angularVelocity = pitch *  2* 3.14159`?
Answer: The question assumes that the waveform at stake is directly human hearable. If that would be the case, an alternative approach to the programmatic one would be to use an additive synthesizer to synthesize the waveform. For those into the computer music/DAW realm, there are a number of free VST synthesizers that perform additive synthesis, and I remember at least one (would have to look for it in my backup archives) that directly genererates a waveform from a mathematical function expression.
However, the presented function is NOT human hearable. It's a combination of 2 sine waves of frequency:

f1 = 0.5 /(2*Pi) = ~0.32 Hz
f2 = 2 / (2*Pi) = ~3,14 Hz

Human hearing starts at around 20Hz, so the presented function is not direcly hearable. In order to have a sonic rendering of the function, we will have to apply some sort of a "sonification" process, i.e., apply some sort of transformation to the function that puts it into the range of human hearable audio. In this case a simple frequency multiplication, say, by a 100, would do the trick, and allow the application of the methods indicated in previous answers. But there a lot very diverse and interesting techniques that can be used to "sonify" any set of sample data.
A wealth of information can be found by searching for "sonification" but for those interested who don't already have a starting point, I suggest trying the free online Earsketch environment from Georgia Tech university. It's a complete interactive music programming environmnt based on the Python syntax, so if you're already familiar with Python that helps a lot, but Python is an easy to learn language anyway. It's totally online, you don't have to install anysoftware.
A specific chapter of the Earsketch online tutorial talks about sonification.
Here's a data sonification shared Earsketch example project (in this case, weather data). It's quite easy just to replace your own data.
Comment: The OP didn't include any physical units. It could as well be _f₁_ = (0.5 min⁻¹) / 2π ≈ 0.0013 Hz, which is even further into the subsonic. Or, more sensibly, it could be understood as referring to an _arbitrary time scale_, i.e. the base frequency is ad libitum.
Answer: Equations could be fed into e.g. SuperCollider. Another option is to "fencepost" the equation and convert the value of the equation at those points into a pitch (and possibly also a duration, perhaps based on the slope at that point, or whatever), though this will require some amount of fussing to appropriately scale the fenceposts (what the x values are) and output (y values) to fit into a suitable ambitus:
% perl -e 'for $x (0..10) { printf "%d\n", 60 + 10 *( 16/15*cos(.5*$x) - 1/15*cos(2*%x) ) }'
70
68
65
60
54
50
48
49
52
57
62
% perl -e 'for $x (0..100) { printf "%d\n", 60 + 10 *( 16/15*cos(.5*$x) - 1/15*cos(2*%x) ) }' | atonal-util pitch2ly --mode=absolute | ly-fu --instrument=orchestral\ harp --open --absolute -


How to display empty XML tag in MS SQL Server

Question: I have a requirement of exporting my data into a XML format. For simplicity, consider that I have a table Employee with FName,MName and LName columns. To export the data into XML, I have written the following query
SELECT  FName, MName, LName from Employee FOR XML PATH ('Emp Details'), ROOT ('Details');
This return the data in correct XML format. However, if there is any row with NULL value, it skips the XML tag for that column. Like in following example MName had a NULL value therefore the tag for MName was missing in the XML as well:-
<Emp Details>

    <FName>Rohit</Fname>
    <LName>Kumar</LName>

</Emp Details>

I have tried using ELEMENTS XSINIL method but it displays the tag like
<MName xsi:nil="true" />

however, I want it to be displayed as
<MName />

Is it possible to display the NULL value XML tags in such a manner?
Thanks
Comment: Use `''` instead, that'll force the node to be displayed. So `ISNULL(MName,'')` would force the node to appear, but blank.
Answer: If you want to have an empty MName element in the result, just convert the NULL value to an empty string in the select statement:
SELECT  FName, coalesce(MName, '') as MName, LName
from Employee
FOR XML PATH ('Emp Details'), ROOT ('Details');

coalesce is the ANSI standard way of converting NULL  values to something, SQL Server accepts this as well as the SQL Server specific IsNull.
Answer: As I mention in the comments, wrap the value with ISNULL to return a blank string:
SELECT Fname,
       LName,
       ISNULL(MName,'') AS MName
FROM (VALUES('Rohit','Kumar',NULL))V(FName,LName,MName)
FOR XML PATH('Details'),ROOT('EmpDetails'); --Nodes can't have spaces in their names

This returns the below XML:
<EmpDetails>

        <Fname>Rohit</Fname>
        <LName>Kumar</LName>
        <MName></MName>

</EmpDetails>

Note that SQL Server does not generate blank nodes using the shorter syntax, it will explicitly open and close the tags.
Comment: Thanks, its working now. But can we restrict the empty tag as ``````. Although I believe, XML considers both the same.
Comment: @Kartikeya I address that in the answer.


Shifted log-normal distribution and moments

Question: I already know how to get the moments if $X$ is log-normally distributed. But what happens when $X$ is being shifted: $Y=aX+b$, $a>0$ and $b>0$. How to compute the moments of $Y$?
Answer: We have
$Y^n=(aX+b)^n=\sum_{k=0}^n \binom{n}{k}(aX)^k b^{n-k}$
so
$\mathbb{E}Y^n=\mathbb{E}(\sum_{k=0}^n \binom{n}{k}(aX)^k b^{n-k})=\sum_{k=0}^n \binom{n}{k} b^{n-k} a^k \mathbb{E}X^k$.
The rest remains on what is $X$ (i.e. what are its $\mathbb{E}X^k$ moments). For log-normal distribution we have
$\mathbb{E}X^k=e^{k\mu+k^2\sigma^2/2}$.
Thus
$\mathbb{E}Y^n=\sum_{k=0}^n \binom{n}{k} b^{n-k} a^k e^{k\mu+k^2\sigma^2/2}$.
I don't immediately see whether this has a closed-form (someone might supplement this).
Comment: @MinPien: I don't think you can bypass integration in this case. Realizing simplifications, such as the very good idea suggested by Glen_b, may be very helpful.
Comment: Thank you Tamas, You made me happy! What if n is being replaced with real number t ?
Answer: You have $Y=aX+b$, but the multiplication by $a$ still leaves you with a lognormal, not really changing anything. If $X\sim \text{logN}(\mu,\sigma^2)$ then $aX\sim \text{logN}(\mu+\log(a),\sigma^2)$, so if you know how to compute moments for a lognormal you can do it for $aX$ as easily as for $X$.
So for $X\sim \text{logN}(\mu,\sigma)$ the problem reduces to working out moments for a simple shift, $Y=X+\gamma$.
You have an answer for raw moments, but I presuming that apart from the mean you want central moments.
So we already have $E(Y) = E(X)+\gamma$ for the mean.
The central moments (and functions of them, like skewness or kurtosis) are all unaffected by the location-shift.


Why is PHP -> MSSQL very slow when the DB is not on the same machine as the PHP code

Question: In the course of trying to move our website to Azure, we've found a problem with our PHP code talking to MSSQL.
On the current dedicated host (hosting both the PHP and the DB), going to a page typically takes less than 2 seconds. I've also run the queries necessary through SMS and they take less than 1 second. The amount of data being returned by the queries is very small - 10-20 records, certainly less than 100kb in total.
With the website hosted on Azure (connecting to an Azure SQL database) the same page takes around 40 seconds to load. Further investigation showed that this might be caused by the database not being on the same machine as the PHP - when the original website is pointed at a remote database (either another dedicated machine or the Azure SQL instance) the page load time goes up into the 40 second range.
In the Azure case, both the website and db are located in the same region (N Europe). When testing using our machines, both are located in the UK.
The current webhosting machine is running PHP 5.4 and Microsoft SQL Server Express Edition.
The Azure website is running on PHP 5.4.
In both cases we're using the 3.0.1 Microsoft SQLSRV drivers
How can we improve the performance when connecting to a remote SQL DB?
I've cross-posted this here in response to the same question on stackoverflow:
https://stackoverflow.com/questions/15835623/why-is-php-mssql-very-slow-when-the-db-is-not-on-the-same-machine-as-the-php
Comment: I don't know mssql that well, but does it try and look up dns entries for remote connections?
Answer: There are lots of things that could cause this. The trick is to whittle it down to the correct one. The most likely causes are Network issue, or connection issue, or DB issue. In this order:
First thing I would try is to rule out a network issue: try pinging the DB server from the Web server. Is the connection string using dns or ip? Does pinging dns vs ip make a difference?
If ping times are normal and fast, could it be a DB login issue? Can you connect to the DB server from SSMS? Is it fast?
If still everything is fine, run the query the website runs using SSMS- is it still fast? If not, it's a DB issue- the new DB is probably not identical to the original. Perhaps certain indexes/constraints didn't get copied over.


Linear congruence proof, show congruence has exactly two incongruent solutions

Question: Let p be an odd prime and k a positive integer. Show that the congruence $x^{2}$ $\equiv 1 \ mod p^{k}$ has exactly two incongruence solutions, namely, $x \equiv \pm 1\mod p^{k}$.
I'm not sure what to do after this:
$x^{2}$ $\equiv 1 \ mod p^{k}$ => $p^{k}$ | $x^{2}-1$=(x-1)(x+2)
Comment: Observe that $p^k$ is relatively prime to one of $x-1$ or $x+1$. So it must divide the other.
Comment: Related : http://math.stackexchange.com/questions/345668/solutions-of-the-congruence-x2-equiv-1-pmodm
Answer: As you have already observed, $p^k\mid (x-1)(x+1)$. In particular $p\mid (x-1)(x+1)$, so either $p\mid x-1$ or $p\mid x+1$. In any case, we cannot have both since $p\not\mid 2$. This implies that $p^k\mid x-1$ or $p^k \mid x+1$. Why?
This works in general: $x^2=n\mod p^k$ has at most two incongruent solutions.
Comment: How does the p∤2 part fit it? Since we're looking at p^k, can we still use p∣x−1 or p∣x+1 in our reasoning?
Comment: @DJ_ Right, we know that $p\mid x-1$ or $p\mid x+1$. But we cannot have both, since this would imply $p\mid x+1-(x-1)=2$, which is impossible. This means that we can assume WLOG that $p\not\mid x-1$, and?


Number field that deletes non-numbers without clearing previous numbers?

Question: I am using:
<code><input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')">
</code>
I use it to prevent the user from entering anything except a number into a field on my page. However, I noticed that if the user types a number first but then accidentally hits a non-number key, the field is cleared and they have to start over. This may cause frustration so I was wondering if there was a way to tweak the code so that it does not do this, or if there was a similar method I could use. I am limited to JavaScript, JQuery, and HTML. Any help would be appreciated! :)
Comment: Meh, there's no reason to allow a user to enter known-bad data. If I was doing client-side validation anyway, why let someone enter a letter for a US Social Security Number? There's no reason to delay feedback--as long as there's feedback, e.g., a fading warning about accepting only digits etc.
Comment: I can't reproduce the described behavior. Nevertheless, this is bad UI design. You should allow the user to enter whatever it wants (letters, symbols) and then run a validation for a number. The current kind of treatment can have unexpected side-effects (as you describe) and, worse, may leave some users disturbed, even angry, because when they type, their keyboard won't work ("damn website!", they shout). Believe me, this is way more frequent than the most of us thinks it is.
Comment: Not sure what you mean; it works fine for me. Can you be more specific?
Comment: I got rid of the code above and ended up using a JS funtion. I hope this helps someone with the same issue!

$("#medianSalary").keydown(
                                    function(event) {
                                                  if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                                                        event.preventDefault();}
                                    });
});
Comment: @user3784596 I think you should validate the value after filling the form. There are easy ways to do that.
Like you can use `input type number`.

What is problem with that?
Comment: I did that at first but that the request of the client I had to simply not allow anything else in the field to be typed at all.
Answer: I found a solution for my issue. I got rid of the code above and ended up using a JS function. I put in within my $(Document).ready(function() I hope this helps someone with the same problem!
<code>$("#medianSalary").keydown( function(event) { if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) { event.preventDefault();} }); });
</code>


Language fallback stack

Question: I have 4 language versions on my website.
Is there a way to define a language fallback order?
For example, if I'm on a node page and the language is set to English and there's no English translation I'd like Drupal to look for French, then German, then Spanish translation.
Comment: Interested in this as well.
Comment: Are you talking about translating the interface (locale) or the content?
Comment: Did you ever find a solution for this?
Comment: For the interface you have this module https://drupal.org/project/language_fallback
Answer: If you have language fallback enabled, then the fallback order is the order of the languages you have set at admin/config/regional/language
Answer: You can try Language Hierarchy module.
It works with entity translation, i18n menu, i18n node translation and string translations.

Language fallback stack


Error installing Oracle-Java6

Question: I'm attempting to install Oracle-Java6 on my VPS, running ubuntu-10.04 for the purpose of running Openmeetings.  I installed the ppa webupd8team/java, updated and ran sudo apt-get install oracle-java6-installer.  At the end of the installation, I am presented with the following error message

Creating jdk1.6.0_45/jre/lib/rt.jar
  Killed
  ERROR: Failed to unpack JAR file:

jre/lib/rt.jar

Installation failed. Please refer to the Troubleshooting Section of
  the Installation Instructions on the download page.
  cannot unpack jdk6
  Oracle JDK 6 is NOT installed.
  dpkg: error processing oracle-java6-installer (--configure):
   subprocess installed post-installation script returned error exit status 1
  Errors were encountered while processing:
   oracle-java6-installer
  E: Sub-process /usr/bin/dpkg returned an error code (1)

I've tried running sudo apt-get -f install to see if that helps but am presented with the same error.
Any help would be greatly appreciated.
Comment: We usually (read: always) install java from the packages available on the oracle website instead of the OS package manager. `mkdir /usr/local/jdk-1.6.xxx/ ; tar -xzvf /tmp/jdk-1.6.xxx /usr/local/jdk-1.6.xxx ;` tends to be easier and more stable for us.
Comment: @lVlint67: & how do you update those packages later, just removing these directories & repeating the process for newer version ? but I what's the issue in installing through webupd8 ppa ?
Answer: Much prefer to install JDK using the ff:
Download package on the oracle official repo
http://www.oracle.com/technetwork/java/javasebusiness/downloads
then put the package on your prefer location e.g /opt/java
then change access permission by typing:
sudo chmod 775 jdk-6u45-linux-i586.bin
then extract the package:
sudo ./jdk-6u45-linux-arch.bin
Comment: Thanks for the tip.  I actually ended up upgrading my server's operating system to Ubuntu 12.04, then no problem.  Thanks for the response though.

Error installing Oracle-Java6


Compact and connected set in $\mathbb{R}^2$ which is locally path-connected at only one point?

Question:
Given a compact and connected set $A$ in $\mathbb{R}^2$. Can it be locally path-connected at only one point? And can it be locally path-connected at every point except one?

My thought
First I thought of the topological sine curve, which is compact and connected but not locally path-connected. But it doesn't solve the problems. Then I tried to construct a space that is locally path-connected at every point except one as
$$
A=\{(t\cos x,t\sin x):\cos x\in \mathbb{Q} , t\in[0,1]\}
$$
But this is not compact.
Do such spaces exist? Any hints would be highly appreciated.
Comment: Idea for loc. path connected at only one point: Hawaiian earring with rational radii
Comment: Cone over Cantor set is compact, path connected and locally path connected only at a single point (the top vertex). But I'm not sure about locally path connected except a single point.
Comment: @G.Chiusole Hawaiian earring is locally path connected at every point, regardless of radii.
Comment: I meant a union over circles in $\mathbb{R}^2$ with radius $q$ and centered at $q/2$ for all $q \in \mathbb{Q}$, so in particular at $(1,0)$ (and all others except $(0,0)$) this should not be path connected. But I just realized that this space is far from compact.
Comment: A trivial example for the first is the singleton: It is obviously compact, connected and path connected, and since it consists of only one point, it trivially is only locally path connected at one point.
Answer: freakish's example checks out, so credit to him. I'll just elaborate on his comment.
Let $C \hookrightarrow \{0\} \times \mathbb{R} \subseteq \mathbb{R}^2$ the ternary cantor set. and let $\mathcal{C}(C)$ be the cone over it. That is
$$\mathcal{C}(C) = (C \times I)/C \times \{1\} \subseteq \mathbb{R}^2~~.$$
Then $\mathcal{C}(C)$ is the quotient of a compact Hausdorff space by collapsing a closed subspace and thus also compact (and Hausdorff). The cone over any space is contractible (to the tip) and thus connected, but $\mathcal{C}(C)$ is locally path connected only at the tip $t := \pi( C \times \{1\})$ with $\pi$ being the projection $C \times I \rightarrow \mathcal{C}(C)$.
Locally path connected at the tip: Let $U$ be a neighborhood of $t \in \mathcal{C}(C)$. Then since $\mathcal{C}(C)$ carries the subspace topology so there is some $\varepsilon > 0$ s.t. $B_{\varepsilon}(t) \cap \mathcal{C}(C) \subseteq U$. This neighborhood is contactible via the contraction on $\mathcal{C}(C)$ restricted to $B_{\varepsilon}(t) \cap \mathcal{C}(C) \subseteq U$.
Nowhere else locally path connected: Let $x = (x_1, x_2) \in C \times I$ with $x_1 \neq 1$ and let $\varepsilon > 0$ s.t. $1 \not\in (x_1 - \varepsilon, x_1 + \varepsilon)$. Then consider the open neighborhood $(x_1 - \varepsilon, x_1 + \varepsilon) \times C$ of $x$. Since $\{ 1 \} \times C \cap (x_1 - \varepsilon, x_1 + \varepsilon) \times C =  \emptyset$, applying $\pi$ to this set yields a homeomorphism of an open subset of $\mathcal{C}(C)$ and $(x_1 - \varepsilon, x_1 + \varepsilon) \times C$. The latter is not locally path connected since $C$ is nowhere locally path connected.
Answer: At least subspaces reduced to a single point satisfy the requirements of the question.
Comment: As far as I am concerned, if $A$ is locally path connected at $a$, it means that for any open subset containing $a$, there is a smaller open set containing $a$, which is path-connected in the subspace topology. I can't see how to show that for **any** open subset containing $b$, there is a smaller open set containing $b$ which is path-connected in the subspace topology. Do I miss some point?
Comment: You're right and I'll modify my answer accordingly. However, a subspace reduced to a single point still answer your requirements.


How prove this inequaliy $\dfrac{1}{b-a}\int_{a}^{b}|f(x)|dx>\dfrac{1}{2}|f(a)+f(b)|$

Question: let $f(x)$  have twice differentiable on $[a,b]$,and such
$$f(x)\cdot f''(x)<0$$
show that
$$\dfrac{1}{b-a}\int_{a}^{b}|f(x)|dx>\dfrac{1}{2}|f(a)+f(b)|$$
I only know and  can prove follow this inequality
$$\dfrac{1}{b-a}\int_{a}^{b}f(x)dx\ge\dfrac{1}{2}(f(a)+f(b))$$
where $f''(x)<0$
But My problem can't use this methods,Thank you
I try to
$$\dfrac{1}{b-a}\int_{a}^{b}|f(x)|dx\ge\dfrac{1}{b-a}\left|\int_{a}^{b}f(x)dx\right|$$
$$\Longleftrightarrow \left|\int_{a}^{b}f(x)dx\right|>\dfrac{b-a}{2}|f(a)+f(b)|$$
and this can't usefull
Thank you very much!
Comment: your example does not satisfy the conditions, because $f(x).f''(x)<0$ but in your example $f(0)f''(0)=0$.
Comment: $f$ cannot vanish and $|f|$ is strictly concave.
Comment: Strike. The following demonstrates that strict negativity is necessary: (Is this even true?) Consider $f(x)=\sin(x)$ on $[a,b]=[-\tfrac\pi3,\tfrac\pi3]$. The claim would be that $\frac{3}{4\pi}>\frac{\sqrt3}2$.
Answer: By the conditions over $f$, $f(x)\neq 0$ for all $x\in [a,b]$. Therefore, we should have that $f(x)>0$ or $f(x)<0$ for all $x\in [a,b]$. Assume, without loss of generality, that $f(x)>0$. Then, we have that $f''(x)<0$ and then, $f$ is concave on $[a,b]$. This implies that for every $t\in [0,1]$, we have
$$
f(ta+(1-t)b)\geq tf(a)+ (1-t)f(b)
$$
then, by the monotony of the integral,
$$
\int_0^1f(ta+(1-t)b) dt \geq \int_0^1 (tf(a)+ (1-t)f(b))dt
$$
The right hand side of the inequality is $(f(a)+f(b))/2$. If we made the change of variable $x=ta+(1-t)b$, then $dt= (1/(a-b))dx$ and it follows that
$$
\int_0^1f(ta+(1-t)b) dt= \frac{1}{a-b}\int_b^a f(x)dx= \frac{1}{b-a}\int_a^b f(x)dx
$$
That is what we wanted because in this case, $f=|f|$
If $f(x)<0$, then $-f$ satisfies the same conditions and $-f(x)>0$. Then we have that
$$
\frac{1}{b-a}\int_a^b -f(x)dx\geq \frac {-f(a)-f(b)}{2}
$$
and again we obtain the result because in this case, $-f=|f|$.


Angular Sortable events work differently than using JQuery

Question: I'm seeing differences in the sortable events from JQuery Sortable and Angular Sortable although my understanding is that the Angular events and options should the same as JQuery:
"All the jQueryUI Sortable options can be passed through the directive."
https://github.com/angular-ui/ui-sortable
The following shows a jquery sortable. When an item is dragged and dropped an alert shows the index of the dropped item AFTER its dropped.
http://jsfiddle.net/L7jemdbh/
<code>$(".sort-list-horizontal").sortable({containment: 'parent', tolerance: "pointer" })
    .on( "sortupdate", function( event, ui ) { alert(ui.item.index()); } );
</code>
The same sortable using Angular has the same alert however it shows the item's index BEFORE the item is dropped.
http://jsfiddle.net/zobgawqt/
<code>$scope.sortableOptions = {
    tolerance: 'pointer',
    update: function(event, ui) { alert(ui.item.index()); }
};
</code>
Why is the Angular version different? How do I find the index after the drop?
(I also note that the containment option works in the jquery version but not in the Angular version so I've turned it off)
Answer: I don't know how Angular Sortable does it job in handling event updates but one way to ensure that your procedure runs when all updates are invoked in angularjs is to wrap it in a <code>$timeout</code>.
FORKED FIDDLE
Change:
<code>$scope.sortableOptions = {
    tolerance: 'pointer',
    update: function(event, ui) { alert(ui.item.index()); }
};
</code>
to
<code>$scope.sortableOptions = {
    tolerance: 'pointer',
    update: function(event, ui) {
       $timeout(function(){
          alert(ui.item.index());
       });

    }
};
</code>
Comment: hmm, this helped in the jsfiddle but not in my app.


What are good libraries for creating a python program for (visually appealing) 3D physics simulations/visualizations?

Question: What are good libraries for creating a python program for (visually appealing) 3D physics simulations/visualizations?
I've looked at Vpython but the simulations I have seen look ugly, I want them to be visually appealing. It also looks like an old library. For 3D programming I've seen suggestions of using Panda3D and python-ogre but I'm not sure if it is really suited for exact simulations. Also, I would prefer a library that combines well with other libraries (E.g. pygame does not combine so well with other libraries).
Comment: What are good libraries for creating a python program for (visually appealing) 3D physics simulations/visualizations? (e.g. for simulating a projectile on a 3D cartesian grid or visualizing em-fields of a moving charged particle)
Comment: http://pyopengl.sourceforge.net/
Answer: 3D support for python is fairly weak compared to other languages, but with the way that most of them are built, the appearance of the program is far more mutable than you might think. For instance, you talked about Vpython, while many of their examples are not visually appealing, most of them are also from previous releases, the most recent release includes both extrusions, materials, and skins, which allow you to customize your appearance much moreso than before.
It is probably worth noting also, that it is simply not possible to make render-quality images in real time (cycles is a huge step in that direction, but it's still not quite there). I believe that most of your issue here is you are looking for something that technology is simply not capable of now, however if you are willing to take on the burden for making your simulation look visually appealing, Vpython (which is a gussied up version of PyOpenGL) is probably your best bet. Below is a run down of different technologies though, in case you are looking for anything more general:
Blender: The most powerful python graphics program available, however it is made for graphic design and special effects, though it has very complex physics running underneath it, Blender is not made for physics simulations. Self contained.
Panda3D: A program very often compared to Blender, however mostly useful for games. The game engine is nicer to work with than Blender's, but the render quality is far lower, as is the feature-richness. Self contained
Ogre: A library that was very popular for game development back in the day, with a lot of powerful functionality, especially for creating game environments. Event handling is also very well implemented. Can be made to integrate with other libraries, but with difficulty.
VPython: A library intended for physics simulations that removes a lot of the texture mapping and rendering power compared to the other methods, however this capability is still there, as VPython is largely built from OpenGL, which is one of the most versatile graphics libraries around. As such, VPython also is very easy to integrate with other libraries.
PyOpenGL: OpenGL for Python. OpenGL is one of the most widely use graphics libraries, and is without a doubt capable of producing some of the nicest visuals on this list (Except for Blender, which is a class of its own), however it will not be easy to do so. PyOpenGL is very bare bones, and while the functionality is there, it will be harder to implement than anything else. Plays very will with other libraries, but only if you know what you're doing.
Comment: Your computer is currently totally capable of running a smooth runtime physics simulation, but you probably have to change your definition of smooth slightly. If you run your simulation in a simple while loop python will try to update as fast as possible which gives rise to a host of problems, however you can limit the rate of your while loop by simply saying something like:
while True:
rate(100)
where the number in parens is the number of refreshes per second, I have found that 20 refreshes a second is about as low as the rate can go without loss in quality, and is light on your processor.
Comment: I believe the rate function is actually built in
Comment: Thnx! Reading what you wrote I figure if I wanted to start now the best way is to begin with VPython, develop the program as far as I can with that and modify it with PyOpenGl when necessary. When do you think the average computer will be fast enough for python to produce runtime physics simulations smoothly(rough estimate)?
Comment: How would you implement that rate function? Using time.sleep(n)?
Thank you great tip!
Answer: Try PyOpenGL. It is a library that provides Python bindings to OpenGL through the Python ctypes library.
Heres a demo of this:
Comment: This screenshot is not encouraging : )
Comment: No, but it was found with a quick search. Just look at the image src.
Answer: If I needed a visualization package for python, I would start with Processing.py:
https://github.com/jdf/processing.py
This is a python binding for the java-based Processing.org codes.  A quick comparison can be found here:
http://wiki.processing.org/w/Python_Comparison
Of course, if you are not constrained to python, then Processing itself would also be a good starting point:
http://processing.org
There are also python bindings out there for Visualization Toolkit (VTK), but most of their examples are either C++ or Tk.
If all you're looking for is scene graph to move geometries around, not native vis, then I have seen some python binding for Open Scene Graph out there, eg: http://code.google.com/p/osgswig/
Good Luck!
Answer: From your question, it is not clear what you want to achieve.  Do you want to create a standalone application that can be used to control the simulation at runtime, or, create a simulation using Python that can then be viewed offline?
For the latter, you could look at Blender, an open source 3D content creation suite which includes a python scripting interface giving access to most (if not all) of the internals of the application.  Blender comes with some physics and particle libraries which might be of use and as an application is indicative of the type of software used to make visual effects for films etc.
If you want to make a standalone application to control the simulation at runtime, this is most likely not a suitable option.  However if you want to produce a series of viewable images it might be worth a look.
Comment: I want to make a standalone application that can be used to control the simulation at runtime. The graphics can be minimal if that is what is needed to make it run decently. E.g. only using lines, arrows and points to recreate a reference frame and mathematical points. If possible also simple but clean models for rigid bodies.


Thread safe code

Question: Is doing get on concurrent arraylist or concurrent map (call it MainMap)  and  doing write/update to it using the same index still a threads age operation
Comment: It depends on how the map is being modified in other parts of your code. But instead of having a map of maps, you should have a single map, whose key type is a pair of strings.
Comment: Right, but how you handle it affects the answer. One way to answer it would be to check if it's null, and if so, create a new map and put it in mainMap. They would leave your with a race condition.
Comment: @JBNizet That's great idea. I updated my code above to reflect the modified portion. If someone is updating the same value that another thread is accessing from getMyValue, is this an issue? I am not sure if ConcurrentHashmap is solving this
Comment: @JBNizet btw your suggestion won't work if I need to know all values that Key1 Own. Right?
Comment: No, indeed. That would be a good justification for keeping your design.
Comment: In the update case, what happens if `mainMap.get(key1)` returns null?
Comment: Yea I should handle it, I am just putting an example to understand threadsafety
Answer: The correct answer is that the thread safety1 depends on type of mainMap and how it is used by other threads.

It will be safe if mainMap is a concurrent map.
It will be safe if mainMap was safely published and is effectively
immutable.
Otherwise, it is not thread safe.

It is not sufficient to say that nothing else updates it at the same time as the current thread reads it.  You have to consider the memory model.

UPDATE
The extra code tells us that the code won't suffer from low level memory anomalies.  Whether it is strictly thread-safe depends on the precise specification of the intended semantics of the operations.
The problem is that you are performing atomic operations on two distinct data structures.  A sequence of atomic operations is not necessarily atomic.  Whether this matters depends on how you expect the getValue and setValue methods to behave.

1 - The classical definition of thread-safety is that a thread-safe program is one that behaves according to its specification for all executions that are allowed by the semantics of the language's (or language implementation's) multi-threaded execution model.  As you can see, it presupposes that there is a specification of some kind for the program itself.
Comment: I updated my code above to reflect the portion place it is modified. I assume that because Main is concurrentMap then everything is good. But from your answer, it seems this is not threadsafe as one can update the object while the other one is reading across 2 different methods.  If true, then how can the above example be made threadsafe.
Comment: hmm, well my concern here is the following.  Assume thread1 is processing the  overloaded toString method (which says is doing byte read/conversion). At the same time thread2 is doing putValue which is updating the same object. Will this cause an issue and if so how can this be avoided knowing that I don't have access to the class of object a ( I can only change the class above)
Comment: Your code is sufficient to guarantee that a `getMyValue` call will see either the "old" value or the "new" value.  But we can't say which one it will see if the  `getMyValue` and `updateMyValue` calls overlap in time.
Comment: Thank you. That is ok for my case. I just want to make sure I am not running into concurrency exception. However, if one thread obtained the object from the mainMap and is working on it while the other thread is updating mainMap by replaceing that object with another object. Wouldn't thread1 be dealing with corrupted object now since it processed half old object and half new object and get exception? Sorry if I am using wrong termonologies here

Thread safe code


VS2005 and Windows SDK 7.1

Question: Running the WindowsSdkVer.exe shipped with Platform SDK 7.1 does not work.
None of the .BAT files in VS 2005 get updated.
can anyone please tell me how to correct this?
Also, how do I verify that VS2005 is using Platform SDK 7.1?
There are several articles for this in MSDN but none of them for above configuration.
Also, none of them describe the concrete way / definate way of verifying this
Comment: VS2005 never used the SDK, it shipped with a private copy of the SDK files.  If 7.1 is important then do consider updating VS.
Answer: You could try to manually set the include and lib paths of the VS environment under

Tools->Options->VC++ Directories

or something like that (it's been a while).
For verification, you can add the /showIncludes parameter to the additional compiler options of the project, and /verbose:lib to the additional linker options to double check that the correct headers/libraries are being used when compiling/linking the project.
IIRC there was some kind of incompatibility between one of the newer versions of the SDK (could have been version 7) and using VS2005, but I can't recall off hand what that was.
Answer: You can use below method for using Windows SDK 7.1 with Visual Studio 2005.
Configuring Visual Studio for Visual C++ Development with the Windows SDK
In the link , you can find the contents with
"To use the Windows SDK Configuration Tool in Visual Studio 2008".
Even though it has such title, you can use the same procedure also for VS2005.

Start the Windows SDK Configuration Tool by clicking Start, then All Programs, then Microsoft Windows SDK v7.1, and then Visual Studio Registration.
Right-click Windows SDK Configuration Tool and then click Run as
administrator.
In the Windows SDK Configuration Tool, in the list, select v7.1.
Click Make Current.

VS2005 and Windows SDK 7.1


Cox regression when reference group had zero events

Question: I would appreciate some advise on an a problem I ran into.
I use SPSS for statistical analysis of a study.
The study look into how a blood test predicts mortality with patients followup of 1 year. Patients were divided into quartiles, and using the first quartile as a reference group I used Cox regression to determine the unadjusted Hazard ratios (HR) and the adjusted HR for quartile 2-4.
The problem is that the reference group (Quartile 1–the first 25%) did not have any events.
Therefore I am getting Hazard ratios of 80,000+ for the 2nd, 3rd and 4th quartiles as well as error messages under SPSS.
Can anyone advise me on what Im doing wrong?
Comment: I think the solution here is @andrea's suggestion to use your continuous covariate as continuous, rather than categorizing it. Categorizing continuous covariates is commonly done; it may make interpretation easier for clinicians, but statistically it is always a poor choice. Your situation is an example of that. Although the context differs substantially, I discussed some reasons to not categorize continuous covariates here: [How to choose between ANOVA and ANCOVA in a designed experiment](http://stats.stackexchange.com/questions/24077//24080#24080) (especially below "**Update**").
Answer: Well, what you're doing wrong is using as the reference group a group with zero events. Instead of hazard ratios, think in simpler terms (in my opinion) of incident rate ratios (IRRs), where the incident rate (IR) is $IR=\text{number of cases }/\text{ total person-time}$.
$$IRR_{\text{quartile 4 vs. quartile 1}}=\frac{IR_{\text{quartile 4}}}{IR_{\text{quartile 1}}}$$
What happens if $IR_{\text{quartile 1}}=0$?
You can change your categorisation (use tertiles or some other meaningful categorisation) or, even better, if you have a continuous predictor you can treat it as such and examine potential nonlinear relationships using polynomial terms, fractional polynomials or restricted cubic splines, for example.
Comment: +1 for "you have a continuous predictor you can treat it as such and examine potential nonlinear relationships using polynomial terms, fractional polynomials or restricted cubic splines", which I think is the real solution here.
Comment: Thanks for the advice. Quartiles really capture the data well. Especially when I have 2 outcomes (Death and heart attacks) and the Kaplan Maier curves come out really well. Its frustrating that after a full year there has been no events in the reference group for heart attacks (ok not frustrating its actually great for the patients) and there is an incremental rise across the remaining quartiles. Was hoping there was a small trick to it that I'm missing... But if what you say is true then there is no way I can use Cox regression to get the HR when the reference has zero events

Thanks again
Answer: To supplement andrea's response by extending it a bit to hazard ratios:
The hazard of an event is the instantaneous probability of an event occurring at time t, conditional on it not having previously occurred.
Your problem should be clear instantly - with no events, the probability is zero. Borrowing from andrea's example, the incident rate is equivalent to a constant hazard - in your case, a constant hazard of zero.
Dividing by zero tends to make software angry.
You need to switch your reference category. My suggestion is to use "Quartile 4" or the other high value of the category, and step down, rather than using Quartile 1 and stepping up. If you were hoping to, for example, show an increase in the HR as you moved up a category, you're now showing the equivalent protective effect from moving down one.
I would also suggest taking a moment to consider why you have no events.
It's possible you're simply having a run of "bad luck", at which point there's nothing you can do but increase the study size or follow the population for longer in hopes of accumulating more events. But you should make sure there's no reason that the probability of having an outcome in your population isn't zero for a reason. For cardiac events I can imagine one, but it is always worth stopping to consider when you have zero events in some level of a covariate.
Comment: @HishamC.Hassan Instead of dividing by zero by using Q1 as a reference, you're dividing zero *by* the reference. You'll still get unstable results for the HRs involving Q1. The difference is that's one unstable result, instead of *all* unstable results.
Comment: My population is high risk for heart attacks. The test used is a new one. Its remarkable that all the patients in Q1 didn't get a heart attack after 1 year (in a population known to have a 30% event rate in the 1st year). This is with n=400. The data is exciting but not sure the best way to present it with 0 events in Q1.Tried using Q4 as reference but still getting HR of 1000 for Q1. I think the best suggest is Andreas-tertiles & reanalyse the whole data.Or wait until something happens in Q1 :p Thanks for taking the time to explain things. Happy to hear any others suggestions or advise...


Calling an async middleware inside of another async middleware in Express.js?

Question: Is it possible to call an async middleware inside of another async middleware in Express.js?
Whenever I try to do so, it doesn't execute in the order I would like it to.
I want them to execute in order and have an output of First, Second, Third.
Could anyone explain why or how I can achieve what I'm trying to?
const first = async (req, res, next) => {
  console.log('First');
  next()
}

const second = async (req, res, next) => {
  await first(req, res, next);
  console.log('Second');
  next();
}

router.get('/logs', second, async (req, res) => {
  console.log('Third');
  res.send('Done');
});

// Console Output:
// First
// Third
// Second

If I don't execute first() inside of second() it works just fine, but for something I'm doing I want to be able to execute the middleware inside of the other.
const first = async (req, res, next) => {
  console.log('First');
  next()
}

const second = async (req, res, next) => {
  console.log('Second');
  next();
}

router.get('/logs', first, second, async (req, res) => {
  console.log('Third');
  res.send('Done');
});

// Console Output:
// First
// Second
// Third

Answer: You passed next to the first function, which will call the route handler, instead of second code
You have to pass a new callback
const first = async (req, res, next) => {
  console.log('First');
  next()
}

const second = async (req, res, next) => {
  await first(req, res, () => {
    console.log('Second');
    next();
  });
}

router.get('/logs', second, async (req, res) => {
  console.log('Third');
  res.send('Done');
});

or
const first = async (req, res, next) => {
  console.log('First');
  next()
}

const second = async (req, res, next) => {
  await new Promise(r => first(req, res, r))
  console.log('Second');
  next();
}

router.get('/logs', second, async (req, res) => {
  console.log('Third');
  res.send('Done');
});

Comment: Oh wow, it worked! Thank you, you are incredible. Are you able to go into a bit of a more in-depth explanation as to why you wouldn't pass in `next` to the middleware and add it to your answer? Also, am I able to use `async` for that callback function replacing the `next`?


Weak form of heat equation with Neumann boundary conditions

Question: I'm trying to wrap my head around the ways to approach the heat problem. This time, with Neumann boundary conditions. Now, I have the theory down, but the only example I found leaves me behind by leaping to the solution without any mention of the process used to get there. So here it is:
I want the weak form of: $$- \biggl( {u' \over x^2+1} \biggl)'+u=e^x$$ $$u'(0)=u'(1)=0$$
defined in $(0,1)$
The solution simply whips out a formula that is basically the Lax-Milgram theorem $$\int_0^1 \biggl[ {1 \over x^2+1}u'v'+uv\biggl]dx=\int_0^1e^xvdx$$
Which of course guarantees the existence of one solution, assuming that the bilinear form is continuous and coercive and the functional is continuous. It makes sense, but what are the steps in between the starting and the ending points?
Thanks.
Answer: You multiply your equation formally by a test function $v\in H^1$ and integrate by parts
$$
-\int_0^1\left(\frac{u'}{1+x^2}\right)'v\,dx+\int_0^1 uv\,dx=\int_0^1 e^xv\,dx,
$$
$$
\int_0^1\left(\frac{u'}{1+x^2}\right)v'\,dx-\left(\frac{u'}{1+x^2}\right)v|_0^1+\int_0^1 uv\,dx=\int_0^1 e^xv\,dx.
$$
Using the boundary condition the non-integral term cancels and you get your weak form of the equation.
Comment: Oh, that makes so much sense, thank you very much. If you don't mind, I have a few follow up questions:
1) is it a coincidence that integrating by parts and applying the boundary conditions is essentially  like using the derivative property of any tested linear functional? i.e. $\langle  f', \phi \rangle = - \langle f, \phi ' \rangle$?
2) I assume that the only reason I can seek out this form is because I have those initial conditions. If I were to have Dirichlet's conditions instead, how would the approach change?
3) The form is weak because it came from a test function, right?
Comment: Question 1) is probably a yes, since with different conditions that non-integral term wouldn't cancel.
Comment: I do not think it is a coincidence. The idea of weakening the concept of solution by multiplying by a "test" and integrating by parts in such a way that the derivatives are now applied to the test and less regularity is required of the solution, which has been used in PDEs for a long time, naturally leads to defining "weak" derivatives in the sense of distributions. In case of Dirichlet condition, the same computation works with $v\in H^1_0$ (you start with $v\in\mathcal{D}(\Omega)$ and extend by density). The form is weak because it makes sense for less regular $u$'s (in some Sobolev space).
Comment: Wonderful, I think I got it. Thank you very much once again.


PROPFIND requests from a Microsoft-WebDAV-MiniRedir/6.0.6002 user agent on Apache server where Samba is also running

Question: Ok, here is the context. We've a server which is inside our network; on the server there is a Samba configured, providing access to a number of shares; there is also and Apache server providing other services (among them is also WebDav, but for svn folders, so they are different folders).
In the past months, I've seen that some windows machines would try to access (with PROPFIND) the same paths which they were accessing via SMB. Just to be clear, someone issuing a
<code>PROPFIND /share/directory/file
</code>
where I knew that client would access
<code>\\server\share\directory\file
</code>
Since WebDAV is not enabled on those directories, the result at the moment is a 405 status (method not allowed).
In the recent weeks, I've seen a surge of PROPFINDs from a few machines; virus-scan didn't detect any problem on them, and they seem to behave normally.
How can I disable the PROPFIND from those machines? Is this a signal of some known problem? How can I further investigate them?
Answer: Sounds like you've got Windows clients trying to use WebDAV instead of SMB.
lifting the following from one of my answers a couple months ago:
In Network Connections, Advanced menu -> Advanced Settings, make sure the "Web Client" provider is below the normal options in the provider order.

Or just disable the Web Client service.


Button growing 8 pixels when MouseOver WPF XAML

Question: I'm dealing with a rather frustrating bug. My ultimate goal is to have an image, which glows on IsMouseOver, and can be clicked to call an event. This seems all too complicated, but the other alternative I found was creating a custom user control, which is even more excessive. This is what I've done so far:

    </Style>

My button is defined as:
<Button HorizontalAlignment="Right" Margin="0,28,6,0" Name="delButton" VerticalAlignment="Top" Style="{DynamicResource DelButton}" Click="delButton_Click" />

This is what's happening:

Thanks for any suggestions.
Answer: i ran into this the other day too, and it might be that one of the images is a standard 96dpi, and the other was something else.  I had one image that somehow was 78 dpi or something else, and thats why it was getting strange sizing.
Comment: Hm this sounds like a possibility, I wasn't aware that png stored dpi information.
Comment: i wasn't either!  so i looked it up and found this as the first hit:

http://www.hanselman.com/blog/BeAwareOfDPIWithImagePNGsInWPFImagesScaleWeirdOrAreBlurry.aspx


Visualize cross over interaction logistic regression categorical variable in R

Question: I have performed a logistic regression with the following variables:

X: Categorical with three levels (St, An, Int)
M: Moderator, which has two levels (Mob,Desk)
Y: Dichotomous dependent variable (0/1)

I found no main effect of X on Y or of M on Y but I did find a significant interaction effect between level 'Int' of X with M.
Hence, I want to show a graph in which I show the cross over interaction but I can't figure out how.
I already read this question (Plotting logistic regression interaction (categorical) in R) but I couldn't rewrite this to my own dataset.
PS: I am using R in case anyone would kindly like to provide an example.
Answer: There could be many ways. One of them is to compute the predicted odds, and turn that into probability for each possible combination between X and M. Here is a short example:
<code>set.seed(144)

x <- as.factor(sample(c(1,2,3), 100, replace=T))
m <- as.factor(sample(c(1,1,2,2,2), 100, replace=T))
y <- sample(c(1,0), 100, replace=T)

m1 <- glm(y ~ x*m, family=binomial)

possibleCombo=data.frame(x = c(1,2,3,1,2,3), m = c(1,1,1,2,2,2))

yhatProb <- predict(m1, possibleCombo, type="response")*100

possibleCombo <- data.frame(possibleCombo,yhatProb)

library(ggplot2)
p1 <- ggplot(possibleCombo, aes(factor(x),yhatProb)) +
      geom_bar(aes(fill=factor(m)), position="dodge", stat="identity")
p1
</code>
The result looks something like this:


P: escolher duas select e exibir resultado

Question: Então galera, sou novo no site e tô precisando de uma ajuda urgentemente. Tô criando um site onde a pessoa seleciona cidade de origem e cidade de destino
até ai tudo bem, eu quero que quando a pessoa selecionar essas duas opções e clicar no valor da passagem, mostre um valor, porém bati cabeça pakas tentando fazer o javascript pra isso, se alguém puder ajudar fico muito agradecido

        <select name="origem" id="item1">
            <option value="sel_ori">Selecione a Cidade Origem</option>
            <option value="ori_poa">Porto Alegre</option>
            <option value="ori_fln">Florianópolis</option>
            <option value="ori_cwb">Curitiba</option>
            <option value="ori_gru">São Paulo</option>
            <option value="ori_sdu">Rio de Janeiro</option>
            <option value="ori_vix">Vitória</option>
            <option value="ori_bsb">Brasília</option>
            <option value="ori_cnf">Belo Horizonte</option>
            <option value="ori_gyn">Goiania</option>
            <option value="ori_for">Fortaleza</option>
            <option value="ori_mcz">Maceió</option>
            <option value="ori_mao">Manaus</option>
            <option value="ori_rec">Recife</option>
        </select>

        <select name="destino" id="item2">
            <option value="sel_dest">Selecione a Cidade Destino</option>
            <option value="dest_poa">Porto Alegre</option>
            <option value="dest_fln">Florianópolis</option>
            <option value="dest_cwb">Curitiba</option>
            <option value="dest_gru">São Paulo</option>
            <option value="dest_sdu">Rio de Janeiro</option>
            <option value="dest_vix">Vitória</option>
            <option value="dest_bsb">Brasília</option>
            <option value="dest_cnf">Belo Horizonte</option>
            <option value="dest_gyn">Goiania</option>
            <option value="dest_for">Fortaleza</option>
            <option value="dest_mcz">Maceió</option>
            <option value="dest_mao">Manaus</option>
            <option value="dest_rec">Recife</option>
        </select>

<input name="Enviar" type="submit" value="Valor Passagem" onclick="passagem()"/>

<input name="Limpar" type="reset" value="Limpar"/>

Comment: Porque não usa Jquery com evento de change ?
Comment: até faria, mas não tive aulas ainda que usa o JQuery e o trabalho é pra fazer no sublime ou notepad onde você faz o html/css e o javascript juntos
Answer: Segue uma soluçao que acho que pode lhe atender, fiz apenas com 2 valores, mas assim podes fazer com os demais, se quiser fazer tudo isso dinamicamente, pode avisar que lhe ajudo!!
Fiz no jsfiddle, mas tambem se clicar ali abaixo no Executar acho que ele irá aparecer para voce...
https://jsfiddle.net/5na4p3ux/

function passagem(){
 var sel_origem = document.getElementById("item1").value;
  var sel_destino = document.getElementById("item2").value;

  if (sel_origem == "ori_poa" && sel_destino == "dest_fln"){
   document.getElementById("valor-passagem").textContent = "Valor da Passagem: R$300,00"
    document.getElementById("valor-passagem").classList.remove("hide")
  } else if (sel_origem == "ori_poa" && sel_destino == "dest_fln") {
   document.getElementById("valor-passagem").textContent = "Valor da Passagem: R$200,00"
    document.getElementById("valor-passagem").classList.remove("hide")
  } else {
   document.getElementById("valor-passagem").textContent = "Destino Inexistente"
   document.getElementById("valor-passagem").classList.remove("hide")
  }
}

function limpar(){
 document.getElementById("valor-passagem").classList.add("hide")
  document.getElementById("item1").value = "sel_ori";
  document.getElementById("item2").value = "sel_dest";
}
.btns{
  width: 100%;
  text-align: center;
  margin-top: 10px;
}

.selects{
  width: 100%;
  text-align: center;
}

#valor-passagem {
  margin-top: 20px;
  color: red;
  text-align: center;
  width: 100%;
}

.hide {
  display: none;
}

<select name="origem" id="item1">
  <option value="sel_ori">Selecione a Cidade Origem</option>
  <option value="ori_poa">Porto Alegre</option>
  <option value="ori_fln">Florianópolis</option>
</select>

<select name="destino" id="item2">
  <option value="sel_dest">Selecione a Cidade Destino</option>
  <option value="dest_poa">Porto Alegre</option>
  <option value="dest_fln">Florianópolis</option>
</select>

<input name="Enviar" type="submit" value="Valor Passagem" onclick="passagem()"/>
<input name="Limpar" type="reset" value="Limpar" onclick="limpar()"/>

Comment: Ah desculpa, devia ter colocado o CSS do "valor-passagem" na div e como classe... mas tirando isso, ta aí! rsrs
Comment: valeu mano, ajudou muito, agradecido ;D
Comment: Opa, eu quem agradeço!!! Abraço!
Answer: Antes de tudo, recomendo você ler esse artigo aqui. Por falta de conhecimento de javascript.
Seu código JS está com erros de sintaxe:
function passagem(){
    var sel_origem = document.getElementById("item1");
    var sel_destino = document.getElementById("item2");
    if (item1 = ori_poa & item2 = dest_fln){
        var resultado = 200;
    }
    else{
        resultado = 0;
    }
}

O correto é assim:
function passagem() {
  var _item1 = document.getElementById("item1");
  var item1 = _item1.options[_item1.selectedIndex].value;

  var _item2 = document.getElementById("item2");
  var item2 = _item2.options[_item2.selectedIndex].value;
  var resultado = 200;

  if(item1 == "ori_poa" && item2 == "dest_fln"){
  alert("200");
  //alert(resultado);
  }
  else{
  alert("0");
  }
}

Veja funcionando em JSFIDDLE: https://jsfiddle.net/fNPvf/37053/
Comment: valeu mano, ajudou muito, deu pra tirar umas duvidas do primeiro que fiz!
Answer: Começando pelo formulário, que você já deve ter, só vou dar um exemplo de como pegar os dados dos selects com jQuery, lembrando que no exemplo vou usar um evento de submit do form, mas você pode criar uma função independente para resgatar os valores.
    <form>
        <select name="origem" id="item1">
            <option value="sel_ori">Selecione a Cidade Origem</option>
            <option value="ori_poa">Porto Alegre</option>
            <option value="ori_fln">Florianópolis</option>
            <option value="ori_cwb">Curitiba</option>
            <option value="ori_gru">São Paulo</option>
            <option value="ori_sdu">Rio de Janeiro</option>
            <option value="ori_vix">Vitória</option>
            <option value="ori_bsb">Brasília</option>
            <option value="ori_cnf">Belo Horizonte</option>
            <option value="ori_gyn">Goiania</option>
            <option value="ori_for">Fortaleza</option>
            <option value="ori_mcz">Maceió</option>
            <option value="ori_mao">Manaus</option>
            <option value="ori_rec">Recife</option>
        </select>

        <select name="destino" id="item2">
            <option value="sel_dest">Selecione a Cidade Destino</option>
            <option value="dest_poa">Porto Alegre</option>
            <option value="dest_fln">Florianópolis</option>
            <option value="dest_cwb">Curitiba</option>
            <option value="dest_gru">São Paulo</option>
            <option value="dest_sdu">Rio de Janeiro</option>
            <option value="dest_vix">Vitória</option>
            <option value="dest_bsb">Brasília</option>
            <option value="dest_cnf">Belo Horizonte</option>
            <option value="dest_gyn">Goiania</option>
            <option value="dest_for">Fortaleza</option>
            <option value="dest_mcz">Maceió</option>
            <option value="dest_mao">Manaus</option>
            <option value="dest_rec">Recife</option>
        </select>

<input name="Enviar" onclick="javascript:passagem();" type="submit" value="Valor Passagem" />

<input name="Limpar" type="reset" value="Limpar"/>

    </form>

Aqui o trecho de jQuery onde são resgatados os valores:
    $(document).ready(function() {
        $( "form" ).submit(function(){ // equivalente a função passagem
            var origem = $('#item1').find('option:selected').val();
            var destino = $('#item2').find('option:selected').val();
            if ((origem == 'ori_poa') && (destino == 'dest_fln')){
                resultado = 200;
            }else{
                resultado = 0;
            }
            alert("Valor da Passsagem: " + resultado);
        });
    });

Function completa em javascript:

Comment: em teoria até entendi, mas é que não uso o JQuery, esse projeto que tô fazendo usa só o sublime ou notepad e ao fazer o próprio html você insere no html o java, era isso que tava tentando fazer
queria que no lugar do JQuery, tivesse o código javascript, mas ae tem que mudar algumas coisas correto?
Comment: ao clicar valor passagem não aparece nada :(
esse código entraria onde? no  ??


How to check if a string is in datetime format in R?

Question: Edit: Is it possible to check if the string is in a certain format such as 'y-m-d','h:m:s'
Comment: run `str()` to see the structure of the object.
Comment: I can't seem to find the documentation on str(). But if I put a string within the str() it would just be chr in R, it doesn't check anything beyond that. @Phil
Comment: you should provide few examples of how you expect the function to behave. It would be even better if you show us that you have tried something that didn't work.
Answer: lubridate::is.timepoint(Sys.time())
#> TRUE
lubridate::is.timepoint(Sys.Date())
#> TRUE

From the documentation of ?lubridate::is.timepoint:

TRUE if x is a POSIXct, POSIXlt, or Date object, FALSE otherwise.

If you want to identify only datetimes and not dates:
lubridate::is.POSIXt(Sys.time())
#> TRUE
lubridate::is.POSIXt(Sys.Date())
#> FALSE

EDIT.
If you want to check a specific format you can try to read it with that format, if you get NA, then it is not.
For example:
is.ymd_hms <- function(x) !is.na(lubridate::ymd_hms(x, quiet = TRUE))

is.ymd_hms("2020-01-01 22:22:22")
#> TRUE
is.ymd_hms("2020-31-01 22:22:22")
#> FALSE

Without lubridate:
is.ymd_hms2 <- function(x) !is.na(as.Date(x, "%Y-%m-%d %H:%M:%S"))

is.ymd_hms2("2020-01-01 22:22:22")
#> TRUE
is.ymd_hms2("2020-31-01 22:22:22")
#> FALSE

However, lubridate gives you more flexibility. Like:
is.ymd_hms("2020/01/01 22:22:22")
#> TRUE
is.ymd_hms2("2020/01/01 22:22:22")
#> FALSE

Comment: look at my edit
Comment: Then is it possible to check if the string is in a certain format such as 'y-m-d','h:m:s'