Why Engle-Granger cointegration test states cointegration between two variables but their trend in time is almost identical?

Question: I have run the Engle-Granger cointegration test in Python between a stock's return and its index return. In this case i have run the test between QQQ returns vs CCMP returns like this:
<code>from statsmodels.tsa.stattools import coint

results = coint(df_stock_returns['QQQ'], df_stock_returns['CCMP'])

print(results)
</code>
which yields:
<code>(-2.7063675732286856,
 0.1972968735378101,
 array([-3.99084033, -3.38795719, -3.08028241]))
</code>
The p-value is huge (0.19) so we can state that the two series are not cointegrated with a 95% confidence right?
Now, if i plot the two variables' time series, this is what i get:

How in the world is this even possible? They seem to move almost identically in time, they are almost like a replica of each other. Shouldn't we we be expecting to see the two variables moving/behaving differently over time? How can we explain that despite the high p-value the two series look so correlated like this? I have been searching about this in Google but i didn't find a meaningful answer and this is driving me nuts, i would really appreciate a good explanation about this.
Thank you very much in advance.
Answer: For cointegration, you need processes with unit roots. Stock returns do not have unit roots (as you can see, they fluctuate around zero rather than wandering off and potentially never returning), so they cannot be cointegrated.
Comment: @Miguel2488, stock prices can be cointegrated, but their returns cannot. You needs to analyze prices, not returns if you want to talk about cointegration and pairs trading.
Comment: Hi again @Richard Hardy, thank you very much for your clarification. I'll try with the prices and contrast the results :)
Comment: @Miguel2488, you are welcome! I am glad I could help.
Comment: Hi @Richard Hardy, thank you for your answer. I know this is a common practice in algorithmic trading, there are a lot of documentation about pairs trading using stock cointegration in Python. How is that stocks can't be co-integrated? Could you give  a bit more of an explanation about this please?
Answer: You have 2 ways to interpret this:

Your statistic (-2.606) > than any of the Critical values (-3.99084033, 3.38795719, -3.08028241). --> we accept the null hypothesis (=no cointegration)

As you say it, p-value is huge: 0.1972968735378101.. 19.72% > than 1%, 5% and 10% ---> therefore we accept the null hypothesis and the data is not cointegrated

In order to interpret our cointegration results, you need to do the following:

Estimate the cointegration regression.
Test the residuals from the cointegration regression for unit root

If the residuals contain a unit root, then there is no cointegration.


Three maximal ideals lying over $3\mathbb{Z}$?

Question: A few weeks ago I asked a question about finding the number of maximal ideals lying above $3\mathbb{Z}$ in $B$, where $B$ is the integral closure of $\mathbb{Z}$ in a splitting extension $E\supset\mathbb{Q}$ for the polynomial $f(x)=x^3+x+1$.
I'm reading over the following solution, but would like to ask a few follow up questions.
Since the discriminant of $f(x)$ is negative, two of the roots are complex conjugates, and since conjugation has order 2, the degree of the extension must be 6. Hence we may think of $E$ as adjoining two roots $a$ and $b$ of $f(x)$ to $\mathbb{Q}$, where $a$ satisfies $a^3+a+1$ and $b$ satisfies the polynomial $(x^3+x+1)/(x-a)=x^2+ax+a^2+1$.
So factor $(3)$ in $\mathbb{Z}[a]$ by factoring $x^3+x+1\pmod{3}$. Since there is one root modulo 3, it follows that
$$
x^3+x+1=(x-1)(x^2+x-1)\pmod{3}
$$
and so as we have seen, $(3)$ factors in $\mathbb{Z}[a]$ as $(3)=(3,a-1)(3,a^2+a-1)$.
Now since $a\equiv 1\mod (3,a-1)$, the polynomial $x^2+ax+a^2+1$ becomes $x^2+x+2$, which is irreducible modulo 3, and thus does not reduce further. Also, since $a^2=-a+1$ modulo this ideal, the polynomial can be further simplified to $x^2+ax-a+2$, so any root has for $ra+s$ for $r$ and $s$ integers modulo 3. This gives the set of equations
$$
\begin{align*}
(ra + s)^2 + a(ra + s) - a + 2 = 0 &\iff r^2a^2 + 2ras + s^2 + ra^2 + sa - a + 2 = 0,\\
&\iff r^2(-a + 1) + 2ras + s^2 + r(-a + 1) + sa - a + 2 = 0.
\end{align*}
$$
and so $-r^2 + r + s - 1 = 0$, and $r^2 + s^2 + r + 2 = 0 \pmod{3}$. This former equation implies $s\equiv (r+1)^2\pmod{3}$, and substituting into the second gives $r^2+(r+1)^4+r+2\equiv 0\pmod{3}$. This is true when $r=0$ and $s=1$, so $x=1$ is a root of $x^2+ax-a+2\mod(3,a^2+a-1)$. This in turn implies it factors as $x^2+ax-a+2=(x-1)(x+a+1)$.
Hence $(3, a^2 + a - 1) = (3, a^2 + a - 1, b - 1)(3, a^2 + a -1, b + a + 1)$, and hence there are three prime factors, and hence maximal ideals since $3\mathbb{Z}$ is maximal in $\mathbb{Z}$, lying above $3\mathbb{Z}$ in $\mathbb{Z}$.
I see that the $3\mathbb{Z}$ is the product of the $3$ factors found, but is there a more detailed explanation about why this immediately implies that there are $3$ maximal ideals lying above $3\mathbb{Z}$? I don't see how the conclusion follows so quickly. Would there need to be some uniqueness about this factoring for it to work as it does? Thank you kindly for your responses.
Comment: Many thanks @BrandonCarter Do you have a proof or reference of these facts, that i) the integral closure of $\mathbb{Z}$ in a finite extension of $\mathbb{Q}$ is a Dedekind domain, and that ii) each nonzero ideal factors uniquely? If you post it as an answer, I would be more than happy to accept.
Comment: You might as well link to the older question. Actually, links both ways would be great. I would do this, but it appears that the older question was created on a separate account.
Answer: Yes. The integral closure of $\mathbb{Z}$ in a finite extension of $\mathbb{Q}$ is a Dedekind domain, where each (nonzero) ideal factors uniquely as a product of (maximal) prime ideals. For proofs of these facts (and much more), see Robert Ash's notes here.


Flags to create mutual friends?

Question: I'm running a D7 system where users follow each other by using a 'follow' flag and then on user profile I've added a view to show all the users followed by a 'logged-in-user'.
What I'm struggling with is how do I generate a list of users who are followed by the friends of 'logged-in' user.
something like facebook 'mutual friends' functionality so 'logged-in' user get a list of users followed by the users he/she following.
Answer: You can do this by using Flag Friend module

Flag Friend aims to be a lightweight friending module utilizing the
  excellent Flag module's API.

Or
Flag Follow

This is a simple module which allows a user to view Heartbeat
  activities of his favorites/followed users. A user can add another
  user to his favorites list by just click on a 'Follow' button. It
  requires no approval to add a user to your favorites list.

or
You can do this by using Follow module.

Follow adds sitewide and per user links that link to various social
  networking sites. The links reside in two blocks. The Follow Site
  block lists all the links for the site itself, and by default is
  visible on all pages. The Follow User block lists all the follow links
  for the user and is visible only on user profile pages.
Comment: thanks for your prompt response but I cannot change the way flags/flag working at the moment as it would cause problems in messaging and notifications I'm running. I've to use the existing flag 'follow' to achieve this functionality.
Comment: Have you try Flag Follow ?
Comment: What I'm looking for is a list of users followed by my friends, again - something like 'would you like to add user X' 'User-X has 3 Mutual friends with 'you' '
Comment: I'll give 'Flag-follow' a run and will update you @NishantP to how it went
Comment: Ok sure. I hope your issue might be solved.

Flags to create mutual friends?


Draw a circle tangent internally to a point of an ellipse and to both its axis

Question: I would like to know how could I draw a circle that touches an allipse internally and at the same time both of its axis. There are, thus, four possible circles of this kind, all of them congruent, their centers being the vertexes of a square.
Answer: The easiest way is to  simply use a CAD system. Any decent one will have a function for constructing a circle tangent to three given curves.
If you want to do the computations yourself, here's how (in outline) ...
Let's use the standard  ellipse with equation
$$
    \frac{x^2}{a^2}+ \frac{y^2}{b^2}=1
$$
and let the circle be
$$
(x-c)^2 + (y-c)^2 = c^2
$$
This circle is automatically tangent to the coordinate axes, so we just have to choose $c$ suitably to make it tangent to the ellipse, also.
If you eliminate $y$ from the two equations above, you will get a quadratic equation for $x$ that is satisfied at the intersection points. To get tangency, this equation must have two equal roots, so it's discriminant must be zero. This gives you an equation that you can solve to get $c$.
Comment: Thank you for the answer. But I meant to DRAW the circle by means of compass, straight lines and even conics.
Comment: OK. Since the process I outlined involves solution of a quartic equation (at worst), there may be some theoretical proof that a ruler-and-compass construction is possible. But I have no idea how to do it in practice. I don't even know where my compass is.


Model Values Getting Lost During PostBack

