Code is throwing an IndexOutOfBoundsException?

Question: Can anyone tell me why this code isn't working? It throws an IndexOutOfBoundsException.
package blok6afvink6;

/**
 *
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;

public class Blok6afvink6 {

    public static void main(String[] args) throws FileNotFoundException {

        //1st, use Scanner to readin all sequence names and sequences;
        //create two arrayList to store sequence names and sequences;
        ArrayList<String> name = new ArrayList<String>();
        ArrayList<String> sequence = new ArrayList<String>();

        Scanner ScanLine = new Scanner(new FileReader("OverlapGraph.txt"));
        String seq = "";
        while (ScanLine.hasNextLine()) {
            String temp = ScanLine.nextLine();
            if (temp.charAt(0) == '>') {
                sequence.add(seq);
                name.add(temp.substring(1));
                seq = "";
            } else {
                seq += temp;
            }
        }

        ScanLine.close();
        sequence.remove(0);
        sequence.add(seq);

        //naam en seq printen
        int Len = name.size();
        for (int i = 0; i < Len; i++) {
            System.out.println(name.get(i) + ": " + sequence.get(i));
        }
        //3rd, connect all sequences with O3 overlap, put the linked-names into a new string ArrayList
        ArrayList<String> overLaps = linkOverlaps(name, sequence);

        System.out.println("\nPrintout results:");
        for (int i = 0; i < overLaps.size(); i++) {
            System.out.println(overLaps.get(i));
        }
    }

    private static ArrayList<String> linkOverlaps(ArrayList<String> name, ArrayList<String> sequence) {
        ArrayList<String> overLap = new ArrayList<String>();
        //int size = name.size();
        for (int i = 0; i < name.size(); i++) {
            int Len1 = sequence.get(i).length();

            for (int j = 0; j < name.size(); j++) {
                if (i != j && sequence.get(i).substring(Len1 - 3).equals(sequence.get(j).substring(0, 3))) {
                    String linked = name.get(i) + " " + name.get(j);
                    overLap.add(linked);
                }
            }
        }
        return overLap;
    }

}

The error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.remove(ArrayList.java:492)
    at blok6afvink6.Blok6afvink6.main(Blok6afvink6.java:36)

Comment: You should explain why you think this exception is different than all the other times people got the same exception.
Comment: Because you are trying to remove an element from the `sequence` `ArrayList` that doesn't exist: `sequence.remove(0);`
Comment: printout to screen as you process the lines to make sure it is working. Or step though with the debugger. Whatever you find more useful
Comment: How do you know that the ArrayLists will always have items in them?
Answer: Line 36 referenced in the exception appears to be:
sequence.remove(0);

This can only fail with this exception if the list was empty.
So one has to assume that sequence.add(seq); is never called.
If that's OK and expected, you could check for empty first:
if (!sequence.isEmpty()) {
    sequence.remove(0);
}

Answer: try
if(sequence.size() > 0) {
    sequence.remove(0);
}

Comment: Please explain why you submitted what you submitted.  Stack Overflow is a knowledge distribution center, not a code writing service.  It would be **a lot** better if OP learned how to fish
Comment: In this case, there was a logic error. We have not a concept error.
Some times, the short answer is the best answer.
Thanks by feedback
Answer: Look closely at the error message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

It would seem that one of your collections has size 0. If so, that would cause this exception because you don't always check to make sure that the collections actually have any items before you try to access them.
Check sequence in particular.


Putting background image in JFrame

Question: import java.awt.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.JPanel;

public class FirstFrame extends JFrame {

    // FirstFrame properties

    public FirstFrame() {

        setTitle("Stacker");
        setLayout(new GridBagLayout());
        setSize(380, 650);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setUndecorated(true);
        setVisible(true);
        setResizable(true);

        JLabel background = new JLabel(new ImageIcon("fw.jpg"));
        background.setLayout(new BorderLayout());
        add(background);

    }

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

Okay now that I have the frame undecorated .. (thanks to you guys) I'm trying to put a background image for the frame. but when I run it, all it shows is a blank frame.
What is wrong? How to correct it?
Comment: Its probably because the ImageIcon can't find the "fw.jpg" in the path. Where is this "fw.jpg" file located?
Comment: By the time of deployment, those resources will likely become an [tag:embedded-resource].  That being the case, the resource must be accessed by `URL` instead of `File`.  See the [info page](http://stackoverflow.com/tags/embedded-resource/info) for the tag, for a way to form an `URL`.
Answer: Please consider doing the following..
1. Add JLabel, background before you setVisible(true).In fact, put the setVisible as the last line in your constructor.
2. Then try to get the image as
getClass().getResource(imgPath)
set the image
Answer: You're likely not looking for the image in the right location. If you're going to look for the image as a file (which you're currently trying to do), you need to do so relative to the user's directory which can be found via System.out.println(System.getProperty("user.dir")). If you're going to look for it as a resource, you will need to look for it relative to the class file locations. This has all be discussed and rehashed ad-infinitum on this site. Please search some more.

Putting background image in JFrame


Need help for a beginner to floating-point arithmetic

Question: I have this question that I need to complete and I literally have zero idea on what to do. I basically need someone to talk me through it and will appreciate all the help I can get.
The question states:
Consider a "toy system" of floating-point arithmetic such that every number is of the form:
$x=(-1)^s * (1+m) * 2^{e - \delta}$
The mantissa $0 ≤ m < 1$ is a number whose binary representation is of the form:
$m=0 . m_1 m_2 m_3$ (base 2)
Where $m_1$, $m_2$, $m_3$ are either $0$ or $1$. Also, $s$ is either $0$ to $1$. The exponent $e$ is an integer such that $1 ≤ e ≤ 6$ and $\delta = 3$ is the shift.

What is the largest positive number?
What is the smallest positive number?
What is the machine epsilon?
List all the possible values the mantissa can take.
How many floating-point numbers are in this set?

Express all the results as decimal numbers (base $10$).
Now I literally have no idea what this is really on about. So guidance and some help would be really wonderful. Thanks for your time.
Comment: @104078: The fact that machine epsilon is 0.25 does *not* imply that the (binary) values the mantissa can take are limited to multiples of machine epsilon.  As the Question itself states, the mantissa can be any *binary* representation $0.m_1m_2m_3$.  It is left to the Readers (doing the exercise) to convert these into *decimal* representations.
Comment: Why not try writing down a few examples, to see what makes such numbers positive or negative, larger or smaller, and how many possibilities in all this representation allows?
Comment: Hi hardmath, thanks for your comment. So if I take the largest value of m which I guess is 0.111 which is 0.875 in base 10 then e as 6. So would 15 be the largest positive number and the smallest positive number would therefore be 0.25?
Comment: I'm confident with converting from base 2 to 10, so if those first 2 are correct, can you help me with 3 and 5 since 4 is just the case of going through 0.000 to 0.111?
Comment: Scrap that, I'm being dumb! I think it's only 3 that I am having problems with. Not sure on what a machine epsilon is and how to work it out.
Comment: 1. 15 - 2. 0.25 - 4. 0 to 0.875 with an increase of 0.125 per step - 5. 96 numbers in the set. If these are correct it is just 3 I need to solve.
Comment: [Machine epsilon](http://en.wikipedia.org/wiki/Machine_epsilon) is often defined as the smallest positive difference between 1 and a slightly larger machine representable value, just big enough to give a positive value (machine epsilon) when 1 is subtracted from it.
Comment: @hardmath as you found it, machine epsilon is 0.25. so does this imply that $m_3=0$. Then,all the possible values the mantissa can take:0.110,0.100,0.010,0000?
Answer: The notion of machine epsilon in floating-point arithmetic is useful in getting upper bounds on the contribution a rounding error can make in a single operation.
The task here is simply applying the definition.  Machine epsilon is the smallest machine-representable positive value we can obtain by subtracting $1$ from a floating-point value slightly greater than $1$.  Intuitively we are apt to think of this as a "unit in the last place" of mantissas normalized to exponent $0$, but as we will see the range of exponents can affect this.
For reference let's begin with a representation of $1$ in our "toy" binary arithmetic scheme:
$$ +(1.000)_2 \times 2^0 = 1.0 $$
Note that net exponent is zero, which means (taking the bias $\delta = 3$ into account) that $e = 3$ (and, of course, sign bit $s=0$ since the number $1$ is positive).
The first thing we would think about is the smallest number we can represent which is greater than one, i.e. by setting the mantissa bit $m_3$ from $0$ to $1$.  Although we can do that, the resulting number is so close to $1$ that the exact difference (subtracting one) is not machine representable.  The exact difference would be one-eighth (or 0.125 decimal), and to represent this in our binary arithmetic scheme would require $e - \delta = -3$, or $e = 0$.  The format specification however says $1 \le e \le 6$, so we cannot represent that difference.  Presumably in an actual calculation the difference might be rounded down to zero, but we don't have to speculate about how it would be handled.
Rather, just applying the definition, we see that the smallest positive difference that can be represented is one-quarter, corresponding to $e=1$:
$$ +(0.010)_2 = +(1.000)_2 \times 2^{1-3} $$
The limitation in the range of (offset) exponents is then a bit of trickery in this problem, giving us machine epsilon of one-quarter or 0.25 decimal.


Aggregating votes from different users with some constraints and probabilities

Question: Suppose we have $N$ users that can vote for a given question by "Yes" or "No". Each user have a probability which is considered as the confidence that we have in that user (e.g. a user may have a probability of 0.8 to answer the question correctly, and a probability of 0.2 to answer it wrongly). Each user requesst an amount of money as a reward for answering the question. I (as the asker of the question) have a limited budget for paying the users.
Given this budget, which users should I ask to maximize the final answer to be correct (i.e. the answer obtained after aggregating the asked answers)?
Additional informations:
"what does it mean for a vote to be correct": if the question is "does 10/2 equals 5?" then "Yes" is a correct answer to this question; now if the probability associated to the user is 1, that means that the user will answer this question correctly because it have a very good knowledge of the domain of the question (mathematics); if the probability associated to the user is 0, this means that the user will answer this question wrongly; if the probability associated to the user is 0.5, then his answer may be correct ("Yes 10/2=5") with a probability of 0.5, or maybe wrong wt probability 1-0.5.
What I want is to maximize the fact of getting the good final answer by aggregating the obtained answers (want to know that the answer to my question is "Yes" 10/2=5). For this, which users should I ask (given my budget, and given that each user request a given amount of money to accept to answer my question), and how to aggregate their answers in order to have the correct one.
What is called "vote" is the classical aggregation of the answers, by taking the most common answer among the received ones (if there is more "Yes" answers then ok I will consider the final result as "Yes), but in my real example I have some constraints: probabilities associated to users, ammount of money requested by each user to answer my question, and the total amount of money that I have, so I need to also consider these constraints. If you want, forget about the word "vote" in the question, just tell me who to ask and how to aggregate the answers that I get.
Comment: Several interpretations of the objective are possible. For instance, do you want to maximize the *expected* number of correct answers? Or perhaps you want to maximize the chance that every answer is correct?  Or the chance that the number of correct answers equals or exceeds a minimum threshold? Also, what role does "voting" have in this question? And what does it mean for a vote to be "correct"? What is the distinction between a "vote" for and an "answer" to a question? It is hard to see how your question can reliably or objectively be answered until you clarify these issues.
Comment: @whuber You are right, how you determine the "reliability" of voters is another somehow complicated problem which depend on many indices like behaviour of voters... For the current question I'll just assume that the probabilities that we are talking about are indeed "probabilities of answering the question correctly".
Comment: @whuber "what does it mean for a vote to be correct": if the question is "does 10/2 equals 5?" then "Yes" is a correct answer to this question; now if the probability associated to the user is 1, that means that the user will answer this question correctly because it have a very good knowledge of the domain of the question (mathematics); if the probability associated to the user is 0, this means that the user will answer this question wrongly; if the probability associated to the user is 0.5, then his answer may be correct ("Yes 10/2=5") with a probability of 0.5, or maybe wrong wt proba 1-0.5
Comment: @whuber What I want is to maximize the fact of getting the good final answer by aggregating the obtained answers (want to know that the answer to my question is "Yes" 10/2=5). For this, which users should I ask (given my budget, and given that each user request a given amount of money to accept to answer my question), and how to aggregate their answers in order to have the correct one.
Comment: @whuber What is called "vote" is the classical aggregation of the answers, by taking the most common answer among the received ones (if there is more "Yes" answers then ok I will consider the final result as "Yes), but in my real example I have some constraints: probabilities associated to users, ammount of money requested by each user to answer my question, and the total amount of money that I have, so I need to also consider these constraints. If you want, forget about the word "vote" in the question, just tell me who to ask and how to aggregate the answers that I get. Is it clear ?
Comment: Much better, thank you.  It would be good for you to incorporate these explanations within the question itself so that hasty readers (who might otherwise neglect to review the comments) will not misunderstand.  Incidentally, I would attach *high* value to a user who has a probability of $0.2$ of answering the question correctly: by reversing their answer, they become just as reliable as the person with a probability of $0.8$!
Comment: @whuber Yes reversing the answer of users having a low probability may be a good suggestion when we consider this probability to be a "probability of answering the question correctly", thank you. I can also consider the probability to be about the "reliability" of the user according to his domain knowledge about the question, in this case users with a low probability (having nearly no knowledge about the domain) may answer randomly, in this case it is better to consider their "probability of answering the question correctly" to be 0.5.
Comment: It is important to have an operational, quantitative interpretation of "reliability." If it cannot be translated into a probability, then you cannot compute the distribution of correct answers, so you cannot even get started with solving this problem.  This begs the question of how you determine the "reliability" of voters in the first place: that is likely estimated from previous experience or simply guessed. Thus the probabilities are themselves uncertain and perhaps ought to be modeled (in a Bayesian fashion) by prior probabilities.
Answer: You can think of the "expected number of correct answers" for each user--for example, your hypothetical user with probability 0.8 of answering correctly has an expected number of correct answers equal to 0.8, when you give him a single question.
Then, divide by your cost for each user. Suppose your user with probability 0.8 asks for \$2 dollars. When you divide, you get an "expected number of correct answers per dollar" of 0.4 for that user. A user with probability 0.6 of answering correctly but who asked for only \$1 would have an "expected number of correct answers per dollar" of 0.6.
Now you have a few possible approaches. The simplest is to use a greedy algorithm, and go through an select as many users as you can within your budget starting with the highest "expected number of correct answers per dollar." This is an approximate algorithm.
A better approach is to treat this as a variant of the knapsack problem. Solving it is NP-hard, but there are polynomial time approximations which are better than the greedy algorithm above.
Comment: (Note that I'm talking just about one question to ask to users). If for example I have a very big budget (say infinit) which is sufficient to ask all the users, then if I ask all the users, the final answer that I aggregate/deduce may be worse (have less chance to be correct) than the case where I just ask only the first user which have an ENCAD equals to 0.98 (very hight) ... Your approximate algorithm is not considering such cases.
Comment: The answer you deduce will only be worse after asking all the users if you do a naive analysis of the answers you get, in which case it's best to just ask the one best user you can afford. Since you have information on how reliable each user is, you can do an analysis using that information such that every additional answer you get from a user, no matter how unreliable that user is, will help you estimate a better overall answer.
Comment: Of course, at some point it's just not worth asking more users, but that's a separate question.
Comment: This is also a part of my question, and of your approximate algorithm: Using the information on how reliable each user is, how can you check that every additional answer you get from a user, will help you estimate a better overall answer ?
Comment: From an information-theoretic perspective, the user is a noisy channel. The "truth" is input at one end, and the user outputs their answer which is equal to the truth with probability $p$ and not equal to the truth with probability $1-p$. The only case in which the user transmits no information at all is if $p = 0.5$ exactly. Unless you already have perfect information (i.e., you have a user who answers correctly with probability one), then the information received from the user will help you answer the question, assuming that different users are independent.
Comment: +1 This can be reframed as a [bounded knapsack problem](http://en.wikipedia.org/wiki/List_of_knapsack_problems) or, if the voters vary from question to question, as a multiple-constraint knapsack problem.
Comment: @Jonathan Christensen But you didn't really answered the last question: How can you decide to stop asking users? i.e., how can you check that the current better overall answer can probably not be improved by asking a new user ? I mean algorithmically speaking you have a sorted vector where each entry i is the ENCAD of the i'th user; you start with the first answer (of the 1st user having the highest ENCAD), you still have budget, you ask the 2nd user and get its answer, now you aggregate the 2 answers that you have, how can you check if you should or not ask another user ? What do you compute?
Comment: @whuber the difference with the knapsack problem is that in our case, we need to maximize a sort of expected correctness for the overall answer (after aggregating all the received answers), while for the knapsack problem we do our best to put items in the sack until we can no more add items to it. There is no relation between items, they should not be aggregated to give a final "good item", while in our case the answers are aggregated to get the best final answer.
Comment: This is now quite different from your original question! In your original question, presumably, you stop asking users when you run out of money. You can consider the new problem as a Bayesian updating problem if you're willing to write down a prior probability for each answer: at time zero, you have some probability of each answer being true (0.5 each, if you want). Then you start asking users. After each user, you check whether your current belief state satisfies some condition, which might be a hard line (e.g. I'm 90% sure of one answer) or, more realistically, would depend on costs etc.
Comment: I disagree, shn: this problem can be framed so that it is *precisely* a knapsack problem. The apparent differences you point to are not fundamental. Here, the "items" are not the voters, but rather increments along an efficient frontier and the costs are incremental costs to move along that frontier.
Comment: @shn, in your original question you specifically say that you wanted to figure out how to "maximize the amount of correct answers," which makes it very much like the knapsack problem. I'm getting the feeling now, though, that you actually want to do something quite different--you want to gain as much information about which answer is correct as possible. For example, for your original request a user with probability 0.001 of giving the correct answer is terrible, but if you're just trying to gain information, that user is just as good as one with probability 0.999 of giving the correct answer!
Comment: @Jonathan Christensen maybe I didn't asked the question well at the beginning. If I still have budget but asking more users will make the final answer worse, I indeed will prefer not to asking them. The Bayesian updating approach seems interesting here, I'm really not familiar with Bayesian statistics however. I, in fact, want to gain as much information about which answer is correct as possible. I did not understood what you want to say in the example of user with proba=0.001 and another with proba=0.999
Comment: @whuber in the knapsack problem we try to put the maximum number of items in the bag. In my case it is possible that with 3 users we get a better final answer than with 8 users ...
Comment: This is a mild generalization (and therefore even harder): you attempt to maximize the total *value* of the increments, rather than their count.
Comment: @JonathanChristensen can you update the answer to explain more precisely how to consider this problem as a Bayesian updating problem ?
Comment: @whuber so it can not be resolved using the usual knapsack problem solutions, right ?


How to make Next.js debugging useful?

Question: From the Next.js VSCode debugging page, I got the following launch.json.
{
  "configurations": [
    {
      "name": "Next.js: debug server-side",
      "type": "node-terminal",
      "request": "launch",
      "command": "npm run dev"
    },
    {
      "name": "Next.js: debug client-side",
      "type": "chrome",
      "request": "launch",
      "url": "http://localhost:3000"
    },
    {
      "name": "Next.js: debug full stack",
      "type": "node-terminal",
      "request": "launch",
      "command": "npm run dev",
      "serverReadyAction": {
        "pattern": "- Local:.+(https?://.+)",
        "uriFormat": "%s",
        "action": "debugWithChrome"
      }
    }
  ]
}

After running the full stack option, Next.js starts like any old npm run dev. The problem is that the debugging isn't very useful. In my debug terminal I have it selected so that there are breakpoints on caught exceptions. In Python applications (where my debugging experience lies), VSCode pauses on the exact line number whenever there is an exception and gives a useful, understandable error.
With Next.js, the breakpoint gives me a complicated, general error that leads to some random Next.js source code. This has next to no meaning for me.
For example, I got a promise rejected error. This is likely from a request I made that was handled with .catch using Axios. Next.js pointed me to the following deeply nested file.
\node_modules\next\dist\server\dev\on-demand-entry-handler.js
On line 202 it caught an error in code which I have never seen before. Upon unpausing the breakpoint, it leads to more of these errors.
How can I make Next.js debug for me more efficiently? I want more clear, understandable errors, that lead me to specific lines of code that I actually wrote.
Answer: Solution

I have it selected so that there are breakpoints on caught and uncaught exceptions

Unchecking "Caught Exceptions" will likely lead to the debug behavior you seek.
Explanation
It appears you may have misunderstood what checking "Caught Exceptions" does. Enabling breakpoints on caught exceptions means the debugger will pause on all caught exceptions: your code and all JavaScript dependencies are included (including files like \node_modules\next\dist\server\dev\on-demand-entry-handler.js)

On line 202 it caught an error in code which I have never seen before. Upon unpausing the breakpoint, it leads to more of these errors.

This is expected behavior, as try/catch statements are standard practice in JavaScript to catch unexpected behavior and errors, and therefore the debugger pauses on all of these statements as long as Caught Exceptions is checked. A catch statement implies an expected error occurred, so pausing on it may not make sense in your debug case!
Breaking on uncaught exceptions is more likely to pause on meaningful errors and exceptions, meaning that an unexpected error was thrown and not caught inside of a try/catch statement. It's likely that dependencies will not have any uncaught exceptions (if they do then it may be considered a bug), hence allowing the debugger to catch mistakes mainly within your code.
Comment: Looking back, I probably shouldn't have mentioned that I had uncaught exceptions checked, as it made my question more complicated than it should be.

Next.js debugging remains frustrating whether uncaught is checked or not. The fact that uncaught exceptions was checked was just a pedantic detail specific to my use case. I've edited my post to reflect this, but I thank you for your input anyways.

How to make Next.js debugging useful?


Heroku Node app keeps crashing

Question: I have an Express app hosted on Heroku. Locally it runs just fine, but keeps crashing on Heroku. Every time I go to it I get the 'Application Error' page.

I double checked all environment variables and they seem ok.
The Heroku logs don't exactly offer much help:
2017-04-16T23:02:49.001768+00:00 heroku[web.1]: State changed from crashed
to starting
2017-04-16T23:02:52.072906+00:00 heroku[web.1]: Starting process with
command `npm run start`
2017-04-16T23:02:56.042611+00:00 app[web.1]:
2017-04-16T23:02:56.042628+00:00 app[web.1]: > email@example.com start /app
2017-04-16T23:02:56.042629+00:00 app[web.1]: > node bin/app
2017-04-16T23:02:56.042630+00:00 app[web.1]:
2017-04-16T23:02:57.200912+00:00 heroku[web.1]: State changed from starting
to crashed
2017-04-16T23:02:57.201454+00:00 heroku[web.1]: State changed from crashed
to starting
2017-04-16T23:02:57.192198+00:00 heroku[web.1]: Process exited with status 0
2017-04-16T23:03:00.981528+00:00 heroku[web.1]: Starting process with
command `npm run start`
2017-04-16T23:03:04.312475+00:00 app[web.1]:
2017-04-16T23:03:04.312489+00:00 app[web.1]: > email@example.com start /app
2017-04-16T23:03:04.312490+00:00 app[web.1]: > node bin/app
2017-04-16T23:03:04.312491+00:00 app[web.1]:
2017-04-16T23:03:06.093211+00:00 heroku[web.1]: Process exited with status 0
2017-04-16T23:03:06.112842+00:00 heroku[web.1]: State changed from starting
to crashed

So then I tried starting the app manually:
$ heroku run bash
...
$ npm run start

I got no errors. I'm using the pm2 process manager, so I checked it to see if the app is running and it seems like it is:
$ node_modules/.bin/pm2 list
...

But then when I go to open my app I get the same 'Application error' page as before.
'heroku restart' doesn't help. It just crashes again every time.
The only difference between my local environment and Heroku (as far as I can tell at least...) is that locally I have a file from which I'm reading a RSA private key, and on Heroku that key is read from the environment.
Edit: As requested, here's my Procfile:
web: npm run start

Any ideas?
Comment: What does the RSA private key do ? Did you follow Heroku's instructions to deploy your app ? https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction
Comment: Yeah I followed the guide. I'm trying my hand at building a GitHub integration, so the key is for GitHub.
Comment: Can you add your procfile ?
Comment: Procfile added.
Answer: Your app need to start listening to the port defined in the env. For example if you have an expressjs app it should look something like this:
const express = require('express')
const app = express()
const port = process.env.PORT || 3000

app.get('/', (req, res) => res.send("Hello world"))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

If the app does not bind to the correct port, heroku is going to consider the app unhealthy and will terminate it.
You need to see this line in the logs, which indicates that heroku recognized the app as healthy:
State changed from starting to up

Keep in mind that this port thing is a special requirement for the web process. The other processes in your app does not have such a requirement.
Answer: Try 2 things:
Change your procfile:
web: node start.js

Then make sure that your web process it running by scaling it up:
heroku ps:scale web=1

On your computer in a terminal window run this command in your project:
heroku local web

It simulates how Heroku runs your app and should give you information of what is happening.
Comment: My only advice is to use Heroku to start your app locally and see what it says (updated answer)
Comment: Tried it but no luck... Changed Procfile to be 'node bin/app' + scaled the app down & back up but it still crashes. If I somehow get it working myself I'll post it here.

Heroku Node app keeps crashing


When is a piece in A minor versus C major?

Question: When would you say a piece, or a movement in a symphony, is in A minor versus C major? They both use the same notes on the scale... what would indicate that the piece is in A minor?
Let's take an example. The 2nd movement of Beethoven's 7th symphony. The principal key is A minor. But what distinguishes the key from C major in this movement? (Obviously, the mood is more appropriate to a minor key, but I'm sure there is a better answer.)
Comment: When you say "the mood is more appropriate to a minor key" you have it backwards. It is by virtue of being in a minor key that creates that mood.
Comment: Couldn't it also be in D dorian, E phrygian, F lydian, G mixolydian, or B locrian?
Comment: A minor and C major keys do not use the same tones. The key _signatures_ only are the same.
Answer: The last chord harmony of most pieces give a feeling of ending. (It would, wouldn't it - otherwise the piece goes on, potentially).With no key signature, shown, a piece could be in C major or A minor. This last chord gives a big clue as to which key the writer thinks it's in. The presence of G#, showing usually a V-I cadence is also a good clue, except that it is used in C major, to modulate to the relative minor. Maybe if it happens a lot, there is more chance of the tune actually being in A minor. Trouble is, that G# may show melodic or harmonic minor tendency, but wouldn't be there if the tune is written using A natural minor notes.
Another pointer is where the tune tends to gravitate to, especially at cadence points. If it feels like it's coming to rest on more Cs, or more As, there's the answer.
A nice example of this dilemma is 'Fly Me To The Moon'. Starts on Am, but ends on C.
Bottom line is probably - 'Does it really matter?'
Comment: +1 for "does it really matter." Taking a long piece using only the natural notes, you could probably find bits in A minor, C major and various other modes. The only time it matters is when you want to number the notes and chords, then you really have to decide what mode you're in. For example, shall we refer to E as the 3rd of C major or the 5th of A minor? Or even the tonic of the Phrygian?
Comment: @Tim I would say it definitely matters. The key defines the tonic, dominant, and subdominant. Take for example the lone G3 note in the theme from Choral Symphony (piano transcription). Why does it have the power to bring everything to a pause? Perhaps because it's the dominant of the scale.
Comment: That's why I added the caveat "usually". I could have gone into modulation as a form of large scale dissonance and resolution as well, but not all tunes modulate. Tonal hierarchy, however, applies even to modality. All modes have a final tone, and they have a dominant ("tenor" in Gregorian terminology) which is generally (but not always) a fifth above the final.

There was a limit to how far I think we could get across those concepts.
Comment: @steve verrill - you're absolutely spot on. Pieces can fluctuate a lot sometimes, and even the key signature may not give accurate enough clues. Right now I'm in a Christmas mode...
Comment: Also just wanted to add that if you can discern the piece's form, you can use the structure to help you determine appropriate key areas. A movement of a symphony may be in a Sonata-Allegro form, so you could compare the Exposition and the Recapitulation. Also, keep in mind the period when it was written - composers from different periods treated harmony differently. For Tim, it matters so far as how well in conveys whatever the composer wishes to convey; a subtle shift in tone color perhaps. It is helpful for movements within a symphony as it conveys a close without sounding too final.
Comment: +1 for 'Fly Me To The Moon' example - when I sing it in my mind, I get that sad feeling of minor... and then when I try to sing its notes in sequence (scale) I have a surprise - hey, the notes make major scale but the song sounds sad, how is that possible? So now I know why.
Comment: For another jazz-standard example, Irving Berlin's "Blue Skies" plays with major/minor a lot. In the verse, it first uses I - IV, and in the repeat of the phrase makes it iv. Then first half of the chorus tonicizes the relative minor, and then the second half is major—"blue skies from now on!"
Answer: A is tonicised (the term we use) rather than C. That means that the tonic chord, the one that defines the key and resolves all harmonic motion, is confirmed by various means as A minor. Tonality is defined by a hierarchy of interval relationships, the strongest being the relationships of a fifth and a fourth. In the key of C, that would be G and F respectively, which is why you see chord progressions like C Maj - F Maj - G Maj - C Maj all the time. The equivalent progression in A minor would be A min - D min - E Maj - A min. I'll get to why E Maj in a bit.
Now those relationships aren't symmetrical: rising a fifth (or falling a fourth), for various reasons both physical and cultural, creates a greater strain than falling a fifth. (TL;DR is that in the harmonic interval of a fifth, the upper note and its harmonics reinforce the harmonics of the lower note, thus moving from one chord to the one a fifth above is changing the effective fundamental, whereas moving to the chord a fifth below supplies a fundamental that encompasses both chords.)
The net effect is that the fourth degree of the key (F Maj in the key of C Major, for example) is, in effect, a point of relaxation in a chord progression in that key (because moving from the tonic to the fourth degree is an easy downward motion of a fifth), whereas a movement to the fifth degree (G Maj in the key of C) sets up an opposition to the tonic, and falling from the fifth degree to the tonic resolves that opposition. That's why progressions like C - F - G - C are so common. In this case, C is being balanced by F and G, and the final motion G to C is a resolving one which confirms C as the tonic.
Melodic intervals aren't symmetrical in strength either. The strongest intervals melodically are seconds, and the very strongest motion is by a minor second upwards. In both C major and the natural scale of A minor, the minor seconds are found between E and F, and B and C. In C Major, when you move from a G Maj chord to a C Maj chord, you have not only got a strong root movement (establishing a fundamental of C), you've got the B in the chord of G (the third of the chord) pushing into the note of C in the tonic chord as well.
Given that the minor second intervals in both C major and natural A minor are the same, the chord on the fifth degree of A minor is normally going to be a minor chord, E min, with G as its third. The melodic motion from G to A is a major second, which isn't as strong as a minor second, so it's very common to substitute G♯ instead, which makes the chord on E a major chord. (If the melodic line was rising from E to A, it's not unusual to sharp F as well.)
So, if you look at a piece in C, you'll find that the piece usually begins with a C Maj chord or G Maj chord (not always, but these are most common), and usually ends with a G Maj chord followed by C Maj final chord. In A minor, the pieces usually start with an A min chord, sometimes an E Maj, occasionally an E min, and usually end with E Maj followed by A Maj or A min. (The reason for A Maj as the very last chord of the piece is that asymmetry I mentioned earlier: a major third in a chord is a better match to the lower harmonics of the chord's root note than a minor third, and thus the chord is more stable. The term for ending a piece in the minor mode with the tonic major chord is tierce de Picardie or Picardy third.)
You'll also see a fair number of G♯s (generally pushing into a neighbouring A) as SSteve mentioned, and possibly some F♯s as well. That is melodic motion inside the piece that is helping to confirm A as the tonic.
Answer: The other answers have good detail on the theory of the chords and scales, so I decided to give an example.
You mention the second movement of Beethoven's 7th Symphony as an example. There are no sharps or flats in the key signature, so how would you tell whether it's in A minor or C major? Let's take a look at that, shall we? Here's the opening chord:

Notice the notes that are being played (remember that the Horns transpose down a sixth, and the Clarinets transpose down a third). Horns: E; Bassoons: A,C; Clarinets: E,A; Oboes: C,E. This is a straight-up A minor chord being held for the first two measure of the piece. That's usually enough of a clue to let us strongly suspect that the piece is probably in A minor.
But we can go further. Lets look at the opening theme, which starts in the low strings (remember that the viola is written in the C-clef, so its first note is E). You can figure out the chords that each set of notes makes, but I've already written the chord name in blue under the staff each time it changes. I've also marked non-harmonic Passing tones and Neighbor tones. (In some cases this is a bit subjective, since many of them do create actual chords. For example, the first set of passing tones in the Viola creates a D7 in second inversion. For our purposes we don't care about this level of detail, though.)

Ignoring the first two measure of silence (while the woodwinds are playing that opening chord) this breaks into 4 phrases of 4 bars each.

Phase 1: Am-E-Am. This is a classic i-V-i. Other answers already explain why the G♯ is used to make E major, so I won't dwell on that. If we were in C major at this point, we'd be focusing on the vi chord and its secondary dominant.
Phrase 2: Am-C/G-G-C. Now this looks like a regular I64-V-I in C major. It seems as if Beethoven is trying to confuse us here, and make us think that we are in C major. These three chords can be said to tonicize C major (they temporarily treat C as the tonic). Does that mean we're in the key of C major? Not really, because keys tend to have a longer scope than three or four bars.
Phrase 3: C-B-Bm-A-Am. Suddenly, we are in what seems to be a tonally-ambiguous section, as the first cellos begin a descending chromatic scale. None of these chords (B, Bm, A) occur naturally in either C major or A minor. However, an A minor tonality is still arrived at by the end of the phrase, when the C♯ descends to a C♮. (A more detailed analysis might notice that, in the B minor measure, the G# that I labeled as a passing tone in the viola creates a G#dim chord (vii dim, relative to A), which has a dominant function leading back to A.)
Phrase 4: Am-E-Am-E-Am. This phrase is very similar to the first. It involves alternating Am and E chords (i and V) and gives us our first true cadence in the key of A minor, which brings a sense of finality and confirms that, yes, we are indeed in the key of A minor.

As an interesting (but largely irrelevant) side note, the fact that the F is always sharped in these phrases, even when the G is not sharped (as occurs in phrase 2), leads me to think that this piece actually leans more towards A-Dorian side of the minor key, rather than A-Aeolian (either way, it's still seen as A minor).
Answer: The tonic in C major is C major; the tonic in A minor is A minor.  The key signature narrows it down to one of the two.  An imperfect method to distinguish between a major key & its relative minor is to analyse the "chord" created when the main theme resolves.  In the case of Beethoven's 7th, movement 2, this occurs, for example, just before the violins come in (26th measure).  The "chord" created by the cellos & violas is an A minor.
Answer: First of all, it probably doesn't matter much.
Then, there can be clues.

Last note / chord. Most pieces end on the chord of their scale. If it ends with C, it's probably C major, if it ends with A, it's probably A minor.
Look at the chords. If it's mostly C, F, G, it's C major. If it's mostly A, D (and sometimes E), it's probably A minor.
Look at other notes. For example, if B is used frequently, it might more likely be C major.
Simply the ratio of major chords vs. minor chords.

When a piece is C major, it's quite likely that the main chords will be C major (tunica), G major (dominant) and F major (subdominant).
When a piece is A minor, it's quite likely that the main chords will be A minor (tunica) and D minor (subdominant), sometimes also E minor (dominant).
The difference is, as you said, the mood, which is caused by those clues.
Examples:

La Esperanza (Ralf Hildenbeutel, Sven Vaeth) chord sequence is A minor, E minor, G major, D minor. The piece is A minor.
La valse d'Amelie (Yann Tiersen) is D minor, A minor, F major, C major. The initial chord and the last chord are A minor. The piece is A minor.
Comment: Unless you're playing in a modal setting, you are not very likely to find an E minor in a piece in A minor.
Comment: @Basstickler I guess you're right. The only piece in A minor that I could quickly make out that uses E minor is La Esperanza. It's A minor, E minor, G major, D minor. I've updated my answer accordingly.
Answer: One way to quickly tell if a piece is in A minor versus C major is to scan through the score and see if you see a number of occurrences of G#. That's an indication of A melodic minor.
Comment: This doesn't work because obviously you could have a secondary dominant (E7) in C major as well. Look around and you'll see zillions of examples.
Answer: The answer varies according to styles. You seem to specify classical movements of symphonies and the like, so I'll answer it there.  Jazz has so many harmonic nuances, and Pop/Rock  really blurs the lines with natural minor.
In Classical theory, minor key does use the same key signature as the relative major, so A minor and C major have no sharps or flats.  However, most classical works do not rely heavily on natural minor, which is all white keys. Instead, composers use melodic minor (F and G are sharpened), and harmonic minor (only G is sharpened). For other keys you have to learn some transposition skills, and key signatures, buts that's a different question.
That's visually studying the score.  In terms of listening, the idea of key in all western music is that the music sounds like, or feels like it is pulled to one of the 12 keys in the octave.  So for A minor, the music is naturally pulled to A, in C major music is pulled to C.  In C major, The destination is C, which is called the tonic, or I (one).  Look at the last note in the movement or piece.  Sing it.  It is probably your key, because that note is the destination note, tonic note, or "key" note.
Answer: The chord progressions revolve around A minor triad instead of C major triad. In other words, the A minor is the chord that is one or more of the following:

repeated most often
starts and finishes the song
the chord that immediately follows G7 or E7
is sustained for longer periods compared to other chords

Additionally the "G" note/tone does not play a big role of emphasis for the melody or improvisation, but "A" and "E" tones do. In other words, melody or improvisation tends to target the root and fifth of the tonic chord.
Answer:
When would you say a piece, or a movement in a symphony, is in A minor
  versus C major? They both use the same notes on the scale... what
  would indicate that the piece is in A minor?

This is no entirely true a minor has a G sharp that C major has not. There are some other indicators. If a piece has a anacrusis (Upbeat) than this is usually built on the dominant chord. SO if the upbeat was build around a E major chord than it would clearly indicate the key of a minor.
In the example you mention we start on C major chord which has a natural G which indicates that piece starts on the tonic chord of the key of C Major. Always check whether the leading tone of the minor key is raised or not. That should give you a clear enough indication most of the time.
Comment: There are songs in A minor that do not contain G#. That in itself is not a good enough criterion.
Answer: If an appreciable number of cadences come to rest on an A minor chord, and E7 (with its distinctive G# note features heavily in the piece), it's in A minor.  Don't be fooled by a final excursion into C major, or even a final A major chord.
Don't worry too much about attaching labels.  It's good that you realise C major and A minor are closely related.
If this is about answering "theory exam" questions, just look out for the G sharps!
Answer: Note that the question of whether a melody is in a major key or its relative minor isn't always answerable, because it's possible for a collection of notes to be both a major-key melody and minor-key melody, with the notes playing different roles in the two keys.  Consider, for example, a melody that alternates between A and F a few times and settles on Bb, then alternates between G and E a few times before settling on A.
If the melody was in F major, it would be going between the third and tonic, which are also the third and root of a I (F) chord, and then sits on the fourth, which would be the root of a IV (Bb) chord.  Then it would cycle between the second and seventh, i.e. the fifth and third of a V (C) chord before settling on the third of the key and the I chord.
If the melody was in D minor, it would be going between the fifth and third, which are also the fifth and third of the I (Dm) chord, then sit on the sixth, which is the third of a IV (Gm) chord.  Then it would alternate between the fourth and second, which are the seventh and fifth of a V7 (A7) chord before settling back to the fifth (which could either be the root of a V7, or the fifth of a I chord).
In the absence of any harmonization, if someone was asked whether the melody was in D minor or F major, neither answer would be uniquely right nor wrong.  Many melodies will have features that would "fit" one key but not the other, such as a minor-key leading tone which would generally represent a rather awkward raised fifth in the relative major.  Sometimes, however, a melody may be genuinely ambiguous, with every note having a plausible role in either key.


Can a Source Generator tell if its being run for editor support (IntelliSense) or as part of an actual build?

Question: My source generator needs to write some files to disk in addition to generating code files for the compilation in progress. These disk writes are completely unnecessary when the generator is being run by the IDE for its IntelliSense (or equivalent) functionality and only makes sense when the project is being actually built (it even tends to cause some failures, the IDE loves to run multiple instances of the source generator simultaneously).
Additionally, I see no reason to generate actual internals of any of the types generated by the source generator. Intuitively, only generating the public surface for the generated types would be lead to a faster and more responsive editor experience.
What is the most robust way for the source generator to differentiate what purpose it is being run for?
Comment: I was just trying to be helpful, and brainstorm solutions, dude.  You didn't mention things you tried.
Comment: You could consider using `Assembly.GetEntryAssembly()`.  For builds, it's going to be `MSBuild.exe`, for Intellisense it will return null because VS is ultimately not a managed executable.  If it ever becomes one, it'll still be a different assembly than `MSBuild.exe`.  Not sure if there's a better technique, but it's the only one that comes to mind.
Comment: @KirkWoll I explicitly asked for "most robust way", I'm already doing it using entry assembly name. And it is not msbuild.exe. According to my experiments "VBCSCompiler" (for builds using IDE) or "csc" (for builds using dotnet) seems to be reliable. But I fully expect different IDEs or future versions of dotnet to behave differently.
Comment: @KirkWoll My apologies if my reply came out rude, didn't mean it that way.
Comment: Thanks, I appreciate that!
Answer: We don't give you a way to ask "am I in the IDE?" since that isn't always the correct question. For example:

Additionally, I see no reason to generate actual internals of any of the types generated by the source generator. Intuitively, only generating the public surface for the generated types would be lead to a faster and more responsive editor experience.

That's correct, up until you are doing Hot Reload/Edit and Continue, and we need those full implementations in the IDE process as were updating the debugee process. Now, that might not be workable in your particular scenario, but you get the idea.
What we have been trying to do instead is give a better way to give hints of intent. An incremental generator can call RegisterImplementationSourceOutput which is our hint to only run that if we need implementations. At the moment of this writing and in VS 17.2 we are still running that in the IDE, but we'll hopefully fix that soon.
There's also still some work in the pipeline: https://github.com/dotnet/roslyn/issues/57589 is tracking adding an API to do the reverse, and https://github.com/dotnet/roslyn/issues/49935 for a way to write other files directly.
Comment: Thank you for an authoritative answer. I have indeed not considered edit&continue, but that is not a functionality we can use due to other constraints anyway (admittedly, having to generate everything with T4 was one of them...). Is there any reason why the intent functionality is being worked on for incremental generators only? Those drive up complexity of the generator a lot, and seem to sometimes have very limited benefit (for example, I need to run protoc to compile a gRPC interface in the background - that needs to be recompiled entirely every time).
Comment: Frankly we're only investing in the incremental generator API at this point; had we figured out the design for that early enough we might have never shipped the first API!


I don't understand uniform convergence

Question: Assume we have some series of functions defined for any $x\geq0$:
$$S(x)=\sum_{n=1}^{\infty} \frac{3x+n}{x+n^{3}}$$
Let's assume uniform convergence. Meaning
$$\forall{\epsilon\geq0}, \exists N s.t. \forall{n \geq N}, \forall{p}, \forall{x\geq0}$$
$$ \lvert \frac{3x+(n+1)}{x+(n+1)^{3}} + \frac{3x+(n+2)}{x+(n+2)^{3}} + \cdots + \frac{3x+(n+p)}{x+(n+p)^{3}} \rvert \leq \epsilon $$
Let's pick a specific $n_0 \geq N$ and $p=1$:
$$ \lvert \frac{3x+(n_0)}{x+(n_0)^{3}} \rvert = \frac{3x+(n_0)}{x+(n_0)^{3}} \leq \epsilon $$
We know this is false, because $\lim_{x\to\infty}=3$ which obviously greater than many $\epsilon$.
However, this is the part I don't really understand... If instead of infinity, we approach some number $M\lt \infty$ then the series is uniformly convergent. Why?
What's to stop us from picking $M+1$ and continuing the series?
Answer: Just asserting that a series of functions is uniformly convergent is meaningless. What has a meaning is to assert that a series of functions converges uniformly (or not) on some given set. Your series does not converge uniformly on $[0,\infty)$, but it does converge uniformly on any bounded subset of $[0,\infty)$. There is no contradiction here.
Comment: Ah, so it really is *any* bounded subset. That really clears it up, thanks!
Comment: I'm glad I could help.
Comment: I have a small follow-up question: If we're asked to prove $S(x)$ is a continuous function for $x \geq 0$, it isn't, right? Because there needs to be an upper bound as well.
Comment: Yes, $S$ is continuous. Take $x_0\in[0,\infty)$. Then your series converges uniformly on $[0,x_0+1)$ and therefore the restriction of $S$ to that set is continuous. In particular, $S$ is continuous at $x_0$.

I don't understand uniform convergence


Comparison of results of monte carlo simulations

Question: I am doing monte carlo simulations. In the first run the experiment is repeated e.g. 10000 times. The result looks like x+/-y, y is the relative error. Next, I change a part of the experiment and run again for e.g. 10000 times and have the result u+/-v, v the relative error.
It is possible that the difference between x and u is small and also there is the relative error. How can I assess this difference with respect to the relative errors?
Example:
First result: 91.6 +/- 9.84
Second result: 95.12 +/- 12.33
Is there a "real" difference in the results or is it just something within the errors?
Any help is very appreciated.
Thanks Ulrich
Comment: Is $\pm y$ the error in the estimate of the mean, or do most/all of the $10000$ values fall in that interval?
Answer: A simple strategy is assume a normal distribution for your MC results. Please check if that applies to you, lot's of practical MC applications (at least my own experience) assume normal or log-normal distribution.
Now, you have your assumed distribution and all the individual recorded values. What's stopping you from something like t-test?


WordPress wp_signon() succeeds but no cookie is attached to response header

Question: I am troubleshooting a problem with a WordPress front-end user login form. The code works great with the same site on a development server, but not on the production server.
On the production server, the authentication passes, and the wp_signon() returns a full user object, however the cookie is not being inserted into the response stream.
The following code demonstrates this:
$user = wp_signon( '', $secure_cookie );
var_dump($user);

When using Fiddler to sniff the packets, this is what is returned by the production server:
HTTP/1.1 302 Found
Server: cloudflare-nginx
Date: Fri, 24 May 2013 07:53:01 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
X-Pingback: http://www.domain.com/blog/xmlrpc.php
X-Frame-Options: SAMEORIGIN
Location: http://www.domain.com/log-in/
Vary: Accept-Encoding,User-Agent
X-Cacheable: YES:FORCED
X-Varnish: 1753703763
Age: 0
Via: 1.1 varnish
X-Cache: MISS
CF-RAY: 73868e9b8da0418
Content-Length: 802

object(WP_User)#329 (7) {
["data"]=>
object(stdClass)#388 (10) {
["ID"]=>
string(2) "53"
["user_login"]=>
string(14) "SubscriberTest"
["user_pass"]=>
string(34) "$P$B8O8w6awJnKrHNoFLOyHJHfKiPE1nt/"
["user_nicename"]=>
string(14) "subscribertest"
["user_email"]=>
string(33) "email@example.com"
["user_url"]=>
string(0) ""
["user_registered"]=>
string(19) "2013-05-23 05:56:42"
["user_activation_key"]=>
string(0) ""
["user_status"]=>
string(1) "0"
["display_name"]=>
string(14) "SubscriberTest"
}
["ID"]=>
int(53)
["caps"]=>
array(1) {
["subscriber"]=>
bool(true)
}
["cap_key"]=>
string(15) "wp_capabilities"
["roles"]=>
array(1) {
[0]=>
string(10) "subscriber"
}
["allcaps"]=>
array(3) {
["read"]=>
bool(true)
["level_0"]=>
bool(true)
["subscriber"]=>
bool(true)
}
["filter"]=>
NULL
}

The WordPress control panel login still works and the cookie is inserted when signing into the backend.
The production server is also using CloudFlare, but I am not sure if that could be related or not. I have sent a support ticket to Cloud Flare as well, hoping that they can confirm whether their proxy service might be stripping them off.
Here is what the response header portion looks like on my development server when running the same code. In this one you can see that the cookie is being sent:
HTTP/1.1 302 Found
Date: Fri, 24 May 2013 02:18:23 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: W3 Total Cache/0.9.2.11
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
X-Pingback: http://domain.com/blog/xmlrpc.php
X-Frame-Options: SAMEORIGIN
Set-Cookie: wordpress_548d950a57c83d7fc5c2eb781062ef26=SubscriberTest%7C1369534704%7C08d4578ca9049beadffa39e0be0ea941; path=/blog/wp-content/plugins; httponly
Set-Cookie: wordpress_548d950a57c83d7fc5c2eb781062ef26=SubscriberTest%7C1369534704%7C08d4578ca9049beadffa39e0be0ea941; path=/blog/wp-admin; httponly
Set-Cookie: wordpress_logged_in_548d950a57c83d7fc5c2eb781062ef26=SubscriberTest%7C1369534704%7Cc41eb224ebec7f57982d0f93e70f7cff; path=/; httponly
Set-Cookie: wordpress_logged_in_548d950a57c83d7fc5c2eb781062ef26=SubscriberTest%7C1369534704%7Cc41eb224ebec7f57982d0f93e70f7cff; path=/blog/; httponly
Location: http://domain.com/
Vary: Accept-Encoding
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

Comment: Hoping the morning crew might have some ideas.  I have been battling with this bugger for over a week now, and I really need to get it fixed today before leaving for the weekend.

 : (
Answer: I finally discovered that Varnish was running on the production server and it was stripping off the cookies. Once URL exclusions were added, the WP functions started working as expected.


Existe alguma forma de converter uma string para base 64 em javascript?

Question: Existe alguma forma de converter uma string para base 64 em javascript?
No PHP podemos fazer assim:
base64_encode('stack overlow'); //c3RhY2sgb3Zlcmxvdw==

Como posso fazer isso em javascript?
Comment: http://pt.stackoverflow.com/questions/92795/como-converter-uma-string-para-base64-em-python
Answer: A resposta moderna é sim, com a função nativa btoa(), disponível nos browsers modernos.
btoa quer dizer base para asci, e existe o oposto que é atob.
Nesse caso seria:
btoa('stack overlow'); // "c3RhY2sgb3Zlcmxvdw=="

Em browsers mais antigos isso não é tão simples e nesse caso sugiro uma função mais complexa, tipo esta.
Mesmo em browsers modernos, há caracteres que podem fazer quebrar a função nativa btoa() como por exemplo:
btoa('✓ à la mode'); // Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

Nesses casos é preciso fazer escape/conversão desses caracteres. Na MDN sugerem estas funções:
function utf8_to_b64(str) {
    return window.btoa(unescape(encodeURIComponent(str)));
}

function b64_to_utf8(str) {
    return decodeURIComponent(escape(window.atob(str)));
}

Mais info (em Inglês) aqui na MDN. Nesse artigo há também uma solução para caracteres que o escape() trata. Uma vez que o escape() está deprecado desde sempre (desde a ECMAScript v3 mas na verdade nunca foi removido) pode ser caso de usar uma alternativa). Aqui fica:
function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}

b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="

Answer: O método btoa() pode fazer o encode pra você, assim como o atob() faz o decode. O retorno de
window.btoa('minha string')

é

bWluaGEgc3RyaW5n

e o retorno de
window.atob('bWluaGEgc3RyaW5n')

é, como de se esperar

minha string

EDIT
Como apontado pelo Omni, ambos os métodos não tem suporte pra versões anteriores ao IE 10 (sempre ele).
Comment: @WallaceMaxters para seguir a convencao do C (como por exemplo `atoi`). Neste caso `atob` significa *ascii to base64*.
Comment: Tenha em atenção que `atob` e `btoa` [não são suportados por versões anteriores ao IE10](http://caniuse.com/#feat=atob-btoa).
Comment: Achei estranho o nome da função. Existe algum significado específico para esse nome? Acho que no PHP ficou mais descritivo
Comment: Essa informação foi muito importante @Omni
Answer: Tal como mencionado, atob e btoa não funcionam em versões anteriores ao IE10.
Pode para isso fazer a sua própria função de conversão (retirada daqui):

var Base64 = {
  _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  encode: function(input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;
    input = Base64._utf8_encode(input);
    while (i < input.length) {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);
      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;
      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }
      output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
    }
    return output;
  },
  decode: function(input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
      enc1 = this._keyStr.indexOf(input.charAt(i++));
      enc2 = this._keyStr.indexOf(input.charAt(i++));
      enc3 = this._keyStr.indexOf(input.charAt(i++));
      enc4 = this._keyStr.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }
    }
    output = Base64._utf8_decode(output);
    return output;
  },
  _utf8_encode: function(string) {
    string = string.replace(/\r\n/g, "\n");
    var utftext = "";
    for (var n = 0; n < string.length; n++) {
      var c = string.charCodeAt(n);
      if (c < 128) {
        utftext += String.fromCharCode(c);
      } else if ((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      } else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }
    }
    return utftext;
  },
  _utf8_decode: function(utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;
    while (i < utftext.length) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      } else if ((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i + 1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      } else {
        c2 = utftext.charCodeAt(i + 1);
        c3 = utftext.charCodeAt(i + 2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
    }
    return string;
  }
}

$encoded = Base64.encode("pt.stackoverflow.com");
alert($encoded)
$decoded = Base64.decode($encoded)
alert($decoded)
Comment: Que paranauezão para fazer um base64. Viva o IE!


. There exists a nondiagonal matrix $A\in \mathcal {M}_n (\mathbb{R}) $ s.t. $A^{k+1}=I_n $ and $I_n-A $ invertible?

Question: Let $k\in \mathbb {N} $. There exists a nondiagonal  matrix $A\in \mathcal {M}_n (\mathbb{R}) $ s.t. $A^{k+1}=I_n $ and  $I_n-A $ invertible?
Answer:
If $k$ is odd, then you can always take $A = -I_n$ as in the other answer.
If $k$ is even and $n$ is even too, then you can take the block matrix, where $B$ appears $n/2$ times:
$$A = \begin{pmatrix}
B & 0 & 0 &\dots & 0 \\
0 & B & 0 & \dots & 0 \\
\vdots & \ddots & \ddots & \ddots& \vdots \\
0 && 0 & B &0\\
0 & \dots & 0 & 0 & B
\end{pmatrix},$$
and the rotation matrix $B$ is given by:
$$B = \begin{pmatrix} \cos\bigl(\frac{2\pi}{k+1)}\bigr) & \sin\bigl(\frac{2\pi}{k+1}\bigr) \\ -\sin\bigl(\frac{2\pi}{k+1}\bigr) & \cos\bigl(\frac{2\pi}{k+1}\bigr) \end{pmatrix}.$$
The eigenvalues of $A$ are all nonreal, hence $A-I_n$ is invertible.
If $k$ is even and $n$ is odd, then $A$ must have a real eigenvalue $\lambda$, because its polynomial characteristic has odd degree (and every real-valued odd-degree polynomial has a real root). But then $\lambda^{k+1} = 1$, hence $\lambda = 1$. Therefore $A - I_n$ has $0$ as an eigenvalue and isn't invertible.
Answer: If $k $ is odd, you can take $A=-I $. So the answer in this case is yes.
If $k $ is even and $n$ is odd, then $A^{k+1} $ has a real eigenvalue $\lambda $ such that $\lambda ^{k+1}=1$. So $\lambda=1$, and so $0$ is an eigenvalue of $I-A $. So the answer in this case is no.
For $k$ even and and $n$ even, see the example in Najib's answer.
Comment: I don't see why $A$ has a real eigenvalue in general. See my answer.
Comment: Yes, you are right.


I want to ask about deleteCharAt method

Question: I searched deleteCharAt method on API Documents. The return type of this method was StringBuilder. So I thought reference variables is needed to put reference value on.
For example, I think sbuf=sbuf.deleteCharAt(0); is better expression than sbuf.deleteCharAt(0);.
However, on many books and codes, the latter is used.
What's the false part in my thought?
Comment: `StringBuilder` often returns the same instance of `StringBuilder` so you can do method chaining `sbuf.append("Hello").deletCharAt(0)` == `ello`. This approach is often used by objects which implement the builder pattern, as it helps you reduce repeated code
Comment: I can understand your codes. But In this code 'sbuf.deleteCharAt(0);', where is the instance returned? to Java Compiler? or Main method?
Comment: Consider the expression being evaluated step by step; `sbuf` evaluates as a reference to a StringBuffer instance, a method is called on that instance and so `sbuf.deleteCharAt(0)` evaluates as a reference to a StringBuffer instance, and so on. The instance is returned from deleteCharAt method out to the calling expression.
Comment: No where.  You can call a method which has a return value and ignore it.  Not always wise, but it can be done.  `StringBuilder` is mutable, so changes made to it (like `deleteCharAt`) effect the internal contents, but for convience, it will return `this` (an instance of the `StringBuilder`) so you can chain method calls together
Answer: The StringBuilder object is mutable; once you call the operation .deleteCharAt(), the reference sbuf is still to the same object, and the internal state of that object has changed. So you can call the method in the form sbuf.deleteCharAt(0);.
Strings, for example, are not mutable, though. When you call the .substring() method, say, it returns a reference to an entirely new instance of the string class. So if you wrote str.substring(5);, the return value would be thrown away and str would still have it's old value. Instead, you need to write something like newStr = str.substring(5); in the case of immutable objects.
Answer: In java, String objects are immutable. Once string object is created its data or state can't be modified but a new string object is created.
Consider the example given below:
class Demo{
 public static void main(String args[]){
   String s="Demo";
   s.concat("String");//concat() method appends the string at the end
   System.out.println(s);
 }
}

Output:

Demo

Here, the new modified string literal is created and discarded.
If we assign it to the reference variable, it will refer to modified object.For example:
class Demo{
 public static void main(String args[]){
   String s="Demo";
   s=s.concat("String");
   System.out.println(s);
 }
}

Output:

DemoString

Java StringBuilder class is used to create mutable string.
class Demo{
  public static void main(String args[]){
     StringBuilder sb=new StringBuilder("Demo");
     sb.append("String");//now original string is changed
     System.out.println(sb);
  }
}

Output:

DemoString

I want to ask about deleteCharAt method


Advanced WordPress Single Post Pagination - Exclude Category & Browse Through Only Set Categories

Question: I have my main blog, which lists all posts.
I also have a category page that lists only posts from 1 category.
Main Blog

Post #1
Post #2
Post #3
Post #4
Post #5

Category A Page

Post #1
Post #3
Post #4

Category B Page

Post #1
Post #3
Post #5

If a user clicks to look at a post, and then uses the default next/prev link functions, there is no way for WordPress to know which post should be next.
For example, if the user is looking at Post #3, should the next post be #4 or #5? It all depends on where the user came from.
So I wrote the following code to answer this problem and thought I'd share it.
Answer: NOTE: I know that this is not the most efficient way to do this, especially if you have thousands of posts. I'd be interested in seeing better ways to get the next post.
Add the following to your functions.php file:
/*
 * Session Tracking
 */
    add_action('init', 'start_session', 1);
    function start_session() {
        if(!session_id()) {
            session_start();
        }
    }
    // Update Cookie trail
    function update_cookie_trail() {
        $_SESSION['ref_category'] = get_query_var('cat');
    }

