Finding $\int \sin^2 (\pi x) \cos^5 (\pi x) dx$

Question: I am trying to find $$\int \sin^2 (\pi x) \cos^5 (\pi x) dx$$
I start by making the $\pi x$ into u
$$\int \sin^2 (u) \cos^5 (u) du$$
I then split it up like the guide says.
$$\int \sin^2 u  \cos u(\cos^2 u)^2 du$$
$$1/\pi\int \sin^2 u  \cos u(1-\sin^2 u)^2 du$$
$$1/\pi\int \sin^2 u  \cos u(1-2\sin^2 u + \sin^4 u) du$$
$t = \sin u$, $dt = \cos udu$
$$1/\pi\int t^2  \cos u(1-2t^2 + t^4) dt/ \cos u$$
$$1/\pi\int t^2 (1-2t^2 + t^4) dt$$
$$1/\pi\int t^2-2t^4 + t^6 dt$$
This gives a wrong answer and I do not know why.
Comment: This is a mess. When you change to $u$, you should not have $dx$, and you are missing a constant factor that comes from the differential (which then magically appears). The integral should not mix $x$s and $u$s, and should not mix $t$s and $u$s. It makes no sense to "divide by cos". "cos" is not a quantity, it's the name of a function, so "dt/cos" is complete, total, and absolute nonsense.
Comment: Since you don't say what "answer" you get, we don't know why you get the wrong answer either. It's too late in the week to hire spies to get at your notes and fax them to us so we can find out when you refuse to tell us.
Comment: Why is there an $x$ in an expenonent, $\sin^x (u)$?
Comment: a [similar](http://math.stackexchange.com/q/151516/31877) question was posed here earlier where evaluation of this type of integral was investigated in every possible detail
Comment: Arturo, I was puzzling over that /cos notation too.
Comment: Does this answer your question? [Integral of $\int_0^{\pi/2} \ (\sin x)^7\ (\cos x)^5 \mathrm{d} x$](https://math.stackexchange.com/questions/151516/integral-of-int-0-pi-2-sin-x7-cos-x5-mathrmd-x)
Answer: So long as you insist on pushing symbols without thinking, you'll continue to produce nonsensical strings of symbols.
If you set $u=\pi x$, then $du   = \pi\,dx$, so the integral goes from
$$\int \sin^2(\pi x)\cos^5(\pi x)\,dx$$
to
$$\int \sin^2 u \cos^5 u \frac{1}{\pi}\,du.$$
It is not okay to do some of the changes now and leave others until later. You did not change the $dx$ in the first step, and you cannot do that. Either do all the necessary changes, or do none of the changes. Otherwise, what you are writing is nonsense.
Now, you correctly take one cosine and convert the rest to sines:
$$\begin{align*}
\int \sin^2(\pi x)\cos^5(\pi x)\,dx &=\frac{1}{\pi}\int \sin^2 u \cos^5 u\,du\\
&= \frac{1}{\pi}\int \sin^2u (\cos^2u)^2\cos u\,du\\
&= \frac{1}{\pi}\int\sin^2u (1-\sin^2u)^2\cos u\,du\\
&= \frac{1}{\pi}\int\sin^2u(1-2\sin^2u + \sin^4u)\cos u\,du\\
&= \frac{1}{\pi}\int(\sin^2u - 2\sin^4u + \sin^6u)\cos u\,du.
\end{align*}$$
Now setting $t=\sin u$, we have $dt=\cos u\,du$, so making all the substitutions, not just some of them, making sure the integral is either only about $u$ or only about $t$, not about both, we get:
$$\begin{align*}
\frac{1}{\pi}\int(\sin^2u - 2\sin^4u + \sin^6u)\cos u\,du &= \frac{1}{\pi}\int(t^2 - 2t^4 + t^6)\,dt\\
&= \frac{1}{\pi}\left(\frac{1}{3}t^3 - \frac{2}{5}t^5 + \frac{1}{7}t^7\right) + C.
\end{align*}$$
Finally, you need to go back to $u$, and then to $x$. Substituting $t=\sin u$ we get
$$\frac{1}{\pi}\left(\frac{1}{3}\sin^3 u - \frac{2}{5}\sin^5 u + \frac{1}{7}\sin^7 u\right) + C$$
and substituting $u=\pi x$ we get
$$\frac{1}{\pi}\left(\frac{1}{3}\sin^3(\pi x) - \frac{2}{5}\sin^5(\pi x) + \frac{1}{7}\sin^7(\pi x)\right) + C.$$
Answer: $${1\over \pi}\int \sin^2(u)\cos(u)(1-2\sin^2(u)+ \sin^4(u))\,du
= {1\over \pi} \int t^2(1-2t^2+t^4)\,dt $$
Now multiply and integrate to get
$$ \int t^2(1-2t^2+t^4)\,dt  = \int (t^2 -2t^4 + t^6) dt=
{t^3\over 3} - {2t^5\over 5} + {t^7\over 7} + C$$
Now substitute all back in to get
$$\int \sin^2(\pi x)\cos^5(\pi x) \, dx = {1\over \pi}\left({\sin^3(\pi x)\over 3} - {2\sin^5(\pi x)\over 5} +
{\sin^7(\pi x)\over 7}\right)  + C$$
One thing to know is that your result can differ from an answer key's result by a constant.  To check for yourself definitively, differentiate.
Comment: Thanks, Arturo. I dropped it in the thick of \TeX formatting


In VBA excel I have a userform with a Listbox of items, how to prevent the user from accidently selecting items as they click into the cell?

Question: What I want to allow is the ability for a user to select a cell for a particular column and then for this to enable a pop-up menu and for them to make a selection. I was able to do this using the following link: http://www.vlsiip.com/exceltips.html
But because the initial behavior (single select) was triggering the userform upon clicking once or hitting the diagonal pad into it, and also not allowing the user to select it again  after confirming an initial selection, I instead opted for the double-click approach in vba like so:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

This worked, now I think it's more intuitive to the user -- they can click the cell twice and this triggers the menu of options, they then make a selection, hit OK and it populates the cell. And they can also double-click again while the cell is still highlighted and make any updates they wish. The problem I am facing is, since there are a lot of options in the userform and since I want to make the userform big -- when a user double-clicks the cell it automatically highlights items from the list where the users mouse is clicking at. So I think its triggered by the users mouse being in the same location of the options in the listbox. So my question is, is there a workaround here? I like the functionality of double-click so far, but am having the unintended consequence of options being accidentally clicked. This was also verified when I trimmed the list of items down to 3, it no longer had options selected, but if I reach like 15 items the userform can get accidentally clicked if the options are in the same region of where the current cell is at.
It looks similar like this but much bigger and many more options:
Comment: I just saw your response to @Tim. In essence, you should provide the code that reproduces your problem, not something, somewhere, which isn't actually producing the error you ask about.
Comment: In your screenshot the cell and list don't overlap though, so how would the user accidentally select something when triggering the userform?
Comment: @TimWilliams That was an example from the link provided. In the actual code the userform is much bigger.
Comment: I'm not sure I understand the problem. It seems you control the selection in the list and  transfer to the sheet very well. Please also show any code you have used for this (we are not happy to look at other sites for code that you should include in your question.
Comment: Hey all, figured it out. Just added a slight delay and this resolved this issue.
Answer: Was able to solve this by creating a slight delay in the userform code:
Private Sub UserForm_Activate()
On Error resume Next
Me.ListBox2.Clear

Me.ListBox2.Enabled = False

For Each element In gCountryListArr
    Me.ListBox2.AddItem element
Next element

UserForm_initialize

Application.Wait Now + TimeValue("00:00:01")

Me.ListBox2.Enabled = True

End Sub


Poisson confidence interval using the pivotal method

Question: I am trying to build a confidence interval for the Poisson distribution using the pivotal method. I have the theory down but I am struggling to come up with $h(Y, \lambda)$, the probability distribution which does not depend on the parameter.
Can anyone help me out?
Comment: When you say you want "*a confidence interval for the distribution*" do you mean (as taking your words literally would imply) that you want a CI for the *distribution function*? Or do you actually mean that you want a CI for the *parameter*, $\lambda$?
Answer: As far as I know, there isn't really a pivotal quantity for $\lambda$*, though it's possible to construct approximately pivotal quantities if $n\lambda$ isn't small. (I include $n$ there just in case you have multiple observations from the same Poisson. In many cases you'll just have the one count. From here on I'll just refer to $X$ and $\lambda$ as if we were using a single $X$.)
* However, that's not to say nothing can be done. You can derive an interval for $\lambda$ from the relationship between the Poisson and the chi-square (see the end of this section). I can't say that it counts as pivotal, though.
For example, $\sqrt{X+\frac{3}{8}}$ is approximately normal with nearly constant variance (this is related to the Anscombe transform for the Poisson), so could be used to construct an approximate pivotal quantity (by subtracting its mean for example); $\sqrt{X}+\sqrt{X+1}$ - Freeman-Tukey - is another, similar choice from which you could obtain an approximately pivotal quantity. (Indeed, the confidence interval here relies on just such an approach)
To my recollection, some papers have given other quantities - if I remember where I've seen these, I'll add references.
With large values of $\lambda$, the simpler $\frac{X-\lambda}{\sqrt \lambda}$ might be used as an approximately pivotal quantity.
But with small $\lambda$ (more generally small $n\lambda$), there's really not much that can be done - I don't think you get a function of the parameter and the data whose distribution doesn't depend on the parameter. If your $\lambda$ is down around 0.5 or 1 or 2, say, there's not much you can really do about it... the large spikes at 0, 1 and 2 change substantially in relative probability with $\lambda$ and no transformation is going to alter that.


correlation of bootstrap sample means

Question: Given a sample $\{x_1,\dots,x_n\}$, $z_1$ and $z_2$ are two bootstrap realizations of sample means, that is,
$$z_1 = \frac{1}{n}\sum\{x\in\text{bootstrap sample 1}\}$$
$$z_2 = \frac{1}{n}\sum\{x\in\text{bootstrap sample 2}\}$$
, how to compute the $corr(z_1, z_2)$?
UPDATE
To make sure I understand the problem correctly, here is what I'm trying to solve:

Here is what I tried, as @probabilityislogic suggested,
$$z = \frac{1}{n}\sum(x_ik_i) ;k_1+k_2+\cdots+k_n = n$$
, since this is a bootstrap sample, so $x_i$ are all constant and $k_i$ are random variables that
$$(k_1,k_2,\cdots,k_n) \sim Mult(k_1k_2\cdots k_n|n, p_1,p_2,\cdots,p_n)$$
. I tried to compute the mean and variance like this,
\begin{align*}
E(z) &= \sum_k\begin{pmatrix}n\\ k\end{pmatrix}p^kz\\
&= \sum_k\begin{pmatrix}n\\ k\end{pmatrix}p^k(\frac{1}{n}\sum_{i=1}^n x_ik_i)\\
&= \frac{1}{n}\left[\sum_k\begin{pmatrix}n\\ k\end{pmatrix}p^k(x_1k_1+\cdots+x_nk_n)\right]\\
&= \frac{1}{n}[np_1x_1+\cdots+np_nx_n]\\
&= p_1x_1+\cdots+p_nx_n
\end{align*}
, and since each $k_i$ could be any number in $[0,n]$, then $p_i = \frac{1}{n+1}$, right? If so,
$$E(z) = \frac{n}{n+1}\bar x$$
.
To compute covariance,
\begin{align*}
Cov(z_1, z_2) = \sum_{k_{z1}, k_{z2}}\left[\text{Pr}(k_{z1},k_{z2})(z_1 - E(z))(z_2 - E(z))\right]
\end{align*}
, where $\text{Pr}(k_{z1}, k_{z2})$ is the joint probability of $k$ for $z_1,z_2$. Am I going the right way here for covariance of $z_1$ and $z_2$?
I can't seem to figure this out here, seems too complicated to me.
Comment: Some alternative comments. First, expectation is a linear operator, so you can pull $x_i$s through, and be left with $E k_i$. Second, you are sampling from a finite population $x_1, \ldots, x_n$, so a good sampling book with sufficient explanation of the finite population sampling and inference will have all the necessary results, like expectations and covariances of the multinomial variables. Finally, the problem is not clearly formulated. There are two probability spaces, that of the normal $x$s, and that of the bootstrap samples. Correlation wrt to which field are they asking about?
Comment: One easier way to figure this out is to define $n_i$ as the number of times unit $i$ is sampled in a given bootstrap replication.  Then you have $z_1=\frac{1}{n}\sum_{i=1}^{n}n_ix_i$.  And you also have $(n_1,n_2,\dots,n_n)\sim Multinomial(n;\frac{1}{n},\frac{1}{n},\dots,\frac{1}{n})$.  Try figuring out the correlation this way (you treat the $x_i$ as fixed values).
Comment: This seems rather like routine bookwork; it's fairly easy to get the covariance out (and from there, the correlation). Is this for some subject?
Comment: @Glen_b, yes, I read it in a book, but no derivation provided in the book, I was considering doing the derivation someway that I'm not sure if it's right, so I post it here in order to get some hint.
Comment: When I did it, I approached it in a similar fashion to that suggested by probabilityislogic; I considered two vector random variables representing the number of repeats of each observation, and computed the covariance matrix (which is simple for a multinomial). From there it's simple to compute the covariance of the sums of the two samples, and from there the covariances of the sample means. Then convert that to a correlation. But there are other ways to achieve the same end.
Comment: Having thought about it some more, isn't the answer $0$?  You can write $ cov (z_1, z_2)=\sum_{i, j} x_ix_jcov (n_i^{(1)}, n_j^{(2)}) $ and because the bootstrap replicates are independent you get $ cov (n_i^{(1)}, n_j^{(2)}) =0$ for all $ i, j $
Comment: @probabilityislogic, hmm if so, we have $corr(z_1,z_2) = 0$? But the answer is supposed to be $n/(2n-1)$.
Comment: I'm looking at this problem too, but I'm thinking it should be 0 because of all the independence when selecting bootstrap samples? And my simulations don't give results anywhere near 0.5....
Comment: @avocado do you remember the book name from which the question came?
Answer: I used to think the answer should be 0, but I see what I did wrong before. The problem is not looking for the conditioned correlation, so without loss of generality, we can look at the case where $\mu=0,\sigma^2=1$:
Let $x_i^{(k)}$ be sample $i$ from the $k$th bootstrap.
Then $\bar{x}_k^* = \frac{1}{n} \sum_{i}{x_i^{(k)}}$.
Key values we need to compute are:
$E\ x_i^{(k)}=E(E[x_i^{(k)}|\mathbf{x}])=E \bar{x}=0$
$var(x_i^{(k)})=E(var(x_i^{(k)}|\mathbf{x}))+var(E[x_i^{(k)}|\mathbf{x}])=\frac{n-1}{n}+\frac{1}{n}=1$
$cov(x_i^{(1)},x_j^{(2)})=E(x_i^{(1)}-0)(x_j^{(2)}-0)=E(E[x_i^{(1)}x_j^{(2)}|\mathbf{x}])=E\bar{x}^2=\frac{1}{n}$
(same is true for $(x_i^{(k)},x_j^{(k)}) \, i\neq j$)
With above, calculation for the following should be easy:
$cov(\bar{x}_1^*,\bar{x}_2^*)=\frac{1}{n^2} (\sum_{i,j}{cov(x_i^{(1)},x_j^{(2)})})=\frac{1}{n}$
$var(\bar{x}^*_i)=\frac{1}{n^2}\left(n*var(x_1^{(1)})+n(n-1)*cov(x_1^{(1)},x_2^{(1)}) \right)\\
\quad \quad \ \ = \frac{2n-1}{n^2}$
$\rightarrow  corr(\bar{x}_1^*,\bar{x}_2^*)=\frac{n}{2n-1}$
Comment: I find it odd that the conditional covariance is 0 but the unconditional covariance is not (after all, covariance is an expectation). Any thoughts?

correlation of bootstrap sample means


Smooth Scroll to Top & Hide  Upon Click

Question: So I have it working perfectly when you click the "back to top" arrow, it hides the menu, but I just want it to do a smoothscroll to the top of the page upon click in addition to that.  You can test out what I currently have at http://rac.site44.com just readjust the width so you are in a mobile view (its responsive) and click the top-right "menu" icon to see the arrow.
Here is the HTML

Projects

About

Contact

Links

Estimate

and the JS: (Obviously I'm assuming you just need a line of code telling it to scroll to top after the $("li.top").click(function(e) { but I can't seem to figure it out)
$(function() {
  $("li.top").click(function(e) {
    $("#nav").addClass('mobile-hide');
    $(".nav-toggle").removeClass('hidden');
    $(".nav-toggle2").addClass('hidden');
    e.preventDefault();
  });
});

Thanks for the help!
Comment: http://css-tricks.com/snippets/jquery/smooth-scrolling/ looks nice
Answer: I just tested this on your site:
$("html, body").animate({ scrollTop: "0px" });

You can read about .animate() here: http://api.jquery.com/animate/

Smooth Scroll to Top & Hide  Upon Click


PHP Tree building function breaks when depth = 4 but works when depth <4, why?

Question: Frankly this is part of my uni assignment, BUT I have already done quite a bit... so please feel comfortable and keep reading since I am not asking for a cheat sheet or so :)
The project is now deployed on my website

Okay, I might have found the reason just minutes ago:
    array_push() fails after pushing many items in an array. Ridiculously small array capacity???
It works when initial depth is set to 3, since 77 rows will not BLOW UP the array; but an initial depth of 4 will generate more rows beyond the PHP array's capacity(weird, never thought about this before).
After commenting out the array_push() part, this Tree building function will work, 10+ seconds cost for an initial depth of 6... So I guess the fix would be finding another collection type in PHP that can hold that many elements...
a test shows that under my current recursive tree building function, the largest number of rows allowed in an array storage is roughly 950... Beyond this would cause an "invisible" Allowed Memory size exhausted error which simply kills the PHP script from further execution. I can fix this problem simply by introducing more array storage objects.
So Please ignore the words below, since now the question has been changed and the focus is no longer there.

The monkey level and rookie level are finished with no bugs(at least I hope so).
I encountered a weird problem when implementing the minimax search algorithm in the Veteran level, particularly when trying to build a tree up to N-th depth.
my buildTree function will only work when initial depth is set no greater than 3.
It generates 16 tree nodes when initial depth is set to 2, and 77 when set to 3.
I reckon the logic works, as you can check that using Fire Bug Console.
The purpose of this function is to simulate ai/player moves for n steps. Each move changes the cells status on the gameboard. Please go to the aforementioned website and play a rookie game so you understand what this is for.
Say, this function is used for AI. AI takes a move A, then player shall take his/her move B according to AI's move, then so forth... After making a move, certain cells on board need to be flipped. The score function is to evaluate a score based on current gameboard status.
When the function finishes, I can get a full list where each row actually represent a node in a Tree, like this :

                                 AI
                                 |
                           |-----------|
                         PLAYER       PLAYER
                           |           |
            |--------|-----------|  |-------|---------|
           AI       AI          AI AI      AI         AI
                        ......................

Below is the function that is buggy, spent hours looking at it but cannot find the cause:
function buildTree($gamecells, $depth, $side, $parent)
{
    //make copies of the arguments passed.
    $currentCells  = $gamecells;
    $currentDepth  = $depth;
    $currentSide   = $side;
    $currentParent = $parent;

    $nextMoves = $this->checkForValidMoves($currentCells, $currentSide);

    if(count($nextMoves) != 0 ) //can still move on.
    {
        foreach($nextMoves as $nextMove)
        {
            $flippedCells = $this->flipCells($currentCells, $nextMove, $side);
            $result = $this->getScore($flippedCells, $this->Session->read('aiside'));
            $score  = $result['score'] - $result['libertyPenalty'];
            $parentsTrace = $currentParent.'_'.$nextMove;

            if($currentDepth > 1)   //currentDepth == 1 means this is a leaf node.
                $this->buildTree($this->getGamecellMap($flippedCells), $currentDepth-1,
                                        $this->swapSides($currentSide), $parentsTrace);

            array_push($this->movesTree, array
                ('depth'=>$currentDepth,
                 'parentTrace'=>$parentsTrace,
                 'move'=>$nextMove,
                 'score'=>$score));
        }
    }
    if($currentDepth == 1)  //we have traversed all leaf nodes, time to quit.
        return;
}

Because I am using PHP + AJAX, my normal way of debugging in PHP (echo some stuff in function) will not work. Plus I am still confusing about what this means when it does work when initial depth is no greater than 3...
Can anyone help me out? Any suggestion is much appreciated and thanks a lot in advance!
Comment: I suggest to make a minimal working (with bug) version of the script and post it here. Just remove all unnecessary calls like `getScore`, `Session->read` and so on. It'll will be much easier to help you. Also there is posibility that you'll solve your problem.
Comment: What is main purpose of your function, are you trying to create multidimentional array?
Answer: for debug purposes i have this function:
function debug_array(){

        echo "
";

        foreach(func_get_args() as $v){
            $v = Filter::htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
        is_array($v) || is_object($v) ? print_r($v) : var_dump($v);
        }
        echo "
";
}

it is very simple to use it pass as many variables you like to debug_array()
debug_array($var1, $array, object, (bool)$test,...)

Comment: Thanks Nazariy for this helper function.
I am using PHP mainly as the "WebService" provider so the output is actually of JSON format. I will try using this in my JSON debug message to check what's going on inside my array.
Answer: You can try to debug the javascript by echoing out console.logs(), or even comments in the json output from the ajax requests (if you are evaluating them), or use something like http://www.firephp.org/.
That way you can debug it with javascript callbacks.
Spontaneous bugs are the hardest to find and fix. It looks like it's working fine now for me though.
Comment: Oh! This is EXACTLY what I have been looking for! I will definitely get the FirePHP and use it for debugging my PHP + AJAX suite. Thanks a lot!


Total perimeter of rectangeles covering the boundary of a Jordan-measurable set in in $\mathbb{R}^2$

Question: A Jordan-measurable set is a bounded set in $\mathbb{R}^2$ whose boundary can be covered with a collection of rectangles whose total volume is arbitrarily small. Since the boundary is closed, and in in this case bounded, the collection can be taken to be finite.
Question: What be said about the total perimeter of these rectangles?
I'm guessing not very much, because the volume decreases to zero much faster than the perimeter.
Comment: If you take the unit disk, you can achieve a perimeter of $\approx 16$. With wilder shapes such as $\{\frac1n|n\in\mathbb N\}\times [0,1]$, the perimeter will grow to infinity as you try to decrease the area.
Answer: By taking the union of the set $E$ with the rectangles covering its boundary, you get a set $E_n$ with piecewise smooth boundary. As the total area of rectangles goes to zero, we have $\chi_{E_n}\to \chi_E$ in $L^1$ norm. The perimeter is lower semicontinuous under such convergence.
Thus, if the total perimeter of rectangles can be kept bounded, then $E$ is a set of finite perimeter, also known as a Caccioppoli set. I think the converse is true as well, due to the fact a domain of finite perimeter can be approximated in measure by polygons with uniformly bounded perimeter (see On the rectifiability of domains with finite perimeter by Caffarelli and  Rivière, and references there). But I'd rather not work on a proof of this.


My main function is repeating in an infinite loop and I do not know why

Question: I am running a program that plays rock, paper, scissors. I have executed the code multiple times and everytime I do, the input asking the user to pick 0,1,2 repeats more than one time. It is only supposed to be asked one time per game cycle. Can anyone help me figure out why this is happening, and how to fix it?
import random

# Function: Display Menu
# Input: none
# Output: none
# displays the game rules to the user
def displayMenu():
    print("Welcome! Let's play rock, paper, scissors.")
    print("The rules of the game are:")
    print("\tRock smashes scissors")
    print("\tScissors cut paper")
    print("\tPaper covers rock")
    print("\tIf both the choices are the same, it's a tie")

# Function: Get Computer Choice
# Input: none
# Output: integer that is randomly chosen, a number between 0 to 2
def getComputerChoice():
    computerChoice = random.randrange(0,3)
    return computerChoice

# Function: Get Player Choice
# Input: none
# Output: integer that represents the choice
# Asks the user for their choice: 0 for rock, 1 for paper, or 2 for scissors
def getPlayerChoice():
    playerChoice = int(input("Please choose (0) for rock, (1) for paper or (2) for scissors"))
    return playerChoice

# Function: Play Round
# Input: two integers--one representing the computer's choice and the other representing the player's choice
# Output: integer (-1 if computer wins, 1 if player wins, 0 if there is a tie)
# This method contains the game logic so it stimulates the game and determines a winner
def playRound(getcomputerChoice, getplayerChoice):
    if getplayerChoice == 0 and getcomputerChoice == 2:
        return 1
    elif getcomputerChoice == 0 and getplayerChoice == 2:
        return -1
    elif getplayerChoice == 2 and getcomputerChoice == 1:
        return 1
    elif getcomputerChoice == 2 and getplayerChoice == 1:
        return -1
    elif getplayerChoice == 1 and getcomputerChoice == 0:
        return 1
    elif getcomputerChoice == 1 and getplayerChoice == 0:
        return 1
    else:
        return 0

# Function: Continue Game
# Input: none
# Output: boolean
# Ask the user is they want to continue (Y/N), and then return True or False accordingly
def continueGame():
    playAgain = input("Do you want to continue playing? Enter (y) for yes or (n) for no.")
    if playAgain.lower() == "y":
        return True
    elif playAgain.lower() == "n":
        return False

# Function: main
# Input: none
# Output: none
def main():
    displayMenu()
    getPlayerChoice()
    if getPlayerChoice() == 0:
        choicePlayer = "rock"
    elif getPlayerChoice() == 1:
        choicePlayer = "paper"
    elif getPlayerChoice() == 2:
        choicePlayer = "scissors"
    getComputerChoice()
    if getComputerChoice() == 0:
        choiceComputer = "rock"
    elif getComputerChoice() == 1:
        choiceComputer = "paper"
    elif getComputerChoice() == 2:
        choiceComputer = "scissors"
    print("You chose", choicePlayer + ".")
    print("The computer chose", choiceComputer + ".")
    playRound(getComputerChoice(), getPlayerChoice())
    continueGame()
    while continueGame() == True:
        displayMenu()
        getPlayerChoice()
        getComputerChoice()
        playRound(getComputerChoice(), getPlayerChoice())
        continueGame()

    playerCounter = 0
    computerCounter = 0
    tieCounter = 0

    while playRound(getPlayerChoice(), getPlayerChoice()) == -1:
        computerCounter += 1
    while playRound(getPlayerChoice(), getPlayerChoice()) == 1:
        playerCounter += 1
    while playRound(getPlayerChoice(), getPlayerChoice()) == 0:
        tieCounter += 1

    print()
    print("You won", playerCounter, "game(s).")
    print("The computer won", computerCounter, "game(s).")
    print("You tied with the computer", tieCounter, "time(s).")
    print()
    print("Thanks for playing!")

# Call Main
main()

Answer: It's because when you do:
    if getPlayerChoice() == 0:
    choicePlayer = "rock"

You are actually calling the method again.
You should do:
p_choice = getPlayerChoice()

if p_choice == 0:
...


What 130 second timeout is killing my WCF streaming service call?

Question: Just recently I started to investigate a tricky problem with WCF streaming in which a CommunicationException is produced if the client waits for any longer than 130 seconds in between sends to the server.
Here is the full exception:
System.ServiceModel.CommunicationException was unhandled by user code
  HResult=-2146233087
  Message=The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '23:59:59.9110000'.
  Source=mscorlib
  StackTrace:
    Server stack trace:
       at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.WebRequestOutputStream.Write(Byte[] buffer, Int32 offset, Int32 count)
       at System.IO.BufferedStream.Write(Byte[] array, Int32 offset, Int32 count)
       at System.Xml.XmlStreamNodeWriter.FlushBuffer()
       at System.Xml.XmlStreamNodeWriter.GetBuffer(Int32 count, Int32& offset)
       at System.Xml.XmlUTF8NodeWriter.InternalWriteBase64Text(Byte[] buffer, Int32 offset, Int32 count)
       at System.Xml.XmlBaseWriter.WriteBase64(Byte[] buffer, Int32 offset, Int32 count)
       at System.Xml.XmlDictionaryWriter.WriteValue(IStreamProvider value)
       at System.ServiceModel.Dispatcher.StreamFormatter.Serialize(XmlDictionaryWriter writer, Object[] parameters, Object returnValue)
       at System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
       at System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer)
       at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Stream stream)
       at System.ServiceModel.Channels.HttpOutput.WriteStreamedMessage(TimeSpan timeout)
       at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
       at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
       at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    Exception rethrown at [0]:
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at WcfService.IStreamingService.SendStream(MyStreamUpRequest request)
       at Client.Program.b__0() in c:\Users\jpierson\Documents\Visual Studio 2012\Projects\WcfStreamingTest\Client\Program.cs:line 44
       at System.Threading.Tasks.Task.Execute()
  InnerException: System.IO.IOException
       HResult=-2146232800
       Message=Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.
       Source=System
       StackTrace:
            at System.Net.Sockets.NetworkStream.MultipleWrite(BufferOffsetSize[] buffers)
            at System.Net.ConnectStream.InternalWrite(Boolean async, Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
            at System.Net.ConnectStream.Write(Byte[] buffer, Int32 offset, Int32 size)
            at System.ServiceModel.Channels.BytesReadPositionStream.Write(Byte[] buffer, Int32 offset, Int32 count)
            at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.WebRequestOutputStream.Write(Byte[] buffer, Int32 offset, Int32 count)
       InnerException: System.Net.Sockets.SocketException
            HResult=-2147467259
            Message=An existing connection was forcibly closed by the remote host
            Source=System
            ErrorCode=10054
            NativeErrorCode=10054
            StackTrace:
                 at System.Net.Sockets.Socket.MultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags)
                 at System.Net.Sockets.NetworkStream.MultipleWrite(BufferOffsetSize[] buffers)
            InnerException:

