Construct a degree 3 monic polynomial with integer coefficients that has 3 irrational roots.

Question: The polynomial $x^3 - 3x + 1$ is monic, degree $3$, has integer coefficients and all its roots are irrational.  I found this polynomial using Mathematica to generate random polynomials and then selecting the ones that have $3$ real roots.  My code is not efficient and I am unable to generate any significant number of examples.
Is there a way to construct such a polynomial?  If we restrict the range of the integer coefficients $(-10,10)$ is there a way to count exactly how many such polynomials exist?
Answer: The discriminant of a monic, cubic polynomial
$$p(x) := x^3 + b x^2 + c x + d$$
is the invariant
$$\Delta := -4 b^3 d+b^2 c^2+18 bc d-4 c^3-27 d^2;$$
it has the useful property that $p$ has three distinct, real roots iff $\Delta > 0$. (If $p$ has a repeated real root, then $\Delta = 0$, but in this case the nonrepeated root is always rational.)
On the other hand, by the Rational Root Theorem, if a monic polynomial $x^n + \cdots + d$ has a rational root $r$, then $r$ is an integer that divides $d$. These facts together suggest a way of generating examples:

Pick a triple $(b, c, d)$ of integers.
Compute $\Delta$; if $\Delta \leq 0$, $p$ does not have three real roots, so start over and pick a new triple. Otherwise, $p$ has three real roots.
For each of the factors $s$ of $d$. Computing $p(\pm s)$. If any of these is values is zero, then $p$ has a rational root, so start over and pick a new triple. Otherwise, if none of these is zero, none of the roots of $p$ are rational, that is, $p$ satisfies the condition.

A quick Maple script shows that $2922$ ($31.2\%$) of the $21^3 = 9261$ monic, cubic polynomials with integer coefficients in $-10, \ldots, 10$ satisfy the condition, so the above procedure is efficient in the sense that in practice, one needn't try too many triples $(b, c, d)$ to produce examples.
Comment: -1 No. It does not have integer coefficients (in general).
Comment: Of course, I meant to specify that $a, b, c$ are integers, not reals, which I've now done.
Comment: Ok, but that misses most of them.
Comment: Yes, of course, there's no claim that these are exhaustive, and indeed, the example in the question cannot be written this way; OP simply asked for a method of generating examples.
Comment: @Travis.  OK Thanks.  I agree with your argument and your computation of 2922.  I also have the number of such cubics with coefficients in -n, ... , n as: 0, 6, 32, 104, 248, 484, 850, 1356, 2046, 2922   for n=1,..,10.
Comment: I am sorry.  I meant to say irrational instead of real.  I edited my question.
Comment: The roots are supposed to be irrational.
Comment: @RossMillikan OP has modified the question since I wrote my answer; I'm updating it now to address the edited version.
Comment: @almagest Cheers.
Comment: This sequence does not seem to appear in the OEIS; why not submit it there? http://oeis.org/
Answer: If $$ x^3+ax^2+bx+c$$
(with integers $a,b,c$) has a rational root, then it is in fact an integer root and is a (positive or negative) divisor of $c$ (rational root theorem).
In particular, if you let $c=\pm1$, you need only ensure that $\pm1$ are no roots, i.e., that $a+b+c+1\ne 0$ and $-1+a-b+c\ne 0$.
If $c$ is $\pm$ a prime there are only a few more conditions and if $c$ is composite, the situation is still not difficult to handle as long as we know the factorization of $c$.
However, in order to exclude non-real roots, we have to do one additional check: The cubic above will have a pair of conjugate complex roots iff its discriminant $$\Delta=a^2b^2-4b^3-4a^3c-27c^2+18abc$$ is negative.
Using these two tests it is not too hard to determine whether a given cubic has only real-irrational roots.
Comment: But he presumably wants (1) all roots real as well as (2) no roots rational.
Comment: @almagest:  2 is covered-the roots will be irrational.
Comment: @almagest  Yes.  I want a polynomial that has all 3 roots that are irrational.  No nonreal complex roots are allowed.
Comment: @GeoffreyCritzer Ah, ok. For me nonreal complex roots are also irrational (as they are not rational) ... - You'll need to use the discriminant as additional criterion then.
Comment: @HagenvonEitzen  yes.  I am sorry for the confusion with my question.  I should have stated it more precisely.  I define irrational to be a subset of the reals.


How do I get my flute to sound clean?

Question: I'm a beginning flute player. When I play, I often- but not always- have a "shh" sound along with it. I noticed that it usually starts out pretty quiet when I start practicing, but after I play for about an hour it gets totally out of control. And since I usually play for an hour or more in one setting, that is a major problem. I've tried changing my lip shape and tilting my flute back and forth, and I found there's a spot where it doesn't sound as bad as the other spots, but the shh sound almost never fully goes away. Anybody know how to help with this?
Comment: Thank you for your side question about the braces. I am getting braces soon too and also play the flute so I share the same concern. I started a separate question for that. I hope it helps you too, although you are probably more proficient in the flute than I: http://music.stackexchange.com/questions/51704/how-will-getting-braces-affect-embouchure
Comment: I've removed your second question about braces, as Melanie has asked it separately. It'll help keep this question focussed, and get you better answers.
Answer: As Tim Burnett - Bassist said, the problem may be that you're getting tired as you play (you mentioned being a beginner and playing for over an hour - that's rough!). Even advanced students and professionals start to sound pretty bad when they're exhausted and their emboucheres are relaxing. It's generally a sign you should stop.
Definitely the best advice you can have is practice! I remember that infuriating hissing sound - sometimes it seemed like it was more hiss than note - and wondering why I couldn't have a nice pretty tone like my teacher's. Tone studies (where you hold each note in turn until you can get it to a nice, full, round tone) definitely helped me; you can talk to your teacher about what tone study would work best for you. :)
Answer: I know people say keep practising, but that's half of your problem! As a beginner, it's difficult to keep that perfect embouchure for an hour, and really, at your stage, it's becoming non-productive - as you found out.
Keep the practice sessions shorter - perhaps 20  to 30 mins at a time. Leave a good hour in between, to give your mouth muscles time to recover. You need that time, and the results will improve because of it. or go even more, and play for 15 mins, but 4 times a day. Note this is not necessarily a permanent situation, as, when your embouchure gets stronger - as in it can be maintained for longer - so your playing sessions can and will lengthen.
Comment: Are there any special exercises for strengthening the embouchure or something like that?
Comment: Like a lot of things in life, just doing what you do - practising - is a good method. It's doing exactly what the embouchure needs, provided you're doing it right. And when it sounds good, you are!
Answer: Check out this thread on fluteland.com. Notably, it's mentioned that this is a 'by-individual-musician' issue...
Also, this nice gentleman is beautifully demonstrating body position, fingering, etc. on a wooden flute with no hiss:

Your ultimate answer here, as you may find in other places on this SE, is: practice, practice, practice. As play becomes second nature, and your instrument becomes an extension of your body, this problem will likely solve itself. Keep it up!
Comment: You mentioned noticing that the hiss gets worse over time during practice... Are you beginning to tire at those times? Slouching or loosening your grip?
Answer: Time and hours on the instrument will strengthen your embouchure and the problem will disappear. Your embouchure muscles just need to become more hardened, which takes time.
Answer: Adding onto other answers regarding embouchure, when playing for extended periods of time, a high amount of moisture from the air you blow into the flute develops inside the opening and pools into droplets inside the head of the instrument. Try swabbing out the instrument with a flag or with a cloth and stick (the kind where you thread the cloth into the stick to be able to push/pull/turn). You might notice some decrease in hiss after that.
Answer: Have proper posture and make sure you play the correct note.
Comment: @guidot Or it's a misspelling of *posture*.
Comment: There's a [**be nice**](https://meta.stackexchange.com/questions/240839/the-new-new-be-nice-policy-code-of-conduct-updated-with-your-feedback) policy for all Stack Exchange sites, including this one, and ending an answer with "duh" does not comply with that policy.
Comment: @ToddWilcox: Not sure, if not simply the syllable to tongue is meant, but the answer is too short to judge. Anyway, *pasture* seems to mean *embouchure*, so a language barrier may make things worse....
Comment: Welcome. Not a good start, but perhaps you could clear up the ambiguity between *posture* and *pasture*. That should narrow the field, so to speak... Playing the correct note is rather too obvious.

How do I get my flute to sound clean?


Don't let NGINX reset established connection if upstream down

Question: I'm trying to perform a graceful restart of my smtp backends in order to accept all of incoming emails: I close the listening socket on the backend side while keeping opened connections alive.
I hoped that NGINX would let the existing connections to finish, but pass all of the new ones to the second available backend. But what I see in the logs of postfix sending emails to NGINX is that NGINX resets all of the established connections ones it notices backend closed listening on its address.
Is my guess correct and if it is how can I make NGINX behave like I wanted it to behave: pass all new connections to another backend, but don't interrupt already established ones?
Here is my NGINX stream configuration.
upstream smtp {
    server 127.0.0.1:1025 fail_timeout=0;
    server 127.0.0.1:1026 fail_timeout=0;

    server 127.0.0.1:1025 backup;
}

server {
    listen       25 reuseport;
    proxy_pass   smtp;
}

Answer: What about the NGINX "down" marker?
You will need to modify your NGINX conf twice each time you want to restart one of your SMTP backend but at least you have zero downtime!
So before restarting one backend, mark its upstream server as "down" like this:
upstream smtp {
    server 127.0.0.1:1025 down;
    server 127.0.0.1:1026;
}

server {
    listen       25 reuseport;
    proxy_pass   smtp;
}

Then you need to reload the NGINX config file with service ngnix reload or nginx -s reload
At this point NGINX should not send any new connection on the port 1025 and also don't drop any existing connection either. So now you cant restart your backend.
After that, you can remove the "down" marker and reload the NGINX config again.
PS: I never try this method but I'm very curious to know if it works


Comparing estimators in Cauchy distribution