/*
 * Return next post based off of cookies
 */
    function next_post_from_session($text, $categories) {
        global $post;

        $cat_array = explode(',', $categories);
        $cat_array[] = $_SESSION['ref_category'];

        // Get all posts, exclude Hidden cat
        $args = array(
            'numberposts'     => -1,
            'category'        => implode(',', $cat_array),
            'orderby'         => 'post_date',
            'order'           => 'DESC',
            'post_type'       => 'post',
            'post_status'     => 'publish',
        );
        $allPosts = get_posts( $args );
        $index = 0;

        foreach( $allPosts as $thePost ) {
            $index++;
            if($post->ID == $thePost->ID) {
                $nextPost = $allPosts[$index++];
                $url = get_permalink($nextPost->ID);
                $a = 'post_title).'" />'.$text.'';
                return $a;
            }
        }
    }

/*
 * Return previous post based off of cookies
 */
    function previous_post_from_session($text, $categories) {
        global $post;

        $cat_array = explode(',', $categories);
        $cat_array[] = $_SESSION['ref_category'];

        // Get all posts, exclude Hidden cat
        $args = array(
            'numberposts'     => -1,
            'category'        => implode(',', $cat_array),
            'orderby'         => 'post_date',
            'order'           => 'DESC',
            'post_type'       => 'post',
            'post_status'     => 'publish',
        );
        $allPosts = get_posts( $args );
        $index = 0;

        foreach( $allPosts as $thePost ) {
            if($post->ID == $thePost->ID) {
                $prevPost = $allPosts[$index-1];
                $url = get_permalink($prevPost->ID);
                $a = 'post_title).'" />'.$text.'';
                return $a;
            }
            $index++;
        }
    }

