Integral problems using Weierstrass Approximation Theorem

Question: The question:
(a) Let $f$ be a continuous periodic complex valued function with period $2\pi $.Then prove that given $\epsilon >0,$ there exists a function $Q(x)=\sum_{k=-M}^{M}c_{k}e^{ikx}$ with $c_k\in \mathbb{C}$ and $M\in \mathbb{N}$ defined on $[-\pi ,\pi ]$ such that $\int_{-\pi }^{\pi }\left | f(x)-Q(x) \right |dx<\epsilon $.
(b)Suppose $f$ is a continuous function on $R^{1}$,$f(x+2\pi )=f(x)$, and $\frac{\alpha }{\pi }$ is irrational. Prove that $\lim_{n\rightarrow \infty }\frac{1}{N}\sum_{n=1}^{N}f(x+n\alpha )=\frac{1}{2\pi }\int_{-\pi }^{\pi }f(t)dt$
for every $x$. Hint: Do it first for $f(x)=e^{ikx}$.
My attempt:
(a) $f$ is continuous on $[-\pi ,\pi ]$, so $f$ is Riemann integrable on $[-\pi ,\pi ]$.
Given $\epsilon >0,$ there exists a continuous function g such that $\int_{-\pi}^{\pi}\left | f(x)-g(x) \right |dx<\epsilon $. I wonder how $Q(x)$ is approximated to $g(x)$ here.
(b) I used the hint and put $f(x)=e^{ikx}$ and found that both sides of the equality are $0$, but I don't know how to expand to the trigonometric polynomials and why the condition "$\frac{\alpha }{\pi }$ is irrational" is needed.
Comment: What's $g$ here? Do you mean to say that it's smooth, not that it's continuous? For your first problem, consider the family of trigonometric polynomials $\{\sum_{k=-M}^M c_k e^{ikx} \}$, and show that it satisfies the conditions for the Stone-Weierstrass theorem.
Answer: (a) To get your result, you can use either Stone-Weierstrass approximation theorem or the theory of summation kernels using the fact that the Fejér kernel is a summation kernel and that the convolution between Fejér kernel and an integrable function is a trigonometric polynomial.
(b) Actually, with the instruments you used to prove (a), you get that for all continuous $2\pi$-periodic $f$ and for all $\varepsilon>0$ there exists a trigonometric polynomial $P$ such that $$\sup_{t\in\mathbb{R}}|f(t)-P(t)|<\varepsilon$$
Then, if $\alpha,x\in\mathbb{R}$ and $m\in\mathbb{Z}$ such that $m\alpha\notin2\pi\mathbb{Z}$ you have: $$|\frac{1}{N} ∑_{n=1}^Ne^{im(x+nα)}|=|e^{imx} \frac{1}{N}(\frac{1-e^{im(N+1)α}}{1-e^{imα}}-1)|≤\frac{1}{N}(\frac{2}{|1-e^{imα}|}+1)\rightarrow0, N\rightarrow\infty.$$ So, if $\frac{α}{\pi}$ is irrational, $\forall m\in\mathbb{Z}, ((m\neq0)\implies (m\alpha\notin2\pi\mathbb{Z}))$.
Then, fix a continuous $2\pi$-periodic function $f$ and fix $x\in\mathbb{R}$. For each $k\in\mathbb{N}$, choose a trigonometric polynomial $P_k$, say $$P_k(t)=\sum_{m=-M_k}^{M_k}a_{m,k}e^{imt},$$ such that $$\sup_{t\in\mathbb{R}}|f(t)-P_k(t)|<1/k.$$
Observe that $$a_{0,k}=\int_{-\pi}^{\pi}P_k(t)\frac{dt}{2\pi}\rightarrow\int_{-\pi}^{\pi}f(t)\frac{dt}{2\pi}, k\rightarrow\infty.$$
Then: $$\limsup _{N\rightarrow\infty}{|\frac{1}{N} ∑_{n=1}^Nf(x+nα) -∫_{-π}^πf(t)  \frac{dt}{2π}|}=\\ \limsup _{N\rightarrow\infty}
{|\frac{1}{N} ∑_{n=1}^N(f(x+nα)-P_k(x+nα))+\frac{1}{N} ∑_{n=1}^N P_k(x+nα) -∫_{-π}^πf(t)  \frac{dt}{2π}|}≤\\ {\limsup _{N\rightarrow\infty}{({\frac{1}{N} ∑_{n=1}^N|f(x+nα)-P_k(x+nα)|}) +∑_{m=-M_k, \\m≠0}^{M_k}(|a_{m,k}|\limsup _{N\rightarrow\infty}|\frac{1}{N} ∑_{n=1}^N e^{im(x+nα)}|)+{|a_{0,k}- ∫_{-π}^π f(t) \frac{dt}{2π}|}}}
\\ \le {\frac{1}{k}+{|a_{0,k}- ∫_{-π}^π f(t) \frac{dt}{2π}|}}\rightarrow0, k\rightarrow\infty$$
and you have got the thesis.
Answer: A) is a good exercise in using Stone-Weierstrass (https://en.wikipedia.org/wiki/Stone%E2%80%93Weierstrass_theorem). As noted in your attempt for any $\epsilon > 0$, there exists a $g$ continuous on $[-\pi,\pi]$ such that $ \int_{-\pi}^{\pi}|f(x)-g(x)| < \epsilon/2 $. Now by Stone-Weierstrass, we can uniformly approximate $g$ by a family of trigonometric polynomials. Indeed, this gives us a trigonometric polynomials on $[-\pi, \pi ]$ such that  $\sup_{x}|\sum_{k=-N}^{N} a_ke^{ikx} - g(x)| < \epsilon/4 \pi$. Pulling all of these together with the triangle inequality, one has $ \int_{-\pi}^{\pi}|f(x)-\sum_{k=-N}^{N} a_ke^{ikx}| < \int_{-\pi}^{\pi}|f(x)-g(x)| + \int_{-\pi}^{\pi}|g(x)-\sum_{k=-N}^{N} a_ke^{ikx}| \leq \epsilon/2 + 2\pi*\epsilon/4\pi = \epsilon   $ as desired.
B) After proving the hint, it should follow directly from A), as A) allows one to approximate any rieemen integrable function that is periodic with period $2\pi$ by a finite linear combination of $e^{ikx}$.


Modify the error message about the maximum upload file size

Question: I would like to modify the default error message for the maximum upload file size, but I can't find the configuration.
I looked at webform general settings, individual settings, and media file settings, but I found nothing about it. Forum issues only talk about configuration of the maximum file size, not about customization of the error message.
Can anyone help me?
Answer: As far as I know, there is not a way to add a validation handler for the file field type in general. You'll need to set a hook form alter and add a custom form validate handler for the edit forms, webforms, etc that you want to override.
Refer to: How do I add a custom validation handler to an existing form/field?
Alternatively, if your site is a multilingual site configured for internationalization, you can probably override the english version of the message in the. po file. I would advise against installing and enabling internationalization just for this use case, as it adds several pieces of functionality to the site and can bloat your database.
Comment: Thank you for your answer! The link will help me!


How to control for industry effects in regression?

Question: Right now I'm working on an analysis of influence of cultural aspects on investment mode preference. However I have to control for many other factors, for example industry, since some industries, for example, are more direct investment intensive, whereas others are more appropriate for licensing. But I have no clue how to manage this issue. Which kind of information do I need in order to be able to control for industry influence and calculate variables expressing the influence of each industry on dependent variable, which is a ratio of royalties to FDI income. I guess I need to include industry dummies, however, I do not really understand how to estimate them and based on which kind of information.
Answer: Which kind of information you need is more of a theoretical question than a statistical one. However, if you only aim at controlling for industry specificities, you do not need much information, apart from the knowledge of which industry each of your observations belongs to. Creating a categorical variable that holds industry affiliation is equivalent to having one intercept per industry (every modern statistical package, such as R, will take care of selecting one of the industry as the baseline, helping you avoid perfect multicollinearity, known as the "dummy variable trap").
This assumes that between industry, the relationship between the dependent and independent variables is the same (the slope of each group is the same), but with a different mean for each group (the intercept is varying by groups).
Answer: Each regression includes a variable equal to the median Tobin's Q for the firm's industry
in the year of the turnover, net of that year's median (across all industries).
16
 Using the industrylevel Q should provide a better measure of  growth opportunities the firm faces at a point in time
Comment: Can you provide more details? I'm not sure to see how this answers the question given the information available in the question (that may be just me, because I'm not familiar with such topics).


SQL Server 2005 windows group permissions overriding individual server logins

Question:
Hi,
I was wondering if someone knows a way round this. I have a database which needs to be accessed by a Windows Group with read only access. Some individuals in this group need write access.
I have added the group and then the individual logins and setup the permissions accordingly but the Windows Group seems to take precedence over the individual logins.
Does anyone know how to get around this?
Thanks
Andy
Answer: Permissions are cumulative, with the exception that DENY rights will overwrite GRANTs.
If you grant select to the group and deny update to the group, then grant update to the login they will not be able to update.
Make sure that you haven't denied any rights to the group or to public.
Comment: Thank you

I removed the deny from the specific columns and this is now working.
Comment: No problem, glad it was that easy.


When was the "Picardy 3rd" invented?