It appears that the server has closed the connection prematurely due to inactivity on the connection. If I instead give a pulse to the server, even one byte at a time, then I never get this exception and I can continue to transfer data indefinitely. I've constructed a very simple example application to demonstrate this which uses basicHttpBinding with Streamed transferMode and I insert an artificial delay from within a custom stream implementation on the client that delays for 130 seconds. This simulates something similar to a buffer under-run condition in which the stream provided in my service call from the client is not feeding the data to the WCF infrastructure quick enough to satisfy some sort of unidentifiable timeout value that appears to be around the 130 second mark.
Using the WCF service tracing tools I'm able to find an HttpException with the a message that reads "The client is disconnected because the underlying request has been completed.  There is no longer an HttpContext available."
From the IIS Express trace log file I see an entry that says "The I/O operation has been aborted because of either a thread exit or an application request. (0x800703e3)"
I've configured both server and client timeouts to use a value well over the 130 second mark just to rule them out. I've tried idleTimeout in IIS Express and a host of ASP.NET related timeout values too in order to discover where this issue is coming from but so far no luck. The best information I can find so far is a comment in the FireFox issue tracker by a developer that describes a similar problem working outside of the WCF architecture. For this reason I'm guessing the issue may be more related specifically to IIS7 or possibly Windows Server.
Custom binding on server Web.config
<binding name="myHttpBindingConfiguration"
         closeTimeout="02:00:00"
         openTimeout="02:00:00"
         receiveTimeout="02:00:00"
         sendTimeout="02:00:00">
  <textMessageEncoding messageVersion="Soap11" />
  <httpTransport maxBufferSize="65536"
                 maxReceivedMessageSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 transferMode="Streamed" />