Question: I'm trying to pass my model back to a controller. I have included all fields of the model in the form but two parts of the model are getting lost once it makes it back to the controller, Employees and EmployeesInMultipleCompanies, which are both of type IList. I have verified that the fields are present when they are passed to the view, they just don't make it back to the controller.
.cshtml
@using (Html.BeginForm("PostEmail","Import",FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>EmailViewModel</legend>

            <input type="email" name="EmailAddresses" value=" " required="required" />
            x

            Add Another Email

        @Html.HiddenFor(m=> Model.Employees)
        @Html.HiddenFor(m=> Model.CompanyId)
        @Html.HiddenFor(m=> Model.CompanyName)
        @Html.HiddenFor(m=> Model.PayFrequency)
        @Html.HiddenFor(m=> Model.FirstPayPeriodBeginDate)
        @Html.HiddenFor(m=> Model.LastPayPeriodEndDate)
        @Html.HiddenFor(m=> Model.NumberPayPeriods)
        @Html.HiddenFor(m=> Model.ValidEmployees)
        @Html.HiddenFor(m=> Model.InvalidEmployees)
        @Html.HiddenFor(m=> Model.EmployeesInMultipleCompanies)
        @Html.HiddenFor(m=> Model.TotalEmployeeCount)

            <input type="submit" value="Send Email" />

    </fieldset>
}

    @Html.ActionLink("Cancel", "Continue", "Import")

controller .cs
public ActionResult SendEmail(ImportViewModel model)
        {
            var editedEmployees = model.EmployeesInMultipleCompanies;
            var importModel = TempData["ImportModel"] as ImportViewModel;

            //for each employee who is in multiple companies, set user-chosen company id and the COHD related to that company
            var importService = new ImportService();
            importService.UpdateEmployeesInMultipleCompanies(editedEmployees, importModel.Employees);
            TempData["ImportModel"] = importModel;

            return this.RazorView("SendEmail", importModel);
        }

        [HttpPost]
        public ActionResult PostEmail(ImportViewModel model)
        {
            IEmailer emailer = new Emailer();
            emailer.SendEmail(model.EmailAddresses, model.Employees);
            var employees =
                model.Employees.Where(e => !string.IsNullOrWhiteSpace(e.ValidationErrorOrException)).ToList();
            var emailViewModel = new EmailViewModel(employees);
            return this.RazorView("Continue", emailViewModel);
        }

Comment: I would consider not rendering them in a single hidden but rather rendering multiple inputs with the same name and different values.  The DefaultModelBinder will see this and interpret it as a collection type and it should just work.  Alternatively, you could create a custom model binder that split the values stored in an individual hidden.
Comment: Also be wary of TempData as it is using sessions under the covers (which is not necessarily bad unless you are in a web-farm) and should really only be used when redirecting: http://stackoverflow.com/questions/1500402/when-to-use-tempdata-vs-session-in-asp-net-mvc.  Also many would consider using TempData in lieu of a strongly typed ViewModel / other persistence mechanism to be a code smell: http://stackoverflow.com/questions/386681/asp-net-mvc-tempdata-good-or-bad-practice.
Comment: @xDaevax thanks for the notice. I will consider it in the future, as for now its already there in server other view I'm just using it in mine.
Answer: Replace it with the following:
@foreach(var i = 0; i < Model.Employees.Count; i++)
{
  Html.Hiddenfor(m => m.Employees[i])
}

The same should be done for EmployeesInMultipleCompanies
Answer: Values that are inserted to hidden fields are serialized to a string to do so.
IList<T> is not serializable because it is an interface and and therefore cannot be stored in a hidden field.
See this question for some more detail
How about you convert your IList<T> to a regular list?
Comment: this makes since but it has no problem serializing my EmailAddresses which is also IList
Comment: even after changing to a regular list I get the same problem
Comment: The IList should be fine since the DefaultModelBinder is smart and isn't serializing the IList, but the type argument `T` of the IList.  The only time this could be an issue would be if the IList had a generic type constraint that was not a concrete type (abstract / interface).  The question you refer to is unrelated to the ModelBinder.
Comment: I figured another way around it. I did not realize the the Employee  data was already present in the TempData which is already in the controller.
Comment: As others have stated using a `foreach` loop to create a hidden field for each item in the collection will work as well as long as the underlying type is also serializable.
Comment: The DefaultModelBinder will convert a generic `IList`  to a `List` given T is a bind-able type.  It seems like your answer is not correct.  The issue isn't with the interface type, it is with the fact that the `HiddenFor` method will invoke the `ToString()` method on the `IList` object, which will put a value in the hidden field that is not usable on return to the controller.
Answer: The problem is not with the controller but rather the way the values are stored on the client.  The DefaultModelBinder is very smart, but it is also sometimes not that smart.  It can handle interfaces in certain situations, collections of complex types and many other things as long as the properties match up.  For detailed information on the behavior, see this article: http://msdn.microsoft.com/en-us/magazine/hh781022.aspx.
If you debug your controller and inspect the values in Request.Form, you will see your data stored as a single value.  If model binders could talk they would say:
The Request.Form["EmployeesInMultipleCompanies"] doesn't relate to the EmployeesInMultipleCompanies property of my model because my model meta data (ModelMetaDataProvider) tells me that I should be looking for a collection type (IList of an unknown generic type) and this is clearly a single string value so I will not bind this value.
To solve this, you have to give the DefaultModelBinder enough of a hint for it to do the work.  One way of doing this is to render the hidden fields in such a way that they have an indexer associated with them.  This is the clue the model binder needs to function the way you expect.
If you rendered both like so:
@for(var i = 0; i < Model.Employees.Count; i++)
{
  Html.Hiddenfor(m => m.Employees[i])
}
@for(var i = 0; i < Model.EmployeesInMultipleCompanies.Count; i++)
{
  Html.Hiddenfor(m => m.EmployeesInMultipleCompanies[i])
}

Then stepped through your debugger again, you would see this now in Request.Form:
Request.Form["EmployeesInMultipleCompanies[0]"]
Request.Form["EmployeesInMultipleCompanies[1]"]

etc...
Now the model binder can do work.
Alternatively, you could create a custom model binder that knows how to read the fields from a single input.

I have created a Gist to demonstrate the different types of possible results when doing this kind of ModelBinding with a generic IList here: https://gist.github.com/xDaevax/bd35b5d88fed03709d30
Comment: Are those supposed to be for loops not foreach?
Comment: Does this approach still require me to use List instead of IList?
Comment: @AntarrByrd  No you shouldn't have to: http://stackoverflow.com/questions/653514/asp-net-mvc-model-binding-an-ilist-parameter  <-- That question is old but the answer should still be relevant.
Comment: Its still not working for me right now. I will move on for now, thanks
Comment: @AntarrByrd  The only exception would be if the `EmployeesInMultipleCompanies` is a non-primitive type (user defined).  If your IList is of `string` or `Guid` for example, you'll be fine.  If it is something like IList, you'll potentially have an issue.  If you would like to discuss this more, we could in chat.
Comment: @AntarrByrd I have added a Gist example to my answer to illustrate the behavior I'm describing.


Solving two coupled functional equations in the same time

Question: Let
$ϕ(s)=f(s)\exp(ig(s))$, $s$ is a complex number.
The expressions of $f$ and $g$ are not known since they depend on the gamma function.
It is well known that we can solve a functional equation in different manners. However, I have two coupled functional equations of the form:
$g(1-s)+g(s)=0 \pmod{2\pi}$
and
$f(1-s)f(s)=1$
The objective is to determine $f$ and $g$ and their domain of definition.
Answer: According to the definition,
$$
\log(\phi(s))=\log(f(s))+ig(s)
$$
Assuming that $f(s)$ and $g(s)$ are real-valued functions, we get that
$$
f(s) = |\phi(s)|
$$
and
$$
g(s) \equiv \arg(\phi(s))\pmod{2\pi}
$$
If we can't assume that $f(s)$ and $g(s)$ are real-valued, then I don't believe there is a way to uniquely determine $f(s)$ and $g(s)$.

Since $\log(f(s))+\log(f(1-s))=0$, about the only thing we can say is that $\log\left(f\left(s+\frac12\right)\right)$ is an odd function of $s$. That is, $f(s)=e^{h\left(s-\frac12\right)}$, where $h(s)$ is any odd function.
A similar argument shows that $g(s)=k\left(s-\frac12\right)+\pi e\left(s-\frac12\right)$ where $k(s)$ is any odd function and $e(s)$ is any even, integer-valued function.
Comment: @RH1: yes. Since $f(z)f(1-z)=1$ for $z\in\mathbb{R}$ and $f(z)f(1-z)$ is harmonic, $f(z)f(1-z)=1$ for $z\in\mathbb{C}$.
Comment: @ robjohn: Ok, this is a great answer. thank you very much.
Comment: @RH1: yes. Being even, $\pi e\left(s-\frac12\right)=\pi e\left(-s+\frac12\right)=\pi e\left((1-s)-\frac12\right)$ so $\pi e\left(s-\frac12\right)+\pi e\left((1-s)-\frac12\right)=2\pi e\left(s-\frac12\right)$, which is $0\bmod{2\pi}$.
Comment: @ robjohn: I know that $g(1-s)+g(s)=0 \pmod{2\pi}$ and $f(1-s)f(s)=1$ holds in the set S={(1/2)+i0}∪{((1/2),∞)×ℝ}∪{{(1/2)}×(0,∞)}. But not in the whole set $S$. My question is: Is the forms given above for $f$ and $g$ can extended to the whole complex plane or not. I notice that ϕ(s) is analytic in $ℂ$.
Comment: @RH1: for $e$ to be analytic, it needs to be constant. As long as $h:\mathbb{R}\mapsto\mathbb{R}$ and $k:\mathbb{R}\mapsto\mathbb{R}$ are odd real-analytic functions, there should be at least a small region around $\mathbb{R}$ into which $f$ and $g$ can be continued. In those regions, $f(z)f(1-z)=1$ and $g(z)+g(1-z)\equiv0\pmod{2\pi}$.
Comment: @ robjohn: The objective is to determine $f$ and $g$ and their domain of definition. Or the domain where the two equations holds in the same time.
Comment: @RH1: Unless more information is given on $\phi$ or $f$ and $g$, I don't see a way to get much more information.
Comment: @RH1: there is not much that can be said about $f$ and $g$, but I think I have described them as much as possible from the relations given.
Comment: @ robjohn: the function $g(s)=k\left(s-\frac12\right)+\pi e\left(s-\frac12\right)$ is modulo $2π$. So $πe(s-1/2)$ represent the corresponding addition modulo $2π$. I am right!
Comment: @ robjohn: But $s$ is a complex number in the question. the departing set of $h$, $e$ and $k$ is the complex plane.
Comment: @ robjohn: The equation $f(z)f(1-z)=1$ does not holds for all real $z$.
Comment: @RH1: I thought that that was given in the question. What is the purpose of the functional equations in the question, then?
Comment: @ robjohn: Ok, we have $ϕ(s)=r(s)Γ(1-s)$ where $r$ is an elementary function with a clear expression in $s$. The function $f$ and $g$ can be calculated from the expression of $ϕ(s)$. But they still depend on $Γ(1-s)$
Comment: Since $\phi(s)=f(s)e^{ig(s)}$, the functional equations say that $\phi(s)\phi(1-s)=1$. Are $f$ and $g$ real-valued functions?
Comment: @ robjohn: Yes, for all complex $s$.
Comment: @RH1: so we know that $\phi(s)\phi(1-s)=1$ and $f(s)=|\phi(s)|$ and $g(s)=\mathrm{arg}(\phi(s))$. $g$ may have to have branch cuts connecting points where $\phi(s)=0$, but otherwise, it should be possible to continue $f$ and $g$ wherever $\phi$ is defined.
Comment: @ robjohn: I know that this is a complicated question. However, $ϕ(s)≠0$ for all complex number $s$ in the chosen domain .
Comment: @RH1: I had assumed $\phi$ was entire. $\phi(s)=\infty$ is just as problematic as $\phi(s)=0$. If $\phi(s)\ne0$ and $\phi$ is entire, then $f$ and $g$ can be well-defined without branch cuts.
Comment: @ robjohn: So, the forms given above for $f$  and $g$  can extended to the whole complex plane without any problem.
Comment: @RH1: if $\phi$ is entire and never vanishes, then yes. Poles and zeros would require branch cuts, but without poles or zeros, there should be no problem.


How do I recieve/get the audio/video data from a youtube video?

Question: I've long time wanting to know how I can get the audio data or whole video data from a youtube video. I did what any reasonable person would do, I googled it.
Sadly I didn't find any good answers. Mostly of what I was suggested was to get the data out of download links provided by: http://www.youtube.com/get_video.php?video_id={VideoKey}
However, it doesn't work anymore. Comments from forum sections etc, also suggest other people facing the same problem as I. So from that I take the conclusion that this information is out of date. But there must be a way since other websites and browser addons like, KeepVid.com or YoutubeInMp3.com still works.
So my question is simple. How do I recieve/get the audio/video data from a youtube video? In a link perhaps?
Comment: You can not do what you want without violating Youtube Terms Of Service: http://www.youtube.com/t/terms
Comment: You realized that SO provides a button to accept answers to your previous questions?
Comment: youtube-dl : https://github.com/rg3/youtube-dl/
Answer: Who better to ask, other than google themselves https://developers.google.com/youtube/2.0/developers_guide_java
Example: The following example demonstrates how to retrieve a standard feed and print information about the videos in that feed.
<code>String feedUrl = "http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed";
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
printVideoFeed(videoFeed, true);
</code>
Comment: That will give you information about the feed, not the audio/video data itself.


radio button will not bind properly Angular

Question: I have the following view

<input type="radio" name="{{item.GroupName}}"  data-ng-value="   {{item.BooleanValue}}" />
     {{bookmark.BooleanValue}}

The above shows the text value of bookmark.BooleanValue after the radio button as true but the radio button is not selected.
I don need any complex binding to the viewmodel. The requirement is to make a DB call on selection (which I will get to once I can get the binding sorted
Any help?
Answer: You use ng-value in conjunction with ng-model. ng-model specifies the property the radio button is bound to and ng-value is the value given to the bound property when that radio button is selected. See the docs.

<input type="radio" name="{{item.GroupName}}"  ng-model="item.BooleanValue" ng-value="true"/>
     {{item.BooleanValue}}

Comment: Many thanks. I had tried this before but not without removing the placeholders {{}} from around item.BooleanValue
Comment: whenever you do `ng-foo` you don't need the `{{bar}}` round the value.


Closed form expression for series involving Legendre polynomials

Question: Given $-1 \leq x \leq 1$ and $0 \leq \eta \leq 1$,
I am interested in computing
$$
E(x,\eta) = \sum_{\ell = 0}^{+ \infty} |P_{\ell} (0)|^{2} \, P_{\ell} (x) \, \eta^{\ell} ,
$$
with $P_{\ell}$ the usual Legendre polynomials.
Can one find a closed form expression for this function?
NB1: Should this be useful, $E(x,\eta)$ is, in essence, the gravitational potential between two massive circles centered around the same location, inclined by a respective angle $\cos^{-1}(x)$ and with a ratio of radii given by $\eta$.
NB2: Of course, in the limit $x \to 1$ or $\eta \to 0$, I expect that I could perform appropriate limited developments.
Answer: As $P_{2n+1}(0)=0$ and $P_{2n}(0)=(-1)^n\frac{(1/2)_n}{n!}$, the proposed series reads
\begin{align}
 E(x,\eta) &= \sum_{\ell = 0}^{+ \infty} |P_{\ell} (0)|^{2} \, P_{\ell} (x) \, \eta^{\ell} \\
 &=\sum_{n=0}^\infty \frac{\left(\frac{1}{2}\right)_{n}^{2} }{n !^{2}}P_{2n}(x)\eta^{2n}
\end{align}
Interestingly, such a series was discussed in connection with Ramanujan type series for $1/\pi$ in this paper (see also here). Wan and Zudilin prove the following identity
\begin{align}
 \sum_{n=0}^\infty\frac{\left(\frac{1}{2}\right)_{n}^{2} }{n !^{2}}\,&P_{2n} \left( \frac{\left(X +Y \right) \left(1-X Y\right)}{\left(X -Y \right) \left(1+X Y \right)}\right) \left(\frac{X -Y}{X Y +1}\right)^{2 n}\\
 &=\frac{\left(1+X Y\right)}{2} \,_2F_1\left(\frac{1}{2},\frac{1}{2};1;1-X^{2}\right)\,_2F_1\left(\frac{1}{2},\frac{1}{2};1;1-Y^{2}\right)
\end{align}
the domain of validity for the parameters $X,Y$ is relatively complex, but numerical experiments seem to indicate that most of the values of $-1\le x\le 1$ and $0\le \eta\le1$ (if not all) could be covered.
Comment: Your formula and mine combined means a weighted integral of an elliptic function can be written as a product of elliptic functions, a pleasant surprise.
Comment: Yes, that is a nice connection, even if the transformations of the involved parameters are rather complicated!
Answer: A single integral form of the series in question is
$$ \sum_{n=0}^\infty t^n P_n(0)^2 P_n(\cos{a}) =
\frac{4}{\pi^2}\int_0^\pi \frac{db}{ u_+(b)+u_-(b)}K\big(\frac{(u_+(b)-u_-(b))^2}{(u_+(b)+u_-(b))^2}\big) $$
where
$$u_+(b) = \sqrt{1-2t\cos{(a+b)} + t^2} \quad,\quad u_-(b) = \sqrt{1-2t\cos{(a-b)} + t^2}$$
and the fact that $u_\pm$ also depends on $a$ and $t$ has been suppressed.
$K(x)$ is the complete elliptic function of the first kind, implemented in Mathematica as $K(x) =$EllipticK[x].
The derivation follows from integrating over $b$
$$\sum_{n=0}^\infty t^n P_n(\cos{a}) P_n(\cos{b}) =\frac{4}{\pi} \frac{1}{ u_+(b)+u_-(b)}K\big(\frac{(u_+(b)-u_-(b))^2}{(u_+(b)+u_-(b))^2}\big) $$
as I found in the answer to
An infinite series involving Legendre polynomials
Note that the argument of K in my answer is the square of the one in the reference, and that is to make it consistent with Mathematica's input. (There is a confusing array of notations for elliptic integrals.)
Gradshteyn and Rhyzhik 7.226.1, symmetry of the integrand, and the known closed-value for $P_n(0)$ can be manipulated to read
$$\int_0^\pi P_n(\cos{b}) db = \pi P_n(0)^2 $$
Hence, the derivation is easy, once the right formulas are available. The answer has been checked numerically for many $a$ and $t.$ It is highly unlikely there is a simpler form.


Filtering Views to make several users see the node

Question: I have a content type which contains files. I have a node with that content type which i want several, but not all people to be able to see it from a Drupal View. I know the list of the people i want to see the files, and am willing to input the names of users into any type of field of that node.
How do i filter a View to only show that node to that certain people listed in that field of users?
For context, the nodes contain some private documentation or architect design files, that not everyone should see, but also should be seen by several people, not only administrator and owner of the node.
Answer: It depends on what kind of view you're creating. You are probably working on a view for content. So the filters are limited to those related to content. You can add a relationship "Content: Author" (Relate content to the user who created it.) under "Advanced Options" to add more filter criteria to the filter criteria list (User will show up in the filter list then, too).

Or you try creating a view for users.

use the Views module to create the list – actually a list of users (rather than nodes/content).
use relationships settings to add in the interests, and finally
add a contextual filter on "user: uid" with a default value fetched from the currently logged-in user.
Answer: You could just add your requisite users to a role / group and then assign access to that role via the access panel in your view.
Comment: In future, there might be a tons of these groups, so that's definitely not what i want.


Maximizing the funciton $f(x,y,z) = x^2 + 2y - z^2$

Question: Solve this for $x$ and $z$. Any help? Been trying for like thirty minutes, no success. Maybe just tired, or it's impossible to solve.
$$\begin{cases}2x = 8 \lambda\\
2 = \mu - \lambda\\
-2z = \mu\\
\end{cases}$$
Edit

Maximize the function $f(x,y,z) = x^2 + 2y - z^2$ subject to the constraints $8x - y = 0$ and $y + z = 0$.

We have that $\nabla f = 2x \hat{i} + 2 \hat{j} -2z \hat{k}$. Let $g_1 = 8x - y$ and $g_2 = y + z$. Then $\nabla g_1 = 8 \hat{i} - \hat{j}$ and $\nabla g_2 = \hat{j} + {k}$.
Now using Lagrange's method: $\nabla f = \lambda \nabla g_1 + \mu \nabla g_2$.
This gives $2x \hat{i} + 2 \hat{j} - 2z \hat{k} = 8 \lambda \hat{i} + (\mu - \lambda)\hat{j} + \mu \hat{k}$, or the next system of equations:
$$\begin{cases}2x = 8 \lambda\\
2 = \mu - \lambda\\
-2z = \mu\\
\end{cases}$$
Comment: When you say that these equations have to be solved for $x$ and $z$, then I assume that $\mu$ and $\lambda$ are some given constants. Then the second equation doesn't contain any information on $x$ and $z$ at all and can be ignored.

From the first equation you get $x = 4\lambda$ and from the third one $z = -0.5\mu$. Or did I miss anything?
Comment: Solve with respect to what? Because if you take the first and third equations, the system is already solved for $x$ and $z$. Which variable do you want to remove?
Comment: For the ones interested, I edited my post.
Answer: There are multiple ways of solving that system for $x$ and $z$. Since $\mu$ and $\lambda$ are constant, the system is already in a solved state: just take the first and third equations, and you get:
$$\begin{cases}x = 4\lambda\\
z = -\frac12\mu
\end{cases}$$
If, however, you want to remove the dependence on one of these constants, you can make use of the second equation to get either
$$\begin{cases}x = 4\lambda\\
z = -1-\frac12\lambda
\end{cases}$$
or
$$\begin{cases}x = 4\mu-8\\
z = -\frac12\mu
\end{cases}$$
Comment: I edited my post, to make my intentions clear.
Comment: @Kamil: Ah I see. This is an entirely different question altogether. Unfortunately I don't know how to help you, I don't know about the Lagrange method!
Answer: maximize $f = x^2 + 2y-z^2 $ subject to the constraints $y =8x$ and $y=-z.$
won't this work.
$$f = x^2 + 2y-z^2 = x^2+16x - 64x^2 = -63x^2 +16x \le -63 \times \left(\frac8{63}\right)^2 + 16 \times \frac{8}{63} = \frac{64}{63} $$  this is achieved at $x = \frac{8}{63}, y =\frac{64}{63}, z = -\frac{64}{63}.$
Comment: Is $64/63$ the answer according to you? I need to find an $x, y, z$ such that the function achieves maximum value.
Comment: Thanks, I inserted that answer and it was correct! Although the method you've used to find it is not so clear to me O.O
Comment: @Kamil, what do you mean? a quadratic expression $ax^2 + bx + c$ has a local maximum at $x = -b/(2a)$ is $a < 0.$ that is what i used ti find the maximum value.


General solution for intersection of line and circle

Question: If the equation for a circle is $|c-x|^2 = r^2$ and the equation for the line is $n \cdot x=d $,  and assuming that the circle and line intersect in two points, how can I find these points?
Also as kind of a side note, is there also a general formula for obtaining the equation of a circle of the intersection of a plane and sphere in $\mathbb R^3$, using similar equations?
Answer: The answer given by Seyhmus is fine if the line is a line through the origin (or $d = 0$ in your formula). Perhaps a better solution, in the general case, is to find the interserction of a circle $|c - x|^2 = r^2$ with a parametric line,
$$
x(t) = a + tb
$$
where $a$ is a point and $b$ is a vector.For a point on this line to satisfy the equation, you need to have
$$
(tb + (a-c)) \cdot (tb + (a-c)) = r^2
$$
which is a quadratic in $t$:
$$
|b|^2 t^2 + 2(a-c)\cdot b t + (|a-c|^2 - r^2) = 0
$$
whose solutions are
$$
t = \frac{-2(a-c)\cdot b \pm \sqrt{[2(a-c)\cdot b]^2 - 4|b|^2(|a-c|^2 - r^2)}}{2|b|^2}
$$
Once you find these two values of $t$ and plug them back intot he parametric equation, you get your two points.
Coincidentally, this method works fine in all dimensions (i.e., $c$ and $a$ can be points of $R^3$, and $b$ a vector in $R^3$), and the same formula works.
In two dimensions, it's pretty easy to convert from the implicit form of the line to the parametric form: find any two points $P$ and $Q$ on the line, and let $a = P$ and $b = (Q - P)$. In three dimensions, it's rather difficult to specify a line implicitly, but quite simple to express it parametrically, so the general case tends to be asked in exactly the form in which I've answered it.
Comment: Live example of parametric line / circle intersection with solution, here: https://www.desmos.com/calculator/0kadyeba6y
Answer: Here I present a method, I don't think it was not used yet, but don't usually find it in mathematics textbooks :
$$\begin{cases}
ax + by + c = 0 \\
(x-\alpha)² + (y-\beta)² = R_{0}^2
\end{cases}
$$
As it shows, the first equation describes the line $\Delta$ with a normal vector $\left( \begin{matrix}
a \\
b
\end{matrix} \right) $ and the second equation describes every point lying on the circumference of the circle with radius $R_0^2$ and a center point lying at $(\alpha,\beta)$.
An easy but very helpful transformation is used here : let $X = x-\alpha $ and $Y = y-\beta$, thus reducing the system of equation to :
$$\begin{cases}
aX + bY = C \\
X² + Y² = R_0^2
\end{cases}
$$
with $ C = -c - a\alpha - b \beta$. (this is equivalent to dealing with the same equations with the center of the circle being the origin of our plane).
let $\left( \begin{matrix}
X \\ Y \end{matrix} \right) \left( \begin{matrix} a & b \\ -b & a \end{matrix} \right) = \left( \begin{matrix} C \\ \gamma \end{matrix} \right)$ with $\gamma \in \mathbb R, \gamma = -bX + aY$.
This expression is equivalent to $z' = z(a-ib)$ with $z' = C + i\gamma$ and $z = X + iY$. Using a basic yet a powerful rule of complex numbers we can safely say that :
$$|z'|² = |z|²|a-ib|² \\
\implies C² + \gamma² = (X² + Y²)(a²+b²)$$
and according to our initial system of equations : $X²+Y²=R_0^2$ and $\gamma = (-bX + aY) $.
$$ \implies (-bX+aY)² = R_0^2(a²+b²)-C²$$
hence :
$$\implies (-bX+aY) = \pm \sqrt{R_0^2(a²+b²)-C²}$$
which explains why we will find
$$\begin{cases}
0 \text{ solutions} & \text{if }   R_0^2(a²+b²)-C²<0 & \implies R_0<\frac{|a\alpha+b\beta+c|}{\sqrt{a²+b²}} \\
1 \text{ solution} & \text{if }   R_0^2(a²+b²)-C²=0 & \implies R_0=\frac{|a\alpha+b\beta+c|}{\sqrt{a²+b²}} \\
2 \text{ solutions} & \text{if }   R_0^2(a²+b²)-C²>0 & \implies R_0>\frac{|a\alpha+b\beta+c|}{\sqrt{a²+b²}}
\end{cases}$$
Back to our linear transformation we have now :
$$\left( \begin{matrix}
X \\ Y \end{matrix} \right) \left( \begin{matrix} a & b \\ -b & a \end{matrix} \right) = \left( \begin{matrix} C \\ \pm \sqrt{R_0^2(a²+b²)-C²} \end{matrix} \right)$$
or equivalently expressed as :
$$(X+iY)(a-ib)=(C \pm i \ \sqrt{R_0^2(a²+b²)-C²})$$
Dealing with complex division is way too easy comparing to matrix inversion, and that's why we keep using them, and now we can directly deduce that
$$X+iY = \frac{(C \pm i \ \sqrt{R_0^2(a²+b²)-C²})(a+ib)}{(a²+b²)} \\
\implies \begin{cases}
X = \frac{1}{a²+b²}(aC \mp b\sqrt{R_0^2(a²+b²)-C²}) \\
Y = \frac{1}{a²+b²}(\pm a\sqrt{R_0^2(a²+b²)-C²} +bC)
\end{cases}\\
\implies \begin{cases}
x = \frac{1}{a²+b²}(aC \mp b\sqrt{R_0^2(a²+b²)-C²}) + \alpha \\
y = \frac{1}{a²+b²}(\pm a\sqrt{R_0^2(a²+b²)-C²} +bC) + \beta
\end{cases} $$


Recursive instance definitions

Question: I have a recursive data definitions:
data Checked a =  forall b. Checked (Either (Warning, Maybe (Checked b), a) a)

I need to define Show recursively:
instance (Show a) => Show (Checked a) where
  show (Right v) = show v
  show (Left (w, Nothing, v) = show w ++ show v
  show (Left (w, Just ch, v) = show w ++ show v ++ "caused by" ++ show ch --recursive here

GHC gives
 Could not deduce (Show b) arising from a use of `show'
  from the context (Show a)
  bound by the instance declaration at Checked.hs:29:10-35
  Possible fix:
   add (Show b) to the context of
    the data constructor `Checked'
    or the instance declaration
  In the second argument of `(++)', namely `show ch'

If I add (Show b) to the constraints on the instance definition, GHC gives:
 Ambiguous constraint `Show b'
  At least one of the forall'd type variables mentioned by the constraint
  must be reachable from the type after the '=>'
In the instance declaration for `Show (Checked a)'

Is there a next step I should take to get this to compile?
Comment: Please notice that @HaskellElephant has corrected your code (which should really be posted in an answer instead of in your question).
Comment: @AndrewC I thought that the error had nothing to with the question asked so I corrected it. Should I revert it? The fix is covered by Sjoerd Visschers answer.
Comment: @HaskellElephant. I nearly reverted it myself, but wanted to give you the opportunity to put your edit as part of an answer. If you revert it, add a line in Sjoerd's answer to explain that `Checked` should be there. (It's unclear whether Sjoerd saw the original or the edited version.) I think it's OK to edit trivial obvious mistakes in an answer, but if you edit the question without telling the asker, they might not notice and they'll be left in the dark unnecessarily. If you do revert it, please reply to me again so I can delete my comments.
Comment: @AndrewC well, one thing is what the asker thinks but anyone visiting this post again to find out what the question is about will have a hard time with the extra errors. Note that it is not just the extra `Checked` there is a mismatched parenthesis a missing `where`, and a wrong indentation which will give you a parse error before you get to the error in the question. I'll revert the edit and make it an answer instead.
Comment: Sorry folks. Corrected those sloppy errors myself. Put it down to unfamiliarity with the wonderful stackoverflow
Comment: Notice that @HaskellElephant made more corrections than that - look at revision 2 in the edit history (click on the time after the word edited). If you prefer to ask that version of the question, it would be worth rolling back to HaskellElephant's version, and I've just wasted people's time with my pedantic adherance to my perception of SO best practice. Sorry.
Comment: @RobertOnslow seems like there is yet another mismatched parenthesis now.
Answer: You need to add the Show b restriction to the data type:
data Checked a = forall b. Show b => Checked (Either (Warning, Maybe (Checked b), a) a)

instance Show a => Show (Checked a) where
  show (Checked (Right v)) = show v
  show (Checked (Left (w, Nothing, v))) = show w ++ show v
  show (Checked (Left (w, Just ch, v))) = show w ++ show v ++ "caused by" ++ show ch

Comment: @RobertOnslow Can you manage without the existential quantification? Would `data Checked a b = ...` do? You'd be able to work without the Show context if so. Alternatively, will wrapping the whole thing in a GADT solve all your troubles?
Comment: Thanks Sjoerd, but is there a solution in which I don't have to contaminate Checked with Show in this way? Because now the compiler is asking for Show a => constraints in other Checked instance declarations, e.g. Applicative which have nothing to do with Show
Comment: @AndrewC I'll have a think about Checked a b first. Thanks.
Comment: @RobertOnslow You can use constraint kinds and pass a useless constraint for other cases. See my answer for usage.
Answer: Add Show constraint to the data type definition.
data Checked a =  forall b. Show b => Checked (Either (Warning, Maybe (Checked b), a) a)

You can also use constraint kinds as
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}

data Checked a c =  forall b. c b =>  Checked (Either (Maybe (Checked b c), a) a)

instance (Show a) => Show (Checked a Show) where
 show (Checked (Right v)) = show v
 show (Checked (Left (Nothing, v))) = show v
 show (Checked (Left (Just ch, v))) = show v ++ "caused by" ++ show ch

Recursive instance definitions


Vertical-align on a Bootstrap column in a height-defined container

Question: I am trying to do a vertical-align on col-sm-12 inside of a height-defined container but this doesn't work.
I have tried a lot of different methods and nothing seems to work.

.home-main-elem {
    content: "";
    display: block;
    background: url('XXXX') no-repeat bottom left;
    height: 450px;
    -webkit-background-size: cover;
    background-size: cover;
    color: #FFF;
}
h1 {color: #FFF;}
.font-orange {color: #ffcc43;}
.vertical-middle {
    float: none;
    vertical-align: middle;
    display: inline-block;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

Welcome to XXXX

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum qui dolore quam et fugiat hic tenetur, quasi in doloremque reiciendis quia, blanditiis eaque adipisci explicabo, facere enim fuga repellendus sunt!

                SIGN UP

Comment: have ypu try this :
Comment: Do you mean you want a column that's two rows high, while the other ones are one row high?
Comment: can you please add your code in jsfiddle?
Answer: Unfortunately the Bootstrap framework does not have a great way 'Out of the box' of vertically centering the content.
There are 2 ways I can think of how to do this but it would require additional CSS and HTML.
Method 1: Use display: flex
See an example here
.wrap {
  display: flex;
  align-items: center;
}

The CSS flexbox model allows us to better manage how our elements are positioned.
Method 2: Use display: table
See an example here
.wrap {
  display: table;
  width: 100%;
}
.item {
  display: table-cell;
  vertical-align: middle;
}

Table cells are capable of being vertically centered within a table
Answer: Try adding these styles to the elements:
.home-main-elem {
    position: relative;
}

.vertical-middle {
    position: absolute;
    top: 50%;
    transform: translate(0,-50%);
}

Comment: The alignement works but the only negative side i've found is the face that now the text on the  does not respect the width anymore
Comment: What do you mean with that exactly? When I'm testing your code in my browser, the text behaves exactly the same as without my changes.
Comment: The  content goes all the way to the right, ignoring the  size


Alter Block render array and add another block's content

Question: I am attempting to attach a block to another block via hook_block_view_alter. The source block is a menu_block and the block to be attached is a view block, but the type of block shouldn't matter to the solution.
Here is the code used to attach the block. Assume that block_attached_block is populated with the bid of the block and at the point where I am altering the render array I have a fully rendered block.
function MODULE_block_view_alter(&$data, $block) {
  if (!empty($block->block_attached_block)) {

    // load the attached block from the database
    $attached_block = db_select('block', 'b')
      ->fields('b')
      ->condition('b.bid', $block->block_attached_block)
      ->execute()
      ->fetchObject();

    // render the block
    $block_content  = _block_render_blocks(array($attached_block));
    $build          = _block_get_renderable_array($block_content);
    $block_rendered = drupal_render($build);

    // attach the block
    $data['block_attached_block'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('block_attached_block'),
      ),
      'block' => array(
        '#markup' => $block_rendered,
      ),
    );
  }
}

If I render $data at this point I see the attached block rendered perfectly.
drupal_render($data);

However, when I load the page the attached block is missing. The documentation is pretty light.
My question is how do I get the rendered block to output on the page.
Comment: Maybe you mean `$data['content']['block_attached_block'] = ...`? A `$block` as returned from `hook_block_info` isn't a render array, confusingly, the render array is actually in the inner `content` element
Comment: Hey Clive, that does not work unfortunately.
Comment: Worth a shot, will try to take a closer look later
Comment: For menu blocks, I need to add it to $data['content']['#content']['block_attached_block']...so that's one down. Now I need to figure out view blocks, webform blocks and custom blocks.
Answer: Here is an updated function taking into account some of the various types of blocks that we can attach blocks to.
function MODULE_block_view_alter(&$data, $block) {
  if (!empty($block->block_attached_block)) {

    // load the attached block from the database
    $attached_block = db_select('block', 'b')
      ->fields('b')
      ->condition('b.bid', $block->block_attached_block)
      ->execute()
      ->fetchObject();

    // render the block
    $block_content = _block_render_blocks(array($attached_block));
    $build         = _block_get_renderable_array($block_content);

    // create attached block render array
    $block_attached_block = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('block_attached_block'),
      ),
      'block' => $build,
    );

    // attach the block
    switch ($block->module) {

      // menu block module blocks
      case 'menu_block':
        $data['content']['#content']['block_attached_block'] = $block_attached_block;
        break;

      // views module blocks
      case 'views':
        $data['content']['#markup'] .= drupal_render($block_attached_block);
        break;

      // block module blocks
      // webform module blocks
      case 'block':
      case 'webform':
        $data['content'] .= drupal_render($block_attached_block);
        break;

      // all other module blocks
      default:
        $data['content']['block_attached_block'] = $block_attached_block;
        break;
    }
  }
}

Thanks Clive for getting me started on the right path.


How can i limit a user to use no more ram than 1gb in window 2012 r2 server?

Question: is it possible to to limit a user ram?
No more ram than 1gb in window 2012 r2 server?
One of of my user is using about 3GB ram
Answer: With standard build in tools that's not possible really. You need to look for third party tools TScale for example. Unless it's more relating to process usage then you can limit that using Windows System Resource Manager.
Answer: Use remote app to lock the user on only the application he need access to or use policy to block app he can access.
If the problem is the application that he use need 3 gig of ram then by definition you cant limit him, as the application will crash...


Over which fields $x^{4} - 2x^{3} + 2x^{2} - 2x + 1$ can be factorized to linear factors

Question:
Over which of the following fields $x^{4} - 2x^{3} + 2x^{2} - 2x + 1$ can be factorized
  to linear factors?

$\mathbb{C}$ 2. $\mathbb{Q}$ 3. $\mathbb{Z_2}$ 4. $\mathbb{Z_3}$

There is no answer in the textbook, so I wanted to check if my solution is correct.
After linear factorization over reals I get the following factors:
$(x-1)(x^{2}+1)(x-1)$

Over $\mathbb{C}$, Yes, (x-1)(x-1)(x+i)(x-i)
Over $\mathbb{Q}$, No, because $(x^{2}+1)$ doesn't have roots over $\mathbb{Q}$
Over $\mathbb{Z_2}$, (I am not sure if that is a correct step) first, I convert $x^{4} - 2x^{3} + 2x^{2} - 2x + 1$ to $\mathbb{Z_2}$, so we get $x^{4}+1$, now there are factors $(x^{2}+1)(x^{2}-1)$, so the root is 1, as a check $1^{4}+1$ = 0, so Yes
Over $\mathbb{Z_3}$, First, convert $x^{4} - 2x^{3} + 2x^{2} - 2x + 1$ to $\mathbb{Z_3}$, so we get $x^{4} + x^{3} + 2x^{2} + x + 1$, now I couldn't find any linear factorization here and checks for 0,1,2 did not reveal any roots, so No

Questions:
a) Is the step with converting polynomial to $\mathbb{Z_2}$ and $\mathbb{Z_3}$ correct or I completely misunderstood that? If not, what would be the correct way?
b) Is there any useful trick to quickly determine if polynomial of degree n irreducible/not linearly reducible in $\mathbb{Z_k}$?
Comment: Why convert when you have the factorization as $(x-1)^2(x^2+1)$. This means you need to only check if -1 is a square in the field. in $\mathbb{C}$ and $\mathbb{Z}_2$ it is but in $\mathbb{Q}$ and $\mathbb{Z}_3$ it is not.
Comment: Hmmm. That is actually a fair question for you to begin investigating, Jill. You have already considered primes $2$ and $3.$ Bigger question: for which primes $p$ does your polynomial factor completely in $\mathbb Z_p \; ?$
Comment: $x=1$ should be a root in every field...  Also, the polynomial is equivalent to $(x-1)^4+2(x-1)^2$, so that might help identify roots more easily.
Comment: @Marco indeed...didn't think about it for some reason, thanks!
Comment: take a look at this one. For inspiration.  https://math.stackexchange.com/questions/2887405/set-of-primes-p-which-x4-x3-2x2-2x-1-completely-factors-in-finite-field-o
Comment: Note that @Marco has given a complete solution for *all* fields: Your polynomial factors into linear factors over a field if and only if that field contains a square root of $-1$.
Answer: Your solution is correct.
Note that you have $$ (x-1)^2(x^2+1)$$ so your only remaining concern about linear factorization is  $x^2+1$ which factors on $\mathbb {C}$ and $\mathbb {Z_2}$ and does not factor over $\mathbb {Q}$ and $\mathbb {Z_3}$ because in  $\mathbb {Z_2}$ we have $x^2+1=x^2-1$ which factors  and  in  $\mathbb {Z_3}$ we have $(x^2+1)=x^2-2$ which does not factor.