Question: When was the Picardy 3rd, the final tonic borrowed chord, invented?
Comment: Wikipedia has a useful summary of its history [here](https://en.wikipedia.org/wiki/Picardy_third#History).
Answer: Sometime in the Renaissance - there are plenty of 16th century examples.
My personal suspicion is that the use of the Picardy third developed along with the shift in keyboard instruments from split-key Pythagorean tuning to quarter-comma meantone with twelve keys per octave.  In meantone temperament minor thirds are flat compared to Pythagorean tuning, but the major thirds are pure (or at least the majority of them are).
Comment: Split key keyboards were never common.
Comment: I don't know how common they were, but I know they weren't extremely rare.  This paper identifies more than three dozen harpsichords, virginals, and organs with split keys in Italy alone: https://core.ac.uk/download/pdf/70978324.pdf
Answer: The Picardy third was likely "invented" during the baroque period by the likes of composers like Bach when equal temperament came into being.  Listen to the Bach Preludes and fugues and you will hear them quite a bit.
Comment: There are plenty of examples of Renaissance era Picardy thirds (like the Coventry Carol), and it was well temperaments that came into wide use during Bach's time, not equal temperament.

When was the "Picardy 3rd" invented?


Are there any functions $f:\mathbb{C}\to\mathbb{C}$ whose Taylor series do not exist on $I$ even if $f$ is infinitely differentiable on $I$?

Question: Let $$T[f(x),a]=\sum_{n=0}^\infty\frac{f^{(n)}(a)\,(x-a)^n}{n!}$$ given that $f:\mathbb{C}\to\mathbb{C}$, that $I\subseteq\mathbb{C}$, that $a\in I$, and that $f^{(n)}(a)$ exists for all $n\in\mathbb{N\cup\{0\}}$.
Does there exist some function $f$ such that $T[f(x),a]$ does not exist on $I$?
Remember that $\mathbb{R}\subset\mathbb{C}$, note that it is possible for $I$ to include or not include numbers that have imaginary parts, and note that functions $f:f(x)\neq T[f(x),a]$ are irrelevant if $T[f(x),a]$ is defined.

Edit 21 August 2017
After heavy consideration, I think this boils down to whether or not there exists a function such that $f^{(n)}(a)\ge n!$ as $n\to\infty$.

Edit 3 September 2017
I have been considering the function $\Pi(x)=\Gamma(x+1)$. You can find a discussion about the very nasty $n$th derivative here. I did, however, run a graph of it through the web graphing calculator Desmos. Basically, each higher bar is a higher derivative of $\Pi(x)$, and it spans the positive interval on which $\Pi^{(n)}(x)\ge n!$

Once I got to $\Pi^{(4)}(x)$, it started crashing, which is why the purple bar is incomplete (if it were meant to stop around $x=5.3$, then there would be a bold vertical line).
To me, this small sample seems to suggest that $\Pi^{(n)}(a)\ge n!$ for $a$ at least greater than or equal to $2$, which would make the coefficients of $T[\Pi(x),a]$ all be greater than or equal to $1$, so $T[\Pi(x),a]$ would diverge.
Comment: If a function has all derivatives at a point, its Taylor series exists. What may happen es that the series does not converge to the function.
Comment: In $\mathbb{R}$, you want [Borel's theorem](https://math.stackexchange.com/questions/63050/every-power-series-is-the-taylor-series-of-some-c-infty-function). I don't understand completely the complex part of your question. Obviously you don't mean that $I$ can be an open set in $\mathbb{C}$ and that differentiability means that $f$ is holomorphic in $I$. If you only mean that $f$ is a $C^\infty$ function of 2 variables, then the Taylor series has a more complicated form.
Comment: @Gribouillis Interesting. I mostly included $\mathbb{C}$ instead of $\mathbb{R}$ to learn something new. I'll have to read about this "more complicated form"!
Answer: Consider first $g: \mathbb R\to\mathbb R$,
$$
g(x)=\left\{ \begin{array}{ccc}
\mathrm{e}^{-1/x^2} & \text{if $x>0$},\\
0 & \text{otherwise.}
\end{array}
\right.
$$
Then $g\in C^\infty(\mathbb R)$, and $f^{(n)}(0)=0$, for all $n\in\mathbb N$. Thus the Taylor series
$\sum_{n=0}^\infty \frac{g^{(n)}(0)\,x^n}{n!}
$
exists but $g(x)\ne\sum_{n=0}^\infty \frac{g^{(n)}(0)\,x^n}{n!}$, for $x>0$.
Using this example, you can create similar situations for functions $f: \mathbb C\to\mathbb C$, when all partial derivatives in $x$ and $y$ exists.
Comment: @ChaseRyanTaylor If all the derivatives of $f$ exists, then so does the Taylor series. What do you mean *the Taylor series doesn't exist*?
Comment: That's nice, but I'm looking for functions where the Taylor series *doesn't* exist… I don't really care if it converges to the original function either…
Comment: Also, what is $C^\infty(\mathbb{R})$? I assume it's a set of functions that map $\mathbb{R}\to\mathbb{R}$.
Comment: Perhaps it doesn't converge at a certain point


In a Session Storage key value pair, is there a character limit to the length of the value string?

Question: I have an object whose data exceeds 5MB.  I'm using pako to compress the data down to about 1.7MB.  I then try to store that compressed data into session storage.  For smaller objects this works fine, but for this larger object I exceed the quota.  Considering I'm calculating the data size to be below 5MB, I'm wondering if there is some other limit to what can be stored in session storage, such as string length of the value or the byte length of the Uint8Array.
<code>cachedLookups = {
  ... //Tons of data
};
const stringifiedLookups = JSON.stringify(this.cachedLookups)
const compressedLookups = pako.deflate(stringifiedLookups);
sessionStorage.setItem(this.sessionStorageKey, compressedLookups);
</code>
Answer: Found the answer.  This was answered previously by Is there a limit to the key length for localStorage?
For SessionStorage with a single key value pair, there is no character limit, save that the combined data size of the key string and the value string do not exceed the ~5MB limit of the Storage.


File upload to mongoDB using C# driver and GridFS generates assertion

Question: First of all, the setup:

Server: Ubuntu 10.04 server
mongod --version
db version v1.2.2, pdfile version 4.5
Wed Nov 23 11:35:42 git version: nogitversion
Client: Windows 7 64bit, VS2010 app, using official C# driver v1.3.

I'm trying to store a png image in the mongoDB using the GridFS. My code looks like this:
var GridFSInfo = DB.GridFS.Upload(TextureFileName, TextureFileName);

Running this code I get the following exception
An unhandled exception of type 'MongoDB.Driver.GridFS.MongoGridFSException' occurred in MongoDB.Driver.dll

Additional information: Upload client and server MD5 hashes are not equal.

I have tried to find info on this error, but I seem to be the only person having trouble with this :(
The server log doesn't give any error, all I get is:
Wed Nov 23 11:42:23 connection accepted from 22.214.171.124:16861 #159
Wed Nov 23 11:42:25 building new index on { _id: ObjId(000000000000000000000000) } for ObjectDBTest.fs.files...
Wed Nov 23 11:42:25 Buildindex ObjectDBTest.fs.files idxNo:0 { name: "_id_", ns: "ObjectDBTest.fs.files", key: { _id: ObjId(000000000000000000000000) } }
Wed Nov 23 11:42:25 done for 0 records 0secs
Wed Nov 23 11:42:25 info: creating collection ObjectDBTest.fs.files on add index
Wed Nov 23 11:42:25 building new index on { filename: 1, uploadDate: 1 } for ObjectDBTest.fs.files...
Wed Nov 23 11:42:25 Buildindex ObjectDBTest.fs.files idxNo:1 { _id: ObjId(4ecccd0382522c02f8e58d75), name: "filename_1_uploadDate_1", ns:    "ObjectDBTest.fs.files", key: { filename: 1, uploadDate: 1 } }
Wed Nov 23 11:42:25 done for 0 records 0secs
Wed Nov 23 11:42:25 building new index on { _id: ObjId(000000000000000000000000) } for ObjectDBTest.fs.chunks...
Wed Nov 23 11:42:25 Buildindex ObjectDBTest.fs.chunks idxNo:0 { name: "_id_", ns: "ObjectDBTest.fs.chunks", key: { _id: ObjId(000000000000000000000000) } }
Wed Nov 23 11:42:25 done for 0 records 0secs
Wed Nov 23 11:42:25 info: creating collection ObjectDBTest.fs.chunks on add index
Wed Nov 23 11:42:25 building new index on { files_id: 1, n: 1 } for ObjectDBTest.fs.chunks...
Wed Nov 23 11:42:25 Buildindex ObjectDBTest.fs.chunks idxNo:1 { _id: ObjId(4ecccd0382522c02f8e58d76), name: "files_id_1_n_1", ns: "ObjectDBTest.fs.chunks", key: { files_id: 1, n: 1 }, unique: true }
Wed Nov 23 11:42:25 done for 0 records 0secs
Wed Nov 23 11:42:29 end connection 220.127.116.11:16861

This looks to me like the file transfer is initiated but then something goes wrong. I triplechecked that the file exists. I used the mongofiles command line utility to see if the GridFS works and everything is fine there, upload of files is no problem. My app also works fine if I do not make the GridFS upload and only use standard BSON document manipulation. I can insert, search, delete fine, so the connection to the server works.
I'm at a loss now as to what could be the source of this. I'd be thankful for any hints.
Answer: Is this easily reproducible? Is it related to a particular file? Let me know if you have any hints to reproduce this.
Are you really using v1.2.2 of the server? The current version is 2.0.1.
Comment: I have tried several different png files, this setup always produces this result. I'm using 1.2.2 because I installed this a while ago using apt. Trying a newer server version was something I thought about. Didn't know it's already at 2.0.1, so I'll definitely try a newer version and see if this fixes things.
Comment: Let me know if you still have problems after switching to the current version of the server and if so we will pursue it further. I see a few JIRAs related to md5 computation over the last year so the current version of the server will likely fix this (the most likely one is SERVER-1233).
Comment: I just installed 2.0.1 and this has fixed this issue. Now everything seems to work just as I need it. Thanks!


Ajax autosave function

Question: I'm currently adding data into db table via Ajax like this: When user pushes button with id #submit_btn it fires following function and posts data. The code of function looks like this.
$("#submit_btn").click(function () {
    $("#add_form").submit(function (e) {
        e.preventDefault();
        dataString = $("#add_form").serialize();
        $.ajax({
            type: "POST",
            url: "processor/dbadd.php",
            data: dataString,
            dataType: "json",
            success: function (result, status, xResponse) {
                //do something if ajax call is success
                var message = result.msg;
                var err = result.err;
                if (message != null) {
                    $.notifyBar({ cls: "success", html: message });
                }
                if (err != null) {
                      $.notifyBar({ cls: "error", html:err});
                }
            },
            error: function (e) {
                //ajax call failed
                alert(e);
            }
        });
    });

Is there anyway to modify this code for automatic submission in every 2-3 seconds? (autosave)
Comment: Yes, I'm sure there is. See e.g. https://developer.mozilla.org/en/window.setTimeout
Comment: I must set timeout for `$("#submit_btn").click(function () {`?
Comment: No, just for the Ajax call itself. Just be sure to remove the `alert()` from the error callback - otherwise, if the connection is lost, you get dozens of alerts
Comment: No. Use `setTimeout` to submit the form `$("#add_form").submit( ...`
Answer: Pleas try this code

/// NEW ANSWER

///THIRD ANSWER

<form id="add_form" action="" method="post">
<input type="checkbox" id="autosave" value="1"/>
<input id="submit_btn" type="submit" name="save" value="Save"/>

</form>

Comment: you can change 2000 with any of other milisecond as your requirement.
Comment: @The Coder here your form will get submitted after every 2 second autometically. So if you want to stop the autosubmit then you need to use clearInterval() function to stop the function calling.
Comment: Now the problem is, i want to start autosubmit only if user pushed submit first time
Comment: Yes you can do this cut the window.setInterval() from top and paste it inside your $("#submit_btn").click(function () {// function
Comment: just replace this with older ones - $("#submit_btn").click(function () {
                  var int = window.setInterval("call();",2000);

 });
Comment: i want to insert data in every 3 sec. but make button available still. now the problem is. when user pushes the button for second, third time. new intervals are appearing
Comment: @TheCoder Then you need to use clearInterval(int); This will clear out the existing interval. also var int is defined inside the document so please remove this var from document and place it just after your
Comment: please modify your solution. i can't understand.
Comment: can we continue discussion via skype or gtalk, or anything else?
Comment: My ajax function doesn't send data into db table, it works only when i click the button
Comment: @TheCoder Please let me verify this.
Comment: please give me your IM.I wanna talk to you
Comment: @TheCoder Is this ok with you if after first click disabling the submit button so the interval won't conflict with other interval. Basically after clicking on button will initiate the interval meanwhile disabling the button so for the next time no one click on the button. If this sounds good to you or can you adopt this strategy? (which i can give immediately) Or you need other solution. Feel free to discuss your requirement here.
Comment: http://pastie.org/2637131 Please take a look at my full code. As you see RSV function validates the form. My main problem is RSV validates the form onlclick, and js code posts data directly to php without checking if validation returned false value. How to fix that problem? And second problem is, can we do something like this: Put autosave checkbox near the "submit" button and if autosave checked, then change button into "save and exit" and if not checked leave it as it is: "save"
Comment: you mean to say that form should be submitted when it passes the validation every time when the form submission is performed.
Comment: no. only 1 time. when user clicks for the first time it should pass validation, if validation returned true then, post via ajax. and fire post lets say in every 30 sec. Validation passes if function 'myOnComplete()' returns true
Comment: @TheCoder See my new answer. Make changes according to your need. Does it code near to your requirement?
Answer: Instead of setTimeout, which you have to set over and over again, consider using setInterval, which needs to be called only once.
Comment: please modify given code. i'm newbie to js. I don't understand how code must look like
Answer: A possible solution would be to put the content of $('#add_form') in a separate function, say, submt() and call submit on setTimeout or if the $('#submit_btn') is clicked.
Comment: 1) please modify given code. i'm newbie to js. 2) All theese functions will be within `$(document).ready(function () {`?

Ajax autosave function


brew install open-mpi fails

Question: Trying to install openmpi, read that:
Could not determine if REAL*16 bit-matches C type

Ran brew doctor, and it's giving me:
Your system is raring to brew

full output
% brew install open-mpi

==> Downloading http://www.open-mpi.org/software/ompi/v1.6/downloads/openmpi-1.6.
Already downloaded: /Library/Caches/Homebrew/open-mpi-1.6.4.tar.bz2
==> Using Homebrew-provided fortran compiler.
This may be changed by setting the FC environment variable.
==> ./configure --prefix=/usr/local/Cellar/open-mpi/1.6.4 --enable-ipv6
checking alignment of Fortran REAL*16... 16
checking for C type matching bit representation of REAL*16... pending
checking if long double == REAL*16... ./configure: line 40736: 15744 Abort trap: 6
$F77 $FFLAGS conftest_f.f conftest_c.o -o conftest $LDFLAGS $LIBS 1>&5 2>&1
Error!
configure: error: Could not determine if REAL*16 bit-matches C type

READ THIS: https://github.com/mxcl/homebrew/wiki/troubleshooting

brew doctor
Your system is raring to brew

Comment: Which C and Fortran compilers are installed?
Comment: To me this looks like it's trying to use a Fortran compiler and then complaining that it cannot see if the results are compatible with C. Maybe try installing GCC as your compiler for Homebrew instead and try again?
Comment: This behaviour might be intended if Fortran and C object files are used in the same application. But I also suggest installing gcc and gfortran and then try again.
Comment: Waiting for your answers, I tried with an older version of open-mpi, and it works without any problem.
I have already install gcc and gfortran before Open-mpi.
Answer: There were some issues with recent gfortran builds in Homebrew. Try reinstalling it with brew rm gfortran; brew install --fresh gfortran. If the error persists, head over to the Homebrew GitHub page and report it as a bug: https://github.com/mxcl/homebrew/wiki/Troubleshooting.
Answer: There seems to be an issue with the gmp and mpfr bottles, which are dependencies of gfortran and thus open-mpi. Try doing brew rm gmp mpfr; brew install --build-from-source gmp mpfr open-mpi
ref: https://github.com/mxcl/homebrew/issues/19046

brew install open-mpi fails


drumming -- voice as a 5th dimension of independence

Question: Working on 4 limb independence.  Counting beats or measures in my head (or out loud) is really hard.  4/4 I can just feel and seldom screw up, but I'm studying jazz and trying not to get lost doing things over the bar line, polyrhythms, fills, etc.  Do you have a solid counter in your head when playing?  Can you count using your voice all the quarter notes when doing complicated stuff?
I know musicians often do count (one-ee-and-a-two-ee etc) when practicing, but I'm specifically thinking of this as an exercise in independence.  How does a jazz musician deal with playing a long solo, for example?
Answer: Counting is an excellent and important tool for learning and practice for all musicians who can count (i.e., those not playing breath operated instruments). But it doesn't present a professional image on stage. Many musicians tap their feet or user other tricks to keep time, but that can also be judged harshly by (some) audience members.
Drummers, and jazz drummers seem to do this more than most, IMHO, have some ways to "count" without using their mouths that are not judged harshly. The number one way is to keep the beat using the high hat pedal. I find keeping time on the high hat to be very difficult, but it definitely helps. It is yet another challenge of independence. It doesn't take much looking at professional drummers of all genres to find many examples of drummers who keep the hats going while playing fills, solos, and even ride cymbal patterns. One completely non-jazz example is John Bonham from Led Zeppelin. Keeping time on the hats also helps other musicians in the band keep track of the rhythm so they can time their return after a drum solo or stay synchronized during a fill.
I often sing along with the singer or hum the bass part while I drum. It's not as solid as counting for keeping time, but it does help me keep track of where I am, especially for very repetitive patterns. I learned to sing while playing other instruments before I got serious about drumming so I don't know as much about the challenges of adding a fifth independent "voice". I do know that counting, singing, and humming while you play is a great skill to learn and develop to help you keep time and improve your general musicianship.
Answer: If you truly want to investigate the voice as a 5th degree of independence, then try actually singing or indeed rapping.
You can simplify the drum part until you get the hang of it, but maybe try playing along to something already known to demonstrate that type of independence [even if it was on a different instrument].
Songs by The Police or Thin Lizzy show great independence of vocal from instrument & core rhythm & are really quite demanding to learn.
One example - Boys are Back in Town - the vocal drifts across the beat as though the singer had nothing else to concentrate on; yet we all know that he was actually keeping a magnificently-swung 4 to the floor right the way through it.
If that's not challenging enough - try some Eminem, or perhaps simpler, Will Smith. That will keep you on your toes.
Source for this - I've had to do all the above live, it sure teaches you how to do it ;)
Comment: Or Rage Against The Machine. I love singing while drumming. It's a shame that it's a bad place for a vocal mic and that I get more winded drumming than playing any other instrument.


Joda Time: how to parse time and set default date as today's date

Question: I have to parse dates in formats:
HH:mm
dd MMM
dd MMM yyyy

I've managed to handle the last two of them:
val dateParsers = Array(
    DateTimeFormat.forPattern("dd MMM").getParser,
    DateTimeFormat.forPattern("dd MMM yyyy").getParser,
    ISODateTimeFormat.timeParser().getParser
)

val formatter = new DateTimeFormatterBuilder().append(null, dateParsers).toFormatter.withZoneUTC
DateTime.parse(updatedString, formatter.withDefaultYear(currentYear).withLocale(ruLocale))

Everything is ok with dd MMM and dd MMM yyyy, but when I'm trying parse time like 05:40 I'm getting 01-01-1970 date instead of today's date. What is the simplest method to set default date as today's date in parser?
Comment: You could try and add the current date with time 00:00:00.000 to the parsed time. There seems to be a class `DateMidnight` so you might want to add your parsed time to an instance of that class.
Comment: Is this Java? Looks like another JVM language.
Comment: Another option might be `DateTime.withTimeAtStartOfDay().plus( yourParsedDateTime.getMillis())`. Note that you might have to handle timezone differences or specify time zones but I'll leave that for you.
Comment: It is scala actually, I fixed tags
Comment: @Thomas The "midnight"-related classes and methods are deprecated. (a) Midnight is difficult to define. (b) The first moment of the day is not necessarily the time `00:00:00.000` because of Daylight Saving Time nonsense and possibly other anomalies. Instead use the new [`withTimeAtStartOfDay`](http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#withTimeAtStartOfDay()) method. `DateTime today = DateTime.now( DateTimeZone.forID( "America/Montreal" ) ).withTimeAtStartOfDay();`
Answer: Joda-Time-Formatter only supports withDefaultYear(), not things like withDefaultDate(). Instead you can do this:
DateTimeFormatter timeParser = DateTimeFormat.forPattern("HH:mm");
LocalTime time = timeParser.parseLocalTime("05:40");
DateTimeZone tz = DateTimeZone.getDefault(); // Or DateTimeZone.UTC or DateTimeZone.forID( "Europe/Paris" )
LocalDate today = LocalDate.now(tz);
DateTime moment = today.toLocalDateTime(time).toDateTime(tz);
System.out.println(moment);
// output in my local timezone: 2014-08-20T05:40:00.000+02:00

Note: I have written the solution in Java, because I am not a scala-guy.
Answer: Date and Time are completely different, without subclassing DateTimeFormatter and implementing your special "time at todays' date"-algorithm you wont get very far. Either subclass or maybe inject your current date into the string if it matches some regular expression
Comment: I did use injecting, but I hope there is more suitable method for this. I think subclassing is overkill.
Answer: I'd use withDate()
private static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("HH:mm");
@Test
public void test() {
    DateTime dateTime = FORMATTER.parseDateTime("05:40");
    DateTime now = new DateTime();
    dateTime = dateTime.withDate(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth());
    System.out.println(dateTime.toDate());
}


How can I apply only one clang-format action?

Question: I want to use clang-format to align my comments, but nothing else.
The option for that is:  AlignTrailingComments (bool).
But when I run the following:
clang-format-3.6 -i -style='{AlignTrailingComments: true}' <file>

It performs all kinds of other formatting options that I suppose have a default when unspecified.
How can I execute just one clang formatting rule on the codebase?
Having all of these defaults make it difficult to see the full effect that a single formatting option has on the code.  I have to parse through the diff of all these other changes and decide if it was the option I specified that actually did it.

I noticed that there is a DisableFormat option, but no matter how I use it, it stops any formatting from happening at all.
clang-format-3.6 -i -style='{AlignTrailingComments: true, DisableFormat: true}'

clang-format-3.6 -i -style='{DisableFormat: true, AlignTrailingComments: true}'

Both cause clang-format to not make any code anywhere.
Comment: Blegh, came here for this functionality too. Sad it doesn't exist.
Comment: @bolov Because I only want to apply one rule change at at a time.  I need a default configuration where clang-format won't make any changes at all.  Then I can tweak one at a time, and see a diff of only that format option.
Comment: i think you should specify `BasedOnStyle`
Comment: you should try it as a plugin (e.g. for Vim , Visual-Studio). It is much handy to use this way.
Comment: @bolov As a plugin, will it still apply more than one formatting rule?  There are many conflicting formatting styles in our codebase,  and I don't want to clutter a commit with all of these additional changes that effect other people's portions of code.  I just want to apply a single style change so that other people can consume the change and handle merge conflicts more easily.  It's not practical to subscribe to an entire code style using BasedOnStyle right now.
Comment: of course. You just specify BasedOnStyle to set values for all options and then you can "override" any number of options. All this via config file. You can even have config files / project.
Comment: @bolov Ok, so if I set every option to false and 0, clang shouldn't change any code at all.  I'll give it a try.
Comment: why would you set every option to false and 0? I don't know try it and read [the documentation](http://clang.llvm.org/docs/ClangFormatStyleOptions.html)
Comment: ok but you should be aware that some rules interact with each other
Comment: @bolov Right.  And a lot of them take integers 0 through N.  There's not really a way to turn them off...
Comment: So it turns out that manual is the best formatting method in 2021... So much for the automation!
Answer: I think clang format was simply not designed for this. Rules are not things it applies incrementally, the program is instead built around, parsing your entire program and forgetting (most of) the old whitespace, and generating new whitespace based on the rules you select.
You can see some overview of the architecture here: http://www.llvm.org/devmtg/2013-04/jasper-slides.pdf
First it runs clang lexer and parser, then it divides groups of tokens into "unwrapped lines" which are "tokens we would like to put together on a single line if there was no column limit". Then a layouter determines the formatting of each unwrapped line based on the various constraints and optimizing for the various penalties.
So, I don't think "one clang-format action" is actually a thing, the design looks pretty much monolithic to me.
Comment: Unfortunately, this seems to be the correct answer.
Answer: clang-format does not have a mechanism to do this.
The palliative I use is to configure what I want changed in two different ways, I run the tool with both configurations and diff them, that tells me the changes that affect what I want, but in general this requires at least some manual work.
clang-format is a good idea with a poor implementation.  Some of the many deficiencies it has are that there is no option to have it indicate the reason for a change, the XML output format is not consumable by any other popular tool...


Can a soundboard, if designed with the right shape and materials, be as accurate as a series of tubes for filtering/amplifying desired frequencies?

Question: By cascading tube resonators of different cross section areas, it is possible to have a lot of control over the filtering of the sound, e.g. vowels in human voice can be approximated by cascading only a small number of tubes. Below are some examples to approximate 'a' and 'i' sounds:

Is it possible to do something similar using different soundboard designs, so that the same effects can be created with string instruments on a soundboard, rather than using tube resonators on a wind instrument, or is such a control of frequency filtering not possible on soundboards?
Comment: Hey ali.  I think you need to check out the work of the recently deceased Hans Reichel.  He made bowed instruments with very strong formants that sound the closest, in my opinion, to vowel sounds of any instrument.  Here's a sample:  https://www.youtube.com/watch?v=j8dG8adbOXQ
Comment: I guess I should ask: why would you want this kind of filtering on a soundboard?  You do get some anyway, I mean in terms of some frequencies corresponding to resonances, which helps make the sound of one violin different from another.  But having a soundboard that somehow selectively amplified frequencies with the Q of Helmholz resonators would make for a rather peculiar sound, perhaps something like autotune.  As alephzero said in his answer, that's precisely what instrument makers strive not to do: they try to make all frequencies as equal as possible.
Comment: @ScottWallace The reason I would want this kind of filtering is not for designing a conventional or better-sounding instrument, but the curiosity about the possibilities. More specifically, this leads to the question whether it is possible to make a string instrument that produces vowel-like sounds (like vowels in human speech as in the above drawings), or if this kind of application is only possible with tubes. Doesn't need to be perfect, peculiar effects are fine as long as formants can be formed. When you refer to these autotune-like sounds, do you mean the wolf tones you mentioned earlier?
Comment: @ScottWallace This is amazing!
Comment: Yeah, he created some very cool sounds.  Cheers from sunny Vienna, Scott
Answer: The resonances of a single narrow tube are simple and well separated. The frequencies are all multiples of the fundamental frequency. Joining several tubes end-to-end does not introduce more resonances, compared with separate tubes, though it does change the resonant frequencies.
For most instruments with soundboards, the soundboard itself is two-dimensional, often has a complex shape, and often has ribs or other features to strengthen it. Even for a simple rectangular plate, the resonant frequencies are proportional to (m^2/a^2 + n^2/b^2)^0.5 where a and b are the lengths of the sides of the plate, and m and n are integers 1,2,3,...
For a square plate, this gives frequencies proportional to
<code>1.00, 1.58, 2.00, 2.23, 2.54, 2.91, 3.00, 3.16, 3.53, 3.60, 3.80, 4.00, 4.12, etc.
</code>
and the higher frequencies are even more closely spaced.
These resonances are much more complicated than a pipe. In fact soundboards are usually intended not to have distinct resonances, but to resonate uniformly at any frequency.
This shows the measured response curve of a piano soundboard, over the frequency range 0 to 5 KHz - taken from https://www.isma-isaac.be/past/conf/isma2010/proceedings/papers/isma2010_0202.pdf (which has more experimental data).
Comment: "In fact soundboards are usually intended not to have distinct resonances, but to resonate uniformly at any frequency." - Is this still true for possible experimental soundboards with complex shapes such as ones with branching areas, varying narrow and wide parts, etc.? In other words, does the two-dimensionality is a limiting factor for the purpose of creating the mentioned vowel-like sounds or is possible but only makes it much more complicated to do?
Answer: Actually, frequency filtering happens quite frequently on soundboards: it's called a "wolf tone".  But wolf tones usually only resonate to one or at most a couple of tones harmonically related.  I guess you could build a soundboard like a steel drum, with many differently tuned areas.  I don't know if anyone's ever tried it.  But nothing like having, say, 12 Helmholz resonators, is possible with normal soundboard construction.
Comment: Wolf tones can be caused by resonances of the air inside the body of the instrument, not of the soundboard itself. That is often the cause for cellos, where it is a common problem, especially if the "wolf" matches the frequency of one of the notes in the musical temperament being used.
Comment: This is true, but in my experience, wolf tone problems caused by soundboard resonance are more frequent.


Split line in data file

Question: I'm struggling with splitting lines in my data file. Here is a few lines sample:
1:0 2:120
1:1 2:131
1:2 2:26
1:3 2:568
1:4 2:176
1:5 2:28 3:549
1:6 2:17
1:7 2:6 3:217 4:401 5:636
1:8 2:139

I want to split it to get out each value ... maybe in form of an array:
((1, 2) , (0, 120))
((1, 2) , (1, 131))
...
((1, 2, 3, 4, 5) , (7, 6, 217, 401, 636))

meaning that for each line the array could have different dimensions.
I was trying to split it in two steps, but it doesn't work.
inf = open("datafile.txt", 'r')

for line in inf:
line.split()
for x in line.split():
    x.split(':',1)

Answer: You can group the elements of two lists, using zip function.
with open("Input.txt") as inf:
    for line in inf:
        print zip(*map(lambda x: map(int, x.split(":")), line.split()))

Output
[(1, 2), (0, 120)]
[(1, 2), (1, 131)]
[(1, 2), (2, 26)]
[(1, 2), (3, 568)]
[(1, 2), (4, 176)]
[(1, 2, 3), (5, 28, 549)]
[(1, 2), (6, 17)]
[(1, 2, 3, 4, 5), (7, 6, 217, 401, 636)]
[(1, 2), (8, 139)]

Suggestion :
It is always good to open the files with with keyword, like I have shown in the code above. Because, it will take care of closing/releasing the resources, even if the program fails with an exception.
Explanation:
Since zip is a function call, the parameters are evaluated first. Lets come to the * later. map(lambda x: map(int, x.split(":")), line.split()), we apply the lambda function lambda x: map(int, x.split(":")) to each and every element of the list of strings returned by line.split() (which splits the sentences at whitespace characters and returns the list).
Each and every split word, will be passed as parameter to the lambda function one by one. If we take the first case, first "1:0" will be sent to the lambda function as x, where we split based on : which will give a list ["1", "0"] and then we apply int function over that, which will give [1, 0]. So, after all the lines are split and lambda is applied, the result will be like this
[[1, 0], [2, 120]]
[[1, 1], [2, 131]]
[[1, 2], [2, 26]]
[[1, 3], [2, 568]]
[[1, 4], [2, 176]]
[[1, 5], [2, 28], [3, 549]]
[[1, 6], [2, 17]]
[[1, 7], [2, 6], [3, 217], [4, 401], [5, 636]]
[[1, 8], [2, 139]]

Now we have two elements in each list. Remember the * which we decided to discuss later, it will unpack the list and pass all the elements as parameters to the zip function, like this
zip([1, 0], [2, 120])

Now zip will pick all the first elements and put them in a list, and then it will pick all the second elements and put them in a list and so on.
This is how we get the answer you expected.
Comment: Thanks a lot, works correctly now. I'm only beginner in python. Could you please give me a quick comment on zip, *map and lambda?
Comment: @user3041107 Please check the updated answer now. I have added a little explanation.
Comment: thanks it is very clear now. one more thing - how can I access those values? If I want eg. access value [1, 2] = 217 on the 8th line of the data.
Comment: I see, I can just make c = np.array() of the whole zip and then it is possible
Comment: @user3041107 I am sorry, I don't know `numpy` :( and I believe my answer best matches your question.

Split line in data file


Is it possible to work out the Fourier series of $\sin^m(x) \cos^n(x)$ without knowing the positive integers $m$ and $n$?

Question: For instance, let $m$ be an odd number. Then the Fourier series of $\sin^m(x) \cos^n(x)$ have forms like $\displaystyle \sum_{k=1}^{+\infty}b_k \sin(kx)$. Next, we can get $b_k$ through the integral
$$\displaystyle b_k = \frac{1}{\pi}\int_{-\pi}^{\pi}  \sin^m(x)\cos^n(x)\sin(kx) \mathrm{d}x$$
However, I find it too hard to compute. Even though I use formulas like
$$\displaystyle \int_{0}^{\frac{\pi}{2}}\sin^p(x)\cos^q(x) \mathrm{d} x=\dfrac{\Gamma\left(\frac{p+1}{2}\right)\Gamma\left(\frac{q+1}{2}\right)}{2\Gamma\left(\frac{p+q}{2}+1\right)}$$
and
$$\displaystyle\sin(kx)=\sum_{j=0}^{[\frac{k-1}{2}]}(-1)^j\binom{k}{2j+1}\cos^{k-2j-1}(x)\sin^{2j+1}(x)$$
I still get a bulk of sums and factorials:
$$\displaystyle b_k = \dfrac{1}{2^{\frac{k+n+m}{2}-3}}\sum_{j=0}^{[\frac{k-1}{2}]}(-1)^j\dfrac{k!(m+2j)!!(k+n-2j-2)!!}{(2j+1)!(k-2j-1)!\left(\frac{k+n+m}{2}\right)!}, \text{ when } n \text{ and } k \text{ are not both odd or even}$$
$$b_k = 0, \text{ when } n \text{ and } k \text{ are both odd or even}$$
What's worse, I can't even get $b_k = 0$ when $k>m+n$ through this way, which should theoretically hold. I am not familiar with skills of calculating factorials so I can only use computer programs to check $b_k = 0$ when $k>m+n$.
Is it possible to work out the Fourier series of $\sin^m(x) \cos^n(x)$ without knowing the positive integers $m$ and $n$?
Answer: If you know a bit of complex analysis you can use the residue theorem for calculating trigonometric integrals.
I will use the bases of complex exponentials
$$
I=\int_{-\pi}^\pi\sin^m(x)\cos^n(x) e^{ikx} dx=\frac{1}{2^{m+n} i^{m+1}}\int_C \frac{(z^2-1)^m (z^2+1)^n }{z^{m+n+1-k}} dz
$$
Notice that if $k\ge m+n+1$ it is the integral of an holomorphic function and so it is zero
For all the other values of $k$ the integral is evaluated as
$$
\frac{\pi}{2^{m+n-1}i^m(m+n-k)!} \lim_{z \to 0} \frac{d^{m+n-k}}{dz} (z^2-1)^m (z^2+1)^n
$$
As the degree of the polynomial is  $2(m+n)$ if $k\le -(m+n+1)$ the residue is zero.
Moreover as the polynomial has only terms of even degree, if $m+n-k$ is odd the residue is zero (we are taking the limit for $z\to0$).
You have
$$
(z^2-1)^m (z^2+1)^n =\left(\sum_{i=0}^m (-1)^{m-i}\binom{m}{i} z^{2i}\right) \left(\sum_{j=0}^n \binom{n}{j} z^{2j}\right)
$$
By using the (finite) Cauchy product, calculating the derivative and the limit we obtain
$$
I=\frac{\pi}{2^{m+n-1} i^m} \sum_{\substack{l_1+l_2=\frac{m+n-k}{2}\\l_1 \le m, \ \ l_2 \le n}} (-1)^{m-l_1} \binom{m}{l_1} \binom{n}{l_2}
$$
for $-(m+n+1) < k < m+n+1$ such that $k$ has the same parity w.r.t. $m+n$
If you want the expansion to be in the bases of $(\sin(kx),\cos(kx))$ you can then proceed as here
Comment: I think you should add "For all other values..." before the paragraph that starts with "The value of the integral is given by.." Other than that (+1)
Answer: $\sin^m(x) \cos^n(x)$ = $(\frac{e^{ix}-e^{-ix}}{2i})^m$ $(\frac{e^{ix}+e^{-ix}}{2})^n$=
$$\frac{1}{(2i)^m (2)^n}(\sum_{k=0}^m \binom{m}{k}e^{ikx}(-1)^{m-k}e^{-i(m-k)x}) \times   (\sum_{k=0}^n \binom{n}{k}e^{inx}e^{-i(n-k)x})$$
you can simplify it further and this is how you find the fourier series and with this method you can calculate the integral.


Falha ao colocar include em site com wordpress

Question: Eu tenho o endereço de uma web rádio e eu gostaria que ela funcionasse no site Wordpress.
Eu coloquei o código abaixo no meu header.php e essa rádio deve aparecer como navbar no topo de todo o site.

<?php include 'https://player.maxcast.com.br/comunidadedomdedeus';
?>

Print de erro abaixo:
https://i.stack.imgur.com/M1mag.jpg
Comment: Vou formular. Sucesso!
Comment: Mas é apenas um link que funciona como navbar, por isso que eu usei include.
Eu não tenho o código todo da navbar.
Claro que eu posso pegar o código fonte mas o resultado é o mesmo.
Comment: Sim, é uma navbar dentro de uma estrutura de página completa, com tags html, head, body, scripts etc...
Comment: Qual a sugestão? iframe?
Comment: Um iframe pode ser uma boa saída e funcionar.
Comment: Eu já tinha tentado com iframe mas não estava muito bom.
Vou tentar novamente.
Comment: Consegui, @Sam.
Quer colocar como resposta?
Answer: O problema é que a origem do include é uma página completa e possui scripts que só irão funcionar na própria página. Um include deve ser uma página apenas com o código necessário e já renderizado.
Você pode usar um iframe, que irá exibir a página de forma independente:

No CSS você pode definir as propriedades do iframe, como width, height e border:
iframe{
   border: none;
   width: 100%;
   height: 60px;
}

Teste:

iframe{
   border: none;
   width: 100%;
   height: 60px;
}


Can't access Sql Server from remote PC

Question: I am working on Screenshare using Red5. I have a servlet that gets and displays clients sharing screen from Sql Server using ResultSet. My Pc acts as the Sql server and am able to display the table using servlet in my red5 server.
But the servlet in red5 server in another PC which is connected to my PC(which has the sql server) through lan cannot access the database and the servlet screen is blank
I get

Cannot open database requested by the login.

I changed the IP to my PC in the servlet, but that caused the WebStart application to stop working correctly.
Answer: Check the username and password.weather it is correct or no
Comment: it's correct..the servlet in my red5 server can access it

Can't access Sql Server from remote PC


Haskell, "Is Prime" function

Question: I am new to Haskell and I couldnt understand the "Null $ filter" thing.
isPrime n
  | n < 2 = error "Zu kleine Zahl fuer Primzahltest"
  | otherwise = null $ filter (\k -> n `mod` k == 0) [2.. n-1]

Comment: This is equivalent to `null (filter (\k -> n `mod` k == 0) [2.. n-1])`, the `null` is `True` if it is an empty list. So in this case if there are no divisors. The code is however not very efficient.
Comment: Replacing [2..n-1] with [2,,n/2] might be faster.
Comment: I found this solution in a document and i couldn't understand it because I didnt know about the null function, now I got it. Thank you!
Comment: @FrancisKing: you can use `sqrt n` as an upperbound to boost the algorithm, but that is still not the most efficient solution.
Answer: The ($) :: (a -> b) -> a -> b operator applies the left operand to the right operand. Because it has a low precedence, it is used as a way to "group" expressions. The expression is thus equivalent to:
-- null $ filter (\k -> n `mod` k == 0) [2.. n-1]
   null ( filter (\k -> n `mod` k == 0) [2.. n-1] )
null :: Foldable f => f a -> Bool is a function that checks whether a Foldable has no elements. So for a list, it will return True if the list is empty, and False otherwise.
The list contains the integers k between 2 and n-1 in ascending order where n `mod` k is 0, hence the divisors of n. By using null we thus check that the number n has no divisors, and if that is the case we return True; otherwise we return False.

Haskell, "Is Prime" function


jquery mobile: $.mobile.orientationChangeEnabled = false but does not freeze in android

Question: My app uses rails and jquery mobile. I used alert function to see the value of  $.mobile.orientationChangeEnabled after been set to false, and it shows 'false' but still changes the orientation.
I tried with
$(document).ready(function(){
     $.mobile.orientationChangeEnabled = false;
        ........
});

and
$(document).bind("mobileinit", function(){
     $.mobile.orientationChangeEnabled = false;
        ........
});

Is there a way such as  one code fits all to freeze orientation?
Answer: I think you have a misconception: $.mobile.orientationChangeEnabled is not meant to lock in your page's orientation, instead it relates to jqm's orientationchange event - see http://api.jquerymobile.com/orientationchange/


Getting the current scroll position in Chrome using scrollTop() on page load/refresh

Question: Running the following in Chrome always returns 0:
$(window).on('load', function(){
     console.log($(window).scrollTop());
});

Running that same command via the console:
$(window).scrollTop()

Does return the correct number. (i.e.: 843)
There are a lot of questions about this issue here on StackOverflow but none of them have given me a correct working answer or alternative.
I'm at a loss...
Comment: Are you talking about loading an URL that points to a named anchor on the page, f.ex: example.com/#section ?
Answer: The scrollTop() returns the current vertical position of the scroll bar. Typically on page load, the scroll bar is at position 0. If the console prints out something else, then you or the browser must have scrolled down before the function was called.
If you are using named anchors or refreshing the page from a scrolled position, you can bind a handler to the scroll event that only triggers once - on page load:
$(window).on('scroll', function() {
    console.log( $(this).scrollTop() );
});

Comment: That is why the question says page load/refresh. Because with a refresh the browser retains its scroll position and that is exactly what I'm looking after.
Comment: I clarified the answer to point out that the solution also covers the auto-scroll feature some browsers have on refresh.
Comment: @David I found this Q&A very useful but I've realized that if I bind the handler to the `scroll` event it always returns 0 (because the browser hasn't scrolled, so you need to scroll first to see the value change). While if I bind it to the `load` event, it returns the scrolled position where I am (Chrome v30, Firefox v24).
Comment: very good and clever solution for getting browser's back button cached scroll value, thanks.
Answer: There are many ways to get the current scroll position In page

First get pageYOffSet
let verticalScrollOffset = window.pageYOffset;
then Set
 window.scrollTo(0,verticalScrollOffset);

If you need both Side position and set then
let scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
let scrollTop = window.pageYOffset || document.documentElement.scrollTop;

window.scrollTo(scrollLeft,scrollTop);

Using ViewportScroller click here to know more
this.viewportScroller.scrollToPosition(this.viewportScroller.getScrollPosition());//does not helps in my case

Ideal Solution works for me, I just save verticalScrollOffset(YaxisSrollPosition) before loading the page or refresh in any constant variable or local storage.Then After Refresh or load the page Use that position
let verticalScrollOffset = window.pageYOffset || document.documentElement.scrollTop;

$("html, body").animate({ scrollTop: verticalScrollOffset }, "slow");//slow Or fast option


Doubt on proving a given application is symmetric.

Question: Exercise. Prove that a certain application, with $d(x,x) = 0$ is a pseudo-metric iff $d(x,z) \leq d(x,y)+d(z,y).$
What I've done so far. I have been able to prove the $(\Rightarrow)$ implication and almost proven the $(\Leftarrow)$ implication aswell. The only doubt I am having is how to prove that $d$ is a symmetric application, knowing only the last inequality is valid. What I've dont to try it is the followig:
For $y=x$ we have:
\begin{equation*}
d(x,z) \leq d(x,y) + d(z,y) \Leftrightarrow d(x,z) \leq d(x,x) + d(z,x) \Leftrightarrow d(x,z) \leq d(z,x).
\end{equation*}
Now, to prove the symmetric I would also have to prove that $d(x,z) \geq d(x,z).$ This is where I am having trouble. I can't figure out how to do it.
Thanks for all the help in advance.
Comment: I don't understand your question. What exactly is the statement you are proving? The exercise says you must prove "the following application". What is this "following application"?
Comment: I am sorry for the mistake. I have no information about the application besides $d(x,x) = 0 \quad \forall x \in X$. The exercises states that I should prove that if $d$ is a pseudo-metric (i.e. non-negative, symmetric, positive defined and the triangle inequality is valid) the inequality above is valid. I should also prove that if the above inequality is valid, then $d$ is a pseudo-metric (i.e. verifies all the properties i stated). Thanks for the help.
Answer: You already proved (let's call this statement 1) the following statement:

For all values $x,z$, the inequality $$d(x,z)\leq d(z,x)$$ is true.

Now, take some value $x', z'$. Then,  define $x=z'$ and $z=x'$. Then, from what you already proved, you can see that
$$d(z',x')=d(x, z)\leq d(z,x)=d(x', z')$$
which means that you also have statement 2, which says

for all $x', z'$, the inequality $$d(z',x')\leq d(x',z')$$ is true.

Now, take any two values $x,z$.
From statement 1, you know that $d(x,z)\leq d(z,x)$.
From statement 2, you know that $d(z, x)\leq d(x,z)$.
Therefore, $d(x,z)=d(z,x)$.


Views Contextual Filter by current day

Question: I am using the Date Repeat Entity module for generating a checklist for users.  I am able to use Views to display the list in chronological order for tasks relevant for the current user using a Contextual Filter.  Could I also use a Contextual Filter to only show the current nodes that have a date equal to the current date?
I would think this could be done by entering some PHP code as shown here:
Comment: Instead of using contextual filter, have you tried using/adding regular FILTER (under FIELDS) ?
Comment: I'm not sure how a regular filter will be able to grab the current day.
Answer:
I'm not sure how a regular filter will be able to grab the current day

Add your date field to the filter.
You will then see this screen

Click apply and continue

Click on select a date, and select relative date

Put today as your relative date.
Comment: ah yes that was it.  Enabling Date Views gave me the extra screen and your filter works!  Thank you!
Comment: I have no idea where you got that first screen.  I have never seen it before.  This is now my date filter looks: [Imgur.](http://i.imgur.com/6h5gUix.png)  Are you running an additional module?  My data type is just a date.  Anyway I got the Contextual Filter to work with this code: [Imgur.](http://i.imgur.com/zgRNpEZ.png)  I am just testing it now with various formats.  I am really curious though about how you got this screen: http://i.stack.imgur.com/5qILi.jpg
Comment: @KyleRiggen hummm, you have **Date Views** module enabled?

Views Contextual Filter by current day


Is there an efficient way to find shortest paths in a functional graph?

Question: My task is to process Q shortest path queries in a functional graph with V nodes. Q and V are integers that can be up to 100000.
My first idea was to use the Floyd-Warshall algorithm to answer queries efficiently, but this algorithm takes O(V^3) time to calculate the shortest paths, which is way too slow.
My second idea runs in O(QV) time, because for every query I start at the starting node and traverse through the graph until I discover a cycle or reach the destination node.
However, this solution is still too slow; it has no chance of quickly processing queries when V and Q become large. I think that there is some pre-processing or another technique that I could use to solve this, but I haven't been able to find any online resources to help guide me. Can somebody please help me out?
Comment: How is this question related to C++? What is `O(QV)`?
Answer: A functional graph means that each node has only a single out-edge, so the maximum number of steps between A and B couldn't be more than the number of vertices without encountering a cycle.  You should be O(V).
Since there are no choices, you could readily build a CostMap[V][V] which recorded the distance between two nodes, and lazily fill it as you encounter queries; thus successive queries would approach constant time.
Comment: A bit more complicated, but you could make a hash table, concatenating src,dst to form a first level index.    There are only |V| connections, so if you chose the next prime number  >  |V|, then just re-probe until you find the right (or empty) entry.
Comment: Thanks for your help. I should have mentioned this, but `V` can reach the magnitude of `100000` in the problem, meaning that `CostMap[V][V]` would likely exceed memory limits. Do you have any other suggestions for this problem?
Comment: Sorry, that isn't quite right; that would only cover the base ones; the transitive ones would be |V|^2 / 2.  You likely have to 'manage' the cache...
Answer: There are a a lot of algorithm designed for this purpose, you can look up the Depth First Search (DFS) or Breadth First Search (BFS) algorithm. As well as the Djikstra's algorithm and the A* (A star) algorithm, this last one is often used in pathfinding for video games. They all have their pros and cons and it depends on the architecture of your network but it should suit your needs.


Closing windows with MacRuby and the Scripting Bridge

Question: I'm trying to write a quick script that will close all but the current window for the terminal application.  This script uses MacRuby and the Scripting Bridge.  Heres' what I have so far:
#!/usr/local/bin/macruby

framework "Foundation"
framework "ScriptingBridge"

terminal = SBApplication.applicationWithBundleIdentifier("com.apple.Terminal")
terminal.windows[2].close while terminal.windows.count > 1

When I try to run this, I get the following error:
undefined method `close' for #<TerminalWindow:0x40033b0e0> (NoMethodError)

This approach seems to work fine with AppleScript.  Does anybody know why it's failing here?
Answer: I found a copy of the TerminalWindow API here.  Using that, all I needed to do was:
TerminalSaveOptionsNo = 'no  '.unpack('N').first
terminal.windows[1].closeSaving(TerminalSaveOptionsNo, savingIn: nil)


Removing the last slash from query parameter using .htaccess

Question: I want to remove the last slash character from query parameter's value using .htaccess.
Suppose I have the following URL:
www.example.com/?key_=/job_category/mobile/

Then from /job_category/mobile/ I want to remove the last slash.
After removing the last slash, it would redirect to www.example.com/snapshots/job_category/mobile.html, but with my current settings it redirects to www.example.com/snapshots/job_category/mobile/.html.
My current .htaccess file looks like this:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^key_=(.*)$
RewriteRule ^(.*)$ snapshots/%1.html [R=301,QSD]

Answer: You don't need to capture anything in RewriteRule, as all necessary information is already captured by RewriteCond. To remove the trailing slash use an expression like \/*$ (zero or more slashes at the end):
RewriteEngine on
RewriteCond %{QUERY_STRING} ^key_=(.*?)\/*$
RewriteRule ^.*$ /snapshot%1.html [R=301,QSD]


Content type with multiple users - create a view of all users that relate to content of that type

Question: Suppose you have a content type called political party. Political parties can have members that are users. A user can be a member of multiple political parties.
I am trying to create a view where I list every user that is a member of a political party, and list them each only once. I don't need to see what party they are in, and this should just be a newest user sorted list of users that are listed in at least one political party's member field.
So these are the content types that need to be related:
<code>party
   |-members (user reference list)
user
</code>
How would you construct a view for this using the views module? I am a little lost on how to tackle this.
(note: I am using political parties, but actual content type name is different. It just is easier to explain this way)
Answer: I'm not entirely positive this is the type of relationship you want for this data.  If you use a node_reference field on the user rather than a user_reference on the node it would be pretty straightforward to create a view of Users who party.
Query all users and then add a Relationship to the field_party node reference.  Require the relationship with a Delta of 1.

This type of reference would seem to make more sense for your use case as well, since this would enable any user to administer their own party affiliations rather than the party manage the list (but then this is an analogy and I don't know the particulars).
Either way you are hitting up against the boundaries of what is possible using references.  I'd encourage you to take a look at the Relation Module which is designed to handle these kinds of bi-directional relationships, e.g. Display the members of the Party, Display the parties an individual is a member.
Answer: If the users are actual people that are going to be adding themselves to these groups then it sounds like you might have better luck with the Flag Module.
This will allow uses to 'join' any political party node by flagging it, and you can setup a view that will show only users that have flagged the particular node.


Get menu item of a content type

Question: Is it possible to get the menu item of a certain content type through the API?
The idea is to improve Markus Orenstrat solution to set the active trail based on the content type. As it stands it requires hardcoding the menu_tree id in the service.
 if ($bundle == 'blog') {
   $plugin_id = 'menu_link_content:a00a209d-075e-46a2-b200-e2d439d92228b';
 }

I figured this could be avoided since the administration area allows to assign a menu item to a content type.
Answer: That's stored in the third party settings of the node type.
$type = NodeType::load('article');
$type->getThirdPartySetting('menu_ui', 'parent')

See also menu_ui_get_menu_link_defaults().

Get menu item of a content type


How do I add the ability to change font size in CKEditor?

Question: I'm trying to install the CKEditor Font Size Module in my my editor. I installed the module via composer and then proceeded to copy the font/plugin.js file from the Font Plugin's page into libraries/ in my document root, per the instructions.
I also threw in a console.log() call into the font/plugin.js file to make sure it was loading. I modified the configuration of the Basic HTML editor to include the font size and family buttons in the toolbar on the /admin/config/content/formats/manage/basic_html page of my site. When I go to create a piece of content that uses the Text Editor, I don't see the font/size buttons I've configured.
Checking the Javascript console, I see my log message so I know the font/plugin.js file is being loaded. There are no error messages in the console. Why would the buttons not be showing up in this case?
Comment: What about when uyou try the Full HTML filter?
Comment: @Kevin Oh, interesting. I see them in Full HTML mode but not in Basic HTML. Why might that be the case?
Comment: It sounds like however those fonts are set, it might be rejected by the filter (like inline style tags) or depend on another plugin that might not be loaded by Basic HTML configuration. In these cases buttons won't show, I have seen this happen on some button plugins I've made before.
Comment: Maybe could be [related to this](https://www.drupal.org/project/ckeditor_font/issues/2900789#comment-12805811), have you applied the patch in #22 ?
Comment: @NoSssweat Thanks for the suggestion, I actually came across this already and the patch by the way is out of date. I believe Kevin was correct that it is the Basic HTML configuration that is not rendering the buttons. I'm testing it out and will post an answer shortly.
Answer: Kevin's comment was spot on and it was in fact the Basic HTML configuration that was preventing the button from rendering. Specifically, the filter "Limit allowed HTML tags and correct faulty HTML" was the issue. The buttons rendered correctly in Full HTML mode so that was the hint.
In the filter configuration at the bottom of the /admin/config/content/formats/manage/basic_html page, I modified the allowed tags. By default the filter allows plain span tags without any attributes. However, this plugin uses span tags with inline style attributes. As a result, I had to change  to  in Allow Tags list.
I can now see the font and size buttons in the editor, and using the tool injects HTML like the following:

The Quick red fox jumps over the lazy brown dog


How to test if a parameter is provided to a function?

Question: I was wondering, can you create a function with an optional parameter.
Example:
function parameterTest(test)
{
   if exists(test)
   {
     alert('the parameter exists...');
   }
   else
   {
     alert('The parameter doesn\'t exist...');
   }
}

So if you call parameterTest() then the result would be a message "The parameter doesn't exist...". And if you call parameterTest(true) then it would return "the parameter exists...".
Is this possible?
Comment: http://www.openjs.com/articles/optional_function_arguments.php
Comment: It is a very old question, but apparently viewed daily, thanks for the input. I edited the original post to make it more clear.
Comment: I think the real-world situation is how to check arguments of a function. `controller`, `service`, `model` layer. There will be a lot of arguments need to be checked.
Answer: This is a very frequent pattern.
You can test it using
function parameterTest(bool) {
  if (bool !== undefined) {

You can then call your function with one of those forms :
 parameterTest();
 parameterTest(someValue);

Be careful not to make the frequent error of testing
if (!bool) {

Because you wouldn't be able to differentiate an unprovided value from false, 0 or "".
Comment: @griffin You're absolutely right. We should stop using `undefined`, it could change at any moment! Might as well stop using `Object` and `Date`, someone might have tampered with those, and you should never ever trust `document.createElement`, it could be overridden!
Comment: @griffin if someone writes `var undefined` in their code, they deserve to suffer. `window.undefined` is unwritable for the same reason `window.infinity` and `window.NaN` are - they are supposed to be used to represent their respective values defined by the specification.
Comment: -1 for suggesting === undefined - try var undefined = true before your code and see what happens ... correct check would be typeof book === 'undefined'
Comment: @griffin in short: `undefined` has the exact same status as `Object`: It's an unwritable (since ES5) property of the global object, defined by the specification, and if you shadow it it's your fault. There's no reason to use one but not the other. Moreover, if the page you're userscripting against does redefine  one or the other, greasemonkey _still_ protects you against that by providing a separate global scope for each userscript.
Comment: @griffin Absolutely, `undefined` is a local variable. That's why [it's a property of the global object](http://es5.github.io/#x18.104.22.168), and obviously [`Object` can't be overwritten](http://jsh.zirak.me/185i9)
Comment: `Object` is not a reserved keyword and never was. It's  a defined property in the global scope, that happens to coincide with the constructor `{}` has. And `window.undefined` can be overriden in two ways: 1) by your own code - then you deserve it, or 2) by the page you script against - but IE8 doesn't support userscripts and firefox and chrome both use ES5.
Comment: @griffin if you're keen on supporting netscape then by all means worry about undefined not being a reserved word ....
Comment: Upvoted again ; For anyone reading these comments: we had a chat about the topic and it seems that `undefined` was already there in IE8 (JScript 1.5 based on ES3), which means this way of checking is actually fine. Still, if you want to check for argument count, you should use arguments.length to prevent bugs leaking due to something being passed as undefined (two differend use cases).
Comment: Looks like youre right :) https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/typeof
Comment: To me it's the same point as teaching people about '===' vs '==' - while the later one may work most of the time, it's just not the same, and many times does not reflect the intent of the author as well as possibly leading to bugs.
Comment: @griffin This discussion is getting too lengthy for comments - if you'd like to continue, we'd love to discuss this with you [in chat](http://chat.stackoverflow.com/rooms/17/javascript-whatever-plus-a-very-serious-duck).
Comment: @griffin I'm pretty sure `=== undefined` reflects the author's intent quite well and is more readable than `typeof`.
Comment: @Johan pretty sure you can use it as a function and an operator. seems to work in chrome at least
Comment: -1 for suggesting useless overhead and also screwing it up internally. Just call `if( bool ) { }` or `return !!bool`
Comment: @dystroy: if one needs to specifically check `0`, it should just go into the condition `if( bool || bool === 0 )`
Comment: Its more unlikely than likely, that you *want* to allow values like empty strings or zero, so just checking for presence and truthyness is far more reasonable (IMO). In other case is specific and should get checked by `typeof bool === 'number'` respectively `typeof bool === 'string'` anyway.
Comment: you're comparing a variable to some other variable - that doesn't even answer the question. I don't care which name you use, but effectively you're teaching people wrong stuff. It might work most of the time, but it could also get you into code hell, and really, there's no reason NOT to use the correct approach. Also wrt. performance: http://jsperf.com/typeof-vs-variable <- there's no difference on my machine using chrome.
Comment: this still doesn't distinguish an explicit `undefined` from an unsupplied argument, though. Consider checking `arguments.length` instead.
Comment: You're both only partially right - undefined is only reserved from javascript 1.8.5 upwards, so for example all IE versions which don't support that will allow a var called undefined. Also `window.undefined` is not the same as `var undefined`! The first one is a window property, the second one is a local variable! And Object  at least has been reserved keyword for nearly forever, and Date probably for nearly as long (would have to look at the javascript specification for that) Edit: @JanDvorak is absolutely right of course and his suggestion is even more correct.
Comment: @JanDvorak Thanks for the useful links, seems I was wrong about `Object`. And yeah, I'll join the chat for that ;) @PatsyIssa IE8 does not support ES5 either, and unfortunately at my company we still have to support IE8
Answer: function parameterTest(bool)
{
   if(typeof bool !== 'undefined')
   {
     alert('the parameter exists...');
   }
   else
   {
     alert('The parameter doesn\'t exist...');
   }
}

Answer: In JavaScript, if you neglect to give a parameter it will default to undefined.
You could try it out for yourself easily enough, either in your browser console or using JSFiddle.
You can check for the existance of the parameter, as you say, and that way write a function that can use a parameter or not. However, JavaScript Garden (a great resource) recommends staying away from typeof in most other cases, as its output is just about useless (check out the table of results of typeof).
Comment: That link says typeof is ONLY useful for this situation, which makes it good enough for this question.
Comment: As an alternative, jquery does provide a `$.type` method that works consistently across browsers.
Answer: init default values if not exists:
function loadDialog(fn, f, local, anim) {
  switch (arguments.length) {
    case 1: f=null;
    case 2: local=false;
    case 3: anim=false;
  }
  ...
}

Comment: This what the right answer for me because I needed to distinguish between a value not being passed at all vs passing undefined to the function. The other answers don't account for passing undefined.
Comment: Pls do consider of explaining your code and how it would help, so that others can be benefited from this.
Comment: Cryptic but nice. Also allows to tell apart `loadDialog(fn, undefined)` from `loadDialog(fn)`.
Answer: None of these answers were doing it for me. I needed to know if someone had used the parameter or not. If someone invoked the function passing undefined I wanted to treat that as them using that value as the parameter. Anyway, the solution was quite easy using some modern JS:
function parameterTest(...test) {
  if (test.length) {
    return `exists`;
  } else {
    return `not exists`;
  }
}

parameterTest(123);         // exists
parameterTest(undefined);   // exists
parameterTest();            // not exists
parameterTest(window.blah); // exists

For older browsers you can use arguments:
function parameterTest() {
  if (arguments.length) {
    return "exists";
  } else {
    return "not exists";
  }
}

Comment: The same answer was already added. You explained the problem better though.
Comment: Thank you! Twenty answers of ignoring `undefined` and then this. +1 for a general solution, and for *not* encouraging the ancient art of the `arguments` pseudo-array.
Answer: function parameterTest(p) {
    if ( p === undefined)
        alert('The parameter doesn\'t exist...');
    else
        alert('the parameter exists...');
}

Answer: best way to check: if the param is not undefined
function parameterTest(param) {
    if (param !== undefined)
    ...

the param could be also a variable or a function name
Answer: null == undefined is true
if (arg == null){
    // arg was not passed.
}

Code example:

var button = document.querySelector("button");

function myFunction(arg){
  if(arg == null){
    alert("argument was not passed.");
  } else {
    alert("argument " + arg + " was passed.");
  }
}
<button onclick="myFunction('foo');">click to fire function w arg</button>

<button onclick="myFunction();">click to fire function w/o arg</button>
Answer: I know this is old, but this is my preferred way to check, and assign default values to functions:
function testParamFunction(param1, param2) {
    param1 = typeof param1 === 'undefined' ? null : param1;
    param2 = typeof param2 === 'undefined' ? 'default' : param2;

    // exit if the required parameter is not passed
    if (param1 === null) {
        console.error('Required parameter was not passed');
        return;
    }

    // param2 is not mandatory and is assigned a default value so
    // things continue as long as param1 has a value
}


ElasticSearch/Kibana fields on update of document

Question: I'm very new to ES. I'm using https://github.com/dariusk/corpora/blob/master/data/humans/us_presidents.json as a learning set.
At first I entered this in Dev Tools tab in Kibana:
POST /presidents/president/1
{ "bo" :
        {
         "website":"",
         "startdate":"2009-01-20",
         "role_type_label":"President",
         "enddate":"2013-01-20",
         "description":"President",
         "district":null,
         "phone":null,
         "title":"President",
         "congress_numbers":[
            111,
            112,
            113
         ],
         "title_long":"President",
         "current":false,
         "person":{
            "name":"President Barack Obama [D]",
            "firstname":"Barack",
            "twitterid":null,
            "middlename":"",
            "gender":"male",
            "bioguideid":"O000167",
            "namemod":"",
            "birthday":"1961-08-04",
            "link":"https://www.govtrack.us/congress/members/barack_obama/400629",
            "youtubeid":null,
            "sortname":"Obama, Barack (President) [D]",
            "lastname":"Obama",
            "gender_label":"Male",
            "osid":"N00009638",
            "pvsid":"9490",
            "nickname":"",
            "id":400629,
            "cspanid":null
         }
         ...
        }
}

Then I realized that if I want add more data about individual presidents, I should rather do this:
POST /presidents/president/1
{
         "website":"",
         "startdate":"2009-01-20",
         "role_type_label":"President",
         "enddate":"2013-01-20",
         "description":"President",
         "district":null,
         "phone":null,
         "title":"President",
         "congress_numbers":[
            111,
            112,
            113
         ],
         "title_long":"President",
         "current":false,
         "person":{
            "name":"President Barack Obama [D]",
            "firstname":"Barack",
            "twitterid":null,
            "middlename":"",
            "gender":"male",
            "bioguideid":"O000167",
            "namemod":"",
            "birthday":"1961-08-04",
            "link":"https://www.govtrack.us/congress/members/barack_obama/400629",
            "youtubeid":null,
            "sortname":"Obama, Barack (President) [D]",
            "lastname":"Obama",
            "gender_label":"Male",
            "osid":"N00009638",
            "pvsid":"9490",
            "nickname":"",
            "id":400629,
            "cspanid":null
         }
}

OK, so ES accepted the update fine.
But now, when I go to Management / Index Patterns in Kibana, I see both person.lastname and bo.person.lastname as fields.
Why the previous field remained? Is this normal for ES to retain fields that are no longer in the updated document?
And obviously, apart from exceptionally funny ones, please no quips about today's election results.
Answer: This is normal, expected, behaviour for Elasticsearch.
ES, by default, will dynamically map the data you are inserting. When you index multiple objects under the same type in an index, all of these objects share the same mapping. The intention is to allow objects to be inserted that do not necessarily carry all of the potential fields of its type, and be inserted into the index anyways.
You can define a mapping yourself, either upon index creation, or by defining a new type for an index. Mappings can also be updated, with some caveats.
To see the mapping of the type in your index, execute the following:
GET /tk_file.2016/TK_FILE/_mapping

Your response will look like this:
{
   "presidents": {
      "mappings": {
         "president": {
            "properties": {
               "bo": {
                  "properties": {
                     "congress_numbers": {
                        "type": "long"
                     },
                     "current": {
                        "type": "boolean"
                     },
                     "description": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "enddate": {
                        "type": "date"
                     },
                     "person": {
                        "properties": {
                           "bioguideid": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "birthday": {
                              "type": "date"
                           },
                           "firstname": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "gender": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "gender_label": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "id": {
                              "type": "long"
                           },
                           "lastname": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "link": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "middlename": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "name": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "namemod": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "nickname": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "osid": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "pvsid": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           },
                           "sortname": {
                              "type": "text",
                              "fields": {
                                 "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                 }
                              }
                           }
                        }
                     },
                     "role_type_label": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "startdate": {
                        "type": "date"
                     },
                     "title": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "title_long": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "website": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     }
                  }
               },
               "congress_numbers": {
                  "type": "long"
               },
               "current": {
                  "type": "boolean"
               },
               "description": {
                  "type": "text",
                  "fields": {
                     "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                     }
                  }
               },
               "enddate": {
                  "type": "date"
               },
               "person": {
                  "properties": {
                     "bioguideid": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "birthday": {
                        "type": "date"
                     },
                     "firstname": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "gender": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "gender_label": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "id": {
                        "type": "long"
                     },
                     "lastname": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "link": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "middlename": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "name": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "namemod": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "nickname": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "osid": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "pvsid": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     },
                     "sortname": {
                        "type": "text",
                        "fields": {
                           "keyword": {
                              "type": "keyword",
                              "ignore_above": 256
                           }
                        }
                     }
                  }
               },
               "role_type_label": {
                  "type": "text",
                  "fields": {
                     "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                     }
                  }
               },
               "startdate": {
                  "type": "date"
               },
               "title": {
                  "type": "text",
                  "fields": {
                     "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                     }
                  }
               },
               "title_long": {
                  "type": "text",
                  "fields": {
                     "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                     }
                  }
               },
               "website": {
                  "type": "text",
                  "fields": {
                     "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                     }
                  }
               }
            }
         }
      }
   }
}

Notice here that you have a set of mappings for the bo object and its related sub-fields, as well as having a mapping for each field of your subsequent document. This is the effect of the dynamic mapping.
To disable this mapping flexibility, you can disable dynamic mappings explicitly, and defining the structure of the document yourself, including its datatypes. Perhaps you want the bioguideid to be an integer instead of text, as it is defined in the current mapping? I direct you to the Mappings API.


Find not irreducible polynomial

Question:
Actually I tried solving it.
A) By Eisenstein's Criteria its is irreducible.
B) and C) These polynomials don't have any zero in $\mathbb Z$ hence are also irreducible.
D) I have doubt in this tried it like ...
Let $$x=y+1$$ then equation becomes $$y^4 + 5y^3+10y^2+10y+5.$$
By Eisenstein's Criterion this is also irreducible.
But its not possible, one of them is not irreducible!!
Can someone help me?
Comment: Unrelated: I know only one Eisenstein criterion. Do you know another one?
Answer: $2x^3+6x+12 =2(x^3+3x+6)$
Note that $2$ is not a unit in $\mathbb Z [x]$.
The criterion you cited (that having no roots implies irreducibility for polynomials of degree $\leq 3$) works only over fields.
Comment: Its over Z not Z[x]
Comment: @user458361 irreducible over $\mathbb Z$ is the same thing as being an irreducible element in the polynomial ring $\mathbb Z[x]$
Comment: @user458361 For elaboration on the prior comment see [this recent question.](https://math.stackexchange.com/q/2329482/242)
Comment: @MatheiBoulomenos Thanks a lot bro!!

Find not irreducible polynomial


My params is coming up as nil. How do you create a new params for a model?

Question: #today_free_time.row
.col-md-2.col-sm-12.arrow_container{:style => "text-align:right;"}
  - if @dates >= 1
    = link_to movies_path(@dates), date: 'sub' do
      /date = date - 1
      %i.fa.fa-caret-left
  - else
    %i.fa.fa-caret-left

.col-md-3.col-sm-12.today_container
  .date_font
    %p
    %p
      =get_month
    %p
      =get_day
    %p
      =get_year

.col-md-5.col-sm-12.free_time_list_container
  %text_backgroud
    .agenda_date Free Time:
    %p
      =free_time
      =@dates

.col-md-2.col-sm-12.arrow_container{:style => "text=align:left;"}
  = link_to movies_path(@dates), date: 'add' do
    %i.fa.fa-caret-right

there's the code in my index file
if params[:add] == "add"
  @dates += 1
  logger.debug "*************Dates1 #{@dates}"
end

logger.debug "*************params #{params[:date].inspect}"
logger.debug "*************Dates2 #{@dates}"

there's the code in my controller
I am a little confused on params. Right now the params :date is coming up nil when I click on the link_to. I want to be able to click the link_to and my index file will be able to increment dates. So I will be able to go up a date or down depending on which link_to is clicked.  Do I need to create a new params somewhere are what?
Comment: The api documentation has examples below it showing different ways to use the method call and what url is generated from each. http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
Answer: # link_to movies_path(@dates), date: 'add' do

changes to
link_to movies_path(@dates,date: 'add') do