</binding>

Client side configuration in code:
    var binding = new BasicHttpBinding();
    binding.MaxReceivedMessageSize = _maxReceivedMessageSize;
    binding.MaxBufferSize = 65536;
    binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
    binding.ReaderQuotas.MaxArrayLength = int.MaxValue;
    binding.TransferMode = TransferMode.Streamed;
    binding.ReceiveTimeout = TimeSpan.FromDays(1);
    binding.OpenTimeout = TimeSpan.FromDays(1);
    binding.SendTimeout = TimeSpan.FromDays(1);
    binding.CloseTimeout = TimeSpan.FromDays(1);

In response to wals idea to try to see if I get any different results by self hosting my service I want to add that I did so and found that I get the same results as when hosting in IIS. What does this mean? My guess is that this means the issue is either in WCF or in the underlying networking infrastructure in Windows. I'm using Windows 7 64 bit and we've discovered this issue by running various clients and running the service portion on a Windows 2008 Server.
Update 2013-01-15
I found some new clues thanks to DarkWanderer once I realized that WCF uses HTTP.sys underneath in self-hosting scenarios on Windows 7. This got me looking into what I could configure for HTTP.sys and also what type of issues people are reporting that for HTTP.sys that sound similar to what I'm experiencing. This lead me to a log file located at C:\Windows\System32\LogFiles\HTTPERR\httperr1.log which appears to log specific types of HTTP issues on the part of HTTP.sys. In this log I see the following type of log entry each time I run my test.

2013-01-15 17:17:12 127.0.0.1 59111 127.0.0.1 52733 HTTP/1.1 POST
  /StreamingService.svc - - Timer_EntityBody -

So it's down to finding what conditions could cause a Timer_EntityBody error and what settings in IIS7 or elsewhere may have a bearing on when and if that error occurs.
From the official IIS webiste:

The connection expired before the request entity body arrived. When it
  is clear that a request has an entity body, the HTTP API turns on the
  Timer_EntityBody timer. Initially, the limit of this timer is set to
  the connectionTimeout value. Each time another data indication is
  received on this request, the HTTP API resets the timer to give the
  connection more minutes as specified in the connectionTimeout
  attribute.

Trying to modify the connectionTimeout attribute as the reference above suggests for in applicationhost.config for IIS Express doesn't seem to make any difference. Perhaps IIS Express ignores this configuration and uses a hard coded value internally? Trying something on my own I discovered that there are new netsh http commands added to show and add timeout values so giving that I go I came up with the following command but unfortunately doing so didn't seem to have any effect on this error either.

