How Many Permutations of Die Rolls Add Up to a Fixed Total?

Question: I'm toying around with the idea of designing a board game. I like the idea of a hexagon-tile setup (a la Catan). There would be some number of different resource categories; I'm trying to determine how many. Each tile would have a number from 1 to 6 associated with each resource category, representing the number you'd have to meet or beat when rolling a D6 to acquire that resource. And you'd get one die roll per resource type. In the interest of fairness, I'd like each tile to have the same total value -- probably the floor of the expected roll value times the number of different resources.
So, for example, if I only had one resource type (let's call it Resource A), then I'd want each tile to have a total value of 3, which trivially means that I'd have one unique type of tile, which had a value of 3 for Resource A. One die rolls that value in exactly one way.
If I had two resource types, Resource A and Resource B, then I'd want the total value of each tile to be 7. Brute-forcing it, I know that there are 6 different permutations of 2D6 rolls that add up to 7 (1 & 6, 2 & 5, 3 & 4, 4 & 3, 5 & 2, 6 & 1). So in that case, I'd have 6 unique types of tiles. But what if I wanted three resource types, with a total value of 10? Or four dice rolls, with a total of 14?
So I'm wondering, what is the formula for generalizing this? Specifically, the number of permutations for which n dice will add up to a total m. And explain it like I'm simple -- it's been a long while since I've done this kind of math. I'm curious for my own enrichment, as well as the (theoretically) practical application of determining how many unique tiles I could potentially include.
Comment: Does this help you? http://en.wikipedia.org/wiki/Partition_(number_theory)
Comment: That's informative, although it may take me some time to grok it. I think technically I want a composition, since order matters, but Wikipedia's page for that is much less detailed.
Answer: The number of ways for $2$ dice to sum to $n$ is obviously $0$ for $n<2$ and $n> 12$. For the others, think about how many different numbers that appear on the first die allow you to create a sum of $n$ with the numbers on the other die. For $7$, as an example, no matter what you roll on the first die there is a way to make seven with the other die. For $6$, however, you can't roll a $6$ on the first die and then get a total of $6$ on both dice.
Since for a given number on the first die there is at most one way to make the desired sum with the other die, counting this will give the desired result. It's easy to see that if $n  \le 7$ the number is $n-1$ and if $n > 7$ the number is $13 - n$.
Plotting this comes out very nicely:

Per your comment we can extend this somewhat to a more general situation: you want the number of ways to have $n$ dice with values between $1$ and $k$ sum to a value $m$. Mathematicians say that this is a $n$-composition of $m$ with largest part at most $k$.
This is a non-trivial problem. See this page. The solution turns out to be the coefficient of $x^m$ in the polynomial
$$\left(\frac{x^{k+1}-x}{x-1}\right)^n.$$
For small values of $m,n$ it's best to compute this by hand or by computer. With large values there are approximation methods, as detailed on the aformentioned link.
Comment: I realize now that I wasn't initially as clear as I'd intended to be (I've edited the original question) -- I'm interested in a generalization for finding the permutations of an arbitrary number of dice rolling an arbitrary total. Still a valuable explanation, though.
Comment: @HammerBro. I added a bit of information for the general problem.
Comment: Spiffy. Didn't realize it was theoretically so complicated. Ironically, I'm also having trouble programming a general method to compute this. But practically, if I just want to type in three or four nested for loops (which the results indicate I want), it's braindead simple. Thanks.
Answer: The number of permutations that give a sum of $k$ when rolling $n$ 6-sided dice is:
$$P\left( {n,k} \right) =\sum\limits_{i = 0}^{{i_{\max }}} {{{\left( { - 1} \right)}^i}\left( {\begin{array}{*{20}{c}}
n\\
i
\end{array}} \right)\left( {\begin{array}{*{20}{c}}
{k - 6i - 1}\\
{k - 6i - n}
\end{array}} \right)}$$
where $\displaystyle {i_{\max }} = \left[ {\frac{{k - n}}{6}} \right]$ and $\left[ x \right]$ represents the "floor" function.
For instance, the number of permutations that yield a sum $k=31$ when rolling $n=10$ dice is:
$$P\left( {10,31} \right) = \sum\limits_{i = 0}^3 {{{\left( { - 1} \right)}^i}\left( {\begin{array}{*{20}{c}}
{10}\\
i
\end{array}} \right)\left( {\begin{array}{*{20}{c}}
{31 - 6i - 1}\\
{31 - 6i - 10}
\end{array}} \right)}  =$$ $$ \left[ {\left( {\begin{array}{*{20}{c}}
{30}\\
{21}
\end{array}} \right) - \left( {\begin{array}{*{20}{c}}
{10}\\
1
\end{array}} \right)\left( {\begin{array}{*{20}{c}}
{24}\\
{15}
\end{array}} \right) + \left( {\begin{array}{*{20}{c}}
{10}\\
2
\end{array}} \right)\left( {\begin{array}{*{20}{c}}
{18}\\
9
\end{array}} \right) - \left( {\begin{array}{*{20}{c}}
{10}\\
3
\end{array}} \right)\left( {\begin{array}{*{20}{c}}
{12}\\
3
\end{array}} \right)} \right] =3393610$$
I tried to explain "step-by-step" the inner workings of that formula , using pure combinatorics arguments in my site, at this link and, honestly, this proved to be not an easy task.
Comment: A small suggestion. The last term in the formula could instead be written as ${(k−6i−1)\choose (n-1)}$
Answer: The number of times sum of $n$ dice rollings is $m$ can be found as coefficient of $x^m$ in expansion of $(x+x^2+x^3+x^4+x^5+x^6)^n$.
$Example:$ When TWO dice are rolled:
$$
(x+x^2+x^3+x^4+x^5+x^6)^2 = x^{12}+2 x^{11}+3 x^{10}+4 x^9+5 x^8+6 x^7+5 x^6+4 x^5+3 x^4+2 x^3+x^2
$$
Because coefficient of $x^7$ is $6$ in above expression, it means there are $6$ combinations that add up to $7$.
$Example:$ When THREE dice are rolled:
$$
(x+x^2+x^3+x^4+x^5+x^6)^3 = x^{18}+3 x^{17}+6 x^{16}+10 x^{15}+15 x^{14}+21 x^{13}+25 x^{12}+27 x^{11}+27 x^{10}+25 x^9+21 x^8+15 x^7+10 x^6+6 x^5+3 x^4+x^3
$$
As coefficient $x^{10}$ is $27$ in above expression, that means there are $27$ combinations that add up to $10$.


tb-megamenu how to click to open/close sub menu in mobile

Question: We are attempting to get submenus to only appear when the user "taps" the menu option on a mobile browser. This functionality works good on hover but some mobile devices don't work with hovering. We need the ability to click submenu titles in order to drop them down and then click them again to collapse them.
Answer: Then look far, the best I found in my case has been the following:
I have overridden the method (js) of tb MegaMenu and done through the function drupal

I created a copy of tb-megaMenu-frontend.js file and called tbmega-custom.js and saved in the js folder of my theme.
What added to the system through the function drupal js_alter.
In my theme in the file called template.php
<code>function mytheme_js_alter (&$javascript){
    $javascript[drupal_get_path('module', 'tb_megamenu') . '/js/tb-megamenu-frontend.js']['data'] = path_to_theme() . '/js/tbmega-custom.js';
}
</code>
I have adjusted the code to my needs. Just change the behavior of tbMegaMenuAction:
<code> Drupal.behaviors.tbMegaMenuAction = {
    attach: function (context) {
        $('.tb-megamenu-button', context).once('menuIstance', function () {
        var This = this;
        $(This).click(function () {
            if (parseInt($(this).parent().children('.nav-collapse').height())) {
                $(this).parent().children('.nav-collapse').css({height: 0, overflow: 'hidden'});
                Drupal.TBMegaMenu.displayedMenuMobile = false;
            }
            else {
                $(this).parent().children('.nav-collapse').css({height: 'auto', overflow: 'visible'});
                Drupal.TBMegaMenu.displayedMenuMobile = true;
            }
        });
    });

    //Comment this for mobile click
    //var isTouch = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion);
    //if (isTouch) {

        $(document).ready(function ($) {
            var mm_duration = 0;
            $('.tb-megamenu').each(function () {
                if ($(this).data('duration')) {
                    mm_duration = $(this).data('duration');
                }
            });
            var mm_timeout = mm_duration ? 100 + mm_duration : 500;

            $('.nav > li, li.mega').click(function (event) {
                event.preventDefault();

                var $this = $(this);

                if ($this.hasClass('mega') && !$this.hasClass('clicado')) {

                    $('.nav > li, li.mega').each(function () {
                        $(this).removeClass('clicado open');
                    });

                    $this.addClass('clicado');
                    $this.addClass('animating');
                    clearTimeout($this.data('animatingTimeout'));
                    $this.data('animatingTimeout', setTimeout(function() {
                        $this.removeClass('animating')
                    }, mm_timeout));
                    clearTimeout($this.data('hoverTimeout'));
                    $this.data('hoverTimeout', setTimeout(function() {
                        $this.addClass('open')
                    }, 100));

                } else {

                    if($this.hasClass('mega') && $this.hasClass('clicado')) {

                        $this.removeClass('clicado');
                        $this.addClass('animating');
                        clearTimeout($this.data('animatingTimeout'));
                        $this.data('animatingTimeout', setTimeout(function() {
                            $this.removeClass('animating')
                        }, mm_timeout));
                        clearTimeout($this.data('hoverTimeout'));
                        $this.data('hoverTimeout', setTimeout(function() {
                            $this.removeClass('open')
                        }, 100));
                    }

                }

            });
        });

    //}

    $(window).resize(function () {
        var windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
        if (windowWidth != Drupal.TBMegaMenu.oldWindowWidth) {
            Drupal.TBMegaMenu.oldWindowWidth = windowWidth;
            Drupal.TBMegaMenu.menuResponsive();
        }
    });
  }
 }
</code>
Comment: Thank you for this code. I use it and it works. But when I have a views block with ajax pager on the same page, the TB Mega menu click behavior gets destroyed, clicking does not open menu anymore. Can you help please?
Comment: Events associated with an item type are often lost when other copies (only lost in the new elements) are added.

Somehow as mention the events are being destroyed navgación bar.

The way to deal with elements that are added in after the page and its load is complete, it is to delegate the event to another element that does not change or refresh.

You can read more on this here:
https://learn.jquery.com/events/event-delegation/
Comment: Thank you. I do not understand this enough. Can you please give me a tip how to rewrite above code so that I have a chance to solve it by myself?
Comment: We must use `on` instead of  `click` something like:

`$('body').on('click', '.nav > li, li.mega', function (event) {
                event.preventDefault();
....
....
....
`
This code use delegation, is only needed in the click event, the rest of the code is the same.
Comment: I found out that the click event is firing multiple times if the ajax pager is used (and page is not 0). Then I found this: http://stackoverflow.com/questions/6120943/why-is-this-jquery-ajax-click-event-firing-multiple-times .... and finally I found the solution here: http://sholsinger.com/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/.  See new code below.
Answer: Because click function fires multiple times (e.g. when using a views block with ajax pager) I had to change the code like this (solution from here):
<code>        //$('.nav > li, li.mega').click(function (event) {
        $('.nav > li > a, li.mega > a').click(function (event) {

          if(event.handled !== true) {
            event.handled = true;

            //event.preventDefault();

            //var $this = $(this);
            var $this = $(this).parent();

            if ($this.hasClass('mega') && !$this.hasClass('clicado')) {

                $('.nav > li, li.mega').each(function () {
                    $(this).removeClass('clicado open');
                });
                $this.addClass('clicado');
                $this.addClass('animating');
                clearTimeout($this.data('animatingTimeout'));
                $this.data('animatingTimeout', setTimeout(function() {
                    $this.removeClass('animating')
                }, mm_timeout));
                clearTimeout($this.data('hoverTimeout'));
                $this.data('hoverTimeout', setTimeout(function() {
                    $this.addClass('open')
                }, 100));
            } else {

                if($this.hasClass('mega') && $this.hasClass('clicado')) {

                    $this.removeClass('clicado');
                    $this.addClass('animating');
                    clearTimeout($this.data('animatingTimeout'));
                    $this.data('animatingTimeout', setTimeout(function() {
                        $this.removeClass('animating')
                    }, mm_timeout));
                    clearTimeout($this.data('hoverTimeout'));
                    $this.data('hoverTimeout', setTimeout(function() {
                        $this.removeClass('open')
                    }, 100));
                }

            }

          }  //if(event.handled !== true)
          return false;

        });
</code>


Is true that $\sum_{k=1}^n\frac{[kx]}{k}\leq[nx]$, for every $x\in\mathbb{R}$ and for every $n\in\mathbb{Z}^+$?

Question: Is true that $\displaystyle\sum_{k=1}^n\dfrac{[kx]}{k}\leq[nx]$, for every $x\in\mathbb{R}$ and for every $n\in\mathbb{Z}^+$?
My work:
Let $x\in\mathbb{R}$ be given. For every $k=1,\dots,n$, define $i_k\in\{0,1,\dots,k-1\}$ such that
$$
[x]+\frac{i_k}{k}\leq x<[x]+\frac{i_k+1}{k}\hspace{20mm} (*).
$$
On one hand, we have that $[kx]=k[x]+i_k$ for every $k=1,\dots,n$.
So  $\displaystyle\sum_{k=1}^n\dfrac{[kx]}{k}=n[x]+\displaystyle\sum_{k=1}^n\dfrac{i_k}{k}=[nx]+\displaystyle\sum_{k=1}^n\dfrac{i_k}{k}-i_n$
Thus  $$\displaystyle\sum_{k=1}^n\dfrac{[kx]}{k}\leq[nx]\Leftrightarrow\displaystyle\sum_{k=1}^n\dfrac{i_k}{k}\leq i_n\,.$$
On the other hand, from $(*)$ is direct that $i_k=[k(x-[x])]$.
Thus  $$\displaystyle\sum_{k=1}^n\dfrac{[kx]}{k}\leq[nx]\Leftrightarrow\displaystyle\sum_{k=1}^n\dfrac{[k(x-[x])]}{k}\leq [n(x-[x])]\,.$$
In other words, we can assume that $x\in[0,1)$.
Now the questions is:
Is true that $\displaystyle\sum_{k=1}^n\dfrac{[kx]}{k}\leq[nx]$, for every $x\in[0,1)$ and for every $n\in\mathbb{Z}^+$?
Any simpler approach? Any thoughts?
Comment: This problem (but with the condition that $x \geq 0$ , though maybe it's not needed...) appeared on the 1981 USAMO (Problem 5) . There are some proofs here : http://www.artofproblemsolving.com/community/c6h424778p2403926
Comment: @ComplexPhi The truth of the inequality is preserved by replacing $x$ by $x+n$ for any $n$, so we may assume $x$ is positive.
Comment: You may have already looked at this, but have you tried to show that $$\sum_{k=1}^n\left(\frac{i_k}{k}-\frac{i_n}{n}\right)\le0 $$
Comment: @JohnWaylandBales yes, I tried but I don't have a clue how to proceed when one of the terms is positive.
Comment: This might help, where I show that if $n$ is a positive integer
then
$\lfloor nx \rfloor = \sum_{k=0}^{n-1} \lfloor  x+\frac{k}{n} \rfloor$: https://math.stackexchange.com/questions/184361/floor-function-properties-2x-x-x-frac12-and-nx-sum-k/1678966#1678966
Comment: Also notice that $$i_k\le k\left(x-[x]\right)<i_k+1$$ so in fact $i_k\in\{1,2,\cdots,k-1\}$.
Comment: If you let $m\in\mathbb{Z}^+$ and $0<\epsilon<1$ and let $x=m-\epsilon$ then $x-[x]=1-\epsilon$. It is then possible to show that if $p\in\mathbb{Z}^+$  $$\frac{p-1}{\epsilon}<k\le\frac{p}{\epsilon}$$ then $i_k=k-p$. This implies that the $i_k$'s form a monotonic increasing sequence. This might be a useful way of rewriting $$\sum_{k=1}^n\frac{i_k}{k}$$.
Comment: I meant to say monotonic non-decreasing.
Comment: @JohnWaylandBales thanks for the insights, actually there is an explicit expresion for $i_k$ where its non-decreasing behavior is clear. I'm going to update my progress.
Answer: Note that the function
$$f:\mathbb{R}\to\mathbb{R},f(x)=[nx]-\sum_{k=1}^n\frac{[kx]}{k}$$
is right-continuous and $1$-periodic function, so it is enough to prove that $f(x)\ge0$ for $x\in[0,1)$. Note also that the set of points of discontinuity of $f$ on $(0,1)$ is contained in
$$\mathcal{D}=\left\{\frac{p}{q}: 1\le p< q\le n,\gcd(p,q)=1\right\}$$ and that $f$ is constant on any interval contained in $[0,1)\setminus\mathcal{D}$. Therefore, in order to prove that $f(x)\ge0$ on $(0,1)$ it is enough to prove that
$f(r)\ge0$ for $r\in\mathcal{D}$.
Now, consider $r=p/q\in\mathcal{D}$ with $1\le p<q\le n$ and $\gcd(p,q)=1$.
For $k\in\{1,\ldots,q-1\}$ we define
$\phi(k)=pk-q[kr]$. Since $[kr]\le kr<[kr]+1$ we see that $0\le\phi(k)<q$, moreover, if $\phi(k)=0$ for some $k$ we conclude that $q$ must divide $k$, beause
$\gcd(p,q)=1$, which is absurd. Thus $\phi$ takes its values in $\{1,\ldots,q-1\}$. Further, $\phi$ is one to one, because if $\phi(k)=\phi(\ell)$ for some
$1\le k\le\ell<q$ we conclude that $q|(p(\ell-k))$ and again, because $\gcd(p,q)=1$ we see that $q|(\ell-k)$ and this implies that $\ell=k$ because
$0\le \ell-k<q$. Thus, $\phi$ is a permutation on the set $\{1,\ldots,q-1\}$.
Using the AM-GM inequality we have
$$\frac{1}{q-1}\sum_{k=1}^{q-1}\frac{\phi(k)}{k}\ge\left(\prod_{k=1}^{q-1}\frac{\phi(k)}{k}\right)^{1/(q-1)}=1$$
because $\phi(1)\phi(2)\cdot\phi(q-1)=1\cdot 2\cdots(q-1)$.
Thus
$$\sum_{k=1}^{n}\frac{kp-q[kr]}{k}\ge\sum_{k=1}^{q-1}\frac{kp-q[kr]}{k}\ge q-1
\ge pn-q[nr]$$
Rearranging we get $f(r)\ge0$ which is the desired conclusion. The proof is complete.
Answer: Here is a solution using induction from AoPS (credit to Martin R for finding this gem in the linked duplicate):

Let $G_{n}(x)$ denote the sum. Add the equations
\begin{eqnarray*}G_{1}(x)&=&\lfloor x\rfloor\\ \ 2(G_{2}(x)-G_{1}(x))&=&\lfloor 2x\rfloor\\ \ \vdots~~~~~~~~~~&=&~~~\vdots\\ \ n(G_{n}(x)-G_{n-1}(x))&=&\lfloor nx\rfloor \end{eqnarray*}
to get
\begin{eqnarray*}nG_{n}(x)&=&\sum_{k=1}^{n-1}G_{k}(x)+\sum_{k=1}^{n}\lfloor kx\rfloor\\ \ &\leq&\sum_{k=1}^{n-1}\lfloor kx\rfloor+\sum_{k=1}^{n}\lfloor kx\rfloor~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(\mbox{strong induction})\\ \ &=&\sum_{k=1}^{n}\Bigl(\lfloor kx\rfloor+\lfloor (n-k)x\rfloor\Bigr)\\ \ &\leq&n\lfloor nx\rfloor~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(\mbox{since }\lfloor a\rfloor+\lfloor b\rfloor\leq\lfloor a+b\rfloor\mbox{)}\end{eqnarray*}
which gives the desired result.
Answer: $$[nx] \geqslant \sum\limits_{k=1}^n \frac{[kx]}{k} = \sum\limits_{k=1}^n \frac{kx-\{kx\}}{k} = nx - \sum\limits_{k=1}^n \frac{\{kx\}}{k}\Leftrightarrow$$
$$f(x):=\sum\limits_{k=1}^n \frac{\{kx\}}{k} \geqslant \{nx\}=:g(x)$$
$f(0)=\{0\}=0$.
$f,g$ at points of differentiability are growing at a rate of $n$. Hence if the interval $(a,b)$ functions $f,g$ differentiable and $f(a)\geqslant g(a)$, even on this entire interval $f(x)\geqslant g(x)$. It remains to prove the inequality gap in the points. Break points - all rational numbers with denominators $\leqslant n$: $x=\frac{a}{m}$, $a,m$ are relatively prime.
$$f(\frac{a}{m}) \geqslant \sum\limits_{k=1}^{m-1} \frac{\{ka/m\}}{k}$$
Numerator - kind of shot $\frac{1}{m},...,\frac{m-1}{m}$, denominators -$1,...,m$. The lowest value of the summation for all permutations of the numerator is obtained when the numerator is proportional to the denominator. So $f(\frac{a}{m})\geqslant \sum\limits_{k=1}^{m-1} \frac{k}{km}=1-\frac{1}{m}\geqslant\{n\frac{a}{m}\}$


Calculating time complexity of Python while loop

Question: I have been working on DSA problems and have also been trying to calculate the time and space complexity of my solutions. I feel like I can do ok with most solutions, however there are many, like the one below, that stump me.
    while paymentTotal <= k:
        temp = heapq.heappop(heap)
        if paymentTotal + temp > k:
            break
        paymentTotal += temp
        toyCount += 1

In this case the loop seems to be able to be broken down into this (heap is a minHeap that contains random ints. k is also a random int):
k = n
p = 0
while p <= k:
     t = heap.heapqpop(heap)
     p += t

So this would mean that the loop runs while p+t <= k, but because t does not increment p in a consistent manner and k is random I am having a hard time conceptualizing what this time complexity would be. The amount of times the loop runs obviously changes based on what k is and also what ints are popped from the heap, but I am lost on how to express that mathematically and in Big O.
Comment: Think of the worst case, when the value popped is always 1 (assuming zero is not possible).
Comment: @dSisk Worse: `heappop` itself is O(lg n), not O(1), in the worst case.
Comment: Would this mean the worst case would be O(n) since it would have to run k+1 times?
Comment: That's right. I keep forgetting that heapq is lg n for push and pop.
Answer: The question to ask yourself is always "what's the worst case scenario?" Imagine an evil genie picking all your inputs to make things go as slow as possible.
In this case, k itself is a red herring, the only thing that matters is the size of the heap since with large enough k you'll have to pop the entire thing -- so that's your N (heap size). (You'll also notice that your program will raise an IndexError when that happens since you haven't accounted for that possibility.)
Errors aside, it's clear to see the loop will run N times, once for each element in the heap, and each time it will do a pop operation which is lg N, yielding N lg N as your final worst-case complexity.
One sanity-check for this result is realizing that you can sort a list by heapifying it and then popping all the elements, so it tracks with every other comparison-based sorting algorithm.
Answer: That's an output-sensitive algorithm, so take that into account accordingly: It's O(toyCount × log(|heap|)).


Access Android's system fonts in webview

Question: So iOS allows users to tap into the system font settings (dynamic type) using css for cordova apps. This article explains the process. The end result being css that looks like so.
h1 {
  font-family: -apple-system-font;
}

This is a powerful feature to have and I was wondering if Android had the same thing? I had read some articles that suggested this approach
h1 {
  font-family: 'RobotoRegular', 'Droid Sans', sans-serif;
}

But it provides no changes. Anyone have any idea if this possible with android 4.0 and up?
Comment: Shouldn't `font-family: sans-serif` use the default system font?
Comment: derp, totally forgot about that trick! Thanks, can you put this as an answer and I'll mark it correct?
Comment: just added it as an answer
Answer: You should just be able to use the default system font with the following:
h1 {
  font-family: sans-serif;
}

Comment: font-family: serif; // works for me but sans-serif not working
Answer: Not very pretty code, but this is how I achieved it:
body{
    font-family: HelveticaLight;
    src: url("file:///android_asset/fonts/HelveticaLight.ttf");
}
@font-face {
    font-family: 'HelveticaLight';
    src: url('file:///android_asset/fonts/HelveticaLight.ttf') format('woff'),
        url('file:///android_asset/fonts/HelveticaLight.ttf') format('truetype'),
        url('file:///android_asset/fonts/HelveticaLight.ttf') format('svg');
    font-weight: normal;
    font-style: normal;
}

Comment: Not really what I was asking for. Basically I want to know if I can use the built in system fonts on android like I can on iOS


Hugely ugly messy determinant - any trick to find it?

Question: Find the determinant of $$\begin{bmatrix}1 & a & a^2 & a^{3}\\
1 & b & b^{2} & b^{3}\\
1 & c & c^{2} & c^{3}\\
1 & d & d^{2} & d^{3}
\end{bmatrix}$$
This seems super ugly to attack directly by using cofactors; is there any way to simplify this?
Comment: If you view the determinant as a function of $a$, evidently it's a polynomial of degree $3$. By inspection--and understanding the basic properties of determinants--you can identify three roots immediately, so you know it up to some multiple that depends only on $b$, $c$, and $d$. Repeating this observation for the other variables pins down the determinant up to a *constant.* By choosing nice values for $a$, $b$, $c$, and $d$, you can compute that constant--and have thereby reduced the problem to finding the determinant of a single matrix with numerical entries.
Comment: Please [see this.](http://en.wikipedia.org/wiki/Vandermonde_matrix) Key word is Vandermonde.
Comment: Eric: The proof of the general result is **not** overkill. Chances are that by giving this exercise, your teacher wants you to either find one of the ideas that prove the general Vandermonde determinant, or to get your hands dirty and compute it by brute force after which the general proof will feel like a cakewalk. To be honest, it'd probably be best for your education to do both. :)
Comment: This page has several proofs http://www.proofwiki.org/wiki/Vandermonde_Determinant
Comment: Proving the general result seems to be overkill.
Comment: The general case is not fundamentally harder than the $4\times 4$. Anyway, you can take the idea for a general proof and specialize it to the $4\times $$.
Comment: I don't quite understand. Could you post a detailed answer? Also, note that this is the first assignment after the introduction of the concept of determinant.
Comment: See: http://math.stackexchange.com/questions/525334/vandermonde-determinant-by-induction and http://math.stackexchange.com/questions/275202/vandermonde-determinant
Answer: There is a way to simplify this. You can row reduce it. For starters, add the negative of the first row to every other row to get zeroes along the first column. You can keep doing this until the matrix is upper triangular. By then, you just multiply the diagonal entries.
Comment: Yes, I know this. I'm not saying that the thing can't be computed; it's just that you end up with a huge polynomial that needs ugly grouping and factoring to get to the one gotten by the Vandermonde formula. Is there a more straightforward way to get a clean formula?
Comment: If every element in a row contains the same factor, you can pull that out.  If you try the suggested row reduction, and then pull out common factors, the next step of row reduction will not be so bad.  You will have to make use of an algebra fact, namely that $x^n-y^n$ factorizes.
Answer: A direct computation, together with a factorization is not difficult at all. We obtain
$$
\det\begin{pmatrix}1 & a & a^2 & a^{3}\\
1 & b & b^{2} & b^{3}\\
1 & c & c^{2} & c^{3}\\
1 & d & d^{2} & d^{3}
\end{pmatrix}=
(a - b)(a - c)(a - d)(b - c)(b - d)(c - d)
$$


Set DateEdit with a date 3 years ahead of other DateEdit in Javascript

Question: I have a javascript function with does the following;
<code><dx:ASPxDateEdit ID="txd_DOM" runat="server" Height="16px" Theme="MetropolisBlue" ClientInstanceName ="txd_DOM">
  <ClientSideEvents DateChanged="function(s, e) {
                  txt_Testing_Date.SetDate(txd_DOM.GetDate());
                                 }"/>
                        </dx:ASPxDateEdit>
</code>
It Sets a datedit box to the same date as another date edit.
However I want it to set the date for txt_Testing_Date to 3 years ahead of the date in txd_DOM
I'm relatively new to this so any Help would be great!!
Answer: I'm not familiarized with the technology you are using but try this, please:
<code>   <dx:ASPxDateEdit ID="txd_DOM" runat="server" Height="16px" Theme="MetropolisBlue" ClientInstanceName ="txd_DOM">
      <ClientSideEvents DateChanged="
            function(s, e) {
                 var date = txd_DOM.GetDate();
                 var newDate = new Date(date.getFullYear() + 3, date.getMonth(), date.getDay());

                 txt_Testing_Date.SetDate(newDate.getDate());
            }"/>
   </dx:ASPxDateEdit>
</code>
Comment: You sent me on the right lines.
It was actually;
function(s, e) {
 var date = txd_DOM.GetDate();
var newDate = new Date(date.getFullYear() + 3,                  date.getMonth(), date.getDay());
txt_Testing_Date.SetDate(newDate);
}


RxJava2 flatMap operator

Question: I'm try to use the flatMap operator to make two request using retrofit on Android. The idea is make the first request to get the users and after that make the second request which I need to know the total of users that I get to make the second request. This is the way I'm trying to do it.
remoteDataSource.requestAuthors()
            .flatMap {remoteDataSource.requestAvatars(it.size) }
            .subscribeOn(Schedulers.io())
            .subscribe {
                //here I need the authors and avatars to create the new object
            }

Is the flatMap the correct operator to do that? Thanks!
Answer - Yes!
Updating
In that case, should I do something like that?
override fun requestAuthors(): Observable<List<AuthorResponse>> {
        val authors = mutableListOf<Author>()
        val authorResponse = remoteDataSource.requestAuthors()
            .doOnNext { authors.addAll(it) }
            .flatMap { remoteDataSource.requestAvatars(it.size) }
            .subscribeOn(Schedulers.io())
            .doOnNext {avatars->
                avatars.results.forEach { avatar ->
                    authors.forEach { author ->
                        author.avatarUrl = avatar
                    }
                }
            }

        return authorResponse

    }

Comment: *Is the flatMap the correct operator to do that* yes
Answer: I think, flatMap is a great operator to do stuff like this. You will handle errors from each request and they will execute one after another.

If you need to do something between these two requests, use doOnSuccess() operator.
remoteDataSource.requestAuthors()
                .doOnSuccess { /*interact with authors*/ }
                .flatMap {remoteDataSource.requestAvatars(it.size) }
                .subscribeOn(Schedulers.io())
                .subscribe {
            /*interact with avatart*/
        }

Comment: Then you need one foreach loop for both collections. And obviously they both should have the same number of elements.
Comment: authors.forEachIndexed { index, author ->
        author.avatarUrl = avatarsList[index]
    }
Comment: I think, you will assign the last avatar in list to all authors in your code.
Comment: Acutally not, I need assign each avatar for each author.

RxJava2 flatMap operator


How to replace an SC-Duplex-switch with an SFP switch?

Question: Currently I have some switches in our network, which use (besides the Fast Ethernet ports) also optical fiber with two SC-Duplex-Connectors (one in and one out). Now I want to replace these old devices by a newer model, but unfortunately modern switches mainly use the SFP interface for optical fiber, which is not directly compatible with our SC-Duplex connectors.
What combination of devices and modules/adapters would be the most sustainable solution to this problem? I mean, if a buy a modern SFP Switch, what would I need to do to connect my SC-Duplex-Connectors?
Answer: Seems like the most simple solution would be to purchase SC-to-LC patch cables.
Comment: Of course it is. :) That's the problem you're trying to solve. The fiber cores are the same diameter, though, regardless of what the connector looks like. Just make sure to get fiber that is compatible with the rest of your fiber plant.
Comment: As far as I know the SC-connector is bigger in size than the LC-connector. Is that not a problem?


Eloquent Javascript - correlation and coefficient

Question: Currently I'm reading Eloquent Javascript book and at chapter 4. This topic entitled 'The lycanthrope's log ' is very confusing to me. How important is correlation and coefficient in real world programming?
I'm trying to understand the formula used to find correlation. I've far forgotten maths since I left my high school. Could, someone who've read this book, explain to me in detail, please? Below is the picture I'm wondering about..
Comment: When you say "correlation *and* coefficient", you appear to be talking about two things -- what coefficient do you mean, besides the correlation?
Answer: The formula is actually pretty straight forward. Consider the table from your question.

The table states that there were a total 90 observations

Out of all 90 observations:

76 times, no pizzas or squirrel
9 times, pizzas but no squirrel
4 times, squirrel but no pizzas
1 time, both squirrel and pizza

So we want to find out how Pizzas & Squirrels are related:

Consider the equation along with your table now,
(since squirrel is on the left)
n00 denotes an observation where there was no squirrel or pizza (1)
n01 denotes an observation where there was no squirrel but pizza (2)
n10 denotes an observation where there was squirrel but no pizza (3)
n11 denotes an observation where there was both squirrel but pizza (4)

n0. refers to the sum of all measurements where we have no squirrel
n.0 refers to the sum of all measurements where we have no pizza
n1. refers to the sum of all measurements where we have squirrel
n.1 refers to the sum of all measurements where we have pizza

Now that we know what these values are, let's plug them in to our formula:
$$    \mathit{correlation} = \rho = \frac{ 1 \times 76 - 4 \times 9}{\sqrt{5 \times 85 \times 10 \times 80}}$$
Comment: It might be worth noting that if you code the binary variables for "no-squirrel/squirrel" and "no-pizza/pizza" as (0,1) (or indeed any other two distinct values where the "no" part is either lower for both or higher for both) then this is actually the same as the ordinary correlation coefficient.
Comment: Well, tbh I had to research the thing first :P
Answer: Maybe it's too late since this question was asked 5 years, 9 months ago. But I hope my explanation will help you to understand the phi coefficient in this book better. Things we know from this book are:

The first variable is the squirrel.
the second variable is the pizza.
If the variable is false it is 0.
If the variable is true it is 1.

Based on that we can compile the first line of the phi coefficient's formula:

n11 both of the variables are true (both squirrel and pizza are true): the value is 1.
n00 both of the variables are false (both squirrel and pizza are false): the value is 76.
n10 the first variable/squirrel is true but the pizza is false: the value is 4.
n01 the first variable is false and the second is true: 9.

So, for the second line (√ n1• x n0• x n•1 x n•0), we need to see where the number and the dot (.) are located. If the dot is after the number, then we are talking about the first value which is a squirrel with 0 or 1 indicating the true or false. And vice versa. For example:

n1. : the dot is after a number so we are talking about the first variable which is a squirrel and 1 is true, so we need to sum everything where the squirrel is true (4 + 1)
n0. : the squirrel is false (76 + 9)
n.1 : the dot is before the number so we are talking about the second variable which is pizza and 1 is true, so we need to sum everything where the pizza is true (9 + 1)
n.0 : the pizza is false (76 + 4)

I hope my explanation will help anyone in the future who stumbles upon this problem and grasp the concept as easy as possible. Cheers!


Split Python list of strings into seperate lists based on character

Question: I'm trying to figure out how to split the following list into separate lists based on a character in the list.
list = ['@', '2014', '00:03:01', 'Matt', '"login"', '0.01', '@', '2014', '02:06:12', 'Mary', '"login"', '0.01']

I want to create a list after every "@" symbol is introduced. For example, I would want the output to be the following:
NewList1 = ['@', '2014', '00:03:01', 'Matt', '"login"', '0.01']

NewList2 = ['@', '2014', '02:06:12', 'Mary', '"login"', '0.01']

Is this possible?
Comment: Don't name you `list` `list`, you are override the build in `list()`.
Answer: You could use itertools.groupby:
import itertools as IT
import operator

seq = ['@', '2014', '00:03:01', 'Matt', '"login"', '0.01', '@', '2014', '02:06:12', 'Mary', '"login"', '0.01']

groups = (list(g) for k,g in IT.groupby(seq, lambda item: item=='@'))
print(list(IT.starmap(operator.add, IT.izip(*[groups]*2))))

prints
[['@', '2014', '00:03:01', 'Matt', '"login"', '0.01'], ['@', '2014', '02:06:12', 'Mary', '"login"', '0.01']]

Comment: Not sure the `starmap` is necessary given it's a constant grouping var:  `groups = [['@'] + list(g) for ... if not k` is possibly more straight-forward...
Answer: Like this:
>>> lst=['@', '2014', '00:03:01', 'Matt', '"login"', '0.01', '@', '2014', '02:06:12', 'Mary', '"login"', '0.01']
>>> [item.split() for item in ' '.join(lst).split('@') if item]
[['2014', '00:03:01', 'Matt', '"login"', '0.01'],
 ['2014', '02:06:12', 'Mary', '"login"', '0.01']]

So what this basically does is join the list together, re-split it on @ and then converts each group back to a list.
Comment: Once you got a `@` in any of those elements you are suddenly in trouble.
Comment: You could just do `['@']+item.split()` instead of just `item.split()` in the list comprehension.
Comment: if any of the items in `lst` have whitespace inside then it produces wrong result.
Comment: Thank you! Is it at all possible to keep the string of '@' in the new lists created?
Comment: From the users input examples, I think it is OK to assume that there are no other occurences of `@` or whitespace in the elements.
Answer: Repeatedly find the index of the element with '@' in the list, starting from the previous position of '@' and take whatever is there in the middle in the result.
idx, result = 0, []
while True:
    try:
        temp = my_list.index('@', idx + 1)
        result.append(my_list[idx + 1:temp])
        idx = temp
    except ValueError, e:
        result.append(my_list[idx + 1:])
        break
print result
# [['2014', '00:03:01', 'Matt', '"login"', '0.01'],
#  ['2014', '02:06:12', 'Mary', '"login"', '0.01']]

Answer: This seems like a perfect use for more_itertools.split_before. The resulting one-liner is both concise and clear.
from more_itertools import split_before

original = ['@', '2014', '00:03:01', 'Matt', '"login"', '0.01',
            '@', '2014', '02:06:12', 'Mary', '"login"', '0.01']

processed = [sublist for sublist in split_before(original, lambda i: i == '@')]

print(processed)

Output (line break added for clarity):
[['@', '2014', '00:03:01', 'Matt', '"login"', '0.01'],
 ['@', '2014', '02:06:12', 'Mary', '"login"', '0.01']]


Find the definite integral $\int\limits_{-\pi}^{\pi} (x^{199} (\sin x )^{202} + \mid x+2 \mid ^{101}) dx$

Question: Find the definite integral:
$$\int\limits_{-\pi}^{\pi} (x^{199} (\sin x )^{202} + \mid x+2 \mid ^{101}) dx$$.
At first it seemed as a pretty obvious and easy problem and now I have unfortunately struggled with it for two hours and still with no progression. My idea was to split the integral into two halves (one has $-\pi$ as lower and $-2$ as upper bound and the second one $-2$ as lower and $\pi$ as upper) to help to lose the absolute value under it but then I faced the situation where I have to integrate $x^{199} (\sin x )^{202}$ and I have absolutely no clue how to do it.
If someone could explain the problem to me (because I am pretty sure I have the wrong ideas) I would be more than grateful. I have three days until finals and hopefully understanding the problem would help me to pass the exam and help to develop my skills enough to give some of your contribution back to the community in the future.
Answer: If $f(x)$ is odd, i.e. $f(x)=-f(-x)$, on $[-a,a]$, $\int_{-a}^{a}f(x)\,dx=0$. That should take care of the first term.
Comment: $\text{lazy}\cap \text{correct}$
Comment: Oh lord, I totally forgot about that. Many thanks, feeling a bit foolish at the moment :D
Answer: For the second term, you have
$$\int_{-\pi}^\pi|x+2|^{101}dx=\int_{-\pi}^{-2}\overbrace{(-x-2)^{101}}^{=-(x+2)^{101}}dx+\int_{-2}^\pi(x+2)^{101}dx=$$
$$\left.-\frac{(x+2)^{102}}{102}\,\right|_{-\pi}^{-2}+\left.\frac{(x+2)^{102}}{102}\,\right|_{-2}^\pi=\frac1{102}\left[-0+(\pi-2)^{102}+(\pi+2)^{102}-0\right]=$$
$$=\frac{(\pi+2)^{102}-(\pi-2)^{102}}{102}$$


How to translate $value in the output code of a view?

Question: I have created a view in which I'm retrieving a time format, whose output is printed by $value.
Here's my Value Code:
$node = node_load($data->nid);
$wrapper = entity_metadata_wrapper('node', $node);
$auction_timeout = $wrapper->auction_timeout->value();
$sub = $auction_timeout - time();
$dtF = new DateTime("@0");
$dtT = new DateTime("@$sub");
return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes');

And the Output code is:
<?php
    print ($value);
?>

The output is in English which is something like:

35 days, 20 hours, 50 minutes

And I want it as

35日、20時間、50分

I couldn't find how to translate it. Can anybody help me?
Answer: return $dtF->diff($dtT)->format('%a ' . t('days') . ', %h ' . t('hours') . ', %i ' . t('minutes'));


Trying to create a custom marker with an icon image from the asset file using MarkerGenerator in flutter

Question: I am trying to create a custom marker using asset image/ network image. I take that image and create a widget to do necessary styling and then I try to call MarkerGenerator which return a List<Uint8List>
MarkerGenerator. But I get the Uint8List without the asset image. I think the rendering of asset image is not completed before the MarkerGenerator was called. How can I call the MarkerGenerator after the completion of rendering assetImage.
import 'dart:typed_data';
import 'marker_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class MyMarkerPage extends StatefulWidget {
    @override
    State<StatefulWidget> createState() {
        return _MyMarkerPageState();
    }
}

class _MyMarkerPageState extends State<MyMarkerPage> {
    Uint8List imageInMemory;
    List<Uint8List> markerImage;
    @override
    void initState() {
        super.initState();
        List<Widget> widgetList = new List();
        for (int i = 0; i < 1; i++) {
            widgetList.add(
            Container(
                height: 50,
                width: 50,
                padding: EdgeInsets.all(10),
                color: Colors.green,
                child: Image.asset("assets/myImage.jpg"),
            ),
            );
         }
         MarkerGenerator(widgetList, (bitmaps) {
             setState(() {
                 markerImage = bitmaps;
             });
         }).generate(context);
     }

     @override
     Widget build(BuildContext context) {
         return new Scaffold(
             appBar: new AppBar(
                 title: new Text('Widget To Image'),
             ),
             body: SingleChildScrollView(
                 child: Center(
                     child: new Column(
                         mainAxisAlignment: MainAxisAlignment.center,
                         children: <Widget>[
                         markerImage != null
                         ? Container(
                         child: Image.memory(markerImage[0]),
                         margin: EdgeInsets.all(10))
                         : Container(),
                         ],
                     ),
                 ),
             ),
         );
     }
}

Answer: The solution would be to wrap the MarkerGenerator.generate content in Future.delayed with 50ms. You could also try another timing.
Future.delayed(Duration(milliseconds: 50), () {
    WidgetsBinding.instance
          .addPostFrameCallback((_) => afterFirstLayout(context));
});

Answer: If I'm understanding your problem and the MarkerGenerator's author's article you need to use https://pub.dev/packages/after_layout in step 3 of his article: https://infinum.com/blog/creating-custom-markers-on-google-maps-in-flutter-apps/.
@override
void afterFirstLayout(BuildContext context) {
  getUint8List(markerKey).then((markerBitmap) =>
    // Set state and use your markerBitmap
  );
}

Quoting the article:

I've shown you how to get RenderObject and convert it to Uint8List,
but when do you call this method?
We need to get our bitmaps right after they are drawn. There are
multiple ways to do this, I use tiny AfterLayoutMixin


How can I safely make statistical inferences on abnormal data?

Question: I have a data set in which the key data point is lap times in seconds around a small set of known tracks in a small set of known vehicles. (Karts around an indoor kart track.)
The data comprises about two months of business and growing; about 4000 racers have participated, completing about 200k laps.
When bucketed into tenth-of-second results, the data looks mostly like a normal distribution, with one important caveat: it is not possible to be faster than (insert theoretical limit here), where that limit is only marginally quicker than the peak of the curve. A small number of racers approach that limit, but the left tail of the bell curve is dramatically smaller than the right tail.

The right tail goes on impressively; sometimes racers spin out or otherwise find themselves in a jam and it can take several minutes to straighten things out and get running again. The longest lap time I've seen is 8.5 minutes; a typical lap is around 24-28 seconds. The fastest time anyone has ever run is 23.036 seconds. I'm working on improving my input data; ideally I would discard any lap where the racers stopped entirely as junk data. For now, I'm discarding anything >40 seconds as a rough approximation. The mean, when discarding >40, is 27.1 -- a decent bit to the right of the peak of the curve, which is ~26.0.
My stats knowledge is spotty at best. I'd like to be able to work with standard deviations and other common statistical operations on this data. Can I do so safely with this data set? If not, what should I do, and more importantly, how do you know?
For context, things I'd like to be able to do with the data:

Compare individual racers against the norm, against each other, against their past selves
See if the distribution changes over time (and correlate that with, for example, tire changes on the karts)
Identify "hot" and "cold" karts
Identify outliers and flag them for inspection (the timing system sometimes produces bad data)
Rank drivers on their consistency
Identify times when the track is likely to be warm (consecutive sessions warm the track, and a warm track yields better traction and therefore faster times)

To be clear, I'm not asking how to do the above, although I would appreciate any guidance. And yes, the raw lap data includes identifiers for karts and racers, as well as dates.
Comment: Your objectives are not an intrinsic part of the data.  Those objectives need to be stated separately.  In other words, what is it that you want to know?  Do you just want to summarize the data?  Maybe the mean, median, and semi-interquartile range is adequate.  Maybe the parametric summary using estimates of $t_\text{min}$, $\mu$, and $\sigma$ (from @MarkFischler 's answer) is an adequate summary.  Do you need to make predictions?  So, to repeat, what are your objectives?  About the data collection:  might the distribution change over time?  Do different tracks have different distributions?
Comment: Sample standard deviations can always be computed for a data set but they might not correspond to converging estimates to a theoretical value, if the underlying theoretical distribution does not have finite variance or mean. Fitting a normal distribution is obviously an oversimplification here since the data-set is heavier on the right tail but it can certainly be done regardless. You can expand your stats toolkit by looking into using some right-tailed distributions.
Comment: I've edited the question to include a list of things I'd like to glean from the data.
Answer: This looks very much like $t-t_\min$ is distributed in a log-normal distribution. That is,
$\log(t-t_\min)$ is normal distributed, with some mean $\mu$ and some std $\sigma$.
To estimate the values of $\mu$ and $\sigma$ for the set of points labelled $t_k$ you can do
$$\hat{\mu} = \frac1n \sum_k \ln(t_k-t_\min)$$
and
$$\hat{\sigma}^2 = \frac1{n-1} \sum_k ( \ln(t_k-t_\min) - \hat{\mu})^2$$
Then you can do all the usual manipulations that you would do with a Normal distribution; for example the interval $[\mu - \sigma, \mu+\sigma]$ contains about $68\%$ of the probability; but that translates to some interval in $t$ which is $[t_\min + e^{\mu-\sigma},t_\min + e^{\mu+\sigma}]$.


How to make a UIButton appear when certain parameters are met objective C

Question: I am trying to make a button appear once the user has entered over 3 characters in the username and log in field. I set up an if statement, but I just do not know how to create the button programmatically...Any ideas?
Comment: I created a button on storyboard...dont know if that helps
Comment: Add from xib, make it `hidden` show it when needed?
Comment: There are lot of links available for how to create button programmatically u can check those links
Comment: If you already have a button on storyboard, connect IBOutlet and use  UIButton's setHidden: method.
Comment: @iphonic if i were to make it hidden how would i go about showing it when it is needeD?
Answer: Creating a button programmatically would look something like this:
<code>UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/2, self.view.frame.size.width/3, self.view.frame.size.height/8)];
button.titleLabel = @"My Button!"
[self.view addSubview:button];
</code>
Comment: I prefer the `buttonWithType` method. And where to the strange factors come from?


