Evaluate integral $\int_0^\infty \frac{e^{-x^2}-1+x^2-\frac12x^4+\frac16x^6}{x^8}dx$

Question: This is one of my final exam problems.
I notice the polynomial in the numerator are the first few terms of the Taylor Expansion of $e^{-x^2}$. But integral of each terms in the Taylor series of $e^{-x^2}$ is not convergent, and I fail to translate the fraction into some form of $e^{-x^2}$. My final attempt is to get the integral series $$\int_0^\infty \sum_{k=0}^{\infty} (-1)^k\frac{k!}{(k+4)!}\frac{x^{2k}}{k!}dx$$whose integral and summation cannot commute due to the divergence.
By Mathematica the solution is founded to be $\frac{8}{105}\sqrt{\pi}$ (which means the integral has some relation with $e^{-x^2}$). How to get it? Any help is appreciated.
Comment: 1) Divide the integral into a sum of integrals.
2) Evaluate each of them individually, using either the standard formula for integration of $x^{n}$ or the Gauss integral + integration by parts.

Edit: I also noticed that, evaluated in that way, the inegral is divergent at 0, so the limits (w.r.t. the variation of the lower integration limit) of the integrals at zero must cancel each other, which is where you use the coincidence of the first terms of the Taylor series with other summands
Comment: Also, where did you get the divergence from? Exponent is an entire function, $-x^2$ is entire, so $e^{-x^2}$ is entire and its Taylor series must converge everywhere
Comment: @DaigakunoBaku Yes, I forgot I can directly calculate the integral. The divergence of every term at 0 is ok because the whole function is convergent, hence I can ignore the terms gained with integral by part at $x=0$ and $x=\infty$. Later I will have a try. Thanks.
Comment: @DaigakunoBaku I mean each monomial's integral is divergent.
Comment: I think a $k$ is missing in the exponent of $x$
Comment: Final exam in what course?  (That may provide a hint of how to solve it.)
Comment: @GEdgar Mathematical Analysis(Calculus), no hints. May seem to be ridiculous, but the answer can just be gained with integral by parts.
Answer: For this type of question, I like to
employ Ramanujan's Master Theorem. Indeed, your integral can be re-written as
$$\int_0^\infty \sum_{k=0}^\infty \frac{(-1)^k}{(k+4)!} x^{2k},$$
which after the change of variables $x\mapsto \sqrt{x}$, becomes
$$\frac{1}{2}\int_0^\infty x^{-1/2}\sum_{k=0}^\infty \frac{k!}{(k+4)!} \frac{(-x)^k}{k!}.$$
Appealing to the Master Theorem, the integral reduces to
$$\frac{1}{2} \Gamma(1/2)\frac{\Gamma(1/2)}{\Gamma(9/2)}=\frac{8}{105}\sqrt{\pi},$$
by Wolfram.
Comment: So quick and nice. Is this Theorem accepted as rigorous in mathematics?
Answer: This solution is inspired by @DaigakunoBaku, just some easy integral by part casting away the boundary terms, due to the summation of all the bouadary terms are zero, using $$\lim_{x \to 0}\int_{0}^x f(x) = \lim_{x \to \infty} \int_x^\infty f(x) = 0$$ where $$f(x) = \frac{e^{-x^2}-1+x^2-\frac{1}{2}x^4+\frac{1}{6}x^6}{x^8}$$
So first we guess the answer is the final integration term of $\int e^{-x^2}/x^8dx$ ,denote $D = (1/N,N)$ and $B = \partial(1/N,N)$:
$$\begin{align}
&\int_D e^{-x^2}x^{-8}dx = -\frac{1}{7}e^{-x^2}x^{-7}|_B - \frac{1}{7}\int_D e^{-x^2}2x^{-6}dx \\
&=-\frac{1}{7}e^{-x^2}x^{-7}|_B+\frac{2}{7\times 5} e^{-x^2}x^{-5}|_B + \frac{2^2}{7\times 5}\int_D e^{-x^2}x^{-4} dx\\
&=-\frac{1}{7}e^{-x^2}x^{-7}|_B+\frac{2}{7\times 5} e^{-x^2}x^{-5}|_B - \frac{2^2}{7\times 5\times 3}e^{-x^2}x^{-3}|_B - \frac{2^3}{7\times 5\times 3}\int_De^{-x^2}x^{-2}dx\\
&= \frac{2^4}{7\times 5\times 3\times 1} \int_D e^{-x^2}dx\\
&+ -\frac{1}{7}e^{-x^2}x^{-7}|_B+\frac{2}{7\times 5} e^{-x^2}x^{-5}|_B - \frac{2^2}{7\times 5\times 3}e^{-x^2}x^{-3}|_B + \frac{2^3}{7\times 5\times 3}e^{-x^2}x^{-1}|_B \\
&\to \frac{8}{105}\sqrt{\pi} + \text{Boundary Terms}\\
\end{align}$$
Now here we check the summation of all infinite boundary terms is zero totally, by letting $\int_0^\infty = \lim_{N}\int_{1/N}^N$:
The summation of $x=N$ boundary terms are (combining the term gained with integral by part and the integral of polynomial)
$$
\begin{align}
&\{\frac{1}{7}x^{-7}-\frac{1}{5}x^{-5}+\frac{1}{6}x^{-3}-\frac{1}{6}x^{-1} \\
&+\frac{1}{7}e^{-x^2}x^{-7} - \frac{2}{7\times 5}e^{-x^2}x^{-5} + \frac{4}{7\times 5\times 3} e^{-x^2}x^{-3} - \frac{8}{7\times 5\times 3\times 1}e^{-x^2}x^{-1}\}|_{x=N} \\
&\to 0
\end{align}
$$
The summation of $x = 1/N$ boundary terms are
$$\begin{align}
    &\{\frac{1}{7}e^{-x^{2}}x^{-7}-\frac{1}{7}x^{-7} \\
    -&\frac{2}{35}e^{-x^2}x^{-5} +\frac{1}{5}x^{-5} \\
    +&\frac{4}{105}e^{-x^2}x^{-3} - \frac{1}{6}x^{-3} \\
    -&\frac{8}{105}e^{-x^2}x^{-1} + \frac{1}{6}x^{-1}\}|_{1/N} \\
    =&\{\frac{1}{7}(x^{-7}-x^{-5}+\frac{1}{2}x^{-3}-\frac{1}{6}x^{-1}) -\frac{1}{7}x^{-7} \\
-&\frac{2}{35}(x^{-5}-x^{-3}+\frac{1}{2}x^{-1})+\frac{1}{5}x^{-5} \\
+&\frac{4}{105}(x^{-3}-x^{-1})-\frac{1}{6}x^{-3} \\
-&\frac{8}{105}x^{-1} +\frac{1}{6}x^{-1} +O(x)\}|_{1/N}\\
\to& 0
\end{align}$$
Hence the estimation is finished. The calculation is more complicated than I thought, thanks @M.Wind. Is there a easier way?
Comment: This is not really a good answer to your own question. You just tell in words how the calculation can be done, and then present the final answer which you found using an online integrator. But that is not the same as actually solving your problem rigorously. If you had written this answer in your final exam, you would not have scored points.
Comment: @M.Wind Yeah you are right. The calculation of the boundary terms is not so trivial as I thought. I will present the detailed answer in minutes. Thanks a lot.
Comment: @M.Wind The answer is uploaded.
Comment: You have improved your answer considerably. It is indeed a good procedure to perform integratation by parts, and then to expand the result in a Taylor series. This way you can demonstrate that cancellation of boundary terms indeed occurs. This was to be expected, given the nature of the integrand, but it still had to be demonstrated. Well done !


What woodwind & brass instruments are most air efficient?

Question: So I am trying to compose this woodwind quintet and other pieces relating to woodwind and brass instruments, and I need to figure out whether I can let some instruments breathe or keep playing. After some research, I now know a few things:

Flutes are extremely air-inefficient. It almost uses as much air as a tuba.
While not bad with air use, double-reed instruments are pretty hard to play. It would be best not to force the players to play a lot.