Towards a census

Question: If we want to define ourselves, and who we want to be as community, it might be informative to explore who we are now. Therefore, I propose a census. This of course voluntary, and might reflect strong self-selection (meta? what is that?). Still, this might be anecdotally interesting.
Before actually carrying it out, we could discuss about:

whether it is worth it,
if so, what is the best approach to it

As I think it is worth it, I will add my proposal as an answer. You could comment on it, add your own, and of course argue against the whole idea though comments, votes, flags, another answer, DDoS attacks, account hacking, et cetera.
Comment: There was a similar, albeit less ambitious, attempt in 2015 which received a rather limited response: https://economics.meta.stackexchange.com/questions/1298/what-is-your-level-of-expertise/1306#1306
Comment: I agree it would definitely be interesting - but i wonder what use can we make of it, and which reach would we have. Say that you get 20% of the members to respond and you find out that most are academics or students. What happens then? (Not flaming, just trying to be constructive before we invest our time ;)
Comment: Worse than a yes/no is (almost) complete indifference... :(
Answer: Proposal

Make the survey through a meta post, rather than an outside online poll mechanism.
This should be a community wiki post, and remain open until the end of times.
Make it featured. This way it will appear in the main site and attract surveyees.
The options to be voted are predefined in advance.
Protect the question so that no more answers than those predefined are allowed (could be changed by mod of course).
One category per answer.
I propose to predefine the categories in advance. I suggest:

Undergraduate student of economics or finance
Undergraduate student, other
Graduate student of economics or finance
Graduate student, other
Post-doctoral student in economics or finance
Academic (lecturer, associate professor, professor, etc)
Professional economist (e.g. working in a research institute, think-tank, finance, etc)
Hobby economist (general interest in economics but not formal studies).

Regarding the voting, I suggest each votes up the answer that represents her/him, but only one answer per person. This probably cannot be enforced, so remains voluntary (no downvoting undegraduates please).
Anonymous? Not sure, but if not, we could ask each user that votes to include her/himself in the answer via editing, ideally via linking to her/his profile page.
Cannot think of anything else... maybe we could bet on the outcome? :)
Comment: One refinement on the categories: the student options are for current students or people who graduated as such? My example: i'm a management consultant who graduated from economics 10 years ago. I don't identify so much with professional economist, but i do identify myself with "Professional with economics studies". Would it make sense to separate?
Comment: Do we need the distinction of study levels? Several master and doctoral students would be simultaneously researcher/ academics.
Comment: @JoaoBotelho I think academic is widely understood as **not being a student**, but a full-time researcher (+ maybe teaching).
Comment: If you must a poll, consider using comments rather than answers: comments can only be upvoted, not downvoted
Comment: I think "graduate student" is too broad a category. It can refer to Masters or PhD students and in countries with widespread terminal Masters degrees (e.g. Europe) there is a big distinction between a Masters and a PhD student.