netsh http add timeout  timeouttype=IdleConnectionTimeout value=300
Comment: ok. can you try *removing* your assigned values for the bindings on the client and server side and seeing if you get *any* difference? (may not fix problem but may narrow it down).
Also, can you run your WCF service in isolation (its own process) to rule out a few things?
Comment: we will need your app.config file (both sides)
Comment: @wal - the config files are uninteresting at this point. I'm reproducing this in a simple test app but to satisfy the request I'll update my post.
Comment: is that receiveTimeout 2 minutes or 2 hours? :)
Comment: try changing it to the max: `24.20:31:23.6470000`
Comment: 2:00:00 is 2 hours and increasing it made no difference.
Comment: @SebastianK - None more than what I have listed above in my post.
Comment: I am setting them on the client and I'm doing it through code. See the section labeled "Client side configuration in code" in my post.
Answer: It turns out that this issue was caused by the Connection Timeout value used by HTTP.sys and that can be specified through IIS Manager through the Advanced Settings for the individual site. This value is configured by default to timeout a connection when both the header and body haven't been received within 120 seconds. If a pulse of data from the body is received then the server restarts a timer (Timer_EntityBody) within the timeout value then the timer is reset to wait for additional data.

This is just as the documentation concerning Timer_EntityBody and connectionTimeout specifies, however it was hard to pinpoint because it appears that IIS Express ignores the connectionTimeout value specified in the limits element in applicationhost.config regardless of what the documentation says. In order to determine this I had to install the full version of IIS on my development machine and modify the setting above after hosting my site there.
Since we are hosting the real service under IIS on Windows 2008 the above solution will work for me however the question still remains on how to properly modify the Connection Timeout value in cases where you are Self Hosting.
Comment: Yes, I tired 140 at first and then tested with a delay of 133 and 160 just to ensure that it would pass for the first and fail for the later and it did just that. I did further testing at 400 seconds and 600 as well just to confirm that the setting was indeed the value that affected this behavior.
Comment: Does anyone know if MS intends to fix IIS Express to honor the connectionTimeout value in limits in applicationhost.config?
Comment: @jpierson Did you ever figure out how to increase the idle timeout for self-hosted services?
Comment: I'm not self hosting in my scenario so no I haven't had to tackle that one. I would welcome any insight here on the matter though just in case any of us need to self host and run into a similar problem though.
Answer: Judging from the error:

The socket connection was aborted. This could be caused by an error
  processing your message or a receive timeout being exceeded by the
  remote host, or an underlying network resource issue. Local socket
  timeout was '23:59:59.9110000'

Looks like this is a simple TCP timeout.
You can verify it by running the application as self-hosted, and then running this command in console:
netstat -no |find "xxxxx"

where xxxxx is the PID of your server process. This command will show you the connections your server has established and refresh every second.
Try to connect with the client and see what happens. Most likely, you'll see "CLOSE_WAIT" or "TIME_WAIT" on your connection after around 100-120 seconds - which will mean it was aborted due to timeout.
This sould be fixable by adding the following to your config:
<httpTransport maxBufferSize="65536"
             maxReceivedMessageSize="2147483647"
             maxBufferPoolSize="2147483647"
             transferMode="Streamed"
             keepAliveEnabled="true" />

The parameter is explained here
Comment: I also assumed at this point that the issue must be related to some lower level timeout such as in the underlying socket. Not sure yet at this point if the timeout value would be server-side or client-side though. Also the keepAliveEnabled value didn't seem to have any effect.
Comment: Still trying to wrap my head around the output from netstat because it shows an unexpected PID as for the process that owns the open port in my tests. It's showing PID 4 which is associated with "System" ntoskrnl.exe and not my self hosting command line application.
Comment: Well, whatever the PID investigation shows, result will be the same... I guess, keepAliveEnabled="true" has no effect with transferMode="Streamed", due to the nature of the streaming socket. If you confirm the reason outlined above, I'd recommend you settle with own "keepalives", as you described in the question.
Comment: It turns out that PID 4 is the Kernel. From what I can gather this is the normal way self hosting is done on Vista and up in that everything is hosted underneath HTTP.sys. I tried changing the the idleConnectionTimeout value for the HTTP.sys module by running "netsh http add timeout  timeouttype=IdleConnectionTimeout value=300" but it didn't seem to make any difference.
Answer: Probably long shot, but... Check your IIS app pool if it has Ping enabled. It's in advanced settings, Process Model grouping.
Comment: yeah, probably unrelated then. I was thinking setting piningEnabled to false or increasing pingResponseTime would help.
Comment: I looked into this and unfortunately I'm reproducing this right now on IIS Express and setting the pingFrequency value in the applicationhost.config only caused IIS Express to crash upon startup. It appears to me that perhaps IIS Express doesn't have the same process model or process model configuration that full IIS has? Perhaps this also indicates that this is not the source of the issue since I'm able to reproduce this just the same regardless of whether I'm running the serivce in IIS7 or IIS Express.
Comment: The documentation on the  element must have been outdated. I've found and tried using the attributes pingingEnabled, pingInterval, and pingResponseTime but unfortunately I haven't stumbled across a combination that works.
Comment: Thinking down the same lines those are the first things I tried after you brought those settings to my attention. Thanks for your input.
Answer: Try this, for me it solved the problem. The problem is that the underlying kernel http.sys has it's own timeout and it will break the connection.
http://mmmreddy.wordpress.com/2013/07/11/wcf-use-of-http-transport-sharing-persistent-tcp-sessions/

netsh http add timeout timeouttype=idleconnectiontimeout value=120

Comment: See near the end of my question, I actually tried this setting to avail in my case.
Answer: Did you consider http://support.microsoft.com/kb/946086 ?
I observed such streaming interrupts in my ISAPI-Extensions. After switching off
buffering in IIS 7 according to this suppport note, everthing worked fined.
Comment: No, I hadn't come across that KB article but to me it seems somewhat unrelated. I was very specifically running into a timeout issue as opposed to an issue that has to do with a buffer hitting the limits of it's capacity. I'm sure of this because the accepted answer which entails changing the timeout in IIS directly solved this problem.


Rests & Their Usefulness in Drums

Question: Well, I'm a drummer. I've been drumming for the past three years. I can read sheet music and I have this question.
What's the point of having 'rests' in drums. I mean, why can't you leave the part where you want a rest, blank?
Comment: You would have to lengthen the note value of the preceding notes to fill in the empty space -- notation MUST be time-consistent.
Comment: The thing about rests is that they are not all the same. They have a particular duration, just as ordinary notes do. If you don't know exactly how long to pause, you won't know when to come back in.
Answer: It's easy to think that a short sound just needs a blob on the music, but it's easier to count through the bars if each one has the prescribed number of beats. Imagine a snare on 2 and 4. If the rests on 1 and 3 weren't marked, you may well think that the first snare hit was on 1.  Who knows?
Whilst most drum sounds are short, cymbals can ring for a whole bar at least. If the composer wanted a short cymbal sound, a quaver (really short), crotchet,(longer)  with appropriate rests to say 'stop it now' gives great information.
The rest signs are exactly what they say - no noise now, for this long.
Comment: with standard notation, you can only *sort of* tell when the note starts by looking at it's spacing.  But when things get busy, the spacing can change wildly.  This *rubber banding* of time makes rests necessary.  Without the rubber banding, standard notation would take up a lot more space (as piano roll notation does).  But if things are always busy *anyway*, like they usually are with drums, piano roll notation can be a lot better.  (*my* opinion)
Comment: @StephenHazel- rather reminiscent of guitar tab. Really well written stuff will be somewhat accurate timing-wise.Other is almost impossible to read from a timing point of view.The spacing can be well out. Heard of electronic drums, but those with a rubber band ?
Answer: Imagine a rest as a placeholder signifying the presence of nothing, sort of like how 0 acts in mathematics. While not actually anything, it relays the information that there is literally nothing there. You could imagine how impossible it would be to decipher a number with no placeholders for nothing.
So instead of a rhythm looking like this, with 1 being a note and 0 being a rest, or empty space:
1 0 0 0 |0 1 0 0 |0 0 1 0 |0 0 0 1 |

This hemiola depends on understanding the space between sound. Without rests as placeholders for silence, you would get something that looks like this:
1       |  1     |    1   |      1 |

Whoops, that doesn't make sense anymore. It looks like you're trying to guess where the beat is.
In the end, it's all for greater precision and accuracy, especially when playing with others.
Comment: Wait-- drummers pay attention to the rest of the group? :-)

Rests & Their Usefulness in Drums


How many partitions are there?

Question:
How many partitions are there for $\{1,\cdots,100\}$ for $3$ sets, $A,B,C$, such that $A$ cannot contain consecutive numbers ($\left|a-b\right|=1$)

Anyway, I thought about using recurrence relation here. Where $a_0 = 1$, $a_1 = 3$, but I'm not sure how to build the general case, $a_n$.
Answer: Let $a_n$ be the number of partitions of $\{1,2,...,n\}$ into $A,B,C$ where $n\in A$,
$b_n$ the number of partitions of $\{1,2,...,n\}$ where $n\in B$,  and $c_n=b_n$.
Set up the recursions, for example $a_{n+1}=b_n+c_n$.

How many partitions are there?


Ranking on multiple variables

Question: I have a list of items (in my case firms) and four characteristics, lets call them A,B,C, and D.
My goal is to rank the firms in my sample based on these characteristics and to find the the firms with the highest (lowest) characteristics A,B,C and D. How can this be done?
I guess this would be like a multivariate ranking or sorting procedure.
Comment: Are all the characteristics equally important? What scale(s) are they measured on?
Comment: I guess all characteristics are equally important. The multiple characteristics are basic key figures, such as firm size, profitability,.. etc. So the characteristics have very different scales.
Answer: There are two options for establishing such a ranking. On the one hand you can define a ranking order, and rank the firms first according to A, then B, etc. On the other hand you can combine the scores of A..D to obtain a single score, which can then be ranked trivially.
I am assuming that you would be more interested in the latter. In order to combine the scores of A to D in a fair way it is important to ensure that they operate on the same scale. If the scores are not already operating on the same scale, then this can be established by normalising each score between 0 and 1 (divide all values for a specific score by the maximum of that score, assuming all scores are positive) or between -1 and 1 if the scores can take on negative values.
Once you have normalised the scores, you can combine them. This can be done trivially by simply taking the average of the score, or by specifying specific weights based on the importance of the score. If you have some historical data available with the correct rankings, then you could also consider to apply regression to this data in order to obtain the weights for each score.
I would start with a simple average of the combined scores, and then ranking. If that does not produce satisfactory results I would manually play a bit with the weights, and see if you can find a configuration that better suits your needs.
Comment: This is a potentially valid answer. There are two things I would also suggest considering: 1) Instead of normalising the scores by scaling you might instead calculate the centiles for each firm on each characteristic (so that the best firms would score 0.9-1, say) and then combining these. It's hard to know whether this would give better or worse results, but it is something that came to mind. 2) Do you want to favour firms which are consistently good or are you happy for firms which excel on one characteristic only to go near the top of the ranking? If the first consider a $x^2$ term.
Comment: Also, if you want to be sure that the top firms are not awful at anything, consider using the geometric mean (i.e. doing the calculation on a log scale).
Comment: Is there a formal name for the latter method (i.e., normalizing the scores and adding them together) so one can learn more about it?

Ranking on multiple variables


Aplicar icon consoante o valor de texto na célula