Question: Given $n$ observations with a Cauchy distribution (location=t,scale=1), I would like to compare estimators such as the mean and median by simulating sample means and mean square errors. This is an exercise given by my book.
The exercise says I may assume t=0. Why is this?
I thought I would try $n=10$ first so I typed in x=rcauchy(10,location=0,scale=1) and then median(x). Is this the right way to go about it?
Also, what is the code for mean square error and coverage probabilities?
Note: Advised to come here from Stack Overflow.
Comment: I see you have added the `self-study` tag. Thank you for doing so. However, please read the [`self-study`tag wiki info](http://stats.stackexchange.com/tags/self-study/info) carefully. You'll see that you should not expect to get code; if you comply with the suggested format there, you may get something along the line of 'hints and pseudocode'. But that suggested format would include you showing your attempts at and explaining your difficulty with doing the mean square and coverage first.
Comment: See also http://stats.stackexchange.com/questions/90531/comparing-estimators-of-location-of-the-cauchy-distribution/139767#139767
Answer: Yes, this is the right approach.  Let's see where it can go.
Getting Off to a Fast Start
You can usually sneak up on to a full-blown simulation by working from the inside out.  The R command
x <- rcauchy(10, location=0, scale=1)

generates a sample of $10$ and stores it in the variable x.  The next step is to compute the statistics of interest.  This is why you stored the original output in a variable: so you could use it multiple times without having to regenerate it.
mean(x)
median(x)
sd(x)

etc, etc.
You can go back to the first calculation (of x), repeat it, and recompute its mean and standard deviation (or any other statistic).  That's fun and instructive up to a point.  For a simulation, though, you will want to repeat these procedures hundreds (or more) times.  This is the point at which you want to encapsulate your work into reliable, reusable, flexible components.
Creating the Simulation
R (and many modern computing platforms) work best by generating all the simulated data at once.  Let's respect this preference by writing a modular piece of code--a function--to handle both the sample generation and the simulation iterations (which in older languages would require a double loop).  Its inputs evidently will include, at a minimum,

n, the sample size
N, the simulation size (number of samples).  Let's default this to $1$ for testing purposes.
..., any other parameters to be passed to rcauchy.

Here we go:
sim <- function(n=10, N=1, ...) {
  x <- matrix(rcauchy(n*N, ...), nrow=n)             # Each sample is in a separate column
  stats <- apply(x, 2, function(y) c(mean(y), sd(y)))# Compute sample statistics
  rownames(stats) <- c("Mean", "SD")
  return(stats)
}

The reason for giving names to the rows of the output is to help us read it, as in this simulation with three iterations.  First the command appears, then its output.

sim(N=3, location=0, scale=1)

          [,1]      [,2]       [,3]
Mean -2.837735  6.471259 0.04831808
SD    4.445549 17.837725 7.00943078

It has been arranged to put all the means in the first row and standard deviations in the second.
With this in hand, let's run a reproducible simulation by setting the random number seed, generating some statistics for independent random samples, and inspecting them.  Let's draw histograms rather than using summary statistics to describe the two rows of output (means and sds).
set.seed(17)
x <- sim(n=10, N=500, location=0, scale=1)
hist(x["Mean", ])
hist(x["SD", ])

(To keep myself honest, I try hard to use the same seed every time for any published results so that people will know I didn't play around with the seed in order to tweak the results to make them look more like I expected!  For private exploration I do change the seeds, or leave them unset, so that I see new results each time.)

Using, Re-using, and Extending the Simulation Code
Now you can play.
These histograms look awful.  Is it because there weren't enough simulations?  Rerun the last four lines of code but change $N$ to $5000$, say.  It doesn't help.  Change location and scale.  Still confused?  Maybe we should fall back to a more familiar situation.  How about generating Normally distributed samples?  To do this, let's just extend our workhorse function sim and let the distribution itself also be a parameter!
sim <- function(n=10, N=1, f=rcauchy, ...) {
  # `f` is any function to generate random variables.  Its first argument must
  # be the number of values to output.
  x <- matrix(f(n*N, ...), nrow=n)                    # Samples are in columns
  stats <- apply(x, 2, function(y) c(mean(y), sd(y))) # Compute sample statistics
  rownames(stats) <- c("Mean", "SD")
  return(stats)
}

The only changes made were to include f=rcauchy in the argument list and to replace the one reference to rcauchy by f.  Let's try this with a Normal distribution:
set.seed(17)
x <- sim(n=10, N=5000, f=rnorm, mean=0, sd=1)
par(mfrow=c(1,2)) # Shows two plots side-by-side
hist(x["Mean", ], main="Normal Means")
hist(x["SD", ], main="Normal SDs")

This seems to be working.  Now you can vary the distribution, the sample size, the simulation size, and the distribution parameters just by editing the x <- sim(...) line and rerunning it.  In a minute or two you should obtain a good sense of how a change of distribution parameters changes the simulation results.  With a little more exploration (consider plotting the sequences of means and SDs) you should be able to see why the Cauchy sample distributions seem so messed up.
For studying the Cauchy distribution (and other long-tailed distributions), a good modification to make to sim would be to include sample medians in its output.
Follow-on Analyses
Finally, what about "mean squared errors" (MSE)?  These typically are used to compare an estimator to what it is estimating.  I recommend storing (in a variable) the value of anything that will be referred to more than once.  Thus, for instance, you can study the mean squared error of the mean like this:
location <- 0
x <- sim(n=10, N=5000, f=rcauchy, location=location, scale=1)
mean((x["Mean", ] - location)^2)                              # Mean squared error

Consider stashing the calculation of the MSE within a function if you're going to compute it a lot.
Other assessments of simulation output--plots, descriptive statistics, etc--are just as easily computed because the entire array of relevant simulation output is still available as stored in x.

Going Further: Sources and Principles
For more examples of working simulations in R, search our site for [R] Simulation.  Many of these will port nicely to other general-purpose computing platforms like Python, Matlab, and Mathematica.  A bit more work might be necessary to port them to specialized statistical platforms like Stata or SAS, but the same principles apply:

Develop the simulation code from the inside out (which is the opposite of good software development practice in general!).
Encapsulate useful blocks of code, such as the simulation code, code to compute the MSE, even code to plot or summarize simulation output.
Respect preferences and idiosyncrasies of the computing environment for best performance (but do not let them dominate your attention: you're doing this to learn about statistics, not about R or Python or whatever).
Extend the functionality of the encapsulated code instead of creating and modifying copies of the original code in order to handle minor variations in what you're doing.
Make the extensions one small step at a time rather than trying to write a do-everything function at the outset.
Use good naming and commenting conventions to document anything that is not immediately clear in the code.
Visualize the output.
Play with your simulations to learn from them.  To this end, make them as easy as possible to use and reasonably fast to run.


Front class not included in body tag in my custom module

Question: We are trying to make a Drupal mini bootstrap for our language selection module.
We implemented hook_boot(), in this function, we included path.inc and common.inc from core.
The language selector always redirects to the frontpage of the according language.
Now the problem is that, when loading the new page, the class of  is not-front. This means that front-specific styles, and template are not used; it just uses the default ones.
We are guessing that we missed something in the Drupal bootstrap process.
Do you have any idea?
Answer: If memory serves me correct the "front" class will only be set on the body, if the URL you are on matches what is set in the "Site Information" > Front Page field.
My guess is that you'll need to override the string or array of body classes in the template.php file of your theme. To do this you'd want to use the template_preprocess_html function provided by Drupal core.
Here is a quick and dirty example of how to add the class to the body of your theme:
function THEMENAME_preprocess_html(&$variables) {

  if (theme_get_setting('my_variable') == 0) {
    $variables['classes_array'][] = 'front';
  }

}

From there you'd need to figure out what classifies the home page as the home page with some conditionals or custom functions.
Comment: thanks for the fast answer! we tried it out, now it uses the right front-template but the body tag still has the "not-front" class. where does drupal decide about what has to be in there?
Answer: The function that set those CSS classes is template_preprocess_html(), which uses the following code.
  // Add a class that tells us whether we're on the front page or not.
  $variables['classes_array'][] = $variables['is_front'] ? 'front' : 'not-front';
  // Add a class that tells us whether the page is viewed by an authenticated user or not.
  $variables['classes_array'][] = $variables['logged_in'] ? 'logged-in' : 'not-logged-in';

$variables['is_front'] is set by _template_preprocess_default_variables(), which is called by template_preprocess(), and contains the following code.
  // drupal_is_front_page() might throw an exception.
  try {
    $variables['is_front'] = drupal_is_front_page();
  }
  catch (Exception $e) {
    // If the database is not yet available, set default values for these
    // variables.
    $variables['is_front'] = FALSE;
    $variables['db_is_active'] = FALSE;
  }

$variables['classes_array'] is then imploded in template_process(), which uses the following code.
  // Flatten out classes.
  $variables['classes'] = implode(' ', $variables['classes_array']);

I tried the following text code, in my test site.
function code_testing_preprocess_html(&$variables) {
  $variables['classes_array'][] = 'front';
}

For a page that is not the front page, I got the following output.

Your code should remove "not-front" as CSS class, before adding "front"; this could done in hook_process(), by altering $variables['classes'], or in hook_preprocess_html(), by altering $variables['classes_array'].


Python Function App connections using managed identity

Question: Unable to set up connection information for service bus with Python Azure functions for managed identity.
I have the following settings in function.json
{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "msg",
      "type": "serviceBusTrigger",
      "direction": "in",
      "queueName": "myinputqueue",
      "connection": "MySvcConn"
    }
  ]
}

and in Application settings in Azure portal i have set
"MySvcConn__fullyQualifiedNamespace":"mysvcns.servicebus.windows.net"

I get the message
"Microsoft.Azure.ServiceBus: Value for the connection string
parameter name 'mysvcns.servicebus.windows.net' was not found. (Parameter 'connectionString').

Version of Runtime used ~4
host.json configuration
{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[2.*, 3.0.0)"
  }
}

Comment: could you check the install bundle: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus?tabs=in-process%2Cextensionv5%2Cextensionv3&pivots=programming-language-python#install-bundle ?
Comment: The azure portal deploys a older version of extension "version": "[2.*, 3.0.0)" where as the recommended version is "[3.3.0, 4.0.0)". How to update extensions
Comment: You should be able to edit the host.json locally then redeploy.
Answer:
To connect to service bus using a managed Identity we have first add servicebus data receiver role to the access control.

Then add the connection setting to application setting under the name
ServiceBusConnection__fullyQualifiedNamespace and add the connection value as <Name_of_servicebus>.servicebus.windows.net.

The above setting will connect the function app to the service bus using managed identity without the use of connection string.

Refer this documentation
Comment: @user2603610 - please refrain from posting lots of follow-up detail here in comments. Edit your question instead. Also, please be sure to include properly-formatted text, not images of text.
Comment: based on the answer i modified the function.json. Removed connection from this file. Now i get this error Microsoft.Azure.WebJobs.ServiceBus: Microsoft Azure WebJobs SDK
ServiceBus connection string 'AzureWebJobsServiceBus' is missing or empty. My app setting have a "ServiceBusConnection__fullyQualifiedNamespace" and the value set to 'mysvcns.servicebus.windows.net"
Comment: try using ServiceBusConnection:fullyQualifiedNamespace  instead of  ServiceBusConnection__fullyQualifiedNamespace
Comment: application settings does not allow ":" in the name field. Only allowed chars are alphabets, number and "_"
Comment: I just  added the ServiceBusConnection:fullyQualifiedNamespace in a function app  https://i.imgur.com/hDx9Kiz.png
Comment: me not able to https://imgur.com/fzPr22A
Comment: i get it , you are using c# functions, i am using python runtime for functions. You are able to add due that. Python runtime does not allow
Answer: Was able to figure this out, need to set up application settings in function app for the following
ServiceBusConnection__clientID:<managedidenity client id>
ServiceBusConnection__credential:managedidentity
ServiceBusConnection__fullyQualifiedNamespace:<servicebusname>.servicebus.windows.net

