We have a box with three different colors of balls. 8 green, n blue and 4 red...

Question: We have a box  with three different colors of balls. 8 green, n blue and 4 red. We chose 3 at random. For each blue we gain 2 points, for each green we lose 1 point, and nothing happens with the red ones. Write the probability function and calculate the expectation of profit.
What have I managed to do so far
b = blue, g = green and r = red
the possible ways to remove the 3 balls are
$A_1 = b, b, b = 6. P[ x = 6]   \frac{\binom{n}{3}}{\binom{12+n}{3}} = \frac{\frac{1}{6} (-2 + n) (-1 + n) n}{\frac{1}{6} (10 + n) (11 + n) (12 + n)}= \frac{B_1}{B_0}$
$A_2 = b,b,r=4. P[ x = 4]      \frac{\binom{n}{2}\binom{4}{1}}{\binom{12+n}{3}} = \frac{2 (-1 + n) n }{\frac{1}{6} (10 + n) (11 + n) (12 + n)}= \frac{B_2}{B_0}$
$A_3 = g,b,b=3. P[ x = 3]    \frac{\binom{n}{2}\binom{8}{1}}{\binom{12+n}{3}} = \frac{4(-1 + n) n }{\frac{1}{6} (10 + n) (11 + n) (12 + n)}= \frac{B_3}{B_0}$
$A_4 = b,r,r=2. P[ x = 2]     \frac{\binom{n}{1}\binom{4}{2}}{\binom{12+n}{3}} = \frac{6n }{\frac{1}{6} (10 + n) (11 + n) (12 + n)}= \frac{B_4}{B_0}$
$A_5 = b,g,r=1. P[ x = 1]    \frac{\binom{n}{1}\binom{8}{1}\binom{4}{1}}{\binom{12+n}{3}} = \frac{32n }{\frac{1}{6} (10 + n) (11 + n) (12 + n)}= \frac{B_5}{B_0}$
$A_6 = r,r,r=0, or, g,g,b=0. P[ x = 0]    \frac{\binom{4}{2}+ \binom{8}{2}\binom{n}{1}}{\binom{12+n}{3}} = \frac{34n}{\frac{1}{6} (10 + n) (11 + n) (12 + n)}= \frac{B_6}{B_0}$
$A_7 = g,r,r=-1. P[ x = -1]  \frac{\binom{4}{2}\binom{8}{1}}{\binom{12+n}{3}} = \frac{48}{\frac{1}{6} (10 + n) (11 + n) (12 + n)}= \frac{B_7}{B_0}$
$A_8 = g,g,r=-2. P[ x = -2]  \frac{\binom{4}{1}\binom{8}{2}}{\binom{12+n}{3}} = \frac{112 }{\frac{1}{6} (10 + n) (11 + n) (12 + n)}= \frac{B_8}{B_0}$
$A_9 = g, g, g= -3. P[ x = -3]  \frac{\binom{8}{3}}{\binom{12+n}{3}} = \frac{56 }{\frac{1}{6} (10 + n) (11 + n) (12 + n)}= \frac{B_9}{B_0}$
Profit
$\frac{B_1+ B_2+ B_3+ B_4+ B_5}{B_0} = \frac{\frac{1}{6} (-2 + n) (-1 + n) n + 2 (-1 + n) n + 4(-1 + n) n + 6n + 32n }{\frac{1}{6} (10 + n) (11 + n) (12 + n)}$
is my reasoning correct?
thanks for any help.
Comment: A bit hard to follow. Note that it is easy to compute the expectation.  Each draw is expected to earn $\frac {2\times n-1\times 8}{n+12}$ points, so by linearity $E=3\times \frac {2 n- 8}{n+12}$.
Answer: I find that the actual profit assigned to different colors distracts from a simpler way of looking at this. Imagine instead that you are given $N$ balls and each ball has an assigned value $b_i$ (not necessarily all distinct. Now, we do the same thing, we choose $3$ balls at random, say they are balls $i$, $j$ and $k$ and get the corresponding profit $b_i + b_j + b_k$. Let $B$ denote the set of balls, i.e. the values from $1$ to $N$.
Now if we want the expectation, we simply sum over all possible choices:
$$
E = \frac 1{N \choose 3}\sum_{\{i, j, k\} \subseteq B} b_i + b_j + b_k
$$
Now notice that in fact each $b_i$ value is counted $N - 1 \choose 2$ times in the sum, so we can rewrite the expected profit as
$$
E = \frac{N - 1 \choose 2}{N \choose 3} \sum_{i \in B} b_i = \frac 3{N}\sum_{i \in B} b_i
$$
Going back to your case, there are a total of $N = n + 12$ balls and the sum of their values is $2n - 8$ so the result becomes
$$
E = \frac 3{n + 12} \cdot (2n - 8)
$$
Comment: It should be $n+12$ at the denominator. If we want to keep things even simpler, we just consider the expected value of one ball being $\frac{2n}{n+12} - \frac{8}{n+12}$ and multiply by 3 because of linearity of expectation.
Comment: Indeed, the two methods must agree and the mistake was on my side. Notice when we count how many times the same $b_i$ value appears in the sum, the correct value is $N-1 \choose 2$ and not $N \choose 2$ because we must not count $b_i$. With that correction the results are the same.


Why is the mean of the minimum of $100$ exponentially distributed random variables equal to $\beta$ divided by $n$?

Question: Here's a question about order statistics, I can't seem to understand.

Suppose a battery lasts $1,000$ hours. If I have $100$ batteries, why is it that the mean that the first battery will go out will be $10$ hours?

I understand how $10$ hours was derived. It's $\beta$ divided by $n$. But, $10$ hours doesn't seem to make any sense. No matter what order, shouldn't the mean be $1,000$?
Comment: Is there an exponential distribution or something similar in the question? Perhaps some batteries dies before others due to the distribution and *first* means *earliest to go out*
Comment: It is an exponential distribution.
Comment: You should be careful when referring the the parameter since everyone does not follow the same convention. $\beta$ can refer to the rate or scale.
Comment: Take a large bunch of people. The length of life of the first person to die is (probably) going to be substantially less than average.
Answer: The lifetime of a battery follows an exponential distribution with mean $1000$.
It is well known that the minimum of $n$ iid exponential random variables follows an exponential distribution with mean $1000/n$. In fact, I explained this to you in the case that $n=3$.
Hence, the expected lifetime of the first to die is
$$\frac{1000}{100} = 10$$
It should not be $1000$ since the minimum lifetime of $n$ batteries does not follow the same distribution as the lifetime of any one particular battery,
$$\min\{X_1,\dotsc,X_n\} \overset{d}{\neq} X_i.$$


How to set a multi-value image field's default value from author's profile field on a node create form?

Question: On /admin/config/people/accounts/fields page, there is an optional multi-value image field field_proof_images. There is a content type Proof, I reuse the field_proof_images in Proof.
Then on /node/add/proof page, I want the field_proof_images to be automatically filled with the images from field_proof_images in the user accounts.
How to make this in Drupal 7?
Answer: You can prepopulate from other content through Tokens and Entityreference field. Here's a tutorial: Automatically Populate Drupal Fields From Other Content.
I don't know if it works with images but I don't see why it wouldn't. Not sure about the multi-value fields, you can try and see.

For a custom module solution you can lean on Prepopulate.

In Drupal 8 you can create a custom Media Entity browser that would show only the current user images from that field, then you might be able to choose them, or maybe even set as default.

Saving the images into the Content types ensures that if the user changes their user images it won't affect the Proof content. But if you want to always have them the same then you shouldn't add that to the Proof content at all. Simply create a contextual Views Block that would always display the content author's proof images and display it on the Proof nodes.
Comment: I'd tried your suggestions before I asked here. None of yours works. Thank you all the same!
Comment: You should have added the steps you tried and where you got stuck to your question. Add all the relevant information to increase your chanced of getting an answer.


How to symlink a package in workspace without updating yarn.lock?

Question: package.json -
"workspaces": [
  "packages/*",
  "samples/*"
],
"packageManager": "firstname.lastname@example.com"

I want to install and symlink the dependencies in samples but I don't want the yarn install to update the yarn.lock file.
Is there a setting in workspaces or yarn to achieve this?
Answer: I think you want to use yarn add your-package@"workspace:^" (or other workspace: ranges). This does end up in your yarn.lock, but when publishing your package yarn will actually replace the dependency with a versioned dependency (depending on the range specifier). Also, it doesn't include any hash or anything in the yarn.lock, so you don't need to reinstall when changes are made to the package.


Show certain content to roles based on taxonomy terms

Question: I am trying to personalize the viewing experience for users on a site.  I'm trying to figure out how to create a view that will show content tagged with taxonomy term 'a_term' to users with the role 'a_role'.  I want to tag all of my content with these different tags so that users with 'b_role' will see content tagged with 'b_term', 'c_role' -> 'c_term', etc...
Note: these are example names for roles/terms - there will be no naming convention like this.
Answer: Have you taken a look at Taxonomy Access? It allows you to set access control for roles based on taxonomy terms.
EDIT: Ignore the above dumb reply and feel free to downvote.
I think you could do this by creating a custom contextual filter in Views. Your contextual filter would look at the current user and decide which taxonomy terms ids to return.
If you are using Drupal 7 you could tag the users themselves with the same terms as a way to store which terms are associated with which users. Otherwise you might need to create a separate table to store the user to taxonomy association.
Comment: Looks great, but I don't want to restrict access to these nodes.  I want a "Things You Might Be Interested In" functionality.  I based what they're interested in on their role, which they choose when they signup.


Possible to send/recieve PHP data from changing an option in a dropdown menu?

Question: Let's say I have a select box like this:
<code><select style="margin-top: 5px; width: 190px;" id="daySelect">
    <option>Monday, April 1st</option>
    <option>Tuesday, April 2nd</option>
    <option>Wednesday, April 3rd</option>
    <option>Thursday, April 4th</option>
    <option>Friday, April 5th</option>
    <option>Saturday, April 6th</option>
    <option>Sunday, April 7th</option>
    <option>Monday, April 8th</option>
</select>
</code>
I want to send some variables to php to write to a file and right after load information fom the selected dropdown (The information I'm saving/loading will be in JSON if that matters).
For example: If I'm currently on Monday, April 1st and i have a variable xyz in JSON. When I click on Tuesday, April 2nd, I want to save xyz to the server (with php) and find Tuesday's xyz variable and load it.
I'm just wondering if this possible? And any ideas on how to approach the code on this one.
Answer: Yes the code to write to the file will be in a standard php script.  You will need to use javascript to attach an onchange handler to the select box which will fire an ajax request sending data to the php page.  The php page can then echo out some data which will be returned in the success handler of the ajax request allowing you to handle the returned data on the front end.
I would suggest looking into jQuery as it makes life a lot simpler.
Comment: If you decide to use jQuery for this, you might want to look at http://zeptojs.com/ or similar "lighter" libraries that are jQuery-like. No need to throw a tank of a solution at a feather of a problem.
Comment: Very true, I tend to use jQuery mainly because I use a lot of the other functionality and to be honest am most familiar with it.
Comment: Yeah I know how it goes, if you're already using it you also tend to find pretty good use for more and more of it's features as well. It's the gift that keeps on giving!
Comment: Ok cool, I've already included the JQuery library for other things, so that works. Do you know what the syntax is for AJAX jquery request (in the past, I've only received data with AJAX) never sent it.
Comment: If you take a look at the jQuery documentation it details very clearly how to do it with lots of examples :) and to be honest you will learn a lot more trying it yourself by looking at the docs than you would if we explain it on here. http://api.jquery.com/jQuery.ajax/  you may also want to look into the post varient if this suits your needs better or one of the other varients like getJson
Answer: I agree with Jon's point, but here's the gist of it anyway :)
<code>$('#daySelect').on('change', function() {
  $.get({
    uri: '/your/php/script',
    data: $(this).val(),
    success: function() { console.log('success') },
    error: function() { console.log('something went wrong') }
  });
});
</code>