Question: Assumindo como exemplo a coluna E, cuja mesma contém o valor Sim ou o valor Não, estou a tentar criar uma formatação condicional que aplique uma seta consoante o texto presente na própria célula:
Sim   = Verde
Não   = Vermelho
outro = Amarelo

A questão é que isto não parece funcionar com texto, apenas com números porque por defeito já assume uma comparação >=.
Se utilizar números, obtenho o resultado pretendido:

Que resulta em:

Mas o problema é que -1, 0 e 1 não são humanamente legíveis (salvo para o programador...).
Pergunta
No Libre Office Calc, como aplicar uma seta automaticamente com base num valor de texto presente na própria célula?
Se impossível, uma alternativa aceitável passa por aplicar uma formatação posterior à formatação condicional onde o valor 1 seja apresentado como Sim, e o valor -1 como Não.
Exemplo da folha de cálculo: exemplo.ods
Comment: Você tentou usar uma fórmula que "traduz" o texto automaticamente para 1, -1 ou 0 (por exemplo, usando a [função `SE`](http://www.ubuntudicas.com.br/blog/2011/11/funcao-se-libreoffice/))? Aliás, você poderia compartilhar um exemplo mínimo da planilha, só pra facilitar os testes de quem for ajudar. :)
Comment: @LuizVieira Adicionei uma folha de calculo exemplificativa. A função `SE` ainda não experimentei, vou testar isso. Tks!
Comment: Eu tava testando aqui, mas parece que ele aplica a formatação condicional só que não exibe quando o conteúdo é texto. Fiz o seguinte teste: apliquei a formatação na coluna usando uma fórmula que referencia a coluna seguinte; ele não exibe os ícones, mas se eu mudo o valor de uma célula pra numérico, dai então ele exibe o ícone. Parece que a minha sugestão não vai funcionar, porque o recurso é só pra células de valor numérico... :(
Comment: @LuizVieira Os meus testes antes de colocar a pergunta também me fizeram chegar a essa conclusão...
Answer: O problema parece ser realmente o fato de que esse tipo de formatação condicional (Icon Set) só funcionar para tipos de dados numéricos. Mas não achei confirmação oficial para essa suspeita em lugar algum da Internet (apenas achei indicação de que é impossível usar um conjunto customizado de ícones, porque a imagem é compilada junto ao código fonte do LibreOffice).
Enfim, descobri uma forma de fazer o que você quer com a alternativa que você mesmo sugeriu: usar na célula realmente os valores numéricos, mas exibí-los ao usuário na forma de texto. Para isso, basta criar novos estilos específicos para os textos "Sim", "Não" e "Outros".

Abra a janela de Estilos, acessando o menu "Formatar" (Format) -> "Estilos e Formatação" (Styles and Formatting) - no meu LibreOffice, que está em inglês, a tecla de atalho é F11.

Nessa janela, clique com o botão direito do mouse sobre o estilo base (Default) e selecione novo. Você vai precisar criar um estilo para cada valor discreto dos seus dados (isto é, um para "Sim", um para "Não" e um para "Outros" - como no seu exemplo). Dê o nome ao seu estilo na aba principal.

Na aba "Números" (Numbers), selecione na categoria o formato definido pelo usuário (User-defined, no meu caso em inglês) e digite a string que deseja que apareça (entre aspas!) no campo do código de formatação (Format code). Clique Ok e esse estilo estará gravado.

Faça o mesmo para todos os estilos. No final você vai ter algo assim:

Agora, vá na coluna de dados que você deseja formatar (que, naturalmente, deverão conter os valores numéricos 1, 0 ou -1 ao invés de texto) e adicione normalmente a formatação condicional de ícones (Icon Set) que você já estava usando. Então, clique em "Adicionar" (Add) para incluir uma nova formatação simples, escolhendo o valor e o estilo a ser aplicado.

Repita para todos os valores/estilos possíveis (no seu exemplo, ao final você vai ter 4 condições simultâneas: a dos icones, e 1 para cada possível texto "Sim", "Não" e "Outros"). Depois de aplicado, os seus dados vão ser exibidos como você deseja, muito embora o valor das células ainda seja numérico (como você pode perceber pelo número exibido ali em cima, onde indicado em vermelho).
Comment: Impecável, um pouco trabalhoso, mas como é reutilizável, Impecável! :)
Comment: Lembre-se que você também pode aplicar o estilo (de texto, não a formatação condicional de ícones) manualmente a uma célula usando a função style em uma fórmula. Como ela retorna sempre 0, você pode fazer, por exemplo: =1+Style("Sim"). Ai só precisa deixar fixa a formatação condicional de ícones. O resto você controla ao atualizar as células. :)


Check if function belongs to a class

Question: I'm trying to write a documentation testing tool which checks whether the docstrings match the actual function signature (among other things). However, I've run into a bit of a roadblock. I can't find a way to figure out whether a given function belongs to a class or not.
import inspect

def func1():
    pass

class Foo:
    def method(self):
        pass

print(inspect.ismethod(func1))  # prints False
print(inspect.ismethod(Foo().method)) # prints True
print(inspect.ismethod(Foo.method)) # prints False - I want something that prints True here

The problem is that methods usually have self as their first parameter, and this is never documented (for obvious reasons). This would cause my tests to fail, since they'd encounter a parameter that's not documented.
I would prefer to not explicitly check if the first parameter is called self and skip it, because a) nothing prevents a function from having a parameter called self and b) the name self itself is a matter of convention (so you could have a method with a first param that's called this_is_definitely_not_self) and my tool would fail in either case. I also can't just initialize an object and check if the function is a method, because this would fail with any class that takes required parameters in its __init__.
So the question is, is there any way I can detect if a function is a method before it is actually bound to an object? Or do I need to resign myself to just checking if the first parameter is called self?
Comment: @patrick `Foo.method.__name__` will just be `method`. `__qualname__` might work for that though.
Comment: You can, at best, detect that a function was originally defined in a class body, semantically speaking. **That's it**. What is the actual use case you are trying to solve here?
Comment: When you're iterating over the members of a class, you know that the attributes that are functions are methods of that class.
Comment: You could look for a `.` in the function name.  `inspect.ismethod(Foo.method) or '.' in Foo.method.__name__`
Comment: @kindall while this is true _if_ you're iterating through the members of a class, I'd like each test to work on arbitrary callables and then have a separate test runner-type entity that does the job of discovery and iteration.
Comment: The thing is, that functions are [descriptors](https://docs.python.org/3/howto/descriptor.html); **any** function can be added to a class and become part of it. Or you can manually bind a function to an instance.
Comment: Also, any reason why the docstring must have the function signature in it? Why not **generate** that signature when you are generating your documentation?
Comment: @MartijnPieters The idea is to build a documentation testing tool that checks for function signature mismatches between `numpydoc` documentation and the actual code. Essentially something that you'd run against your code along with your unit tests, ensuring that your docs don't go out of date. When doing this, because `self` is not typically documented as a parameter, the test fails for functions that _would be bound if the class was instantiated, but aren't because it isn't_. I'm simply looking for a clean way of determining if something is be a bound method without needing to make an object.
Comment: I should not be the first to think this. But since nobody is talking about it, it  must not be right for this case. So, please tell me why not do a `'method' in dir(Foo)`.
Comment: @Abhijeetk431 because I want to be able to check this on an arbitrary object. Consider that I'm testing 100s of functions/methods in 10s of classes. Given an arbitrary callable from this list, I want to have a way of detecting whether it belongs to a class (any class), so I can exclude `self` from the parameter checking, or whether it's free-standing, so I can check all the parameters.
Answer: One option is __qualname__. For methods this includes the class name which you can use. This is one of the reasons why it was added:

definition.__qualname__
The qualified name of the class, function, method, descriptor, or generator instance.

See PEP 3155's proposal for more on this attribute.
Of course, since __qualname__ is set during class definition, one can get false-positives when functions are dynamically added to a class. So, this answer basically covers the question of if a function has been defined in a class.
So, there's no clear-cut way to detect this since, a function defined inside a class and accessed via the class and a function outside a class have no difference. (except for __qualname__ in most cases).
A sensible course of action would be to use the __qualname__ as a "quick" check to see if a function has been defined inside a class and, if that is False, fall back to checking for self with the inspect.signature function and 'self' in signature(func).parameters.
You won't be able to cover all cases, this is Python and I can do pretty much anything I'd like. Purportedly we are all consenting adults, though. :)
Comment: Ouch! That's a nasty gotcha, I can see it leading to some really hard-to-find bugs. Not sure it's better than just checking for `self` in that case :\ Have an upvote in any case!
Comment: @ChinmayKanchi yup, and I can see how the approach of checking for `self` can also lead to nasty places. I don't believe there's a single approach that covers all edge cases; it seems you'll need to combine approaches.
Comment: I might just stick to checking for `self` actually. Since this is a documentation testing tool, I think I can reasonably make the assumption that anyone who cares enough to run it, will care enough to not make totally stupid decisions like renaming `self` :p
Comment: Plus, I don't think I've ever seen in-the-wild code that used `self` in an unbound function or called the first parameter of a bound method anything other than `self`. I have certainly seen code that adds methods to objects/classes at runtime though (and have even written some when auto-generating tests)!

Check if function belongs to a class


Why can users delete their questions if someone already contributed an answer?

Question: I helped the user @Natsu to solve his employment test. I spent half a day on it, because there were many things that I did not knew myself. So I posted my answer and he commented that it solved his problem!
But then an hour later he deleted his question and my whole work was pointless! I answered the question not only for him, but for many other users who will have the same question in the future.
Why can users delete their questions which already have an answer, wasting the helpers time? I won't help any fresh users anymore after this, thats for sure.
Answer: Black, I am sorry as you had felt bad for this scenario.
In more perspective, this user should not delete their question when anyone gives a useful answer over it. But As a Q&A  community member, a user can delete his/her delete their, it is his/her call. We cannot changes a user mindset :).
As this question and answer both have a valuable for the community, So at last day, I saw your post and I have Undelete question. Now it open.
Comment: Thank you very much!


Como obter a diferença entre datas em dias uteis e fim de semana no javascript

Question: Preciso construir uma aplicação que faz o check-in em um hotel, o valor da diária de seg a sex é x e fim de semana é y. Gostaria de saber como eu faço esse cálculo quando houver dias da semana e do fim de semana misturados.
Estou usando o Date para pegar os dias que foram selecionados no calendário, e um for para ver quantos dias o usuário ficou hospedado, mas não consigo saber se houve finais de semana ou não;
segue exemplo
<code> // If para validar se a hospedagem está em dia de semana
  if (data_entrada.getDay() >= 1 && data_saida.getDay() <= 5) {
    for (let index = data_entrada.getDate(); index < data_saida.getDate(); index++) {
      vSumDiasHospedagem++
    };

    validaTaxaExtra = data_saida.getHours() + ':' + data_saida.getMinutes();

    if (validaTaxaExtra > '12:00') {
      vSumDiasHospedagem++
    }

    vSumTotal = vSumDiasHospedagem * 450;

  }
</code>
No else sigo a mesma lógica só passando os valores do fim de semana
Answer: Portanto fazes um ciclo pelos dias e verificas se é dia de semana ou fim-de-semana para incrementar os respetivos contadores.
Depois verificas se passa do meio-dia e se é dia de semana ou fim-de-semana.
Por fim fazes a conta do total tendo em conta os preços à semana e ao fim-de-semana.
<code>vSumDiasHospedagem = 0;
vSumDiasSemana = 0;
vSumDiasFimDeSemana = 0;
vSumTotal = 0;