Display following 2 elements on button click

Question: I have a ul li list.
On page load I want to hide all elements with class hide and on add more button i want to display next 2 elements and so on.

$(function() {
  $('.hide').hide();

  $('#add_more').on('click', function() {
    // show
  })
})

<button id="add_more">Add next 2</button>

1

2

3

4

5

6

n

Comment: why do you hidding these li 's ,dont you add it dynamically?
Comment: @Sreeraj_ms I have some predefined static data
Answer: To achieve this you can retrieve the last currently shown elements, then use slice() to get the following two and display them. Try this:

$(function() {
  $('#add_more').on('click', function() {
    $('.show:last').nextAll().slice(0, 2).toggleClass('show hide');
  })
})
.hide { display: none; }

<button id="add_more">Add next 2</button>

1

2

3

4

5

6

n

Comment: Not sure what you mean by 'previous result'
Comment: Ah, I see. In that case just remove the first `toggleClass()` call. I've updated the answer for you
Comment: this works but the previous result is not displaying
Comment: it should not toggle. it should just add. like 1, 2 and then 1,2,3,4


What is the implication of having the simple mean very different from the expected value?

Question: I was in the process of analyzing the data below. The first 2 columns are correct. They represent a point in time and a value of a stock at that point.
I decided to calculate the probability surrounding each value and calculated the average to be the Sum(price)/16 =4.6875. I calculated the mean as Sum(price * P(value=price)=E(y) and took the average of that last column. I expected that these to values to be close but E(y) was found to be 0.7617.
I want to know the following:

Do the calculation look right (just take a single random row, I don't expect anyone to waste time checking all the numbers of course).
Why is E(y) so different from AVG(y)? What is the statistical significance of that?

The list of y values (2nd column) is:
3, 4, 5, 6, 7, 8, 3, 4, 5, 6, 3, 1, 3, 7, 4, 6

The entire table is:
Time Price.y N.gt.y N.eq.y N.eq.y.1 P.gt.y P.eq.y P.eq.y.1    E.y
   1       3     11      4        1 68.75% 25.00%    6.25% 0.7500
   2       4      8      3        5 50.00% 18.75%   31.25% 0.7500
   3       5      6      2        8 37.50% 12.50%   50.00% 0.6250
   4       6      3      3       10 18.75% 18.75%   62.50% 1.1250
   5       7      1      2       13  6.25% 12.50%   81.25% 0.8750
   6       8      0      1       15  0.00%  6.25%   93.75% 0.5000
   7       3     11      4        1 68.75% 25.00%    6.25% 0.7500
   8       4      8      3        5 50.00% 18.75%   31.25% 0.7500
   9       5      6      2        8 37.50% 12.50%   50.00% 0.6250
  10       6      3      3       10 18.75% 18.75%   62.50% 1.1250
  11       3     11      4        1 68.75% 25.00%    6.25% 0.7500
  12       1     15      1        0 93.75%  6.25%    0.00% 0.0625
  13       3     11      4        1 68.75% 25.00%    6.25% 0.7500
  14       7      1      2       13  6.25% 12.50%   81.25% 0.8750
  15       4      8      3        5 50.00% 18.75%   31.25% 0.7500
  16       6      3      3       10 18.75% 18.75%   62.50% 1.1250

Comment: A weighted average won't necessarily equal a simple average. If there is reason to suspect that they should, that could mean that your weights are inaccurate. Can you type / paste in your data to make it easier for people to work with? (Ie, not a jpg; people will help with the formatting.)
Comment: Can you explain a bit more about how you arrived at E(y)?
Comment: @mdewey, E(y) is calculated as follows, say for Time=1, y=3, so E(3)=(P(y=3)*3)=0.25*3=0.75.
Comment: @gung, thanks for your comment. E(Y) is the weighted average of the cost, I wanted to calculate the Mean as the expected value times the probability. I will post the data in typing now.
Answer: If I understand correctly, it should not be surprising that these numbers are very different. I think you are not comparing what you think you are. From you data I gather you are comparing:

The arithmetic mean of the stock price: (sum of prices / n)
The arithmetic mean of: (price * the frequency with which that price was observed)

Take row 1 for example. The value 3 was observed 4 times out of 16, or 25% of the time. You took 25% * price (3) which = .75 and labeled .75 as the expected value. Why would .75 be the expected value? According to your frequencies, the expected value will be greater than 3 68.75% of the time and a value less than 3 will be observed 6.25% of the time. Therefore, I would say it is highly unlikely to observe a value of .75.
The mean (.76) at the bottom is the mean if you repeated the above for each row, summed the values, and divided by n (16).
If you want to calculate the average expected value, I recommend you use a simple linear regression with price as your independent variable y and time as your dependent variable x. From there, you can take (sum predicted value y-hat /n) to get the average expected value.
Comment: Thank you for your answer, E(y) in fact is not the correct term.                    E(y)= Sum (P(yi)*yi) = 3*0.25+4*18.75+6*12.5+...+6*18.75.=0.761. This value is so far from the average 4.6875. Major question is why? What does the large difference signify?
Comment: There is no good answer to "why" because the numbers you are comparing have no relationship.
Answer: Without repercentaging the P(=y) column to 100%, the average of that column times Price is way underestimating a more appropriate weighted average. This is for the simple reason that the P(=y) column, by itself, does not sum to 100%.
By summing P(=y) up, repercentaging each cell, and multiplying that new value by Price, appropriate weighted average can be generated.
Per @gung's comment, at 4.023, this new weighted average isn't equal to the raw unweighted average.
For me, a more basic question is why you are multiplying price by a partitioned likelihood in the first place.
Comment: Thank you for your answer. I don't think we can sum P(=y) to get 100%. P(v=y) in this context is the probability of the occurrence of the price v in the set given. Since prices repeat, it can't add up to 1.
Comment: The very premise of your analysis is highly dubious to me. What is your motivation for partitioning the likelihood of a price event into 3 buckets?
Comment: What I wanted to see is, given a price value such as $6, what is the probability that this price will repeat (=6), increase (>6), decrease (<6).
Comment: I've been thinking about your reply to my question. I still have questions about the bucketing but there is no information about how you arrived at the likelihoods. My concerns boil down to two: first, why treat the probabilities as mutually exclusive, summing to 100%? They could just as easily be treated as independent, random variables. Next, isn't your primary concern that price could decline? If that is true, then why not just model that? This would eliminate two of the buckets, simplifying the analysis.
Comment: Thank you for your concern. As per the first question the sum of the values, taken horizontally should be 1 because any number regardless of what it represents must satisfy this $p(xv) = 1$ ( as long as $x$, $v$ are not complex). The vertical sum of probabilities does not have to yield 1. You are correct, the price for the sake of this case, can be considered as a random variable. I was interested in having the full picture for price probabilities, but for the case of price decrease $p(x<=v)$ would suffice.


about TranslateTransform and RenderTransformOrigin

Question: I am using Silverlight 3.0 + .Net 3.5 + VSTS 2008 + C# to silverlight application.
I want to learn TranslateTransform and RenderTransformOrigin, could anyone recommend me some tutorials? I am a newbie of this area. And I did not find anything which is good to learn for a newbie from MSDN (correct me if there are some good stuff). :-)
BTW: I am headache about the coordination transformation matrix, it is great if the tutorial could cover this topic.
EDIT: here is the code which I am confused.
    <Grid Margin="-1,0,100,0" x:Name="controlsContainer" Height="35" RenderTransformOrigin="0.5,0.5" VerticalAlignment="Bottom">
        <Grid.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform/>
                <TranslateTransform Y="0"/>
            </TransformGroup>
        </Grid.RenderTransform>
        <Rectangle Margin="0,0,0,0" Height="35" VerticalAlignment="Top" Fill="#97000000" Stroke="#00000000" RenderTransformOrigin="0.5,0.5"/>
        <VideoPlayer:mediaControl Height="35" Margin="1,0,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Top" x:Name="mediaControls" Visibility="Visible"/>
    </Grid>

Comment: "coordination transformation matrix" are you refering to the MatrixTransform?
Comment: I mean the matrix under Remarks section of this MSDN page,

http://msdn.microsoft.com/en-us/library/system.windows.media.translatetransform(v=VS.95).aspx

Appreciate if you could recommend me some good materials for a newbie.
Comment: I have posted my confusions about TranslateTransform and RenderTransformOrigin in EDIT 1 section of my post. Appreciate if you could let me know in order to understand the code I posted, what kinds of tutorials do I need to read?
Answer: First of all translation does not use an origin so the RenderTransformOrigin does not apply to a TranslateTransform.
To learn about transforms why not try them out? Place a shape two times in a grid, and let the top one be transparent. Then transform the top shap and view the effect. Here I have rotated a rectangle by 45 degrees around the center of the rectangle.
<Grid Background="White">
  <Rectangle Width="50" Height="50" Fill="Black"/>
  <Rectangle Width="50" Height="50" Fill="Red" Opacity="0.5"
      RenderTransformOrigin="0.5, 0.5">
    <Rectangle.RenderTransform>
      <RotateTransform Angle="45"/>
    </Rectangle.RenderTransform>
  </Rectangle>
</Grid>

Comment: Thank you! I am a newbie for Silverlight animation and I am maintaining code which is using TranslateTransform and RenderTransformOrigin. Appreciate if you could recommend me some good tutorials for a beginner of this area.
Comment: I have posted my confusions about TranslateTransform and RenderTransformOrigin in EDIT 1 section of my post. Appreciate if you could let me know in order to understand the code I posted, what kinds of tutorials do I need to read?
Answer: Translate is specifically referred to by MSDN as Move. Refer to section to get a visual understanding of Transformations and Coordinate Systems.

Moves (translates) an element by the specified X  and Y  amounts.

alt text http://i.msdn.microsoft.com/dynimg/IC212086.png
Comment: Thank you! I have posted my confusions about TranslateTransform and RenderTransformOrigin in EDIT 1 section of my post. Appreciate if you could let me know in order to understand the code I posted, what kinds of tutorials do I need to read?


Inserting a table name into a string with SAS

Question: I'm writing a macro in sas, that exports a file. I want the name of the file, to
be the same as the name of the table in sas. So if i run:
<code>%to_excel(my_table);
</code>
I want the file to be saved to "Q:/my_table.xlsx". Heres what I have so far:
<code>%macro to_excel(tb);
proc export data=&tb
outfile=?????????????????
dbms = xlsx
replace;
run;
%mend;
</code>
Answer: You are almost there.  Try this.
<code>%macro to_excel(tb);
proc export data=&tb
outfile="Q:/&tb..xlsx"
dbms = xlsx
replace;
run;
%mend;

%to_excel(my_table);
</code>


Spivak Calculus Question 6 a) Prove that if 0 < x < y, then x^n < y^n, n = 1,2,3,....