Integral with $\delta$ function

Question: I got this integral in a quantum field theory problem:
$$
\int\limits_{-\infty}^{+\infty}\!\!\! dp \,
\frac{p^2 \delta\left(\sqrt{p^2-m_2^2}+\sqrt{p^2-m_3^2} -m_1\right)}{\sqrt{p^2-m_2^2} \sqrt{p^2-m_2^3}}
$$
Are there any 'tricks' to compute  integrals  where there $\delta$ is composed with another function?
EDIT: The solution is $\frac{\sqrt{(m_1-m_2-m_3) (m_1+m_2-m_3) (m_1-m_2+m_3) (m_1+m_2+m_3)}}{m_1^2}$. I calculated it as proposed in the answers.
Comment: Provided $f$ is continuously differentiable and it has most countably many simple roots $r_n$, $\int_{-\infty}^\infty g(x) \delta(f(x))=\sum_n \frac{g(r_n)}{|f'(r_n)|}$. This can be heuristically proven by changing variables. This is entirely applicable to your situation, since $\sqrt{p^2-m_2^2}+\sqrt{p^2-m_3^2}-m_1$ is a nice increasing function of $p$, so there is a single root. Assuming it does not occur at $p=m_2$ or $p=m_3$, everything will be OK.
Comment: what about changing variables?
Comment: Please check if the differential I added is ok.
Comment: I tried $u=\sqrt{p^2-m_2^2}+\sqrt{p^2-m_3^2} -m_1$, but it gets very messy. I'd like to know if there is a better way to deal with this kind of integrals.
Comment: That might be helpful
Comment: Incidentally, are $m_1,m_2,m_3$ all positive here?
Comment: Yes, there are particle masses.
Answer: Assume that:

$f$ has at most countably many roots $r_n$
$f$ is continuously differentiable at $r_n$ for each $n$
$f'(r_n) \neq 0$ for each $n$.
$g$ is continuous, at least at $r_n$.

Then
$$\int_{-\infty}^\infty g(x) \delta(f(x)) dx=\sum_n \frac{g(r_n)}{|f'(r_n)|}$$
One can heuristically prove this using a change of variable, but as a strict mathematical matter this should be considered to be a definition.
In your case, $f(p)=\sqrt{p^2-m_2^2}+\sqrt{p^2-m_3^2}-m_1$. This function is increasing for $p \ge \max \{ |m_2|,|m_3| \}$, decreasing for $p \le -\max \{ |m_2|,|m_3| \}$, and not real-valued elsewhere. It is also even. So for fixed $m_2,m_3$ and sufficiently large $m_1$, $f$ has two roots, both of which satisfy the assumptions above.
Comment: By the way, does that formula generalize for roots of multiplicity greater than one?
Comment: @mlainz No. Actually, unless $g=0$ at such a root, the resulting expression will not even be defined.
Answer: We have (see here)
$$
\delta\left(\sqrt{p^2-m_2^2}+\sqrt{p^2-m_3^2} -m_1\right)
= \delta(g(p))
= \sum_k \frac{\delta(p-p_k)}{\lvert g'(p_k)\rvert}
$$
where
$$
g(p) = \sqrt{p^2-m_2^2}+\sqrt{p^2-m_3^2} -m_1
$$
which has simple roots at $p_k$:
$$
g(p_k) = 0
$$

Integral with $\delta$ function


How to get microsecond timings in JavaScript since Spectre and Meltdown

Question: The situation
When writing high-performance JavaScript code, the standard profiling tools offered by Chrome et al are not always sufficient. They only seem to offer function-level granularity and it can be quite time-consuming to drill down and find the information I need.
In .NET the StopWatch class gives me exactly what I need: sub-microsecond resolution timing of arbitrary pieces of code.
For JavaScript performance.now() used to be a pretty good way to measure performance, but in response to Spectre and Meltdown all major browsers have reduced the resolution down to not even a millisecond.
To quote MDN on performance.now():

The timestamp is not actually high-resolution. To mitigate security
  threats such as Spectre, browsers currently round the result to
  varying degrees. (Firefox started rounding to 2 milliseconds in
  Firefox 59.) Some browsers may also slightly randomize the timestamp.
  The precision may improve again in future releases; browser developers
  are still investigating these timing attacks and how best to mitigate
  them.

The problem
I need microsecond precision timings. At the time of writing, browsers don't seem to offer any options or flags to disable these security measurements. Maybe I'm googling the wrong terms but the only articles I come across are explanations of the security problems and how these mitigations address them.
I'm not interested in the security aspect here - I'm benchmarking performance-critical pieces of JavaScript code on my own machine and the only thing I care about is that I get as accurate measurements as possible with as little effort as possible.
Existing workarounds
Two options come to mind:

Install an older version of a browser that doesn't have these mitigations implemented

I'd have to dedicate an old version of FireFox to benchmarking, and a new version of Chrome to browsing for example. That's not practical since I need to test in all browsers (and preferably also benchmark in all browsers). Also, new optimizations are not implemented in old browsers so the benchmarks would be potentially useless.

Implement a custom timer using WebWorkers

I've seen various older blog posts on this but none of them seem to achieve the high precision that I need (after all, there used to be performance.now() for that).
The question
How do I get an effectively pre-Spectre performance.now() without having to resort to older browser versions, Virtual Machines and such?
Are there any coding techniques or libraries in JavaScript that achieve microsecond precision?
Are there any options or flags for the 3 aforementioned browsers that disable these security measures?
I'm ultimately looking for a way to accurately measure the relative performance of different pieces of code compared to one another - so if there is a solution that gives me ticks, rather than microseconds, that would be acceptable too as long as it's accurate and works across browsers.
Comment: I think your best bet is to look for a knob somewhere that re-enables high precision timing in modern browsers; presumably they made it possible to enable for use-cases like yours.  I don't know how, but I'd guess it's possible.  You may have to build your own Firefox and Chromium from source with that option disabled, though.  You mainly care about using this in your own browser on one or a few machines, because this is for benchmarking use.
Comment: Given what you're describing sounds like quite low level timings, presumably it's not totally dependent on running in a browser (where accessing the DOM, performing ajax etc will be orders of magnitude slower than any code that's running) - could you instead work within the node.js environment?  You have [`process.hrtime`](https://nodejs.org/api/process.html#process_process_hrtime_time) there.
Comment: @PeterCordes JavaScript doesn't do threading, everything conceptually happens in a message loop in a single thread - while you have the likes of service workers now (which can be thought of as threads), you have to post messages between them - there's no guarantee as to how fast that message will be seen
Comment: Yeah you'd say so, but I've googled all over for disabling the precision restriction - the utter lack of results is what led me to ask this question. I think I found the commit in chromium: https://github.com/chromium/chromium/commit/a77687fd89adc1bc2ce91921456e0b9b59388120 - looks pretty hard-coded to me.
Comment: @Mike'Pomax'Kamermans One example of what I want to benchmark is specific hot paths in a parser. Testing whether a switch statement with 100 cases is perhaps a few % faster than a switch statement with only 20 cases and 2-3 if-elses. The optimizations are very different in Chrome vs FireFox vs Edge. Sometimes in Chrome it cannot be optimized further, but in FireFox it can. Apart from this low-level example, there are also higher-level benchmarks I'm looking for which are still sub-millisecond.
Comment: @PeterCordes Thanks for the useful insights. I'm currently looking at how to build Chromium :) If I somehow figure this out for Chrome and FF I'll post it as an answer. Hopefully someone else comes along in the meantime with an existing solution but that's probably wishful thinking, hah
Comment: In order to give a good recommendation: what do you need this precision timing for? And do you need precision timestamps, or precision *intervals*?
Comment: @Mike'Pomax'Kamermans Intervals. Quite simply, I need a "stopwatch" that can tell me how long a certain piece of code took to execute, and after trying to optimize that piece of code, compare the two timings to see if my optimization has improved the performance or not.
Comment: Can you run the code in a loop without the JIT optimizer doing something that destroys your microbenchmark?
Comment: @JamesThorpe Well yes and no. It is pure JavaScript that I'm looking to measure the performance of, so it's not dependant on running in a browser, but I do need to know how it performs *in a browser*. NodeJS would only give me the metrics for Chrome, presumably
Comment: @PeterCordes Doing thousands of iterations in a loop is how I'm currently doing my benchmarks, but the JIT optimizations do give some uncertainty here. Also the looping itself makes it quite tedious to do benchmarks since I have to refactor and isolate code and effectively make it different, just to be able to measure. Ideally I just want to drop some measurement points in existing code without having to rewire everything,
Comment: *Are there any coding techniques or libraries in JavaScript that achieve microsecond precision?* If there were, it would be a vulnerability in the current defence mechanism against Spectre.  (AFAIK, you can't easily exploit Meltdown from JS, just Spectre.  And kernel Meltdown patches totally block it, while kernel Spectre patches only defend the *kernel*, and maybe processes from other processes; they still leave sandbox VMs vulnerable to guest code in the same process.  Making the timing-based side channels unusable is basically necessary to defend the browser internals from JS guest code.)
Comment: @PeterCordes Fair point. But say for example if you had an infinite loop running in a webworker, just counting (and fully utilizing a CPU core in the process), and you'd ask it the current count on two different moments, that would potentially still be useful information. I just don't know exactly how to do that (and whether it's viable to begin with - not sure about the overhead of postMessage, etc)
Comment: @PeterCordes Yeah I'm kind of looking for a knob, just saying I'd be open for other options as well if they existed. Building firefox and chromium from source is actually a pretty clever idea, I'll look into that.
Comment: Interesting; that loop hack hopefully would get you better than ms precision, but likely with many microseconds of overhead.  Probably not good enough for reliable Spectre attacks.  Does JS have shared atomic variables that you can read from one thread while another atomically increments them?  Or would the looping thread have to receive and reply to a message?  (I don't really know javascript, just CPUs / low level stuff; I'm here for the `[benchmarking]` and `[performance]` tags :P)
Comment: This also feels a bit like optimizing the wrong thing: timing individual pieces of code when the full codepath is already at, or sub-2ms suggests you already have code code in which optimization is going to be -effectively- irrelevant. To optimize those pieces of code, you're really more looking at complexity analysis, not runtime analysis, so that increased length input doesn't go from 2ms to 2 seconds to 2000 years over two orders of magnitude. And if you _have_ to optimize them, you have code for which Node.js would be fine.
Comment: @Mike'Pomax'Kamermans: 2 ms is about 8 million CPU clock cycles on a 4GHz CPU.  That's many thousands of times longer than the out-of-order window (224 uops) on Skylake, even running code with low instructions per clock.  It's also long enough that you can probably usefully microbenchmark something that you might use as part of a loop without having things totally distorted by it being so small that it normally gets folded into part of a larger operation.  (i.e. we're not talking about ++x vs. x++ here or other things that are meaningless without looking at the JIT asm output.)
Comment: @FredKleuver: Yup, as an asm guru, that sounds like a reasonable thing to try to profile / microbenchmark this way, except that microbenchmarking branches that might mispredict is *hard*.  Modern branch predictors learn easily, and creating the same amount of unpredictability as in your real use-case is hard.  (And just putting it in a loop distorts that.) Maybe a *bit* on the small side, especially if it turns into a jump table.  (Err, if the cases aren't integers like they have to be in C, but instead string matches or something, that's a bit bigger and an even better fit for microbenching.)
Comment: @PeterCordes Interesting. With that in mind the results will also vary from cpu to cpu, and I can only go so far. There will always be some rate of error and that's perfectly acceptable. Surely microsecond vs millisecond precision timing is the low-hanging fruit here, hence that's what I'm focusing on.
Comment: For a single `switch` statement you might well need nanosecond precision to get useful results.  Some messy multi-threading stuff you hack up is not going to be worth the trouble vs. getting the JS implementation to give you high-rez time directly.  For open source browsers it's *definitely* possible, it just might take a bit of work.  The relative performance of the same x86 asm can be different on different hardware, too, so you don't want a timing method that also varies with CPUs making it impossible to tell what's what.  (But beware of turbo / powersave CPU frequency variation either way)
Comment: I'd look for the commits that introduced this change, and see if it included an option to disable it in a Firefox config setting that has no GUI menu entry, just buried in about:settings somewhere.  Or actually I'd just go looking in those settings at first, and maybe google on how to disable the precision restriction.  You probably aren't the first person to want this.
Comment: @FredKleuver: Yeah, no sign of a time API that bypasses `TimeClamper::ClampTimeResolution`.  But if there is, you wouldn't necessarily see it in that patch, because there was already a 5us limit before that.  Anyway, looks easy to disable in the source.  Changing `static constexpr double kResolutionSeconds = 0.0001` to `1.0` would work, or for lower overhead by making `TimeClamper::ClampTimeResolution` a no-op or leaving out calls to it.  (And BTW, `floor(time_seconds / kResolutionSeconds)` would be more efficient as `floor(time_seconds * (1.0/kResolutionSeconds))` to avoid runtime division.
Comment: You really got [nerd sniped](https://xkcd.com/356/) by this huh :) Thanks a ton though, very helpful info! I haven't been able to build chromium yet (no large OS product ever manages to build first try on Windows), so no good news from my end yet.
Answer: Since Firefox 79, you can use high resolution timers if you make your server send two headers with your page:

Starting with Firefox 79, high resolution timers can be used if you cross-origin isolate your document using the Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

These headers ensure a top-level document does not share a browsing context group with cross-origin documents. COOP process-isolates your document and potential attackers can't access to your global object if they were opening it in a popup, preventing a set of cross-origin attacks dubbed XS-Leaks.
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Performance/now

It's not mentioned on that page as of this moment, but with a little experiment, I've concluded that the accuracy of the timer is 20µs with those headers present, which is 50x better than the accuracy you get by default.
(() => {
  const start = performance.now();
  let diff;
  while ((diff = performance.now() - start) === 0);
  return diff;
})();

This returns 0.02 or a value very close to 0.02 with those headers, and 1 without.
Comment: These headers now also give improved timer precision in Chrome, see https://web.dev/coop-coep
Comment: Also Safari 15.2 (both iOS and Mac) gets 0.02ms intervals with those headers, and 1ms without. Chrome gets down to 0.005ms intervals with those headers enabled (Chrome 97 on M1 Mac seems to have a bug resulting in 0.125ms intervals, but this seems fixed in Chrome Canary).
Answer: Firefox does have a config setting called privacy.reduceTimerPrecision that disables the Spectre mitigation. You can switch it to false using Firefox's about:config page (type about:config into the address bar).
Figured this out via a hint on MDN.
Comment: I read about that option in FireFox back when I posted this question but it didn't seem implemented yet at the time. It's there now though.
I should note that toggling that doesn't actually disable the Spectre mitigation entirely, it just clamps it to 20µs which is what the mitigation was in v59. Still a lot better than the default clamping to 1-2ms, but not quite the 5µs that it used to be..


PHP Switch using it with Functions

Question: I have this switch and I do certain things based on the selection of the action with the switch. Based on my testing, function thats in the switch is not even taking place when the page runs.
I am interested in being able to running the sortby action for now. when I go to the page, switch puts me in the first case but does not run the function.Why? How do I fix it?
<code>switch ($_GET['action']) {
        case 'sortby':
            sort_by($_GET['sortby']);
            break;
        case 'add':
            resident_add($_GET['residentID']);
            include('inc/modify/add.php');
            break;
        case 'edit':
            resident_edit($_GET['residentID']);
            include('inc/modify/edit.php');
            break;
        case 'delete':
            resident_delete($_GET['residentID']);
            include('inc/modify/delete.php');
            break;
        case 'search':
            echo "";
            break;
        default:
            resident_default($_GET['sortby']);
    }

function sort_by($sortby) {
    if ($sortby == "last_name") {
        $sort_db_field = "Last Name";
        $sort_order = "ASC";
    } elseif ($sortby == "lot") {
        $sort_db_field = "Lot";
        $sort_order = "ASC";
    } elseif ($sortby == "date_added") {
        $sort_db_field = "No";
        $sort_order = "DESC";
    } else {
        include('inc/error.php?error_code=100');
    }
return $sort_db_field;
return $sort_order;
}

$data = mysqli_query($dbcon, "SELECT * FROM `residents` ORDER BY `residents`.`".$sort_db_field."` ".$sort_order."") or die(mysqli_error());
</code>
Comment: @rainfromheaven what should I return in this case in sort_by? I forgot I to use functions the most part... @amal $data = mysqli_query($dbcon, "SELECT * FROM `residents` ORDER BY `residents`.`".$sort_db_field."` ".$sort_order."") or die(mysqli_error());
Comment: Are you sure it doesn't run the function? You're not returning/printing from the `sort_by`, so how can you know?
Comment: I added this still not working
 return $sort_db_field;
 return $sort_order;
Comment: Your `mysqli_error()` should have the link inside: `mysqli_error($dbcon);`
Comment: TWO `return`s in a single function ??? this is madness, second one will never run
Comment: I see. how should I accomplish what I need to be done?
Answer: You can't have 2 return statements in a function, the second one will never be executed.
Declare two variable before your switch:
<code>$sort_db_field = "";
$sort_order = "";

switch ($_GET['action']) {
    /*snip*/
}
</code>
Then in the function drop the returns. This function will now set the values in the two variables you declared.
Comment: Only if you use `global` or pass those vars in by reference.

PHP Switch using it with Functions


Where are the pages for the Statistics module shown?

Question: I've installed the Statistics module (version 7.18) in my Commerce Kickstart 2 store, but I can't find it anywhere in menu.
What should I do to access this module?
Answer: After enabling the statistics module, be sure to configure the module (admin/config/system/statistics).
The documentation for the statistics module indicates that:

To enable collection of statistics, the Enable access log checkbox on
  the Statistics settings page must be checked. This access log is used
  to store data about every page accessed, such as the remote host's IP
  address, where they came from (referrer), what node they've viewed,
  and their user name. Enabling the log adds one database call per page
  displayed by Drupal.
The Discard access logs older than setting on the settings page
  specifies the length of time entries are kept in the log before they
  are deleted. This setting requires a correctly configured cron
  maintenance task to run.
Enable Count content views to turn on and off the node-counting
  functionality of this module. If it is turned on, an extra database
  query is added for each node displayed, which increments a counter.

After configuration, data will begin to be collected for the four reports that statistics provides:

Recent hits (admin/reports/hits)
Top Pages (admin/reports/pages)
Top Visitors (admin/reports/visitors)
Top Referrers (admin/reports/referrers)

NOTE: This applies to all Drupal 7 installations.  Statistics is a core module and is not specific to Commerce Kickstart 2.


How to plot contour of a covariance matrix of a gaussian distribution?

Question: I just want to ask how you can plot the contour of covariance of a Gaussian, say covariance of [513.5211 -160.7084; -160.7084 808.8846].
For example

The gaussian points are red and the covariance is represented by the blue dotted circle. How can I plot the plot dotted circle (covariance matrix) in Matlab?.
EDIT
Here is what I have done
Sigma = Cov(X);
Contour(Sigma);

Any idea?
Comment: @DangKhoa, please see Edit for wjat i was trying.
Comment: i am trying to use the example here: http://statlearn.free.fr/doc/Multidimensional%20distribution%20tutorial.htm, but g = gaussdens('m',[1;2],'var',[4 1;1 2]); does not exist in mt matlab version(Ver R2008b). The show(g) also does not work. Any idea of any function that does this job in matlab?
Comment: I think `gaussdens` is a function of the 3rd-party toolbox [`statlearn`](http://statlearn.free.fr/). Do you have that toolbox?
Comment: @Schorsch, No i don't have the gaussdens toolbox.
Comment: Have you tried downloading and using the [`statlearn`](http://statlearn.free.fr/index.html) toolbox?
Comment: @Schorsch, i have used a different third party function and it is working for me now. I just have one issue, in my program, i generate population initially using rand and for each iteration of my loop, i select top 25% of the population. I plot both the Generated Population and selected individuals for each run of the algorithm, but each time i look at the positions of the selected individuals on their plot and their position in the plot of the initial generated population, they are different, when their positions should be the same. I don't know why. Any idea why and how to solve it?
Answer: I finally did what i wanted to do by using a third party function called plot_gaussian_ellipsoid from the Matlab Central FileExchange.
It plots the contour of the covariance matrix.


Is it possible to target the first child of a div with CSS?

Question: Is it possible to target the first .col/h2 and add a CSS style of padding-top:0px?

xxxx

xxxx

xxxx

xxxx

Comment: This question is off-topic because it is asking about **possibilities** and **is not a concrete coding question**. If you want to know if something is possible you should **research it** and **attempt to implement it**. If you have issues while doing this you then can ask a **specific** question, **showing the code you have written**, your expected results, and your actual results.
Answer: You can use the pseudo-class :first-child to accomplish that.
.container .holder article:first-child {
padding-top: 0px;
}

Also, just a heads up, you are closing your
 tag with an
.
Answer: Yes, it's possible. Use :first-child:
.col:first-child h2 {
    padding-top: 0px;
}

:first-child
The :first-child CSS pseudo-class represents any element that is the first child element of its parent.
Comment: Thanks, I tried it out and it works. I just wasn't sure because I tried it out before posting here if using :first-child only applied to lists.
Answer: DEMO
pseudo-class :first-child
.col h2:first-child {
    padding-top: 0;
}


covariance of mean estimate via Monte Carlo approximation

Question: Please read the following explanation:

Let's consider an example where we want to estimate the mean of a
  random variable $x$. Let's call this a Monte Carlo approximation
  $\hat{\mu}$. If we look at the variance of this estimate, so the
  covariance of $\hat{\mu}$ is equal to this expression, where this is the
  Monte Carlo approximation of the mean, $\hat{\mu}$. What we see here is
  that our variance or covariance of $\hat{\mu}$ does not depend on the
  dimensionality of $x$, but rather decreases just linearly as we add samples.

My question is, why this equation is true?
${\rm{Cov}}\{ {\bf{\hat \mu }}\}  = {\rm{Cov}}\{ \underbrace {\frac{1}{N}\sum\nolimits_{i = 1}^N {{{\bf{x}}^i}} }_{{\rm{Monte.Carlo.approximation.of.the.mean: }}{\bf{\hat \mu }}}\}  = \frac{1}{N}{\rm{Cov}}\{ {\bf{x}}\} $
Comment: It does not apply to MCMC simulations per se but the decrease of the variance in $1/N$ remains true.
Answer: If we assume independent samples $x^i$, then
$$\operatorname{cov}\left({1\over N}\sum_{i=1}^N x^i\right)={1\over N^2}\sum_{i=1}^N\operatorname{cov}(x^i)={1\over N^2}\sum_{i=1}^N \operatorname{cov}(x)=\frac{1}{N}\operatorname{cov}(x)$$
Comment: because $x_i$ is assumed to be sampled from $p(x)$
Comment: Thank you for your answer. Why the $cov(x^i)$ is substituted by $cov(x)$? I'm a little confused!


git: squash three last commits together

Question: I want to squash my 3 last commit together (from ax38aa to ax18aa).
i had
commit ax18aa
commit ax28aa
commit ax38aa
commit ax48aa
commit ax58aa

Code
git rebase -i ax48aa

but was surprised that when i did git log i have only
commit ax48aa
commit ax58aa

and didn't ask mi the new message for the commit. How can i do? please?
who can help please
Thank youu,
Comment: Does this answer your question? [Squash my last X commits together using Git](https://stackoverflow.com/questions/5189560/squash-my-last-x-commits-together-using-git)
Comment: @mnestorov no . I did **git rebase -i ax48aa**
Comment: Does the same result happen when you do `git rebase -i HEAD~3`
Comment: but now in my git log i haven't the **commit ax18aa
commit ax28aa
commit ax38aa** so can't see :/.
Comment: @mnestorov can you help me please?``
Comment: @mnestorov in this link https://stackoverflow.com/questions/5189560/squash-my-last-x-commits-together-using-git they said that **git rebase -i **
Comment: During your interactive rebase, to each commit, what was the command you issued? Did you pick some of the commits? Did you squash all of them?
Comment: i changed all the pick to squash. @mnestorov
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/220217/discussion-between-mnestorov-and-jappa).
Answer: That can be done like this:
git reset --soft ax38aa
git commit --amend -m "some blahblah"

Comment: `git reset --soft ax38aa`
Comment: You also need to add -m before the "some blahblah"
Comment: thank you @eftshift() but i don't want to squash the **ax58aa** the new commit i mean for the squashed commit commit **ax18aa, commit ax28aa, commit ax38aa**
Answer: It looks like you squashed all of the commits during your interactive rebase, leaving you in a state of rebasing. This means that you are currently doing the rebase, but have not finished it and can only see the oldest two commits ax48aa and ax58aa. The easiest way to get out of this situation is to:
git rebase --abort

This will discard any changes you might have done and will put you in the state before the rebase. If by any chance you still do not see all of your 5 commits, then look into the reflog with git reflog, find the first commit and do git reset --hard ax18aa.
Now do a new rebase again, but this time, pick the oldest/top most commit of your interactive rebase.
git rebase -i HEAD~3
# or
git rebase -i ax48aa

and then do the following:
pick ax38aa commit message 3
squash ax28aa commit message 2
squash ax18aa commit message 1

This will do what you wanted.
Also keep in mind that after your rebase, you will have a new commit and you will need to force push to your remote repo in order for your changes to be uploaded!

git: squash three last commits together


Find the number of polynomial functions satisfying a given condition.

Question: How many  polynomial functions $f$ of degree $\geq 1$ are there, satisfying $f(x^2)=(f(x))^2 =f(f(x))$, for all real $x$?
I have found the function $f(x)=x^2$ satisfies the condition. I have no idea how to find it generally.
Please help me to solve this.
Answer: If the degree of $f$ is $d$, then the degree of $f(x^2)$ is $2d$, that of $(f(x))^2$ is also $2d$, but that of $f(f(x))$ is $d^2$. We conclude $d=2$ (or $d=0$, but that's excluded).
So $f(x)=ax^2+bx+c$ with $a\ne0$. Then $$f(x^2)=ax^4+bx^2+c$$ and
$$f(x)^2=a^2x^4+2abx^3+\ldots$$
so that $a^2=a$, hence $a=1$, and $2ab=0$, so $b=0$. So now we can refine to
$$ f(x^2)=ax^4+c$$
and $$ f(x)^2=a^2x^4+2acx^2+c^2$$
and conclude $c=0$. It follows that $f(x)=x^2$ is the only possibility, and on verifies immediately that it actually works.
Answer: Hint Suppose $f(x)$ has degree $n$, so that $f(x) = a_n x^n + \cdots$, where $a_n \neq 0$, and here and henceforth $\cdots$ denotes a sum of lower-order monomials than the one that appears before it. Computing the leading terms gives
\begin{align} f(x^2) = (a_n (x^2)^n + \cdots) &= a_n x^{2n} + \cdots \\ f(x)^2 = (a_n x^n + \cdots)^2 &= a_n^2 x^{2n} + \cdots \\ f(f(x)) = a_n(a_n x^n + \cdots)^n + \cdots &= a_n^{n + 1} x^{n^2} + \cdots \end{align}

Additional hint Comparing degrees gives $n = 2$, and then comparing leading coefficients gives $a_n = 1$, so $f(x)$ must have the form $f(x) = x^2 + b x + c$ for some $b, c$. For which $b, c$ does it satisfy the conditions?


Parameter estimation from single dynamic experiment. How many degrees of freedom?

Question: I am estimating a parameter (diffusivity) from a set of experimental data coming from the same dynamic experiment: it can be summarised as changing the oxygen partial pressure around a solid and measuring the mass uptake with time (it is actually somewhat more complex than this but for the sake of this question, this description suffices).
This experiment was carried out only once and, as it is measured online, it provided a lot of data. I estimate the diffusivity of oxygen for trying to assess whether the diffusivity changes when changing the relative humidity.
I did a first estimation (least-square minimisation) using 8 data and I obtained the following figure

The estimated value of the diffusivity is $D = 0.10$ and a $ \alpha = 0.05$ confidence interval would be approximated by $[0.06 - 0.17]$. To obtain the confidence interval I used the asymptotic approximation
$$ \hat{\theta} \pm t^{\alpha/2}_{n-m}  \hat{\sigma} \sqrt{diag(J^{T}J)^{-1}}  \tag{1}$$
where $n$ is the number of data, $m$ is the number of parameters (in this case 1), $J$ is the Jacobian of the regression function and the unbiased estimator of the error variance
$$\hat{\sigma}^2 =\frac{\sum_{i=1}^n (y_i-f(\hat{\theta}))^2}{n-m} \tag{2}$$
If I repeat the estimation of the parameter using 62 data points I obtain

Now, the estimated value of the diffusivity is $D = 0.130$ and the confidence interval $[0.122 - 0.138]$.
What troubles me here is that, these additional data points are not "independent" in the sense that, coming from the same experiment, we can expect them to be dependent on the previous data point. Likewise, the second figure does provide more information to estimate the parameter but, it would seem that if the measurements can be taken online, the parameter (in this case, the diffusivity) can be estimated with arbitrary confidence, which of course, is not true.
My intuition is that those extra data points provide some information that allows a more accurate estimation. But only to a certain extent. To be really considered as independent data, each should come from an individual experiment (which in this case would be unfeasible).
So, here comes my question: How many degrees of freedom are there in a single dynamic experiment such as this one? And how should the different number of data be used when comparing the obtained parameter (e.g. t-test) with another one at different conditions?
Comment: Welcome to the site. You wrote "What troubles me here is that, these additional data points are not "independent" in the sense that, coming from the same experiment, we can expect them to be dependent on the previous data point. "  Can you say more about why you think this? Why should they be dependent on the prvious data?
Comment: Well, the evolution of a deterministic system depends on the previous state. Therefore, the concentration at t+1 will depend on the concentration at t. Eventually, all the data points depend on the initial one. I would consider them as independent if I reconstructed the same profile (62 data points) with data from 62 experiments and, from each experiment, I would take only one data point at different sampling times. Again, it is more my intuition than something I can formalise
Comment: What is the origin of this confidence interval?  It strangely admixes two nearly contradictory theoretical elements: the asymptotic maximum likelihood theory and the small-sample Student t distribution.  Perhaps your question could be resolved simply by using a different confidence interval procedure.
Comment: I have to admit I don't follow exactly your point @whuber. Is it about equation (1), which I have used until now repeatedly? Or my comment "_e.g. (t-test)_"? Which different procedure would you suggest?
Comment: Because the fits aren't good, I would suggest (a) using a different model that (b) allows for correlation among the errors and (c) uses standard ML confidence intervals (which typically are based on the standard Normal distribution rather than the t distribution and use the MLE of $\sigma$ for its estimate).  Also, because it's likely $\hat\theta$ is strongly correlated, consider using a confidence region rather than separate confidence intervals for its components.
Comment: You're right. As I have been working with these data during these days, I have corrected the systematic error (drift upwards) to the expense of a higher measurement error. Now the fits are better and note that $\hat{\theta}$ is a single parameter so I assume that the confidence region becomes a confidence interval. Still, my question holds, I can take an almost arbitrary number of data for this experiment and the confidence interval would keep shrinking, but, can I just compare the value of parameter $D$ with a single different dynamic experiment and check if $D$ changes?
Answer: What you're dealing with here is a common task in the field of system identification: You're trying to estimate one parameter $D$ (diffusivity) of your model $C(D, t)$ (which is hypothesized to be the true model, normally found by applying first principles) based on measured data $C_m(D, t)$:
$C_m(D, t) = C(D, t) + n(t)$
Where $n(t)$ is measurement noise. $n(t)$ should be independent of $C(D, t)$. Furthermore, very often it is assumed that $n(t)$ is white noise with a constant variance $\sigma$. Under these assumptions, all $N$ samples of $n(t)$ are iid and you can construct confidence intervals for your estimation of $D$ with $N-1$ degrees of freedom.
So the main point is that your intuition is correct: The $N$ samples of $C_m(D, t)$ are not idd due to the function $C(D, t)$ being deterministic, but the $N$ samples of measurement noise $n(t)$ should be iid.
More details can be found in books about System identification. The classic reference is: Lennart Ljung: System Identification — Theory For the User, 2nd ed, PTR Prentice Hall, Upper Saddle River, N.J., 1999.
Answer: Statistical independence/dependence does not make reference or concern itself with whether or not the data comes from the same experiment but about the data generating process. Independence in statistics is whether or not the data points influence each other, not whether or not they come from the same experiment. So your concern of "What troubles me here is that, these additional data points are not "independent" in the sense that, coming from the same experiment, we can expect them to be dependent on the previous data point." is not a concern in general but likely because of your specific experimental setup.
That is it's a different concern to say "my data are all from one experiment and so I might have a problem" than to say "my data are not independent". In your case you have both problems. However, the only way to address the limitation of "my data is just from one experiment" is to run more experiments. However then you get into the issue of "all my data is just from one experimental apparatus" so you need to find another experimental apparatus... so on and so forth. Another way to address this is to say that the all from one experiment concern addresses "systematic" error and the "data are not independent" concern reflects the concern that your uncertainties are miscalculated from that experiment (i.e., you are misestimating the "random" error.
Furthermore, for these models and this setup that you are doing I would argue that "degrees of freedom" is an ill defined concept and so you just shouldn't worry about it. The trickiness with defining it for your particular experiment is that it isn't clear in how many ways you can vary/change your system independently. I guess my answer is: you're asking a good question and the answer is unfortunately that the concept just doesn't really apply.
You are doing diffusion experiments and I have some familiarity with them though likely in a very different context and it sounds to me like you are measuring how quickly oxygen diffuses into a material (if this is wrong then your model will need to be more complicated). Let's go with measuring oxygen uptake in a material to measure the diffusion coefficient. So there are some possible parameters that your model is interested in fitting: the diffusion coefficient and the measurement error.
Instead of fitting a curve to your data as you have done now which leads you to all sorts of nasty considerations such as what happens when the data are not statistically independent (that is the data depends on other data points; in your case points depend on the value before them). I would propose you setup a physical model of your system and then fit the parameters using a bayesian model. The basic idea I am proposing is as follows:
1) write a physical model that generates the data from a diffusion coefficient
2) use a MCMC sampler to fit the diffusion coefficient and measurement error that best fits your data along with the uncertainties
For the MCMC sampler you will need to use a likelihood function and for that I propose weighted square deviations:
$$L = \sum_i {(y_i-s_i) \over \sigma^2}$$
where $$s_i$$ are the simulated data that correspond to each $$y_i$$ and $$\sigma^2$$ is the measurement error that you are fitting from your data.
Assuming that the MCMC sampler does it's job and finishes you should get both the parameter values and uncertainties without having to explicitly worry about degrees of freedom.
Here is some example code for a similar situation: https://github.com/bblais/pyndamics
Comment: Thanks. I would say that in a single dynamic experiment data points do influence each other as the value at t+1 is conditioned by the value at t
Comment: Yes, it is gas diffusion, not really oxygen but it is a similar setup anyway
Comment: So the thing about the dependence is that the data points are not dependent once you know the time at which the data point is taken because all you have at that point is the measurement error. What I mean is this: the data point at t+1 is not dependent on the data point at t because you have measurement error in your setup. The true concentration at t+1 is dependent on the true concentration at t, but once you know what which time you have sampled you can calculate that from the actual physical model of the system and so that dependence in removed when thinking about the measurement error.
Comment: I forgot to answer this in my post but it is another reason why I like the approach of specifying a physical model and then adding measurement error on top of it.

A simple example of this is consider the case of a linear regression: The y value is dependent on the x value but once you know the x value and predict the likely y value the distance from the line is independent of the x value.
Answer: Suppose that your instrument measures
$$y=f(D)+n$$
where $f(D)$ is the exponential diffusion curve that you plotted and $n$ is the measurement noise. Since you are talking about a single experiment we assume that $f(D)$ is deterministic and only the measurement noise is random. When you are talking about independence and degree-of-freedom, it concerns $n$, not $D$.
You wrote "the evolution of a deterministic system depends on the previous state. Therefore, the concentration at t+1 will depend on the concentration at t. Eventually, all the data points depend on the initial one."
This does not make any problem. This actually enables us to use all the points in the experiment to estimate one single parameter $D$, assuming a model function $f$.
In the case of a single experiment assuming that all the uncontrolled conditions are at a single value, the confidence interval only concerns the measurement process.
Every measurement equipment has a bandwidth: it can produce a limited number of independent observations in a time span. Hopefully, the bandwidth of your measurement equipment is large enough such that it can measure $f(D)$ without any distortion. But we like to make as many observations as possible to improve the accuracy of the estimation.
You need to answer this question: "Do you already see bandwidth limitation in $n$?
You can calculate the residual of your estimate and study their autocorrelation function or their power spectral density. In the case that you see a strong correlation, you can calculate an equivalent number of independent samples and adjust your estimate of the variance of parameters. For example, is your collect 100 samples per second for a duration of 1 second then you have 100 samples. If you analyze the residuals and see that the bandwidth of the data is 25Hz instead of 50 Hz it means that half the samples are effectively redundant and then you need to multiply your variance by 2. Or you can downsample your signal to remove the correlation. If you don't see any correlation in the samples then the degree of freedom would be the number of samples minus one. But the confidence interval concerns the measurement process not the diffusion constant.
The fact that confidence interval is reported from a single experiment, however, is troublesome in my view, unless the propose of the experiment is to demonstrate the accuracy of the measurement apparatus, not the diffusion constant. We report the number because it supposed to be reproducible. So at least given all your conditions and instruments if someone repeats the experiment then she should be able to get similar numbers and we report confidence interval to make possible to measure similarity.
Also a side note About selecting the point: When estimating the parameter in a decaying process, e.g.:
$$y = A - B \exp(-Dt) + n$$
The points close to $t=0$ are the most important ones. Since as $t$ increase the signal component to noise ratio becomes smaller.
Comment: Thanks. That's an approach I haven't thought of. My only concern is, would autocorrelation only mean "sampling redundancy"? Let's imagine that the model has a larger mismatch at large t, then the autocorrelation would be represent model mismatch, right? That would make it more useful even! But I want to make sure I understood your answer
Comment: If the model has a larger mismatch n for large t then that should be modelled in as different variance for samples of n. The auto correlation of n shows the dependency of samples of n.


Flutter on Android emmulator bottom control panel either disapears or overlaps my screen

Question: I am working on a Flutter project, I've noticed that when I run it on an Android Emulator / Device, the bottom panel (with the controls on it, sorry I am not sure what this is called in Android) is sometimes either not showing or being shown on top of and hiding the bottom of the screen. Which is a problem as there is a Button located there.
Could someone please let me know how to control this in Flutter. What I want is that the Red button is always showing above the bottom panel.
Any help with this would be much appreciated
Please see the attached screen shots:
Answer: Wrap the whole body widget inside Safe Area


Negative y axe in matplotlib

Question: I want to make negative values on y-axe using
plt.yticks([10**(-8), 10**(-5), 10**(-2), 10, 10**(4)]) OR
plt.ylim([10**(-8), 10**(4)])

However, I have the following result:

Numbers are clustering together. This graph is a sample that I am looking forward to making :)

Answer: You need to make the scale of your y-axis logarithmic. Also, the values you are using are not negative. These are less than 1 and therefore the exponent is negative. Use
plt.yscale('log')

Negative y axe in matplotlib


Lógica de todas as misturas possíveis dos valores de um array de quantidade variável. PHP

Question: Estou quebrando a cabeça para criar uma lógica que faça o seguinte:
Receba um array de N posições, dentro dessas posições definir todas as possibilidades possíveis sem repetir a key de uma posição.
Exemplo:
Array('A','B','C')
A
AB
ABC
AC
ACB
B
BA
BAC
BC
BCA
C
CA
CAB
CB
CBA
Exemplos da fórmula matemática
Quando existem 3 posições:
3+(3*2)+(3*2*1)
Quando existem 4 posições:
4+(4*3)+(4*3*2)+(4*3*2*1)
Comment: ta dificil implementar isso... kkkkkkkk
Comment: Acredito que poderia resolver isso utilizando `n` `for`, sendo `n` a quantidade de variáveis que irão ser utilizadas
Comment: Uma dúvida, você tem algum controle sobre a quantidade de variáveis que entram?
Comment: Sim, podem entrar de 1 a 10 valores e posso identificar quantos são.
Answer: Se houver controle em cima da quantidade de variáveis que entram, você pode criar X estruturas for, sendo X a quantidade de variáveis do array, fazendo algo do tipo:
$arr = array("A","B","C");

for ($i = 0; $i < count($arr); $i++) {
    echo $arr[$i]."\n";
    for ($j = 0; $j < count($arr); $j++) {
        if ($i != $j) {
            echo $arr[$i].$arr[$j]."\n";
            for ($k = 0; $k < count($arr); $k++) {
                if ($i != $j && $i != $k && $j != $k) {
                    echo $arr[$i].$arr[$j].$arr[$k]."\n";
                }
            }
        }
    }
}

Veja funcionando no ideone
É um processo mais manual, e exigiria uma quantidade maior de codificação, vou ver se consigo criar algo mais automatico.
Comment: Já pensei por esta possibilidade, mas acho que não fui claro no meu comentário anterior. Eu não defino quantos valores entram, somente sei quantos, a logica que busco deve comportar valores a serem definidos depois do recebimento dos valores do array. Estou tentando fazendo algo utilizando a recursividade nas chamadas para o for. Mas mesmo assim muito obrigado por esta resposta.
Comment: @paje Acredito que utilizando uma lógica meio hibrida usando o conceito de "binários" e potencia de um "número n" (tamanho do seu array), você consiga resolver seu problema, estou tentando elaborar aqui
Comment: Não entendi o que você quis dizer com "conceito de binários". Estou tentando fazer quase do mesmo modo que você realizou manualmente, porém sem a necessidade de incluir mais chaves dentro do loop.


Using Azure, is there a way I can detect text orientation?

Question: I'm currently using the Auzre Vision API through Python like so:
import azure.ai.vision as vision

service_options = vision.VisionServiceOptions(
    os.environ["PAY_VISION_ENDPOINT"], os.environ["AZURE_PAY_VISION_KEY"]
)

vision_source = vision.VisionSource(filename=str(image_path))

analysis_options = vision.ImageAnalysisOptions()
analysis_options.features = vision.ImageAnalysisFeature.TEXT
analysis_options.language = "en"

image_analyzer = vision.ImageAnalyzer(
    service_options, vision_source, analysis_options
)

result = image_analyzer.analyze()

In the result set, I see a bounding box, but it always starts in the top left, so I can't use that to detect orientation. I don't see any other way to get orientation. I've seen this question, but that just points out that I should be able to see orientation, but not set it. However, when I try the sample, I don't see orientation.
The documentation from MS (here and here) indicates that I should be able to get this information via a detectOrientation property, which I've tried setting as analysis_options.detectOrientation = "true", but that doesn't change the response. I'm clearly missing something.
How can I get the orientation of the text like it seems I should be able to?
Answer: Based on the documentation,  It looks like there might be a confusion in the usage of the Azure Vision API. The detectOrientation property is not part of the ImageAnalysisOptions in the azure.ai.vision.
You get the orientation, you can check OCR result,
https://<Endpoint_Name>.cognitiveservices.azure.com/vision/v3.1/ocr?detectOrientation=True

With above request, I able to get orientation and angle.

You can also check document intelligence's layout model that also gives angle output.


Python datascience library vs SQL

Question: I am working on a project where there is a necessity to store considerable data. I was wondering what is the difference between using SQL and the datascience library in python. I intend to use SQL from its python based libraries too or use a csv file to store info if I am going to use "datascience". I am leaning very much towards "datascience" as I find the following advantages:

It is subjectively very easy to use for me. I make much less mistakes.
With my limited knowledge in runtime, I think the datascience library will be more efficient.
Most importantly, it has many inbuilt functions that could allow me to make easier functions.

However, since so many people are using SQL, I was wondering if I am missing something major, particularly in scalability.
Some people online said that SQL allows us to store files on a database, but I do not see how that makes a difference. I can simply store the file in a folder on a system and save the link in the "datascience" table.
Comment: However, learning SQL is important. For example, if you want to deal with Big Data then you can use other tools like Hive to perform operations using SQL-based language. Learning Hive becomes simpler if you already know SQL language. Instead of Python, you can use Pyspark as well. So I think you should use both SQL together with Python libraries for data science, e.g. Numpy, Pandas, Matplotlib, ScikitLearn, etc. Both are really important
Comment: What do you mean by "datascience library" in Python?
Comment: Well... SQL is particularly good at searching, filtering, reordering, grouping, ranking, etc. You can also index and get high performance. Well... all of this at the cost of actually learning SQL -- something that can take a few months at least.
Comment: For simple operations SQL is straightforward. However for data manipulation it's better to use Python libraries. As a simple example, try to transpose a table in SQL: https://stackoverflow.com/questions/15297809/sql-transpose-full-table. As you can see, it becomes unnecessarily complicated whereas using Pandas in Python becomes really simple: `df.T`.
Comment: @user322778 Tables don't transpose, they pivot. Transposing a matrix means reordering its axes. It is possible to encode a 2-d matrix & its axis info into a table so that pivoting the table transposes the matrix, but that should be done after straightforward relational manipulation. The choice of matrix vs table depends on the manipulations one is doing (which could include converting between types).
Comment: @philipxy Sorry about my wording. When I said "transpose a table" I meant transpose the data inside the table (or the matrix if you wish). Trying to do this using only SQL becomes really complicated but in Python it becomes really simple, it's just a single line: `df.T` where `df` is a Pandas dataframe. For fancy feature engineering you need something else than SQL. That's my point
Comment: Looks like we're on the same page. (Including your earlier comments.)
Comment: @user322778 "datascience" is a library that allows us to store data in a table object and perform operations on it.
Comment: @Kavi Vaidya Oh I see. Well, as you can see, "datascience" library is not a  standard tool among data scientists. Also, if you really have considerable data then I don't think it's a good idea to handle it using introductory libraries, it's a bit like trying to implement Gradient Boosting or Neural Networks using only VBA/Excel...
Answer: The "datascience library" is only intended to be a tool for teaching basic concepts in an academic entry level class. Unless you are taking such a class, you should ignore it and learn more standard tools.
If it helps you, you can learn Data Science using Pandas starting just from flat data files, such as CSV and JSON. You will absolutely need to learn to interface with SQL and NoSQL servers eventually. The advantages of a database over flat files are numerous and well described elsewhere.
It's up to you whether you want to learn Pandas first and SQL second, or SQL first. Many people in the real world would have learned SQL before Python/Pandas/Data Science, so you may want to go that route.
If you go ahead and study that datascience library, you will learn some concepts, but will then have to re-learn everything in there "for real." Maybe this is best for your learning style, maybe it isn't. We don't know you well enough. Do you want academic hand holding or do you want to do things the real way?
Good luck and enjoy your journey.

Python datascience library vs SQL


How can I simplify this difference quotient?

Question: (1) $r(t)=3t+\frac5t: \quad \frac{r(t+h)-r(t)}h =\ldots $
My (incorrect) work=

Distribute the 3 to (t+h) in the numerator:

3(t+h)+[5/(t+h)] = 3t+3h+[5/(t+h)]

Find a common denominator for each term in the numerator by multiplying the numerator and denominator by the denominator of the separate fraction:

I am then left with [(3t^2)+(3h^2)+(6th)+(5)]/(t+h) for the first part of the numerator.
For the second part of the numerator I found a common denominator in the same way, and was left with [(3t^2)+(5)] / t
With the whole numerator I, once again, found a common denominator.
My result: [(3t^3)+(6t^2)h+(3th^2)+5t-((3t^3)+5t+(3t^2)h+5h)] / [(t^2)+(th)]
After cancelling some terms, I am left with this expression:
[(3t^2)h+(3th^2)-5h] / [(t^2)+(th)]
From here I am unsure about which step to take. As the limit h approaches zero, the function would work since the denominator would not equal zero (if t~=0), but the question specifically asks for it to be as simplified as possible.
Comment: How would it mean anything differently, @Dr.SonnhardGraubner?  Parentheses are used well to disambiguate any other interpretation, no?
Comment: Is this $$r(t)=3t+\frac{5}{t}$$ and $$f(x)=3\sqrt{x}-2$$?
Comment: Yes you have right, i have worked to much today.
Answer: In the first we have
$$\frac{r(t+h)-r(t)}{h}=\frac{3(t+h)+\frac{5}{t+h}-3t-\frac{5}{t}}{h}$$
and the second is given by
$$\frac{f(x+h)-f(x)}{h}=\frac{3\sqrt{x+h}-2-(3\sqrt{x}-2)}{h}$$
Can you proceed?
($h\ne 0$)
simplifying the first term
$$\frac{3h(t+h)t+5t-5(t+h)}{(t+h)t}$$
Comment: Thanks for editing my post!
Answer: HINT
Just plug in according to the definition to obtain
$$\frac{r(t+h)-r(t)}h = \frac{3(t+h)+\frac{5}{t+h}-\left(3t+\frac5t\right)}{h}$$
$$\frac{f(x+h)-f(x)}h =\frac{3\sqrt{x+h}-2-\left(3\sqrt{x}-2\right)}{h} $$
and then simplify the expressions.
To give an example and guide to proceed let consider the simpler case $f(x)=\sqrt x$, then we have
$$\frac{f(x+h)-f(x)}h =\frac{\sqrt{x+h}-\sqrt x}{h} =\frac{\sqrt{x+h}-\sqrt x}{h}\cdot\frac{\sqrt{x+h}+\sqrt x}{\sqrt{x+h}+\sqrt x}=$$
$$=\frac{x+h-x}{h(\sqrt{x+h}+\sqrt x)}=\frac{h}{h(\sqrt{x+h}+\sqrt x)}=\frac{1}{\sqrt{x+h}+\sqrt x}$$
Comment: I think you have to much parantheses in your second equation,
Comment: Do what any normal, decent user typically does, @gimusi, upon first submitting, and realizing another user already submitted precisely what you just did, without typos.  *Delete your duplicate answer.*  What is the point of submitting a second duplicate answer, even if you did not know someone submitted the same answer prior to you?
Comment: Fixed the missing parenthesis
Comment: Did you really feel the need to replicate @Dr.SonnhardGraubner's answers?
Comment: @amWhy I was finishing when he published his answer!
Comment: Ok, and is the $3$ on the right place now?
Comment: @Dr.SonnhardGraubner Thanks a lot! Fixed
Comment: The reason I am having trouble is due to the simplification. I know to substitute in the numerator, but I have tried multiplying by the conjugates, factoring, etc., but WebWork tells me my answers are all incorrect.
Comment: @J98 Let show your work in the OP (not here in the comment but in your original question). I'll take a look to that to give further help and suggestion if I can.
Comment: @J98 I've added a guide for a simpler example in order to show how we need to proceed. Let try with your functions and show your work here.


Question about weighted logistic regression

Question: I'm helping a friend perform a logistic regression on field data pulled from several archeological sites. By chance the overwhelming majority of records in the analysis dataset were collected from a single site.
In order to prevent the characteristics of this one site "overwhelming" the other sites, is it appropriate to apply weights (by site) to the records, say weight=1/(stnd error)?
Comment: If you have different sites and more measurements for each site, I would use a multilevel model. http://en.wikipedia.org/wiki/Generalized_linear_mixed_model
Comment: Thanks @andrea - I'm planning on running a random intercepts model w/ proc glimmix in SAS. I just got hung up on the weighting issue.
Comment: no need to use any kind of weight, then.
Answer: I would not apply weights. Include a term for "site" in your logistic regression. It would not need to be a random effect, as Andrea suggests above. A fixed effect could be appropriate, depending on the number of sites and how they were chosen.
I think the algorithm "understands" that different numbers are involved and adjusts accordingly. Weighting takes place where the raw data are not involved but only a mean (or proportion) from each group is recorded. You then need to weight the means by group size.
However if the sites are fairly heterogeneous, and the bulk of your data comes from only one, it might be wiser to limit the analysis to that one site.
Comment: @Placidia is right: `site` needs not to be random, but I see why you (@RobertF) want to model it as such. But also consider the number of sites you sampled from. If they're too few, maybe using a random effect for `site` might not be a good idea.
Comment: Thank you @Placidia, this is helpful. I was considering a random effect for the site variable since in effect there are an indeterminate number of similar archaeological sites throughout Europe given the number of urban areas during this period (Roman Empire), of which only a handful have been excavated. Here I'm presuming those sites which have been excavated are a random sample from this larger population of sites.
Comment: PS (@RobertF): to be clear, when I say "`site` needs not to be random", I am thinking of conditional (fixed-effects) logistic regression
Comment: I'm sorry, I should have specified - there are 17 sites in my friend's sample, with # records per site ranging from 4 to 373 for 16 of those sites, plus a single site with 1,386 records. It's not a big sample, but perhaps large enough to warrant using a random effect?
Comment: Based on what you describe, I agree that "site" should be random.
Answer: I have been thinking about this some more and I am concerned that the parameter estimates of the model might be swamped by the larger site. I suggest that after fitting the model, you pay close attention to how the residuals look by site. If your model is basically fitting the big site and letting everything else slide, you should see patterns of residuals if you plot residuals against site.
If there is a problem, I was thinking that you could select random samples of items from the big site - sample size to be similar to the other sites - and fit a bunch of models that way. You could average parameter values over the sampled estimates.


Given a cubic and quadratic share a root, prove $(ac-b^{2})(bd-c^{2})\geq 0$

Question: Here is an interesting problem.  Perhaps someone would be so kind as to give me a shove in the right direction?.
If $ax^{3}+3bx^{2}+3cx+d$ and $ax^{2}+2bx+c$ share a common root, then prove that
$$(ac-b^{2})(bd-c^{2})\geq 0$$
I thought about equating coefficients somehow, but that got messy.
I used the quadratic formula on the given quadratic to find
$\displaystyle x=\frac{-b\pm\sqrt{b^{2}-ac}}{a}$ are two roots.
So, if the cubic shares on of these, then I should be able to sub this in for x in the cubic.
Upon doing so, I got:
$$\frac{2(ac-b^{2})\sqrt{b^{2}-4ac}}{a^{2}}-\frac{3bc}{a}+\frac{2b^{3}}{a^{2}}+d$$
This is where I got hung up.  This may not even by a good way to go about it.
I see a part of what is to be proven in the above expression, $ac-b^{2}$
Setting it to 0 does not help much.
I also thought about dividing them. If they share a root, then it should reduce to a quadratic in the numerator and a linear denominator. But, then what?.
Can anyone give a hint as to the best way to proceed?.
Comment: Heard about resultants?
Answer: We begin by using a single step of the Euclidean algorithm.  Let $f(x) = ax^3 + 3bx^2 + 3cx + d$ and $g(x) = ax^2 + 2bx + c$.  If $f$ and $g$ share a common root, then the polynomial
$$
h(x) \;=\; f(x) - xg(x) \;=\; bx^2 + 2cx + d
$$
must share that root as well. Now, the roots of $g(x)$ are real when $ac-b^2 \leq 0$, and complex when $ac-b^2 > 0$.  Similarly, the roots of $h(x)$ are real when $bd-c^2 \leq 0$, and complex when $bd-c^2 > 0$.  If these two polynomials share a common root, it follows that $ac-b^2$ and $bd-c^2$ are either both positive or both nonpositive, and therefore $(ac-b^2)(bd-c^2)\geq 0$.
Comment: Thanks very much.  Nice.  I played around with the discriminant because I noticed $ac-b^{2}$ was just the negative of $b^{2}-4ac$, but I failed to put it together. I certainly did not notice the f(x)-xg(x). I subtracted them, but did not multiply the quadratic by x.
Answer: Hint: Notice anything coincidental about the derivative of the cubic?
Suppose that $\phi$ is the common root.  Let $f(x)=ax^3+3bx^2+3cx+d$ and let $g(x)=ax^2+2bx+c$.  Notice that $f^'(x)=3g(x)$ so that $f'(\phi)=0$ as well.  Hence $\phi$ is a double root of $f$. Since $f$ is a cubic, and complex roots come in pairs, it follows that $\phi$ is real, and hence all the roots of these polynomials are real.
In particular this implies something a bit stronger, that both $c^2-bd\geq 0$ and $b^2-ac\geq 0$.  (To get $b^2-ac\geq 0$, look at the discriminant.  I leave showing that $c^2-bd\geq 0$ to you.  (I have a solution if you really want.))
Hope that helps,
Edit:  Why do we have $c^2-bd\geq 0$?
Here is the immediate brute force way, there is probably a nicer solution.  The cubic has $\phi$ as a root with multiplicity $2$, and a third root, call it $\gamma$.  Then since $c=a \frac{\phi^2 +\phi\gamma+\phi\gamma}{3}$, $b=-a\frac{\phi+\phi+\gamma}{3}$ and $d=-a\phi^2\gamma$ it follows that $c^2 - bd \geq 0$ is equivalent to $$\phi^2 \gamma \left(\frac{\phi+\phi+\gamma}{3}\right)\leq\left(\frac{\phi^2+\phi \gamma+ \phi\gamma}{3}\right)^2.$$  Dividing by $\phi^2$ and multiplying by $9$, we get $$3\gamma (2\phi + \gamma) \leq (\phi+2\gamma)^2,$$ which is then equivalent to $$0\leq\phi^2 -2\phi\gamma+\gamma^2.$$ This last line clearly holds since it is a square.
Comment: Wow, I just used what you wrote to try to derive c,b, and d, but I did not get that.  I neglected to include the leading 'a' on the LHS.  I need to brush up on some polynomial tricks. Thanks much. Fun problem. I learned something.
Comment: Yes, Eric.  I had equated coefficients and derived b,c, and d. It was in front of my nose all along. I also looked up Viete's formula, and I see what you mean. I know those for a quadratic, but not for the cubic. Thanks. I learn something every day. By equating coefficients, I got $c=\frac{a({\phi}^{2}+2{\phi}{\gamma})}{3}$ and so on.  I got the same with Viete. Thanks for that.
Comment: Thanks very much.  I suppose the $c^{2}-bd$ comes from the discriminant of $bx^{2}+2cx+d$ that JB mentioned.  I played around with the discriminants but failed to put it all together. Thanks much.
Comment: @Cody:  I added a solution explaining why $c^2-bd\geq 0$.  It is the brute force approach, and just follows from writing things in terms of the roots.
Comment: Wow, very nice Eric. Thanks. May I ask one more question?.  How did you know what b,c, and d were in terms of the roots you called phi and gamma?.  That's interesting. But how did you arrive at those?. Sorry if this is a stupid question.
Comment: @Cody: It is a good question.  So we have the root $\phi$ twice, and $\gamma$ once, so we _must_ have $$a(x-\phi)^2(x-\gamma)=ax^3+3bx^2+3xc+d.$$  From here you can just expand, I get what I wrote above.  But this isn't I did it, I wrote it down immediately by knowing Vieta's Relations for the roots of a polynomial.  They are useful, and intuitive:  http://www.artofproblemsolving.com/Wiki/index.php/Vieta%27s_Formulas
Comment: @Cody:  Since the inequality would have the $a$'s cancel no matter what I didn't pay too much attention.  On a second glance, it appears that the $a$'s should be in the numerators.


If $f_n\rightarrow0$ and $|f_n|\leq\frac{1}{x\log x}$, prove that $\int_2^\infty f_ndx\rightarrow0$

Question:
Let $g(x)=\frac{1}{x\log x}$ for $x>1$. For given measurable subsets
  of $[2,\infty]$ and non-negative sequence $c_n$, define
  $f_n(x):=c_n\chi_{A_n}(x)$.
  Prove or disprove that  if $f_n\rightarrow0$ and $|f_n|\leq g(x)$, then $\displaystyle\int_2^\infty f_nd\mu_L\rightarrow0$. Note that $g$ is not
  integrable.

After so many examples, I believe it to be TRUE. After some trying to prove my guess, I reduced the problem to the case when $A_n=[a_n,b_n]$ and $\displaystyle\beta:=\sup_n b_n<\infty$.
Now I just need to prove $$c_n\mu(A_n)=c_n(b_n-a_n)\xrightarrow{n\rightarrow\infty}0$$
I'm mixed up a little here.
Comment: Then $c_n\chi_{A_n} \le 1/(2\ln 2)\chi_{[2,\beta]}$ for all $n.$ So you have a dominating $L^1$ function.
Comment: Hint: The worst case is $f_n=g(a_n)\chi_{[a_n,\infty)}$ with $a_n\to\infty$. What happens then?
Comment: @Did: I guess you mean $[2,a_n]$.
Comment: @Did, in your example, $\{f_n\}$s are not dominated by $g$
Comment: But the hint of Did still holds, @FardadPouran, if the set is changed to $[2,a_n]$.
Comment: Ah Yes, Indeed:
$$c_n\chi_{[a_n,b_n]}(x)\leq g(b_n)\chi_{[2,b_n]}(x)=:h_n(x)$$
 But how can it help when $\beta=\sup_nb_n<\infty$ ? $\int h_n = \frac{b_n-2}{b_n\log b_n}$
Comment: @JohnMa Indeed, I typed this comment too quickly (and have been offline since then), thanks for the correction. Yes the idea is to look at the case $f_n=g(a_n)\chi_{[2,a_n]}$ carefully.
Comment: @zhw., Thaks; It worked. You would add it as an answer, too.
Answer: As said in comments, this is true.

Let $\beta_n=A_n$. Since $c_n\le \frac{1}{\beta_n\log \beta_n}$, it follows that $\int f_n \le 1/\log \beta_n$.
Thus, if the integrals $\int f_n$ fail to converge to zero, we can extract a subsequence with bounded $\beta_n$.
But as long as $\beta_n$ stays bounded, we have a uniformly bounded family of functions on a set of finite measure, so dominated convergence theorem applies.


What are the benefits and drawbacks of the Floyd Rose SpeedLoader tremolo system?

Question: I have seen some guitars that have a Floyd Rose SpeedLoader tremolo system.
The idea is that it uses special strings and a modified Floyd Rose tremolo. The strings have bullets at each end, rather than just at one end and are each of a specific length for their note.
Is this kind of thing worth the cut down in time it takes to replace strings?
What are the benefits and drawbacks of such a system?
Comment: For more info: http://en.wikipedia.org/wiki/Floyd_Rose_SpeedLoader
Answer: A friend of mine had a guitar like this, and it wasn't too bad.  One of the main bummers was that finding strings for the thing was pretty tricky.  If you have to have special strings for the guitar, you have a lot less selection of strings and the different tones that different brands can provide, which is kind of a bummer.  On the plus side though, the guitar was still very playable, you could down tune it just fine (with some limitations, but reasonable limitations none the less), and re-stringing can be done pretty painlessly.
In my personal opinion, I think these guitars are kind of a waste, and more of a commodity item than anything else.  If you really need to have a string replaced that fast, just have a second guitar on standby that's fully tuned and ready to go.
Answer: It's bizarre that Floyd Rose couldn't get this right.
I have a Steinberger G3T and it stays in tune amazingly well - not quite up to the level of my Ibanez or Jackson guitars, but still very good.
Benefits

being able to pop a new string on and by fully in tune within a couple of minutes, as opposed to trying to replace a string on a normal floating bridge, which can take a couple of days to settle down.
No need for snips or any tools when changing strings.
Colour-coded at each end, making restringing that much easier
(yes I have made that mistake before:-)

Drawbacks

need to get special strings. But they aren't much more expensive than normal ones, and very easy to get at most music shops.
Answer: I know this question is ancient, but I played as my main guitar for several years, a G&L Legacy modified with a Speedloader bridge and nut, and I loved it. To this day I am dismayed that Floyd Rose ditched the entire enterprise. You had great tuning stability without the need for Allen wrenches or the need to master the zen of tuning slightly below pitch before tightening the screws, then adjusting with fine tuners after: a total pain that I always hated. With the Speedloader, not only did you avoid that, you didn't even need normal tuning machines at all: just pop out the old string and pop in the new one, and only adjust the fine tuners. It was awesome!
I feel the downfall here was Floyd Rose's marketing: he wanted to sell guitars and not just the bridges, and he didn't license the bridge to anyone else... no famous players got behind it because they couldn't put it on their brand signature guitar... therefore string manufacturers didn't get behind it... it's really too bad because the concept was great and the execution was great too. I mean: it really worked and worked great! But it just got buried because people poo-pooed the special strings. Call me nuts, but special strings vs. Allen wrenches to change normal strings? I'll take the special strings any day of the week. I'm sure I'm not the only one: there would have been enough of a boutique market to continue the operation indefinitely, but Floyd Rose sold out.
Now that it's all history, I play non-locking trems. I still hate the Allen wrenches... but I'd go back to a Speedloader system in a heartbeat.
PS, the string-through Floyd-style trem sold at GuitarFetish.com, along with the Tone Vise locking nut is something I may check into... it looks close to the ease of the Speedloader.
Answer: I played once with this... I had an awful time trying to tune the guitar also if you palm mute to hard you will end with a unbalanced bridge... personal exp.
Comment: @Maika - Editing out that word was okay, but making comments like yours about something so minor is really not appropriate. If you have an issue with a particular swear word, then just edit it out, or if you think it is serious, flag for a moderator. Please don't exaggerate issues like this!


Why is the image of a smooth embedding $f: N \to M$ an embedded submanifold?

Question: I'm reading An Introduction to Manifolds (Tu) and got confused on p.123 Theorem 11.13. Let me briefly explain what was done before that.
The author defines an embedding between two manifolds $f: N\rightarrow M$ as an injective immersion (differential is injective everywhere) with the additional property that $f(N)$ as a subspace of $M$ is homeomorphic via $f$ to $N$. Then a canonical form theorem is proven, namely, that for any point $p \in N$, there are charts $(U,\phi = x^1, \ldots, x^n) \ni p$ and $(V,\psi = y^1, \ldots, y^m) \ni f(p)$, such that the transition map takes the following form:
$$\psi \circ f \circ \phi^{-1} : (r^1,\ldots,r^n) \mapsto (r^1,\ldots,r^n,0,\ldots,0).$$
(I guess it is implicitly assumed that $f(U) \subset V$).
Now in the process of proving that $f(N) \subset M$ is an embedded submanifold, he states that $f(U) \subset V$ is defined by the vanishing of the coordinates $y^{n+1},\ldots,y^m$. I can prove that
$$
f(U) \subset \{q \in V: y^{n+1}(q) = \cdots = y^m(q)\}
$$
but not the reverse inclusion. Can anyone explain why this should be true?
Answer: The reverse inclusion doesn't necessarily follow from the canonical form theorem you've stated, since $V$ can just happen to be too large (or, if you like, $U$ can be too small): given $U$ and $V$ as you have one can always replace $U$ by a much smaller neighborhood $U'$ of $0$, and still guarantee that $U'$ and $V$ have charts satisfying your theorem -- and also be sure that the inclusion $\supset$ can't hold.
The solution, of course, is just to prove a slightly better canonical form theorem, by reducing the possible size of $V$:
Theorem. For any $p \in N$, there exist charts $(U, \phi = x^1, \dots, x^n)$ and $(V, \psi = y^1, \dots, y^m)$ satisfying
$$
    \psi f \phi^{-1} : (r^1, \dots, r^n) \mapsto (r^1, \dots, r^n, 0, \dots, 0)
$$
and such that
$$
  f(U) = \lbrace q \in V : y^{n+1}(q) = \cdots = y^m(q) = 0 \rbrace.
$$
Proof. The proof is simple once you have your canonical form theorem; if $(U, \phi)$ and $(V', \psi)$ are the charts guaranteed by your theorem, then you can take
$$
   V = \psi^{-1} \Big( \psi(V') \cap (\phi(U) \times \mathbb{R}^{m-n}) \Big).
$$
Then $(U, \phi)$ and $(V, \psi|_V)$ satisfy the conditions of this new theorem.
Comment: Thank you so much! this does it (had to change U to \phi(U) in the last equation) but that was an obvious fix.
Comment: Your theorem can be generalized to arbitrary smooth maps of constant rank. The rank theorem says that if $F:M\to N$ is a smooth map of constant rank $r$ between manifolds, then for each $p\in M$ there are charts $(U,\varphi)$ for $M$ centered at $p$ and $(V,\psi)$ for $N$ centered at $F(p)$ such that $F(U)\subset V$ and in which $F$ has the coordinate representation of the form
$$
\hat{F}(x^1,\dots,x^r,x^{r+1},\dots,x^m)=(x^1,\dots,x^r,0,\dots,0).
$$
The result of this theorem can be strengthen to say that
Comment: $(U,\varphi)$ and $(V,\psi)$ can be chosen to additionally fulfill $\psi(F(U))=\psi(V)\cap(\mathbb{R}^r\times\{0\}^{n-r})$. The proof is given in John M. Lee _Introduction to Smooth Manifolds_, and even though Lee states the rank theorem without this strengthening, after close inspection one can see that the charts that Lee constructs in his proof do satisfy the strengthening. (This is due to the way in which Lee defines the coordinate neighborhood $V_0$.)


Performance penalty virtualising x86 from arm vs x86 from x86

Question: Im not entirely sure if this is the correct place for this question, but I would like to build a server to run some experiments on and im considering arm, most of my code can be compiled to run on arm but there will be some external dependencies which may have to run on x86 so Im trying to understand how this might look.
I understand there is a performance penalty running x86 applications from arm. Im not entirely clear how this is handled - for example, I assume that if a given application is not compiled for arm it will not run natively on an arm environment so what would be the procedure for calling such an application - e.g does the os recognise it as an executable and emulate the x86 calls in the background somehow (i guess maybe os dependent) or would you have to spin up a full virtualised x86 environment to run these x86 applications.
I have used a range of virtualisation technologies and im particularly interested in how this would affect a typical type 2 hypervisor (is there an additionl penalty going from x86 to x86 vs arm to x86 as well something like wine which is mapping windows calls anyway - is support even there for this at this time?
would appreciate a brief explanation of how this works and a link to any performance benchmarks for the described operations
Answer: Emulation is required to run x86 on ARM. How transparent and easy to use depends on your environment.
Windows 10 on ARM extends WOW64. The goal is an ARM device that Just Works with x86 apps. No server builds yet, though presumably such a thing is being tested internally in Azure.
Another user emulation example: QEMU on Linux with binfmt_misc to make it slightly more user friendly. No need to emulate hardware and run another kernel. However you do need to provide libraries of the other architecture like you would when cross compiling.
Emulate hardware and you can create whatever virtual machine you want. ARM VM on x86 using QEMU is one example. This is a different kernel on virtual hardware, but virtual machines are familiar these days.
Performance overhead, again it varies. Native binaries are of course the best, CPU instruction rewriting can be near native, emulating an entire computer is a bit slower.
Worst case, you acquire both ARM and x86 boxes for their respective workloads. Complicates operations a bit, but you gain hardware diversity.
Comment: After having attempted to emulate arm and aarch64 on x86_64, I will go with the hardware any day. The performance difference is night and day. I can't imagine that trying to emulate x86 on arm would be much better. Probably worse.


Using a constant tone to find the key center

Question: I have a song that I'm trying to figure out the key center. I'll explain the process and you can tell me if I"m on the right track.
I start by analyzing the song using software that finds the chords. (Studio One ) . I know that this is not an exact science even with modern software. It shows the main chords being F-G and D and seventh variations of those including major and minor G's. So that didnt help me since it doesnt seem to fit a progression I would expect from a New Orleans blues, slide song.
Next I play the song and hold down various keys and find the one that sounds like it could be the key center. This seemed to work the best as I can just let this tone play for as long as I want, through the main sections, chorus solos...
So the D sounds best by far, but I want to be sure I'm right and at this point and I'm not good enough to figure out the progression manually in a timely manner.
My question is, is playing the note like I do a acceptable way of finding the key center and how would the three main chords of D,F and G fit into a common progression ?
Thanks
Comment: For what purpose are you trying to find the key center? Who or what is supposed to do what, with the key center information?
Comment: @mike628 So are you trying to transcribe a song, to make a lead sheet for a band, and you'd like to write correct key signatures? Or you'd like to know what the key is, so you could better guess what the chords are? Why not ask how to find the key of a passage of music? It could be that the effective key center changes throughout the song. Does the song have a melody? How about transcribing the melody first? Can you play even parts of the melody by ear? If you are sure about the bass notes and the melody notes, then you're already quite far in getting it transcribed.
Comment: The "one single steady pitch for a long time" idea doesn't feel suitable for finding the key. Find bass notes, melody notes and see what scale they seem to fit. Make a guess and play a so-fa-mi-re-do line in your guessed key. Does the final "do" feel like you landed home and that could be the end of the song? If not, make a new guess and try again. Pause the song, can you play I - IV - V - I in the guessed key and the "I" feels like a "I" in the song? If not, guess again. Anyway, forget the "one long drone" idea and read up on learning to find the key.
Comment: It's better to home in on cadence points and find the chord there.
Comment: Have you ever found or suspected that the key center of the chorus is different from the key center of the verses?
Comment: piiperi...knowing the key center helps you in your overall knowledge of the song. It also along with other information, makes it easier to transcribe a piece.
Comment: @piiperi, I can answer most of those questions as yes, but I think you misunderstand the question or I explained it in too much detail. The reason I want to know is irrelevant. Here it is simplified : Can you find the key center of a passage by playing a drone over that section ?
Comment: I think there are much easier and more certain ways for finding the key center for a passage of music than playing a constant tone over an entire passage.
Comment: So, tell us what they are?
Comment: @Laurence I think there are already several questions and answers about that, and I don't feel inspired to re-write about that here to a person who seems to be relying on some piece of software for listing chords, instead of, say, finding bass notes and melody notes, and trying to play other notes on top of those to get a feel of possible scales or cadences or anything. He seems to have decided that this "software and constant drone sound" method must be the way to go, and answers must be about that exact method only. I addressed that method only. Boxing day football feels more interesting.
Comment: @piiperi I didn't say or imply I was using software to find the key center, just as an added tool to possibly help me decide if I was on the right path. I can transcribe melodies quite well, chords not so quickly. And as far as "decided" , actually just the opposite, hence the reason for even asking in the first place. I understand harmonic analysis is about listening and figuring it all out, but when you're new at all of this, everything that can confirm or deny your intuition helps the learning process.  Understanding?
Comment: Thanks @piiperi,  that's the constructive answer I was looking for.
Answer: When a chord appears in both major and minor forms, consider the possibility that it's IV.
But I have to say, if you need software assistance in finding the chords, you're probably not ready to do much harmonic analysis.  Work on detecting what the notes and chords ARE.  Hanging a key label on them isn't really that important, is it?
Answer: Using that constant tone is certaintly a valid way to determine the key, but I think there are better ways. For starters, using harmonic analysis software, as you have wisely noted, is dodgy at best, impossible at worst. Especially with blues and other non-diatonic progressions, software can't tell the context well enough to put good chord labels on them. But I think the best solution would be to develop a better musical ear so that you could tell "oh, this song is centered on this". It sounds like you're nearly there, so don't despair! And yes, eventually you do need some reference tone to identify "oh, the note the song centers on, that's an E♭ on my (musical instrument)" (I must sound like a broken record, but that isn't necessary if you have perfect pitch).


keepalived service is not down despite I turned it down

Question: For high availability I have two servers: 172.24.4.51 and 172.24.4.52 and virutal ip is 172.24.4.53. The master is 172.24.4.51 and backup is 172.24.4.52.
I'm on 172.24.4.51 and then I made systemctl stop keepalived but keepalived services is still alived on that server. I made kill -9 to keepalived's process but then these process are recreated again automatically. And I made systemctl staus keepalived and the status shows Loaded: loadeded, Active: inactive but it keeps alived. I made ip a and I see the virtual ip active.
I'm giving you keepalived configuration
What could it be happening?
<code>vrrp_script chk_haproxy {
   script "killall -0 haproxy"   # verify the pid existance
   interval 2                    # check every 2 seconds
   weight 2                      # add 2 points of prio if OK
}

vrrp_instance VI_1 {
   interface ens192              # interface to monitor
   state MASTER
   virtual_router_id 51          # Assign one ID for this route
   priority 101                   # 101 on master, 100 on backup
   unicast_src_ip 172.24.4.51
   unicast_peer {
       172.24.4.52
   }
   virtual_ipaddress {
       172.24.4.53                        # the virtual IP
   }
   track_script {
       chk_haproxy
   }

   notify_master /etc/keepalived/master.sh
}
</code>
Answer: Please check master.sh content, actually keepalived try to make primary node as master only if server is reachable and don't have any issue with keepalived config, I think in your case whenever you are trying to stop/kill may be restarted by config management tool/monit or from some other script.
Also please check the transition logs.


Como inserir hora junto com data no c# com sgbd Mysql -

Question: utilizo essa linha para salvar a data quando subo algum registro para meu bd
 sql = "INSERT INTO ativacao (codigo, nomepc, data) VALUES (@codigo, @nomepc, curDate())";

essa é só a primeira linha e funciona muito bem, consigo salvar certinho a data da inclusão daquele registro, mas gostaria de inserir juntamente o horário, la no meu banco de dados já mudei o campo para DATETIME, mas qual seria a função que salva o horário junto?
Answer: Como vc está escrevendo a query, a linguagem da sua aplicação é indiferente. Considerando que a sua coluna data esteja no formato correto vc pode utilizar as funções UTC_TIMESTAMP() ou NOW(), dependendo se quer usar o fuso-horario da sessão ou UTC. Recomendo usar sempre UTC.
Ex: INSERT INTO ativacao (codigo, nomepc, data) VALUES (@codigo, @nomepc, UTC_TIMESTAMP())
Para maiores detalhes dessas funções e outras alternativas, pode consultar a documentação do MySQL: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html