/*
 * Generate a "back" URL to the previous category page based off session data
 */
    function previous_category_permalink() {
        $ref_url = $_SESSION['ref_category'];
        return get_category_link($ref_url);
    }

And then on any category.php or page where you show several blog posts (like a "related posts" section), run this function:
update_cookie_trail();

Then on your single.php you can use the following functions.
<?php echo next_post_from_session('Next', '-24, 10'); ?>

<a class="close" href="<?php echo previous_category_permalink(); ?>">
    Back

<?php echo previous_post_from_session('Previous Post', '-24, 10'); ?>

The '-24, 10' is a parameter that allows you to exclude, or specifically include categories via comma separated ID's.


Orchestra warmup sounds

Question: Background: I am guitar player who does not know anything about tuning other instruments and classical music traditions
I really love the sound of warming up (and final tuning) of an orchestra. They are always playing this

or something very similar. What sounds is the orchestra playing?
Answer: When the concert master (first chair violinist) comes on stage, it is their job to tune the orchestra. The concert master plays a concert A for the orchestra. The sounds you then hear are those of each instrument tuning to the A given by the concert master.
Since each string instrument (violin, viola, cello, and double bass) has four strings, they must tune each of these strings.
The winds and brass as well tune to the concert A. Each of these instruments is unique, so depending on its particularities, these instruments may or may not tune to more than just the concert A. As a clarinetist, for instance, I like to tune not only my concert A, but also the the octave A's above and below, as well as the fifth below (concert E-natural). This is because the clarinet's tuning acts differently in different registers of the instrument.
There can be variations in this tuning tradition when there is a soloist playing with the orchestra. For example, if there is a piano concerto being performed, usually the concert master will play an A on the piano instead of on his/her violin.
Comment: Good explanation, but symphony orchestras traditionally have the 1st chair oboe (or _occasionally_ clarinet) give the tuning note. He or she is signaled to do so by the concertmaster after they take their bow. For a string orchestra without winds, you are correct--the concertmaster would provide the tone.
Comment: NRellingh has it right - if there's an oboe in the orchestra, it will generally give the tuning note.  Typically the winds will tune first, then after a brief pause, another A will be played and the strings will tune.  I've seen junior orchestras even tune 3 times, having brass and woodwinds tune separately.  The oboe is used to tune because the instrument itself is theoretically impervious to going out of tune.  There's no tuning slide - tuning is controlled solely with the reed - thus, the principal oboist plays the note.
Comment: @wadesworld https://www.youtube.com/watch?v=2eAC0NtxF-k shows this quite beautifully.
Comment: Sorry, wrong again!   Oboe gives the A.  Orchestra tunes.  Concertmaster enters, takes his bow, sits down, checks HIS tuning.   Conductor enters.   All in that order.
Answer: The reason for the unique sound quality of this is the layering of perfect intervals, essentially fifths. The string instruments, save for the double basses, have their strings tuned in fifths, that's what you mainly hear. Fifths are the canonical choice for comparison of different notes, since they are the secondmost pure interval after octaves, so you can hear very clearly when you're out of tune.
Maybe it's also in part because of this that pure perfect fifths are seldom used in classical music, they usually only come together with the less open-sounding thirds. They are, in fact, far more common in modern guitar play – not just in powerchords but also in modal chords. Stacking two fifths results in a sus2 chord, adding yet another fifth you also get a 6. No unusual in Jazzy guitar parts, but you seldom hear such chords arranged for string sections, so what you associate with them is just the tuning sound.
Answer: 1st oboe giving A=440 Hz or any other A according to the tuning of the orchestra (442, 445 etc). Then, the whole orchestra tunes at once according to the 1st oboe, not the Konzertmeister.