Towards a census


Intersection of two parabolas with perpendicular axis

Question: Let there be two parabolas:
$$y^2+2kx=k^2 \tag{1}$$
$$x^2+2ky=k^2 \tag{2}$$
What will be the point of intersection of these two curves? The general form of intersection of such two curves would lead to solving a quartic equation(a lengthy solution), which I want to avoid, since there is clear symmetry in the two parabolas, as visible after plotting them, and also evident from the Wolfram's Solution. So, I'm trying to find the solution by exploiting the symmetry (if possible), and not by going through the quartic equation.
Along the lines of this post, I added eqns (1) and (2):
$$y^2+x^2+2ky+2kx=2k^2$$
After completing the square,
$$(y+k)^2+(x+k)^2=(2k)^2\tag{3}$$
Let $k>0$, then the circle in (3) has centre at $O'=(-k,-k),$ and radius $2k$. For $k=6$, the parabolas and the circle look like this:
Clearly, the first intersection point $P(x,y)$ has $x>0,y>0$. Drawing a radius from centre of circle $O'$ to point $P(x,y)$, $O'P=2k$.
Let origin be $O(0,0)$. Then $O'O= \sqrt2 k$.
As $O'P=O'O+OP,$ $ OP=2k-\sqrt 2 k= \sqrt2 k(\sqrt2-1)$.
Also, $OP=\sqrt{x^2+y^2},$
so $\sqrt{x^2+y^2}= \sqrt2 k(\sqrt 2 -1)$
Now I only need to put $x=y$ to obtain $x=y=k(\sqrt 2-1)$, which is indeed one of the solution given by Wolfram Alpha (for $k>0$). However, I can't think of how to state $x=y$; I assumed this after seeing the solution by WA. But, if we let $x=y$ in (1) and (2), then it reduces to solving a quadratic and all solutions can be obtained as $x=y=\pm \sqrt2 |k|-k$.
By (3), the circle has centre at $(-k,-k)$, which means the circle remains the same even if we interchange the X and Y axis. And since the intersection points lie on the circle, so $x=y$ for intersection point(s) $P(x,y)$. Is this reasoning correct? It feels more like an assumption, but it gives the answer, so it is true, but how can it be proven? Or is there any alternative for finding solution?
Comment: Substract the equations...
Comment: Thanks a lot. I have no idea how I missed this. Subtracting the eqns, it gives $y=x$ (which is true), and $y+x+2k=0$. How to know that the second equality doesn't hold?
Comment: this is $y+x-2k=0$ report in the original equations and eventually discard it (delta<0)
Comment: Sorry, my mistake! Thanks.
Answer: Since one curve is the reflection of the other across the line $y = x$,
there are two possible kinds of intersections:

Points on the line $y = x$.
Pairs of points not on the line $y = x$, such that the pair is symmetric across the line $y = x$.

To find points of the first kind, replace $y$ be $x$ in one of the equations.
(Choose either equation; the result is the same.)
Now you just have to solve a quadratic equation in $x$.
The rest of the solution is to show that there are no other solutions.
Graphically, it's obvious, but I don't propose that as a proof.
From $x^2+2ky=y^2+2kx$ we can derive
$$ (x + y)(x - y) = 2k(x - y), $$
so either $x - y = 0$ (the first kind of solution) or $x + y = 2k$.
Substituting $2k - x$ for $y$ in Equation $(1)$, we find that $x = k = 0$,
hence also $y = 0$, so this is actually not a solution of the second kind but just the first kind of solution for the special case where $k = 0$.

In fact, the solution of $x^2+2kx=k^2$ along with the assertion $y = x$ finds both of the actual solutions.
Comment: The intersection points of first kind seems more obvious to me than those of second kind. The first kind can be interpreted as solution of $f(x)= f^{-1}(x)$ ( the eqns here aren't functions, it's just an analogy), and solution of $f(x)=f^{-1}(x)$ lie on   $y=x$. But how does intersection points of second kind exist?
Comment: The second kind does **not** exist in this problem. But consider the intersection points of the two curves $x^2+2y^2=1$ and $y^2+2x^2=1$. Then you have both kinds of solution. The idea is that if there is any intersection that is **not** on the line $y=x$, then you can reflect both curves across $y=x$ and the intersection also is reflected across $y=x$. Therefore such intersections can only occur in pairs.
Comment: Thanks. I'm closing the question now.


The order type of the rationals.