"ServiceBusConnection" in the above settings being the connection name in function.json file.


Alterar texto com Javascript

Question: Olá,
Alguem poderia me ajudar com um script JS para alterar o texto do botão instantaneamente ?
Mas alterar somente quando o status da variavel $x mudar de 0 para 1, ou então quando clicar sobre o botão que contém o texto.
Comment: Falta colocar o código
Answer: O rótulo do botão pode ser alterado ao clicar, dessa forma:
<button class="meu-botao">Clique aqui</button>

Alterar o rótulo do botão quando uma variável muda de valor, pode ser feito com Proxy, mas é importante que essa variável faça parte de um objeto
<button class="meu-botao">Clique aqui</button>

Alterar texto com Javascript


Integration by parts appears to prove the existence of integrals that have discontinuity.

Question: Consider the following integral:
$$\int \lfloor x \rfloor dx$$
I know the integral reduces to:
$$x \lfloor x \rfloor - \frac {\lfloor x \rfloor ^2}2 - \frac {\lfloor x \rfloor}2$$
However, if we use integration by parts:
$$\int \lfloor x \rfloor dx = x\lfloor x \rfloor - \int x (\lfloor x \rfloor)' dx$$
Using simple algebra:
$$\int x (\lfloor x \rfloor)' dx = \frac {\lfloor x \rfloor ^2}2 + \frac {\lfloor x \rfloor}2$$
Yet, this is a contradiction. The indefinite integral is always continuous, yet the final expression is a piecewise constant function with infinite jump discontinuities. Does integration by parts only work for continuous functions or something? This is incredibly confusing.
Comment: It is the correct approach for any useful definition of an integral...
Comment: i haven't said it is the only one approach. Btw. splitting the integration domain is  essential to every integration theory...
Comment: Check your notes. There are some conditions on the integrands...
Comment: Depending on the context, absolute continuity of $f,g$ is the usual condition for $\int f' g = fg - \int f g'$ almost everywhere.
Comment: the usual approach for piecewise function is to integrate it on the subintervals and sum up.
Comment: Like to proof that the indefinite integral is absolutely continuous? The base for integral by parts... or how do you define Riemann integral?
Answer: The problem with your argument is, as stated in the comments, the continuity of $u$ and $v$ are necessary conditions for applying the integration by parts. Take a look at this article:

The theorem can be derived as follows. Suppose $u(x)$ and $v(x)$ are two continuously differentiable functions...

As a side-note, according to the fact that:
$$\int_a^b f(x)\delta(x-x_0)dx=\begin{cases}f(x_0)&a<x_0<b\\0&\text{otherwise}\end{cases}$$
and knowing:
$$d(\lfloor x \rfloor)=(\lfloor x \rfloor)'dx=\delta(x-\lfloor x \rfloor)dx$$
where $\delta$ is the Dirac delta function, one can write:
$$\int x d\lfloor x \rfloor=\int x\delta(x-\lfloor x \rfloor)dx$$
Therefore
$$\int_a^b x\delta(x-\lfloor x \rfloor)dx=\sum_{a<\lfloor x\rfloor<b}\lfloor x \rfloor$$
Comment: @TheGreatDuck Well, that was unexpected `:)`


a flute question - low B status

Question: This question is for flute users and experts, including flutists, flute sellers, flute repairers, flute teachers, and others who know the current state and keying system of the transverse flute in general.
About fifty years ago I wrote a classical piece for flute and piano (as equal partners, not for solo and accompaniment).  It was in the 'key' of E Phrygian.  The initial note for the flute part was the low B, the note immediately below middle C, and this note occurred several more times in the work.  The person I wrote the piece for had the 'B-extension,' as it was known at the time, on their instrument, and could hit the pitch clearly and confidently every time, provided the dynamic level was mp or lower.
After the premiere, I was urged by several people, including the person I wrote it for, to seek publication.  I did not, primarily because orchestration books I owned advised avoiding that low B as not available on most flutes.  If I was to submit it for publication, I felt I would have to transpose the whole thing into F-Phrygian, with five flats, and I found the prospect more than daunting.  (This was long before notation software with built-in transpose function.)
Lately the piece has been running through my head again, and I dug out the old score and realized that with some revision and a tweak here and there, it wouldn't be bad.  Which leads to my question.
What is the status of the low B on today's flutes?  Do most well-made instruments come with that note available?  Do flutists in general feel confident about playing that pitch?  Do publishers routinely print music that includes that pitch?  (I still would rather not transpose it.)
Answer: Most professional flutists nowadays have a flute with a B-foot, and have no trouble playing low B- although not fortissimo, so it shouldn't really be a problem.
Answer: Whatever book said that the low B is not available on "most flutes" is not written well.  It's not available on some beginner/intermediate level instruments, but it's going to be present on every single professional quality flute without exception.  It's not a commonly used note because it's hard to project that low, but any advanced level flutist should be able to play it without significant difficulty.
Comment: They were old books even then and probably obsolete by now, which is why I asked the question here.
Answer: As others have said, low B is available on most professional level flutes and even on Intermediate/Step-up flutes. Where I deviate from the previous answers is the level of projection to low B. I play a Haynes and projecting low B is no more a problem than any other low or second register note on the concert flute, i.e. B3 through C5 and even C#5.
Just my experience.

a flute question - low B status


Resultado de busca abrir em nova aba

Question: Tenho um motor de busca simples que faz a busca no próprio html, como posso fazer para que os resultados da busca sejam mostrados em uma nova aba?

<input type="text" placeholder="Digite sua pergunta"  autofocus name="query" size="16" style="font-size: 11 pt; color: #000000; font-family: Verdana; font-variant: small-; border: 1 solid #000000">

<input  type="submit" value="Buscar" style="font-size: 8 pt; color: #000000; font-family: Verdana; font-variant: small-caps; border: 1 solid #000000">

Site de busca
http://leituracrista.com/indice/
Comment: Miguel só um detalhe, a tag `` foi descuntinuada, vc deve fazer agora os estilos direto pelo CSS, https://www.w3schools.com/tags/tag_font.asp além disso a tag de  fechamento ` ` está no lugar errado, deveria vir após ``
Comment: Obrigado! @hugocsl
Answer: você pode adicionar um atributo no  chamado "target",
ficaria assim:
<form action="" method="GET" target="_blank">
...
</form>

mais informações no link > https://www.w3schools.com/tags/att_form_target.asp
att,
Answer: Não sei se te ajuda mas vc pode fazer assim:
Vc tem que bolar um jeito de pegar o que está digitado dentro do input name="query" e colocar no final do link query=
<input onclick="myFunction()" type="submit" value="Buscar" style="">

Sei que não é a reposta "completa" mas as vezes te ajuda. Com jQuery acredito que vc captura facilmente o valor do input de busca e coloca onde quiser. Mas não é muito minha área então não vou me estender.
Comment: Acredito que esse é o caminho, deste modo é possível por exemplo adicionar apenas o botão de busca em qualquer site, aguardo mais informações de outros
Comment: Preciso agora capturar o esse valor da query e jogar no final do endereço
Comment: Isso mesmo Miguel, acredito que não é algo complicado para que já domina JS, mas como não é meu caso só te dei um norte. Outros colaboradores do site com certeza vão te responder até melhor que eu.

Resultado de busca abrir em nova aba


How I can calculate the fractional part of this number

Question: Let us consider this real number:
$$z=\frac{(-\sqrt3+2)^{2^{p-2}}+(\sqrt3+2)^{2^{p-2}}}{2^{p}-1}$$
My question is: How I can calculate the fractional part of this number for big natural number $p$. I remark that $0<(-\sqrt3+2)^{2^{p-2}}<1$ for all $p$.
Answer: $$x_{1}=2-\sqrt{3},x_{1}=2+\sqrt{3}\\x^2-sx+p=0\\x^2-(2-\sqrt{3}+2+\sqrt{3})x+(2-\sqrt{3})(2+\sqrt{3})=0\\x^2-4x+1=0\\a_{n+2}-4a_{n+1}+a_{n}=0$$may be help you
Comment: @ darya khosrotash: How this can help for this situation.
Comment: I am thinking ...
Comment: Can binomial theorem solve $2^p-1$?
Comment: @user45195: I do not know.
Comment: Also, if ${(-\sqrt3+2)^2}^{p-2}$ in the numerator is between 0 and 1, can't it be considered negligible, with extremely large p and therefore, even larger denominator?
Comment: @user45195: Yes, and what happen next.
Comment: By the way, I meant the rules for factorizing $a^n+b^n$ and $a^n-b^n$. I accidentally wrote binomial theorem.
Comment: as in identity 7 and 11 of this site: http://www.mathwords.com/f/factoring_rules.htm
Comment: Using identity 7, we get $2^p-1=2^{p-1}+2^{p-2}+2^{p-3}+\cdots+2^2+2$
Comment: @daryakhosrotash: How I can relate my question to your answer?


toggle show/hide div with button? load state hidden

Question: I am using Jquery to toggle hide/show a div with:
HTML:

    Test text

<button>Click</button>

Jquery:
$("button").click(function() {
    $("#newpost").toggle();
});

(the above is working perfectly)
from: http://jsfiddle.net/andrewwhitaker/KpFRb/
How can I change the state on page load to be hidden?
Answer:

    Test text

try this by adding this css to the div
Answer: Add css or style to mark it display:none
See the working fiddle
Answer: use style="display:none"
or hidden="true"


Visualizing directed edges without crossing

Question: I am given a directed graph with set of nodes with fixed positions (Map of cities) and want to add connections to them, so that I have as few crossings as possible. For simplicity, let's consider only one source (compare to the attached image). For an undirected graph, straight lines would work perfectly fine. Now, for the directed version, I tried using quadratic bezier curves with a control point at x_1, y_2, which eliminates a lot, but not all crossings. I feel like there must be a general formula for a curve that can be applied without crossings, right?
Example for current approach
Answer: Alright, extending my research I found a paper offering a solution that may work for me using circle arcs based on the circle packing theorem instead of bezier curves. (Article, Circle Packing algorithm)


Sign in through Steam with Java

Question: I want to use STEAM-LOGIN in my JSF2 web application. I found this in Steam Web API documentation:
"Steam can act as an OpenID provider. This allows your application to authenticate a user's SteamID without requiring them to enter their Steam username or password on your site (which would be a violation of the API Terms of Use.) Just download an OpenID library for your language and platform of choice and use http://steamcommunity.com/openid as the provider. The returned Claimed ID will contain the user's 64-bit SteamID. The Claimed ID format is: http://steamcommunity.com/openid/id/"
Here are my questions:

There are several OpenID libraries for Java, which one should I use?
I have no idea how to implement redirection to Steam login page and back to my page