Orchestra warmup sounds


Sending data from view (javascript) to controller in MVC 5

Question: So in my index view I receive and display the user's current location in the form of latitude and longitude.
(function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        }
    }());
    function showPosition(position) {
        $('#lat').text(position.coords.latitude);
        $('#long').text(position.coords.longitude);

    }

Is there a way to send position.coords.latitude and position.coordes.longitude to my index controller?
Or should I have the user click a button to submit them, like a form ? I am new to using coordinates.
Thanks in advance!
Answer: Put this in your showPosition function:
var postData = { Lat: position.coords.latitude, Long: position.coords.longitude };
$.ajax(
{
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "AjaxTest",
    //dataType: "json",
    data: JSON.stringify(postData),
    success: function (data, status) {
        alert("Pass" + data);
    },
    error: function (ex) {
        alert("Fail" + ex);
    }
});

In your controller, you need this action. Give it a better name please:
public JsonResult AjaxTest(Position position)
{
    // do whatever you want here. I am simply returning the value.
    return Json("You posted: " +  position.Lat + " items.", JsonRequestBehavior.AllowGet);
}

And you will need a model like this:
public class Position
{
    public double Lat { get; set; }
    public double Long { get; set; }
}

Comment: I am getting this alert when running the application now: http://i.imgur.com/n12Jy15.png
Comment: Because you need to change the url you are posting to. Did you create that action in the same controller where the view was generated? If not you have to specify the url. I just put the name of the action because the view was generated from the same controller.
Comment: You have a controller named IndexController? Are you sure? And did you created the action I posted in the answer in the IndexController and you are serving the view from the IndexController as well? It is not possible because that has to work. Your url is incorrect. Also if you are doing other work in the action, that may be failing. To start just use my code and once it is working then modify the action method code.
Comment: Sorry, the controller is named HomeController but the inside there is a task for Index, About and Contact. I found some other strange behavior. If I change the postData to position then it works only once. If I want it to work again, I change it back to postData and run and it works but only once, whats going on?
Comment: Ok those are all other issues you are having. Put your view and controller code [here](http://pastebin.com/) and share the link with me. I will take a look.
Comment: it seems that running a new instance of the app in the browser is the problem. If I just refresh the last tab and close the new one, it will retrieve the coordinates just fine.
Comment: Actually , no. It seems its very hit or miss?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/129753/discussion-between-codingyoshi-and-crystyxn).
Answer: If you can send as a get request then You could format the lat and long into a query string. Then use window.location to redirect the browser to whatever route you want. E.g.
Window.location.href = querystring