Question: Looked up a solution and the result I found looked nothing like what I had, and so I was wondering if a solution along these lines would work?
I tried to solve the following problem as follows:
]
$0 \le x < y \implies  [x \in P \land (y/x > 1)] \lor x = 0$
Case 1: $x = 0,x^n = 0$ for any nonnegative n or 0, and since 0 < y it follows $x^n = 0 < y^n$.
Case 2: $x \neq 0 \land x < y.$ If x < y yet again it implies y/x > 1
$x^n < y^n$, we divide both sides by $x^n (x \neq 0)$ and get $1 < (y/x)^n$. Since we know y/x > 1 it follows $(y/x)^n$ to any nonnegative power (except 0, which we don't consider) will still be bigger than 1.
It feels like it should work.
Comment: "Since we know y/x > 1 it follows (y/x)^n" I think in this exercise you are asked to prove it. The "$n=1,2,3,\dots$" should suggest a method ;-)
Comment: Oh I see, makes sense. Edited. Thank you :)
Comment: [Related](https://math.stackexchange.com/questions/3069716). But not considered as a duplicate, since your question was about your own proof (I answered it in my first comment above).
Comment: Ok I see, this makes sense. Thanks a lot Anne!. :)
Comment: Why does the title say '$x"\le y"$' while the content says '$x^n < y^n$'?
Comment: Is it a problem? I had noted it while making the calculation, but while writing the proof I only use the y/x > 1 in case 2, where we know x != 0.
Comment: I see it does make sense. Would the issue with this "proof" be that I am not really using first principles?
Comment: That is what I think.
Comment: For some reason when I copy-pasted it, it pasted it as ", I don't see the equal tho?
Comment: Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to format your question.
Answer: This is very well suited for mathematical induction... The induction base is trivial, as $0\leq x < y \Rightarrow 0 \leq x < y$. We just need to show that when $0 \leq x < y$ and $x^n < y^n$, we also have that $0 \leq x^{n+1} < y^{n+1}$. This is immediate, since
$$
x^{n+1} = x x^n < x y^n < y y^n = y^{n+1}
$$
In the previous inequalities I first used the induction hypothesis and then the given fact that $x < y$.
Comment: Agreed about induction. Chapter 2 introduces inductive arguments. The placement of this problem (and a few others) before that chapter, is a bit unfortunate.
Comment: Thanks a lot, this is more natural (to me) than the other solutions I saw.