I found some examples for PHP but nothing for Java.
Comment: [This might answer the question](http://stackoverflow.com/a/18680478/4808244)
Answer: You can use pac4j. It has openid connect support.
They also have several implementations that they offer here.
You can see here an example of pac4j's j2e implementation.

Sign in through Steam with Java


Given $\min \{a^Tx\mid x^TQx+2b^Tx+c\leq0\}$ and $Q\succ0$ find conditions for $Q,b,c$

Question: Given $\min \{a^Tx\mid x^TQx+2b^Tx+c\leq0\}$ and $Q_{n\times n}\succ0,b\in\mathbb{R}^n,c\in\mathbb{R},a\in\mathbb{R}^n\backslash\{0\}$

find conditions for $Q,b,c$ for which the problem is feasible
find conditions for $Q,b,c$ for which KKT conditions are suffices
find conditions for $Q,b,c$ for which KKT conditions are necessary

I thought maybe to look at   $2b^Tx+c\leq0$ because $Q$ is positive but couldn't get more conditions from this inequality
Answer: Let's check feasibility, the problem is infeasible only if,
$$\
g(x) = x^TQx + 2b^Tx + c>0 \ \forall x
$$
You can easily check $g(x) = x^TQx + 2b^Tx +c$ is convex. Let $x^*$ be the minima. For the problem to be feasible we need $g(x^*) \leq 0$.
$$\
\nabla g(x^*)=2Qx +2b=0 \implies x^*=-Q^{-1}b
$$
Setting $g(x^*)\leq0$, we get,
$$\
c-b^TQ^{-1}b \leq 0
$$
Hence, we have this upper-bound on $c$ for the problem to be feasible. Note that we have assumed $Q$ to be a symmetric matrix. In case if its not, you can always replace $Q$ by $\frac{1}{2}(Q^T+Q)$. This won't change anything.
Since, both the objective and constraints are convex. KKT conditions suffice. But are they necessary? Can you figure it out?
Hint1: Are there points which violates the regularity conditions?
Hint2: Do we need $g(x^*) < 0$ for KKT?
Comment: You said that g>0 for every x but the global minima is less than 0
Comment: In the first line it says problem is infeasible only if $g(x)>0$ then onward we check when is the problem feasible.
Comment: Oh didn't see, thanks
Comment: I agree it was bit misleading. Fixed it in the edit.
Comment: I'm not sure for the third part,The iregularity is only when the gradient of g is zero. and for hint 2 you mean that slater condition exist and then the KKT is necessary
Comment: Yes. You are correct. I was referring to slater condition. Gradient of $g$ zero, won't actually be a problem in this case.
Answer: Hint
Define $P={Q+Q^T\over 2}$. Then $P=P^T\succ 0$ and $$x^TPx=x^TQx$$also since $P=P^T$, Cholesky decomposition can be defined for it as $$P=LL^T$$where $L\succ 0$ is lower-triangular. By substitution we obtain $$x^TQx+2b^Tx+c=x^TLL^Tx+2b^T\underbrace{(L^T)^{-1}L^T}_{I}x+c$$which by defining $y=L^Tx$ and $b_1=L^{-1}b$, reduces to $$x^TQx+2b^Tx+c=y^Ty+2b_1^Ty+c=||y+b_1||^2+c-b_1^Tb_1$$
where $$b_1^Tb_1=b^T(L^T)^{-1}L^Tb=b^T(LL^T)^{-1}b=b^TQ^{-1}b$$Finally, your optimization problem is equivalent to this one:
$$
{\min a^T(L^T)^{-1}y
\\
\text{s.t.}
\\
||y+b_1||^2<b^TQ^{-1}b-c
}
$$
Remark
KKT conditions are sufficient only if the problem is convex.


Implementing CNN with TensorFlow on Anaconda

Question: The code cannot run properly
I am a beginner of deep learning and python, this is my code of a convolutional neural network. I cannot understand the error at all and it doesn't look like any thing wrong with syntax.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 20 17:23:07 2017

@author: gengyoung
"""

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
sess = tf.InteractiveSession()
def weights(shape):
    return tf.Variable(tf.truncated_normal(shape,stddev=0.1))
def biases(shape):
    return tf.Variable(tf.constant(0.1,shape=shape))
def conv2d(X,W):
    return tf.nn.conv2d(X,W,[1,1,1,1],padding='SAME')
def max_pool_2x2(X):
    return tf.nn.max_pool(X,[1,2,2,1],[1,1,1,1],padding='SAME')
X = tf.placeholder(dtype=tf.float32,shape=[None,784])
y = tf.placeholder(dtype=tf.float32,shape=[None,10])
keep_prob = tf.placeholder(tf.float32)
X_train = tf.reshape(X,[-1,28,28,1])
w1 = weights([5,5,1,32])
b1 =biases([32])
conv1 = tf.nn.relu(conv2d(X_train,w1)+b1)
pool1 = max_pool_2x2(conv1)
w2 = weights([5,5,32,64])
b2 = biases([64])
conv2 = tf.nn.relu(conv2d(pool1,w2)+b2)
pool2 = max_pool_2x2(conv2)
f_w1 = weights([7*7*64,1024])
f_b1 = biases([1024])
f_w2 = weights([1024,10])
f_b2 = biases([10])
flatten_pool2 = tf.reshape(pool2,[-1,7*7*64])
h1 = tf.nn.relu(tf.matmul(flatten_pool2,f_w1)+f_b1)
h1_drop = tf.nn.dropout(h1,keep_prob)
predict_y = tf.nn.softmax(tf.matmul(h1_drop,f_w2)+f_b2)

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y*tf.log(predict_y),reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(0.0001).minimize(cross_entropy)
corrct_prediction = tf.equal(tf.argmax(predict_y,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(corrct_prediction,tf.float32))
tf.global_variables_initializer().run()
for i in range(2000):
    batch = mnist.train.next_batch(50)
    if i%100 == 0:
        train_accuracy = accuracy.eval(feed_dict={X:batch[0],y:batch[1],keep_prob:1.0})
        print("step:%04d accuracy:%.9f"%(i,train_accuracy))
    train_step.run(feed_dict={X:batch[0],y:batch[1],keep_prob:0.5})
print("Test accuracy: %.9f"%accuracy.eval(feed_dict={X:mnist.test.images,y:mnist.test.labels,
                                           keep_prob:1.0}))

Next the err information:
Python 3.6.0 |Anaconda custom (x86_64)| (default, Dec 23 2016, 13:19:00)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> runfile('/Users/gengyoung/CNN.py', wdir='/Users/gengyoung')
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
Traceback (most recent call last):
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1022, in _do_call
    return fn(*args)
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1004, in _run_fn
    status, run_metadata)
  File "/anaconda/lib/python3.6/contextlib.py", line 89, in __exit__
    next(self.gen)
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [800] vs. [50]
     [[Node: Equal = Equal[T=DT_INT64, _device="/job:localhost/replica:0/task:0/cpu:0"](ArgMax, ArgMax_1)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)
  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "/Users/gengyoung/CNN.py", line 50, in <module>
    train_accuracy = accuracy.eval(feed_dict={X:batch[0],y:batch[1],keep_prob:1.0})
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 567, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3729, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 767, in run
    run_metadata_ptr)
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 965, in _run
    feed_dict_string, options, run_metadata)
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1015, in _do_run
    target_list, options, run_metadata)
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1035, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [800] vs. [50]
     [[Node: Equal = Equal[T=DT_INT64, _device="/job:localhost/replica:0/task:0/cpu:0"](ArgMax, ArgMax_1)]]

Caused by op 'Equal', defined at:
  File "<stdin>", line 1, in <module>
  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)
  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "/Users/gengyoung/CNN.py", line 44, in <module>
    corrct_prediction = tf.equal(tf.argmax(predict_y,1),tf.argmax(y,1))
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/gen_math_ops.py", line 721, in equal
    result = _op_def_lib.apply_op("Equal", x=x, y=y, name=name)
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 763, in apply_op
    op_def=op_def)
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 2327, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1226, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Incompatible shapes: [800] vs. [50]
     [[Node: Equal = Equal[T=DT_INT64, _device="/job:localhost/replica:0/task:0/cpu:0"](ArgMax, ArgMax_1)]]

Comment: Welcome to SO, you might need to take the [tour](https://stackoverflow.com/tour), read [how to ask](http://stackoverflow.com/help/how-to-ask) and provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). If you elaborate more, people will be more willing to help you (for now we are missing too much information).
Comment: Additionally - don't post your code as photographs. Copy and paste it into your post.
Comment: @asongtoruin Thanks a lot! Can you help me? I cannot figure what's wrong with the code. This is really frustrating for a beginner.
Answer: The strides of the sliding windows of your max pooling function returned you a different shape tensor that multiplied down to the predictions gives you the error. Change it to
def max_pool_2x2(X):
        return tf.nn.max_pool(X,[1,2,2,1],[1,2,2,1],padding='SAME')

to be consistent with your code.
I also suggest you to check some explanation and implementation about convolutions and max pooling like this to understand how to change it for your code.
Comment: Thank you! I made this mistake before and made it again. But I think that this has been engraved on my heart!


How to backup Peewee database (SqliteQueueDatabase) programatically?

Question: I'm using Peewee in one of my projecs. Specifically, I'm using SqliteQueueDatabase and I need to create a backup (i.e. another *.db file) without stopping my application. I saw that there are two methods that could work for me (backup and backup_to_file) but they're methods from CSqliteExtDatabase, and SqliteQueueDatabase is subclass of SqliteExtDatabase. I've found solutions to manually create a dump of the file, but I need a *.db file (not a *.csv file, for example). Couldn't find any similar question or relevant answer.
Thanks!
Comment: Can't you just copy the file?
Answer: You can just import the backup_to_file() helper from playhouse._sqlite_ext and pass it your connection and a filename:
db = SqliteQueueDatabase('...')

from playhouse._sqlite_ext import backup_to_file
conn = db.connection()  # get the underlying pysqlite conn
backup_to_file(conn, 'dest.db')

Also, if you're using pysqlite3, then there are also backup methods available on the connection itself.
Comment: @coleifer what if I can't use cython? In fact, why is this method only available in CSqliteExtDatabase?
Comment: Great, that worked perfectly for me. Couldn't find that much in the docs about `backup_to_file`, except what I already cited. Anyways, thanks for the answer. Also, I really admire the great work you do supporting your own library, I've found your answers everywhere and it's really inspiring to see. Thanks again!


Intuition behind multinomial logistic regression

Question: I need some clarification in my understanding of what's going on under the hood of multinomial logistic regression (MLR).
I have a nominal (not ordinal!) dependent variable, $Y$, that takes values $A$, $B$ and $C$ and single quantitative predictor, $X$, so I run MLR with $A$ set as reference level of $Y$. I get intercepts and regression coefficients for $B$ and $C$, say $b_{0B}$, $b_{1B}$, $b_{0C}$, $b_{1C}$.
All the sources I consulted (like this one) say that these are coefficients of following equations:
\begin{align}
\log\left( \frac{P(Y=B)}{P(Y=A)}\right) = b_{0B}+b_{1B}X  \\[10pt]
\log\left( \frac{P(Y=C)}{P(Y=A)}\right) = b_{0C}+b_{1C}X
\end{align}
They (the sources) say also that these estimates come from following procedure:

Code $Y$ with dummies, say $Y_B$ that is $1$ if $Y=B$ and $0$ otherwise and  $Y_C$ that is $1$ if $Y=C$ and $0$ otherwise.
Find estimates for two "ordinary" logistic regressions (one for $Y_B$ and one for $Y_C$) at once.

My question is:  since $Y_B$ is $1$ if $Y=B$ and $0$, shouldn't we interpret $b_{0B}$ and $b_{1B}$ as coefficients of
$$ \log\left( \frac{P(Y_B=1)}{P(Y_B=0)}\right) = \log\left( \frac{P(Y=B)}{P(Y=A | Y=C)}\right) = b_{0B}+b_{1B}X \qquad ?$$
Second question (less important): Is the following procedure wrong? Why, what are its drawbacks?

Create 3 variables: $Y_A$ that is $1$ if $Y=A$ and $0$ otherwise, $Y_B$ that is $1$ if $Y=B$ and $0$ otherwise and  $Y_C$ that is $1$ if $Y=C$ and $0$ otherwise
Estimate three ordinary logistic regressions

I know that one of these three dummies is redundant, but thanks to it I could see how $X$ affects log odds of each possible value of $Y$ against any others (log odds of choosing $A$ against any other choice, log odds of choosing $B$ against any other choice, log odds of choosing $C$ against any other choice).
Comment: 1. The first two displays are fit by *excluding* observations from the other categor(y/ies). So the first display can be fit with a logistic model on a subset of the data so that $Y \ne C$, the second on the subset with $Y \ne B$.

2. Your second approach does not account for the constraint that the predicted category probabilities must sum to 1 for every value of $X$ (unless the model is saturated).
Comment: Thank you. Can you tell why can't we use all the observations and get my imterpretation with $P(Y=A) | P(Y=C)$ in denominator?
Comment: For $P(Y=A)/P(Y=C)$ to be an *odds ratio*, the denominator event has to be the converse of the numerator. That means the event $Y \ne A$ is the same as $Y = C$. This is only true when $Y \in A \cup C$.
Comment: I was asking about $P(Y=A or Y=C)$ in denominator not about  $P(Y=A)  / P(Y=C)$ :) Sorry for typo
Comment: Okay, so suppose you fit two models: P(Y=B)/P(Y= A or C). *then* P(Y=A)/P(Y=C). You can use this to predict P(Y= A or B or C (forgive my sloppy notation. *However*, if you did say P(Y=A)/(P(Y=B or C) *then* P(Y=B)/P(Y=C) this will not give you the same predictions. You have introduced the model's dependence on the parametrization which is undesirable when equivalent inference could be obtained otherwise.
Comment: Why not fit two models: P(Y=B)/P(Y= A or C) and P(Y=A)/(P(Y=B or C) and use them for predictions?
Comment: I don't think a CV chat is going to appease your curiosity. Why not set up some simulations to convince yourself what works and what doesn't?
Answer: I think your confusion is about censoring. One way to understand multinomial logit is by looking at it as competing risks. If you did the binomial regressions as $Y=B$ vs. $Y\ne B$, then you would allow $Y=C$ in the latter box.
In competing risks thinking you have a base category $A$, and two competing risks $B$ and $C$. If you go $B$ then you can't be $C$, thus you sensor out $C$ when estimating the binomial logit on $B$ from base $A$.
Comment: I'm not sure if it answers my questions (it certainly does not answer the second one). I gave my interpretation and asked if it is correct. You gave me another one... Why it is better than mine?
Comment: Your interpretation will not lead to an identifiable model


Command to Create fresh Aws Instance?

Question: How can we create new aws instance ubuntu using cli ? We are facing the problem as we dont have Ami ID for this ?
1.I have all the details like key pair, security group etc
Can anyone help me to get the command.
Answer: You can find the ami id base on the Ubuntu version, architecture, instance type and AWS region in the Ubuntu EC2 AMI locator.
In any case you will need the ami-id.  You can search for an image in the create instance wisard (copy the ami-id when you have found the image you want) or use the describe-images command from the cli.

Command to Create fresh Aws Instance?


Conditioning on two normal variables $E[x|y=y_0,x\leq k]$ and obtaining an analytical expression

Question: suppose $x=a+e$ and $y=b+e$, where $e$ is normally distributed with mean 0 and variance $\sigma^2_e$. $a$ and $b$ are independent and normally distributed, both with mean $\mu$ and variance $\sigma^2$. $a$ and $b$ are also independent of $e$.
Given this,
$$E[x|y=y_0,x\leq z]=E[E[x|y_0]|y=y_0,x\leq z]$$
And since
$$E[x|y_0]=\mu +\frac{\sigma^2_e}{\sigma^2+\sigma^2_e}[y_0-\mu]$$
$$E[x|y=y_0,x\leq z]=E[\mu +\frac{\sigma^2_e}{\sigma^2+\sigma^2_e}[y_0-\mu]|x\leq z]$$
Where am I going wrong here? My original intuition was that the above would imply
$E[x|y=y_0,x\leq z]=\mu -\mu \frac{\sigma^2_e}{\sigma^2+\sigma^2_e}+\frac{\sigma^2_e}{\sigma^2+\sigma^2_e}E[y_0|x\leq z]$ but sice $y_0$ is realized, and not random, it wouldnt make any sense to write it this way.
Comment: Your approach is not good, the problem is more complex than it seems to be. I write a solution by using the conditional expectation below.
Answer: Hint:
First, we prove the vector $(x,y)$ follows a bivariate normal distribution. It suffices to notice that
$$
\begin{pmatrix}
           x \\
           y \\
\end{pmatrix}  =
\begin{pmatrix}
           1 &0&1 \\
           0&1&1 \\
\end{pmatrix} \cdot
\begin{pmatrix}
           a \\
           b \\
e\\
\end{pmatrix} =:V\cdot\begin{pmatrix}
           a \\
           b \\
e\\
\end{pmatrix}
$$
with
$$
\begin{pmatrix}
           a \\
           b \\
e\\
\end{pmatrix}  \stackrel{\mathcal{D}}{=} \mathcal{N}_3\left(\begin{pmatrix}
           \mu \\
           \mu \\
\mu_e\\
\end{pmatrix};\begin{pmatrix}
           \sigma^2&0&0 \\
           0&\sigma^2&0 \\
0&0&\sigma^2_e\\ \end{pmatrix} \right)=:\mathcal{N}_3(\Gamma;\Sigma)
$$
We deduce that
$$\color{red}{\begin{pmatrix}
           x \\
           y \\
\end{pmatrix} \stackrel{\mathcal{D}}{=} \mathcal{N}_2 \left(V\Gamma; V\Sigma V'  \right)} \tag{1} $$
Second, from $(1)$ and this result, we deduce that the conditional distribution  $x|\{y = y_0\}$ follows a normal distribution. I let you determine the parameters with the result. The density function and probability function of $x|\{y = y_0\}$  are denoted by $f_{x|\{y = y_0\}}(t)$ and $F_{x|\{y = y_0\}}(t)$.
Third, from the property of conditional expectation
$$\begin{align}
\mathbb{E}(x|\{y = y_0\} \cap \{x \le z  \}] &= \frac{\mathbb{E}(x\cdot \mathbf{1}_{ \{x \le z  \}}|\{y = y_0\} ]}{\mathbb{P}(x \le z|\{y = y_0\} ]} \\
&= \color{red}{\frac{\int_{-\infty}^z t\cdot f_{x|\{y = y_0\}}(t)dt}{F_{x|\{y = y_0\}}(z)}} \tag{2}
\end{align}$$
You can compute $(2)$ analytically with some easy transformations.


What exactly is the nginx request_uri?

Question: I'm trying to understand the $request_uri variable in nginx configuration. The documentation says

full original request URI (with arguments)

To me that seems to be totally unambiguous - it should be the entire requested URI, including the host and protocol. But in actual usage, it seems to only include the path & query arguments. Is there any authoritative source that says exactly what nginx considers to be a request_uri? I can't find any further references in the documentation, and I tried to get it out of the source code, but there are no comments and it's hard to understand the overall structure.
Answer: The Request-URI does not refer to the RFC 3986 URI, but is a term from RFC 2616, 5.1.2 HTTP/1.1 draft standard from 1999.
The Request-URI in RFC 2616 could have been any of:

Request-URI    = "*" | absoluteURI | abs_path | authority

Here, the absoluteURI is equivalent with the RFC 3986 URI, and mainly used in HTTP proxys. Søren Løvborg explains in an answer on Stack Overflow why it is not necessary to have the full URI in this context:

In normal HTTP requests, the URL scheme and host have already been handled by the time the request is sent (and the URL fragment does not exist at the HTTP protocol level at all), meaning the Request-URI is a path-absolute-URL string, possibly followed by ? and a URL-query string.

Request-URI seems to be replaced with the (more unambiguous) term Request Target in RFC 7230, 3.1.1 proposed standard from 2014, where a Request Line...

begins with a method token, followed by a single space (SP), the request-target, another single space (SP), the protocol version, and ends with CRLF.
request-line   = method SP request-target SP HTTP-version CRLF

The Request Target term is also used in the RFC 9110, 7.1 of the Internet Standard (June 2022); URI References are defined in RFC 9110, 4.1.
Comment: Thanks for the references! Is it safe to assume that "Request-URI" always refers to the path, args, etc. or is it genuinely ambiguous? As for the justification, that does make sense.

What exactly is the nginx request_uri?


vTune, how do I pass input parameters

Question: I have developed a simple piece of C code, and launch it by
<code>cat input.txt | ./code
</code>
(so code read input.txt as a stdin)
Question is: how do I simulate that within vTune?
In the vTune Launch Application page, if I fill in the Application parameters field with input.txt, vTune runs for ever for 'Collecting basic hotspot data'.
thanks, mario
Answer: You should create a shell script running this command. Specify the path to script in the "Application" field.

vTune, how do I pass input parameters


Error bound of the Euler method

Question: I am self studying working through the book "A First Course in the Numerical Analysis of Differential Equations" and have come to a deadend on q 1.2.
The linear system $y' = Ay, y(0) = y_0$, where $A$ is a symmetric matrix, is solved by the Euler method.
Let  $e_n = y_n - y(nh)$
Where $y_n$ denotes the Euler approximation and $y(nh)$ the exact solution ($h$ is Euler step size).
Prove that $ ||e_n ||_2 = ||y_0||_2 max|(1+h\lambda)^n - e^{nh\lambda}|$
Where $\lambda \in \sigma(A)$ where $\sigma(A)$ is the set of eigenvalues of A.
I have tried various approaches such as writing $e_n$ as the error bound of the Euler method and taking the norm, but I can't seem to get $||y_0||_2$ in my answers.
Comment: Did you ever figure out this problem?
Answer: Given that A is symmetric it can be diagonalised. Therefore we can write down the solution of the system of ODEs directly, and simply subtract the discreteized solution front the exact.

Error bound of the Euler method


Test keeps failing for product landing page

Question: I am currently doing Free code camp and working on the product landing page. I keep getting an error that my internal link is not working properly. The code can be found at: Codepen link

Product information

Where to find

Pricing

This is where product info can be found

<video  id="video" width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

This is where product can be found

Enter your e-mail to get a quote.

<form action="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js" id="form">
<input   name="email"
    id="email"
    type="email"
    placeholder="Enter your email address"
    required/>
<input id="submit" type="submit" value="Get Started" class="btn"/>
</form>

The error is shown in the following screenshot.
Free code camp error.
Answer: All your  anchor tags nesting the
 elements should have an id that corresponds with the nav-bar anchor links but all your anchor tags have the name attribute instead. Replace all the name attributes with id attributes and your 5th test should pass.
Example:
This:

This is where product info can be found

Should be:

This is where product info can be found

And this:

This is where product can be found

Should be:

This is where product can be found

Comment: Thank you so much. I was racking my brain on this. Hopefully I will get the hang of this eventually.
Comment: @Idallenbach Glad I could help. And you're doing great so far. Keep at it!
Comment: @Idallenbach Also, do mark this as the correct answer by clicking the grey tick-mark on the side of the question if it helped you solve your problem :)


Sort list using other list with different length

Question: I am attempting to resort a list based on the order in which they are listed in a dataframe, despite the dataframe column being of a greater length.
    enrolNo   Surname
0         1  Jones
1         2  Smith
2         3  Henderson
3         4  Kilm
4         5  Henry
5         6  Joseph

late = ['Kilm', 'Henry', 'Smith']

Desired output:
sorted_late = ['Smith', 'Kilm', 'Henry']

My initial attempt was to add a new column to the existing dataframe and then extract it as a list, but this seems like a very long way around. Furthermore I discovered that my attempt was not going to work due the the different lengths as stated by the error message after trying this to start with:
df_register['late_arrivals'] = np.where((df_register['Surname'] == late),
                        late , '')

Should I be using a 'for' loop instead?
Answer: Why not using the .isin() function?
df['Surename'].isin(late)

then you should get the desired output.
Answer: Pluck out the matching values from dataframe itself. No need to sort the list itself:
sorted_late = df[df.Surname.isin(late)].Surname.to_list()

If it were a list you can be clever with that too:
sorted_late = [master_late for master_late in master_list if master_late in late]

Comment: That worked like a dream. On another note, if the dataframe was a list instead, called 'master_list' for example how would that look?
Comment: Could be many possible ways via list comprehensions. One way along these lines would be: `sorted_late = [master_late for master_late in master_list  if any([late_elem==master_late for late_elem in late])]`
Comment: Consider accepting answer if it solved your problem
Comment: Sorry for leaving this unresponded to for so long. Thank you once again
Answer: you can specify a custom key for the sort function
import pandas

df = pandas.DataFrame([
    {"enrolNo": 1, "Surname": "Jones"},
    {"enrolNo": 2, "Surname": "Smith"},
    {"enrolNo": 3, "Surname": "Henderson"},
    {"enrolNo": 4, "Surname": "Kilm"},
    {"enrolNo": 5, "Surname": "Henry"},
    {"enrolNo": 6, "Surname": "Joseph"},
])

# set Surname as index so we can access enrolNo by it
df = df.set_index('Surname')

# now you can access enrolNo by Surname
assert df.loc['Kilm']['enrolNo'] == 4

# define the list to be sorted
late = ['Kilm', 'Henry', 'Smith']

# Sort late by enrolNo as listed in the dataframe
late_sorted = sorted(late, key=lambda n: df.loc[n]['enrolNo'])
# ['Smith', 'Kilm', 'Henry']


What is a TCP stream in a Nginx connection?

Question: I'm working with Nginx and I'm searching what is a TCP stream. I haven't found relevant definition on the web, so please maybe someone has any answer to provide us ?
Comment: https://stackoverflow.com/questions/17446491/tcp-stream-vs-udp-message might be relevant.  TCP "streams" are just streams of TCP data - this isn't really an NGINX-specific question, and NGINX doesn't really have anything to do with a "tcp stream" other than being a piece of software that can interact with TCP data.
Comment: It depends on the context, but most likely in this case "TCP stream" is being used as a synonym for ["TCP connection"](https://stackoverflow.com/questions/8156254/tcp-vs-udp-what-is-a-tcp-connection).
Answer: Normally Nginx handles http or https connections. It now has tcp stream support. This means it can handle generic tcp protocols like DNS or smtp, etc. There are extra config parameters that need to be setup to enable this
https://nginx.org/en/docs/stream/ngx_stream_core_module.html
also, concerning the TCP's support in NGINX, source here: https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/


CRON expression : make last hour non exclusive at minute 0

Question: so I have a task I need to schedule, it needs to be ran every 10 minutes, from monday to friday between 10am and 8pm.
So far, I'm using this expression :
0 */10 10-19 * * mon-fri

Note : this is a Spring expression, but I believe the classic cron expression would be the same without the first 0 for the seconds.
Is that Correct ?
The issue with this expression is that it runs correctly except for the 8pm, the last occurrence is 19:50 and not 20:00.
How could I fix this and make it run one more time ?
Also I Believe it does, but to make sure, it will also run at 10:00 ?
Comment: It's not possible to achieve the desired result with 1 cron. for the final 20:00 run you'r going to need a seperate cron line. `0 0 20 * * mon-fri`. And to confirm yes your given cron wil run at 10:00, basicly it says run when day is between mon-fri, hour is between 10-19 and minutes can be divided by 10. See https://stackoverflow.com/questions/41743720/crontab-run-every-15-minutes-between-certain-hours for a simulair issue
Comment: Oh, so it's not possible in one expression :(, thanks for your input.
Answer: So like Ralan commented, it is apaprently not possible to do this in one cron expression.
The simplest solution is to add another expression matching the missing hour at minute 0.
Answer: In a classic cron job, the right expression for such job would be as follow:
0,10,20,30,40,50 10-20 * * 1-5

where:
0,10,20,30,40,50: At minute 0, 10, 20, 30, 40, and 50
10-20: hours
* : day of month (1-31)
* : month
1-5: monday to friday
Comment: This will also run at 20:10, 20:20, etc.


Python multiprocessing: AttributeError: Can't pickle local object

Question: I wrote a ChatOps bot for the collaboration tool Mattermost using this framework. Now I'm trying to write and run integration tests and I used their examples. By cloning the git repository you can run the tests by yourself. Their docker-compose.yml file will only work on a Linux machine. If you want to reproduce it on a Mac machine, you'll have to edit the docker-compose.yml to:
version: "3.7"

services:
  app:
    container_name: "mattermost-bot-test"
    build: .
    command: ./mm/docker-entry.sh
    ports:
      - "8065:8065"
    extra_hosts:
      - "dockerhost:127.0.0.1"

After running the command docker-compose up -d Mattermost is available at localhost:8065. I only took one simple test from their project and copied it in base-test.py. You can see my source code here. After starting the test by running the command pytest --capture=no --log-cli-level=DEBUG . it will return the following error: AttributeError: Can't pickle local object 'start_bot.<locals>.run_bot'. This error also shows up on the same test case in their project. The error happens at line 92 in the utils.py file
What am I doing wrong here?
Comment: Without understanding anything about your problem, I would suggest looking at `multiprocessing_on_dill` https://pypi.org/project/multiprocessing_on_dill/
Comment: What's not understandable at my problem? @DAdams You can reproduce the case very simple that's documented on their GitHub repository: https://github.com/attzonko/mmpy_bot/tree/main/tests/integration_tests
Comment: Sorry!  My comment was not a criticism of your question, which appears to be well written. I meant to say - I don't have the knowledge or experience to tackle the true cause of your issue. I did however run into generic multiprocessing pickle problems myself, and found `multiprocessing_on_dill` to almost always work for me.
Comment: Alright I'll look into it tomorrow. Hopefully someone else have more experience to tackle the cause of this issue :)
Answer: I don't know if you already went down this road but I think you might get past the pickling error by making run_bot take the bot that it does bot.run() with as an argument and then pass it to the process.
Comment: Don't quite understand what you meant. I've tried multiple things like passing `bot` as an argument but no success :(
Answer: Take a look at the Action tab on that GitHub repository. Pytest seems to execute correctly (ignoring the exceptions on the webhook test)
Here is a recent run you can use to compare your environment set-up: https://github.com/attzonko/mmpy_bot/runs/4289644769?check_suite_focus=true
Comment: I have exact the same environment: Python 3.8.2 and Pytest 6.2.5. Also I'm running a different command stated in the question above and it returns the `pickle error`. When I try to use the command you're using: `pytest . -vv -n auto` it returns: `unrecognized arguments: -n auto`. Do you maybe know why? Also I posted this question six days ago and the tests runned 7 days ago, maybe that explains why it is now failing at my local machine?
Comment: Here is a run from 1hr ago: https://github.com/attzonko/mmpy_bot/runs/4356753006?check_suite_focus=true


Finding the change point in data from a piecewise linear function

Question: Greetings,
I'm performing research that will help determine the size of observed space and the time elapsed since the big bang. Hopefully you can help!
I have data conforming to a piecewise linear function on which I want to perform two linear regressions. There is a point at which the slope and intercept change, and I need to (write a program to) find this point.
Thoughts?
Comment: see cross posted question: http://stats.stackexchange.com/questions/5700/finding-the-change-point-in-data-from-a-piecewise-linear-function
Comment: See : https://fr.scribd.com/document/380941024/Regression-par-morceaux-Piecewise-Regression-pdf
Answer: A simple answer would be to consider the break point a variable, call it x.  Collect the points below x and perform a linear fit, returning the error (say sum of squared errors over the points).  Collect the points above x and do the same.  Then you can define f(x) as the total error over the two fits.  Consider this a function in one variable and minimize it.
Comment: @StudnetT: that is exactly what I was describing.  Julián Aguirre gave a process to make sure it is continuous, which I did not consider.  In my case, the abscissa of the break point is the independent variable and the error of the fit is the result.  We then minimize the error as a function of the breakpoint.
Comment: The point is how to find the optimal break point.
Answer: I am assuming that you want a continuous piecewise linear fit of the form
$$
a(x-\xi)+c\hbox{ if }x\le\xi,\quad b(x-\xi)+c\hbox{ if }x>\xi.
$$
There are 4 variables to determine: the slopes $a$, $b$, the point $\xi$ and $c$, the ordinate at $\xi$. Let $\{(x_i,y_i)\}$, $1\le i\le N$, be your data. For simplicity I will assume that $x_i<x_{i+1}$. For each $i=1,\dots,N-1$ minimize the expression
$$
O_i=\sum_{j=1}^i(y_j-a(x_j-\xi)-c)^2+\sum_{j=i+1}^N(y_j-b(x_j-\xi)-c)^2.
$$
This can be done by solving the system of 4 equations with 4 unknowns
$$
\frac{\partial O_i}{\partial a}=\frac{\partial O_i}{\partial b}=\frac{\partial O_i}{\partial c}=\frac{\partial O_i}{\partial \xi}=0.
$$
(This will be nonlinear, and will have more than one solution)
Finally, choose the index $i$ that gives the minimum $O_i$.
I tried this in a mock example, and it came out quite right.
Answer: (This was supposed to be a comment, but it got too long.)
The problem of piecewise linear regression has been looked into many times before; I do not currently have access to these papers (and thus cannot say more about them), but you might want to look into these:
This paper (published in a physiology journal, of all places) discusses how to fit a piecewise linear function to certain data sets encountered in neurological research. A FORTRAN routine is included.
This paper also includes a FORTRAN routine for fitting piecewise linear functions to data.
This paper relies on maximum likelihood to find the best fit piecewise linear function.


should I load all data from json file into html or load everytime from json file

Question: i need to load different data values from json file..
should I load all data from json file into html  or i load everytime from json file? . for example i'm loading values on a menu change
currently i'm appending all listmenu items in UL and adding values into attributes. so on selecting any menu item, all the attributes are called..
..
for(i = 0; i < list.items.length; i++) {
        $('#listMenu ul').append('
'+list.items[i].name + "
")

       }

Now i want to know.. what is the better way of getting from json file.. am i using the right way or not? because i'm worried if there is discription of too many lines.. that will become an issue for performance!
Comment: i think.. i must declare some global variables and pass root of json objects.. and call them from json file if data is larger .. and if only yes/no's or small values. then load them into html .. right?
Answer: If your data which you get from json is permanently,it much better to load into html.
Comment: i think.. i must declare some global variables and pass root of json objects.. and call them from json file if data is larger .. and if only yes/no's or small values. then load them into html .. right?


How to enable comments on custom entities

Question: I'm using a contributed module that provides a custom entity. I would like to modify that entity and want to enable comments for this entity.
Does anybody know how to enable commens for custom entities?
Comment: an 'entity' can mean nearly anything - are you referring to a node? a content type? a field?
Comment: It's not a node and not a content type. It is a custom entity.
You can create own custom entities by implementing hook_entity_info() (see [Creating your own entities with Entity API](http://www.trellon.com/content/blog/creating-own-entities-entity-api) for more details)
Answer: For Drupal 7, this module should do it - https://www.drupal.org/project/comments_entity
For Drupal 8, comments are available as a field for any entity type.
Summary:

Create a new Entity Type
Create a new Bundle for that Entity Type
Create a new Comment Type and select your Entity Type
"Manage Fields" on your new Bundle and add a new "Comments" field.
Configure comments as desired in the field settings.

Wrote a blog post about it here: http://www.daggerhart.com/drupal-8-add-comments-custom-entity-type/
Comment: That's true for Drupal 8 but not for Drupal 7.
Comment: @seb I see now this is for D7. My mistake. Here is a potential D7 solution - https://www.drupal.org/project/comments_entity
Answer: It's not possible to enable comments for custom entities because the structure of comments is made to comment nodes and not entities.


Ocaml: Bad style, all clauses in this pattern-matching are guarded

Question: I get a "Error: Warning 25: bad style, all clauses in this pattern-matching are guarded"
What does "guarded" mean?
My code has pattern matching-
match z with
    | y when List.length z = 0 -> ...
    | y when List.length z > 0 -> ...

Answer: The guards are the when parts.  What the compiler is telling you is that it can't tell whether your match is exhaustive (covers all possible cases), but that it might not be.  The compiler can't really tell for sure, because exhaustiveness is undecidable for arbitrary expressions.  The compiler just figures you should have at least one pattern without a guard because when the match is exhaustive, a guard on the last case would be redundant.
Since you know your match is exhaustive, the compiler is basically right.  Your second guard is redundant.  You can just leave it off with no difference in meaning:
match z with
| y when List.length z = 0 -> ...
| y -> ...

This will make the compiler happy.
I like this warning; it has found a few logic errors for me over the years.
If this code isn't just an example but is really what you wrote, it would be much more idiomatic to write it like this:
match z with
| [] -> ...
| head :: tail -> ...

It's also a tiny bit more efficient since it won't bother to calculate the length of the list and then discard the result.
If you don't need to destructure the list, you can make it simpler still:
if z = [] then
    ...
else
    ...

Comment: Thanks Jeffrey. You really cleared things up and helped me learn how to write cleaner code (esp with the if statements). :)


Does this limit exist?

Question: Does this limit exist?
$$ \lim_{n \rightarrow \infty}\sum_{(i=1)}^n (-1)^{i-1} \frac{1}{i} $$
Also, is there a name for this sum?
Comment: Yes, by the alternating series test. Are you familiar with the Taylor series of the natural logarithm?
Comment: It's sometimes referred to as the "alternating harmonic series".
Comment: I think it equals to $\log 2$
Comment: http://en.wikipedia.org/wiki/Alternating_series_test
Answer: This series is sometimes referred to as the alternating harmonic series. (An alternating series is just a series with alternating nonnegative and nonpositive terms.)
The convergence of this series follows directly from the alternating series test or the Leibniz test, of which this series gives an ideal textbook example.

Alternating series test. Suppose that the sequence $\lbrace a_n \rbrace_{n \geq 1}$ is monotonically decreasing and converges to $0$. Then the alternating series $\sum \limits_{n=1}^{\infty} (-1)^{n-1} a_n$ converges.

On the other hand, it is not absolutely convergent, since the harmonic series $\sum \frac{1}{n}$ famously diverges again and again. (See also this question: 255.)
It turns out that we also know the exact sum of the series. The logarithmic function has the Taylor expansion:
$$
\ln (1+x) = \sum\limits_{n=1}^{\infty} (-1)^{n-1} \frac{x^n}{n} \ \ \ \  (-1 \lt x \lt 1),
$$
with a radius of convergence $1$. Since $1$ is the end-point of the interval of convergence, it is not immediately clear that one can plug in $1$ in the above series. However, Abel's theorem for power series, in fact, guarantees that
$$
\lim_{x \to 1-} \ln(1+x) = \sum_{n=1}^{\infty} \frac{(-1)^{n-1}}{n}.
$$
Thus the series evaluates to $\ln 2 \approx 0.693\ldots$.
This answer is mostly an elaboration of Qiaochu Yuan and J.M.'s comments. Thanks to Robert Israel for pointing out the need for Abel's theorem.
Comment: Since $1$ is an endpoint of the interval of convergence, it's not so obvious that the sum of your series is $\ln 2$.  You need Abel's theorem.  See e.g. http://en.wikipedia.org/wiki/Abel%27s_theorem
Comment: @Robert You are correct. But I was not trying to derive the domain of convergence. I was more like, well, stating it from the know-it-all wikipedia. :-) I will update my answer to be more complete.

Does this limit exist?


Android Studio v.2021.1.1- How to install plugin from disk

Question: in the Android Studio 2021.1.1, I am not seeing any portal to install plugin from disk
Preference->Plugin
enter image description here
Answer:
In the light blue circle, you can find the option of adding plugin from the disk.


To bring status bar in iphone 6 to normal size

Question: I am making an iphone application which is automatically getting autoresize in iphone 6 and 6s. But status bar is also getting zoomed because of which status bar is looking bigger than normal size. So I want to bring status bar to normal size. When I am using iphone 6 splash and default image it is not getting auto resize and black patch is coming on top and bottom of screen. So I want that app should autoresize status bar should not be zoomed and be .
Is there any other way to reduce the size of status bar.
Any Help would be appreciated.
Thanks in advance
Comment: screenshot of what you are talking please...
Comment: Hi I had edit my question and put the screenshot i which status bar is zoomed.
Comment: what Default images you have in your app? AFAIK, you didn't include default images of iphone 6 and 6 plus bcz of which what you see is zoomed version of iphone 5s
Comment: Hi,Even I tried to put Default Image as well as launch image for 6 and 6s. But I think I am missing something please can you tell exact size and name of default images I should put in project.
Answer: You can't change size of status bar. you can't customize it. Status bar's height is fixed 20 pixel in any device or resolution and it's width is same with screen's width.
So, You can't customize status bar.
now for splash screen issue, set imagview in Launchscreen.storyboard and set top,bottom,leading and trailing constraints to it


How long should I make my SSL cert valid for?

Question: <code>* sgsax hates ssl certs
< Landon> indeed
< Landon> next time my servers cert expires I'm just going to make one
                for 100 years or something ridiculously long
</code>
Is there anything wrong with the above reasoning? Obviously someone might brute force it in 100 years, but how do you determine what's acceptable time frame?
Answer: It greatly depends on what your cert is for. If it is for identifying a specific website, you can probably make one that lasts until the expiry date for that domain. After the domain is renewed, you can also renew the SSL cert.
But if you are making a root cert for your own CA, you may want to make a long-term cert so that all the other certs generated by your own CA does not become invalid too soon. Something like 10 years is probably fine.
So, it all depends.
Answer: to build on diffbeer703, this is about identity and integrity.  the identity verified by the certificate is trusted because the signing CA is trusted.  if the CA signs certificates for 100, that generally is not trustworthy behavior and so the certificates they sign should not be trusted.
it is unlikely that a server identity will remain the same, let alone in existence for 100 years.  also if the server is compromised its certs can be stolen and used to identify another server as yours.  short lived certs make more frequent cert verification necessary thus making
server identity theft less of a threat.
if you manage the entire chain then, it is less of a concern especially if the only person needing the server identity verified is you.  the more people depending on the server identity  the more important it is that good practices are followed by the CA.
Comment: Isn't that what a CRL is for, listing revoked certs?
Comment: If you don't really know what you are doing, will you even know that a cert still exists in 2020. The motivation for the 100 year cert sounded like laziness to me.
Comment: @bill CRL's are frequently not honored or checked by many ssl clients.   It's still good practice to use them, but it's not a panacea.  Good practices are good practices for a reason.
Answer: Can you do it? Sure -- if you're generating a throwaway self-signed cert that is for trivial business or personal use. If you're going to setup a PKI for anything more serious, you need to learn more about the issues involved.
PKI is about more than just encryption -- its about establishing a chain of trust.
A good resource is "Windows Server 2008 PKI and Certificate Security by Brian Komar", describes all of the various PKI scenarios that you are likely to care about. You don't need to use Microsoft's CA to get something out of the book.


Code a message box when a workbook is selected

Question: I would like to make a macro so when the workbook is opened or when it becomes active (meaning that its not active when its running in the background but the user is working in another workbook or in another application) there comes a dialog box with a customized warning message. Ideally the code would look something like this and would be in the ThisWorkbook Object code:
Sub warningmsg()

Dim wb As Workbook
Set wb as This.Workbook
If wb.first.mouseclick <> True
Then
    MsgBox "Warning, this workbook is HOT"
end sub

How is this possible in Excel VBA?
Comment: When exactly would this code run? And what would cause the MsgBox to appear? The question, currently, is not specific enough.
Comment: The event of the user opening the workbook or activating the workbook after doing something else should trigger the message box.
Answer: Stick the below code in the ThisWorkbook code
Private Sub Workbook_Activate()
    MsgBox "this workbook is hot"
End Sub

Save and close file (make sure you use an extension that contains macros, .xlsm for instance).
Open it again, and open another workbook. Switching between windows and activating the one that has the above code in it will cause the MsgBox to appear and show your this workbook is hot string
Comment: @steinbitur that is how to Workbook_Activate() event works. You cannot overwrite this behavior. It only works between workbooks.
Comment: thank you, it works like you say, but when I click on another window e.g. the browser and then back it does not pop up like I would like


r - How to find name of Max vlaue in Closeness Centrality igraph output

Question: I use of igraph package in R for work on graph. I get Closeness Centrality with igraph method, and I want to find maximum value in Closeness with name.
library(igraph)
# Create of Graph Matrix for Test Closeness Centrality
g <- read.table(text="A B
     1 2
     2 3
     3 4
     4 5", header=TRUE)
gadj <- get.adjacency(graph.edgelist(as.matrix(g), directed=FALSE))
igObject <- graph.adjacency(gadj) # convert adjacency matrix to igraph object
gCloseness <- closeness(igObject) # Assign Closeness to Variable for print

When I use of max() I get maximum value of Closeness and when use of names() back NULL.
> max(gCloseness)
  [1] 0.1666667

other:
> names(max(gCloseness))
  NULL

Answer: Try V(igObject)[which.max(gCloseness)]
Comment: Show only value, my result is : "Vertex sequence: [1] 4"
Comment: The output for `V(igObject)[which.max(gCloseness)]` with your example data is `3`. If you label the nodes, i'd be the label, e.g. for `V(igObject)$name <- letters[1:5]; V(igObject)[which.max(gCloseness)]` the output is `c`
Comment: Yep! thanks. my training data have not label. I test on another data set is right.


How to detect the already selected mailbox using IMAP commands?

Question: Is there any IMAP command, which can help to identify the currently selected mailbox.
Use case:
Suppose there is a proxy server which is caching the IMAP connection, when the clients connect , clients need not waste time selecting the mailbox if its already selected.
Comment: I don't believe so.  IMAP has a strictly defined state machine, and the client needs to keep track of the state.  Going from NON-AUTHENTICATED to SELECTED is an invalid state transition.
Answer: You are misunderstanding the RFC3501's state machine, as Max said. There is no way you could "end up" already selected into any mailbox. If something like that happened, the IMAP proxy would be hopelessly broken and there would be no sane way of using it.
See the IMAP state machine from RFC3501. Within the IMAP protocol, after the connection is established, the state can only ever be one of "authenticated", "unauthenticated" and "logout". At no time it is possible to enter the selected state directly.
If you add an "IMAP proxy" to the picture, either it cannot cache the IMAP connections in this way, or you cannot talk IMAP to your proxy. While there could easily be some protocol inspired by IMAP which you can use here, i.e. with a couple of extensions for doing exactly what you'd like to do, it would not be IMAP as defined by RFC3501 anymore.
Now, what is definitely possible is to have a proxy in front of your IMAP servers which would help with e.g. TLS connection overhead. However, if that is your setup, your IMAP proxy must make sure that no mailbox is selected at the time the connection is reused. You will also have to invent some reauthentication method as well, but that's outside of scope now.
For a little more technical background on why it is designed this way, be sure to read how the SELECT command works. In IMAP, certain mailbox data are transfered during the SELECT processing, and these data are very important to ensure that both client and server share a well-synchronized view of the mailbox state. If your client suddenly jumped into the selected state, you would have to get these metadata in some other way (and note that this "other way" is explicitly forbidden, i.e. you should not issue STATUS on the currently selected mailbox. With a reasonably modern IMAP server, i.e. one which supports CONDSTORE or QRESYNC extensions, the requirements are even more important.
In general, the IMAP protocol does not benefit from proxies in the way most people expect it to do. If you actually need to use one, perhaps you can share more information on what leads you to this conclusion.
Comment: Hope you didn't get my question. I will elaborate, say an IMAP proxy can cache a connection till 5 minutes. So the client first connects to the proxy, the proxy opens the connection, then login and selects inbox.  Now within 5 minutes if the same client connects to proxy it need not open the connection again, because the connection is in Authenticated and selected state. This saves few seconds(10 - 30 sec). The only problem arises here is that when the second time the client connects it doesn't know what mailbox is selected. This is how we end up in a "already selected" state.
Comment: I have added much more details to my reply; hope you will find it clearer now.


If the letters of the word 'mathematics' are arranged around a circle, what is the probability that alike letters are not together?

Question: If the letters of the word 'mathematics' are arranged around a circle, what is the probability that alike letters are not together?
My thought : I think that between two M, two A and two T, we can put the letters. But there are more cases when MTMT like arrangements are also possible. So please suggest a right way of counting.
Comment: Inclusion-exclusion.  Instead count the number of arrangements where at least one of the letters that come in a pair *are* together.  To account for the circle aspect of arranging, go ahead and treat $S$ as **s**pecial and place it at the **s**tart, and just care about how things are placed with respect to the $S$.
Answer: The word contains $\bf{2M,2A,2T,H,E,I,C,S}$
Place $\bf{S}$ as reference point, as suggested by JMoravitz. Then there are a total of $10$ letters left with $3$ pairs, and we can now treat them as permutable in a straight line with respect to $\bf{S}$
By inclusion-exclusion, we get
[Valid arrangements]
= [All ways]
$\,$- [at least $1$ pair together]
$\,$+ [at least $2$ pairs together]
$\,$- [all $3$ pairs together]
$= \dfrac{10!}{(2!)^3} - \dbinom31\dfrac{9!}{(2!)^2} +\dbinom32\dfrac{8!}{2!} - \dbinom33{7!} = 236880$


ParseQueryAdapters... Recycler Views instead?

Question: It seems that Recycler Views are the way to go, at least from what I have been reading through documentation. But it seems that using a ParseQueryAdapter it is designed to use a listview to display data it pulls down
I have a recyclerview displaying the data in a card style look, it reads in an array with 2 strings and 1 picture per each "card" example:
<code>private void initializeData(){
    persons = new ArrayList<>();
    persons.add(new Person("Emma Wilson", "23 years old", R.drawable.ic_launcher));
    persons.add(new Person("Lavery Maiss", "25 years old", R.drawable.ic_launcher));
    persons.add(new Person("Lillie Watts", "35 years old", R.drawable.ic_launcher));
}
</code>
for this I just manually entered data in to test the card interface, how would I go about pulling fields from a query, is there a way I can setup varibles and run some sort of loop?
Would love to hear your guys thoughts...
Thanks
Comment: I want to pull data down from parse using a query and then nicely display it in a timeline
Answer: try using ParseQuery in your intialize method
check this out
Comment: You should include in your answer the relevant content from the link you provided. If the link goes offline or is moved, your answer becomes useless.


How to click on a link in a table with Geb

Question: I have the following table in the page I'm trying to test.  I can't seem to get a handle on the link in the second td tag to click on it.  I've tried everything I can think of.  I have put the table into a module, I have tried to drill down to it manually, and nothing.  I'm pretty new to Geb so I'm sure I'm just not doing it right.  What is the best method?

query = pn:smith

            438819
            20000422 06:42:42.000Z 00438819 c 3
            100 1␣ $a Abel-Smith, Brian

            2000911
            19900530 09:45:42.500Z 02000911 c 3
            100 1␣ $a Acklen, Joseph Alexander Smith, $d 1816-1863

Comment: did you try  traversing down something like `def a = browser.$("table", id: "record-list")` and then `def b=a.("children")` and `def c = b.("tr", class: "even")`. I am not sure about the syntax.
Answer: The easiest way to click the link in the second td tag which is also the first link inside of your table is:
$("#record-list a", 0).click()
Comment: Thank You!  That finally got me what I needed.


HTML PayPal Form Input Show On Payment

Question: So, I have this basic required text forum input on my paypal button. How do I make it so when the person it buys it, the text they put in shows up on my payment or invoice?
Comment: any code for us to look at? or is this question asking us to write the whole thing for you
Comment: I guess so, this is my button. http://pastebin.com/u5Me7H6C
Answer: Go to 'My Saved buttons' in PayPal profile, click 'edit' on this button, in "Edit your PayPal payment button' page,there is a customize button section in which you need to check 'Add text field'.

HTML PayPal Form Input Show On Payment


Many to many relationship with attributes and surrogate key

Question: I have the following tables:
users

id INT PK
created_at DATETIME
updated_at DATETIME
is_archived BOOLEAN
name VARCHAR

publishers

id INT PK
created_at DATETIME
updated_at DATETIME
is_archived BOOLEAN
name VARCHAR

subscriptions

user_id INT PK,FK
publisher_id INT PK,FK

I want to have additional attributes in my the subscriptions such as created_at, updated_at and is_archived (like all other tables) and other fields.
My options are:

user_id INT PK,FK
publisher_id INT PK,FK
created_at DATETIME
updated_at DATETIME
is_archived BOOLEAN
expires_at DATETIME

OR

id INT PK
user_id INT FK
publisher_id INT FK
created_at DATETIME
updated_at DATETIME
is_archived BOOLEAN
expires_at DATETIME

What are the pros/cons of having an autoincrement key instead of using both foreign keys as a primary composite key?
Answer: In mapping tables for many-to-many relationships I typically use a compound primary key of the two items. The main pro of this approach is that the uniqueness of the record as a combination of the two is enforced by them being the primary key. Also, the existence of a separate auto-increment id in most cases doesn't provide much benefit or give a row any more meaning so to me it is noise more than anything else. That said, it can be beneficial if the mapping of the two tables is an important domain entity in its own right that will be used on occasion without joining the other tables to it.
The main con of this approach is that queries can be a bit more verbose and you generally cannot directly access a record without having a join against the other tables in the relationship. It also enforces uniqueness, so you can't have multiple instances of the same user and publisher together.
If subscriptions are an important entity in your application that can standalone without a user or publisher then you may want to go with the auto-increment. Additionally, if you have the need to have multiple records for any combination of user and publisher (which seems like you will) then the auto-increment approach is the correct way to go.
Answer: For me this depends mainly on how you are going to access the data.
If you always start from a users or publishers point of view and just want to get the related data, an additional primary key will be pretty much obsolete.
If the subscriptions table in itself has a lot of data and is not always depending on the user or publisher data to make sense, then an additional primary key would make sense to access the data.
So if it is a conventional linking table I don't see a reason to add a seperate primary key.
If you can look at it more like a seperate entity - usually if you can give it a more meaningful and independent name - which has 1:m relationships to users and publishers then an additional primary key makes sense.