Will tack on the query string to the existing route...or if you can extract only a part of the existing route (like the domain only) and tack on the additional segments along with your query string. Checkout window.location for all the various options.


Finding the limit that involves Fourier coefficients,

Question: Given the function $f(x) = 1 - \dfrac{|x|}{\pi}$, I had computed its Fourier coefficients, using integration by parts and got:
$$
a_n = \begin{cases} 0, & \text{for $n$ even}, \\[6pt]
\dfrac{2}{n^2\pi^2}, & \text{for $n$ odd}, \\[6pt]
\dfrac{1}{2}, & \text{for }n = 0.
\end{cases}
$$
So, I know the coefficients decay like $\dfrac{1}{n^2}$.
What if I now took $f(x)$ to be $\left(1 - \dfrac{|x|}{\pi}\right)^4$.
What is $\lim\limits_{n\to\infty}$ $n^3a_n$?
This is part 2 of a question that I am working on, and the question does not ask for a detailed proof but rather just the answer and the reasoning behind it.
Thanks,
Edit:  Of course, if we iterate the integration by parts enough times, we can certainly compute the Fourier coefficients for the new function.  But this is quite a bit of computation and I'm sure is not the point of the question - part 1 of the question already asked for explicit computation of the $a_n$'s.  I'm not sure how to proceed, without direct computation.  Perhaps there are decay / growth conditions of the $a_n$'s and convergence properties of the Fourier series that I am not aware of...
Comment: Have you tried computing the coefficients for $f(x)=(1-\frac{|x|}{\pi})^2$? Or maybe you can share, the computation of the coefficients of your original function, to see if there is a pattern that you are omiting.
Answer: If $f$ has Fourier series $\sum a_n \cos nt+b_n\sin nt$, then $f'$ has Fourier series $ \sum na_n \cos nt-na_n\sin nt$. (I treat these as formal series, making no claims about their convergence). So, whenever you see Fourier coefficients multiplied by powers of $n$, think of derivatives.
So the natural idea is to consider $f'''$, but the differentiability of $f$ isn't that great... which brings to mind the second idea.
Suppose $n^3 a_n$ is bounded. Then the series for $f'$ has coefficients bounded by $C/n^2$. (In your case, all $b_n$ vanish since the function is even.) It follows $f'$ is represented by a uniformly convergent Fourier series, and is therefore continuous.
However, for $f(x)=(1-|x|/\pi)^4$, the derivative $f'$ is not continuous at $0$. Hence, $\lim n^3 a_n$ does not exist.
Comment: Hi, @Idisagree, I would like to ask you one more question that's been lingering in my head since we last discussed your answer.
Does the Weierstrass M-test, giving us uniform convergence to a continuous function, f', from the bound of C/n^2 of the coefficients, necessarily mean that the Fourier series for f' converges to f' for its *entire* domain of definition, which would be the (extended) real line?
Comment: I feel like you, and the M-test, must mean that, in order for your contradiction proof to work - you looked at x=0, which proves n^3*an must be unbounded.  you also didn't mention anything about the radius of convergence, which also makes me think that the *uniform* convergence to f' must be for its entire domain of definition and not restricted to a smaller interval.  Thanks,
Comment: There is no such thing as a radius of convergence of a Fourier series.
Comment: Ah, ok.  Thanks a lot, @Idisagree!


Wordpress update_post_meta not saving

Question: Is there any funky caching/versioning going on with Wordpress that I should know in regards to meta data against a post?
I am building a plugin and when I update a meta value, I can see that it updates it (by adding a die() statement after my call to update_post_meta and looking in mysql), but when I let the page load continue, the value hasn't changed (and it has reverted back in mysql).
Any ideas? If I delete the value from the post and then try update, it creates it correctly. It's just updates that don't stick!
Answer: So the problem was that my code was updating the value, but then Woocommerce was then saving the values it received from the form POST over my values. The solution was to hook into an action that is called after the form is saved, so that my data is saved after Woocommerce has done it's save.

Wordpress update_post_meta not saving


Passar valores de um fragment para uma activity

Question: Estou querendo passar o valor de um EditText (que está em um fragment) para um atributo de um objeto de uma activity, porém não estou obtendo sucesso, o Toast da activity retorna null. Segue o código do fragment:
public class PerguntaUmFragment extends SlideFragment {
    private PerguntaUmInterface perguntaUmInterface;
    private EditText editMensagem;

    public PerguntaUmFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_pergunta_um, container, false);

        editMensagem = view.findViewById(R.id.editMensagem);

        perguntaUmInterface.setMensagem(editMensagem.getText().toString());

        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        try {
            perguntaUmInterface = (PerguntaUmInterface) context;
        } catch (Exception e) {
            Log.e("ERROR", e.toString());
        }
    }

    public interface PerguntaUmInterface {
        void setMensagem(String mensagem);
    }

    public void setPerguntaUmInterface(PerguntaUmInterface perguntaUmInterface) {
        this.perguntaUmInterface = perguntaUmInterface;
    }
}

Activity:
public class OcorrenciaActivity extends IntroActivity implements PerguntaUmFragment.PerguntaUmInterface {
    private final Ocorrencia ocorrencia = new Ocorrencia();

     @Override
     protected void onCreate(Bundle savedInstanceState) {
        Toast.makeText(OcorrenciaActivity.this,
                "Mensagem: "+ ocorrencia.getMensagem(),
                Toast.LENGTH_SHORT).show();
     }
    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
        if (fragment instanceof PerguntaUmFragment) {
            PerguntaUmFragment perguntaUmFragment = (PerguntaUmFragment) fragment;
        }

    }
    @Override
    public void setMensagem(String mensagem) {
        ocorrencia.setMensagem(mensagem);

    }

Comment: Pq simplesmente vc nao manda um toast direto do Fragment?
Comment: Não, o toast é apenas uma forma de verificar se a mensagem chegou corretamente, o mesmo só imprimi "null" na tela.
Answer: Você pode usar a classe SharePreference para compartilhar a informação para essa finalidade ou utilizar outro dois métodos descritos abaixo:
Criando um SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("DATA", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("EDITEXT1", "string value");  // Salvando dados do seu editext
editor.commit(); // confirmar e salvar seus dados para a SharedPreferences

Agora você pode recuperar seus dados como no código abaixo:
SharedPreferences pref = getApplicationContext().getSharedPreferences("DATA", MODE_PRIVATE);
String email=pref.getString("EDITEXT1", "");       // Salvando dados de string do seu editext

Pela Instância
Ou você pode definir um campo de instância em sua Activity e acessá-la subindo a referência getActivity() para a MainActivity no fragmento:
((MainActivity) getActivity()).filedName.setFragmentOneData(data);

Por Argumentos
Por ultimo o método utilizando o Bandle para passar informações pelo fragmento:
Bundle bundle = new Bundle();
bundle.putString("someEditTextData",someEditTextData);
SomeFragment fragment = new SomeFragment ();
fragment.setArguments(bundle);

E para recuperar os dados no fragmento (adaptando a sua realidade)
Bundle args = getArguments();
    if (args != null) {
        showReceivedData.setText(args.getString("someEditTextData"));
    }

Comment: Não sei se seria possível, mas poderia se basear e aplicar no meu código?? eu realmente não sei como colocar essa lógica no programa


MLE vs MAP estimation, when to use which?

Question: MLE = Maximum Likelihood Estimation
MAP = Maximum a posteriori
MLE is intuitive/naive in that it starts only with the probability of observation given the parameter (i.e. the likelihood function) and tries to find the parameter best accords with the observation. But it take into no consideration the prior knowledge.
MAP seems more reasonable because it does take into consideration the prior knowledge through the Bayes rule.
Here is a related question, but the answer is not thorough.
So, I think MAP is much better. Is that right? And when should I use which?
Answer: If a prior probability is given as part of the problem setup, then use that information (i.e. use MAP). If no such prior information is given or assumed, then MAP is not possible, and MLE is a reasonable approach.
Comment: It is worth adding that MAP with flat priors is equivalent to using ML.
Comment: Also worth noting is that if you want a mathematically "convenient" prior, you can use a conjugate prior, if one exists for your situation.
Comment: Comment from @Tim should *be* the answer.
Answer: A Bayesian would agree with you, a frequentist would not.  This is a matter of opinion, perspective, and philosophy. I think that it does a lot of harm to the statistics community to attempt to argue that one method is always better than the other.  Many problems will have Bayesian and frequentist solutions that are similar so long as the Bayesian does not have too strong of a prior.
Comment: It is not simply a matter of opinion.  There are definite situations where one estimator is better than the other.
Comment: @TomMinka I never said that there aren't situations where one method is better than the other!  I simply responded to the OP's general statements such as "MAP seems more reasonable."  Such a statement is equivalent to a claim that Bayesian methods are always better, which is a statement you and I apparently both disagree with.
Comment: jok is right. The Bayesian and frequentist approaches are philosophically different. So a strict frequentist would find the Bayesian approach unacceptable.
Answer: Assuming you have accurate prior information, MAP is better if the problem has a zero-one loss function on the estimate.  If the loss is not zero-one (and in many real-world problems it is not), then it can happen that the MLE achieves lower expected loss.  In these cases, it would be better not to limit yourself to MAP and MLE as the only two options, since they are both suboptimal.
Comment: In my view, the zero-one loss does depend on parameterization, so there is no inconsistency.
Comment: The MAP estimator if a parameter depends on the parametrization, whereas the "0-1" loss does not. 0-1 in quotes because by my reckoning all estimators will typically give a loss of 1 with probability 1, and any attempt to construct an approximation again introduces the parametrization problem
Answer: Short answer by @bean explains it very well. However, I would like to point to the section 1.1 of the paper Gibbs Sampling for the uninitiated by Resnik and Hardisty which takes the matter to more depth. I am writing few lines from this paper with very slight modifications (This answers repeats few of things which OP knows for sake of completeness)
MLE

Formally MLE produces the choice (of model parameter) most likely to generated the observed data.

MAP

A MAP estimated is the choice that is most likely given the observed data. In contrast to MLE, MAP estimation applies Bayes's Rule, so that our estimate can take into account
  prior knowledge about what we expect our parameters to be in the form of a prior probability distribution.

Catch

MLE and MAP estimates are both giving us the best estimate, according to their respective denitions of "best". But notice that using a single estimate -- whether it's MLE or MAP -- throws away information. In principle, parameter could have any value (from the domain); might we not get better estimates if we took the whole distribution into account, rather than just a single estimated value for parameter? If we do that, we're making use of all the information about parameter that we can wring from the observed data, X.

So with this catch, we might want to use none of them. Also, as already mentioned by bean and Tim, if you have to use one of them, use MAP if you got prior. If you do not have priors, MAP reduces to MLE. Conjugate priors will help to solve the problem analytically, otherwise use Gibbs Sampling.
Answer: Theoretically, if you have the information about the prior probability, use MAP; otherwise MLE.
However, as the amount of data increases, the leading role of prior assumptions (which used by MAP) on model parameters will gradually weaken, while the data samples will greatly occupy a favorable position. In extreme cases, MLE is exactly same to MAP even if you remove the information about prior probability, i.e., assume the prior probability is uniformly distributed.
So:

If dataset is large (like in machine learning): there is no difference between MLE and MAP; always use MLE.
If dataset is small: MAP is much better than MLE; use MAP if you have information about prior probability.
Answer: As we know that
$$\begin{equation}\begin{aligned}
\hat\theta^{MAP}&=\arg \max\limits_{\substack{\theta}} \log P(\theta|\mathcal{D})\\
&= \arg \max\limits_{\substack{\theta}} \log \frac{P(\mathcal{D}|\theta)P(\theta)}{P(\mathcal{D})}\\
&=\arg \max\limits_{\substack{\theta}} \log P(\mathcal{D}|\theta)P(\theta) \\
&=\arg \max\limits_{\substack{\theta}} \underbrace{\log P(\mathcal{D}|\theta)}_{\text{log-likelihood}}+ \underbrace{\log P(\theta)}_{\text{regularizer}}
\end{aligned}\end{equation}$$
The prior is treated as a regularizer and if you know the prior distribution, for example, Gaussin ($\exp(-\frac{\lambda}{2}\theta^T\theta)$) in linear regression, and it's better to add that regularization for better performance.

I think MAP is much better.

MAP is better compared to MLE, but here are some of its minuses:

It only provides a point estimate but no measure of uncertainty
It predicts overconfidently
Hard to summarize the posterior distribution, and the mode is sometimes untypical
Reparameterization invariance
The posterior cannot be used as the prior in the next step
Can't compute credible intervals
Answer: If the data is less and you have priors available - "GO FOR MAP". If you have a lot data, the MAP will converge to MLE. Thus in case of lot of data scenario it's always better to do MLE rather than MAP.
Comment: It isn't that simple.
Comment: @MichaelChernick I might be wrong. I read this in grad school. I request that you correct me where i went wrong.
Comment: The frequentist approach and the Bayesian approach are philosophically different. The frequency approach estimates the value of model parameters based on repeated sampling.  The Bayesian approach treats the parameter as a random variable. So in the Bayesian approach you derive the posterior distribution of the parameter combining a prior distribution with the data. MAP looks for the highest peak of the posterior distribution while MLE estimates the parameter by only looking at the likelihood function of the data.
Comment: @MichaelChernick - Thank you for your input. But doesn't MAP behave like an MLE once we have suffcient data. If we break the MAP expression we get an MLE term also. With large amount of data the MLE term in the MAP takes over the prior.
Comment: It depends on the prior and the amount of data.  They can give similar results in large samples.  The difference is in the interpretation. My comment was meant to show that it is not as simple as you make it. With a small amount of data it is not simply a matter of picking MAP if you have a prior. A poorly chosen prior can lead to getting a poor posterior distribution and hence a poor MAP.
Comment: If you have a lot of good information to construct a prior the MAP could be better when the sample size is small. These comparisons are only valid if you treat MLE and MAP as point estimates of the parameter. That would not be the viewpoint of a Bayesian,
Comment: @MichaelChernick I completely agree on your point of parameters being a point estimate in MLE and a distribution in MAP. Going from here, what will be the answer to the originally asked question. When will I use MAP? In other words, how does one know if the prior(if available) is good or not?