How can I calculate the conditional probability of several events?

Question: Could you inform me please, how can I calculate conditioned probability of several events?
for example:
P (A | B, C, D) - ?
I know, that:
P (A | B) = P (A $\cap$ B) / P (B)
But, unfortunately, I can't find any formula if an event A depends on several variables. Thanks in advance.
Comment: I guess one should assume that B,C and D are mutually independent.
Answer: Another approach would be:
P(A| B, C, D) = P(A, B, C, D)/P(B, C, D)
              = P(B| A, C, D).P(A, C, D)/P(B, C, D)
              = P(B| A, C, D).P(C| A, D).P(A, D)/{P(C| B, D).P(B, D)}
              = P(B| A, C, D).P(C| A, D).P(D| A).P(A)/{P(C| B, D).P(D| B).P(B)}

Note the similarity to:
      P(A| B) = P(A, B)/P(B)
              = P(B| A).P(A)/P(B)

And there are many equivalent forms.
Taking U = (B, C, D) gives:
    P(A| B, C, D) = P(A, U)/P(U)
P(A| B, C, D) = P(A, U)/P(U)
              = P(U| A).P(A)/P(U)
              = P(B, C, D| A).P(A)/P(B, C, D)

I'm sure they're equivalent, but do you want the joint probability of B, C & D given A?
Comment: @DrorAtariah: https://en.wikipedia.org/wiki/Chain_rule_(probability)
Comment: Can someone provide some references to this answer?
Answer: Take the intersection of B,C and D call it U. Then perform P(A|U).
Answer: check this wikipedia page under the sub-section named extensions, they do show how to derive conditional probability involving more than 2 events.