Question: Herewith another mind-numbingly naive question from a reader of philosophy.
My question concerns the order type of the rational numbers.
Omega squared seems a natural first choice, but obviously this does not look anything like the natural ordering of the rationals.
Is it known where the order type of Q occurs in the hierarchy of ordinal numbers?  Is there a known ordinal-arithmetic expression describing it a function of omega?
Finally, I really must buy a textbook on the subject of Set Theory.  Wiki is a fantastic resource and the maths pages are of exceptionally high quality, but I don't want to get into bed at night with my laptop.  Is there a standard, undergraduate text that could be recommended.
Comment: The order type of the rationals, which as Asaf points out is not an ordinal,  is often denoted with $\eta$.
Comment: Note we are all assuming that when you say "the rationals", you are referring to the rationals *along with* their usual ordering.
Comment: @Hurkyl  That's a very good point.  I really need to take a course on this subject!
Comment: @MJD Somehow I missed your comment earlier.  That's very helpful.  Not all order types are represented as ordinal numbers.
Answer: The ordinals are order types of well-ordered partial orders. The rational numbers are not well-ordered, therefore their order type does not occur within the ordinal hierarchy.
Comment: Thanks again Asaf.  I really must do a course on this subject!
Comment: Yes. That is a good idea.
Answer: E. Kampke's book on set theory, which I think has a Dover edition, has some material on the order type of the rationals.  It's not found among the ordinals because it's not well-ordered.  However, there's a proof, which I seem to recall goes back to Cantor, proving that any two countable linearly ordered sets without endpoints that are densely ordered (i.e. between any two points there's another) are order-isomorphic.
Comment: You probably have to add "countable" in your theorem.
Comment: [Relevant earlier discussion](http://math.stackexchange.com/a/13796/25554); it agrees with you that the theorem is due to Cantor. [Also relevant](http://math.stackexchange.com/questions/37151/showing-any-countable-dense-linear-ordering-is-isomorphic-to-a-subset-of-mat).
Comment: @Michael Hardy.  Thanks for your recommendation and your interesting comment.
Comment: @GEdgar : Done.  I'm surprised I forgot that.  BTW, the same method of proof show that up to isomorphism there is only one countably infinite atomless Boolean algebra.

The order type of the rationals.


Difference between Functions and polynomial equations

Question: Why the function
$f(x) = x-5 $
is not equal to the function
$g(x) = \frac{x^2-25}{x+5}, x\ne-5$
Where can we say the equation are same i.e. $x-5$ and $\frac{x^2-25}{x+5}$, in case these were not any functions.
As $\frac{x^2-25}{x+5}$ is same as $x-5$.
Comment: I upvoted to partially reverse the anonymous downvotes, which I disagree with for two reasons: (1) If you are going to downvote a new user's query, I think it is reasonable to tell him why, so he can try to improve his query. (2) I can only think of two reasons that the query may have been downvoted: (2a) Poor formatting -  If that was the reason, why not simply cite the mathJax article and give him a chance to edit the query. ...see next comment
Comment: (2b) No work shown - my opinion, which seems to be in the minority, is that since the query involved questioning a definition or interpretation, as opposed to attacking/solving a math problem, there isn't really work for the OP to show.
Comment: @user2661923 Thanks dear but still my question is understandable by someone that's why 5 answers are already given . So why they downvote
Comment: I didn't downvote, I upvoted to partially reverse other downvotes.  I don't think that the question should have been downvoted at all.  I tried to make this clear in my previous comments.
Answer: $$f(x)=x-5\\g(x)=\frac{x^2-25}{x+5}=\frac{(x-5)(x+5)}{x+5}$$
If $x\neq -5$, then we can simplify $g(x)$, so that $$g(x)=x-5$$
So both $f(x),g(x)$ are the same on the domain $(-\infty,-5)\cup(-5,\infty)$. However, if we also include $-5$ in our domain, we will get:

$f(-5)=-10$
$g(-5)=\frac{0}{0}$

The last value is undefined, and so they don't agree.
If you were to dra both $f(x),g(x)$ then the only difference would be that $g(x)$ makes a "jump" at $x=-5$.
Often this is drawn as follows:
Comment: But if they were not functions but just polynomial expressions can we say that both the expressions are equal.
Comment: That's a good question, and it really depends on your definition of "equality". If you only consider them as elements, without thinking about $x$ as a variable, then in some sense, yes.
Comment: oh that means suppose, if  there is a problem or question in which the expression were created for specific purpose and x should not be variable but a single element to fit with the condition of the problem then the expression are equal
Answer: $g(x)$ is not defined at $x=-5$. But $f(x)$ is defined at every point. So you see the domains of the functions are different.
Comment: why is this downvoted?
Comment: Hey dear but as we simplify the "x²" expression we actually get x-5 . So the "x²" expression  is actually x-5 . My question is if we can't say the function is identical but can we say the expression are equal or the expressions can be termed like any numbers so can we say the number are identical. Or what other term can we use to say the expression are equal not the functions
Answer: Because $\;x-5\;$ is defined in the whole real line $\;\Bbb R\;$, whereas $\;\cfrac{x^2-25}{x+5}\;$ isn't defined at $\;x=-5\;$, i.e.: it is defined only at $\;\Bbb R\setminus\{-5\}\;$.
Remember: two identical functions must (necessary condition) have the very same definition domain.
Comment: Hey dear but as we simplify the "x²" expression we actually get x-5 . So the "x²" expression  is actually x-5 . My question is if we can't say the function is identical but can we say the expression are equal or the expressions can be termed like any numbers so can we say the number are identical. Or what other term can we use to say the expression are equal not the functions
Comment: @Debakant "Dear"? ... Anyway, I've no idea how you mean to simplfy $\;x^2\;$ ...what is simplified is the thole expression in the numerator with the whole expression in the denominator. And the explanation why can't they be identical is there.
Answer: The way you have written $f(x)$ and $g(x)$ is that these are identical functions when $x\ne -5$. Since there is a disagreement at one point of the solution , $(x-5)$ and $\frac{x^2-25}{x+5}$ are non-identical.
Comment: You can cancel a factor up and down or on LHS and RHS only if the factor itself is non-zero. So the moment you are doing so called factorization are assuming $(x+5)=\ne 0.$  Next, in this equation: $2(x+5)=3(x+5)$ if you cancel $(x+5)$ you get $2=3.$
Comment: Hey dear but as we simplify the "x²" expression we actually get x-5 . So the "x²" expression  is actually x-5 . My question is if we can't say the function is identical but can we say the expression are equal or the expressions can be termed like any numbers so can we say the number are identical. Or what other term can we use to say the expression are equal not the functions


Erro sem solução

Question: Boa Tarde pessoal fiquei a semana inteiro quebrando cabeça com uma aplicação e não consegui resolver, eu pago quem me ajudar sem problema... Pra explicar melhor fiz um video e postei no facebook...
OBs: em algumas maquinas funciona normal e em outras não, ja formatei, ja fiz de tudo...Ja testei em umas 10 maquinas, algumas funcionam e outras não, não descobrir o porque, todas que testei foi com windows 7 32 e 64 aleatoriamente
linnk https://youtu.be/2lvW1g5-sOE
Comment: Alguma diferença de antivírus nas máquinas? Sandbox algo assim?
Comment: Muito difícil descobrir o que pode ser, já tive problemas no passado onde o programador anterior, que fez o sistema, instalou o .exe no servidor e mapeou as unidades de rede das outras máquinas apontando para ele, fazendo o carregando remoto através de um atalho nas máquinas clientes. Resolvi deixando o .exe na maquina cliente, como costumo fazer sempre. Mas não tem como saber. Na minha experiência, erros de memória são os mais complicados de descobrir para quem esta olhando de fora.
Comment: Tenta utilizar o EurekaLog, pode ser que exiba mais informações
Comment: Já tentou fazer um Debug na máquina onde apresenta o erro? Instala o Delphi e executa no modo de Debug, de repente você consiga identificar a linha que está causando.
Answer: Tivemos um problema misterioso assim também.
Dá uma olhada em sua Midas.dll substitua por outra, de uma máquina que esteja funcionando.
Boa sorte.

Erro sem solução


Múltiplo UPDATE a partir de um campo dinâmico

Question: Estou tentando pegar os ids que vem por checkbox selecionados pelo user (array), e através desses ids, fazer um update na tabela, com o código a seguir:
$ocs_imp = $_POST['check_imprime'];
$contar = count($ocs_imp);
$id = implode(',',$ocs_imp);

   $inicio = 0;
   $ultimo = $contar-1;
   $arr = range($inicio, $ultimo);

$sqli = "";
     foreach ( $arr as $k => $v ) {
$sqli .= "UPDATE oc_cadastro SET imprime_oc='s', imprime_oc_data='".$pega_data."' WHERE id = '".$ocs_imp[$v]."')))";
                                  }

                            $mysqli->query($sqli);

Porém não está funcionando, não apresenta erro, simplesmente não atualiza os registros, também tentei com WHERE id IN ($id), sem sucesso.
Comment: Removi as saudações e agradecimentos da sua pergunta. Entenda o motivo [aqui](http://meta.pt.stackoverflow.com/a/851/3907).
Removi as tags do título da sua pergunta. Entenda o motivo [aqui](http://meta.pt.stackoverflow.com/a/1911/3907).
Comment: Blz @FrancescoPerrotti-Garcia
Comment: O que está em `$mysqli->error` depois de ter executado a query?
Comment: Adicione na sua pergunta o erro que você está recebendo que fica mais fácil de te ajudar.
Comment: Obrigado por responder André, não há erro impresso na tela, o procedimento é o sistema pegar os ids e abrir outra página, e ao mesmo tempo fazer o update como no código postado, porém ele abre a outra tela com os ids, mas não faz o update conforme código.
Comment: Já verificou se o `$_POST['check_imprime']` está retornando  os dados esperados?
Comment: Já sim @luciorubeens, tanto que com os id s recuperados, ele executa outra função que não vem ao caso, e é nessa hora que ele deveria fazer o update e não faz, estou em dúvida se esse código está correto, ou se existe outra maneira.
Comment: Blz, já testou a saída do `$sqli` diretamente no banco?
Answer: O problema no código está na concatenação dos SQLs na variável $sqli e executando todos os querys juntos.
Cada query deve ser executada sozinha dessa forma sugiro:
foreach ( $arr as $k => $v ) {
    $sqli = "UPDATE oc_cadastro SET imprime_oc='s', imprime_oc_data='".$pega_data."' WHERE id = '".$ocs_imp[$v]."'";
    $mysqli->query($sqli);
 }

Espero te-lo ajudado.
Answer: Tem alguns parentesses sobre no seu update:
"UPDATE oc_cadastro SET
    imprime_oc='s',
    imprime_oc_data='".$pega_data."'
WHERE id = '".$ocs_imp[$v]."')))";
                             ^^^
--------------------------------

Tinha sugerido anteriormente o uso de multi_query() que executa várias instruções sql separadas por ponto e vírgula(;) porém esse método não parece se adequado para INSERT/DELETE/UPDATE porque ele verifica apenas se a primera instrução está correta e retorna true mesmo que as demais possuam erros ou seja ele executa todas instruções até encontrar o primeira errada e para e retorna true como se tudo estiver certo, com isso registros são inseridos/atualizados/removidos pela metade.
Para processar vários INSERTS de uma só vez use multiplos valores na cláusula VALUES ex:
INSERT INTO tabela (c1, c2, c3) VALUES ('v1', 'v2', 'v3'), ('v12', 'v22', 'v32')

No caso do DELETE basta passar os ids na cláusua IN ex:
DELETE FROM tabela WHERE id IN (1,2,3,4,5)

No caso do UPDATE para ter certeza de que todos os registros serão modificados desligue o auto commit, isso significa que o código fonte e não o banco é responsável por efetivar a transação rollback para falha e commit para sucesso. Rode as consulta usando query() dentro do foreach.
Opções - sprintf
$mysqli->autocommit(false);
$sqli = "";
$erro = false;
foreach ($arr as $k => $v) {
   $sqli = sprintf("UPDATE oc_cadastro SET
                        imprime_oc = '%s',
                        imprime_oc_data = '%s'
                    WHERE id = %d;", 's', $pega_data, $ocs_imp[$v]);

   if(!$mysqli->query($sql)){
      $erro = true;
      echo 'Atualização cancelada:
'. $mysqli->errno .' - '. $mysqli->error;
      break;
  }
}

if($erro == true)
   $mysqli->rollback();
else
   $mysqli->commit();

Uma observação:
No trecho da pergunta $k(contém os índices do array) não é utlizado em nada, pode então simplificar um pouco o código e removê-la pois $item terá o mesmo valor de $v.
foreach($arr as $item){
   " ... WHERE id = %d;", 's', $pega_data, $ocs_imp[$item]);

Comment: Perfeito @rray, como sempre funcionou perfeito. Obrigado mais um vez, não sabia desses comandos rollback e commit, vivendo e aprendendo! Obrigado!
Comment: @DenisL.Murara Isso é chamado de transação em duas fases, alguns bancos deixam por padrão a opção `auto commit` como true outros te obrigam a dar rollback/commit. Ainda falando de transações você pode procurar por alguns assuntos relacionados como, niveis de isolamento, ACID e check save/point que um complemento do rollback/commit.
Answer: Considerando que o retorno do seu $_POST['check_imprime'] já é um array:
$ocs_imp = $_POST['check_imprime'];
$sql = "";

foreach ($ocs_imp as $id => $val) {
   $sql .= "UPDATE .. WHERE id = {$val};";
}

$mysqli->query($sql);


Is harmonic Hardy space $h^p (D)$ complete for $0<p<1$?

Question: Let $D$ be the unit disk and $0<p<1$. Let $h^p(D)$ be the harmonic Hardy space on the unit disk (i.e. $u\in h^p(D)$ if and only if $u$ is harmonic on the disk and $\sup_{0<r<1}\int_{-\pi}^\pi|u(re^{it})|^p\frac{\operatorname{d}t}{2\pi}<+\infty$), equipped with its natural metric, i.e. $$d(u,v):=\sup_{0<r<1}\int_{-\pi}^\pi|u(re^{it})-v(re^{it})|^p\frac{\operatorname{d}t}{2\pi}$$
I've the following question: is $(h^p(D),d)$ complete? The failure of Young's convolution inequality prevents me to prove the result following the same path that works for harmonic Hardy spaces with $p\ge1$ (i.e.: using the Poisson reproducing formula for harmonic functions and then use Young's convolution inequality), to get uniform convergence on compact subsets of $D$ (does it even hold true here? Or at least the point evaluation functionals are continuous?), so I don't know if the limit function defined circle by circle (using the fact that $L^p$ is a complete metric space) is actually continuous, even less harmonic.
Comment: I _believe_ that you could prove that the analogous space of _holomorphic_ functions is complete by using the fact that if $f$ is holomorphic then $|f|^p$ is subharmonic. But $u$ harmonic does not imply that $|u|^p$ is subharmonic for $0<p<1$, so I wonder if it's even true that your space is complete.
Comment: For the case $H^p(D)$ with $0<p<1$, I know the path through factorizing out the zeros of the function dividing by the Blaschke product of its zeros, taking a $p$-th power, obtaining the uniform estimate on compact sets we were looking for in terms of the $p$-th "norm" using the $H^1(D)$ estimate we already knew. Can you hint me how we can reach the same conclusion through subharmonicity? I tried, but i failed...
Comment: I've got what you mean: $|f(z)|^p\le \frac{1}{2\pi r} \int_{\partial D_r(z)}|f(\zeta)|^p|d\zeta |\le\frac{1}{\pi r} \int_{\partial D_R(0)}|f(\zeta)|^p|d\zeta |$, if $z\in D$ and $r\in(0,1)$ is such that $\partial D_r(z)\subset D$ and $R\in (0,1)$ is such that $\partial D_r(z)\subset D_R(0)$.
Comment: All I said was I _believe_ one can. Will think about it and get back to you.
Comment: Hence Cauchy in $H^p$ implies uniform convergence on compact sets. That much is clear - the details getting from there to convergence in $H^p$ are what I haven't got yet...
Comment: I saw how Duren in his book on $H^p$ spaces concludes once he gets the uniform estimate... If I get at all what is the point, we need, for $g\in H^p(D)$ and $r\in(0,1)$, that $\int_{-\pi}^\pi|g(re^{it})|^p\frac{\operatorname{d}t}{2\pi}\le\int_{-\pi}^\pi|\tilde{g}(t)|^p\frac{\operatorname{d}t}{2\pi}$ to get $\lim_{n\rightarrow\infty} \sup_{0<r<1}\int_{-\pi}^\pi|f_n(re^{it})-f(re^{it})|^p\frac{\operatorname{d}t}{2\pi}=0$, so it seems that we need anyway subharmonicity contrary to what I thought... probably then is time to look for counterexamples for the $h^p(D)$ case...
Comment: Me stupid - the bit I was stuck on is just Fatou's Lemma. Btw there are some constants missing in the inequalitites above about $|f|^p$ being subharmonic...
Comment: The non-answer has been greatly expanded - some of it may be iilluminating.
Answer: If I didn't make any silly mistake $h_p$ indeed is complete. We will first prove that for every $z\in D$ $u\to u(z)$ is continuous. To do so we will need the following estimate (see Fefferman and Stein "$H^p$ spaces of several variables", 9; Lemma 2, page 172):
Theorem 1.
There exists constant $c_p > 0$ such that for every harmonic function $u$ in $D$ we have
\begin{equation}\label{H-L}
|u(0)|^p \le \frac{c_p}{|D|}\int_D |u(z)|^pdz.
\end{equation}
(Note that we are integrating over the whole disk, not over spheres!)
From this theorem it is easy to deduce that $z\to u(z)$ is indeed continuous and we also have uniform control of the constant on the compact subsets of $D$ (consider a small ball centred at $z$ and estimate rhs in Theorem 1 by constant times $h_p$-norm of $u$). Now we are ready to prove the desired result:
Theorem 2. $h_p$ space is complete.
Proof
Let $u_n\in h_p$ be a Cauchy sequence. From above reasoning we can easily see that for every $z\in D$ $u_n(z)$ is a Cauchy sequence and moreover convergence is uniform on compact subsets of $D$. From this it follows that we have $u(z) := \lim_{n\to \infty} u_n(z)$ is a harmonic function on $D$. It remains to prove that $u_n\to u$ in $h_p$ (note that $u\in h_p$ obviously by Fatou lemma).
For $n \ge N$ we have that $d(u_n, u_N) \le \varepsilon$. Then $u_n - u_N$ pointwise converges to $u - u_N$ and again by Fatou $d(u, u_N) \le \liminf d(u_n, u_N) \le \varepsilon$. Thus since $\varepsilon$ is arbitrary $u_N \to u$ in $h_p$.
Comment: Thanks for the answer. Can you provide a proof or a reference for theorem 1?
Comment: @Bob added link to the proof of Theorem 1, sorry that it took a while to find correct reference.
Answer: Not an answer to the question, but a discussion of related issues arising in the comments.
The closest I have   to an answer is that I'd be very surprised if $h^p$ was not complete, but I have no idea how to prove it's complete.
General Comment: Reading Duren is a Good Thing. If you like Duren you'll love Garnett Bounded Analytic Functions. But you should be aware that these days "complex methods" are deprecated, because they don't extend to other contexts where people want to do analogous things. And from that point of view Blaschke products are positively evil, being totally and irredeemably "complex". You've seen an example of this already - Blashcke products are obviously useless for the current question. Otoh the argument by subharmonicity could have worked, it just doesn't.
What argument?

The completeness of $H^p$ for $0<p<1$ is immediate from the fact that $f$ holomorphic implies that $|f|^p$ is subharmonic.

If $K\subset\Bbb D$ is compact there exists $c_K$ such that if $u$ is subharmonic in $\Bbb D$ and continuous on $\overline{\Bbb D}$ then $$\sup_{z\in K}u(z)\le c_K\frac1{2\pi}\int_0^{2\pi}u(e^{it})\,dt.$$
Say $(f_n)$ is Cauchy in $H^p$. Since $|f_n-f_m|^p$ is subharmonic it follows that $|f_n-f_m|^p\to0$ uniformly on compact sets, hence $f_n\to f$ uniformly on compact sets. And this implies by Fatou's Lemma that $||f_n-f||_p\to0$, where $||.||_p$ is the sup over $r$ of the $L^p$ norm on circles of radius $r$ about the origin. (If $||f_n-f_m||_p<\epsilon$ for all $n,m>N$ and $n>N$ then FL says $$\int_0^{2\pi}|f(re^{it})-f_n(re^{it})|^p\,dt\le\liminf_{m\to\infty}\int_0^{2\pi}|f_m-f_n|^p\le\epsilon$$for every $r\in(0,1)$.)
So the completeness of $H^p$ really is immediate from the fact that $|f|^p$ is subharmonic. But if $u$ is harmonic then $|u|^p$ need not be subharmonic for $0<p<1$.
(For example: Say $u=P[\mu]$, where $\mu$ is a measure on the circle. If $|u|^{1/2}$ is subharmonic then $\mu$ is absolutely continuous.)
A proof of that last statement leads to stuff about the F&M Riesz theorem.
We need to recall a fact about $1<p\le\infty$, in order to be able to talk about what goes wrong for $p=1$:

Proposition 0. If $1<p\le\infty$ and $u\in h^p$ then $u=P[f]$ for some $f\in L^p(\Bbb T)$.

Proof: For $0<r<1$ define $u_r:\Bbb D\to\Bbb C$ and $f_r:\Bbb T\to\Bbb C$ by $$u_r(z)=u(rz), f_r(e^{it})=u(re^{it}).$$Then $$u_r=P[f_r].$$Since $||f_r||_p$ is bounded and $p>1$ there is a sequence $r_j\to 1$ with $f_{f_j}\to f$ weakly in $L^p$. (Not that the sequential part really matters, but if $X$ is a separable Banach space then the unit ball of $X^*$ is sequentially compact in the weak* topology.) Hence $P[f_{r_j}]\to P[f]$ pointwise, hence $u=P[f]$.
Of course if $\mu$ is a singular measure on $\Bbb T$ then $u=P[\mu]$ shows that Proposition 0 fails for $p=1$. And it's clear what goes wrong with the proof: The unit ball of $L^1$ is not compact in any relevant topology. For $p=1$ the proposition becomes

Proposition 0.1. If $u\in h^1$ there exists a (regular complex) measure $\mu$ on $\Bbb T$ such that $u=P[\mu]$.

The reason I mention all that is to show how surprising the following is:

F&M Riesz Theorem. If  $f\in H^1$ then there exists $F\in L^1(\Bbb T)$ with $f=P[F]$.

(If that's not the statement you think of as the F&M Riesz theorem it's in any case the hard part; various versions of the theorem are immediate from the above. I'm going to call it F&M Riesz below.)
In fact F&M Riesz follows easily from the fact that $|f|^{1/2}$ is subharmonic. This is actually analogous to the proof you know, by Blaschke products: Let's define another space - say $sh^p$ is the space of subharmonic functions with bounded $p$-th means on circles. The proof of F&M Riesz in Duren uses the fact that $f$ is the product of two $H^2$ functions. The proof below uses the analogous but much more trivial fact that $|f|$ is the product of two functions in $sh^2$ (it's obvious that if $f\in H^1$ then $|f|^{1/2}\in sh^2$.)
For the proof:

Lemma. If $1<p\le\infty$ and $u\in sh^p$ then there exists $f\in L^p(\Bbb T)$ with $u\le P[f]$.

Proof: Same as the proof of Proposition 0, with $u_r\le P[f_r]$ in place of $u_r=P[f_r]$.
Oops In that proof we need to assume that $u$ is continuous, to get $u_r\to u$ pointwise. That case is sufficient for our application below. In fact the Lemma holds for a general (usc) subharmonic function, by essentially the same argument - use the solution to the Dirichlet problem on the disk $D(0,r)$ instead of using those dilations to transfer to $\Bbb D$.
Now if $\phi:\Bbb D\to\Bbb C$ let $M\phi$ be the radial maximal function:
$$M\phi(e^{it})=\sup_{0<r<1}|\phi(re^{it})|.$$

Corollary If $1<p\le\infty$ and $u\in sh^p$ then $Mu\in L^p(\Bbb T)$.

Now, just to emphasize that we're really using nothing but the fact that $|f|^{1/2}$ is subharmonic, we point out that F&M Riesz is an immediate corollary of this:

Theorem. Suppose $\mu$ is a (regular complex) measure on $\Bbb T$ and $u=P[\mu]$. If $|u|^{1/2}$ is subharmonic then $\mu$ iis absolutely continuous.

Proof: Since $u\in h^1$ it is  clear that $|u|^{1/2}\in sh^2$. So $$M|u|^{1/2}\in L^2,$$hence $$Mu=(M|u|^{1/2})^2\in L^1(\Bbb T).$$
And now we're done: We know that there exists $F\in L^1$, namely the absolutely continuous part of $\mu$, such that $u(re^{it})\to F(e^{it})$ almost everywhere. The fact that $Mu\in L^1$ gives precisely the domination we need to conclude by DCT that $$\int_0^{2\pi}|u(re^{it})-F(e^{it})|\,dt\to0.$$
Comment: You were so bright that I had to wear sunglasses :) This morning I tried without having being succeeded to work out your claim about absolute continuity, so your editing anticipated the answer to my next question. :) Thanks a lot.


Finding expectation from joint distribution

Question: Suppose that $P(X=i,Y=j)=c(i+j)$ for non-negative integers $i$ and $j$ with $i+j \leq 3$; otherwise, the probability is zero.
(f) Compute $E[XY]$
(g) Compute $E[X]$ and $E[Y]$
(h) Compute $E[X+Y]$
only parts f,g,h below
I've done the previous parts a to e but am confused with the parts related to mean E
I have attached a picture of my work for parts a to e for reference
Comment: Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for typesetting math.
Answer: You've miscalculated $c$, it should be $1/20$, the points with non-zero probability mass are $$\mathcal{S}=\{(0,1),(0,2),(0,3),(1,0),(1,1),(1,2),(2,0),(2,1),(3,0)\}$$
Anyway, this won't change the calculation method of (f-h). Since you have the marginals, and they're same for $X,Y$ due to symmetry, we have $E[X]=E[Y]$:
$$E[X]=\sum_{i=0}^3 iP(X=i)$$
For (h), we'll use the linearity of expectation: $E[X+Y]=E[X]+E[Y]=2E[X]$. For (f), we need a double summation since it's a joint statistic:
$$E[XY]=\sum_{i+j\leq 3}ijP(X=i,Y=j)=P(X=1,Y=1)+2P(X=2,Y=1)\ ...$$


Oracle 8, SQL: RTRIM for string manipulation is not working as expected

Question: Oracle 8 SQL: I do have data like "VTR 564-31 / V16 H12 W08 E19 L14" from which I want to trim the second part => "VTR 564-31"
According to this website I can use the rtrim function

rtrim('123000', '0'); would return
  '123'

like this it works, but adapted to my use case, the following one does not trim at all? Do I have to escape the special character???

rtrim('VTR 564-31 / V16 H12 W08 E19 L14',' / ')
Answer: RTRIM removes characters specified in the second parameter from the end of the string specified in the first.  Since the last character of 'VTR 564-31 / V16 H12 W08 E19 L14' is a '4', which is not specified in the second parameter ' /', there is nothing to trim.
It looks like you think it looks for the first occurence of ' /' in the first string and removes everything from there on, but that's not what it does.
For example:
SQL> select rtrim('AAABBBCCCBBBAAA','AB') from dual;

RTRIM('AA
---------
AAABBBCCC

RTRIM removed all the As and Bs from the end of the string.
Probably what you actually want is:
select substr(yourstring, 1, instr(yourstring, ' / ')-1) from dual;

i.e. use INSTR to locate the position of ' / ' and then SUBSTR to get just the part of "yourstring" before that.
Answer: What you want is something like:
SELECT RTRIM(SUBSTR('VTR 564-31 / V16 H12 W08 E19 L14',1,INSTR('VTR 564-31 / V16 H12 W08 E19 L14','/')-1),' ')
FROM DUAL;

The INSTR function locates the '/' in your string value, the SUBSTR function extracts the characters from the start of the string to the character immediately before the '/' located by INSTR, while the RTRIM removes any spaces that had occurred before the '/'


Rhythmic analysis examples by jack Perricone

Question: My question refers to
PERRICONE, Jack. Melody in songwriting: tools and techniques for writing hit songs. Hal Leonard Corporation, 2000.
In chapter 3 Jack Perricone elaborates on rhythm and explains how to find the amount of stress a note gets naturally by rhythmic stress and metric stress. I know that real world examples don´t work that mechanically but I would like to understand the textbook examples anyway.
I´ve included two of his expanatory measures and the two examples, my quetion refers to, below.
Three rules he gives that might be important here:

Syncopated notes get increased stress
Anticipations receive the stress of the anticipated note and additional stress due to syncopation
Notes after a rest are stressed if they are not shorter than the note before. If they are shorter they are just acting as a pickup for the following beat.

1. Question
Do you know of any other textbook detailing his approach?
2. Question
I have some problems understanding the syncopation and anticipation examples shown below (the letters are not in the book). I would be grateful for any review or remarks on my reasoning!
Syncopation example (alla breve)
(?C?) this should get stressed, since its part of the 1st beat? Does it reveice no stress because it the 2nd 1/8 out of a (hypothetic) group of two which is rhythmically unstressed?
(?D?) no idea. I can´t see why this one is stressed
Anticipation example (4/4)
(?H?) is this on stressed because it´s after a rest and has the same value as the note before? Shouldn´t this give //? Or is this on an anticipated beat 1 of measure 6
(?K?) Weak stress because of rest?
(?M?) Strong stress because of anticipation of beat 3 and syncopation, right?
Any thoughts are greatly appreciated!
Comment: People should give reason for downvote - I see no reason here.
Comment: Maybe it's because of its resemblance to a homework question?
Comment: @jjmusicnotes: Yes in deed, did not understand that.
Comment: @jjmusicnotes Also, people *(not me)* probably dislike that the question takes such a rigorous and mechanical approach to such a subjective part of rhythm. Honestly, this question has well-defined parameters and is completely within its own guidelines, so I see no reason to downvote. That said, as of this writing, it's only one downvote, so maybe it's just someone random who doesn't have any good reason.
Comment: There are endless discussions and analysis about pitch, so I am always glad to see discourse on rhythm and other elements.
Answer: Not familiar with Perricone or his approach but I'll respond to your confusion as a composer.
1.) Nope. Asking for material recommendations is off topic here. Perhaps you should Google more of his materials? Use the scholarly search function to turn up papers that might cite or discuss him.
2.) The "C" isn't stressed and here's why: occurs on a metrically weak part of the beat: what we would consider the "e" of that half-note grouping (as in "1-e-+-a"). Remember in cut time the pulse is at the halfnote. That last quarter receives stress because it's longer than the 8th before it as well as being on a stronger part of the pulse.
3.) "H" anticipation - this gets stress because of aural memory. Since we have a quarter on beat one - when the music repeats we expect another downbeat. However, it comes a half-bear early. To examine, try taking out that last note and repeating the first measure a couple times. Then put it back in - you'll see the stress that it gets.
"K" - not convinced it's anything meaningful. You can only have an anticipation if it subverts expectation. In other words, you need to be able to measure it against something. In this case, the surrounding notes are also syncopated, therefore equal relative to themselves. Thus, labeling them as "ant" is an attempt to shoe-horn meaning.
"M" is interesting. It anticipates a rhythm on downbeat 4. It's length collects and recenters the pulse. The type of stress that it anticipates is strong enough such that, to be properly released, that measure would need to be 3/4, the resulting downbeat stress would now be in beat 1 of the repeated phrase. Best 1 is the nose stable in this phrase and therefore has the greatest stress. "M" is the 2ns most stable, and it's anticipation can only be fully resolved by the most stable beat.
Comment: Thank you for your thorough response and good explanation.


