Bootstrap validation for panel data machine learning

Question: A traditional machine learning validation strategy is to train on some data and check performance on some holdout data. When data are time-dependent, an obvious way to proceed is to train on early periods and test on later periods, say train on data from $2000$ to $2011$ and then check performance in $2012$, $2013$ and $2014$ (those are the real years for which I am likely to have data).
A technique from biostatistics is to train on a bootstrap sample of the data and then test on the original data. An advantage of this is that valuable training data are not allocated to a holdout set.
However, when it comes time to bootstrap this, the way to proceed is not clear. Do we bootstrap everything and use the future to predict the past? That seems problematic.
What would be the way to do this for the panel-data I seem to have?
This seems related but not a duplicate.
Answer: I disagree that selecting later data as a hold-out set is an obvious way to proceed (with validation) when you have panel data. This is in fact a different and more stringent way to perform model validation. In some literature, these are distinguished as external validation or temporal validation. To illustrate this point, consider that a cubic curve locally approximates a sigmoidal curve prior to the inflection point, but once you sample data over the entire extent of the curve, the quality of fit deteriorates.
If we focus on cross-sectional validation, it's straightforward to conceive of the bootstrap as yet another resampling based approach to developing independent datasets that are expected to have the same internal structure. That is, if you inspect first and second moments comparing datasets that are randomly split p/(1-p) and bootstrap resamples, all univariate and bivariate statistics have the same expectations. The advantage of the bootstrap, which Frank Harrell points out in his text Regression Modeling Strategies, is that many properties of estimators are affected by small samples (feature selection using LASSO, small sample bias in logistic regression, etc.), and so bootstrapping can mitigate these problems by having the same $n$ in the training and validation sets.
It is a sound question, therefore, to ask whether a temporal bootstrap can be conducted for a panel analysis that produces a similar sized $n$ in training and validation sets, which enforces the stringency of a temporal validation, but which averts the issues of reducing the effective sample size. One obvious choice is just to apply the date cutoff and then resample observations to achieve a maximal $n$, another obvious choice is to not do that because the point of the exercise is to impose a needful penalty on model complexity. The correct choice would depend on your specific analysis, and perhaps some simulations to explore the operating characteristics of either approach. Of course, the specifics of bootstrapping panel data is already addressed as per your post.
Comment: "One obvious choice is just to apply the date cutoff and then resample observations to achieve a maximal $n$" Could you please elaborate on this?


Update data from table to mongodb

Question: Is there any framework or technique to simply update data edited in table and stored in mongoDB
I am using angularjs, node.js and mongoDB.
My 'by hand' idea is to:

track edits in angular table that will return json with updated fields
send REST request for update edited fields with proper document id
Comment: [Mongoose](http://mongoosejs.com/), [Express](http://expressjs.com/)
Comment: ok, Mongoose is for server side. But still I need to send REST with data and translate into query
Comment: Why don't you use Angular `$http` ?
Comment: Yes to azium's point, you are using Angular, which has the tools you need for communicating with a server: `$http`
Answer: Using the Angular JS, we can do all CRUD operation. For your question i have answer,
In HTML

                      {{$index+1}}
                    {{list.firstname}}
                    {{list.lastname}}
                    <button type="button" class="fa fa-edit btn btn-primary" ng-click="edit($index,list)"></button>

In controller,
 $scope.edit=function(idx,list){
    $scope.<name of ng-model>=angular.copy(list)
    flag=idx;
}

and now in controller where to saving, check the data in save() function, where the list is existing in the table. If yes the call update(), else call add().

Update data from table to mongodb


An Identity Involving Double Integrals

Question: I'm reading a physics paper that uses the following identity:

$$ \int_{0}^{\tau} dt_1\int_{0}^{\tau} dt_2 = \int_{0}^{\tau} dt_1\int_{0}^{t_1} dt_2 \; + \; \int_{0}^{\tau} dt_2 \int_{0}^{t_2} dt_1. $$

I'm not sure where this idenity comes from? Does it come from:

$$ \int_{0}^{\tau} dt_1 = \int_{0}^{b} dt_1 + \int_{b}^{\tau} dt_1. $$

If someone can "prove" the identity, that'd be great.
Comment: The LHS represents the integration over a square domaine. The RHS is the same square domain but cut in half in the diagonal which gives two triangles. The two integrals on the RHS covers these two triangles.
Answer: I'll call $t_1 :=x$ and $t_2 := y$ just to have a picture of what happens in the $2D$ plane.
The proof :
$$
(A)\ \int_0^{\tau} dx \int_0^{x} dy = \int_0^{\tau} dx (x-0) = \frac{x^2}{2}|^{\tau}_0 = \tau^2/2 \\
(B)\ \int_0^{\tau} dy \int_0^{y} dx = \int_0^{\tau} dy (y-0) = \frac{y^2}{2}|^{\tau}_0 = \tau^2/2
$$
So the RHS $ = \tau^2$ and the LHS clearly $= \tau^2$ since it is just the integral of $1\ dxdy$ over the square in the plane $[0,\ \tau]^2$
For the intuition let's look at the integral $(A)$ and think of the $2D$ plane. We first fix an $x$ coordinate (the outer integral is done over $x$) which represents a vertical line in the plane. We then integrate over this vertical line from the bottom of the square (the $x$-axis) to the fixed $x$ value. Then varying our fixed $x$ will cover the lower rectangular triangle that appears when you cut the square domain $[0,\ \tau]^2$ by the curve $y = x$ (a simple diagonal). This represents half of the domain to integrate. The $(B)$ integral is exactly the same, but this time you first fix $y$ and the integral will cover the upper rectangular triangle.
So it more or less comes from the fact you quoted in the sense that you can cut the integral domain in several parts, integrate over them, and sum the results. However the fact you proposed represents this idea in one dimension, here we work in $2D$.

An Identity Involving Double Integrals


Is there something like "stateful" backups?

Question: I work in bioinformatics and we store a lot of very large files which never change - plant genomes, genomic reads etc. We constantly receive new data of this type and the size of our backups is exploding.
In my opinion, it doesn't make sense to backup these large files all of the time, three or five times would be enough. Is there something like "stateful" backups which store what files are already "safe" (already on 5 tapes or so, using maybe file-hashes) and then only backup the rest?
I've googled around and found nothing.
Thanks!
Comment: If you only want to back a file up once, a differential backup should work.
Answer: Some variant of an incremental backup would work for this. Or perhaps you can set aside archived tapes containing static data on a regular basis to reduce the daily backup load.
Comment: What if someone corrupted an archive and the incremental backup stores the corruption?

But I agree we should set aside tapes with the usual static data..
Comment: @Philipp: If the data is static and not changed in any way, detecting corruptions is quite easy with checksums.
Comment: I'd say that the verification from your backup process should catch any corruption. Also you *will* be archiving to a different medium, correct? Are you using a backup software package?
Comment: Yes, we'll be archiving to tapes, and are currently using no software packages - just cp. I just started here and I want to change that.
Answer: Normally this is solved with either an incremental backup (backup all files since the last backup) or differential backup (all files since the last full backup).  The Gnu Tar manual (section 5.2 and 5.3) has a brief discussion of these type of backups.  However, this doesn't solve your problem of wanting a minimal number of copies of each file.
Another option, if you want to get an exact snapshot of the system on each backup, yet still save space is to use rsync snapshot backups (do a google search for rsync snapshot, there are several articles and tools that implement this).  Basically this uses rsync to make copies to a remote system (or external drive), and uses hard links against files that don't change between each backup, to save space.  To get multiple copies, you would then rsync your backup drive to another backup drive.
But, if you want this to all happen on tape, the only thing I'm aware of is commercial backup tools such at Tivoli.  You might look into Bacula, which I think also supports keeping a minimum number of copies, but I haven't used that one yet.
Something that will be available soon, is a backup tool that I've been working on myself.  I need to put together a bit more documentation and clean up the code before putting it up on github, but basically it does the snapshot-style incrementals-forever backups, keeping track of files by MD5 hash, and storing a catalog of snapshots of what a system looks like at each backup.  It also, as a side effect, does file-level de-duplication when backing up multiple hosts to a single backup server.  If you are interested, I'll come back later and update this post once I have the initial version of this tool uploaded (assuming it isn't against policy here to promote your own projects -- if it is, my apologies).
Comment: Marking this as answer because it contains the other answers plus additional information - I'll most likely go to for the multiple-rsync-solution, but keep me posted about your project! It's unlikely that I convince my boss to go for that (as it's new and untried) but I'm still interested.

Thanks to everyone!
Comment: Derek, you might take a look at BackupPC
Comment: @Philip, I created a project on code.google.com/snebu, which I will upload what I've got done so far.  I just made some last minute improvements, so I want to put it through a validation test one last time before submitting it -- should have it in the next couple days.  If you want, you can email me through the project page.
Answer: Store the files you import based on the date you get them. Hardlink them into the layout you need to use them in. Backup the last 5-7 days of directories.
Answer: Store your data in different places and have different backup strategies. I have worked for a huge company and even there, that was the setup for the petabyte of data.
Something like:

/master for files that are almost immutable. A few user would usually upload big files to there. This was backuped once a month;
/data for all other files. there were links to /master files. This was backuped every night.


A little bit of Intuition for Corepresentations from Representations

Question: Hi folks I am trying to prove what I think should be a straightforward enough result but I am having to make a somewhat unnatural definition to do it. This unnatural definition is hinted at in a paper by Franz & Gohm:

If $G$ is a group, then $b:M\times G\rightarrow M$ is called a (left) action of $G$ on $M$, if it satisfies...
...as before we have the unital *-homomorphisms $\alpha_g:F(G)\rightarrow F(G)$ defined by $\alpha_g(f)(x):=f(b(x,g))$. Actually, in order to get a representation of $G$ on $F(G)$, i.e. $\alpha_g\alpha_h=\alpha_{gh}$, we must modify the definition and use $\alpha_g(f)(x):=f(b(x,g^{-1}))$. Otherwise we get an anti-representation.

Let $G$ be a finite group and let $\rho:G\rightarrow GL(V)$ be a representation of $G$. I had wanted to prove that if we define a map by
$$\chi(v)=\sum_{g\in G}u\otimes\mathbf{1}_{\{g\,:\,\rho(g)u=v\}}=\sum_{g\in G}\rho(g^{-1})v\otimes\mathbf{1}_{\{g\}},$$
that $\chi$ would be a corepresentation of the quantum group $F(G)$ on $V$. Something that will ultimately fix my problem, in line with Franz & Gohm's comments above, is if I define
$$\chi_0(v)=\sum_{g\in G}u\otimes\mathbf{1}_{\{g\,:\,\rho(g^{-1})u=v\}}=\sum_{g\in G}\rho(g)v\otimes\mathbf{1}_{\{g\}}.$$
The reason I am uneasy about this is because it destroys a lot of the understanding I thought I had... briefly, if we consider the representation to be an action of $G$ on $V$ such that $u\overset{g}{\longrightarrow}v$ I wanted $\chi$ to encode all of this by saying look all of the things that bring you to $v$: something that looks or feels like $\coprod_i(u_i\overset{g_i}{\longrightarrow} v)$.
To be a corepresentation we need $(I_V\otimes \varepsilon)\circ\chi=I_V$ where $\varepsilon$ is the counit. There is no problem showing this with either definition.
The other property we need is
$$(I_V\otimes \Delta)\circ \chi=(\chi\otimes I_A)\circ\chi,$$
which works fine for $\chi_0$ but for what I want the best I can do is
$$\sum_{g,t\in G}\rho(gt)^{-1}\otimes \mathbf{1}_{\{gtg^{-1}\}}\otimes\mathbf{1}_{\{g\}}=\sum_{g,t\in G}\rho(gt)^{-1}\otimes \mathbf{1}_{\{t\}}\otimes\mathbf{1}_{\{g\}},$$
which only works if $G$ is abelian.
The map $\Delta$ is the coproduct given by $\Delta: F(G)\rightarrow F(G)\otimes F(G)$
$$\Delta(\mathbf{1}_{\{g\}})=\sum_{t\in G}\mathbf{1}_{\{gt^{-1}\}}\otimes \mathbf{1}_{\{t\}}.$$
I suppose I am a little uneasy about letting go of the very little intuition that I have in the realm of quantum groups and I am wondering is there a better reason for using $\chi_0$ over $\chi$ apart from "it works".
Thank you for your time.
Comment: This question is very well-asked. I wish I could upvote it more than once. ... also, if you don't get any answers soon, it's probably specialized enough that you can take it to MO.
Comment: What is called a "(left) action" in your quote is called a "right action" everywhere else... Also, you should give a full citation and quote also what "it satisfies", for the off chance that it does introduce a left action but, for some reasons unknown, writes it on the right.
Comment: @darijgrinberg The quote is from http://link.springer.com/chapter/10.1007/11376637_1 and the corepresentation definition is from http://www.ems-ph.org/books/book.php?proj_nr=72
Comment: Could you define what you mean by the quantum group $F(G)$?
Comment: The algebra of functions on $G$ with the comultiplication given by the coproduct and the counit given by $\varepsilon(f)=f(e)$.
Comment: Answered on Mathoverflow  [1]: http://mathoverflow.net/questions/160138/a-little-bit-of-intuition-for-corepresentations-from-representations
Answer: This question has been answered over on Mathoverflow... here.
My confusion came from confusing left and right...


Varnish in front of multiple servers with versioning

Question: I've got Varnish in front of multiple webservers, I can run them as native to varnish or through upstream checks via nginx, but only static content is cached (no surprise), also respecting query strings i.e.
/main.css?v=1 and /main.css?=v2 are cached separately
I update servers one by one, in fact, all this cannot be done at exactly the same time without downtime, general deployment thing.
If main.css gets updated on one backend and I send request according to the new webpage version to the varnish and request /main.css?=v2, it may still look for file on the machine which has old version and where main.css hasn't been updated yet, so, now I am getting v1 in the cache as v2 and there is nothing I can do, unless TTL expires (which is too late).
I can manually invalidate cache via requests, that's ok.
Is there any automated solution without manual interfering on rewriting software for feedback to varnish? like:

Is it possible, to expire cache when backend comes up, after probe is good?
anything else?

Thanks
Answer: If you load this code, or adapted for your varnish version, you can then send requests of type PURGE, with the request URL matching the thing you want to purge, to wipe the item from varnish cache. You can use this to basically automate selectively purging at the end of the deployment process against your Varnish servers, via cURL commands or similar.
https://github.com/dreamhost/varnish-vcl-collection/blob/master/lib/purge.vcl


Does each note have a more specific name depending on its pitch?

Question: Other than the symbolic identifier for the pitch of the note in sheet music, is there a way to specify the pitch of a note in some other notation or call it by any other name? This would be very handy to know for a software project I am working on.
Comment: The title seems to be asking a different question than the question body here. In the body, you are asking for an *alternative* nomenclature for notes, whereas in the title, you seem to be looking for a *more specific* naming scheme (possibly distinguishing octaves rather than just the notes within one octave). Both exist, but they are quite different in look and purpose.
Comment: The standard "A" is often called A440, as in 440Hz.  Some orchestras might use A438, A442, or others.  This can be (and is) extended to any other note/pitch.
Answer: In many computer applications referring to pitches with their MIDI number is useful.
If you want to be physical about it, you could use the frequencies in Hertz.
Also, scientific pitch notation may provide a more human interpretable way of unambiguously identifying notes. (Helmholtz notation is similar, but potentially less useful due to its use of special characters to indicate octave.  For indicating sharps/flats you may want to look at how they do it in lilypond)
Comment: Note that of these, frequencies in Hertz are different since they already incorporate tuning. The others name a note, but the exact ratios of the frequencies of those named notes depend how you choose to tune your instrument (https://en.wikipedia.org/wiki/Musical_tuning#Tuning_systems)
Comment: Related to MIDI numbers, one may specify pitches by combining a note name with an octave number.  Within each octave, C is the lowest note, and C5=60=middle C (so Cn is 12 times n).
Answer: 'Call it by any other name' rather than 'pitch' - The tonic sol-fa (the clue's in the name!) as used in Britain,is an adaptation of the solfege system  used in some European countries - France being one - calling C 'doh', D  'reh' and so on.Tonic sol-fa has a moveable doh, being the root note of any key. Solfege says that doh is always C. The names are note specific, and have their attendant sharps and flats.Any doh will have a frequency of 2x, 3x, 4x et al of the lowest note.
This may well not be useful to you for your software project, but could be adapted - doh 1, doh 2, etc. But it is an answer to the question.


how to obtain state space diagram and state space model for transfer function

Question: How do we obtain a state-space realization and a block diagram of a given transfer function?
Consider the transfer function
$$\frac{C(s)}{R(s)}=\frac{5s}{3s^{2}+3s+1}$$
Steps for solution are
$$\frac{C(s)}{R(s)}=\frac{5s}{3s^{2}+3s+1}\frac{Q(s)}{Q(s)}\\$$
$$C(s)=5(s^{-1})Q(s)\\$$
$$\Rightarrow R(s)=(3+3s^{-1}+s^{-2})Q(s)$$
$$\Rightarrow R(s)=3Q(s)+3(s^{-1})Q(s)+s^{-2}Q(s)$$
$$\Rightarrow 3Q(s)=R(s)-3(s^{-1})Q(s)-s^{-2}Q(s)$$
$$\Rightarrow Q(s) = \frac13R(s)-s^{-1}Q(s)-\frac13s^{-2}Q(s)$$
$$\Rightarrow Q(s) = \frac13R(s)-Q(s)\left[s^{-1}+\frac13s^{-2}\right]$$
the graph which is plotted in the book is of last equation of above solution.
I do not know how to post the graph here on Stack Exchange, but what I want to understand is:

How is the graph of this equation plotted?
Comment: Some MSE users tried to improve your post using TeX (for better readability). Please check whether these edits did not unintentionally change the meaning of your post.
Comment: Consider using LaTeX for formatting.
Comment: Yes, please, please learn some LaTeX for posting huge formulas like this. It was very difficult to read as it was.
Comment: Yes, that is the other problem! Cheers Julian. :)
Comment: yes the edits done are correct what is latex I am hearing it first time the edits are correct
Answer: Only some parts of your question make sense. In particular, given the transfer function
$$
H(s) = \frac{5s}{3s^2+3s+1}
$$
you invert the Laplace transforms to obtain the ode
$$3y''(t) + 3y'(t) + y = 5u'(t).$$
Define $X_1 = y$, $X_2 = y'$, $U_1 = u$, $U_2 = u'$. The state equations may therefore be written as
$$
\begin{aligned}
X_1' &= X_2\\
X_2'  &= -X_2 - \frac{1}{3}X_1 + \frac{5}{3}U_2\\
\end{aligned}
$$
and thus
$$
\begin{bmatrix}
X_1\\
X_2\\
\end{bmatrix}'
= \begin{bmatrix}
0 & 1\\
-\frac{1}{3} & -1
\end{bmatrix}
\begin{bmatrix}
X_1\\
X_2\\
\end{bmatrix}
+
\begin{bmatrix}
0 & 0\\
0 &
\frac{5}{3}
\end{bmatrix}
\begin{bmatrix}
U_1\\
U_2\\
\end{bmatrix},
$$
corresponding to the partial
realization
$$
A = \begin{bmatrix}
0 & 1\\
-\frac{1}{3} & -1
\end{bmatrix}
,\ B = \begin{bmatrix}
0 & 0\\
0 &
\frac{5}{3}
\end{bmatrix}.
$$
This is the only interpretation I can think of for "state space model". The only thing I can imagine is meant by "state variable diagram" (other than a block diagram which there is no "plotting" involved in making) is the $X_1$ vs. $X_2$ contour plot which you get by plotting the vector field of the RHS minus the controller parametrically. I have no idea what the calculation you show is trying to do and without any reference to where you got it from have no idea where to start with that.


Proof that geometric product is associative

Question: Geometric product has nice property since it is a ring and it is associative to multiplication, which is not the case for vector cross product. But besides it is an axiom for geometric product, in the process of actually defining geometric product in a constructive way, is there a proof that it is indeed satisfy the associativity?
i.e., the geometric product of a blade $A_r$ and blade $B_s$ by grade expansion of
$$ A_rB_s = \langle A_rB_s\rangle_{|r-s|} + ... + \langle A_rB_s\rangle_{r+s}$$ is this associative?
Comment: For the main examples it is easy to see that they are associative.
Comment: The usual approach is to take the fact that the multiplication is associative as an axiom. See Chapter 1 of Hestenes and Sobczyk, Clifford Algebra to Geometric Calculus, Reidel 1984.
Comment: @Sanath, you have to prove the computation rules made up for the geometric product do satisfy the axioms. Otherwise you know there is a thing called geometric product, but do not know whether it is the same thing you are calculating.
Comment: Isn't it one of the three axioms for the geometric product? You can't prove an axiom!
Comment: @ahala You're taking as axiomatic that the geometric product is associative, so what "rules" do you think must be shown to be consistent with this associative axiom?
Comment: Still not sure I'm understanding your question. This decomposition by grade is merely a way of grouping different components of the resulting multivector. Labeling components of a multivector by their grades in this way (because you have all the terms, so it is exhausive) does not change the value of the multivector in any way.
Answer: If you defined the geometric product "from the bottom" on basis elements, then it follows from the fact the product is defined to be associative on the basis elements (See proposition 1 pg 4 in this text by Jacobson for a proof that associativity on basis elements is sufficient for associativity of the ring.)  (I think this is basically what you're asking when you're talking about the grade decomposition.)
If you are defining it from the top down as a quotient of the tensor algebra on $V$, then it is associative because the tensor algebra is associative.
Comment: thanks. I think that is a valid question since one has to recover vector analysis from an implementation of geometric product, in which it needs a proof to link the axioms to the implementation.
Comment: @ahala I don't follow what you're saying, but that's ok.
Answer: There are two approaches:

Write down a list of axioms for geometric algebra. Associativity probably needs to be on the list. Advantage: One can get down to the business of using the algebra right away. Disadvantage: How does one know that the list of axioms does not hide an inconsistency?
For most people "it has been proved consistent" is a good enough answer to the question above. But some will want to see a construction of GA and proofs of its properties, including associativity of the geometric product. There are several proofs. My own is the topic of the paper An elementary construction of the geometric algebra, Adv. Appl. Clif. Alg. 12, 1-6 (2002). A somewhat improved version is available at my website http://faculty.luther.edu/~macdonal/ . The paper cites other proofs.


Cordova iOS 9.2 - photo capture

Question: I'm trying to take photo from Cordova built iOS app:
<input id="imageInput" type="file" accept="image/*">
In simulator and earlier iOS versions (7, 8) it work perfect - you can take photo from camera or choose existing from library. The problem is in app on iOS 9.2 it fails - you can see "Cancel" option only.
I tried also
<input id="imageInput" type="file" accept="image/*;capture=camera">
and <input id="imageInput" type="file" accept="image/*;" capture="camera">
but there is the same result
Comment: I think you should use cordova-plugin-camera
Comment: are you using xcode 7? which cordova version do you use?
Answer: I have updated xcode to the latest version and it is working now

Cordova iOS 9.2 - photo capture


Correct intent to show only Audio files

Question: I am trying to pick Audio from Gallery. I am using the following intent.
private void selectAudioFromGallery() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/3gp, audio/AMR, audio/mp3");
        startActivityForResult(Intent.createChooser(intent, getString(R.string.select_audio_file_title)), REQ_CODE_PICK_SOUNDFILE);

    }

I want to select files of type 3gp, AMR, mp3 and only these files should be listed in the file chooser but the problem I am facing it, it also shows the other files too like text files, image etc.
Answer:     Intent intent = null;
    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
         intent = new Intent(Intent.ACTION_GET_CONTENT);
    }else {
         intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    }

    // The MIME data type filter
    intent.setType("audio/*")

Works..
Comment: Work like charm
Answer: Use this
intent.setType("audio/3gp|audio/AMR|audio/mp3");

Adding multiple mime type need pipe sign, not comma.
Another way
intent.setType("audio/*");
String[] mimetypes = {"audio/3gp", "audio/AMR", "audio/mp3"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);

Comment: *I want to select files of type 3gp, AMR, mp3 and only these files should be listed* - this won't achieve that
Comment: @TimCastelijns: updated my answer. Thanks for pointing that out.
Comment: @Rohit5k2: It still showing me File Manger in the chooser dialog, with File Manager I can pick any file i want. How Can I restrict that?
Comment: Both solutions are not restricting application for audio mime type. Chooser shows the File Manager and user can attached any type of file

Correct intent to show only Audio files


How to resolve an XMLReader warning produced by Wordpress Migrate module?

Question: I'm converting a Wordpress site to Drupal. To do so, I need to import a wordpress export file. But whenever I try to import my wordpress export file, I get this error:

Warning: XMLReader::open() [xmlreader.open]: Unable to open source data in WordPressBlog->__construct() (line 188 of /mnt/www/html/dev/docroot/sites/all/modules/wordpress_migrate/wordpress.inc).
Exception: Could not open XML file wordpress://blog.wordpress.2013-09-05.xml in WordPressBlog->__construct() (line 219 of /mnt/www/html/dev/docroot/sites/all/modules/wordpress_migrate/wordpress.inc)

As shown in the path names within the error mesages also (ie: 'wordpress_migrate'), I'm using the Wordpress Migrate module. For this module, only a 7.x version exists.
I'm not quite sure why it can't read the XML file. I've run the file through the xmllint command with no errors.
Can anyone help me with this?
Answer: I had the exact same error.  I uninstalled all the WordPress migrate and migrate modules (uninstalling migrate may not have been necessary), removed from site directory and then reinstalled.
I re-installed Migrate 7.x-2.6 and WordPress Migrate 7.x-2.3-beta2+4-dev.
After that the import worked.


Let R be the relation on the set of ordered pairs of positive integers, Z+ × Z+, such that (a, b)R(c, d) if and only if ad = bc.

Question: (For instance, (2, 4)R(6, 12) since 2·12 = 4·6.) Show that R is an equivalence relation.
I was tasked to show that the sets is an equivalence relation if the three conditions Reflexive, symmetric and transitive is shown valid, However I faced difficulties when showing transitive?
I really need hints.
Thanks.
Comment: What difficulties did you face? What did you try to do to prove that the relation is transitive, and where did it go wrong?
Comment: well I just want to show that is transitive: aRb and bRc then aRc, if a is related to be and b is related to c then a related to c. I started ad=bc and bc=? thats where I have trouble.
Answer: Assume that $(a,b)R(c,d)$ and $(c,d)R(e,f).$ We see that this implies that
$$ad = bc \wedge cf = de.$$
We want to show that
$$af = be.$$
Given that $b \neq 0.$ We see that
$$\frac{ad}{b} = c \implies \frac{adf}{b} = de.$$
$$\implies adf = bde.$$
Given taht $d \neq 0$, We see that
$$af = be \implies (a,b)R(e,f).$$
And we have thus proved transitivity.


Under what conditions in Apache installations is AddHandler application/x-httpd-php .php required?

Question: I am a security researcher who has been running into multiple cases where file upload forms can be exploited, allowing attacker-controlled PHP code to be interpreted by the server, leading to remote code execution. The root cause of this vulnerability seems to be a legacy setting that is enabled by default in the Apache config of following Linux Distros:

CentOS 5.8
CentOS 6.5
RedHat 5.10
RedHat 6.5

and possibly others. The setting is:
AddHandler application/x-httpd-php .php

The effect of this setting that is concerning is that it tells the server that files with names that match \.php should be interpreted as PHP code. If an attacker uploads an image with the name shell.php.jpg with php code embedded in it, and navigates to the page, the server will execute the script as the server user.
My recommended remediation is to disable this setting by commenting it out. My reasoning is that .php files already have an implicit handler built in to Apache, which tells the server to interpret the code as php, so this setting seems to my eyes to be redundant. I get the feeling that this is a legacy setting carried forward by old versions of CentOS and RedHat, and the newest versions do not have this setting.
My question is: Under what circumstances will disabling this setting break functionality?
Answer:
My reasoning is that .php files already have an implicit handler built in to Apache, which tells the server to interpret the code as php

As far as I know, there is no implicit handler, this AddHandler command is what tells apache to pass files with a .php extension to the application/x-httpd-php handler (mod_php)
However, overall you are correct.  It is (apparently) a little known feature of mod_mime that files with multiple extensions have ALL of their extensions examined for handlers and other information.  Apache's documentation suggests that that directive should be replaced with:
<FilesMatch \.php$>
  SetHandler application/x-httpd-php
</FilesMatch>

to only pass files ending in .php to that handler.
The best solution, though, would be to store untrustable user-uploaded files outside of DocumentRoot where browsers can't request script.php.jpg (or mail out links to http://www.example.com/uploads/thisisreallyyourbank.html)


Find the Generating Function with respect to n

Question: The following is a problem from Chapter 2 of Herbert Wilf's generatingfunctionology:

Let $S$ and $T$ be two fixed sets of nonnegative integers. Let $f(n,k,S,T)$ denote the number of ordered representations of $n$ as a sum of $k$ integers chosen from $T$, each being chosen with multiplicity that belongs to $S$. Find $\sum_{n}f(n,k,S,T)x^n$.

I believe the answer to be:
$$[y^k]\prod_{t\in T} (\sum_{s\in S} y^s x^{st}).$$
However, in the back of the book where he provides solutions, he states that it is rather the following:
$$\left[\frac{y^k}{k!}\right]\prod_{t\in T}\left(\sum_{s\in S} \frac{y^sx^{st}}{s!}\right)$$
Can anyone explain to me why this is the case? Per my understanding, exponential generating functions are more convenient for labelled structures but I'm having hard time seeing why and if this is the case here.
Thanks
Answer: Your answer counts unordered representations; the question was for ordered representations.
How many ways are there to order a multiset of $k$ elements with multiplicities $s_1,s_2,\cdots$? You should be able to count $k!/(s_1!s_2!\cdots)$ orderings, which leads to the desired answer.
Comment: @Pavelshu The sum $\sum_n g(n,k,T)x^n=\sum_n f(n,k,\{0,1\},T)x^n$ should be $$\left[\frac{y^k}{k!}\right]\prod_{t\in T}(1+yx^t).$$ You can check with small examples that this is the correct form.
Comment: If so, then I have a follow up question:
>Let $g(n,k,T)$ be the number of ordered representations of $n$ as a sum of $k$ _distinct_ integers chosen from a fixed set of nonnegative integers $T$. Find $\sum_n g(n,k,T)x^n$.

My solution for this agrees with the solution in the back, namely:
$$[y^k]\prod_{t\in T}(1+yx^{t}).$$

Based on your solution, is this wrong?
Comment: I see, I'll have to contemplate about this a bit more. Thank you for your replies.


Error distributions and loss functions

Question: If I'm right, using the Gaussian distribution in the maximum likelihood estimate yields the mean squared loss.

Are there similar relationships between other distributions and losses (say Bernoulli and logistic loss)?
How do you derive such relationships mathematically?
Note: the context is  regression/classification kind of problems where the goal is to predict $y|x$
Answer: Let $X_1, X_2, ..., X_n$ be i.i.d with density $ke^{-g(x-\theta)}$
Then  $-\log(\mathcal{L}(\theta))= c +  \sum_i g(x_i-\theta)$
This gives a big clue about the correspondence between density and what loss function is being minimized with ML.
So for example, if $g$ is $(x-\theta)^2$, we have a least-squares problem and the MLE of $\theta$ will be the sample mean.
If $g$ is $|x-\theta|$ we'll maximize likelihood by minimizing the sum of absolute deviations ... which will give us the median.
--
In response to the question in comments, note that $f=ke^{-|\epsilon|}$ is a Laplace distribution, so the regression model you mention there would correspond to a no-intercept model with conditionally Laplace errors.
[I've ignored scale in this answer but it doesn't alter anything substantive about the answer.]
Comment: So here g = $Pr(y_{i}|x_{i})$?
Comment: Your question contains nothing whatever about there being two variables in your problem. You have some regression type problem?
Comment: Yes. Let's say I'm trying to predict Y using $x_{i}s. $So for the Gaussian distribution here g = $Pr(y_{i}|x_{i})=c_{1}e^ {-(y_{i}-\theta x_{i})^2}$.  Then what distribution corresponds to $Pr(y_{i}|x_{i}=c_{1}e^{-|y_{i}-\theta x_{i}|}$
Comment: There is still no indication of this in your question; if that's what you mean to ask about, please edit. It is not clear to me how you thought people would guess this (implied by your first comment under my answer).
Comment: @Wabbit thanks for the edit. Note that your errors  $y_i-\theta x_i$ contain no intercept term (when $x=0$ then under symmetric losses you'd try to put your fitted $y$ near $0$). Was that deliberate or did you mean to allow lines to have their intercept somewhere other than 0?

Error distributions and loss functions


How do I notate b5 chords in roman numerals?

Question: I want to name the chord C♭5 (i.e., C with a diminished fifth) in roman numerals; how would I do that? The key is C major. I am fairly sure it is I♭5, but I want to check.
Also, how do you name modal triads like C lydian (still in C)? Is there a more efficient way than something like Iadd♯4(no3)?
Comment: Why not VII5? I'm wondering if you're trying to use roman numerals in a context where they don't really fit. Music that has Lydian chords is less likely to be functional and roman numerals are more about function than anything else.
Comment: @codeb0i Assuming that you're using functional harmony (for which degree numeration is important for their harmonic role), all chords you're mentioning are *altered* chords, so they need a specific notation: considering that degrees normally follow tonality and mode, G♭ doesn't exist in C major and in C in general, so you have to specify the "exception": I♭5. I don't really like the term "modal triads", as it's ambiguous (C-F#-G *may* describe a lydian chord, but it could also define many others), but the concept remains: you have to specify all exceptions that are not the in standard triad.
Comment: Using regular text with no superscript , it is better to write C(b5) so as not to confuse it with (Cb)5 which is R-5. Also, the principles of constructing triads is no different in Lydian mode, a C chord is simply 1-3-5, or CEG. Anything beyond that can be done but is not a simple triad.
Comment: You really need to provide a longer passage where the chromaticism occurs and especially show enough that `C` major a key is _clear_. The closer to full notation, the better. Your description mixes flat 5 and sharp 4 which makes me think you aren't fully understanding how the chromaticism is functioning. More harmonic context is needed, the chords before and after at the very least.
Comment: @musicamante what do you mean by "specify all exceptions that are not in the standard triad"?
Comment: @codeb0i the conventional meaning of triad is a set of three notes at intervals of thirds from the root (considering reordering in case of inversions): II-IV-VI, V-VII-II, etc. While some theorists also call triads any group of three notes, regardless their intervals (thus allowing, for instance, I-II-VI), these are normally (and more clearly) referred to as "trichords". I understand that "lydian triad" may be acceptable for I-VI-V of a lydian scale, as it includes the fundamental aspects of that mode, it's ambiguous and inconsistent: for instance, what about modes that have characteristic »
Comment: » notes *outside* of the normal degrees of a standard triad? There is no difference between a dorian or aeolian triad, as there's none between ionian and mixolydian triads. Moreover, if a lydian replaces the third with the fourth, then, following the same concept, a locrian should also replace the third with the second, making things ambiguous if there's no proper context: without knowing inversions, C-F#-G can also be a F# locrian triad.
Answer: There is a symbol for an augmented triad and one for a diminished triad.   Nothing, I think, specifically for a major triad with a flattened 5th.   But 'I(♭5)' would be understandable and unambiguous.
If a 'Lydian triad' is 1, ♯4, 5, I guess that would be 'I(sus♯4)' in Roman.
Comment: `sus` is something we'd expect from jazz style chord names. In roman numeral analysis this is not a common notation. Rather the general assumption is that 4 replaces 3, and 6 replaces 5. So in this case this would simply be `I 4#`. If we wanted to include the third we'd need to have `I 3 4# 5` (`I 3 4` by itself would be read as `I 3 4 6`).


Conjunto usando matriz em c#

Question: Tenho a seguinte matriz:

a   d   k   m
s   j   e   r
t   c   f   p

Coloquei tal matriz em um array da seguinte forma:
char[,] matriz = new char[3,4];
matriz[0,0] = 'a';
matriz[0,1] = 'd';
matriz[0,2] = 'k';
matriz[0,3] = 'm';
matriz[1,0] = 's';
// E assim sucessivamente.

Eu gostaria de gerar todos os conjuntos possíveis baseados em tal matriz, levando em conta quantidade de colunas para determinar o tamanho do conjunto.
Logo no exemplo citado, seria possível criar (3^4) 81 conjuntos diferentes.
Ex.:
[1] "adkm"     [4] "adem"    [8] "adfm"      [11] "ajkm"
[2] "adkr"     [5] "ader"    [9] "adfr"      [12] "ajkr"
[3] "adkp"     [7] "adep"    [10] "adfp"     [13] "ajkp"

Qual seria a melhora maneira de varrer esse array e criar conjuntos baseados nas colunas?
int qtdColunas = 4;

char[] conjunto1 = new char[qtdColunas];
conjunto1[0] = 'a';
conjunto1[1] = 'd';
conjunto1[2] = 'k';
conjunto1[3] = 'm';

char[] conjunto2 = new char[qtdColunas];
conjunto1[0] = 'a';
conjunto1[1] = 'd';
conjunto1[2] = 'k';
conjunto1[3] = 'r';

char[] conjunto3 = new char[qtdColunas];
conjunto1[0] = 'a';
conjunto1[1] = 'd';
conjunto1[2] = 'k';
conjunto1[3] = 'p';

Tentei encontrar na web algo já pronto, mas não sei exatamente nomear o que estou fazendo.

Eu gostaria de uma solução limpa, rápida e com pouco consumo de memória.

A matriz dada na pergunta é apenas um exemplo, pois em meu código posso construir matrizes maiores. E é claro que não a preencho linha por linha como exemplifiquei.

Acredito ser apenas uma questão de lógica, mas boas práticas fazem muita diferença nessa hora. Por estar começando, eu não gostaria de cometer mais erros que o aceitável.
Answer: Imagino que isso resolva qualquer tamanho de matriz
    public static string[] TodosPossiveis(char[,] letras)
    {
        int linhas = letras.GetUpperBound(0) + 1;
        int colunas = letras.GetUpperBound(1) + 1;
        int max = (int)Math.Pow(linhas, colunas);
        string[] todos = new string[max];

        int[] posY = new int[colunas];

        int atual = 0;
        while(atual < max)
        {
            string nova = "";
            for(int i = 0; i < colunas; i++)
            {
                nova += letras[posY[i], i];
            }
            for(int i = colunas-1; i > -1; i--)
            {
                posY[i]++;
                if(posY[i] == linhas)
                {
                    posY[i] = 0;
                }
                else
                {
                    break;
                }
            }
            todos[atual++] = nova;
        }

        return todos;
    }

Comment: Cara, se eu pudesse te dar + 2, eu te daria! Muito obrigado, funcionou perfeitamente. E usando tipos primitivos ficou da forma como eu queria.

Conjunto usando matriz em c#


Integration by parts Green's formula

Question: I would like to do some kind of integration by parts to $$\int{f(\nabla g \cdot \nabla h)}$$
We know Green's identity holds with $f \equiv 1$.  Is there a nice expression with general $f$?  Let's say everything here is smooth so the integrals and derivatives make sense.
Comment: downvote... why?
Answer: One might note that $\nabla g \cdot \nabla h = \nabla \cdot (g \nabla h) - g \Delta h$. Not sure where to go from here, but this might be a start.
Comment: In fact, that actually was exactly what I needed.  Thank you!
Comment: I'm interested to know what you ended up with?
Comment: I'm dealing with functions that are $0$ on the boundary anyways, so do green's identity in vector form (choose $f\nabla g$ and $\nabla h$), then apply your identity.  This moves derivatives off of the function I wanted to get them off of.
Comment: You need $f \nabla g$ to be the gradient of some function, right? Of what function is it the gradient? (I'm just learning this stuff, too...)
Comment: I'm using $\int_{U} (\psi \nabla \cdot \bf{\Gamma} + \bf{\Gamma}\cdot \nabla \psi)  dV = \oint_{\partial U}{\psi \bf{(\Gamma \cdot n})}ds$

Integration by parts Green's formula


Django updating model has broken the admin

Question: I updated my models class called Account. I have removed a field called "user"
Removed this line:
user = models.ForeignKey(User, unique=True)

I then ran makemigration and then migrate successfully.
When I goto:
http://127.0.0.1:8000/admin/reports/account/
I get the below error message:

Account' object has no attribute 'user'

My question is, how do I update the admin code easily when making structural changes to my models/migration?
My admin.py looks like this:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import Account
from .models import Report

from django.contrib import admin

# Register your models here.

admin.site.register(Account)
admin.site.register(Report)

Answer: It is a bit complex process.
The easier way is if you don't have any important data and you are only in development phase, just delete your database, and try makemigrations and migrate after that.
It will work fine.
Comment: Sorry, my bad, I had user in the in my  def __str__(self): return user.username. All fixed thanks for your help
Comment: What you are doing can you explain?
Comment: @ChrisEvans, Nice to hear that you fixed, If the solution helped, please vote up and select the answer. Thanks for all the cooperation.
Comment: @ChrisEvans you can select the answer if it helped.
Answer: Well, you probably forgot to remove user reference somewhere, possibly in admin.py. If you go there, there should be something like this (if not, post yours):
@admin.register(Account)
class AccountAdmin(admin.ModelAdmin):

    list_display = ('user', ...)

Just remove the user from there and you should be good.
Comment: Hey Jahongir Rahmonov, thanks for your response.

I just added my admin.py to the post. Look a bit different.


Probability distribution for sum of squared differences of randomly distributed marbles

Question: Suppose I have $n$ buckets and $m$ marbles, where $m >> n$, and I randomly put marbles in buckets Each marble has a $1/n$ chance of being put in each bucket. At the end of the process, bucket $i$ has $m_i$ marbles for $1 \leq i \leq n$.
As a function of $n$ and $m$, what would be the probability distribution of
$$
\sum_{i=1}^n \left( m_i - \frac{m}{n} \right)^2
$$
If there's some more interesting quantity for measuring "even-ness" of distribution (maybe with a simpler PDF expression), I'd be even more interested in that!
PS: This came up as I was trying to write some tests automatically checking how "fair" bucketing functions are
Answer: I don't think there is a usable formula for the exact distribution of your quantity, but $n/m$ times your quantity has approximately a chi squared distribution on $n-1$ degrees of freedom.  (After multiplication by $n/m$ your quantity is  the Pearson chi squared test statistic, so a lot is known about it.)  If $m/n\to\infty$ and also $n\to\infty$, you can probably use a normal approximation to this chi squared distribution.
Comment: m \to \infty is fine, but n \to \infty doesn't work. Thanks for the pointers though: they are a good place to start hunting!


SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.BATTERY_CHANGED

Question: I am trying to develop a widget which showing Battery Temperature. when i am registering a broadcast Receiver with android.intent.action.BATTERY_CHANGED
it shows some error like this.
java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.BATTERY_CHANGED from pid=-1, uid=10058

As far as i know there is no need of permission for broadcast .  If it is in the case of an activity. it is working properly.
    Intent intent = new Intent();
    intent.setAction("android.intent.action.BATTERY");
    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Comment: show the code how you register
Comment: @MarcinOrlowski : please check the code.
Comment: Check this url if it solves your problem - http://stackoverflow.com/questions/11277302/i-cant-receive-broadcast-on-battery-state-change
Comment: why would you even want to do this?
Answer:
As far as i know there is no need of permission for broadcast

Yes, there is. You are sending the broadcast. And, quoting the documentation for ACTION_BATTERY_CHANGED:

This is a protected intent that can only be sent by the system.

You are not the system; you cannot send this broadcast.
I have no idea why you are creating a PendingIntent that is trying to send this broadcast, but you will need to do something else instead. If your objective is to trigger your BroadcastReceiver from a tap on your app widget, where that receiver also happens to listen to ACTION_BATTERY_CHANGED, then just use an explicit Intent identifying the receiver when creating your PendingIntent:
PendingIntent.getBroadcast(context, 0, new Intent(this, YourReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);


Proof formula for $(\sin(x))^n$

Question: I currently try to prove the following equation:
$$(\sin(x))^n=\sum_{k=0}^{n}{a_k\cos(kx)+b_k\sin(kx)}$$
with $a_0,...,a_k$ and $b_0,...b_k$ being real numbers for each $n$.
I tried to proof this by induction, then I could use the induction hypothesis for replacing $\sin(x)^{n}$ with $\sin(x)\cdot (\sum_{k=0}^{n}{a_k \cos(kx)+b_k\sin(kx)})$
Do you have any idea, how I can get this in the form $\sum_{k=0}^{n+1}{a_k \cos(kx)+b_k\sin(kx)}$?
Thanks
Answer: Hint
$$\sin^n(x)=\left(\frac{e^{ix}-e^{-ix}}{2i}\right)^n = ?$$
Comment: Yeah, binomical theorem but I don't think that this really helps me in this case, I think that it is much easier with addition theorems..
Comment: @slkjck3: this pretty much gives you the answer immediately.
Comment: @CheerfulParsnip Thanks. {}{}{}{}{}{}{}
Comment: I don't see that..
Comment: @slkjck3: Once you expand it out using the binomial theorem, use that $(e^{ix})^k=e^{ikx}=\cos(kx)+i\sin (kx)$, so that each summand becomes a linear combination of terms of the form you are looking for.
Comment: @CheerfulParsnip hey, this is my main account (I'm slkjck3). I had trouble getting this account working but now it's ok. I still don't see how I could use this as a proof. I think that mrtaurho's answer below is much better because in my oppinion I think that you still have to do crazy reshuffling of terms, etc. If not, then it would be really kind if you could explain it a bit more indepth. Because I think you get somethin like $sin((n-k)x)$ which is not equal to $sin(kx)$...
Comment: @Gykonik: It's true you have to do some reindexing but it's not bad. You get terms of the form $\sin((2k-n)x)$ where the coefficient $(2k-n)x$ can range from $-n$ to $n$, and using the oddness of sine, can be converted to all lie between $0$ and $n$ just as you desired. I'll do an example to convince you. Stay tuned.
Answer: This is an example to illustrate Hamam Abdallah's method. Let's compute $\sin^6(x)$.
\begin{align*}
\sin^6(x)&=\frac{1}{(2i)^6}(e^{ix}-e^{-ix})^6\\
&=\frac{-1}{2^6}(e^{6ix}-6e^{(5-1)ix}+15e^{(4-2)ix}-20e^{(3-3)ix}+15e^{(2-4)ix}-6e^{(1-5)ix}+e^{-6ix})\\
&=-\frac{1}{2^6}((e^{6ix}+e^{-6ix})-6(e^{4ix}+e^{-4ix})+15(e^{2ix}+e^{-2ix})-20)\\
&=-\frac{1}{2^6}\left(2\cos(6x)-12\cos(4x)+30\cos(2x)-20\right)
\end{align*}
In general you can derive formulas for $\sin^n(x)$ based on the parity of $n$ modulo $4$. Symmetry among the terms in the binomial expansion will cause terms to group together to form sines or cosines.
Edit (11/29/18): Having nothing better to do on a rainy day, I worked out the general formulae. Enjoy:
\begin{align*}
\sin^{2m}(x)&=\left(\frac{e^{ix}-e^{-ix}}{2i}\right)^{2m}\\
&=\frac{(-1)^m}{2^{2m}}\sum_{k=0}^{2m}(-1)^k\binom{2m}{k}e^{ikx-i(2m-k)x}\\
&=\frac{(-1)^m}{2^{2m}}\sum_{k=0}^{2m}(-1)^k\binom{2m}{k}e^{i(2k-2m)x}\\
&=\frac{(-1)^m}{2^{2m}}\left[\sum_{k=0}^{m-1} (-1)^k\binom{2m}{k}e^{i(2k-2m)x} + (-1)^m\binom{2m}{m}+\sum_{k=m+1}^{2m}(-1)^k \binom{2m}{k}e^{i(2k-2m)x}\right]\\
&=\frac{(-1)^m}{2^{2m}}\left[\sum_{u=1}^{m} (-1)^{m-u}\binom{2m}{m-u}e^{-i(2u)x} +(-1)^m \binom{2m}{m}+\sum_{u=1}^{m} (-1)^{m+u}\binom{2m}{m+u}e^{i(2u)x}\right]\\
&=\frac{(-1)^m}{2^{2m}}\left[(-1)^m \binom{2m}{m}+\sum_{u=1}^{m} (-1)^{m-u}\binom{2m}{m-u}(e^{-i(2u)x}+e^{i(2u)x})\right]\\
&=\frac{1}{2^{2m}}\left[ \binom{2m}{m}+\sum_{u=1}^{m}(-1)^{u} \binom{2m}{m-u}2\cos(2ux)\right]\\
\end{align*}
\begin{align*}
\sin^{2m+1}(x)&=\left(\frac{e^{ix}-e^{-ix}}{2i}\right)^{2m+1}\\
&=\frac{(-1)^m}{2^{2m+1}i}\sum_{k=0}^{2m+1}(-1)^{k+1}\binom{2m+1}{k}e^{ikx-i(2m+1-k)x}\\
&=\frac{(-1)^m}{2^{2m+1}i}\sum_{k=0}^{2m+1}(-1)^{k+1}\binom{2m+1}{k}e^{i(2k-2m-1)x}\\
&=\frac{(-1)^m}{2^{2m+1}i}\left[\sum_{k=0}^{m}(-1)^{k+1}\binom{2m+1}{k}e^{i(2k-2m-1)x}+\sum_{k=m+1}^{2m+1}(-1)^{k+1}\binom{2m+1}{k}e^{i(2k-2m-1)x}\right]\\
&=\frac{(-1)^m}{2^{2m+1}i}\left[\sum_{u=0}^{m}(-1)^{m-u+1}\binom{2m+1}{m-u}e^{-i(2u+1)x}+\sum_{u=0}^{m}(-1)^{u+m}\binom{2m+1}{u+m+1}e^{i(2u+1)x}\right]\\
&=\frac{(-1)^m}{2^{2m}}\sum_{u=0}^{m}(-1)^{m-u}\binom{2m+1}{m-u}\left(\frac{e^{i(2u+1)x}-e^{-i(2u+1)x}}{2i}\right)\\
&=\frac{1}{2^{2m}}\sum_{u=0}^{m}(-1)^{u}\binom{2m+1}{m-u}\sin((2u+1)x)
\end{align*}
Comment: Oh yeah, thanks I understand this one. It would be easy if the exercise was "Find a formula for $\sin(x)^n$. Sadly the exercise was, that I should proof that $sin(x)^n$ corresponds to the above forumla and with your approach I think it is possible, but with much more effort then "simply" proof it by induction. Because I have to do a lot of reshuffling, arguing and splitting for n odd and n even, etc... (I think so)
Comment: @Gykonik: I'm really not getting your objection. This approach gives you explicit formulae for the coefficients $a_k$ and $b_k$ which is even stronger than what your problem asked for.
Answer: One may consider the two formulae
$$\begin{align}\sin(n)\cos(m)&=\frac12(\sin(n+m)+\sin(n-m))\\
\sin(n)\sin(m)&=-\frac12(\cos(n+m)-\cos(n-m))\end{align}$$
which are both a direct consequence of the addition theorems for the sine function and the cosine function respectively. In your case we set $n=x$ and $m=kx$ to get
$$\begin{align}
\sin(x)\cos(kx)&=\frac12(\sin(x+kx)+\sin(x-kx))=\frac12(\sin((k+1)x)-\sin((k-1)x))\\
\sin(x)\sin(kx)&=-\frac12(\cos(x+kx)-\cos(x-kx))=-\frac12(\cos((k+1)x)-\cos((k-1)x))
\end{align}$$
As you can see this produces a term of the type $a_{k+1}\cos((k+1)x)+b_{k+1}\sin((k+1)x)$ which implies a higher upper border and therefore you are done hence this procedure can be applied for any value of $k$ and $n$ respectively.
Concerning the special terms $\sin(-x)$ and $\cos(-x)$ occuring for $k=0$ recall the symmetric properties of the trigonometric functions.

EDIT
Since I realised for myself - by extending my answer within the comments - actually writing down a proof using these given formulae seems to be more difficult than I thought in the first place.
Therefore lets plug in the new terms constructed by using the given formulae. So we get
$$S=\sum_{k=0}^n \left[\frac{a_k}2(\sin((k+1)x)-\sin((k-1)x))-\frac{b_k}2(\cos((k+1)x)-\cos((k-1)x))\right]$$
Hence we are dealing with finite sums we are perfectly fine with rearraging the sums aswell as splitting them up. So lets do a little bit of reshaping
$$\begin{align}
S&=\sum_{k=0}^n \left[\frac{a_k}2(\sin((k+1)x)-\sin((k-1)x))-\frac{b_k}2(\cos((k+1)x)-\cos((k-1)x))\right]\\
&=\sum_{k=0}^n \left[a_k'\sin((k+1)x)-b_k'\cos((k+1)x)+b_k'\cos((k-1)x))-a_k'\sin((k-1)x)\right]\\
&=\sum_{k=0}^n \left[a_k'\sin((k+1)x)-b_k'\cos((k+1)x)\right]+\sum_{k=0}^n \left[b_k'\cos((k-1)x))-a_k'\sin((k-1)x)\right]\\
&=\underbrace{\sum_{k=1}^{n+1}\left[a_{k-1}'\sin(kx)-b_{k-1}'\cos(kx)\right]}_{=S_1}+\sum_{k=0}^n \left[b_k'\cos((k-1)x))-a_k'\sin((k-1)x)\right]\\
&=S_1+b_0'\cos(-x)-a_0'\sin(-x)+\sum_{k=1}^n \left[b_k'\cos((k-1)x))-a_k'\sin((k-1)x)\right]\\
&=S_1+b_0'\cos(x)+a_0'\sin(x)+\underbrace{\sum_{k=0}^{n-1} \left[b_{k+1}'\cos(kx)-a_{k+1}'\sin(kx)\right]}_{=S_2}\\
&=a_0'\sin(x)+b_0'\cos(x)+S_1+S_2
\end{align}$$
Now we can argue there are terms for $k=0$ produced by the sum $S_2$, terms for $k=n+1$ produced by $S_1$, the extra term which matches with the case $k=1$ for either $S_1$ or $S_2$ and terms inbetween with coefficients composed out of these given by $S_1$ and $S_2$. Therefore we can proceed to say that
$$S=\sum_{k=0}^{n+1}a_k''\cos(kx)+b_k''\sin(kx)$$
for some $a_k''$ and $b_k''$ which can be computed by oberserving the matching constants infront of the sines and cosines for the respective values of $k$ in each sum $S_1$ and $S_2$ and for $k=1$ the remaining term respectively.
Comment: @saulspatz Well since the induction hypotesis states that there are terms of the type $a_k\sin(kx)+b_k\cos(kx)$ for any $k=0,1,...,n$ there are indeed such terms with an $k-1$ as argument beforehand. Furthermore the $a_k$s and $b_k$s are some constants not explicitly choosen so the new terms with the argument $(k-1)x$ can be absorbed within the given ones by considering the new constants $a_{k-1}'$ and $b_{k-1}'$.
Comment: You're right; I don't know what I was thinking.  I must still be asleep.
Comment: @mrtaurho yeah I understand this approach. I also tried it with the addition theorems but I don't get your second last pararaph. Why this produces a term of the this type? And the part with "implies a higher upper border" I totaly understand but is there a way of writing this down mathematicly correct?
Comment: Split up the sum in an part with the $(k-1)$ terms and in one with the $(k+1)$ and apply some suitable index shifts, so you will get sums which will add up in one sum with the bounds $0$ and $n+1$.
Comment: Mhh I can't figure out the index shifts. I tried to shift the two sums by +1 so I end up with a sum from k to n+1, which is my desired result but this wasn't good. Then I tried to shift the sum with $(k-1)$ terms, so I have $sin((k+1)x$ / $cos$ in both sums but also there I couldnt figure out any further... Could you give me another hint?
Comment: @slkjck3 I have added a complete solution to my answer which hopefully clears all doubts :)
Comment: @mrtaurho oh yeah, now it's much clearer! I only don't understand the "argumentation" (second last pagaraph) because $S_1$ is a sum from 0 to n+1 and $S_2$ is a sum from 0 to n-1. This would mean that you need the missing $S_2$-sums for n and n+1 and I don't know how you can argue that they exists :D
Comment: @slkjck3 Actually the sum $S_1$ is from $1$ up to $n+1$ and $S_2$ from $0$ up to $n-1$ respectively. Concerning your doubts regarding to the $n-$th and $n+1-$th term: I would argue that their coefficients - $a_{n-1}',b_{n-1}',a_n'$ and $b_n'$ (which can be found by oberseving the sum $S_1$ for $k=n$ and $k=n+1$) - are all non-zero since they are just defined as $a_{n-1}'=\frac{a_{n-1}}2$ -  and so on. As long as we claim that the originial sum has the characteristic that for all $k$ we can say $a_k$ and  $b_k$ are non-zero this will be a valid argumentation.

Proof formula for $(\sin(x))^n$


Apache displays error page half way through PHP page execution

Question: I've just installed Zend Server Community Edition on a Windows Server 2003 box, however there's a bit of a problem with the display of a lot of our PHP pages.  The code has previously running under the same version of PHP (5.3) on IIS without any issues.
By the looks of things, Apache (installed as part of Zend Server) is erroring out during the rendering of the page when it comes across something it doesn't like in the PHP.  Going through the code, I've been able to get past some of the problems by removing the error suppression operator (@) from function calls and by changing the format of some includes. However, I can't do this for the whole site!
Weirdly, the error code is reported as "200 OK".  The code snippet below shows how the Apache error HTML interrupts the regular HTML of the page.

Ma quande lingues coalesce, li grammatica del resultant lingue es plu simplic e regulari quam ti del coalescent lingues.</<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>200 OK</title>

OK

The server encountered an internal error or
misconfiguration and was unable to complete
your request.

Please contact the server administrator,
 firstname.lastname@example.com and inform them of the time the error occurred,
and anything you might have done that may have
caused the error.

More information about this error may be available
in the server error log

The Apache error log doesn't offer any explanation for this, and I've exhausted my Googling skills, so any help would be greatly appreciated. Thanks.
Answer: You'll want to look through your code.
My immediate line of thinking is that you're include()ing (or similar function) a page or script via HTTP (you have allow_url_fopen enabled), and the server the included page/script is running on is having issues.
If you edit php.ini (and restart Apache) to change allow_url_fopen to false, you'll have better security in your hosting environment as well as most likely get a better error, telling you where you're trying to include a broken URL.
Comment: Thanks for your reply. However, allow_url_fopen is already off. Admittedly, a couple of the "fixes" have been to do with changing includes, but none are via HTTP and this has not been the only cause of the error appearing.
Answer: The @ error suppression operator is expensive - a better option is to use error_reporting( 0 ) to disable errors, or use your own function.
In this case, seeing as you have no info at all, you could try using this error handler in place of your default handler to see if you can tie this error to a PHP function crashing apache.
function Andy_errorHandler( $errno, $errstr, $errfile, $errline ) {
    $stack_trace = '';
    switch ( $errno ) {
        case E_NOTICE:
        case E_USER_NOTICE:
        case E_STRICT:
            return;
            break;
        default:
            try {
                throw new Exception( $errstr, $errno );
            } catch( Exception $e ) {
                //build stack trace
                $stack_trace .= "File: $errfile Line: $errline\n" . $e->getMessage() . "\n" . "Error No: ".$e->getCode(). "\n";
                $stack_trace .= $e->getTraceAsString();
            }
        break;
    }

    if( ! isset( $GLOBALS['error_handler_output'] ) ) {
        $GLOBALS['error_handler_output'] = nl2br( $stack_trace ) . '
';
    } else {
        $GLOBALS['error_handler_output'] .= nl2br( $stack_trace ) . '
';
    }

    return true;
}
$old_error_handler = set_error_handler( "Andy_errorHandler" );

Comment: Couldn't agree more on the @ advice. Unfortunately the code is quite old and busted and could do with a rewrite. I'll give the error handler function a go later today and see if it sheds any light. Thanks!


Como contar registos iguais numa uncia coluna e obter esse mesmo numero?

Question: Exemplo da tabela:
| Ti | Orien      |

| ---|   JML      |

| ---|   JML      |

| ---|   RGM      |

| ---|   AAA      |

| ---|   AAA      |

Resultado exemplo: JML - 2
                   RGM - 1
                   AAA - 2
Answer: Com o php5.5 pode combinar a função array_column() que extrair os valores de indíce e retorna eles como um novo array, com use a função array_count_values() que dira quantas valores iguais existem no array, as chaves são os valores do banco de dados e os valores são o número de ocorrências.
$arr = [['str' => 'abc'], ['str' => 2015], ['str' => 2015], ['str' => 'doge'], ['str' => 'wow'], ['str' => 'wow']];
$itens = array_count_values(array_column($arr, 'str'));

echo "
";
print_r($itens);

Retorno:
Array
(
    [abc] => 1
    [2015] => 2
    [doge] => 1
    [wow] => 2
)

Comment: Estava a pensar em algo como um Select Ti, count(Orien) as num FROM tabela".
Comment: @RuiManuelMartins , um `select Ti, count(Orien) as num FROM tabela group by Orien` resolve?
Comment: Não testei ainda. o meu código é este:
Comment: $query_b="SELECT * FROM `docentes` ORDER BY `docentes`.`NomeAscii` ASC";
$query_c= "SELECT Orientador, COUNT(*) AS numInstances FROM teses GROUP BY Orientador";

print_TD(""; // list box select command
echo "" ."Convidar orientador";
foreach ($db->query($query_b) as $row)//Array or records stored in $row {
      echo "$row[CodDocente] - $row[NomeAscii]";
      /* Option values are added by looping through the array */
     }
      echo "";
Comment: Desculpa enganei-me.
o objectivo basicamente é fazer um dropdown list com a informação de uma tabela e depois ir buscar á outra tabela os registos que já tem mais de um.


Show $P(\frac{1}{n}\sum_{i=1}^{n}Y_i\geq c)\leq e^{-nd}$ for constants $c$ and $d$

Question: Let $Y_1, Y_2\ldots$ be a sequence of i.id. random variables uniformly distributed on $[0,1]$. Let $c>\frac{1}{2}$. Show that there exists $d>0$ (depends on $c$) such that
$$P\left(\frac{1}{n}\sum_{i=1}^{n}Y_i\geq c\right)\leq e^{-nd}$$
What I could do best so far:
$E(Y_i)=\frac{1}{2}$ and $V(Y_i)=\frac{1}{12}$ since $Y_i$ are uniformly distributed on $[0,1]$.
By the Weak Law of Large Numbers:
$$P\left(\Big|\frac{1}{n}\sum_{i=1}^{n}(X_i-E(X_i))\Big|\geq\epsilon\right)\leq\frac{V(X_i)}{n\epsilon^2}$$
then
$$P\left(\Big|\frac{1}{n}\sum_{i=1}^{n}X_i-\sum_{i=1}^{n}E(X_i)\Big|\geq\epsilon\right)\leq\frac{V(X_i)}{n\epsilon^2}$$
$$P\left(\Big|\frac{1}{n}\sum_{i=1}^{n}X_i-\frac{n}{2}\Big|\geq\epsilon\right)\leq\frac{1}{12n\epsilon^2}$$
I am stuck here.
I have little clue how to get the exponential function.
Could someone please give some light on how to approach and proceed with the problem?
Thanks.
EDITED
Thanks @Fnacool for the clue. But I was still stuck in some steps:
$$P\left(\frac{1}{n}\sum_{i=1}^{n}Y_i\geq c\right)=P\left(e^{\theta\sum_{i=1}^{n}Y_i}\geq e^{\theta cn}\right)\leq\frac{E\left(e^{\theta\sum_{i=1}^{n}Y_i}\right)}{e^{\theta cn}}=\frac{E[e^{\theta Y}]^n}{e^{\theta cn}}$$
Now $E[e^{\theta Y}]^n=(\int_0^1 e^{\theta y}\times1 dy)^n$ since pdf of $Y$ is $f(y)=1$
Then
$$\left(\int_0^1 e^{\theta y}\times1 dy\right)^n=\left(\left[\frac{1}{\theta}e^{\theta y}\right]_0^1\right)^n=\left(\frac{e^{\theta}}{\theta}-\frac{1}{\theta}\right)^n$$
Then I was stuck here. How can we perform the multinomial expansion?
Comment: Actually using Markov's inequality : $P(|\omega | \ge x) \le \frac{E(\omega)}{x}$
Answer: Clue:

$\{\sum_{i=1}^n Y_i > cn\} = \{e^{\theta \sum_{i=1}^n Y_i }>e^{\theta cn}\}$ for any $\theta>0$.
For positive random variable, $Z$ and $z>0$, $P(Z>z)\le E[Z]/z$.
$E[e^{\theta \sum_{i=1}^n Y_i}] = E[e^{\theta Y_1}]^n$
Next,

$$ E [ e^{\theta Y}]= \int_0^1 e^{\theta u} du = \frac{e^{\theta}-1}{\theta}=e^{\theta} \left( \frac{1-e^{-\theta}}{\theta}\right).$$
Therefore, our upper bound is
$$ e^{n \theta}  \left( \frac{1-e^{-\theta}}{\theta}\right)^n e^{-\theta c n}.$$
Take logarithm to obtain
$$ n \left ( \theta (1-c)+\ln (1-e^{-\theta})-\ln \theta\right)=(*)$$
We need this to be negative. We will optimize over $\theta$. In principle, small enough $\theta$ will do the trick. Here is a bare hands approach.
Take $e^{-\theta} > 1-\theta+ \theta^2/2 -\theta^3/6$ (fourth derivative is positive). Therefore,
$$\ln (1-e^{-\theta}) < \ln \theta + \ln (1-\theta/2+\theta^2/6) .$$
and then
$$(*) < n (\theta(1-c)+ \ln (1-\theta/2+\theta^2/6)).$$
Using $\ln (1-x)<-x$ for $x<1$ and choosing $\theta$ so that $\theta/2-\theta^2/6<1$, we finally have
$$ (*) < n (\theta (1-c) -\theta/2+\theta^2/6)=n\theta( (\frac 12 -c) + \frac{\theta}{6}).$$
For small enough $\theta>0$ this is negative.
Comment: I have made some edits and I was stuck in the process. Could you lend a hand please? Thanks @Fnacool


How do I get the actual dimensions (i.e., sans-black bars) of a YouTube video using the JS iframe API?

Question: I need to know the actual width and height of a YouTube video embedded in my website. Here's a crude illustration.
I've searched through the API docs and I haven't found a way to do this. I've noticed the player variable contains a method called showVideoInfo() which overlays exactly the data I want on the video player... but unfortunately since it is in the iframe I'm unable to access it from JavaScript.
Is there any way to do this without having a backend script that queries the JSON API? Because I'd seriously rather not have to do that.
Comment: Can you use jQuery? I mean, need to be only with iframe API?
Comment: Yeah, I'm using jQuery. I'm currently looking into using JSONP for this, actually, but it'd be nice if I didn't have to do that.
Answer: Fiddle
As I understand, this is what you want? Ignore I'm writing, the dimensions, It's onlye to let you know actual dimensions
    var vidWd = $('.videoCont iframe').width();
    var vidHg = $('.videoCont iframe').height();

$(document).ready(function(){
 function getDimension() {
 var vidWd = $('.videoCont iframe').width();
  var vidHg = $('.videoCont iframe').height();

  $('.videoCont h1 p').remove();
  $('.videoCont h1 span').remove();
  $('.videoCont h1').append('
These are the dimensions:
' + vidWd + ' Widht - ' + vidHg + ' Height');
}
$(document).ready(getDimension);
$(window).resize(getDimension);
});
.videoCont{
  font-family: sans-serif;
  border: 1px solid #333;
  padding: 5px;
}
.videoCont iframe{
  width: 100%;
}
.videoCont h1 p{
  font-size: 14px;
}
.videoCont h1 span{
  font-size: 15px;
  text-decoration: underline;
}

This is your video:


Cannot login to cyradm to administrate Cyrus IMAP

Question: I have a fresh installation of cyrus-imapd (2.3) on CentOS 5 with all these packages:

cyrus-imapd
cyrus-imapd-utils
cyrus-sasl
cyrus-sasl-plain
cyrus-sasl-md5

I have changed the password of user cyrus: passwd cyrus.
I am trying to log in to cyradm with cyradm -user cyrus localhost, but, when I enter my password, I get the following error message:
Login failed: generic failure at /usr/lib/perl5/vendor_perl/5.8.8/i386-linux-thread-multi/Cyrus/IMAP/Admin.pm

I am afraid that I have the same problema that is explained in cyradm: cannot authenticate to server, but I am not able to solve it with the hints given by that guy.
How could I solve this issue and succesfully connect to my instance of cyrus-imapd and using cyradm?
Comment: +1 for fighting with "generic failure" errors :)
Answer: The command passwd cyrus does not set the password for the cyrus user; unless you've setup sasl to use the local passwd file.
What is your cyrus config file?  Specifically how have you configured sasl?  The link you have mentioned sasldb.  If you using sasldb, you should use saslpasswd2 to set the cyrus user password.
Comment: How do you configure cyrus to use the local password file?


How to implement MVC with asynchronous callbacks?

Question: I am currently refactoring my GWT client and try to apply the MVC pattern to all concerned classes. My problem is that I am not sure about two things here:

Where do I control which view gets displayed? For example if the user logs in and the start page should get loaded. Would the controller load that page or the model?
How would I best handle asynchronous callbacks and who (model or controller) is supposed to hold the async service?

I have this simple login example that is my actual code as it currently looks like:
LoginModel
// LoginModel appears kind of obsolete ..
public class LoginModel {

    private final LoginServiceAsync loginService = LoginService.Util.getInstance();

    public void onLoginClick(String userId, String password, AsyncCallback<UserDTO> asyncCallback) {
        // Login on the server ..
        this.loginService.login(userId, password, asyncCallback);
    }
}

LoginView
public class LoginView extends Composite {

    private static UILoginUiBinder uiBinder = GWT.create(UILoginUiBinder.class);

    @UiField Button btnLogin;
    @UiField TextBox txtPassword;
    @UiField TextBox txtUserID;

    interface UILoginUiBinder extends UiBinder<Widget, LoginView> {
    }

    public LoginView() {
        initWidget(uiBinder.createAndBindUi(this));
    }

    public void addLoginButtonClickHandler(ClickHandler clickHandler) {
        this.btnLogin.addClickHandler(clickHandler);
    }

    public String getUserId() {
        return this.txtUserID.getText();
    }

    public String getPassword() {
        return this.txtPassword.getText();
    }

    public void displayLoginFailure() {
        // TODO display login failure ..
    }
}

LoginController
public class LoginController {

    private final LoginModel loginModel;

    private final LoginView loginView;

    public LoginController(LoginModel loginModel, final LoginView loginView) {

        this.loginModel = loginModel;
        this.loginView = loginView;
        this.loginView.addLoginButtonClickHandler(new LoginButtonClickHandler());
    }

    private class LoginButtonClickHandler implements ClickHandler {
        @Override
        public void onClick(ClickEvent event) {

            loginModel.onLoginClick(loginView.getUserId(), loginView.getPassword(), new AsyncCallback<UserDTO>() {
                public void onFailure(Throwable caught) {
                    onLoginFailure(caught);
                }

                public void onSuccess(UserDTO userDto) {
                    onLoginSuccess(userDto);
                }
            });
        }
    }

    public void onLoginFailure(Throwable caught) {
        Throwable cause = caught.getCause();
        if (cause instanceof LoginException) {
            GWT.log("Cause: " + cause.getMessage());
            cause.printStackTrace();
        }

        this.loginView.displayLoginFailure();
    }

    public void onLoginSuccess(UserDTO userDto) {
        // NOTE: UIStart is what is going to become StartView!
        UIStart home = new UIStart();
        RootPanel.get("mainUIContainer").clear();
        RootPanel.get("mainUIContainer").add(home);
    }
}

Is this a good implementation of the MVC pattern? Can I do better?
Answer: Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user (Source: Wikipedia)
Saying that, MVC has 3 components,
1) Model: Ideally, it should contain only getters and setters. No buisness logic should be mentioned here
2) View: This part contains only view. You will not link your view to the main html here. Its just a simple view with access to model.
3) Controller: All your buisness logic should go here. Controller can access both view and model.
MVC w.r.t GWT should go something like this.
First controller gets instantiated. A controller then creates an instance of model and view.
Model is linked with view, usually model is passed as an argument to the view. You can implement dual binding just like in angular using command pattern and change listeners or update the model values as and when you want (usually on save or submit)
Now coming to your async part. All the async handling should be done at the controller. In the controller, after the success of the async call, model should be updated and it in turn will update the view as model is linked with the view.
I hope this answers your questions and also explain you MVC paradigm.
Comment: Thank you! Your answer explained a lot but I accept El Hoss answer since it directed me to a place where most GWT Developers are might going to want to land. But anyway +1 for your explanation!
Comment: agreed mvp is the way to go. My answer was w.r.t your question which was on mvc. Thats all. Good that you found a way. Cheers..
Answer: There were a talk from Ray Ryan at the Google I/O 2009: Best Practices for Architecting GWT App
In GWT you do not use MVC, you use MVP (Model - View - Presenter) which divides the parts much clearer. You can use MVP for your widgets and your screen.
Next use a EventBus to decouple the components.
Last you should use Acticities & Places to navigate inside your application.
Take a look here:
MVP Activities and Places.
This is a good source to start.
Also, you can look at GWT-Platform GWTP or mvp4g as they are different implementations of the mvp pattern in GWT.
As Abhijith Nagaraja already mentioned: Do your async calls inside the presenter.
Edit: See also Demystifying MVP and EventBus in GWT (Link taken from comment section).
Comment: @El Hoss: I disagree with your statement "In GWT you do not use MVC, you use MVP". Although it is favorable to use MVP, People who should support older versions may still use MVC. Also I believe, providing model access to view in MVC which is not possible in MVP has its own advantage. There is no intermediate handling of data between model and view which is not the case with the MVP, which inturn make presenter code more bulky than controller.

Am not saying people should use MVC over MVP, but just that MVC has its own advantage and people may still use it.

Even I advocate the use of MVP :P
Comment: That video is old but gold! Thanks for that I might not have noticed that I should implement MVP instead of MVC if it wasn't for you!
Comment: @StefanFalk https://www.youtube.com/watch?v=kilmaSRq49g hoss says that mvp is the way to go.. actually not always. it depends a lot on the size of your application and what are your goals. in this video erik kueffler will talk about Ray Ryan video and explains when to use MVP
Comment: @Abhijith Nagaraja: Of course you can use MVC in a GWT application. In the beginning of GWT people used the MVC pattern (for example: Sencha). Using MVC your view deals with the controller and the model, where as in MVP the view deals only with the presenter. It is much cleaner and makes takes and switching the view much easier. Some more informations: http://www.codeproject.com/Articles/288928/Differences-between-MVC-and-MVP-for-Beginners
Comment: @Tobika Thank you for that video! Very informative from a practical point of view and a great explanation!


How to solve ${\bf x}' = A{\bf x}$ with $A=\begin{pmatrix} -3 & 2 \\ -2 & 1 \\ \end{pmatrix}$?

Question:
How to solve ${\bf x}' = A{\bf x}$ with $A=\begin{pmatrix} -3 & 2 \\ -2 & 1 \\ \end{pmatrix}$?

Well, so first I got the eigenvalues which both are $-1$, and eigen vector is $(1,1)$. Then I wrote the answer as ${\bf x}(t) = c_1e^{-t}(1,1) + c_2e^{-t}(2,2)$
In the answer It's written like that:
$x = (C_1+2C_2t)e^{-t}$
$y = (C_1+C_2+2C_2t)e^{-t}$
Can someone explain please how they got to that answer?
Edit: Like I written, I can show that $x = (C_1+2C_2t)e^{-t}$, but when I'm trying to show $y$, I can't add the $+C_2$ there.
Comment: "I don't know myself why they gave me a matrix that isn't diagonalizable" Because "they" wanted you to learn the method to solve the non diagonalizable case (and this step should be over) and to apply this method to the present example, obviously.
Comment: @Moo, *defective* might be the word that you're looking for. The Jordan form will certainly be helpful here.
Comment: Your solution for ${\bf x}(t)$ is incorrect.

There is a *systematic* way to deal with the ODE ${\bf x}'=A{\bf x}$ when $A$ is not diagonalizable. Any "reasonable" ODE textbook should contain a section about this topic.

You might want to try first a "simpler" version of your problem:

${\bf x}'=A{\bf x}$ where
$A=
\begin{pmatrix}
1&1\\0&1
\end{pmatrix}.
$
Comment: Related: http://math.stackexchange.com/q/441121/9464
Comment: @Jack I don't know myself why they gave me a matrix that isn't diagonalizable
Comment: What book are you reading? What is the context for this exercise?
Answer: When you have a repeated eigenvalue of multiplicity $n$ but fewer than $n$ associated eigenvectors, then the eigenvalue is called "defective."  That's the case here, with $n=2$.  If $v$ is the eigenvector, then one solution to the system is $e^{\lambda t}v$.  But you need a second, linearly independent solution and the one you give is not linearly independent (because $(2,2)$ is a scalar multiple of $(1,1)$.
A second, linearly independent solution is given by $e^{\lambda t}(tv+w)$ where $w$ is a "generalized" eigenvector.  It's the solution to $(A-\lambda I)w=v$.  (Actually, it's the solution to $(A-\lambda I)^2 w = 0.$  So in your case, solve
$$\begin{pmatrix} -2 & 2 \\ -2 & 2 \\ \end{pmatrix} w =\begin{pmatrix} 2\\2\\ \end{pmatrix}$$
(where I choose the second version of the eigenvector to match the solution you were given.)
Take $w = (0,1)$ and you have the solution you were given.


Why are these not bases in $\mathbb{R}^4$?

Question: I know that bases vectors must span and be linearly independent.
The (i) is not bases because the last vector contains $\pi$.
The (iii) is not bases because they are not linearly independent.
The (iv) is not bases because there are only 3 vectors here and bases for $\mathbb{R}^4$ must contain at least 4 vectors.
The (v) is not bases because they do not span.
What about (ii), is it a basis?
Comment: Note that any set that contains the zero vector must be linearly dependent.
Answer: (ii) contains only 3 linearly independent vectors, so cannot span a 4-dimensional space.
Also, your answer for (i) is wrong: the $\pi$ is irrelevant. Count the vectors again. Can they be linearly independent?
Comment: Got it, thanks!
Answer: (i) contains 5 vectors, so they can certainly not be linearly independent.  Similarly, (iv) only contains 3 vectors, so certainly cannot span a 4-d space.
(iii) notice that the fourth vector is a multiple of the second one


Using ROBOCOPY to MOVE data around, not copy it

Question: I have the following powershell script, which executes a few robocopy commands:
ROBOCOPY.exe $q3 $q4 /R:5 /W:15 /S /NP /MT:32 /XA:SH /XJD
ROBOCOPY.exe $q2 $q3 /R:5 /W:15 /S /NP /MT:32 /XA:SH /XJD
ROBOCOPY.exe $q1 $q2 /R:5 /W:15 /S /NP /MT:32 /XA:SH /XJD
ROBOCOPY.exe $src $q1 /R:5 /W:15 /S /NP /MT:32 /XA:SH /XJD

This works fine, but it takes a really long time, I'm wondering, if there is a way that I can have robocopy do a "cut + paste" instead of a "copy + paste" so windows will move the NTFS pointer to the file, instead of actually copying all of the bits of each file?
Answer: The /MOV option is designed to do exactly that. Check your specific version of robocopy for it (robocopy /? should show the option).
Comment: not correct answer - robocopy with /MOV parameter actually copies&deletes files, instead of just moving and changing pointer. Which is the original question
Comment: yes, tested this in Windows 10 and robocopy is still copying files
Comment: RoboCopy.exe with /MOVE used to delete source files, but now it sees the source is the same as destination and leaves the source. Win2008r2.  MS knows there are problems with RoboCopy.  Very Disappointing.
Answer: Robocopy only leaves empty source folders when using /MT (in my case 32) switch, if I don't use /MT everything is moved, running on 2008R2.
Answer: move or move-item
Move-Item -Path $source -Destination $source

I believe the existence of the move & ren commands is part of the reason why robocopy doesn't move the pointer (robocopy wants to be robust & recoverable).
Might want to check if it was on the same logical drive on the same machine before deciding to use move or robocopy:
$source_root = [System.IO.Path]::GetPathRoot($source)
$dest_root = [System.IO.Path]::GetPathRoot($dest)
if($source_root -like $dest_root){...


Inside php script isn't working

Question: Im new to php and its developing. i'm using codeigniter. header tag is the only tag display there .latter part of script isn't avaliable in view page.
my login_view.php code
<!DOCTYPE html>

    <meta charset="utf-8">
        <title> Login page </title>

Login

        <?php

        echo form_open();

        echo "
 Email :";
        echo form_input('email');
        echo "
";

        echo "
 password :";
        echo form_input('password');
        echo "
";

        echo "
";
        echo form_submit('login_submit','login');
        echo "
";

        echo form_close();
    ?>

and its  page source
<!DOCTYPE html>

    <meta charset="utf-8">
        <title> Login page </title>

Login

login.php -controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

    public function index()
    {
        $this->load->view('login_view');
    }
}

Comment: did you mean `codeigniter`?
Comment: @itachi yes dude it is
Comment: Turn on your error reporting (`ini_set('display_errors', 1); error_reporting(E_ALL);`). After that, let us know if anything else shows up..
Comment: post your controller.
Comment: @itachi i have posted controller. but it is nothing just call to view
Comment: @Darren where do i find that code.please
Comment: you didn't load the form helper.
Answer: You need to load form helper using $this->load->helper('form'); in controller or config file for showing it. At first, check it and if still you face any problem, then post your controller.
Answer: as far as my CI memory goes back, you have to do like this.

class Login extends CI_Controller {

    public function index()
    {
        $this->load->helper('form'); //<----------- this
        $this->load->view('login_view');
    }
}

Inside php script isn't working


What does the computed code do for a computed field in content type

Question: I have content type field called 'field_p_bo' and it have the computed code as follows

it causes some problem since it affect the saving of this content type , This code is there for some other fields too . What will happen when i remove the computed code ? will it affect any other part of the content type ?
Comment: It's not possible to say without knowing all of the attributes of the content type. Try it on your dev copy and test. That's the only way you'll know for sure
Comment: didnt understand **Try it on your dev copy and test** am already on my dev system
Comment: I need answer for what the computed code does for the content type
Comment: It saves the node if it isn't already saved, gets some data from the database, and populates the field with it. If you want context you'll need to ask the person who wrote the code what it's intended to do. It's not something that can be guessed. Same thing for _will it affect any other part of the content type ?_ Only you or someone else with access to the full site/code can answer thta
Answer: The code fetches the id of the node_project.
For example if the node's project field is set 'Foo' it will get the id of that row where it was saved. As its not clear from where $node comes whether its current loaded node or any other node. But it seems that in computed field you are storing the ID of the project
What I think is causing the problem is if project names are FOO and FOO_BAR the query will result both the ids which can cause to store incorrect ids.
You can simply remove the like operator and add equality.


Can the bass be used instead of drums?

Question: I noticed how there's not a lot of drums in orchestral classical music, in comparison to today's beat-based music. Do they get away with that in the orchestra by having instruments in the bass range act as drums. So the bass instruments (double bass, cello, etc) provide the rhythmic component to the song? And is that true for a song that doesn't have a steady drum beat, because sometimes a steady drum beat can be overbearing in a melodic (think classical music) song. In that case do bass instruments take the role of the drums?
For example, in Shostakovich's Waltz No. 2 there's a bass that sets the rhythm of the waltz.
Comment: What do you mean "get away with that"? Can you give an example where an orchestra got away with something? What was the achievement they were able to do without having a lot of drums?
Comment: Every instrument provides rhythm. Every sound you make has a rhythm, unless it has an extremely slow attack. Every instrument is capable of ruining the groove for everyone else. Flute, piano, violins, choir, you name it. Can you give an example of music that does _not_ have rhythm?
Comment: @piiperi maybe bad choice of words, I meant they use the bass as a way to provide rhythm.
Comment: @piiperi good point. I thought it was mainly the lower range instruments that provide rhythm. this may be a good answer rather than a comment.
Comment: The opening of Brahms's first symphony is probably as close as you will get to a pop music-like steady drum rhythm in pre-20th century classical music. https://www.youtube.com/watch?v=BRdEgS_OHAk
Comment: For a bit of an example of the opposite, think of Jefferson Airplane's White Rabbit - the bass comes in first and establishes the beat, the drums kind of follow it, and the guitar kind of meanders around without being strongly tied to it
Answer: The relative dearth of percussion in classical music versus rock is part of what makes those genres sound different. Nothing takes on the role of a drum kit in the classical orchestra. That role remains empty and that's part of the sound.
When a more percussive sound is desired in the classical orchestra, then percussion instruments are used. These include timpani, cymbals, and triangle in the classical era, and more popular during the romantic era (but not totally unknown in the classical era) are many other instruments, including snare drum, bass drum, slaps, tambourine, bells of various kinds, and many flavors of pitched percussion such as glockenspiel and xylophone.
Comment: If Zeppelin removed the drums from Moby Dick they'd get sued by John Cage.
Comment: @B.Goddard May a good rock song has gone downhill after a great guitar intro; and it has a lot to do with the drums suddenly masking everything.  Sometimes it's the reverse though.
Comment: Still, remember that ochestral percussion very rarely sets the beat.  Even when you want to have a beat, you do it with other instruments (not only bass or tuba, but also e.g. ostinato strings).
Comment: @B.Goddard I really want to put your claim to the test. I just need to find some rock songs with the drums removed.
Comment: @WaterMolecule  Find the most popular rock songs.  Stairway to Heaven.  James Taylor's stuff.  Hotel California.
Answer: In general "classical" music usually has less of a "strict time" feeling than music that typically uses percussion heavily. That's one reason that a conductor is there - to define the time feel, cue sections and so on.
But when a composer wants to make the listener aware of strict time, they can and do use percussion - something like Ravel's Bolero being an obvious example, with that snare figure throughout the piece. Other works could use bass or indeed a repeating melodic motif for the same function (think of the 2nd movement of Beethoven's 7th for instance).
(Of course you won't find trap drums in older classical music, simply because they didn't develop until the early 20th century. But modern composers use all kinds of percussion, even electronic.)
(As an aside, note that in jazz, the bass often takes the "time keeper" role, leaving the drummer free to add rhythmic punctuation - or just try to confuse everyone ;-) So even outside "classical" music, the roles of drums and percussion are far from fixed.)
Comment: I would modify to say "...when a composer does want *the audience to be aware of* strict time..."  .
Comment: good idea! noted
Comment: There are even examples in rock music: in reggae the drums are often heavily syncopated and the "on-the-beat" rhythms come from the base. You can also listen to Stewart Copeland of the Police who often uses similar technniques.
Answer: Every instrument provides rhythm. Every sound you make has a rhythm, unless it has an extremely slow attack. Even chord changes have a rhythmic impact, and the timing of harmonic changes is felt in relation to everything else that's happening in the music. It seems to be a common misconception that a drummer makes the groove and all other players are free to pour any sort of timing mush on top of it. Not at all! Every instrument is capable of ruining the groove for everyone else. Flute, piano, violins, choir, you name it.
A good swinging rhythm has ups and downs, highs and lows, attacks and releases, and basses can provide some of that. Low instruments have a certain role in the big picture, but any instrument with a sharp percussive attack can work somewhat like a drum.
Here's a small example, sequencing orchestral sounds, deliberately starting with non-bass and softer instruments. At what point do you feel there's rhythm? Myself, I'm in the groove from the first measure.

It's of course just a bunch of samples, tightly sequenced, machine-like timing etc. and I didn't put the sounds in a virtual hall because it would have just made it mushy. Could an actual orchestra play like that? Beats me. At least there are extremely groovy violin sections on soul and R&B records! And the same goes with flutes and pianos. But it must be kind of difficult to sound like a Motown studio album when you're on a wide stage in a big hall, conducted by someone with a baton, and ... playing classical music, which isn't actually supposed to sound like Motown.
The thing about modern electronic pop music is that due to technological advancements (or "advancements" depending on how you see it), all kinds of sonic phenomena can be emphasized to be arbitrarily and unnaturally strong. Timing can be machine-like perfect all the time, attacks can be sharp all the time, everything can be incredibly loud and punchy at the same time, the whole soundscape can be made to pump in rhythm with the kick drum, etc. Anything that you can feel, can be distilled and synthesized to feel much stronger. Just look at many questions here, people want to find formulas and rules to musical phenomena so they could turn all knobs to 11, without having to actually learn music.
Maybe there's another question behind this: how can anyone be interested in listening to orchestral music played by actual people, when there are so much stronger artificially enhanced synthetic sensations available?
Comment: "how can anyone be interested in listening to orchestral music played by actual people, when there are so much stronger artificially enhanced synthetic sensations available?" - to me a well recorded band or musician is almost always more interesting. Of course there is music that suits machines more, but that music itself tends to take on a kind of machine like quality, I've noticed. For instance, a Stax or Cannonball Adderley rhythm section just grooves *way* harder than anything I've heard come out of a computer. Light years better. But I guess it's a matter of taste.
Comment: @dmb It was naturally a rhetorical question. Groove makes you move, and music can move you on many different levels. Sometimes it requires human touch to be moving.
Answer:
So the bass instruments (double bass, cello, etc) provide the rhythmic component to the song?

In most classical music with a tune and a harmonic accompaniment the bass instruments play the root notes and change of 4th on-beat, while the  the middle voices are playing the off-beat rhythm to the melody played by the smaller instruments.
So it is correct to compare the rhythmic function of the double bass or the tuba with the bass drum and the alt and tenor voices with the snare - like the left hand of the piano is playing the bass (drum) and the chords are often played (left or right hand) and representing the snare or hi-hat rhythm.

we have just to compare this piano sheet music with the following drum patterns:

The distribution of the rhythmic functions like described above is obvious. In an orchestral instrumentation the bass instruments are playing the same role, of course not in all music and in all cases.
Edit:

Notice that the rhythmic touch is reinforced when the bass (string) instruments are playing pizzicato. Especially in a Waltz the Bass can provide the rhythmic impulse - together with other instruments.
I agree with Todd Wilcox that the drum-set can't be replaced in an orchestra. I always felt that this difference was one critical reason that pupils didn't like as much classic music. It seems to be as it was for them like a salad without a sauce.  When I  played a classic piece e.g. with band-in-a-box or with piano and add a drum set  a lot of people can hardly hear the difference. (POP-classic or Play Bach).
Comment: However,  the rhythm in the bass may not be the same as the midrange or lead part rhythms.  Two vs.  three;   hemiola,  and so on.
Answer: Tango music typically does not use drums. (Older Argentine orchestras for example.) Lots of European and American orchestras do use lots of percussion with a tango. Here's a typical  Argentine dance orchestra.

And here's a German (I think) dance orchestra playing the same piece.

Note that Strasser uses snare drums to emphasize the arrastre (the notes connecting the fourth beat with the first beat of the next measure.) Argentine orchestras often use bass and cello on the arrastre by increasing the bow speed (not pressure) on the notes. Snares are common in the US and Europe. (I use the piano in 32nd notes for a similar effect.)
In Latin (and for that matter most Smooth) dance orchestras, the bass and drums work together. Either can be used to mark out a rhythm. Older Cuban music uses a combination of bongo, conga, timbale, guiro, clavve, maracas, cowbells, etc. for part of the rhythm; the bass and piano the produce a harmonic background. (Others play the melody.)
Any way is OK if it sounds good.
Answer: It's not "classical", but it illustrates the concept.  Below is Reflections of Earth, by Gavin Greenaway, which was used as the fireworks music for Epcot between 2000 and 2019.

The piece takes you through a wide range of styles over its 9-ish minute duration.  The first and last thirds are highly rhythmic, and you'll notice that through much of those portions (as well as some portions of the slower middle section), the rhythm is provided primarily by the articulations in the strings (and, to some extent, brass).  Percussion is certainly present, but it serves more to color the rhythm and provide emphasis than it does to directly communicate the rhythm.

Can the bass be used instead of drums?