Evento para nav-tab do Bootstrap rodar no lado do servidor c#

Question: Estou usando o seguinte código para usar tabs em minha aplicação Asp.Net, existe alguma forma de adicionar um evento para que quando trocar de aba executar algum evento no lado do servidor igual o evento da TabContainer do ajaxcontroltoolkit ? (http://www.ajaxcontroltoolkit.com/Tabs/Tabs.aspx)
Não estou usando a TabContainer pelo motivo de não conseguir aplicar o Bootstrap nela.
Encontrei o código abaixo mas ele faz no lado do cliente.
https://stackoverflow.com/questions/20705905/bootstrap-3-jquery-event-for-active-tab-change
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  var target = $(e.target).attr("href") // activated tab
  alert(target);
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

Home

Profile

    home tab!

    profile tab!

Comment: @MatheusMiranda ajaxcontroltoolkit.com não é meu, apenas ultilizei o componente. Agora ele ele mantido pela DevExpress: https://www.devexpress.com/products/ajax-control-toolkit/ Documentação: https://github.com/DevExpress/AjaxControlToolkit/wiki
Comment: O evento vai ser síncrono ou assíncrono? Você pode utilizar ajax?
Comment: ajaxcontroltoolkit.com é seu site ? Se sim, onde voce hospedou ?
Answer: Ao invés de você usar link normal você pode usar LinkButton do asp.net e pegar o evento do click no lado do servidor:

<asp:LinkButton data-toggle="tab" OnClick="Method_Click">Home

<asp:LinkButton data-toggle="tab" OnClick="Method_Click">

     home tab!

    profile tab!

Comment: Seu código não funciona mas você me deu uma luz usando LinkButton, depois vou colocar minha resposta para que possa ver. De qualquer forma obrigado.
Comment: Não funcionou, mesmo usando runat="server"?


Monitor and act on another process CPU consumption

Question: I'm looking for away to monitor a specific process CPU consumption and act if the process didn't consume any CPU for the last X minutes/seconds on linux.
The use case it that I've a machine on EC2 (obtained using spot request) that I would like to power down if a given process on  doesn't really do any work (not crashed, just sitting in ideal) I would like to accomplish it from within the  machine without any of AWS services.
Thanks,
Eden
Answer: I suppose you could use Monit at the OS level.
But why would you want the instance to power off?
Comment: To save money, I've no use for it once its ideal


Cron issue with Drush 8

Question: My Drupal 6 sites are hosted on a Linux server with Apache 2.2, PHP 5.5, MySQL 5.6 installed. I use Drush 8 which I installed via composer.
I set a cron job via cPanel which runs every day this script:
#!/bin/bash
# Script to execute all the cron jobs with drush
echo '**************** French site *******************'
cd /home/myuser/public_html/fr/sites/fr.mysite.com
/home/myuser/.composer/vendor/bin/drush -v core-cron
echo '**************** English site ******************'
cd /home/myuser/public_html/en/sites/en.mysite.com
/home/myuser/.composer/vendor/bin/drush -v core-cron
echo '**************** Spanish site ******************'
cd /home/myuser/public_html/es/sites/es.mysite.com
/home/myuser/.composer/vendor/bin/drush -v core-cron
echo '**************** Completed **********************'

But it fails and ends with:
**************** French site *******************
X-Powered-By: PHP/5.5.33
Content-type: text/html

Warning:  proc_open(): Descriptor item must be either an array or a File-Handle in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 434

Warning:  proc_get_status() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 435

Warning:  proc_close() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 436

**************** English site ******************
X-Powered-By: PHP/5.5.33
Content-type: text/html

Warning:  proc_open(): Descriptor item must be either an array or a File-Handle in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 434

Warning:  proc_get_status() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 435

Warning:  proc_close() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 436

**************** Spanish site ******************
X-Powered-By: PHP/5.5.33
Content-type: text/html

Warning:  proc_open(): Descriptor item must be either an array or a File-Handle in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 434

Warning:  proc_get_status() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 435

Warning:  proc_close() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 436

**************** Completed **********************

The strange thing is that when I manually run drush -v core-cron on any site, the cron run ends successfully. I really don't know where the problem comes from.
Comment: Looks like your cron script is using php-cgi instead of php-cli. Compare the environment variables, php and php.ini being used, etc. between the working and non-working users (cron user, vs. user you are using when manually running Drush).
Comment: I forgot to mention that this cron script worked well with Drush 6 before. Would it have been able to work yet if there was a php-cgi / php-cli problem?
Comment: Probably not, but Drush 7 and earlier are unsupported; been a long time since I've used Drush 6.
Comment: What about adding "php -v" as the first line of your script (after the shebang line of course), and then run the script through cron and manually - to verify which version of PHP is executed in each situation.
Answer: I would suggest that instead of calling cd within your script, you either set up drush aliases or pass the --root and --uri parameters to the cron request.
/home/myuser/.composer/vendor/bin/drush -v --root=/home/myuser/public_html --uri=fr.mysite.com core-cron

That should make sure that drush is running in the right context.
You can also make sure that drush is running with the php that you would like by setting the DRUSH_PHP environment variable.
Answer: Following the comments to the question, I've added php -v as the first line of my script after the shebang line and run it both manually and through cron.
Manually, I've run sh myscript.sh and got:
PHP 5.5.33 (cli)

and the script's ended successfully.
Through cron, I've got:
PHP 5.5.33 (cgi-fcgi)

and the script's ended in failure.
So it's indeed a php-cgi / php-cli problem: cron is using php-cgi instead of php-cli in my case.
But since I'm hosted on a managed VPS and since I don't intend to use D6 for much longer, I've finally found easier to write another script using wget:
#!/bin/bash
# Script to execute all the cron jobs with wget
echo '**************** French site *******************'
wget --no-cache --spider http://fr.mysite.com/cron.php
echo '**************** English site ******************'
wget --no-cache --spider http://en.mysite.com/cron.php
echo '**************** Spanish site ******************'
wget --no-cache --spider http://es.mysite.com/cron.php
echo '**************** Completed **********************'

It's a little slower than using drush but it runs well.

Cron issue with Drush 8


Sproutcore custom getter/setter

Question: In Sproutcore i am using the universal setter/getter method like so:
foo.set('bar', newValue );
val = foo.get('bar');

This is quite different to Objective-c, how would i write a custom getter/ setter?
EDIT
Thanks to those who helped, the way to do it is
bar: function( propKey, propVal ) {
  if(propVal===undefined) {   // called as getter method
    var computedBarValue = ...
    return computedBarValue;
  } else {
    this.bar = propVal + ...    // called as setter method
  }
}.property()

As you can see, you have one method that is the both the getter and the setter.
if you call
val = foo.get('bar');

the method argument 'propVal' will be undefined.
if you call
foo.set('bar', newValue );

the method argument 'propVal' will be newValue
Answer: Custom setter/getter function would look smth like this:
bar: function(key, value){
  if(value != undefined){
    this._bar = value;
  }

  return this._bar;
}

This would simply get/set the value. To do smth on set, just add what you want after this._bar = value, to do smth on get, just add if value == undefined.
Comment: Hi, thanks for the answer - this is pretty much what i think won't work.. but ill try to do some tests and maybe expand the question with some more details.
Comment: The ToDos demo described at http://guides.sproutcore.com/html_based.html includes this setter/getter pattern for the allAreDone function

Sproutcore custom getter/setter


Seemingly simple combinatorial problem

Question: Count all $n$-length strings of digits $0, 1,\dots, m$ that have an equal number of $0$'s and $1$'s. Is there a closed form expression?
Comment: What do you mean by "a n-permutation of m digits"?
Comment: All the strings in $\{0,\ldots,m\}^n$?
Comment: Yes, the length of each permutation is n
Comment: Sorry, I was just confused because a "permutation" is usually a bijective map.
Comment: A permutation is a different animal. A better way to describe your objects is "strings of length $n$".
Answer: Assuming we want the number of strings of $n$ characters over the alphabet $\{0,\ldots,m\}$ with the same number of "zeroes" and "ones" we just have to compute:
$$\sum_{j=0}^{\lfloor n/2\rfloor}\binom{n}{2j}\binom{2j}{j}(m-1)^{n-2j}.$$
Reason: set $j$ as the number of zeroes, then choose the $2j$ over $n$ places where putting all the zeroes and ones, then choose where to put the zeroes over such $2j$ positions, the choose how to fill the remaining part of the string with characters from $\{2,\ldots,m\}$ ($(m-1)$ possible choices).
Expanding $(m-1)^{n-2j}$ with the binomial theorem we get:
$$\sum_{j=0}^{\lfloor n/2\rfloor}\binom{n}{2j}\binom{2j}{j}\sum_{k=0}^{n-2j}\binom{n-2j}{k}m^k (-1)^{n-2j-k},$$
and the balanced strings are generated by the grammar:
$$ S \to 0S1,1S0,SS,\varepsilon.$$
Comment: The upper limit of the first sum should be floor(n/2).
Comment: I think, m-2j should be m-2.
Comment: @JK900: You're right, fixed.
Comment: Can the above expression be simplified? I spent several hours without any result.
Comment: I think it can be written in terms of Stirling numbers, too, but does not have a really "closed" form.
Comment: It's a problem from the 1st chapter of "Introduction to combinatorial mathematics" by C.L. Liu. I suspect simple answer exists as with other problems from that chapter.
Answer: This can be computed recursively. For $m\ge1$, let $f_m(n,d)$ be the number of $n$-letter strings over the alphabet $\{0,\dots,m\}$ containing exactly $d$ more $0$'s than $1$'s. Then $f$ satisfies the following, which provides a recursive definition:
$$\begin{align}
f_m(0,0)&=1\\
f_m(0,d)&=0\mbox{ if }d\ne0\\
f_m(n,d)&=f_m(n-1,d-1)+(m-1)f_m(n-1,d)+f_m(n-1,d+1)\\
\end{align}$$
The last of these equestions can be explained by considering how a string of length $n$ containing $d$ more $0$'s than $1$'s can be built by appending a digit to a string of length $n-1$. It can be built by appending a $0$ to a string among those counted by $f_m(n-1,d-1)$, by appending a digit other than a $0$ or $1$ (there are $m-1$ such digits) to a string counted by $f_m(n-1,d)$, or by appending a $1$ to a string counted by $f_m(n-1,d-1)$.
For $m=9$, this gives the following sequence of answers to the original question, beginning with $n=0$:
$1$, $8$, $66$, $560$, $4870$, $43248$, $390804$, $3582048$, $33213510$, $310850480$, $2931397756$.
This sequence does not appear (yet) in the Online Encyclopedia of Integer Sequences.
(These results agree with the sum Jack D'Aurizio gave in his answer.)

Seemingly simple combinatorial problem


Arduino button interrupt triggered on high power switch on

Question: I have a nearly finished prototype using an arduino uno. Basically its purpose is to switch a 2000w main AC heating load using a heavy relay on and off. The input of the relay is comming from the mains but is connected to the power company using a special meter that is only switched on between 23-07 hrs at night. The power for the arduino is continous by the way, so this stays on.
The whole thing is nicely build into a box with on the front an small lcd display and a button, connected using 20cm wires to the arduino board (I am using a protoshield).
The button is pulled up with a 10k resistor which is pulled to ground when pressed. I have put a 0.47 uF cap on the input pin = pin 2 to also debounce the circuit a bit. In software I am using an interupt on the falling edge to detect button presses. The whole thing works nicely... Except...:
When the load ac input is switched on by the power company this is sometimes recognized as a button press! I am thinking that the suddon power spike induces a voltage in the 20 cm button wires which is recognized as a falling edge. How can I avoid this?
I am equiped with multimeter, oscilloscope, soldering... so I can try out any suggestions in detail.
Comment: The solution to this problem will more than likely include filtering hardware, I would ask here: http://electronics.stackexchange.com/
Comment: Use the oscilloscope (hope it's digital) to see the actual waveform. Probably it's an induction on the button wires, so the first thing I'd try (since you already filtered it with the debouncing circuit) is to shield the cables (you can try with an aluminum foil soldered to ground only on the board (not on the button side) or use shielded cables
Comment: my scope is indeed digital so I will measure this in the next couple of days, using a shielded cable also was my next idea, lets see how it goes :)
Comment: I replaced the wire running to the button with a fully shielded wire and of course connected the shield to ground. Unfortunately this did not solve the problem. I indeed see spikes on the lines when the AC is switching. I have now found out that I can easily simulate the issue by playing around with the input AC connector (creating some sparking contact on the input). My next move will be to add a snubber network just in parallel over the input AC. I let you know how it goes...
Comment: By the way, I solution that would indeed most probably work is to replace the mechanical contact relay with a solid state version that switching on the zero crossing of the AC. However since I have a heavy load (10 A @ 240 V AC) the SSR would dissipate to mach heat for my enclosure so I want to stick with the mechanical relay and see if the snugger network does the trick
Answer: I am having a similar problem building a fuel injection flow bench. The button press starts a simulated engine run sequence that powers a relay. That relay then powers up to 6 injectors. What happens is as soon as I press the button the injectors closing induces a current and trips the whole system to start over again. The solution I've found that worked was using a battery to supply voltage to the injectors as opposed to the power supply itself. This isolates the arduino supply from the injector supply via my relay. The problem is of course now I need to keep the battery charged. I'm looking for a more elegant solution.
Answer: I tried to solve this issue in hardware, but unfortunately failed.
These are the options I tried, but that did NOT work

used a shielded cable for the button
implemented an XY denoise capacitor network on the AC of the load (input)
like this one : http://www.conrad.be/ce/nl/product/450571/K042201052-Ontstoringscondensator-XY-Radiaal-bedraad-01-F-250-VAC-1-stuks?ref=searchDetail

In the end I implemented the following software solution:
The first time the button is pressed, it must be pressed 1 second before the button actually becomes active. This will never happen due to the AC turning on because this is a very brief spike. I programmed this into the arduino using interrupt to detect button press and then micro delay (inside the ISR) to check that after 1 seconds the button is still pressed.
After the initial 1 second button press, the button stays lively for 1 minute


existence of weak* continuous means for amenable locally compact groups

Question: Let G be an amenable locally compact group.
Does there exist a left invariant mean $m \colon L^\infty(G) \to \mathbb{C}$ on $L^\infty(G)$ which is in addition weak*-continuous ?
Recall that the von Neumann algebra $L^\infty(G)$ admits $L^1(G)$ as unique predual.
Answer: No, except in the trivial case where $G$ is compact.
If $m$ is weak-* continuous then, being a linear functional, it's given by a function $g\in L^1$: $$m(f)=\int_G f(x)g(x)\,dx,$$
where $dx$ is left-invariant Haar measure. (Or maybe it's right-invariant; I'm never sure which is which... Take $dx$ to be the flavor of Haar measure such that $\int\phi(cx)\,dx=\int\phi(x)\,dx$.)
Since $m$ is left-invariant it follows that $g$ is left invariant. So $g$ is constant, and since $m(1)=0$ it follows that $g\ne0$. So there exists $c\ne0$ with $\int_G c=1$, hence $G$ has finite measure.


Why isn't my data populated when i used VBA to create worksheets beforehand?

Question: Previously, when I created the worksheets index 1,2,3 in excel,

it can be sorted into like this in index 1 2 and 3 respectively

But now if i stop creating worksheets in excel but through VBA instead, the data cant be populated and it leaves index 1,2 and 3 empty.

This is the code that I used for populating the data but with the addition of add.sheets. The add.sheets here are for creating index1,2,3 worksheets but they doesn't trigger the program to continue to populate the data even though these worksheets exists when I program them in VBA.
 Sub UpdateVal()
        Static count As Long
        Dim iRow As Long
        Dim aRow As Long
        Dim a As Long
        Dim b As Long
        Dim selectRange As Range
        Dim lastline As Integer
        Dim sheetname As String
        Dim indexrowcount As Integer
        Dim wb As Workbook
        Dim ws As Worksheet
        Set wb = ActiveWorkbook
        Set ws = wb.Worksheets("Result")
        Set site_ai = Sheets.Add(after:=Sheets(Worksheets.count))
        site_ai.Name = "Index1"
        Set site_bi = Sheets.Add(after:=Sheets(Worksheets.count))
        site_bi.Name = "Index2"
        Set site_ci = Sheets.Add(after:=Sheets(Worksheets.count))
        site_ci.Name = "Index3"**

       '^additional codes sheets.Add added here for creating worksheets namely index1,2,3

        j = 2
        iRow = 1
        lastline = ws.UsedRange.Rows.count
        While iRow < lastline + 1
            a = iRow + 1
            b = iRow + 17 ' Max Group Size with Same name in F to H column
            count = 1
            If ws.Cells(iRow, "F").Value = "Martin1" Then
                sheetname = "Index1"
            ElseIf ws.Cells(iRow, "F").Value = "John1" Then
                sheetname = "Index2"
            Else
                sheetname = "Index3"
            End If
            For aRow = a To b
                If ws.Cells(iRow, "F") = ws.Cells(aRow, "F") And ws.Cells(iRow, "G") = ws.Cells(aRow, "G") And ws.Cells(iRow, "H") = ws.Cells(aRow, "H") Then
                    count = count + 1
                Else
                    Set selectRange = Range("A" & iRow & ":J" & aRow - 1)
                    selectRange.Copy
                    indexrowcount = Sheets(sheetname).UsedRange.Rows.count
                    Sheets(sheetname).Range("A" & indexrowcount).PasteSpecial xlPasteAll
                    iRow = iRow + count
                    Exit For
               End If
            Next aRow
        Wend
    End Sub

what am I missing here and how should i solve it?
Comment: Why do you have three columns with the same data? Also, `site_ci.Name = "Index3"**` if giving a syntax error.
Answer: Your code is too confusing. If your example data is accurate, I don't understand why you need to check all three columns. You can accomplish what you are trying to do, by just using column F. If your data is already sorted as shown, then I would loop through column F testing for duplicates until no match. I would then add a worksheet and name it using the start cells' value. Then copy the rows from the start cell to the current rwNbr - 1 and paste to the new worksheet. Reset the start cell for the next group and loop.
Sub SaveRangewithConsecutiveDuplicateValuestoNewSheet()
'Define all variables
Dim wb As Workbook, ws As Worksheet, sCel As Range, rwNbr As Long

Set wb = ThisWorkbook 'Set workbook variable
Set ws = wb.Worksheets("Sheet1") 'set worksheet variable using workbook variable

Set sCel = ws.Cells(1, 6) 'Set the first start cell variable to test for duplicate values

    Application.DisplayAlerts = False
        For rwNbr = 2 To ws.Cells(ws.Rows.count, 6).End(xlUp).Offset(1).Row Step 1 'Loop

            If ws.Cells(rwNbr, 6).Value <> sCel.Value Then 'loop until the value changes
                wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.count)).Name = sCel.Value 'Add sheet and name based on the first cell of group

                ws.Range(sCel, ws.Cells(rwNbr - 1, 6)).EntireRow.Copy Destination:=ActiveSheet.Range("A1") 'select group of consecutive duplicates

                Set sCel = ws.Cells(rwNbr, 6) 'reset start cell to test for the next group of consecutive duplicates
            End If

        Next rwNbr
    Application.DisplayAlerts = True