let day = new Date(data_entrada);
while (day <= data_saida) {
    vSumDiasHospedagem++;
    var dt = new Date(day);
    if (dt.getDay() >= 1 && dt.getDay() <= 5) {
        vSumDiasSemana++;
    }
    else {
        vSumDiasFimDeSemana++;
    }

    let next_day = day.setDate(day.getDate() + 1);
    day = new Date(next_day);
}

validaTaxaExtra = data_saida.getHours() + ':' + data_saida.getMinutes();

if (validaTaxaExtra > '12:00') {
    vSumDiasHospedagem++;
    if (data_saida.getDay() >= 1 && data_saida.getDay() <= 5) {
        vSumDiasSemana++;
    }
    else {
        vSumDiasFimDeSemana++;
    }
}

vSumTotal = (vSumDiasSemana * 450) + (vSumDiasFimDeSemana * 600);
</code>
Comment: Vlw, foi resolvido


Problemas com modal/boostrap

Question: Olá, estou com um problema no meu site, gostaria que quando eu clicasse no botão do modal, ele fechasse e abrisse o modal novamente(o código a seguir é um código resumido do que eu necessito), neste código, quando eu abro a página o modal abre automaticamente, e quando eu clico no botao close, ele fecha e abre, porém, quando faço isso duas vezes, o modal simplesmente não abre mais e a tela fica toda preta e travada.

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Activate Modal with JavaScript

  <button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

          <button type="button" onclick="functiona()" class="btn btn-default" data-dismiss="modal">Close</button>

<?php
      $IdUsuario = $_GET['IdUsuario'];
      $senhaConfere = "nao"

      if (isset($senhaConfere)) {
        if ($senhaConfere=="nao") {
          echo $senhaConfere;
          ?>

    <?php
        }
      }
    ?>
}
?>

Alguém já teve esse problema, ou sabe como resolver?
Grato desde já!
Comment: @EricRosário valeu, vou verificar.
Comment: Ás vezes o problema está na inserção de arquivos JS do Bootstrap,verifique o console do seu navegador pode estar faltando algum import e aparentemente seu código está com duas declarações de Bootstrap o que pode esta ocasionando esse conflito!
Comment: Quando você fecha o modal ele tem de abrir logo de novo de imediato ? então porque permitir ele fechar ?
Answer: Amigo, você não pode colocar tudo na mesma função, por que você tá usando a mesma para ocultar e exibir chame-as separadamente, tente fazer da seguinte forma:

Comment: Valeu, vou tentar assim mesmo, quando chegar no local aviso se funciona
Comment: Infelizmente o problema persiste.

Problemas com modal/boostrap


Show that at least 4 of any 22 dates in the calendar must fall on the same day of the week

Question: Show that at least 4 of any 22 dates in the calendar must fall on the same day of the week
I have a question regarding this proof. When we assume the opposite is true, that is, assume that no more than 3 of the 22 days fall on the same day of the week. Does this mean 22 consecutive days or 22 random dates? Or does it mean that we have to choose 3 full weeks + 1 extra day which would obviously contradict the assumption that 22 days were picked so 21 days were picked.
If any 21 random dates were picked say... 26th july-31st july (6 days), 2nd august-7th august (6 days), 9th august-14th august (6 days), 16th august-18th august (3 days) = 21 days then 4 mondays can be picked, 4 tuesdays or 4 wednesdays so I am confused by how picking 21 days results in at most 3 of days falling on the same day of the week.
So does it mean any 21 days or 21 consecutive days?
Comment: This follows from the Pigeonhole Principle.
Comment: yes the pigeonhole principle would apply if they were consecutive days but since it is ANY 21 dates then I can pick 21 wednesdays which is > at most 3 @GeoffreyTrang
Answer: I am afraid I cannot see which part of your question is the proof that you want to see explained. If you could clarify where the unclear proof starts and ends in your post, we can address your actual question.
However, if you are also happy with a reference so that you can solve the problem on your own, then you should have a look at the pigeonhole principle: https://en.wikipedia.org/wiki/Pigeonhole_principle The generalized version applies to your problem. The pigeon holes are the seven days of the week, and the 22 dates are the pigeons. If you don't believe the pigeonhole principle, try to prove it by contradiction.
Edit:
After reading some of your comments, I think that the following might be the problem. The proof states: If you pick days from the calendar such that each day of the week appears $\leqslant 3$ times, then you picked only up to $21$ days.
Maybe you understood it like: If I pick $21$ days from the calendar, then each day of the week occurs $\leqslant 3$ times.
The first reading is intended in the proof, and the statement is true. The second understanding of the proof is indeed wrong, as you pointed out in several comments (with the counterexample of 21 Wednesdays).
Comment: It is the first part of the proof, where you assume the contrary. I am aware of the pigeonhole principle. But the 22 dates are random dates and so are the 21 dates. If I pick any random 21 dates I can choose 21 wednesdays each on different weeks which would not mean at most 3 wednesdays were picked, it would be 21
Comment: I added a suggestion to my answer that might help. But I still don't see where you cite a proof. Maybe can you edit your original question and make this very precise?
Comment: I think you answered my question so theres no need but I will just double check, so what they're trying to say if if at most 3 days of the week occurs less than 3 times then *at most* 21 consecutive days must have been picked right not random days?
Comment: @computerscienceI don't get what you mean. I don't mean anything containing "at most 3 different days of the week. I was never talking about consecutive days (and I think the proof also never explicitly meant consecutive days). In fact, it does not matter wether the picked days are consecutive or partially consecutive or not consecutive. And what do you mean by "picked right not random days"?
Comment: sorry I am not great at explaining things. You said this: 'The proof states: If you pick days from the calendar such that each day of the week appears ⩽3 times, then you picked only up to 21 days.' Please elaborate on this. Where in the proof does it state that '*up to* 21 days' were picked? I thought 21 days *had* to be picked
Answer: It means $22$ random dates. And nobody claims that picking $21$ days always results in at most $3$ of days falling on the same day of the week. But sometimes it does. Just pick $3$ random Saturdays, $3$ random Sundays, and so on. In the end, you will have $21$ says, with exactly $3$ of days falling on each day of the week.
Comment: I agree with your example but my example I showed above when I picked monday-saturday then monday-wednesday I proved the statement wrong. If it is sometimes true then its not true
Comment: Indeed. And that's what I wrote, right?! That's why there's the number $22$ in the statement of the problem; it's because if you have less than $22$ days, then the statement is not always true. And $21<22$.
Comment: so if I pick 21 wednesdays (as you said any 21 days) then at most 3 wednesdays were not picked
Comment: Where did I say "any $21$ days"?
Comment: If I'm not mistaken you said 'it means 22 random dates' and you said '3 random saturdays, 3 random sundays' etc which would mean any 21 days
Comment: Firs of all, I *never* wrote "any $21$ days". Furthermore, a set of $3$ random Saturdays, $3$ random Sundays and so on is *not* an arbitrary set of $21$ days. Actually, it's a *very specific* type of set of $21$ days.
Comment: That is what my question was, do we pick any 21 days or 21 consecutive days? That's where my confusion lies
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/128976/discussion-between-jose-carlos-santos-and-computerscienceisapain).
Answer: The idea is to use $7(3)+1=22$ to show there are at least $3+1=4$ dates on at least 1 day of the week. Even split $21$ allows $3$ each day of the week, and in any other case by law of averages, at least $1$ day has more than $3$ .  So assume the exceptional case for $21$, then adding $1$ date, forces at least $4$ on exactly one day of the week.


PSYoungGen has wrong space

Question: I test some jvm arguments to show GC logs,and find some details not as I wish, Maybe I was wrong?
public class EdenDemo {

private static final int _1MB = 1024 * 1024;

/**
 * vm arguments:-verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:SurvivorRatio=8
 */

public static void testAllocation(){
    byte[] allocation1, allocation2, allocation3, allocation4;
    allocation1 = new byte[2 * _1MB];
    allocation2 = new byte[2 * _1MB];
    allocation3 = new byte[2 * _1MB];
    allocation4 = new byte[4 * _1MB];
}

public static void main(String[] args) {
    testAllocation();
}

}

the jvm arguments

-verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:SurvivorRatio=8

the gc logs

[GC (Allocation Failure) [PSYoungGen: 6794K->990K(9216K)]
  6794K->5094K(19456K), 0.0041458 secs] [Times: user=0.00 sys=0.00,
  real=0.00 secs]  Heap  PSYoungGen      total 9216K, used 7372K
  [0x00000000ff600000, 0x0000000100000000, 0x0000000100000000)   eden
  space 8192K, 77% used
  [0x00000000ff600000,0x00000000ffc3b718,0x00000000ffe00000)   from
  space 1024K, 96% used
  [0x00000000ffe00000,0x00000000ffef7910,0x00000000fff00000)   to
  space 1024K, 0% used
  [0x00000000fff00000,0x00000000fff00000,0x0000000100000000)  ParOldGen
  total 10240K, used 4104K [0x00000000fec00000, 0x00000000ff600000,
  0x00000000ff600000)   object space 10240K, 40% used
  [0x00000000fec00000,0x00000000ff002020,0x00000000ff600000)  Metaspace
  used 3244K, capacity 4496K, committed 4864K, reserved 1056768K   class
  space    used 350K, capacity 388K, committed 512K, reserved 1048576K

why the PSYoungGen space size is 9216k(9M) not 10M?
 I already set "-Xmn 10M"
Answer: Quoting your logs
... eden space 8192K, 77% used ...
... from space 1024K, 96% used ...
... to space 1024K, 0% used ...

Young space -Xmn is a sum of eden, S0, S1 (from and to are same as S0, S1, though S0 have from role for half of collections and to role for others, same for S1).
eden + from + to = 10MiB as expected.
Though, due to logic of young collection, to space should have zero utilization at all times, so effective capacity of young space is eden + from thus 9 MiB.
In general, though, some GC variant can dynamically adjust young space size (only reduce it compared to -Xmn) so effective young space at runtime could be smaller than configured.

PSYoungGen has wrong space


Windows Server Backup crashing

Question: Environment: I'm running an HP DL165 G7, with Windows 2008 R2 x64.
Recently, when I perform a backup with "Windows Server Backup", it will crash the system.  I run the backup over the weekend.  When I come in on Monday, it has the screen shows a BSOD. (I will try to get the info from BSOD).
I have to hold the power button to power down the system.  Then power it back on.  It comes back up normally; all features running: Active Directory, DHCP, DNS, WINS, etc.
I check the event log.  At the start of the backup I get a series of warnings Event ID 8230:

Volume Shadow Copy Service error: Failed resolving account admin6 with status 1376. Check connection to domain controller and VssAccessControl registry key.
Operation:
    Initializing Writer
Context:
Writer Class Id: {afbab4a2-367d-4d15-a586-71dbb18f8485}
    Writer Name: Registry Writer
Error-specific details:
    Error: NetLocalGroupGetMemebers(admin6), 0x80070560, The specified local group does not exist.

Then I get Error Event ID 8193

Volume Shadow Copy Service error: Unexpected error calling routine RegOpenKeyExW(-2147483646,SYSTEM\CurrentControlSet\Services\VSS\Diag,...).  hr = 0x80070005, Access is denied.
  .
  Operation:
    Initializing Writer