Submitting a form rebuilds (expensive) page upon submit

Question: I have a simple menu callback that draws a page with a form on it. The page callback does a very expensive operation (requests a bunch of data from an external API).
function test_menu() {
  $items = array();
  $items['test'] = array(
    'title' => 'Test',
    'page callback' => 'test_page_handler',
    'access callback' => TRUE,
  );
  return $items;
}

function test_page_handler() {
  $data = very_expensive_data_operation();
  $output = drupal_get_form('test_simple_form', $data);
  return $output;
}

function test_simple_form(&$form_state, $data) {
  $form['create'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function test_simple_form_submit(&$form, &$form_state) {
  // do something
}

The problem I am seeing is that when the form is submitted, Drupal will re-execute the page callback in the background, resulting in the very_expensive_data_operation() running again.
There are probably lots of great reasons for Drupal to do this, but how can I change my app so that the very_expensive_data_operation() doesn't have to run again when submitting the form (after all, that's why I'm passing $data to the form, rather than having the form run it directly.)
One workaround I can think of is to toss $data into a cache table, but it feels like I'm missing something that available to me in the Drupal+FAPI api.
Answer: You can also try using drupal_static

Provides central static variable storage.
All functions requiring a static variable to persist or cache data
  within a single page request are encouraged to use this function
  unless it is absolutely certain that the static variable will not need
  to be reset during the page request. By centralizing static variable
  storage through this function, other functions can rely on a
  consistent API for resetting any other function's static variables.

function test_menu() {
  $items = array();
  $items['test'] = array(
    'title' => 'Test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_simple_form'),
    'access callback' => TRUE,
  );
  return $items;
}

function expensive_data() {
  $data = &drupal_static(__FUNCTION__);
  if (!isset($data)) {
    $data = very_expensive_data_operation();
  }
  return $data;
}

function test_simple_form(&$form_state) {
  $data = expensive_data();
  $form['create'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function test_simple_form_submit(&$form, &$form_state) {
  // do something
}

You might notice that the static variable technique only stores data for the duration of a single page load. For even better performance try this
function expensive_data() {
  $data = &drupal_static(__FUNCTION__);
  if (!isset($data)) {
    if ($cache = cache_get('my_module_data')) {
      $my_data = $cache->data;
    }
    else {
      $data = very_expensive_data_operation();
      cache_set('my_module_data', $my_data, 'cache');
    }

  }
  return $data;
}

If you want to refresh your cache from time to time you can try
cache_set('my_module_data', $my_data, 'cache', time() + 360);

OR you can manually rebuild your cache using
cache_clear_all('my_module', 'cache', TRUE);

Answer: I think the best place to run your expensive function is in the form itself, even though you've mentioned you're currently avoiding that.
As it stands, your page callback has no link to the form that's currently being submitted; there are ways you could get it from the cache_form table, but it's a bit messy.
Instead, I'd advise saving the data to a variable in the form, and checking to see if that variable has been submitted in the $form_state array. You'll also need to flag the form to rebuilt in the submit handler:
function test_simple_form(&$form_state) {
  // If the form has already been biult, and we already have the data, don't load it again.
  if (isset($form_state['values']['expensive_data'])) {
    $data = $form_state['values']['expensive_data'];
  }
  else {
    // Otherwise get the data from source.
    $data = my_expensive_function();
  }

  // Store the data
  $form['expensive_data'] = array(
    '#type' => 'value',
    '#value' => $data
  );

  // ...

  return $form;
}

function test_simple_form_submit(&$form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

In your submit handler you'll have access to $form_state['values']['expensive_data'], which will contain the results of the function call.
This method has the added benefit of caching the data if the form validation fails, not just when it's submitted successfully.
Judging from the function signature you're using for the form I'm guessing you have a Drupal 6 site, although the above method will work equally well for a Drupal 7 site (the function signature would just need to change).
Comment: This actually doesn't solve the problem. When you originally draw the form, my_expensive_function() will be run. When you submit the form, it will be run again.  Here's my simple test: http://pastebin.com/07WfQTkw
Comment: @rcourtna Sorry about that I forgot the most important bit (flagging the form to be rebuilt). I've updated the answer; the code's tested and `very_expensive_data_operation()` doesn't run when the form is submitted
Comment: My test shows that very_expensive_data_operation() *does* run again. So it gets run when originally drawing the form, and when submitting the form. You can see this by setting a status message in both very_expensive_data_operation() and in the submit handler. http://pastebin.com/yiJNGrSC
Comment: I copied your original code directly, added the submit handler, and the message in very_expensive_data_operation() was only shown when the form was originally built. When the form was submitted, there was no message shown. It's on a blank Drupal 6.26 installation so I'm not really sure what to suggest
Comment: I'm also on a blank 6.26. Draw original form, VEDO message gets set. Submit, a new VEDO message gets set and then finally the form submit function is called. The only effect that setting $form_state['rebuild'] = TRUE has is that the expensive function doesn't get called a third time (ie: after the form is submitted and the client simply redraws the form page) - the same effect can be achieved by setting form_state['redirect'] = 'node' (instead of setting $form_state['rebuild'] = TRUE).
Comment: You might want to try switching the form item type from `#value` to `#hidden`. Also, you might try checking for `$_POST['form_state']['values']['expensive_data']` (in which case you should be sure to sanitize the data before using it).
Comment: @Clive from my understanding $form_state['rebuild'] is used mostly in multi-step forms right ?? Also I had a look at the api as well. http://api.drupal.org/api/drupal/includes!form.inc/function/drupal_rebuild_form/7  am I missing anything here ??
Comment: @junedkazi Yeah it probably is used mostly in multi-step forms, but all it does is rebuild the form from scratch again (but with a populated `$form_state`), I've found quite a few different uses for it down the years. Not sure if those uses were _intended_ though :)