End Sub

Comment: ok technically my code works as it should be without the add.sheets and it will sort the data and paste them accordingly but that is with worksheet index 1, index 2 and index 3 created in excel workbook. But now when the worksheets are not created in excel, but instead i use vba to create this worksheets through add.sheets, the data wont be sorted and paste even they exists
Comment: your code gets the idea that what I want but how to code such that you named the sheets as index 1,index2,index3 instead of naming them based on cell value like martin,charlie like the one that you used   wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.count)).Name = sCel.Value


APNS doesn't call didReceiveRemoteNotification after icon click

Question: I m tring to pass the below payload from PHP Server to APNS.
$body['aps'] = array(
        'badge' => 1,
        'ArmyGroupID' => 12345
);

While the app in the foreground, i get the entire dictionary, that is no issue.
Problem:
But while the application is in the background, it successfully appends the badge,
but while I click on the icon, the message is not dispatched to didReceiveRemoteNotification.
Am I doing it in the right way?
Answer: This is expected behaviour.See following snippet from Apple documentation:

As a result of the presented notification, the user taps the action button of the alert or taps (or clicks) the application icon.
  If the action button is tapped (on a device running iOS), the system launches the application and the application calls its delegate's application:didFinishLaunchingWithOptions: method (if implemented); it passes in the notification payload (for remote notifications) or the local-notification object (for local notifications).
  If the application icon is tapped on a device running iOS, the application calls the same method, but furnishes no information about the notification . If the application icon is clicked on a computer running OS X, the application calls the delegate's applicationDidFinishLaunching: method in which the delegate can obtain the remote-notification payload.