Context:
    Writer Class Id: {e8132975-6f93-4464-a53e-1050253ae220}
    Writer Name: System Writer
    Writer Instance ID: {9d7780ba-4e63-4c0e-a90c-c6f492c75870}

I've done some googling.  but most of the responses I've seen involve Small Business System (like this: http://support.microsoft.com/kb/2537096) or SQL server, which this server does not have.  I'm still searching.
Does the SBS situation apply? I'm thinking no, but need verification.
Anyone experience these errors before? and what solutions were applied?
Comment: 1. I wouldn't suspect the VSS errors to be related to the BSOD. The VSS errors look like permissions problems. 2. If you're going to ask a question about a BSOD then make sure you have the BSOD information to post in the question. There are about a bazillion reasons a Windows machine can BSOD and at this point we'd be guessing as to what's causing yours. 3. I wouldn't think the SBS issue is related to your issue. The SBS issue looks like it's related to the SharePoint VSS writers, which shouldn't exist on your system.
Comment: What joeqwerty said.  BSODs are frequently hardware-related;  perhaps network or hard drive?  That's just a wild guess because we don't have your BSOD info.
Comment: Yeah, I screwed up and didn't get that information.  it was a rush since the company was waiting for the server to come back up.
Answer: http://www.itexperience.net/2011/09/02/vss-error-failed-resolving-account-administrator-with-status-1376/
this link showed how to do it.  it's  registry change.  go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS\VssAccessControl
Find the account that is shown (in the event log error) and delete that entry.  I guess I misread or didn't understand what this was asking me to do.
I deleted the registry entry and both the errors do not show up during backup.  Hopefully it won't crash the system.  If the BSOD appears again, then it wouldn't be related to this issue and I'll research and start another topic if necessary
Answer: The Event ID 8193 error is caused by installation of the DHCP Server role on your server.  During installation of that role, the registry key referenced in the event log entry (HKLM\SYSTEM\CurrentControlSet\Services\VSS\Diag) has its permissions overwritten, resulting in the NETWORK SERVICE account no longer having access to that key.
This is documented at http://support2.microsoft.com/kb/2298620.
The solution (taken from the MSKB article) is as follows:

Download the SubInACL.exe tool from the following Microsoft website: http://www.microsoft.com/downloads/en/confirmation.aspx?familyId=e8ba3e56-d8fe-4a91-93cf-ed6985e3927b&displayLang=en
Restore the old permissions together with permissions for the DHCP Server by running the following command:
subinacl.exe /Subkeyreg System\CurrentControlSet\Services\VSS\Diag /sddl=O:SYG:SYD:PAI(A;;KA;;;BA)(A;;KA;;;SY)(A;;SDGRGW;;;BO)(A;;SDGRGW;;;LS)(A;;SDGRGW;;;NS)(A;CIIO;RC;;;S-1-3-4)(A;;KR;;;BU)(A;CIIO;GR;;;BU)(A;CIIO;GA;;;BA)(A;CIIO;GA;;;BO)(A;CIIO;GA;;;LS)(A;CIIO;GA;;;NS)(A;CIIO;GA;;;SY)(A;CI;CCDCLCSW;;;S-1-5-80-3273805168-4048181553-3172130058-210131473-390205191)

Answer: Open regedit and navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS\VssAccessControl. Once you done this, delete the account in question by removing the key and restart the computer for changes to take place.

Windows Server Backup crashing


Typescript & Gatsby: gatsby-plugin-ts + graphQL queries integration

Question: I'm using gatsby-plugin-ts to generate types for my graphql page queries.
The issue I have is that all types generated return a T | undefined type for all fields, so I would need to check all query subfields before using them in any component, otherwise the compiler will throw an error.
Take gatsby-plugin-image for example. Given a query:
export const query = graphql`
  query IndexPage {
    banner: file(relativePath: { eq: "banner.jpg" }) {
      childImageSharp {
        gatsbyImageData(width: 1920)
      }
    }
  }
`;

The result data.banner should be passed to the getImage function, though if you try to do so typescript understandably throws the following error, since undefined is not assignable to IGAtsbyImageData expected by getImage

And this is even worse when it comes to more complex queries, like the ones from the markdownremark plugin: all subfields of one query result would need to be manually checked every time. Is there a work around for this?
Comment: You should switch over to https://github.com/cometkim/gatsby-plugin-typegen, which does the same thing but much better maintained.
Comment: I expected this to work outside of the box. I have the same problem, and don't want to use `gatsby-plugin-typegen` just for this. Did you find a solution?
Comment: @DerekNguyen Gatsby now includes a built-in GraphQL Typegen feature, all you need to do is turn on a config setting. https://www.gatsbyjs.com/docs/how-to/local-development/graphql-typegen/
Comment: @dspacejs If you don't want to use a plugin to automatically generate your typings then you can just write them manually as in Alexey Chekmarev's answer.
Answer: This appears to be caused by a bug in the gatsby-plugin-image typings. Unfortunately the typings for getImage, getSrc, etc. don't match their null-safe behaviour. This also looks like it was only partially fixed, since the troublesome | null type is down one level on { childImageSharp: { gatsbyImageData: IGatsbyImageData } | null } (at least in the GraphQL Typegen typings - YMMV).
The easiest workaround is to use a type assertion:
const result = getImage(data.banner as ImageDataLike);

This tells Typescript: "Hey, I know these types don't exactly match, but trust me, data.banner will always be an ImageDataLike".

Of course, you can avoid all this if you're happy to define your typings manually, as in @Alexey's answer.
If you want to stick with auto-generated types, I'd recommend upgrading to the official GraphQL Typegen which is built into Gatsby and kept up-to-date.
Answer: type of data.banner should be ImageDataLike
export interface DataBannerProps {
  banner: ImageDataLike;
  alt: string;
}


Question about proof for why every partial order on a nonempty finite set has a minimal element

Question: The proof goes as follows:

Proof. Let $R$ be a partial order on a set, $A$. For any element, $a ∈ A$, let $g(a)$ be the set of elements "less than or equal to $a$", that is, $g(a)::=R\{a\}\cup\{a\}$.
Now if $bRa$, then transitivity of $R$ implies that $g(b) ⊆ g(a)$. Also, if $bRa$ and $b \ne a$, then  $a\notin g(b)$ since $R$ is antisymmetric, and so $g(b) ⊂ g(a)$. So if $a$ is not minimal, then there is some $b$ such that $g(b) ⊂ g(a)$. If $A$ is finite, this implies that $|g(b)| < |g(a)|$.
So if $A$ is finite, the Well Ordering Principle implies that there must be an $a_0$ such that $g(a_0)$ has minimum size. So no $g(b)$ can be smaller than $g(a_0)$, which means $a_0$ must be minimal.

I do not understand the relevance of the middle paragraph. I can intuit why a partial order on a non-empty finite set has a minimal element. But I thought that all you would need to show that some minimal element exists is the Well Ordering Principle. I do recognize that partial orders can have more than one minimal element (say in acyclic directed graphs)--is the paragraph in the middle meant to address that somehow?
One  other question: why does transitivity of $R$ imply $g(b) \subseteq g(a)$?
Super confused and appreciate any help.
Thank you!
Comment: You might explain why you "thought all you would need to show that some minimal element exists is the well-ordering principle." Did you think that the well-ordering principle, which is about natural numbers, could be directly applied to other partially ordered sets?
Comment: The well-ordering principle applies only to the natural numbers. How were you going to apply it to a poset? The above argument is to say there is an $a$ so that $|g(a)|$ is minimal. $|g(a)|$ is a natural number. So we can find an $a$ so that $|g(a)|$ is minimal by the WOP.
Comment: "A $\not\exists g(b)$" makes little sense. Do you mean $a\notin g(b)$?
Comment: @HagenvonEitzen yes. Sorry that was a typo on my part. And thank you guys. I forgot that the well-ordering principle only applies to natural numbers.
Answer: I'll answer the second question first. Suppose that $b\mathrel{R}a$. If $x\in g(b)$, then either $x=b$, in which case $x\mathrel{R}a$ and hence $x\in g(a)$, or $x\mathrel{R}b$. But $b\mathrel{R}a$, so by transitivity $x\mathrel{R}a$, and hence again $x\in g(a)$. Thus, every member of $g(b)$ is a member of $g(a)$, i.e., $g(b)\subseteq g(a)$.
The point of the second paragraph is to arrange a situation in which the Well Ordering Principle actually applies. It says that any non-empty set of natural numbers has a smallest element, so in order to use it, we must have a non-empty set of natural numbers. This set is $\{|g(a)|:a\in A\}$, the set of sizes of the sets $g(a)$ for $a\in A$. Since $A$ is finite, and $a\in g(a)$ for each $a\in A$, each $|g(a)|$ is in fact a positive integer. The Well Ordering Principle now says that there is some $a_0\in A$ such that $|g(a_0)|\le|g(a)|$ for each $a\in A$: $|g(a_0)|$ is the smallest member of the set $\{|g(a)|:a\in A\}$ of positive integers.
Now suppose that $a_0$ is not minimal in $A$. Then there is some $b\in A$ such that $b\mathrel{R}a_0$ and $b\ne a_0$. But then $g(b)\subseteq g(a_0)$ and $a_0\in g(a_0)\setminus g(b)$, so $g(b)\subsetneqq g(a_0)$, and therefore $|g(b)|<|g(a_0)|$. This contradicts the minimality of $|g(a_0)|$, thereby showing that no such $b$ can exist and hence that $a_0$ is minimal in $A$.
Answer: (I prefer to write $x\prec y$ instead of $(x,y)\in R$)
The well-ordering principle is applied here to the set of cardinalities $|g(a)|$ as $a$ varies. Since $A$ is finite, these numbers are all $\in\mathbb N_0$ and hence we apply the well-ordering principle only to $\mathbb N_0$.
The purpose of the middle paragraph is to establish that $a$ with minimal number $|g(a)|$ (with respect to the usual total order $<$ on $\mathbb N_0$) is also itself minimal in the sense of the given partial order $\prec$ on $A$.
Here's why transitivity of $R$ implies that $g(b)\subseteq g(a)$ if $b\preceq a$: Let $x\in g(b)$, that is $x\preceq b$. As also $b\preceq a$, we have $x\preceq a$ and hence $x\in g(a)$.
Comment: Hey sorry, I'm not familiar with $\mathbb N_0$. What does that refer to?
Comment: @wcarvalho $\mathbb N$ is generall yused to denote the set of natural numbers. As some prefer to have $0\in \mathbb N$ and others prefer $0\notin\mathbb N$, I use $\mathbb N_0$ to stress that this should be the version *with* $0$.


Distribution of complex results for pool of ten-sided dice, specific to custom tabletop RPG system

Question: I'm no statistician, but I do find the area of mathematics fun and fascinating. I have a friend who has designed a "roll-mid" dice system for his custom tabletop RPG and as part of the game balancing, I'm interesting in finding out certain result possibilities.
An individual die has the following results:
1        : critical failure, total of -1 "success"
2-3, 8-9 : no "successes"
4-7      : +1 "success"
0        : critical success, total of +2 "successes"

A player will roll from one to ten individual ten-sided dice (d10s). I haven't any idea how to approach an issue like this with the additional layer of complexity. The concept, however, is just really cool to me.
My question: What is the distribution of "success" totals for any number of dice 1-10?
Answer: You might like a procedure to answer similar questions so you can play with your options.  A good one uses the probability generating function, pgf.  For dice, this is just a polynomial (or rational function) in a single variable (say, $t$).  The powers of $t$ correspond to numbers of successes and their coefficients give the associated probabilities.
In your example, the pgf is
$$p(t) = \frac{1}{10} t^{-1} + \frac{4}{10} t^0 + \frac{4}{10} t^1 + \frac{1}{10} t^2 = \frac{1 + 4t + 4t^2 + t^3}{10 t}.$$
The pgf for the sum of successes with $k$ independent rolls of the dice ($k = 0, 1, 2,$ etc) is just the $k^\text{th}$ power of the pgf.  Any computer algebra system will make short work of computing such powers.  You can read off the desired probabilities from the results.
For example, with two dice $k=2$, so the pgf for the numbers of successes is
$$p(t)^2 = \frac{1 + 8t + 24t^2 + 34t^3 + 24t^4 + 8t^5 + t^6}{100 t^2}.$$
Noticing the factor of $100 t^2$ in the denominator, we get:
$$\eqalign{
\Pr[-2] &= 1/100 \\
\Pr[-1] &= 8/100 \\
\Pr[0] &= 24/100 \\
\cdots \\
\Pr[4] &= 1/100.
}$$
I have written "$\Pr[i]$" for the chance of $i$ successes, which (with two dice) can range from $-2$ up through $4$.
Once $k$ gets larger than $5$ or so, you can approximate these probabilities with a Normal distribution.  The expectation of the original die is
$$\mu = \frac{1}{10}  \times (-1) + \frac{4}{10} \times 0 + \frac{4}{10} \times 1 + \frac{1}{10}\times 2 = 1/2$$
and therefore its variance is
$$\sigma^2 = \frac{1}{10} \times (-1 - \frac{1}{2})^2 + \frac{4}{10} \times  (0 - \frac{1}{2})^2 + \frac{4}{10} \times (1 - \frac{1}{2})^2 + \frac{1}{10} \times (2 - \frac{1}{2})^2 = 13/20.$$
Consequently, the expectation for the sum of $k$ independent dice is $k\mu$ and the variance is $k\sigma^2$.  Use these parameters to compute probabilities.
For example, with $k=10$ (counting successes on $10$ dice), the expectation is $5$ and the variance is $13/2$.  What are the chances, say, of $10$ or more successes?  We apply a "continuity correction" by equating $10$ or more with $9.5$ or more ($9.5$ splits $9$ and $10$, of course), and compute the upper tail area of a normal distribution of mean $5$ and variance $13/2$.  This expression uses R, a free statistical calculator:
k <- 10 # An integer between -10 and 20
1 - pnorm(k-1/2, mean=(1/2)*k, sd=sqrt(13/20*k)) # Chance of k or more successes

It returns $0.03877808$; the correct value is $\frac{23617383}{625000000} \approx 0.0377878$.  The normal approximation is only $1.03$ times greater than the correct value in this case: it would take a few million rolls to detect the difference.
Comment: Thanks @whuber, this is exactly the breakdown I didn't have the statistics knowledge to compose. I will need to review this several times and give that statistical calculator a look ([link](http://www.r-project.org/) I assume?)
Comment: @whuber thank you so much for this. I've wondered idly about similar questions in the past.
Comment: pan, that link is correct, but hardly necessary: see [tag:r]!


Transfer entropy value between 0 and 1

Question: Given two variables, X and Y, there is a way of obtaining a Mutual Information value between 0 and 1 by:
<code>MI_normalised=MI_original/sqrt(H(X)*H(Y));
</code>
where H(X) and H(Y) are entropies of X and Y respectively.
Just wondering if there is a similar operation to obtain a Transfer Entropy value between 0 and 1. If so, what is it?
Any help much appreciated.
Answer: Transfer entropy is defined as:
$$T_{X \to Y} = H(Y_t \mid Y_{t-1 : t-L}) - H(Y_t \mid Y_{t-1 : t-L}, X_{t-1 : t-L})$$
where $t$ is the current time and $L$ is the history length.
If $X$ perfectly predicts $Y$ then
$$H(Y_t \mid Y_{t-1 : t-L}, X_{t-1 : t-L}) = 0$$
and $T_{X \to Y}$ therefore has a maximum value of $H(Y_t \mid Y_{t-1 : t-L})$.
If $X$ contains no information about $Y$ then
$$H(Y_t \mid Y_{t-1 : t-L}, X_{t-1 : t-L}) = H(Y_t \mid Y_{t-1 : t-L})$$
and $T_{X \to Y}$ therefore has a minimum value of $0$.
So, if the goal is to normalize transfer entropy to the range $[0, 1]$, it seems reasonable to divide it by its maximum possible value:
$$\frac{T_{X \to Y}}{H(Y_t \mid Y_{t-1 : t-L})}$$
I don't know whether this is standard; just working off the definition. So please check that this makes sense.
A similar definition is given in

Gourevitch and Eggermont (2007). Evaluating Information Transfer
  Between Auditory Cortical Neurons

and other neurophysiology papers (search for 'normalized transfer entropy'). They often include an additional correction term based on shuffled data to correct for bias when estimating from finite, noisy signals.
Answer: I think that in practice I would use user20160's answer, but I'd like to offer a few warnings and a possible alternative.
Warning 1: The definition $T_{X\rightarrow Y} / H(Y_t | Y_{t-1:t-L})$ only works for discrete random variables. If you you have continuous random variables, then $H(Y_t | Y_{t-1:t-L})$ could be negative and your quantity would no longer be between zero and one.
Warning 2: Suppose that $H(Y_t | Y_{t-1:t-L}) = \epsilon$ and $H(Y_t | Y_{t-1:t-L},X_{t-1:t-L}) = 0$. You will get a score of 1. In the limit of $\epsilon\rightarrow 0$, you continue to have a score of 1 even though, in some sense, the amount of information transferred is going to zero.
Alternative 1: If you are using discrete random variables, note that $0 \leq T_{X\rightarrow Y} \leq H(Y) \leq \log k$, where $k$ is the number of discrete possibilities $Y$ can take. Then if you define $T_{X\rightarrow Y} /
log k$, you still get something between zero and one, but it will only be one if $Y$ is maximally uncertain and $X$ is a perfect predictor. This would bypass warning 2, if that is a concern in your case.
Alternative 2: For the continuous case you could define your score as $T_{X\rightarrow Y} / I(Y_t ; Y_{t-1:t-L},X_{t-1:t-L})$. The denominator is always non-negative and $T_{X\rightarrow Y} \leq I(Y_t ; Y_{t-1:t-L},X_{t-1:t-L})$ (you could see that using the chain rule, e.g.). You would get one if $I(Y_t ; Y_{t-1:t-L}) = 0$ which could loosely be interpreted as saying all the information that can be predicted about $Y_t$ comes from $X$, and not from $Y$'s past.

Transfer entropy value between 0 and 1


Get the most bought top 10 items as a list

Question: I want to get the most bought items in a list. But at the moment I got only the counts of the number. How do I get the itemids ?
I want the list like the following [element 1, element 2, ...,element n-1, element n]. How do I get the top 10 most bought items?
How do I get most of the items I have bought? By counting how often the itemid occurs, the id that occurs the most is the item bought most often.
import pandas as pd
d = {'userid': [0, 0, 0, 1, 2, 2, 3, 3, 4, 4, 4],
     'itemid': [715, 845, 98, 12324, 85, 715, 2112, 85, 2112, 852, 102]}
df = pd.DataFrame(data=d)
print(df.head(10))

df_new = df.groupby('itemid').count().head(10) # get the top 10 products
print(df_new)

print(df_new.values.tolist())

Now the output
# the dataframe
   userid  itemid
0       0     715
1       0     845
2       0      98
3       1   12324
4       2      85
5       2     715
6       3    2112
7       3      85
8       4    2112
9       4     852

# the counts
        userid
itemid
85           2
98           1
102          1
715          2
845          1
852          1
2112         2
12324        1

# the list
[[2], [1], [1], [2], [1], [1], [2], [1]]

# what I want
[85, 98, 102, 715, 845, 852, 2112, 12324]

Comment: If "most bought" is based on the number of rows it's just value_counts, which returns a sorted result then slice the index: `df['itemid'].value_counts().index[0:10]`. But you'll need `groupby` + `nunique` if you want to go based on the number of unique people who buy an item
Comment: It looks like what you want is the index of df_new : `df_new.index.tolist()`
Answer: Sort by 'userid' then return index of top 10
new_df = df.groupby('itemid').count().sort_values(by=['userid', 'itemid'], ascending=[False, True])
print(new_df[:10].index.tolist())

we can rename the userid to user_counts, in that case we sort by user_counts
top_10 = df.groupby('itemid').count().rename(columns = {"userid": "user_counts"}).sort_values(by=['user_counts', 'itemid'], ascending=[False, True])[:10].index.tolist()
print(top_10)

Comment: Thanks for the answer. Why do I have to sort by `userid`?
Comment: It is actually userid_counts, but the column was named userid


Case & When no Select

Question: SELECT
    c2.quantidade AS qtde_solicitada,

IF (
    (
        SUM(c1.quantidade) - c2.quantidade
    ) < 0,
    '0',
    c2.quantidade
) AS estoque,
 (
    SELECT
        SUM(quantidade_autorizada)
    FROM
        ferramental_requisicao
    WHERE
        devolvido = 1
) AS devolvido,

IF (
    c2.quantidade <= devolvido,
    'ferramental_estoque',
    'ferramental_requisicao'
) AS tabela,
 CASE
WHEN tabela = 'ferramental_requisicao' THEN
    (
        SELECT
            *
        FROM
            ferramental_requisicao
        WHERE
            id_ativo_externo = c1.id_ativo_externo
        AND devolvido = 1
    )
ELSE
    'pare aqui'
END AS retorno
FROM
    ferramental_estoque AS c1
JOIN ferramental_requisicao AS c2 ON c2.id_ativo_externo = c1.id_ativo_externo

Erro: coluna tabela não existe

Como eu posso adequar?
Comment: não pode fazer um case com um alias do mesmo select, nesse caso "tabela", precisar fazer o select separado para usar isso, e usar `WITH`
Comment: @RicardoPontual você consegue postar uma sugestão?
Answer: Uma sugestão seria vc adequar uma os dados conforme a necessidade, gerando esses atributos dentro do FROM para ser consumida em outro nivel, um exemplo seria assim,
SELECT
c3.qtde_solicitada,
c3.estoque,
c3.devolvido,
c3.tabela,
CASE
WHEN c3.tabela = 'ferramental_requisicao' THEN
    (
        SELECT
            *
        FROM
            ferramental_requisicao
        WHERE
            id_ativo_externo = c3.id_ativo_externo
        AND devolvido = 1
    )
ELSE
    'pare aqui'
END AS retorno
FROM (
    SELECT
        c2.quantidade AS qtde_solicitada,
        c1.id_ativo_externo
    IF (
        (
            SUM(c1.quantidade) - c2.quantidade
        ) < 0,
        '0',
        c2.quantidade
    ) AS estoque,
    (
        SELECT
            SUM(quantidade_autorizada)
        FROM
            ferramental_requisicao
        WHERE
            devolvido = 1
    ) AS devolvido,

    IF (
        c2.quantidade <= devolvido,
        'ferramental_estoque',
        'ferramental_requisicao'
    ) AS tabela,

    FROM
        ferramental_estoque AS c1
    JOIN ferramental_requisicao AS c2 ON c2.id_ativo_externo = c1.id_ativo_externo
) as c3;

Como não tenho a base de dados não posso garantir que funcione, mas essa seria a ideia

Case & When no Select