However, can I make clarinets and French horns play for extended periods of time without them protesting against my score for either air or difficulty reasons? What other woodwinds and brass instruments are out there that can play long, hard phrases with no problem?
Comment: Fascinating question. The flute/tuba comparison is truly surprising. Do recall where you learned that?
Comment: Point two reveals that air efficiency isn't your only concern, or even your primary concern.  The oboe is the most air efficient instrument hands down, but your research shows that you nonetheless should give them periods of rest.  It's also not clear if you're asking how long a phrase a player can play without needing to breathe or how long a passage a player can play before you should give them a chance to put their instrument down.
Comment: @Aaron This really short video helped me realize that: [How to Write for Flute in 2 Minutes](https://www.youtube.com/watch?v=E6eLjRI7F8U&list=PLDNH2wJD6kQx_UeA5BViPMtpSztR5U_c7&index=2). As a professional musician, I wouldn't believe any such random facts easily, especially from such types of tutorials, but the guy in the video does have a point.
Comment: As @Aaron suggests, a clarinet player and a sax player I know can circular breathe and they can play legato for at least two minutes at a stretch. These are exceptional musicians who are essentially at the low end of virtuoso status. I would only consider writing long passages like that if one of them specifically commissioned a concerto from me. As it stands they will both just connect phrases that are not marked as such to show off/enhance the music. But it's their choice to do it when they are rested and motivated.
Comment: Just look at some scores to see how good composers write for the different instruments. There's a huge selection for free on imslp.org.
Comment: @phoog A rental flute and 1-2 lessons or a copy of a woodwind methods book wouldn't add up to much money and would explain everything much better than I could. Regarding "lips providing back pressure", that phrase completely agrees with my statement that no back pressure is provided by the flute itself.
Comment: Who's going to be playing the piece?  Professionals?  Students?  If students, what level?
Comment: An extension of @phoog's thoughts: are you allowing for circular breathing?
Comment: @Aaron take 2-4 flute lessons. If you don't get light-headed in your first week on flute it could only be by never playing it. Half the air you blow at it just goes right past the sound hole - there's zero back pressure like on all reed and lip reed instruments.
Comment: @ToddWilcox - I know a similar woodwind player. Darned impressive, though almost a circus trick used in solo/duet gigs, like making a big show of playing the top of Rhapsody in Blue as a single 2-octave bend … which he can also do
Comment: @ToddWilcox a flutist's lips provide back pressure.  Doesn't it vary with the pitch?  In other words, doesn't the answer to "how long before a breath is needed" depend on whether it's a passage in the lower half of the staff or in the ledger lines above?
Comment: I'll see your oboe & raise you a harmonium. See who runs out of breath first ;))
Comment: Personally I do not find the bassoon to be hard to play at all in terms of air or embouchure. Perhaps a bit on the high notes but that applies to all woodwinds. The trick with the bassoon is the fingering can be pretty complicated. Flute has easy fingering but requires lots of air and tricky embouchure. Clarinet requires very particular embouchure and easily squeaks but fingering isn't too bad. Oboe is hardest for me - lots of air pressure, tough embouchure, and fairly complicated fingering. Bassoon was easiest for me - even intonation wasn't hard after only 5 weeks.
Comment: Related [question](https://music.stackexchange.com/q/104370/2600), where answers cover the air supply issue.
Answer:
can I make clarinets and French horns play for extended periods of time without them protesting against my score for either air or difficulty reasons?

No. You can't extend any particular instrument. It doesn't matter much which instrument is most air efficient (it's probably the oboe), because the greatest need to breathe is often "stale air", not lack of air.
As air sits in our lungs, our lungs are removing oxygen and adding carbon dioxide to the air. Normally we exhale and inhale again fresh air that has plenty of oxygen in it. The longer the air sits in our lungs, the less oxygen it has and the harder it becomes to extract the oxygen - the air is "stale" and we need to replace it with fresh air.
This is why oboe players actually have to breathe out sometimes when they play. Their instrument is so air efficient that their air becomes stale before they can breathe out enough through the instrument.
Even on clarinet I've had to put exhale breath marks in my part sometimes.
The other thing is musically you usually want instruments to breathe together, even the strings should "breathe" with the winds and brass in many cases.
Finally, no matter what you write, players will breathe. You can't stop them from doing it and you shouldn't try. The only thing to do as a composer is if there are moments where you really don't want them to breathe, you can put slurs over those moments and encourage breathing before and after with rests and/or longer notes with no slurs and even decrescendos on them. That's when we like to breathe.
Pros won't protest. They might roll their eyes at each other when your back is turned and they will breathe when they have decided it is musically correct.
I'm also remembering that for oboes and brass (especially horn), their chops (aka "face" for oboes) just can't last through long extended passages. Breath support and embouchure require significant physical effort - not quite athletic level but still fairly tiring. I can currently go about two hours on clarinet (with breaks) but only like ten minutes on oboe. Obviously pros will have more developed facial muscles than mine, but it's still tiring for your face and core.
Be good to musicians and they will be good to your music.
Comment: "No"?  No to what? (If upvoted, by the way; I just don't understand the first word.)
Comment: As an oboist and occasional player of all the other instruments mentioned here, I concur.  It's not even possible to use up an entire lungful of air, playing quietly, before your oxygen runs out and you need to inhale again.
Comment: @phoog There was only one yes or no question in the question but for you I've reproduced it in my answer.
Answer:
I need to figure out whether I can let some instruments breathe or keep playing.

The best way is to make some friends (or to have them already) and ask them to play through the piece for you.  They can tell you not only how difficult the piece is but also what aspects are difficult and why, and they may be able to give pointers on what to change.

can I make clarinets and French horns play for extended periods of time without them protesting against my score for either air or difficulty reasons?

This depends on who your players are.  Undergraduate liberal arts students?  If so, majoring in music or something else?  Conservatory students?  If so, at what level (and at what conservatory)?  Professionals?  Adult amateurs?
(Further, "extended" is vague, and for each category mentioned above, the threshold for "extended" will be different.)

What other woodwinds and brass instruments are out there that can play long, hard phrases with no problem?

When I was a student, there was sometimes talk of which instrument is "hardest."  At some point, I realized that this was largely about which instrument was hardest for beginners.  Every instrument is hard to play at a professional level, because, as with every human endeavor, the people who are best at it work very hard at it to become good.  The threshold for "long" and "hard" will be different for different instruments, but the top players in the world will be able to play long, hard phrases relatively easily, while high school players will have problems.
If you don't play the instruments yourself, there's really no substitute for workshopping your piece (or pieces) to get a better sense of the instruments' and their players' capabilities.  Consider having the group play a piece from the standard literature to compare.  Study several yourself beforehand, and pick one or two for them to play.  Studying these questions only theoretically is insufficient.  For example, take "how to write for flute in 2 minutes."  With those points in mind, study some flute parts from orchestral pieces and wind quintets, both scores and recordings, to see how composers put those points into practice.  "Don't write below G unless you know what you're doing"?  See how composers who did know what they were doing actually used that part of the flutes compass.


Restful permission is required

Question: I've created a @RestResource plugin to provide a REST endpoint to get some data, but when I try a GET from Postman it shows this error:

{
      "message": "The 'restful get ez_share_document_resource' permission is required."
  }

I thought it was because I need to add something else, so I decided to enable the Watchdog database log REST resource to prove it, but I got the same error:

"message": "The 'restful get dblog' permission is required."

Rest module has set bc_entity_resource_permissions  as false.
This is the annotation of the plugin.
/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "ez_share_document_resource",
 *   label = @Translation("Ez share document resource"),
 *   uri_paths = {
 *     "canonical" = "/ezshare/{ezshare_id}"
 *   }
 * )
 */
class EzShareDocumentResource extends ResourceBase {

And this is my get method:
public function get($ezshare_id = NULL) {
    if ($ezshare_id) {
      $record = ['It Works!!'];
      if (!empty($record)) {
        return new ResourceResponse($record, 200);
      }

      throw new NotFoundHttpException($this->t('EzShare doc with ID @id was not found', ['@id' => $ezshare_id]));
    }

    throw new BadRequestHttpException($this->t('No EzShare doc ID was provided'));
  }

Drupal core is recently updated to 8.8.1.
Comment: You have to add the permission to the roles that must have the permission under, `/admin/people/permissions`.
Comment: Yes, all permissions are enabled for Authenticated users.
Comment: Do you use `cookie` or 'simple_auth' as authentication?
Comment: Yes, I use Basic Auth, but when I use cookies in the browser it works. The issue is only with Basic Auth.
Comment: You have to send the Authorization header with in Postman. In postman you can choose to authenticate with basic auth where you enter the username and password.
Comment: Yes, I have it, I'm using my user credentials, should I enable another permission? Headers are Content-type => application/json, Accept => application/json and Authorization => Basic aX....
Comment: If authenticated users have permission and you have configured postman to use basic auth, the only thing that I can think of as a problem is that either the username or password that you use is incorrect.
Comment: I thought the same, but I tested those from a different browser and they work. I was able to log in. I enabled the resource from REST UI like so: Ez share document resource /ezshare/{ezshare_id}: GET, PUT
methods: GET
formats: json
authentication: basic_auth
Comment: Also I tested it with Soap UI and I got the same error, so it is not related with Postman. I dont know what else I should check
Answer: Finally, I was able to solve this issue adding the method permission to the RestResource plugin like so:
public function permissions() {
  return [];
}

Comment: Yes! this is the right answer. Also you should add the annotation to your method like this:
  /**
   * {@inheritdoc}
   */
  public function permissions() {
    // permissions are required.
    return [];
  }
Answer: The default permissions() method creates a permission per method
In ResourceBase
/**
* Implements ResourceInterface::permissions().
*
* Every plugin operation method gets its own user permission. Example:
* "restful delete entity:node" with the title "Access DELETE on Node
* resource".
*/

Shown in admin/people/permissions

Everything else being equal anonymous can be given access (or a specific role).
Clearing permissions doesn't open access.
Check the REST configuration. Either via configuration synchronisation or REST UI. Install the Rest UI module and check that an authentication provider is installed (OP Basic Auth). The permissions can be configured from the Rest UI interface

Some authentication methods also require access. Check in the network monitor in the browser. With JWT for example, a request for an expired token is required first. If this is denied, or fails it is a problem with the authentication provider.
Comment: It's not so clear with JWT token, can you provide more info ? I'm testing with Postmant, but no matter what I write in the Bearer, I keep getting access to the endpoint.
Comment: I guess you turn off all access to make sure you are hitting the right end point? If there is full access without a token then it is an access rules problem, not a token problem.
Comment: Alright, but which access rule ? I haven't done anything specific, it's seems like a cache problem in my case because once it's validated I never go into the EventSubscriber provided by the JWT module
Comment: You could try rebuilding permission  /admin/reports/status/rebuild https://drupal.stackexchange.com/questions/216940/rebuild-node-access-permissions

Restful permission is required


Is this site only for "expert-level questions"?

Question: In this question, a close-vote was justified as follows:

The question is too broad. But, more importantly, it is not at all an
  expert-level question, to the degree that intermediate undergraduate
  courses in Economics should discuss this topic. Hence I voted close
  under the off topic reason.

It is clear then that the specific user sees this site as a site only for "expert-level" questions.
I disagree, for the following two reasons:
A) An "expert-level" only site will have too small a potential target popualtion from which the community members will come.  "Expert-level" rules out even graduate students -what is being taught in various masters around the world is not at all expert-level. "Expert-level" is equivalent to "professional academic level", so full time academics, PhD's, late-phase PhD candidates, early-phase PhD candidates (grudgingly accepted), and maybe the occasional amateur who is really inamorata with Economics and has studied the field deeply.  My forecast is that with such a restricted target audience, the site will eventually die.
B) More personally, this is not my vision for this site. I see also an educational aspect to it. I believe that this site should accept any question that relates to the scientific study and scientific application of Economics and Econometrics.
But of course, my vision is not the "vision-to-be-formed" by the actual community that just started to materialize.
So I am putting this up for discussion, comment, answer, up-voting, down-voting (remember, votes in the meta-site predominantly mean "agree-disagree", so if you don't want to write an answer expressing your opinion, you can just up-vote or down-vote this question).
This is the defining moment people! Here in private beta. So please, participate in this discussion.
Comment: My god, someone actually voted to close a meta question...
Comment: I think this is a straight duplicate of [How technical must the questions be?](http://meta.economics.stackexchange.com/questions/4/how-technical-must-the-questions-be), isn't it?
Comment: @LateralFractal Voting to close meta questions as duplicates is appropriate sometimes.
Comment: Would it be possible to create a system of tags that would distinguish expert-level questions from the rest? Maybe a single tag called "research" or "expert" or something?
Comment: @EnergyNumbers Looking at the answers to the post you link, (its title is misleading) yes, they ended up treating the same issue. The difference is that I have put forth a specific policy proposal for voting, while the other post asked a question.
Comment: @EnergyNumbers Except linking them, can they be merged somehow?
Comment: given there's only one short answer here, with a single vote, I don't think a merge is justified - normally, questions are only merged if there's a lot of good content on both, as i understand it.
Comment: @EnergyNumbers Indeed, but this is meta, not the main site. Discussions here have also to do with decisions, or emerging consensus, and this is the case here. The three upvotes to the question itself are of value in the on-going discussion.
Comment: The simplest thing is probably to delete this question, and post an answer to the other. The other option is to flag this question, and request a merge. While it's probably fairly easy for an SE employee to merge answers from two questions, I'm not aware of any mechanism for merging the bodies of the questions themselves, so I don't know what would happen there.
Comment: I don't think its a duplicate. Experts can post non-technical questions, (as in: What are references, whats the intuition of..). Non-expert can ask technical questions (as in, beginner material, but in the proper framework).
Comment: Does an upvote on this question mean "Yes?".
Comment: @Calmarius In meta, upvotes have that meaningm ("yes" or "I agree") and likewise for downvotes, as written in the body of the question.
Answer: Just my thoughts:
I think the point is that a stack exchange site can easily lower it's expertness (if that is a word) but it is much harder to raise it.
During private beta we are time and population limited and so things are somewhat artificial.  A number of questions are clearly being asked for the sake of asking a question, not driving a real research need.  We need this, otherwise we probably wouldn't have enough questions.  On the other hand, when it goes public, if the questions are mostly "expert-level" then the hope is that experts might use the site to ask their questions.  If experts start asking questions, then they might answer them as well.
On the other hand, if we go public and a quick browse shows what looks like lots of undergrad/lay questions then that will imply that the site is not of the caliber to answer expert level questions.
Non-expert users will be very easy to attract, and won't be put off by the presence of expert level questions.
After beta, we should relax our "level" bar, but the bar should be higher during the private beta.
Comment: (+1) A sensible remark, and an indication of strategic thinking!
Answer: Well, what constitutes an "expert-level question"?  Clearly, that definition is a bit of a moving target.
The beautiful thing about most major Stack sites is that you can show up with any level of proficiency and receive expert-level feeedback and information.
For instance, when I was learning R (right out of school and an expert at SAS), I could go to StackOverflow and say, 'How in the world do I aggregate on multiple conditions?' and I would get a concise, expert answer that never exceeded the bounds of my limited knowledge.
Now, I can go there and ask, 'Is aggregating a dataset larger than 6 GB using 'Obscure Package B' more or less resource intensive than using data.table, and why?' and I get a much more technical answer that understands my current level of knowledge and answers accordingly.
That, to me, is the power of these sites- accessible, concise, and in-depth.  A college freshman, senior, grad student, doctoral candidate, and 45 year professional can all walk away with actionable, professional answers to their queries, without fear that they will be chased off-site with torches and pitchforks because their question failed to meet some esoteric, ego-inflating idea of "expert-level".
I say, bring it on- nearly all of it.  The beauty of these sites, at the core, is the idea that experts enjoy sharing knowledge and helping folks solve the very same problems that once stumped us- let's continue that tradition.
Comment: +1. I've been trying to wrap my head around why some people want such a narrow requirement of expert questions for _economics.se_ even if this kills community engagement and diversity. I've come to the revelation that a minority are mistaking this site for a _journal_. The journal paradigm is an exclusive rather inclusive paradigm in which content snobbery and reputation is vital - birds of feather flock together / the protruding nail gets hammered down / what will mother say. A paradigm that's become broken if we're honest about it - and entirely unsuited for Q&A pedagogy and problem solving.
Answer: Expert is a wishy-washy term. My preferences are as follows:

I strictly oppose to Econ 101 questions and their intuitions [1]
I dislike, but not completely oppose to questions of intermediate Economics undergraduate levels

I'm happy to see any question that is above that level. If you refer to this level as "expert" questions, yes, that's what I would prefer most.
[1] And this is because I personally find no interest in them. This would make me indifferent. But I have the big worry that having them here would make it more difficult to actually find questions that interest me, which renders me against them.
See also Mathematics and Mathsoverflow, where they have noticed that expert level content and normal content cannot coexist, and hence decided to split it up.
Expert level Questions versus Expert level Answers
The level of OP makes a huge difference. If I can expect a certain level of familiarity with Economics, I can provide much more compact and precise answers using the proper terminology.
A question that implies that OP had very little exposure to Economics will need an answer that is either very long (to introduce relevant concepts and/or terminology) or will be too short and vague.
Comment: Why do you oppose "Econ 101" questions?
Comment: The frustrating thing is we all agree that expert well-curated answers are of value; but we seem to disagree on whether _questions_ need to be expert in to order get such answers. I feel the attitude that only expert questions deserve answering (from the onset, I might add) flies in the face of three principles: 1) There no such thing as a stupid question (pro-learning principle); 2) A diverse community is more healthy than an academic clubhouse (we can coexist harmoniously); 3) Half of the beta committers agreed on a diverse site from the onset (participation in good faith).
Comment: This is not about scaling being impossible or not. I'm just disagreeing that quality of an answer is independent of the quality of the question. If I have to introduce demand and supply or other relevant basic economic concepts into every answer where they might be relevant, every answer is either blown out of proportion or just vague.
Comment: You keep ignoring my concern about lengthy and incorrect answers. The past responses have been mixtures of rhetorics and aggressive platitudes. That's of course one way of "winning" an argument, ignoring the point and insulting the other side. Given that you're a representative of the company, that's it for me, I'm out. You win. Perhaps I'll sometimes ask or answer one  question or two, but given this attitude, I'm not interested in "shaping a community" for you.
Comment: @LateralFractal The level of OP makes a huge difference. If I can expect a certain level of familiarity with Economics, I can provide much more compact and precise answers using the proper terminology.
Comment: @LateralFractal Non-expert questions cannot be answered both at good quality and at short length, this comes from the background that those OP will bring. I updated my answer.
Comment: The only relevant part of your next comment (as a response to my previous) "this is to be expected". The rest is irrelevant. To sum up, you claimed that non-expert questions can still result in expert answers. I provided the reason why I disagree. And your answer is "[this is] to be expected". Well then, I don't see a point in arguing here anymore. Especially given your subtile puns on ivory towers and bored grad students. Im out of this discussion.
Comment: Huh? I answered it thrice on length. Once on pedagogic grounds (long answers are not bad); again on infrastructure grounds (econ101 questions are usually repetitious and so we can use the duplication feature to weed the site); and again on grounds of choice and autonomy (no one says you personally have to be a teaching-orientated member; just focus on the questions you want to answer, the site is inclusive). As for incorrect, well, I dunno, isn't that within the control of the answerer? Unless you feel only people willing to answer novice questions are novices?
Comment: @LateralFractal, keep in mind that non-economists who complain about how economics has an "image problem" are pretty much the last thing that a site like this needs.
Comment: I don't think we are really far apart. I guess "Econ 101" has to do with US curriculum. I am not familiar with it but I suspect it is the firs-first Economics course taught at undergraduate University level? If this is the case, then "Econ 101" questions are bound to be either trivial "homework" questions from students or questions from "interested outsiders". Such questions may create the temptation to "preach the Principles to Laymen"  (excuse the arrogance please), but indeed, this is not the core staff that would really give value to this site. (CONT'D)...
Comment: (CONT'D) The problem is what to do when such questions relate to issues that permeate all economics. For example, the question which you vote to close and I answered, has to do with the trade-off between present and future. Should we perhaps treat it as "too broad" rather than "off-topic" and attempt to communicate to the OP that he should really narrow the scope of the question or go read his books?
Comment: @datahappy I thought the pros and cons of selective questions were already known; I updated my answer to give short reasoning.
Comment: That is a pedagogical hypothesis that implies that scaling is impossible. If that was actually true, then no one would learn anything. At least you are honest that you only want an academic post-grad _economics_ stack exchange; even if this desire is simply unreasonable. Such a site would enrich only the fraction of the people that a general economics site would; and isolates the many economists willing to "lower themselves" to answering economics questions asked by the general public. Ivory towers haven't done anyone any favours in increasing the macroeconomic literacy of the wider community.
Comment: Mechanisms for duplicate questions exist. If non-duplicate questions dovetail into the same class of answers; well this is to be expected as most disciplines strive for general purpose solutions and unified fundamentals where possible. This then becomes a discussion about what questions may bore post-grads seeking to grow or prove their engagement in the outer edges of their discipline - not what questions serve as useful on a Q&A site.
Comment: Not exactly puns; rather genuine concerns about the risk of selective commitment. Bore, as I hope you read the comment rather than skimmed it, means the risk of members that don't want to answer the same questions in-depth (i.e. expert) multiple times when they could answer interesting questions (expert-to-expert, which they always could). @corone's answer is the best I've seen so far in balancing the concerns of the prosumers and general public. Some other answers reek of the very unfunny ivory towerism I'm worried about. You do know that economics, unlike biology has an image problem?
Comment: I'm not a representative of anyone other than myself, and perhaps the enthusiast/general cohort. Disassociating a scoping argument (Meta) from the rest of the site (Beta) is oft-times [difficult](http://www.livescience.com/21837-internet-comments-angry.html), I'll grant you; but Meta is inherently more argumentative than Beta (to keep Beta clear of it). I figure being challenged on any statement you make in Meta is something you would be comfortable with. There is always a risk that a conversation becomes eristical; but an argument that there should be A+B doesn't block you from doing A only.
Comment: @nominallyrigid You can't wish away the deficiencies of incestuous academic mainstream economics by throwing fairy dust in the air and clapping your hands. But whatever. I'm done with this site.
Answer: I think lay questions should be welcome because of the profound links between economics and policy.
For policy, economics is a lot more directly important than physics or astronomy.  Consider that newspapers have daily economics sections, but at most weekly science sections.  Economical knowledge is used to take policy decisions that affect everybody on a day-to-day basis.  Therefore, in a democracy, it is important that laypeople have some understanding of economics.
For example, in the Eurozone, there is a debate ongoing in how to improve the economy: austerity or stimulation?  Austerity has been the main policy so far, but many — including people with Economics PhDs — disagree.  If I am to have a fact-based opinion, I need some understanding of the situation.
Therefore, I very much hope that lay questions will remain welcome here.
Answer: I fully agree with datahappy and LateralFractal's response.
I think the site should be as open and accepting as possible. The fact that there was an Econ SE beta before that didn't make it (despite the fact that economics is a very widely spread subject) is another manifestation of the usual snobbery that is so common among some (majority of?) economists. I say this as a student, as a researcher and as a teacher of the area.
Please, please, let's not go that way.
Comment: I think it's exactly the opposite: the previous site didn't make it _precisely because_ it wasn't snobbish enough, and by failing to provide enough expert-level content discouraged all experts from participating. No researcher wants to wade through vague popular-level questions or ideologically tendentious tirades to ask her question about a specific model or institution or algorithm or data source.
Comment: @nominallyrigid The problem with that outlook is you assume the site is just for you. It isn't. Precisely because there is otherwise nowhere on the Stack Exchange network to park "non-expert" or "non-mainstream" economic questions. A academic boys-club of sorts is of little interest to me and adds less value to the internet than a broader site; and so I've not generally revisited this site in weeks.
Answer: Expert question or not, the question must be interesting enough to be useful for a more broad community. The main entry points of the site are the search engines. So try to find questions that people ask often (in other forums for example), and ask here, and provide good answer for it. Even if the questions are trivial, often the trivial looking questions are the most viewed and highest voted ones on the sites.
If we can't turn all the stats "okay" or better, then we risk that the site fails again. I think pushing the site through the Beta status should be the top priority isn't it?
Comment: If you scroll the questions, you will see mainly  "undergraduate theoretical" questions (educational aspect) and "current issues" questions (applied economics aspect), rather than "research-level" questions. As I wrote in another thread, SE is about getting expert _answers_ to _any_ questions -and this is what is happening, on its own.


Find nearest postcode to Latitude Longitude in MySQL

Question: I have a table Postcode which holds all UK postcode (approx 1.8m i think)
CREATE TABLE `Postcode` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Postcode` varchar(8) DEFAULT NULL,
  `Postcode_Simple` varchar(8) DEFAULT NULL,
  `Positional_Quality_Indicator` int(11) DEFAULT NULL,
  `Eastings` int(11) DEFAULT NULL,
  `Northings` int(11) DEFAULT NULL,
  `Latitude` double DEFAULT NULL,
  `Longitude` double DEFAULT NULL,
  `LatLong` point DEFAULT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `Postcode` (`Postcode`),
  KEY `Postcode_Simple` (`Postcode_Simple`),
  KEY `LatLong` (`LatLong`(25))
) ENGINE=InnoDB AUTO_INCREMENT=1755933 DEFAULT CHARSET=latin1;

What I want to achieve is...Given a co-ordinate, locate the postcode nearest to the co-ordinate. Problem is I'm having a bit of an issue with the query (actually in a stored procedure) I've written to do this. The query is:
SELECT
    Postcode
FROM
    (SELECT
        Postcode,
        GLENGTH(
            LINESTRINGFROMWKB(
                LINESTRING(
                    LatLong,
                    GEOMFROMTEXT(CONCAT('POINT(', varLatitude, ' ', varLongitude, ')'))
                )
            )
        ) AS distance
    FROM
        Postcode
    WHERE
        NOT LatLong IS NULL) P
ORDER BY
    Distance
LIMIT
    1;

The problem I'm having is that the query takes some 12seconds to run and I cannot have it take that long to get a result. Can anyone think of any ways I can reliably speed this query up?
(Here's the explain for the query)
id select_type table      type possible_keys key    key_len ref    rows    Extra
1  PRIMARY     <derived2> ALL  (NULL)        (NULL) (NULL)  (NULL) 1688034 Using filesort
2  DERIVED     Postcode   ALL  LatLong       (NULL) (NULL)  (NULL) 1717998 Using where

I've been trying to think of a way to narrow down the initial amount of data that I must perform the distance calculation on, but I haven't been able to come up with anything that doesn't restrict to finding postcodes within a given distance.
Comment: did you create index, PKs, what is the table structure? to speed up the query
Comment: @jcho360 Index's and primary keys are already created but don't help a create deal for the query i'm using unfortunately. The table structure is already shown above...
Answer: Maybe try something along the lines of:
SELECT Postcode, lat, lon
FROM
(
SELECT Postcode, MAX(latitude) AS lat, MAX(longitude) AS lon
FROM PostCode

-- field name
GROUP BY Postcode

HAVING MAX(latitude)<varLatitude AND MAX(longitude)<varLongitude

LIMIT 1
) AS temp

which will basically bring the postcode whose lat and lon are less than the ones you specify but greater than any other lat/lon combination that is less than your vars; so effectively the closest lat/lon to your vars, hence the closest postcode. You can try the same using MIN and greater then instead to go the other way round.
The above will only get you a single result/postcode. If you're looking to have something niftier with like finding a group of postcodes given in a specific radius of lat/long then you should have a look at the formula explained at https://developers.google.com/maps/articles/phpsqlsearch_v3#findnearsql
Comment: Hmm, I can't seem to get this method to work at all, it seems to be returning an awful lot of unwanted and inaccurate results.
Comment: Alas that does not appear to work either. I shall see what else I can come up with. Thank you ever so much for all of your help, it's greatly appreciated!!!
Comment: This seems to get me the correct co-ordinates, but the postcode returned in the sub-query is not the postcode that matches the returned co-ordinates. This would be down to the aggregate functions, so I would have to get the postcode using the co-ordinates returned, which means they then need to be indexed too.

Im going to investigate this solution more though, as it does narrow down the data very quickly.
Comment: @JohnHenry sorry my mistake, HAVING should be used instead of WHERE, made the update as needed in the answer
Comment: the difference between the two is that although similar, HAVING will return records based on the aggregate functions, whereas WHERE will not take them into account. Also if you add GROUP BY postcode and a LIMIT you should be able to get a list of closest postcodes
Comment: mmm, I don't have a mysql instance to test at the moment but my last idea would be to add the WHERE condition(latitude<varLatitude and same for long) above the GROUP BY Postode and maintain the HAVING as it is. So WHERE will filter all the rows, remaining rows will be grouped into blocks by postcode, and the row groups will be filtered by HAVING.
Answer: I've written a tutorial on pretty much exactly what you're after.
Basically, you're on the right lines. In order to improve the efficiency of the search, you'll need to reduce the number of GLength() calculations made by making use of a spatial index on your LatLong field. If you restrict the search to a refined area, such as polygon 10 miles around the point you're comparing the postcodes to, you'll find the query is much quicker.


Prove (or disprove) that these numbers are Liouville numbers

Question: How would I prove (or disprove) that these following numbers are Liouville:
$\displaystyle\sum^\infty_{n=0}\frac{1}{\left(n!\right)!}$
$\displaystyle\sum^\infty_{n=0}\left(n!\right)^{-n!}$
Both of these numbers seem to have continued fractions that have mirroring* terms and terms that grow larger and larger very rapidly, without bound.
And I'm stuck. I know what makes a Liouville number what it is, but still, I'm stuck.
Answer: Usually in these cases you should work in this way:
$$A_n=\sum_{i=0}^n a_i$$
Since $a_n\to 0$ very fast and $A_n$ is a rational number you may hope that $\forall n$ large enough
$$\forall c>0,\ \ \sum_{i=n}^\infty a_i<(den(A_n))^{-c}$$
For example, in the first case $$den(A_n)=(n!)!$$ while for $n$ large enough
$$\sum_{i=n}^\infty a_i<\frac{2}{((n+1)!)!}$$
since
$$\frac{2(n!)!^c}{((n+1)!)!}\to 0$$
for all $c$ you have done


mongodb morphia save with id not override

Question: mongo morphia basicDAO.save() basicly does
save(T entity)
Saves the entity; either inserting or overriding the existing document

If entity.id is NOT null, morphia will try to override existing document, is there a way to let morphia throws an duplicate key Exception (like mongodb does) instead?
Comment: Just curious - what is your @Id field? Why not use ObjectId and you're pretty much guaranteed to not have conflicts
Answer: Your best approach is for you to check if the document already exists. The most performant is to use:
db.collection.find({_id: "myId"}, {_id: 1}).limit(1)

And then check for null or not. 'findOne' will actually load the document from the database so avoid that.


Question on complete discrete valuation field.

Question: Let $F$ be a complete discrete valuation field and $f(X) = X^n + a_{n-1}X^{n-1} +\cdots+ a_0$ is an irreducible polynomial over $F$. How to show that
a) $ v(a_0) > 0$ implies $v(a_i) > 0$ for $i=1,...,n-1$;
b) if $v(a_0) \leq 0$, then $v(a_0) = \min(v(a_i)\mid i=0,...,n-1)$.
Edit. This is Exercise 2 on page 38 in Fesenko and Vostokov, Local Fields and Their Extensions.
Comment: You complain that it has not received enough attention. But what attention have you showed it, yourself? What do you think? You've only just stated the problem. Is this homework?
Answer: Hints:

If $L\mid F$ is a splitting field of $f$, then there is a unique extension $w \mid v$ of $v$ to $L$.
If $\alpha$ is a root of $f$ in $L$, then $w(\alpha) = w(\sigma(\alpha))$.
write $a_i$ as a symmetric polynomial in the roots $\alpha_i$ of $f$ and use the triangle inequality to get estimates on $v(\alpha_i)=w(\alpha_i)$.


Find legacy id of newly created node

Question: I have 3 non-drupal tables : items, item_actions, actions.
 items(id, title, body, published_at);
 item_actions(item_id, action_id);
 actions(id, name);

I were able to migrate items to drupal 7. Now i want to migrate actions but since i don't know the node_id of the newly migrated items just the legacy id it is throwing an error.
How do i find the node_id knowing the legacy_id so that it finds the right node and migrate related content.
$query = Database::getConnection('default', 'for_migration')
  ->select('actions', 'actions')
  ->fields('actions', array('id', 'name'))
  ->orderBy('id', 'DESC');
// Join values from the action_items.
 $query->leftJoin('action_items', 'ai', '(actions.id = ai.action_id)');
 $query->addField('ai', 'item_id', 'item_list');

Here is the error:
The referenced entity (node: 123456) is invalid.

update
   The migration was done with the migration module. So i had to write class migration and use queries like the one above to migrate to D7 the items table.
Can i create a table in the drupal DB and add the ids(old and new) for example: migrate_nodes(legacy_id, drupal_node_id) .
How do you capture the node_id?
I am new to drupal so this is still a learning process, thanks.
Comment: For getting help on this issue, please provide more details on how you migrated your non-Drupal entities. Did you create custom entities or do you use node types (bundles). Did you use custom code for migrating your entities or did you do so by using database queries? Provide your sources and the steps you conducted for migration, and you might get suggestions on how to rebuild your relations. As for now your description is too broad to give qualified answers without too much guessing.
Answer: How did you migrate the content from the nond-drupal tables to nodes?  Module or custom code?
I would suggest a 'custom' migration routine/module (if it is a lot of data you can do this as a cron and/or batch job - that is a separate discussion).
Any case, in your custom routine, when you migrate each record (so read a record form your table and create a new node) from items and actions - you will be able to 'capture' the node id (nid) if the new node.  Save this value to your 'old' items/actions tables (new field required).  Now when you step through your item actions table you can use the nid saved in items and actions as reference values.

Find legacy id of newly created node


I install ultimate cron and I saw that errors

Question: I have all this error but when i am running cron without cron ultimate all run perfect but with cron ultimate i got that errors... Could anyone help i really need help here:
    exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error
    or access violation: 1064 You have an error in your SQL syntax; check
    the manual that corresponds to your MySQL server version for the right
    syntax to use near '))' at line 1' in
    /var/www/html/drupal7.36/includes/database/database.inc:2171
    Stack trace:
    #0 /var/www/html/drupal7.36/includes/database/database.inc(2171): PDOStatement->execute(Array)
    #1 /var/www/html/drupal7.36/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array)
    #2 /var/www/html/drupal7.36/includes/database/query.inc(858): DatabaseConnection->query('DELETE FROM {er...', Array, Array)
    #3 /var/www/html/drupal7.36/sites/all/modules/bla/includes/bla.functions.inc(245): DeleteQuery->execute()
    #4 /var/www/html/drupal7.36/sites/all/modules/bla/bla.module(56): bla_clean()
    #5 [internal function]:bla_cron()
    #6 /var/www/html/drupal7.36/sites/all/modules/ultimate_cron/ultimate_cron.module(941): call_user_func('bla_...')
    #7 [internal function]: _ultimate_cron_run_hook('bla_...', Array)
    #8 /var/www/html/drupal7.36/sites/all/modules/background_process/background_process.module(574): call_user_func_array('_ultimate_cron_...', Array)
    #9 /var/www/html/drupal7.36/sites/all/modules/background_process/background_proces
    s.module(503): background_process_service_execute('uc:error_log_ji...', false)
    #10 [internal function]: background_process_service_start('uc%3Aerror_log_...')
    #11 /var/www/html/drupal7.36/includes/menu.inc(519): call_user_func_array('background_proc...', Array)
    #12 /var/www/html/drupal7.36/index.php(21): menu_execute_active_handler()
    #13 {main}

function blabla_clean() {
  $number = variable_get('blabla_number_select');
  // Keeps values equal to the number that user had selected.
  $query = db_select('blabla', 'j')
    ->fields('j')
    ->range(0, $number)
    ->orderBy('j.timestamp', 'DESC');
  $ids = $query->execute()->fetchCol();

  // Deletes all the other values.
  db_delete('blabla')
    ->condition('wid', $ids, 'NOT IN')
    ->execute();
}

Answer: The issue isn't Ultimate cron, per se. It's your custom bla module; it's running some function called bla_clean() that's building a Delete SQL query with broken syntax. When executed, it's producing the error.
You're using the NOT IN operator incorrectly. Here's a post that demonstrates a NOT IN within a query.


Construction of a Triangle

Question: The method which I adopt for constructing the triangle is very similar to the method used in the construction of the batman curve.
If you are not familiar with this technique I suggest you look at this answer concerning the construction of the batman curve so you may become familiar with the method.
Okay So I am trying to construct a right-angled triangle. First I start with this equation:
$$|x|+|y|=1$$
This produces a square as such:

Now to cut this in half I turn the absolute function into it's root representation and swap the square and radical for $x$:
$$\left(\sqrt{x}\right)^2+\sqrt{y^2}-1=0$$
that produces this:

Now this is the first part of the equation.
Second part focuses on a line $x=0$ from $x=-1$ to $x=1$. This is what I came up with:
$$x\sqrt{1-y^2}=0$$

Now in theory I should be able to multiply the two expressions from the LHS of equation $1$ and $2$ to get my desired triangle. However this is not the case and the $2^{\text{nd}}$ expression becomes hidden. However what I have found is that if you add an arbitrarily small value to $x$ it becomes visible but it is not geometrically a triangle. So I have devised a hypothesis about the expression.
$$\left(\left(\sqrt{x}\right)^2+\sqrt{y^2}-1\right)x\sqrt{1-y^2}=0$$
The equation that doesn't work.
$$\left(\left(\sqrt{x}\right)^2+\sqrt{y^2}-1\right)\left(\lim_{\epsilon\to0} x + \epsilon\right)\sqrt{1-y^2}=0$$
This is my hypothesis.
So my questions are:
Am I going down the right track in constructing a triangle if so:

Is there anything I can do to improve my current work?
Why is it that the second expression gets hidden?

If not:

What route should I be taking?
Is there a general equation for a triangle?
Comment: I believe the second expression "gets hidden" because of some simplification made by whatever program you are using to plot these level sets. Your limiting procedure won't help, as $\lim\limits_{\epsilon\to 0}x+\epsilon=x$.
Comment: Note that one reason the equation last displayed fails, is that it includes the entire $y$ axis. [See my answer for another approach.]
Comment: @coffeemath Do you mean $x\sqrt{1-y^2}=0$ fails? Because I'm pretty certain it doesn't.
Comment: If $x\sqrt{1-y^2}$ is a *factor* of the overall equation set equal to zero to get the shape, then that shape will include all values $(x,y)$ where this factor is zero. In particular it will include all points of the form $(0,y)$ and also all points of the form $(x,\pm 1).$
Answer: The approach is based (correctly) on the fact that setting the product of two expressions $A(x,y),B(x,y)$ to $0$ produces the union of the two curves represented by setting them separately to zero, and also using the fact that $\sqrt{u}$ is only defined for $u \ge 0.$ I can see how your first expression, which I'll call $A(x,y)=(\sqrt{x})^2+\sqrt{y^2}-1$, to zero results in the right half of the square you have drawn in red.
However, in creating the vertical blue segment, you are dealing with imposing two conditions at once: $x=0$ and $-1 \le y \le 1$. Whatever you do for this will involve an intersection (rather than a union) of two zero sets, and maybe the best way to do that if the expressions are $E,F$ is to use the expression $E^2+F^2$, which will capture the intersection of the two relations $E=0,F=0$ when used as a factor. Now to get at the inequality $-1 \le y \le 1$ you could employ the expression $\sqrt{1-y^2}-\sqrt{1-y^2},$ which will be defined exactly when $-1 \le y \le 1$, and will be zero in that interval.
So a version that seems to do the job would be obtained by multiplying the expression giving the right half square by the suggested sum of squares here. This is
$$[(\sqrt{x})^2+\sqrt{y^2}-1]\cdot [x^2 + (\sqrt{1-y^2}-\sqrt{1-y^2})^2]=0.$$
ADDED:
The OP Alizter has pointed out in a comment that Wolfram Alpha did not produce the graph correctly using the cooked up second factor here, which involves an expression subtracted from itself internally to the expression. My guess is that the software simplified that part to $0$ before evaluation, and so did not get a reswtriction on $y$. [Note one should be using implicit plot for this equation in $x,y$, maybe with some "tolerance", to have a hope of getting it right.]
So here is another factor designed to capture the vertical line segment:
$$B(x,y)=x^2 + (\sqrt{y+1})^2 + (\sqrt{1-y})^2 -2)^2.$$
Then $B(x,y)=0$ iff both of the squared expressions are zero, and the second squared term is undefined when $|y|>1$, and is otherwise zero. So I think the relation $B(x,y)=0$ should produce exactly the vertical line segment joining $(0,-1)$ to $(0,1)$. Using this updated $B(x,y)$, which is hopefully not as likely to be simplified by plotting software, along with the already mentioned factor $A(x,y)$ noted above (and used in OP), the triangle as a whole "should" have equation $A(x,y)\cdot B(x,y)=0.$. I say "should" because I don't know how the software would work on it, and as mentioned I'd suggest at least using some kind of implicit plot, maybe with a tolerance built in to allow for slight errors in a calculated thing being exactly zero.
Comment: Isn't $$\sqrt{1-y^2}-\sqrt{1-y^2}=0?$$
Comment: @Alizter : Yes it is, but it is only defined for $y \in [-1,1]$, and that is why the expression is used, to keep the solution set of the equation from containing any points of the form $(0,y)$ for which $|y|>1$, since if these points are not excluded the vertical line will extend beyond where it is wanted, making the result into two sides of a triangle and a line through their ends, rather than having it all a simgle triangle.
Comment: @cofeemath Why does [this](http://www.wolframalpha.com/input/?i=%28x%C2%B2%2B%28%E2%88%9A%281%E2%88%92y%C2%B2%29%E2%88%92%E2%88%9A%281%E2%88%92y%C2%B2%29%29%5E2%29%3D0) happen then?
Comment: @Alizter See the part after 'ADDED"; basically I think the software simplified that $A-A$ term before evaluating.

Construction of a Triangle


Exchange 2010 + Sharepoint on single server

Question: I seem to have the most unideal server setup so here we go:
Situation: 1 Server (2008 Std), Exchange 2010 (CAS + HUB) and Sharepoint Services 3.0 installed on it.
Mission: To get OWA working at: mail.systems.com and Sharepoint at, intranet.systems.net
Execution: you tell me how, becuase I do not know where to start :(
Shamil
Comment: I would strongly advise you not to do this.  And if only one server is availble to run the WSS instance in a VM.  I can only see endless headaches and downtime coming out of this setup.
Answer: I've been advised not to do this, and henceforth, I abandon this attempt.
Comment: So you choose yourself instead of the guy who helped you... interesting ;)
Answer: This is not really recommended as SharePoint tends to take over the .NET and IIS configurations and generally wreak havoc for non-SharePoint things. It can be done (see Small Business Server as proof), but it generally isn't worth the effort. Virtualize if you can, SharePoint web servers run great as a VM and you can host the SQL inside the VM for low traffic, or on your Exchange box or elsewhere if necessary.


Sorting an array of values by shifting to the right

Question: I have to make a method that sorts an array of values going from lowest value to the highest. The way these  functions are supposed to work is that it grabs each value, tries to put them in rising order going from left to right by shifting every bigger value to the right.
I have made the following functions:
int findIndex(double *arr, double num, int length)
{

   for (int i = 0; i < length; i++)
   {
      if (arr[i] > num)
         return i;
     }
   return length - 1;
}

void placeOnIndex(double *arr, double num,int index, int length)
{

   if (length > 1 && arr[index] != num)
   {
       for (int i = length - 1; i > 0; i--)
       {
            arr[i] = arr[i - 1];
       }

       arr[index] = num;
   }
}

void insertSort(double* arr, int length)
{
   for (int ix = 0; ix < length; ix++)
   {
       double num = arr[ix]; //Current value to put as far to the left as possible
       int index = findIndex(arr, num, ix+1);  //Locates index to put it
       placeOnIndex(arr, num, index, ix+1); //Uses the index to put in the right place
   }

}

void main()
{
   double arr[4] = {1,8,4,5};
   insertSort((arr), 4);
}

My problem is that the output with this array becomes:
   1,1,5,8
Apparently it sometimes overrides the second element in my array. Sometimes it works and sometimes it doesn't. If the array is longer even more values are overridden.
I'm sorry if it looks confusing, english isn't my native tongue.
Comment: In `placeOnIndex` when `i == index` you place `num` in `arr[index]`. But what happens to the value that was stored in `arr[index]` beforehand?
Answer: This line
for (int i = length - 1; i > 0; i--)

causes all the elements to move right, not just the ones that should move.
You need
for (int i = length - 1; i > index; i--)


Python Regular Expression Escape or not

Question: I need to write a regular expression to get all the characters in the list below..
(remove all the characters not in the list)
allow_characters = "#.-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

I don't know how to do it, should I even use re.match or re.findall or re.sub...?
Thanks a lot in advance.
Answer: Don't use regular expressions at all, first convert allow_characters to a set and then use ''.join() with a generator expression that strips out the unwanted characters.  Assuming the string you are transforming is called s:
allow_char_set = set(allow_characters)
s = ''.join(c for c in s if c in allow_char_set)

That being said, here is how this might look with regex:
s = re.sub(r'[^#.\-_a-zA-Z0-9]+', '', s)

You could convert your allow_characters string into this regex, but I think the first solution is significantly more straightforward.
Edit: As pointed out by DSM in comments, str.translate() is often a very good way to do something like this.  In this case it is slightly complicated but you can still use it like this:
import string

allow_characters = "#.-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
all_characters = string.maketrans('', '')
delete_characters = all_characters.translate(None, allow_characters)

s = s.translate(None, delete_characters)

Comment: "convert your `allow_characters` string into this regex" isn't as complicated as it sounds; it's just `r'[^{}]+'.format(allow_characters)`. But I agree that the first solution is clearer.
Comment: @F.J the set idea is extremely easy to understand but is there also a performance concern being taken into consideration here.. is one super fast against the other one? Is there an easy way to figure out which character should be escaped in the regular expression, why dash need to be escaped?
Comment: Dash needs to be escaped if it is within a character class because otherwise it will be interpreted as a range separator, for example `[a-z]` matches all lowercase letters, and `[a\-z]` would match "a", "-", or "z".  You can use `re.escape()` to automatically do the escaping, just make sure this is the first step in the transformation (before you add the `[` and `]+` to the ends).
Comment: Also I wouldn't be too surprised if the set solution was faster than regex anyway.
Comment: @DSM Nope, the wording of the question is slightly confusing but the OP wants to keep all characters in `allow_characters` by removing everything else.
Comment: @F.J: ah, you're right.  I failed even given multiple attempts to get that right. :^)  I think the only common option you didn't mention was `translate`, which is often very fast.
Comment: Oh good point, yeah I will add that to the answer... on second thought, not really sure how to apply `translate` here since I don't see a way to do "delete every character except these".

Python Regular Expression Escape or not


Forward DNS requests from router

Question: I've got a server behind a router and I'm trying to use my server as my DNS and DHCP service. I have them configured correctly, and I can connect out through, but I cannot seem to get my router to forward DNS requests to the server. In my router settings I've disabled DHCP, I port forwarded port 53 to the server and I set the DNS to my IP of the server, and If I set a user computer to statically use the DNS in the adapter settings I can connect fine, but if I use dynamic settings, I get an error in the network and sharing center saying I could not find the DNS server.
I have a netgear R6300v2 router and a server running windows server 2008 r2. So, what gives? what settings do I have to change in my router for it get the DNS correctly? Statically coding the computers isn't really an option so please help? Thanks!
Answer: The reason it's only working when you set the DNS server addresses statically, is that the DHCP Server is not providing the DNS information to clients. In order for DHCP to provide the DNS Server address to a client, the DNS Server option needs to be enabled:
Per Technet (http://technet.microsoft.com/en-us/library/dd183679%28v=ws.10%29.aspx)

To define a new option
<code>Open DHCP.

In the console tree, click the applicable DHCP server.

On the Action menu, click Set Predefined Options.

In Predefined Options and Values, click Add.

In Option Type, type the required information to define the new option, and then click OK.
</code>

http://technet.microsoft.com/en-us/library/cc958941.aspx

Table 4.6 Common Information Option Types
Code
Description
3
Router
6
DNS server
15
DNS domain name
44
WINS server (NetBIOS name server)
45
NetBIOS datagram distribution server (NBDD)
46
WINS/NetBIOS node type
47
NetBIOS scope ID
Clients can receive these values to set their TCP/IP configurations,
  during the period of the lease.

Edit to note that Routers do not by default forward DHCP requests, since DHCP uses Broadcasts to find DHCP Servers. You would then need to configure your router or another server to function as a DHCP proxy.
Comment: 127.0.0.1 is localhost, meaning "this computer" or "myself", meaning that if you assign 127.0.0.1 as the DNS server in your DHCP options then all of your DHCP clients will look to themselves (localhost - 127.0.0.1) for DNS. - http://en.wikipedia.org/wiki/Localhost
Comment: under server options I have an option name "006 DNS Servers" with a value of 127.0.0.1. is that what you are referring to making? If so, it is already there.
Comment: Ah found, the problem, it was in there. I added the server IP address as another value (ie 192.168.1.42) and it made it work fine. My question is shouldn't 127.0.0.1 have worked as well?
Comment: I actually discovered this recently on my DHCP server. It defaults to the localhost when you configure the server as a DHCP server and create a scope.

Forward DNS requests from router


Javascript (Node.js) - How to read and process multiple line provided as an input to a function?

Question: I am practicing to code in various languages and hence, am a newbie to node.js. The site I am using to practice the code mostly gives me multi-line inputs as an argument to my function, which I don't know how to process (I tried using split on \n, but, that, doesn't work).
Following is a code that, gets multi-line input and then, this input is passed to a function. Can you please tell me how can I read/process the input in-order to store each line of an input in an array as a data item ?
function main(input) {
    //Enter your code here
    // var arr = input.split("")
    process.stdout.write(input[6]);
}

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;
});

process.stdin.on("end", function () {
   main(stdin_input);
});

Thanks'
Answer: Splitting on a new line works for me.
function main(input) {
    //Enter your code here
    var arr = input.split("\n")
    process.stdout.write(JSON.stringify(arr));
}

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;
});

process.stdin.on("end", function () {
   main(stdin_input);
});

It's important to note that process.stdout.write can only write a string. Trying to pass an array as an argument will cause an error.
Comment: you rightly pointed out, that, process.stdout.write will only print a string, which is why, I was getting an error.
Answer: just a idea my code is just for  many string or number  have space between for example if you want sum two number we write in terminal : 23 56

notice i use here string_decoder for any one want to raplace number
with string

const {StringDecoder} = require('string_decoder');
const decode = new StringDecoder('utf8');

const sum = (a, b) => {
    let operation = a + b;
    return console.log('result is : ', operation);
}

process.stdin.on('readable', () => {
        const aa = process.stdin.read(); // read string from REPL
        const buffer = Buffer.from(aa);
        const j = decode.write(buffer).split(' ');
        const a = +j[0];
        const b = +j[1];
        // console.log(a + b)
        if((a & b) != null) // check if the value not empty
        {
            sum(a, b);
        }
    });


Differentiate using the chain rule. Do not simplify.

Question: $$y = (\cos x)^{(\sin x)^x}$$
I'm not sure at all how to solve this problem. I know that the derivative of $a^x$ is $a^{x}ln(a)$. I know the derivative of $\cos(x)$ is $-\sin(x)$ and that the derivative of $\sin(x)$ is $\cos(x)$.
I assume that I start with $(\sin x)^x$. Will the derivative of that part be
$(\sin x)^{x}*\ln(\sin(x))*\cos(x)$
Does this rule work with the chain rule? Should I differentiate the $\ln(\sin(x))$ once more? I don't think so, but I'm quite confused, so a clarification would be nice.
This is the first problem which has so many "layers" and I'm not sure how to put the rest of the equation into the chain rule.
Thank you for the help.
Comment: To get more than one character in an exponent or subscript, enclose them in braces: (\cos x)^{(\sin x)^x} renders to $(\cos x)^{(\sin x)^x}$
Comment: I find that keeping track of where I am in the chain rule is more difficult with a stack of exponents, and so I would write out functions $f,g,h(x)$, solve the chain rule in this (slightly) more abstract case. Then you can separately differentiate each to get the needed $f',g',h'(x)$ to write the final expression.
Comment: @CuddlyCuttlefish I think that would be the best solution and it's what I was trying to achieve (I am not familiar with the methods used by Bill Cook or Paramanand Singh). Could you be so kind and provide an answer using this method?
Comment: I posted what I would do - note that it is equivalent because they all require logarithmic differentiation. I prefer it because nearly all of the arithmetic difficulty is delayed until simplification, but that seems (to me) like less of a tradeoff because all of the methods require some simplification to neaten the answers.
Answer: You need a combination of chain rule as well as logarithmic differentiation. Let the function be denoted by $y = f(x)$ so that $$y = (\cos x)^{(\sin x)^{x}}$$ and on taking logs we get $$\log y = (\sin x)^{x}\log\cos x$$ Further taking logs gives us $$\log\log y = x\log\sin x + \log\log\cos x$$ and then we differentiate using chain rule to get $$\frac{1}{\log y}\cdot\frac{1}{y}\cdot\frac{dy}{dx} = \log \sin x + x\cot x + \frac{1}{\log \cos x}\cdot\frac{-\sin x}{\cos x}$$ and finally we get
\begin{align}
\frac{dy}{dx} &= y\log y\left(\log\sin x + x\cot x - \frac{\tan x}{\log\cos x}\right)\notag\\
&= (\cos x)^{(\sin x)^{x}}(\sin x)^{x}\log \cos x\left(\log\sin x + x\cot x - \frac{\tan x}{\log\cos x}\right)\notag\\
\end{align}
Update: Note that the method of logarithmic differentiation is symbolic and does not take care of fine details. It does produce the correct answer, but there is a subtle mistake in above argument.
First of all note that the function $y = f(x) = (\cos x)^{(\sin x)^{x}}$ is defined only when both $\sin x$ and $\cos x$ are positive which means that $x$ lies in the first quadrant (excluding end points of the quadrant). Even if we assume that the value of $x$ is in first quadrant then $\log \cos x$ is defined but already negative and hence taking a second log is not justified so that we can't have an expression like $\log\log\cos x$. The way out is to differentiate $\log y = (\sin x)^{x}\log \cos x$ using product rule taking $$u = (\sin x)^{x}, v = \log\cos x, \log y = uv$$ In order to proceed further we need find $\dfrac{du}{dx}$ and for that we take logs to get $\log u = x\log \sin x$ and on differentiating we get $$\frac{1}{u}\cdot\frac{du}{dx} = x\cot x + \log \sin x$$ or $$u' = \frac{du}{dx} = (\sin x)^{x}(x\cot x + \log \sin x)$$ We then have $$\frac{1}{y}\cdot\frac{dy}{dx} = uv' + u'v = (\sin x)^{x}(-\tan x) + (\sin x)^{x}(x\cot x + \log \sin x)\log\cos x$$ or $$\frac{dy}{dx} = y(\sin x)^{x}\log\cos x\left(x\cot x + \log \sin x - \frac{\tan x}{\log\cos x}\right)$$ and putting value of $y$ we get the same answer as before.
Comment: I've never seen this method, but thank you for the clear explanation. I will try to understand it.
Comment: You left out "implicit differentiation" from the list of techniques applied here.
Comment: @PaulSinclair: where have I used implicit differentiation?
Comment: @DanielWaleniak: The method of logarithmic differentiation is pretty standard one available in introductory calculus textbooks. It should be used if you get an expression of type $\{f(x)\}^{g(x)}$ where both the base and exponent are variables. If either of base or exponent is constant then you know the simple rules $(x^{a})' = ax^{a - 1}, (a^{x})' = a^{x}\log a$.
Comment: ${d\over dx} \log \log y = {1 \over \log y}\cdot{1 \over y}\cdot {dy \over dx}$ is implicit differentiation. Not a major omission, but I thought it worth noting that the technique had been used.
Comment: @PaulSinclair: Thats chain rule as far as I am aware of. In case the function $y$ is given implicitly like an expression $f(x, y) = 0$ which can not be transformed into an explicit version $y = g(x)$ then we differentiate the whole equation $f(x, y) = 0$ with respect to $x$ to get an equation containing $x, y, y'$ and from it we find $y' = dy/dx$. This process is normally called "differentiation of implicit functions". But the rule used in this process is called chain rule.
Comment: Implicit differentiation is an application of the chain rule, and if you follow your own description you will see that the only thing that doesn't apply here is the claim that $y$ cannot be solved for. But that is simply a common cause for implicit differentiation to be used. It is not a requirement for it to be "implicit differentiation". Even though $y$ can be solved for here, you chose not to, but solved it specifically by the method you just described.
Comment: @PaulSinclair As long as functions of  $x,y$ are not structured together and it is possible to express one in terms of the other it is explicit and so its differentiation.
Comment: @PaulSinclair: Not to quibble so much for almost trivial stuff, but I want to reiterate that there is no specific rule called "implicit differentiation", rather there is a "process to differentiate implicit function using chain rule" and some textbook describe this process under the heading "implicit differentiation". "Implicit differentiation" is not a rule/theorem like sum, product, quotient , chain rule of differentiation.
Comment: Please google "implicit differentiation". Just because you don't use the terminology does not mean that it is not widely used and recognized. It isn't a "rule/theorem", but is a very common name given to the whole technique.
Comment: My prof just covered this method today. I guess I worked a bit too far ahead but thank you for the very detailed explanation!
Answer: I find it very easy to make mistakes when using the chain rule with exponent towers or just large functions in general. Instead, let's define the following functions and their derivatives:
$$f(x) = \ln(x) \Rightarrow f'(x) = \frac{1}{x}$$
$$g(x) = \cos(x)\Rightarrow g'(x) = -\sin(x)$$
$$h(x) = \sin(x)\Rightarrow h'(x) = \cos(x)$$
Then we know that
$$f(f(y)) = xf(h(x)) + f(f(g(x))$$
Apply the chain rule and product rule to differentiate both sides:
$$f'(f(y))f'(y)y' = [xf'(h(x))h'(x) + f(h(x))] + [f'(f(g(x))f'(g(x))g'(x)]$$
$$y' = \frac{xf'(h(x))h'(x) + f(h(x)) + f'(f(g(x))f'(g(x))g'(x)}{f'(f(y))f'(y)}$$
Replace with the functions
$$y' = \frac{x\frac{1}{\sin(x)}\cos(x) + \ln(\sin(x)) + \frac{1}{\ln(\cos(x))}\frac{1}{\cos(x)}(-\sin(x))}{\frac{1}{(\sin(x))^x\ln(\cos(x))}\frac{1}{(\cos(x))^{(\sin(x))^x}}}$$
This is equivalent to the accepted answer (change the divided trig functions to $\tan$ or $\cot$ and flip the bottom over).
I find this much easier because you compute $3$ simple derivatives, the natural logarithm, sine, and cosine. The only trick was using the logarithm to make it possible to express the function in simple form; but any time you have $(something)^x$, you should expect to do something equivalent to logarithmic differentiation.
After that, just apply the product rule and the chain rule to differentiate each side, and then divide by some terms from the LHS to isolate $y'$. For me at least, I'm much less likely to make arithmetic errors by pushing around letters than I am with actual values.
Then you can just replace each of the $f,g,h$ and $f',g',h'$ in the expression and simplify if necessary.
Answer: Generally you want to use exponentials and logs to unravel complicated powers.
$y = \cos(x)^{(\sin(x))^x} = e^{\ln\left(\cos(x)^{(\sin(x))^x}\right)}=e^{(\sin(x)^x\ln(\cos(x))} = e^{e^{\ln((\sin(x))^x)}\ln(\cos(x))} = e^{e^{x\ln(\sin(x))}\ln(\cos(x))}$
Now differentiating is a little more straight forward -- I guess...
$y' = e^{e^{x\ln(\sin(x))}\ln(\cos(x))} \cdot \dfrac{d}{dx}\left[e^{x\ln(\sin(x))}\ln(\cos(x))\right]$
$= e^{e^{x\ln(\sin(x))}\ln(\cos(x))} \cdot \left( \dfrac{d}{dx}\left[e^{x\ln(\sin(x))}\right]\ln(\cos(x))+e^{x\ln(\sin(x))}\dfrac{-\sin(x)}{\cos(x)}\right)$
$= e^{e^{x\ln(\sin(x))}\ln(\cos(x))} \cdot \left( e^{x\ln(\sin(x))}\left(\ln(\sin(x))+x\dfrac{\cos(x)}{\sin(x)}\right)\ln(\cos(x))+e^{x\ln(\sin(x))}\dfrac{-\sin(x)}{\cos(x)}\right)$
At this point, you could start collapsing exponentials and logs back down (if you needed to simplify).


Help with rational functions word problem.

Question: When looking at a rational function, Jamal and Angie have two different thoughts. Jamal says that the function is defined at $x = -3, x = -4$, and $x = 6$. Angie says that the function is undefined at those $x$ values. Describe a situation where Jamal is correct, and describe a situation where Angie is correct. Is it possible for a situation to exist that they are both correct?
My thoughts:
I don't understand what they mean when they ask "the function is DEFINED at $x= -3,-4, \& 6$. And how would a situation would be possible to be undefined and the function is defined.
Comment: is $\ln 0$ defined?
Comment: Consider the function $f(x) = \frac 1x$. This function is not defined at $x=0$.  Now consider the function $f(x) = \frac1{x^2-1}$.  This function is not defined at $x=\pm 1$.
Answer: A rational function $p(x)/q(x)$ is undefined at those $x$ for which $q(x) = 0$.
Otherwise it is defined.
The only "gray area" is when $p(x) = d(x) f(x)$ and $q(x) = d(x) g(x)$ for some polynomials $d, f, g$: then at points where $d(x) = 0$ but $g(x) \ne 0$,
Angie can say $p(x)/q(x)$ is undefined but Jamal can say $p(x)/q(x) = f(x)/g(x)$  and $f(x)/g(x)$ is defined.


approximate the solutions to a second order ordinary differential equation

Question: The exercise is:
Approximate the solutions of $x'' + x + ε*x^3 = 0$, the initial value is $x(0) = 1$ and $x'(0) = 0$ up to order one. (Hint: It is not necessary to convert this second order equation to a first order system.)
To solve this, we have to use Regular perturbation theory: we have to get it with the equation: $\varphi(t, \epsilon) = \varphi_{0}(t) + \varphi_{1}(t)\epsilon + o(\epsilon)$ where $\varphi$ is the solution of the ode and $\epsilon$ is the perturbation.
$\varphi_{0}(t) = \varphi(t, 0)$ is given as the solution of the unperturbed equation
where $\epsilon = 0$
$$\varphi_{1}(t) = \frac{\partial \varphi(t,\epsilon)}{\partial \epsilon} \bigg|_{\epsilon=0}$$
how can I compute $\varphi_{1}(t)$? or is this the wrong approach?
Comment: Why are you taking a derivative with respect to $\epsilon$?
Comment: i think it is the second taylor-term of the approximation, it was defined in the script we use in our lecture, I dont really know why in respect to  $\epsilon$
Answer: First you solve the unperturbed equation $x''+x=0$ with the given initial conditions to get $\phi_0(t)$.  Can you do that?  Then you use that to approximate the cubic term.  You need to find the solution to $\phi_1(t)''+\phi_1(t)+\epsilon \phi_0(t)^3=0$.  You are imagining that the effect of the cubic term is small so the solution will be approximately $\phi_0(t)$.  That gives you a nice second order differential equation to solve.
Comment: so I found the term $\phi_0(t) = cos(t)$  and I put it in the equation $\phi_1(t)''=-\phi_1(t)-\epsilon\phi_0(t)^3=-\phi_1(t)-\epsilon\cos(t)^3$,
 $\phi_1(t)$ is also periodic, so in generaly it looks like $a*cos(t) + b*sin(t)$?, how can I find $a$ and $b$ ?
thank you for your answer
Comment: There is an identity relating $\cos^3 t$ to $\cos t$ and $\cos 3t$  You can plug that in.  You get a forced oscillator with a forcing frequency three times higher than resonance.  The $\cos t$ term is right on resonance, so will generate a solution that involves $t \cos t$, which I believe one usually argues is non-physical, but the $\cos 3t$ term changes the shape of the resonance.
Comment: great explanation, thank you for your help.


Add an extra class to views exposed filter "select" if default option is selected

Question: I have some views exposed filters and need to add an extra class "test" to each list if it has default option selected.
I try to implement it using jquery with the following code:
<code>function ($) {
$(document).ready(function () {
    $('.form-select option:eq(0)').prop('selected', true);
      $(".form-select").addClass("test").on('change', function() {
      var optionIndex = $(this).find('option:selected').index();
      $(this).toggleClass('test', optionIndex === 0);
   });
});
})(jQuery);
</code>
Question is how to make this code to act properly in Drupal 7? Currently it adds the "test" class to all the dropdown lists after the page load. But if you chose any not default value in any list the "test" classes of all lists (even where default option is selected) disappeared and never appeared again until the page reload.
Answer: Change the selector and class name to your needs, but this should work.
<code>(function ($) {

  $("select")
    .change(function() {
      if ($(this).val() === $(this).find('option[selected]').val()) {
        $(this).addClass('default-value-selected');
      }
      else {
        $(this).removeClass('default-value-selected');
      }
    })
    .trigger("change");

})(jQuery);
</code>
Comment: Thanks for trying. But your code just makes closed loop and it causes uninterrupted page reloads. My code is working while it is inserted into the pure html page. But when I've set it to Drupal site its behavior became weird. So I've thought that there are some additional tricks should be implemented to  change the class of views exposed filters in Drupal.
Comment: May be it should be somehow tethered with AJAX because my views exposed filters changing via AJAX.
Answer: Well, proper solution of my task is represented below:
<code>(function ($) {
$(document).ajaxStop(function() {
    $("select").each(function() {
          var optionValue = $(this).find('option:selected').val();
          $(this).toggleClass('made_choice', optionValue !== 'All');
    });
  });
})(jQuery);
</code>
Once again I've proved to myself: if you want to do something in the best way - do it by your own.
So, the first problem was script starting by .ready(function()). It is wrong in case of exposed filters and AJAX loading procedure. You should start it by .ajaxStop(function()) to be able to fire the script every time you have chosen new value of exposed filter.
The second problem is that in case of two and more exposed filters on the form indexes of their options starting from 0 in the first used filter and finishing with the index of last option in last filter widget. Thus, you can not say that (optionIndex === 0) for every default value in each filter widget. So it will be more proper way in such case to check whether the option:selected has value 'All' or not.

Add an extra class to views exposed filter “select” if default option is selected


Why do we not always use the closed testing principle for multiple comparisons?

Question: From the Wikipedia entry:

Suppose there are k hypotheses $H_1,..., H_k$ to be tested and the overall
  type I error rate is $\alpha$. The closed testing principle allows the
  rejection of any one of these elementary hypotheses, say $H_i$, if all
  possible intersection hypotheses involving $H_i$ can be rejected by using
  valid local level $\alpha$ tests. It controls the familywise error rate for
  all the k hypotheses at level α in the strong sense.

By using the closed testing principle, we ensure all the false positive rate of all hypothesis tests in a family will be controlled at $\alpha$. This seems too good to be true. Why do we bother with Bonferonni or other corrections for multiple comparisons, when we can just test all the intersection hypotheses? The only downside seems to be that you need to conduct $2^{n}$ tests.
EDIT: I am thinking about a relatively small number of individual hypothesis tests, say $n = 3 \text{or} 5$. Then you would have a reasonable number of tests.
Comment: Your "only" downside is a huge one!  It limits practical procedures to $n\ll 30$ or so, and in cases where the tests are onerous to compute (think bootstrapping, for instance) to $n\ll 10.$
Comment: @whuber Not really true, is it? The closed testing principle is used all the time.
Comment: @whuber, I had in mind a relatively small number of hypothesis tests. For example, I'm curious why didn't  I learn this for ANOVA with two treatments and an interaction.
Comment: I wonder if this sucks power from the test. Sure, you control $\alpha$, but at what cost? If even the Bonferroni correction is more powerful, then I think that this would be an inadmissable testing procedure. (Confession: I don't know this to be the case, and it might be totaly wrong.)
Comment: @Dave I don't think Bonferroni is more powerful, but I'm not sure.
Comment: @Dave I've added a bit on power to my answer. Essentially, there is usually no power down-side. It is more usually a down-side in terms of a statistician having to spend time to define a non-standard procedure.
Answer: It is actually used quite often (in fact, Bonferroni and Bonferroni-Holm can be shown to be valid tests using the closed testing principle - see below). Part of the reason why some simple procedures like Bonferroni are still so popular is of course, that they are very easy to implement and it is easy to communicate what you did.
E.g. even for the simple Bonferroni or Bonferroni-Holm writing down the tests for the intersection null hypotheses is a bit tedious. That's why the graphical approach to constructing closed testing procedures is very popular - at least in the clinical trials setting (where there is usually a trained statistician at hand that can help pre-specify a tailored testing procedure for a specific trial). This graphical approach provides a really easy way to construct valid testing procedures and makes communication easier. Various variants, extensions and improvements such as exploiting correlations, prioritization of certain hypotheses depending on which hypotheses are already rejected etc. have been proposed over the years.
Bonferroni vs. Bonferroni-Holm as closed testing procedures example
The Bonferroni test can be easily written down in terms of the closed testing principle, e.g. in the case of two null hypotheses as

Test for $H_1 \cap H_2$: $p_1 \leq \alpha/2$ and $p_2 \leq \alpha/2$
Test for elementary null hypothesis $H_1$: $p_1 \leq \alpha/2$
Test for elementary null hypothesis $H_2$: $p_2 \leq \alpha/2$

with $H_1$ rejected overall, if both $H_1$ and $H_1 \cap H_2$ are rejected. Thus, we know it is a valid test. You also immediately see that for the elementary null hypotheses $H_1$ and $H_2$ you are using a test that is not exhausting the significance level and that the Bonferroni-Holm test

Test for $H_1$ and $H_2$: $p_1 \leq \alpha/2$ and $p_2 \leq \alpha/2$
Test for $H_1$: $p_1 \leq \alpha$
Test for $H_2$: $p_2 \leq \alpha$

is uniformly more powerful.
Figure 1: Illustration of the graphical approach for displaying these two procedures

Power considerations and other considerations
Usually, there's no downside in terms of power to using a closed testing procedure - if anything it tends to be easier to make sure the test fully exhausts the significance level. It can sometimes be a bit tricky to build in some desired features (e.g. exploiting a known correlation) while keep some other desired contraints (e.g. that the closed testing procedure can be easily displayed graphically due to the consistency requirement on the testing procedure).
Comment: Thank you. I have a followup question. Let's ignore changing the importance of particular test or accounting for correlation. If I can construct a uniformally most powerful test (UMP) for every hypothesis test in the family, is that the most powerful procedure I can construct that still controls the Family wise Error Rate.
Comment: I didn't see your addition when I asked my question. I think your addition covers my question. Thank you.


Pessoal como percorrer um array com múltiplas requisições?

Question: Estou recebendo este objeto via API e precisaria percorrer cada uma dessas paginas, lembrando que cada pagina é uma requisição. Aqui nessa demostração estou na pagina 1 cada pagina me traz 50 registros e o retorno me mostra que existem 39 paginas.. como eu percorro essas 39 paginas fazendo uma requisição a cada pagina? Desde fico muito agradecido pela ajuda de todos.
Array
(
[retorno] => Array
    (
        [status_processamento] => 3
        [status] => OK
        [pagina] => 1
        [numero_paginas] => 39
        [contas] => Array
            (
                [0] => Array
                    (
                        [conta] => Array
                            (
                                [id] => 504024714
                                [nome_cliente] => IRINEU DOMINGOS ANTUNES
                                [historico] => CONTAS A PAGAR - (Cliente sistema antigo - incluso no SCPC)
                                [numero_banco] =>
                                [numero_doc] => 000022554
                                [serie_doc] => 0
                                [data_vencimento] => 10/12/2014
                                [situacao] => aberto
                                [data_emissao] => 28/11/2017
                                [valor] => 392.66
                                [saldo] => 392.66
                            )

                    )

                [1] => Array
                    (
                        [conta] => Array
                            (
                                [id] => 503982261
                                [nome_cliente] => MARCUS VINICIUS DE OLIVEIRA CUNHA
                                [historico] => Ref. Venda otica self care Elisama
                                [numero_banco] =>
                                [numero_doc] => 000270860
                                [serie_doc] => 0
                                [data_vencimento] => 27/02/2015
                                [situacao] => aberto
                                [data_emissao] => 28/11/2017
                                [valor] => 444.00
                                [saldo] => 444.00
                            )

                    )

                [2] => Array
                    (
                        [conta] => Array
                            (
                                [id] => 503885902
                                [nome_cliente] => LUIZ CARLOS MIRANDA
                                [historico] => CONTAS A RECEBER - PEDIDO 5912 - LUIZ CARLOS MIRANDA - Parcela (1/8)
                                [numero_banco] =>
                                [numero_doc] => 000005912
                                [serie_doc] => 0
                                [data_vencimento] => 14/01/2016
                                [situacao] => aberto
                                [data_emissao] => 27/11/2017
                                [valor] => 125.00
                                [saldo] => 125.00
                            )

                    )

                [3] => Array
                    (
                        [conta] => Array
                            (
                                [id] => 503885904
                                [nome_cliente] => LUIZ CARLOS MIRANDA
                                [historico] => CONTAS A RECEBER - PEDIDO 5912 - LUIZ CARLOS MIRANDA - Parcela (2/8)
                                [numero_banco] =>
                                [numero_doc] => 000021248
                                [serie_doc] => 0
                                [data_vencimento] => 13/02/2016
                                [situacao] => aberto
                                [data_emissao] => 27/11/2017
                                [valor] => 125.00
                                [saldo] => 125.00
                            )

                    )

                [4] => Array
                    (
                        [conta] => Array
                            (
                                [id] => 503991231
                                [nome_cliente] => WELLIGTON RODRIGO RIBEIRO DA SILVA
                                [historico] => CONTAS A RECEBER - PEDIDO 1452 - WELLIGTON RODRIGO RIBEIRO DA SILVA - Parcela (1/10)
                                [numero_banco] =>
                                [numero_doc] => 000001452
                                [serie_doc] => 0
                                [data_vencimento] => 13/02/2016
                                [situacao] => aberto
                                [data_emissao] => 28/11/2017
                                [valor] => 30.00
                                [saldo] => 30.00
                            )

                    )

Answer: Execute um foreach a cada nível do array.
foreach($retornoDaAPI['retorno'] as $key => $value){
    foreach($value['contas'] as $key2 => $value2){
       //e assim sucessivamente
    }
}

Comment: Muito obrigado pela resposta Marcos Fabre.
Exemplo quando faço uma requisição eu tenho um retorno com 50 registrários por  pagina até sí bacana consigo percorrer tranquilo o array.
só api me manda separado todos os registros num total de 39 paginas.
ou seja são 39 requisições que terei de fazer... mas como fazer? lembrando que informo um parametro na url informando qual pagina quero obter  ex &pagina=5,  na url da requisição. mas pretendo saber se existe uma foma de trazer percorrer todas essas paginas numa unica chamada a api.