As a workaround I can suggest one little check into didFinishLaunchingWithOptions like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Get user info dict
    NSDictionary* userInfo = [launchOptions   valueForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
    if([UIApplication sharedApplication].applicationIconBadgeNumber >0 && userInfo == nil){
        //Do like you did in didRecieveRemoteNotification method
    }
    return YES;
}

Comment: You actually want to check `userInfo != nil`. I also suggest the use of the `UIApplicationLaunchOptionsRemoteNotificationKey` constant instead of an error-prone static string.
Comment: I'm agree for constant, but not agree about userInfo check.In question is said, that he clicks icon, and when click icon userInfo is nil.If alert of push notification is clicked then userInfo is not nil.
Comment: Not really. He said that the `didReceiveRemoteNotification` is not called and that's why the notification should also be searched for in `didFinishLaunchingWithOptions` as you pointed out. How would you handle a nil notification anyway?
Answer: in swift2:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
  }


What is necessary sample size for B in A/B test with unequal sample sizes?

Question: I have a situation in which I want to measure if the error rate in system B (test) is worse than the error rate in system A (control). System A has a sample size of 100 and that cannot be modified. So my question is, how can I get an estimate of the minimum sample size required of system B to know if the error rate is worse than in system A?
To put some numbers in, let's say the mean error rate of system A is 1 and the standard deviation is 0.1. Let's assume I want 95% confidence and a power of 0.8. I'm assuming a one-sided test because I'm only interested in testing whether system B is worse than system A, not if it's better. I also assume a margin of error of sd/10=0.01.
Using R's power.t.test, I input the following:
power.t.test(sig.level = .05, delta = .01, sd = .1, alternative = 'one.sided', power = 0.8)

     Two-sample t test power calculation

              n = 1237.188
          delta = 0.01
             sd = 0.1
      sig.level = 0.05
          power = 0.8
    alternative = one.sided

NOTE: n is number in *each* group

First, is power.t.test the right method to use here? Second, the result says I need 1237 samples in each group. However, since system A (control) cannot have more than 100 samples, how can I interpret or modify this test to account for that?
Answer: For an unequal sample size problem, you can use pwr.t2n.test from library(pwr).
I'm assuming from your question that you want to be able to detect a mean difference only .1 standard deviations away, so set d=.1.  Unfortunately, I don't think you'll be able to achieve .8 power under the conditions you've described, as this produces an error message:
library(pwr)
pwr.t2n.test(n1=100, sig.level = .05,  d=.1, power=.8, alternative = 'great')

If you set a more modest goal of being able to detect a d=.5 standard deviation difference between A and B, you'd need a sample size of about 33 in system B.
pwr.t2n.test(n1=100, sig.level = .05,  d=.5, power=.8, alternative = 'great')

         n1 = 100
         n2 = 33.31148
          d = 0.5
  sig.level = 0.05
      power = 0.8
alternative = greater


How to encode [CLLocation] properly in swift?

Question: I am doing an application which need to store the user's data in local. I read the documentation in Apple website, it covers part of the info in how to encode basic type, such as String and Int. However, when I try to encode with the [CLLocation]type, it failed. I am asking if some expert can give me any hint on how to encode such type in Swift?
Here is my code about the Model class.
import Foundation
import UIKit
import CoreLocation
import os.log
import CoreData

//route model
//store the model in the local database.
//change all the [CLLocations] to become the String inorder to store it in local.???? not willing
class Route:  NSObject, NSCoding {
    //MARK: Properties
     var name :String
     var area : String
     var image: UIImage?
     var date : DispatchTime
     var routePoints = [CLLocation]()
     var rating: Int

     //MARK: Achieving paths
    //static properties, belong to the
    static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
    static let ArchiveURL = DocumentsDirectory.appendingPathComponent("Routes")

    //MARK: NSCoding
    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: PropertyKey.name)
        aCoder.encode(image, forKey: PropertyKey.image)
        aCoder.encode(date, forKey: PropertyKey.date)
        aCoder.encode(area, forKey: PropertyKey.area)
        //unable to encode the [cllocation]
        aCoder.encode(routePoints, forKey: PropertyKey.routePoints)
        aCoder.encode(rating, forKey: PropertyKey.rating)
    }
    //should also added in the locations as one of the variable.
    init?(Name: String, Area: String, Date: DispatchTime, Image: UIImage?, RoutePoints: [CLLocation], Rating: Int) {
        guard (Rating >= 0) && (Rating <= 5) else {
            return nil
        }
        self.name = Name
        self.area = Area
        self.image = Image
        self.date = Date
        self.routePoints = RoutePoints
        self.rating = Rating
    }

    required convenience init?(coder aDecoder: NSCoder){
        //this is the necessary property
        //these are optional properties
        let rating = aDecoder.decodeInteger(forKey: PropertyKey.rating)
       guard   let date = aDecoder.decodeObject(forKey: PropertyKey.date) as? DispatchTime,
        let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String,
        let image = aDecoder.decodeObject(forKey: PropertyKey.image) as? UIImage,
        let area = aDecoder.decodeObject(forKey: PropertyKey.area) as? String,
        let routePoints = aDecoder.decodeObject(forKey: PropertyKey.routePoints) as? [CLLocation] else{
            print("Unable to decode")
            return nil
        }
        self.init(Name: name, Area: area, Date: date, Image: image, RoutePoints: routePoints, Rating: rating)

    }

    //MARK: Types
    struct PropertyKey {
        static let name = "name"
        static let image = "image"
        static let date = "date"
        static let area = "area"
        static let rating = "rating"
        static let routePoints = "routePoints"
    }

}

Best wishes
Answer: The reason is that CLLocation can't be stored with NSCoder.  You could implement a simple coder / decoder using a swift map for this type of value to basically store the locations in a dictionary.
let p1 = CLLocation(latitude: 1, longitude: 1)
let p2 = CLLocation(latitude: 2, longitude:2)

var locations = [p1, p2]

let codedArray = locations.map{ ["lat":$0.coordinate.latitude, "long":$0.coordinate.longitude] }
let decodedArray = codedArray.map{ CLLocation(latitude:$0["lat"]!, longitude:$0["long"]!) }

Comment: Hello, but after trying , it still doesn't work. Should I encode the codeArray?


Finding spurious regression based on Ferson et al and by detecting co-integration

Question: After reading Ferson et al's (2003) paper on spurious regression, I understand that he uses extensive simulations to generate the true regressors and then compare them with those in the literature to find out those spurious regressors. What I am still confused about is, how spurious regression can be discovered by this approach in this paper since we don't have a pool of regressors all the time?
Is it possible to detect any spurious regression by finding co-integration?
Answer:
Is it possible to detect any spurious regression by finding co-integration?

On the contrary: if cointegration is present, then the estimated statistical relationship is genuine and there might be a causal relationship between the variables, i.e. the regression might be not spurious.
However, presence of a statistical relationship (such as correlation or cointegration) does not guarantee presence of a causal relationship -- as the cointegrated variables could all be caused by yet another variable (omitted from the regression model) without causing each other.