Why is $ \frac{x}{\sqrt{x^{2}+1}}=x^{4}-x$ considered impossible to solve?

Question: This is from Stewart's Transcendentals.

If we were to try to find the exact intersection points, we
would have to solve the equation $$ \frac{x}{\sqrt{x^{2}+1}}=x^{4}-x$$
This looks like a very difficult equation to solve exactly (in
fact, it's impossible), so instead we use a graphing device to draw
the graphs of the two curves in Figure 7.

Why is this equation considered imposible to solve?
What is the factor that indicates you to not even try and just go directly with a graphing program.
Comment: If you square both sides, and cross multiply, you will get a polynomial equation of degree 10.  Polynomials of degree greater than 4 do not have closed form solutions.
Comment: Polynomials of degree higher then 4 may permit closed form solutions quite obviously like $x^{4}-16=0$
Comment: @marshalcraft $x^5-32=0$ would have been a better example, since that actually is of degree higher than $4$. There are actually closed-form solutions in radicals for all quartics.
Comment: closed form solutions? How do calculators solve those polynomials then?
Comment: @OlegPikhoff with numerical approximations
Comment: By closed form he probably means an finite equation or finite set of equations for the zeros using typical arithmetic and algebraic operations like addition, subtraction, multiplication, division, raise to power and nth root.
Comment: Polynomials of degree higher then 4 may permit closed form solutions quite obviously like $x^{n}-a=0$ $x=a^{1/n}$
Answer: Let me try to explain what this is saying. I am going to guess at some of the author's intentions, because what's written down is not quite precise.
First off, if you are doing problems at this level, what the author is really trying to communicate to you is: this problem looks too hard: it has a lot of terms (including a square root), with terms with pretty high degree, so from that you could guess that you probably don't have the mathematical tools to solve it algebraically, and thus will have to use a graphing calculator. This is not a precise, mathematical statement: any simple problem can me made to look hard just by adding a bunch of redundant terms that will cancel once you start simplifying it. But just based on how it looks, it's probably so complicated that you'll want to use a graphing calculator.
The author adds, as a side note/justification, that the problem is "impossible to solve".

Why is this equation considered imposible to solve?

That is a very hard question. The author is probably referring to the notion of "solvability in radicals": the ability to write down a root of a polynomial in terms of addition, subtraction, multiplication, division, and taking $n$-th roots. All polynomials of degree up to 4, that is, all equations of the form $ax^4 + bx^3 + cx^2 + dx + e = 0$, are solvable in radicals. There is a very famous theorem, the Abel-Ruffini theorem, which says that for polynomials of degree 5 and higher, there may not be solutions in radicals. For example, the equation $x^5 + x + 1 = 0$ has a solution, but you cannot write it down using just arithmetic and $n$-th roots.
For your problem, if you try to simplify it -- square both sides, then multiply by the denominator, then bring everything to one side -- you will see that you have a degree 10 polynomial. However, although some degree 10 polynomials do not have solutions in radicals, it is generally not at all easy to see which ones do and which ones do not. (In particular, 0 is a solution of your equation, and once you "eliminate" that one, you are left with a degree 6 polynomial -- almost down to degree 4!)
In fact it is true that you cannot write the solutions (other than 0) to that equation in radicals, but this is by no means easy to demonstrate or obvious. The author is just telling you, without expecting you to understand why at this stage.
Answer: Of course it is possible to solve this equation, but answer cannot be written in closed form.
$$\frac{x}{\sqrt{x^{2}+1}}=x^{4}-x,x\in\mathbb{R}$$
$$\frac{x}{\sqrt{x^2+1}}\left((x^3-1)\sqrt{x^2+1}-1\right)=0$$
$$x=0\lor (x^3-1)\sqrt{x^2+1}=1$$
Let find real root other than $x=0$.
$$(x^3-1)\sqrt{x^2+1}=1,x\in\mathbb{R}$$
$$(x^6-2x^3+1)(x^2+1)=1 \land x^3-1>0$$
$$x^8-2x^5+x^2+x^6-2x^3+1-1=0 \land x>1$$
$$x^2(x^6+x^4-2x^3-2x+1)=0 \land x>1$$
$$x^6+x^4-2x^3-2x+1=0 \land x>1$$
Real root of original equation other than $x=0$ is real root of $x^6+x^4-2x^3-2x+1=0$ which is greater than $1$. This root can be written in Wolfram Root notation (which is not part of commonly used closed form arrangement) as $Root(x^6+x^4-2x^3-2x+1,i)$, where $i$ is some integer number from $1$ to $6$. Numerical value of this root can be found using numerical methods or plotting.


Empty Array inside Controller's function called from Directive - AngularJS

Question: I'm having a pretty tricky problem that seems to be trivial but I'm not finding a good way to solve it.
Essentially, I'm building a todo list application using Angular and Angular-Material.
I have a main.html where, the important part is:
<md-content ng-show="mainCtrl.todos.length">
   <md-list class="todo_list" flex>
     <md-subheader class="md-no-sticky">{{mainCtrl.todoList.label}}</md-subheader>
       <acme-todo ng-show="mainCtrl.todos" ng-repeat="todo in mainCtrl.todos track by $index"
                  text="todo.content" index="$index"></acme-todo>
   </md-list>
</md-content>

Where acme-todo is a directive which contains a todo.html:
<md-list-item layout='row' layout-sm='column' layout-align='center center' layout-wrap>
    border_color

{{mainCtrl.text}}

        <md-button class='md-fab md-primary md-small box red-btn'
                   aria-label='delete' ng-click='mainCtrl.deleteTodo(mainCtrl.index)'>
            highlight_off
        </md-button>

</md-list-item>

Where todo.directive.js:
(function () {
    'use strict';

    angular
        .module('todoApp')
        .directive('acmeTodo', acmeTodo);

    function acmeTodo() {
        var directive = {
            restrict: 'EA',
            scope: {
                text :  '=',
                index : '='
            },
            templateUrl: 'todo.html',
            controller : 'MainController',
            controllerAs : 'mainCtrl',
            bindToController : true
        };

        return directive;
    }

})();

And finally, main.controller.js:
(function () {
    'use strict';

    angular
        .module('todoApp')
        .controller('MainController', MainController);

    function MainController() {

        var vm = this;
        vm.todos = [];

        . . .

        vm.addToDo = addToDo;
        vm.deleteTodo = deleteTodo;

        //vm.todo.content is the ng-model of the input-box
        function addToDo() {
            if( vm.todo && !_.isUndefined(vm.todo.content)){
                   pushNewToDo(vm.todo.content);
            }
        }

        function deleteTodo(index) {
            vm.todos.splice(index, 1);
        }

        function pushNewToDo(todo) {
            vm.todos.push({ content : todo });
            vm.todo.content = '';
        }

    }

})();

Everything works fine except when deleting a todo. When deleteTodo
  is called, the function correctly receives external $index from
  main's ng-repeat but, can't find out why, vm.todos is empty at
  that moment, so, nothing gets deleted.

If, instead, I manage to move all of todo.html content at acme-todo place's everything works fine.
I also tried setting $scope : true in the directive instead of passing both text and $index but I'm still encountering the same problem.
Here is a working Codepen which reproduces my issue. N.B. On the CodePen I'm using template instead of templateUrl and I changed the icons just to make things work properly there.
Here's a screen of the real application:

I know that, by default, if I do not specify any controller, the directive will still pick its scope, but
EDIT
Using a Service or a Factory also solves the problem like in this CodePen solves the problem, but I feel like adding way too much logic for such a small thing.
Why Am I getting an empty todos array even thought both controller and directive share the same scope? How can I fix that keeping the same approach (using a todo directive)?
Answer: You should separate app and directive controller because when you're initializing directive you're creating new controller, so new $scope and new todos array locally inside directive. After that you can pass delete function from the main controller to directive's $scope.
Take a look here: http://codepen.io/anon/pen/zZWyLV


(Minimal?) Polynomials using the Nullstellensatz

Question: I'm struggling with an exercise that was asked in class:

Let $\alpha = \sqrt[3]{3} + \sqrt{7}\sqrt[4]{2}.$ Show that there is a polynomial $p$ in
  the ideal $I=\left&lta^3 - 3, b^2 - 7, c^4-2, \tilde{\alpha}-(a+bc)\right> \subset \mathbb{Q}[a,b,c,\tilde{\alpha}]$ depending only on $\tilde{\alpha}$ with $p(\alpha) = 0$ (ie substituting the real number $\alpha$ for the variable $\tilde{\alpha}$ gives zero). If we can
  choose this polynomial to be irreducible, it is the minimal polynomial of $\alpha$. You may assume the Nullstellensatz.

The approach I tried was to say that over $\mathbb{C}$, $V(I)$ is the points $(\omega^d\sqrt[3]{3},\pm\sqrt{7},\pm i\sqrt[4]{2}, \omega^d\sqrt[3]{3}+ \pm\sqrt{7}\pm i\sqrt[4]{2})$, where $\omega$ is a cube root of 1.
Hence the polynomial $ P = \Pi (\tilde{\alpha} -  (\omega^d\sqrt[3]{3}+ \pm\sqrt{7}\pm i\sqrt[4]{2}))$ is in $I(V(I))$, so there is some $N > 0$ with $P^N \in I \subset \mathbb{C}[a,b,c,\tilde{\alpha}]$ (and obviously $\alpha$ is a root of this).
I was then trying to show that this must be in $\mathbb{Q}[a,b,c,\tilde{\alpha}]$; but I couldn't get there (also don't think this is true in general).
Can anyone offer any guidance?
I know this is really representative of a general method of finding the polynomials that vanish on the sums and products of algebraic numbers given their minimal polynomials. Eg if $\alpha, \beta$ solve $f, g$, this gives polynomials that vanishe on $\alpha + \beta$ or $\alpha\beta$... Any insight on why this works in the general case would be great too.
Thanks!
(N.b. I've adited this for accuracy: I was assuming before that this gives minimal polynomials, rather than just ones that vanish.)
Comment: The convention is, if you find that the problem as stated is not the problem you wanted to state, then edit, but do it transparently (e.g., write enough stuff so people won't wonder why there are comments that don't jibe with the question).
Comment: See Theorem 2.3 and Example 2.4 at http://www.math.uconn.edu/~kconrad/blurbs/linmultialg/tensorprod2.pdf for a method using tensor products that produces a monic polynomial over a given field having a sum or product of numbers as a root when you already know monic polynomials over that field with the individual terms as roots. There's no assurance that the result is going to be minimal, but "random" examples will likely have that feature (in the same sense that a random irreducible has Galois group $S_n$).
Comment: Is it really a method that is supposed to find a minimal polynomial or just *some* (nonzero) polynomial that has the sum and product of algebraic numbers as a root? It seems like the "choose to be irreducible" assumption is the only reason you're supposed to get a minimal polynomial out of this.
Comment: $I$ is certainly contained in ${\bf Q}[a,b,c,\tilde\alpha]$, so if you have proved $P^N$ is in $I$, then you have proved that $P^N$ is in ${\bf Q}[a,b,c,\tilde\alpha]$, no? Or have I misunderstood your "but I couldn't get there"?
Comment: @GerryMyerson, the later $I$ mentioned is indeed the $IV(I)=I\mathbb{C}[a,b,c,\tilde{\alpha}]$ in the OP's meaning.
Comment: @KCd You're right, it's not necessarily minimal... Whoops. I paraphrased (badly) the other two parts of the exercise: use this to give the minimal polynomial: then, given roots a,b of two quadratic polynomials, give a polynomial with roots ab, a+b. My bad. Is it convention to edit such mistakes or leave them to stand?
Comment: @GerryMyerson wxu is right, shoddy abuse of notation on my part. Fixed it now.
Answer: I should rewirte this answer.
Lemma
Let $\mathfrak{p}$ be a prime ideal of $\mathbb{Q}[x_1,\ldots,x_n]$. Let $F/\mathbb{Q}$ be a finite Galois extension. Let $Gal(F/\mathbb{Q})=\{\sigma_1,\ldots,\sigma_f\}$. Let $S=\{\mathfrak{p}_i\}$ be the set of prime ideals of $F[x_1,\ldots,x_n]$ which are lying over $\mathfrak{p}$. Then $G=Gal(F/\mathbb{Q})$ may act transitively on $S$. In particular, $S$ is finite.
Proof
First, $G$ acts on $S$. Suppose $\sigma\in G$. Then $\sigma(\mathfrak{p}_i)\cap \mathbb{Q}[x_1,\ldots,x_n]\supset \mathfrak{p}(=\sigma(\mathfrak{p}))$ and $\sigma^{-1}(\sigma(\mathfrak{p}_i)\cap \mathbb{Q}[x_1,\ldots,x_n])\subset \mathfrak{p}_i\cap \mathbb{Q}[x_1,\ldots,x_n]=\mathfrak{p}$, hence $G$ acts on $S$.
Second, $G$ acts transitively on $S$. Let $\mathfrak{p}_1,\mathfrak{p}_2\in S$ and $x\in \mathfrak{p}_1$. Then $\sigma_1(x)\sigma_2(x)\cdots \sigma_f(x)\in \mathfrak{p}\subset \mathfrak{p}_2$. Hence there exists some $\sigma$ such that $\sigma(x)\in \mathfrak{p}_2$, in other word, $x\in \sigma^{-1}(\mathfrak{p}_2)$. So $\mathfrak{p}_1\subset \bigcup_{i}\sigma_i(\mathfrak{p}_2)$. By prime avoidance theorem, $\mathfrak{p}_1=\sigma(\mathfrak{p}_2)$ for some $\sigma\in G$.
Now, come back to our problem:
Let $I\subset \mathbb{Q}[x_1,\ldots,x_n,y]:=\mathbb{Q}[X,Y]$ be an ideal such that $\mathbb{Q}[X,Y]/I$ is of dimension zero. Suppose $L$ is a field finite over $\mathbb{Q}$ such that the maximal ideals $\mathfrak{m}_i,i=1,2,\ldots,l$ containing $I$ are $L$-coefficients. Write $\mathfrak{m}_i=(X-A_i,Y-b_i)$, and $P(Y)=(Y-b_1)(Y-b_2)\cdots(Y-b_l)$. We ask if $P(Y)\in \mathbb{Q}[Y]$?
The answer is Yes.
Let $F$ be a finite Galois extension of $\mathbb{Q}$, which contains $L$. Then it is clear to see that $(X-A_i,Y-b_i)$ are already maximal in $F[X,Y]$. So all maximal ideals in $F[X,Y]$ containing $I$ are exactly $\mathfrak{m}_iF[X,Y]$. Thus we may assume $L$ is a finite Galois extension of $\mathbb{Q}$.
Let $\sqrt{I}=\bigcap \mathfrak{n}_{i}$ in $\mathbb{Q}[X,Y]$. Let $S_i$ be the set of maximal ideals which lying over $\mathfrak{n}_i$ in $L[X,Y]$. Denoted $S$ the set of the maximal ideals $\mathfrak{m}_i$. Then $S$ is a disjoint union of $S_i$. And $G$ may act on $S$ having orbits $S_i$, $P(Y)=\prod_i P_i(Y)$ each $P_i(Y)\in \mathbb{Q}[Y]$.
Example Let us consider a concrete example. Consider $(x^2-2,y)$ in $\mathbb{Q}[x,y]$ is maximal, and $(x-\sqrt{2},y),(x+\sqrt{2},y)$ in $\mathbb{Q}[\sqrt{2}][x,y]$. Now our $P(y)=y^2$ which is not irreducible. However, this example suggests that $P(y)$ is a power of an irreducible polyonomial.
This is true!
lemma
Let $\mathfrak{n}$ be a maximal ideal of $\mathbb{Q}[X,y]$ and $L$ a finite Galois extension of $\mathbb{Q}$ such that the fiber of $\mathfrak{n}$ in $L[X,y]$ are all $L$-points. We construct $P(Y)$ as in the way above. Let $S$ be the set of maximal ideals $\mathfrak{m}_i=(X-a_i,Y-b_i)$ in $L[X,Y]$ which lying over $\mathfrak{n}$. Let $\mathfrak{n}\cap \mathbb{Q}[y]=(f(y))$ where $f(y)$ is a monic polynomial thus a monic irreducible polynomial. Then $P(Y)$ is a power of $f(y)$.
Proof
Observing that $G$ acts transitively on $S$, thus the group $H_i=\{\sigma\mid \sigma(b_i)=b_i\}$ are all conjugate. It follows that $P(y)=f(y)^{|H_1|}$. In particular, if all $b_i$ are different, then $P(y)=f(y)$.
Practice In practice, let $\alpha_1,\ldots,\alpha_s$ be algebraic numbers and $\beta=g(\alpha_1,\ldots,\alpha_s)$ for $g\in \mathbb{Q}[x_1,\ldots,x_s]$. We let $I=(f_1(x_1),\ldots,f_s(x_s),y-g(x_1,\ldots,x_s))$ where $f_i$ are minimal polynomials of $\alpha_i$ over $\mathbb{Q}$. If certain good conditions holds, for example, the extension $\mathbb{Q}[\alpha_1,\ldots,\alpha_i]/\mathbb{Q}[\alpha_1,\ldots,\alpha_{i-1}]$ has degree $deg(\alpha_i)$ for $i=1,\ldots,s$, then our $I$ is maximal. More, if we require $g(x_1,\ldots,x_s)$ are all distinct for substituting the roots of $f_i$. Then our $P(y)$ is irreducible polynomial of $\beta$ over $\mathbb{Q}$.

No Galois theory, no Nullstellensatz, but use ``The fundamental theorem of symmetric polynomials''.
Let $\alpha_1,\alpha_2,\ldots, \alpha_s$ be algebraic numbers. Let $\beta=g(\alpha_1,\ldots,\alpha_s)$ for some $g\in \mathbb{Q}[x]$. Let $f_i$ be the minimal polynomial of $\alpha_i$. Let $P(y)=\prod (y-g(\theta_1,\ldots,\theta_s))$ where $\theta_i$ runs through the roots of $f_i$. Then $P(y)$ is a polynomial of $\mathbb{Q}[y]$.
Proof
Let $\gamma_{i}$ be the roots of $f_1$. Then $\prod_i(y-g(\gamma_i,x_2,\ldots,x_s))$ is a symmetric polynoimal of $\gamma_i$ in $\mathbb{Q}[x_2,\ldots,x_s,y][\gamma_1,\ldots,\gamma_t]$ (View $\gamma_i$ being indeterminate). Since the element symmetric polynomials of $\gamma_1,\ldots,\gamma_t$ have vaule in $\mathbb{Q}$. Hence  $\prod_i(y-g(\gamma_i,x_2,\ldots,x_s))$ is a polyonomial in  $\mathbb{Q}[x_2,\ldots,x_s,y]$. Finally $P(y)\in \mathbb{Q}[y]$.
Comment: That's great. Thanks very much!
Answer: *Update: there is something wrong in the proof as pointed out. We should use Galois extension. And take Galois actions to $P(y)$. *
Let $\mathfrak{n}$ be a maximal ideal of $\mathbb{Q}[x_1,x_2,\ldots,x_n,y]:=K$.  We may find a finite field extension $L/\mathbb{Q}$, such that $V(\mathfrak{n})=\cup\{(x_1-a_1,\ldots,x_n-a_n,y-b)\}=\{\mathfrak{m}_1,\ldots,\mathfrak{m}_k\}$(i.e. the closed points containing $I$ are $\mathbb{Q}[\alpha_1,\ldots,\alpha_m]$-points) in $\operatorname{Spec}L[x_1,\ldots,x_n,y]$
Now we get a polynomial $P$ by multiplying all $(y-b)$, and we ask that if $P(y)\in\mathbb{Q}[y]$?
This answer is yes!
update: Now we may assume $L/\mathbb{Q}$ is Galois, suppose $Gal(L/\mathbb{Q})=\{\sigma_1,\ldots,\sigma_l\}$, then for $\sigma_j$ act on $\mathfrak{m}_i$ will be a maximal ideal containing $\sigma_j(\mathfrak{n})=\mathfrak{n}$, that is to say $Gal(L/\mathbb{Q})$ act on the set $\{\mathfrak{m}_1,\ldots,\mathfrak{m}_k\}$(the fiber of $\mathfrak{n}$), so we will obtain $P(y)\in \mathbb{Q}[y]$, but we have not said that $P(y)$ is irreducible.
The map $\mathbb{Q}[y]\to\mathbb{Q}[x_1,\ldots,x_n,y]\to L[x_1,\ldots,x_n,y]$ sends closed points to closed points. And $\mathfrak{m}_1\cdots\mathfrak{m}_k\cap \mathbb{Q}[y]=(f(y))=\mathfrak{n}\cap \mathbb{Q}[y]$. Hence $f(y)=P(y)G(y)$ for some $G(y)\in L[y]$(Here we just let $x_i=a_i$ to get this equation). But all the closed points in $f(y)$ are appeared, we obtain that $G$ is a constant. Now $P(y)$ is monic, we can see $P(y)\in \mathbb{Q}[y]$.
Notice: here we use the separablity of $L/\mathbb{Q}$!.

For general, we only suppose $I$ is an ideal of $\mathbb{Q}[x_1,x_2,\ldots,x_n,y]$ such that $\mathbb{Q}[x_1,x_2,\ldots,x_n,y]/I$ is of dimension zero. We find a finite field extension $L/\mathbb{Q}$ such that the closed points over $I$ in $L[x_1,\ldots,x_n,y]$ are $L$-points. Then $\mathfrak{m}_1\cdots\mathfrak{m}_k\cap\mathbb{Q}[y]=(f(y))$, now $f(y)$ is a monic nonzero square-free polynomial. So our $P(y)$ equals $f(y)$.

In the OP's case, the ideal $I$ is maximal so the polynomial $P(y)$ is indeed an irreducible polynomial over $\mathbb{Q}$.
Comment: I'm afraid you lose me slightly in the third paragraph: why does $f(y) = P(y)G(y)$?

Thanks again!
Comment: I donot know how to edit a wrong answer, maybe I should delete the origin words?
Comment: I can just about follow this, but there was no Galois theory to be seen in this course, and 'fiber' is a rather alien word to me.

I can't help but wonder if there's a slightly more basic proof to be found...? :/
Comment: @TomH, Ok, let me think a think.


Modulation from D major to D minor, should I go sudden or gradual?

Question: I am composing a Scherzo in the key of D major and I have the first section of my Scherzo already written down. Now I'm into the second section of the Scherzo that precedes the Trio. And in this second section, I am wanting to modulate to D minor and end at least the repeat with a half cadence. I'm now thinking that this repeat would be a great place to have a first and second ending, where the first ending leads back to the modulation via a half cadence(I mean after all, the dominant is a chord that often leads to a modulatory passage) and the second ending concludes in D minor, the key of the Trio section of my Scherzo in D.
Now, I can think of a few ways to modulate from D major to D minor, some gradual, and others sudden.
Circle of Fifths Modulation
This is perhaps the most gradual of the modulations. However, I usually see this used when the motion is to a key that isn't parallel to the original key(so for example, a motion from C minor to Eb major might be acheived through the Circle of Fifths harmonic sequence). Here is a motive that shows up frequently in my Scherzo melody:

And here is what happens if I take that melodic motive and use the Circle of Fifths Modulation:

As you can see, I did it by using a literal subdominant chain. While this isn't usually what people are talking about when they say that the Circle of Fifths is used to modulate, this is a possible interpretation of that statement.
Pivot Chord Modulation
This is by far the most common form of modulation in Classical Music. But, I basically have to either stick to the dominant as my pivot or use some secondary chord as my pivot if I go this route(okay, so there is the diminished seventh possibility but I will mention this separately). If I use secondary chords, then C major becomes a possible pivot chord. However, for parallel modulations, I see this less frequently than for other keys, even those more distantly related. It isn't as gradual as the Circle of Fifths modulation I mentioned earlier, but it isn't as sudden as the other modulations I will mention.
Diminished Seventh as Pivot
So, even though this technically falls under Pivot Chord Modulation, I am mentioning it separately because a common usage of the diminished seventh is as the one and only pivot chord in a modulation from a major key to a minor key. This does multiple things that using a chord like C major just wouldn't do. Here are the things that make a Diminished Seventh Pivot more sudden of a modulation:

The obvious, it brings that crunch of the overlapping tritones into what has otherwise been a consonant piece
Diminished sevenths are very commonly used as a dominant substitute in minor keys, and so a diminished seventh without a preceding dominant brings in that minor key tendency already
The diminished seventh is a bit ambiguous, and thus, even with the spelling, it isn't obvious at first where it wants to resolve, just that it wants to resolve somewhere.

All of these make the Diminished Seventh Pivot a more sudden modulation.
And then of course, there is the sudden switch with no sort of pivot whatsoever. But, that isn't what I am aiming for. I want it to sound like I am truly modulating to D minor.
Since I am aiming for a more humorous character to my Scherzo as well as a smooth transition from the half cadence back to the modulation upon the repeat of the second section of the Scherzo, does this mean that I should go the Circle of Fifths route for my modulation or what? Would my aim for it being in the Classical Style change anything as to what route I should go for my modulation?
Comment: I'd actually suddenly switch from D major to D minor with no pivots--such a switch to the tonic minor is a common enough tactic in scherzos (e.g. the minuet-scherzo-dance hybrid 3rd movement of Beethoven's Piano Sonata No. 4 in E Flat Major, the end of the trio of Chopin's Scherzo No. 1 in B Minor, the E major-to-E minor shift in Chopin's Scherzo No. 3 in C Sharp Minor).
Comment: "Should I..." is asking us to decide an artistic choice for you.  I'd reference Max Reger Modulation for some ideas.  But really there is no limit.
Comment: Of course you could jump from any chord to any other chord - the piece would still be classical or (neo-classical) because of the motifs and their treatment....
Comment: It (almost) never sounds sudden when you are changing key to the tonic minor.
Answer: Lots of Latin music uses the parallel mode change here.  It's fairly striking (at least in a short dance tune.) The point is that D major and D minor share the same dominant. You might vary the approach to the change, perhaps something like ii06-i64-V7-I going one way and ii-bII6(N6)-i going back (or any other variation on a cadence). I'd suggest abrupt as the tonic doesn't change. You may still need another section in a contrasting key as swapping modes may not generate enough variety over a long piece.
Answer: Of course you could jump from any chord to any other chord - the piece would still be classical or (neo-classical) because of the motifs and their treatment.
But I would prefer among your propositions the circle of fifths. It sounds quite funny and would make it scherzo-like (not referring to the classical scherzo term ... but somehow witty!)
another idea would be D-G-C-F-B♭-E♭/G (N6!)-A7-Dm or the shortcut I-iv-V7-i with the Neapolitan sixth chord I-n6-V7-i
http://legacy.earlham.edu/~tobeyfo/musictheory/Book2/FFH2_CH6/6B_Neapolitan6th.html


Why is the referee treated so different in soccer and rugby

Question: Recently, in Dutch amateur football, a linesmen died after being attacked by players. This terrible news was directly the reason for the Dutch football association, KNVB, to apply some rules with respect to protesting a lot stricter after the winter break in the professional leagues.
I've been annoyed a lot when watching soccer on television (Champions League for example), when I see a bunch of soccer players protesting against the referee in a quite agressive manner. When watching rugby matches, it doesn't happen as far as I've seen. What is the reason that is does happen in (professional) football, but not in rugby?
Comment: This is a great question.  As a US college rugby player I had mostly great refs.  But learned early on you never say a word to the ref.  I also had some mildly drunk refs that were terrible and nobody said a word to him either.  Not only did players not backtalk the refs but the players on the sideline even kept the fans from complaining.
Answer: I think it has to do with the traditions. I believe originally rugby was played by the higher class, with a certain upbringing. I have a colleague who works as a part time rugby ref and he's puzzled as to why the ref doesn't send off half of the players in a football game. I, on the other hand, am often puzzled as to how the refs command so much respect in rugby.
Another point of view could be that football's expansion to take over the world is based on the fact that one really doesn't need much to play football. Compared to some other sports (e.g. ice-hockey), it's cheaper and easier to play football, all you need is a ball (or something that you can use as a ball) and a good imagination (to define the field and goals). "What does that have to do with anything?", you might ask.. Well, if anyone and everyone can play football, however they like, you might argue that people take their local manners and traditions and incorporate it into the game. I play football on amateur level, and the "quality" of the game especially with regards to manners and temperament has been very closely related to which nationalities were present on the field.
Finally, and perhaps most importantly, football has become such a huge money-maker so that football associations do not dare/want to impose serious penalties for inappropriate behavior. I mean there isn't a single person in the football world that could imagine giving a 10 match ban to Lionel Messi or Cristiano Ronaldo, for diving. Or a seasonal ban to whatever player for shouting at the ref's face. I believe the situation has gotten this bad because bad behavior has been tolerated for just way too long.
Comment: I would add that in rugby, the ref can and is allowed to tell the player who are about to commit a foul (of any kind) to leave the place, release the ball, roll out, etc. Making the decisions he take more clears, and allowing him to show yellow cards for team fouls is also a good point to make it more clear. Football left to much for interpretation.
Answer: I agree with the accepted answer but there is something else pertinent to point out. In Rugby, the ref has a very simple and commonly used option when a player backchats or abuses him for giving a penalty, which is to march the position of the penalty 10 metres closer to the defenders tryline. This provides a meaningful bonus in territory, or assistance in making a penalty goal kick easier, but isn't a huge additional advantage meaning it can be used lightly without the ref worrying about appearing to over-react and unbalance the game with a big call.
I have seen this occur 2 or even 3 times in succession if a player continues to abuse the ref, however usually it is a very effective way of silencing a player quickly and maintaining respect from the players.
There is no equivalent in Football and it wouldn't work anyway since territory is not nearly so important as it is in Rugby (or at least 10 metres either way makes little difference).
In Football a yellow card is too big a penalty to apply for backchat, but that leaves the referee with no options at all for dealing with it. Hockey (field hockey) has a green card that is used amongst other things for backchat, with multiple green cards leading to a yellow. This might be one way to give the referee some protection from abuse in Football.
Comment: I disagree that advancing the free kick would not work in football. It only takes a couple of free kicks being advanced to the edge of your penalty area before you quickly learnt to cut out the dissent / delaying ther restart / failure to respect the required distance.
Comment: In a Super XV game last weekend a penalty was changed from a short arm to a long arm due to back chatting. It's a great rule that should be implemented in other codes
Comment: This was experimented with (and abandoned). http://www.theguardian.com/sport/2015/sep/25/joy-of-six-short-lived-football-rule-changes
Comment: It was abandoned because it was poorly implemented. The advancement was not optional, there was no ability to advance free kicks on the edge of the area, and a caution was mandatory, making the punishment too harsh. The experiment was destined to fail.
Comment: +1: good point I have not thought about that :)
Comment: @Mormegil - a pity, judging by the article it was working and just needed a few tweaks...
Answer: I'd say something rarely mentioned about the sports themselves : scoring is low in football, but high in rugby and basket and many others sports.
Thus, a small mistake can rarely change the complete outcome of a game in rugby or in basket : to make a team win, the referee generally has to be partial during the whole game ; but in football, a very tiny error and the winner can change.
And this, I think, explains a lot.
Comment: Because they are way to busy punching the opponents to punch the referees. Plus when this occurs, in most of the case there is no assistant referee, and there is a feeling of injustice from the player. I could add that the conversion rate for penalty kicks in football is way higher than in hockey... (Roughly 80% vs. 40%) which could explain the nervosity when the referee has to make a decision.
Comment: Good point; however it doesn't explain how refs don't get abused as much in hockey which is more or less on par in number of goals as in football.
Comment: We can even take in consideration the face that in football, the interpretation is more important than the rule and the players will always tend to interpret fouls differently and so will the referees... And a tiny interpretation change can let to a different score even without refereeing error : there is almost never one only good decision in football.
Answer: In rugby, the ref always comes over to meet the captains of each team before the game so he can identify them on the field.  When I first started playing all the older members on my team gave me crazy looks before our first game and ordered all the rookies to never, ever, EVER speak to the ref.  If you need to tell him something your captain should relay the message.  This year a player got sin-binned (like hockey's penalty box, usually only used for dangerous repeated fouls) for cussing on the field.  Additionally, all of our refs are unpaid volunteers at the high school and college level (at least in Texas), so everyone is just grateful that we have a ref at all.
Answer: Having refereed both sports, I'd like to offer another possible  answer. The laws of rugby support the referee as being the sole 'judge of law and fact'. This places the referee in an esteemed role which is backed up (at least most of the time) by the administrators of the game. Football (soccer) does not have such an explicit status and protection for referees (or, at least, does not enforce it). If football administrators drew a line in the sand of referee abuse, it would all change. Until then, players will continue to have a free regin. This does show that football is more ambivalent about the role of referrees than in rugby.


Port scanning from VM users

Question: After receiving an Abuse Notice from my server provider, i was wondering how they make to check up all my traffic and send me these abuses. I would possible like to know if there is some kind of software that i can download so that i can stop my clients from doing malicious activities.. or atleast notice me before my provider treathens me.
I have seen some things like Snort, NodeWatch and VPSmon, but none of them 'Control' VPS machines from port scanning.
Any help out here would be far more than appreciated
Edit : I am not trying to stop people from the outside to port scan, but people from the inside to port-scan the internet, AKA my clients from doing malicious activites :)
Comment: Did your provider tell you specifically that the malicious activity was an outbound port scan?
Comment: I had a huge list, all going from one of my IP to another random server. Totalling 21K scans..
Answer: Outbound ACL's
At our firewall configure outbound ACL's so your users can can only consume the services on the Internet that you allow.
I imagine that an outbound port http and https rule with an any>any would be fine.  DNS would be consumed internally (assumption on my part) and that would probably solve your problem.
Comment: My clients type are VPS, meaning they can basically do anything themselves. You think that i could apply firewall limitation on a VPS service ? Im using Linux SolusVM on openVZ containers
Answer: Since you are a VPS provider and I assume your customers get root on their VPS, there is very little you can do on the network stack, since filtering won't block or detect everything and very likely you'll get a lot of false poitives. You could configure iptables to filter certain repeting tcp flags in short time span intervals, log them and use something to send you notifications
Only other solution I can think of is scanning your customers filesystem with a rootkit scanner such as https://rootkit.nl/projects/rootkit_hunter.html or similar looking for know tools. But you might face privacy concerns from you customers.
Comment: If i configure IPTables on the main machine, will it actually block the traffic going to the other VPS machines ?
Comment: No, as I said you can setup iptables to filter and log only specific tcp flags.Look here for an [example](https://rmohan.com/?p=957) Of course you'll need to spend some time fine tunning the ruleset and dealing with some complains.
Answer: Using something called PSAD, it is now blocking port scans.
pSAD check the logs and you can set danger levels such example : 15 scans = level1, 50 scans = level2 etc.. and get notified on a certain level of danger.
If you have any problems of port scannings, I highly recommend looking at the pSAD
http://cipherdyne.org/psad/
It does the intrusion detection automatically, and you dont need to go change things in the IP tables as it takes care of this itself.
Thanks to @ecelis for his comment as it brough me towards this discovery.

Port scanning from VM users


How to filter on multiple attributes in XMLStarlet?

Question: For example, given:
<fruit>
   <banana source='Ecuador' category='I'>
      <quantity>1</quantity>
   </banana>
   <banana source='Costa Rica' category='I'>
      <quantity>1</quantity>
   </banana>
</fruit>

Say I want to change
<banana source='Costa Rica' category='I'>

to
<banana source='Costa Rica' category='II'>

or its quantity to 2, how would I reference it if I want to filter on both the source and the initial category value?

I'm trying to do the following:
xmlstarlet ed -u "/fruit/banana[@source='Ecuador' @category='I']/quantity" -v 2

...but this results in a syntax error, as follows:
Invalid predicate: /fruit/banana[@source='Ecuador' @category='I']/quantity
Invalid expression: /fruit/banana[@source='Ecuador' @category='I']/quantity

Comment: Should probably be tagged `xpath`.
Comment: Have you read the [documentation](http://xmlstar.sourceforge.net/doc/xmlstarlet.pdf)?  Have you tried any of the command options? Can you show what you've tried and explain what didn't work?
Comment: Yes, I read the documentation, found references and examples with only one attribute.

I was trying to do something like: xmlstarlet ed -u "/fruit/banana[@source='Ecuador' @category='I']/quantity" -v 2 example.xml

But it gives me:

Invalid predicate: /fruit/banana[@source='Ecuador' @category='I']/quantity
Invalid expression: /fruit/banana[@source='Ecuador' @category='I']/quantity
Comment: @MichaelVehrs You're right.
Answer: After quite a bit of trial and error, reached a solution:
I need to close and re-open [] with the next attribute. For example:
xmlstarlet ed -u "/fruit/banana[@source='Ecuador'][@category='I']/quantity" -v 2 example.xml

And would correctly output:
<?xml version="1.0"?>
<fruit>
  <banana source="Ecuador" category="I">
    <quantity>2</quantity>
  </banana>
  <banana source="Costa Rica" category="I">
    <quantity>1</quantity>
  </banana>
</fruit>

Edit: also works:
xmlstarlet ed -u "/fruit/banana[@source='Ecuador' and @category='I']/quantity" -v 2 example.xml

Comment: ...and you just found the other approach I was preparing to add as a separate answer. :)
Comment: That's one approach, yes.


Remove query strings from static resources in template.php

Question: I've read several articles throughout the web about removing query strings from static resources, in the template.php file, after I saw a recommendation to do so in a forum, for better page-loading time in Drupal.
All of the articles I've seen lacked some didcatance in the following points:

Why should one remove Query strings for better loading times? I've never seen them in any URL of any my site's pages, and, I don't understand why would their appearance in a URL effect in any shape or form the loading time of a site's page (that deals more to image-optimization, bandwidth, etc).
What is a static resource in Drupal? Cache is something dynamic so I'm guessing it's not the cache itself. So what is it?
Where should I put the following code of this JavaScript function, at the start of the file, at the end, or between any special segments? It wasn't clear from none of the articles.
/**
 * Implements template_process_html().
 */
function MYTHEME_process_html(&$variables) {
  $variables['styles'] = preg_replace('/\.css\?.*"/','.css"', $variables['styles']);
}

Answer: The only reason you'd want do this is to remove any cache busting query parameter. These are query parameters that are appended to a URL (e.g. www.example.com/js/some_file.js?b= 1433781670 & www.example.com/css/some_file.css?b= 1433781671 ) to prevent browser caching.

As the tutorial probably explained, you'd only want to do this for static resources (i.e. any web resource like a CSS/JS/Image file that will never change) so that the browser will cache the static resource.
As for the template question you can place the MYTHEME_processs_html() function anywhere in template.php (if you don't have one, create it). On top of that, the only thing you'd need is to replace MYTHEME with the short name of your theme and flush your theme cache.
If you're new to Drupal I'd recommend avoiding this for now; unless you're sure there's only static CSS stylesheets that can safely have its cache-busting query string removed, you can end up with a scenario where modules/themes aren't displaying correctly because the cache busting query parameter was needed.
Comment: Yes, if your browser decides to retrieve from cache, it could miss a change that happened server side. The whole point of cache busting query parameter is to *ensure this never happens*. That's why I suggested avoiding this; you should let the module/theme developers decide what/when to break caching.
Comment: A best answer one could get - Just one little question to make sure I understand right... What is "css\js\image file that will never change" I tend to change my CSS much... Do you mean that in browsing it won't be changed?
Comment: The page can change the link URLs when the resources linked to change.  So far so good.  The problem is that those URLs are being constructed using the query parameter.  It would be better to put it in the path, and have it stripped out again using a RewriteRule in .htaccess, or something equivalent (e.g. for nginx).
Comment: The biggest problem with the "cache busting" query string is that it makes it hard to use certain developer tools.  This is not a minor problem.  It's a problem where I think some of the Core dev people are simply not listening when developers cry out in frustration.  This really should be an admin setting.
Comment: Works like charm for Drupal 7 but when I use the code for Drupal 8 via mytheme.theme and flush cache, the site crashes. I can't find documentation on this anywhere. I would thank you dearly to update the comment. I have yet to learn enough on URLs and Regex to solve it myself will gladly give the bounty for an update.
Answer: The query parameters on the CSS and JS resources in Drupal are used to clear browser cache when the file changes on the server-side. But in normal circumstances, the query parameters will remain the same for all requests, thereby allowing the browser to cache the resources.
Removing these parameters might create problems if you ever decide to edit the CSS file in the future and someone already has the file cached on their browser. Such a user will continue to see the old CSS file (which you changed) until the cache lifetime expires.
What you can set caching rules for static resources in your .htaccess, which, in my opinion would be a better thing to do (cause there is a reason why Drupal devs did additional work to add those query parameters in the first place).
# Set expiry for static files
<FilesMatch "\.(?i:gif|jpe?g|png|ico|css|js|swf|ttf|otf|woff|svg)$">

  <IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 1 seconds"
    ExpiresByType text/html "access plus 1 seconds"
    ExpiresByType image/x-icon "access plus 6 hours"
    ExpiresByType image/gif "access plus 6 hours"
    ExpiresByType image/jpeg "access plus 6 hours"
    ExpiresByType image/png "access plus 6 hours"
    ExpiresByType text/css "access plus 6 hours"
    ExpiresByType text/javascript "access plus 6 hours"
    ExpiresByType application/x-javascript "access plus 6 hours"

    ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
    ExpiresByType application/x-font-ttf "access plus 1 month"
    ExpiresByType application/x-font-opentype "access plus 1 month"
    ExpiresByType application/x-font-woff "access plus 1 month"
    ExpiresByType image/svg+xml "access plus 1 month"
  </IfModule>

  <IfModule mod_headers.c>
    Header set Cache-Control "public, max-age=21600"
  </IfModule>

</FilesMatch>

Of course, you can remove the lines you do not need or add new ones as per your requirements. Hope it helps!
Comment: I already use mod expires (tested and it's working), but I still get a GTmetrix comments about disabling cache busting query strings...
Answer: I solved it with this code:

use Drupal\Core\Asset\AttachedAssetsInterface;

/**
* Implements hook_css_alter().
*/

function YOURTHEMENAME_css_alter(&$css, AttachedAssetsInterface $assets){

     foreach ($css as &$file) {
    if ($file['type'] != 'external') {
      $file['type'] = 'external';
      $file['data'] = '/' . $file['data'];
    }
  }

 }

/**
* Implements hook_js_alter().
*/

function YOURTHEMENAME_js_alter(&$javascript, AttachedAssetsInterface $assets){

     foreach ($javascript as &$file) {
    if ($file['type'] != 'external') {
      $file['type'] = 'external';
      $file['data'] = '/' . $file['data'];
    }
  }

 }

Put the code into YOURTHEMENAME.theme file.
It works perfect on Drupal 8.


How would I plot this function for all values of X,Y?

Question: I have this function which I wish to plot:
$y=b(a-x)^{8/25}$
I have the values for $x,y$ as part of a data set, with thousands of values. This is in a file.  What i have found is that $x$ is between 0 and 5 and $y$ is between 0 and 1.
I tried rearranging the equation to solve for $a$ and $b$, but I am still not sure what to do with that information

My main problems are that I dont know how to plot $a,b$ in a single graph that represents all values in the $x,y$ range. A secondary problem might be that I don't know how to write the equation properly, given what I am trying to do.
And a tertiary concern is that I am also unsure how to get this into a graphing program. Insights are welcome.
Comment: Your question is very unclear. Will your graph plot $x$ against $y$ or $a$ against $b$? If you are graphing $x$ vs. $y$, and you have values of $x$ and $y$, why don't you just graph them and ignore $a$ and $b$? Or are you trying to find $a$ and $b$? Are your values of $x$ and $y$ exact for a given $a$ and $b$? And so on. Please clarify: this is a hopeless mess now.
Comment: I have X,Y and Im trying to find A,B.
Comment: OK, what about all my other questions? Note that my question "Are your values of $x$ and $y$ exact for a given $a$ and $b$?" refers to the best-fit idea given by @RobertIsrael. Is that what is going on?
Answer: I suspect that what you're really trying to do is find $a$ and $b$ that best fit  the equation $y = b (a-x)^{8/25}$, and further that "best fit" is in the least squares sense, i.e. you want to minimize
$$ \sum_i (y_i - b(a-x_i)^{8/25})^2$$
where $(x_i, y_i)$ are your data points.  This is a non-linear least squares problem, so it is not easy, but methods are available on various software systems (Matlab, Maple, Sage, etc.).
Comment: Gauss-Newton, Levenberg-Marquardt, Sequential Quadratic Programming.
Comment: Do those methods have names?


O que seria parâmetros dinâmicos javascript?

Question: O que seria parametros dinamicos no javascript?
Comment: vale a pena ler, não é exatamente  o que você perguntou "mas e como se fosse" http://pt.stackoverflow.com/questions/93144/como-o-jquery-faz-os-par%C3%A2metros-serem-dinamicos
Comment: Explique um pouco melhor a que você se refere por parametros dinâmicos.
Comment: [Como criar uma função em Javascript que aceita um número arbitrário de argumentos?](http://pt.stackoverflow.com/q/4293/91) seria isso?
Comment: Guilherme, sua pergunta está com 4 votos para ser colocada em suspenso (pode ser reaberta), mas ao mesmo tempo tem 3 votos positivos e uma resposta bem legal; provavelmente ficará aberta e será popular. Mas para benefício de outros que tenham a mesma dúvida que você e encontrem a solução aqui, será que pode descrever melhor o porquê da sua pergunta? É que quando o título e descrição são exatamente iguais fica bem estranho...
Answer: Parâmetros dinâmicos ocorrem quando sua função aceita um número variável de argumentos, tipo:
minhaFuncao(x)
minhaFuncao(x, y, z)

A quantidade de argumentos pode ser finita, tipo 1 ou 2 ou 3 argumentos aceitos, mas podem também ser indeterminada, em aberto. Veja dois exemplos:
function recado(mensagem, nome){
    if(typeof nome == 'undefined'){
        nome = 'Amigo';
    }
    alert('Recado para ' + nome + ': ' + mensagem);
}
recado('Tenha um bom dia.'); //resultado: 'Recado para Amigo: Tenha um bom dia.'
recado('OK', 'Guilherme'); //resultado: 'Recado para Guilherme: OK'

function soma(inicio){
    var resposta = inicio;
    if(arguments.length > 1) {
        for(var i=1; i<arguments.length; i++){
            resposta += arguments[i];
        }
    }
    return resposta;
}
soma(3); // retorna 3
soma(100, 10, 2, 3); // retorna 115

Comment: Exatamente isso, Obrigado pelo seu tempo!


Convert IImage to Structure

Question: Is there a way to convert EmguCV IImage to EmguCV structure?
Image<Bgr, Byte> Frame;           // current frame from camera
Image<Bgr, Byte> Previous_Frame;  // previous frame aquired
Image<Bgr, Byte> Difference;      // difference between the two frames

double ContourThresh = 0.003; //stores alpha for thread access
int Threshold = 60; //stores threshold for thread access

private void ProcessFrame(object sender, EventArgs arg)
{
    if (Frame == null)
    {
        Frame = imageBox1.Image; //error
        Previous_Frame = imageBox2.Image; //error
    }
    else
    {
        Frame = imageBox1.Image;//error
        Previous_Frame = imageBox2.Image;//error

        Difference = Previous_Frame.AbsDiff(Frame);
        Difference = Difference.ThresholdBinary(new Bgr(Threshold, Threshold, Threshold), new Bgr(255, 255, 255)); //if value > 60 set to 255, 0 otherwise

        Previous_Frame = imageBox2.Image;
    }
}

I'm getting:

Error 14  Cannot implicitly convert type Emgu.CV.IImage to Emgu.CV.Image<Emgu.CV.Structure.Bgr,byte>. An explicit conversion exists (are you missing a cast?) d:\ece design project\aslt software\aslt software\seatplan.cs   917 25  ASLT Software

I am trying to get the difference between two image boxes, imageBox1 and imageBox2.

imageBox1 is a processed image from the image captured by the camera while * imageBox2 is an image from imageBox1 which are saved to the ms access database..

What I'm trying to do is to find an image in the database that matches to the imagebox1.. is what im doing here correct or you guys have a better option than using absdiff?
Comment: i added the compiler error through the snapshot sir, sorry if i've done it wrong...
Comment: done sir., thanks, and sorry for the mistake. :)
Comment: thanks for the edits.,
hope someone can help
Comment: Please do not post image of text.  Post text as text (which I see you have done separately - so you can remove the snapshop).
Comment: @Sabuncu.., done sir. thanks..
Answer: after surfing some article i found out myself the answer for my own question.
this is what i did..
            Frame = new Image<Bgr, Byte>(imageBox1.Image.Bitmap);
            Previous_Frame = new Image<Bgr, Byte>(imageBox2.Image.Bitmap);

Comment: where i can find opencv dll's that are working with your code?

Convert IImage to Structure


integral of $e^{x}f(x)$

Question: Can someone explain me in detail how this result has been found using integration by parts
$$\int_{-1}^{1} e^{ikr\mu}f(\mu) d\mu = \frac{e^{ikr}f(1) - e^{-ikr}f(-1)}{ikr} + O(\frac{1}{k^2r^2})$$ where $\mu = cos(\theta)$, provided $\frac{df}{d\mu}$ is bounded.
Answer: $$\int_{-1}^1 f(\mu) v'(\mu) \, d\mu = [f(\mu) v(\mu)]_{\mu=-1}^1 - \int_{-1}^1 f'(\mu) v(\mu) \, d\mu$$
where $v(\mu) = \frac{e^{ikr\mu}}{ikr}$.
Comment: ooouuu. Sorry for being so dumb and thanks for your reply.:P

integral of $e^{x}f(x)$


Break python regular expression with escape into multiple lines

Question: I have a python beginner's question.  How would one break this line into multiple lines?
SET_CMD = re.compile (r'boot +set-cmd +-s +command\=(?P<pw>.*?)$')

I don't want to do this because pep8 complains.
SET_CMD = re.compile\
    (r'boot +set-cmd +-s +command\=(?P<pw>.*?)$')

Thanks,
Mat
Answer: Do something like this:
SET_CMD = re.compile (r'boot +set-cmd +-s'
                      r' +command\=(?P<pw>.*?)$')

There are two key facts here:

being inside of parentheses provides implicit line continuation
consecutive strings are automatically concatenated
Answer: Instead of breaking before the parantheses, you could use the regex verbosity flag to split the expression in multiple lines. Additionally you can include comments, which might come handy for complicated expressions.
For your example:
SET_CMD = re.compile(r'''boot\s        # Comment
                         +set-cmd\s    # ...
                         +-s\s
                         +command
                         \=(?P<pw>.*?)$')''', re.VERBOSE)

Note that I inserted some \s to match whitespaces, since re.VERBOSE ignores the whitespaces and linebreaks in the expression.


Syntax error on a doctrine query (Symfony2)

Question: Im getting a syntax error on this query:
protected function _getimsg($id)
{
    $imsgRepository = $this->getDoctrine( )->getRepository( 'DonePunctisBundle:Imsg' );
    $imsg = $imsgRepository->findOneBy(array('to' => $id, 'read' => 0 ));
    if($imsg) {
        $em = $this->getDoctrine()->getEntityManager();
        $imsg->setRead('1');

        $em->persist( $imsg );
        $em->flush( );

        return $imsg->getContent();
    } else {
        return '';
    }

}

imsg Entity
<?php

namespace Done\PunctisBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Imsg
 *
 * @ORM\Table(name="imsg")
 * @ORM\Entity
 */
class Imsg
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="to", type="string", length=25)
 */
private $to;

/**
 * @var string
 *
 * @ORM\Column(name="content", type="string", length=255)
 */
private $content;

/**
 * @var integer
 *
 * @ORM\Column(name="read", type="integer", length=1)
 */
private $read;

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set To
 *
 * @param string $to
 * @return Page
 */
public function setTo($to)
{
    $this->to = $to;

    return $this;
}

/**
 * Get to
 *
 * @return string
 */
public function getTo()
{
    return $this->to;
}

/**
 * Set content
 *
 * @param string $content
 * @return Page
 */
public function setContent($content)
{
    $this->content = $content;

    return $this;
}

/**
 * Get content
 *
 * @return string
 */
public function getContent()
{
    return $this->content;
}

/**
 * Set read
 *
 * @param integer $read
 * @return Imsg
 */
public function setRead($read)
{
    $this->read = $read;

    return $this;
}

/**
 * Get read
 *
 * @return integer
 */
public function getRead()
{
    return $this->read;
}

}

The error output

An exception occurred while executing 'UPDATE imsg SET read = ? WHERE
  id = ?' with params {"1":"1","2":1}:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MySQL server version for the right syntax to use near 'read = '1'
  WHERE id = 1' at line 1

Any ideas?
Answer: From the MySQL manual: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html - READ is a reserved word. I'm guessing that's why you're getting the syntax error.
Doctrine can automatically quote the column names for you:
<?php
/** @Column(name="`number`", type="integer") */
private $number;

Add backticks to the colum's name - taken from http://docs.doctrine-project.org/en/latest/reference/basic-mapping.html#quoting-reserved-words
Comment: Thanks for this, I had the exact same issue with the exact same keyword ("read"), and was on my way to pull my entire app apart before I saw your answer.
Answer: if you use yaml, you can do this
Number:
type: entity
table: `number `


$a \equiv b$ (mod $p$) implies $a^{p^n} \equiv b^{p^n}$ (mod $p^n$)?

Question: Let $p$ be a prime number. If $a \equiv b$ (mod $p$), does that imply $a^{p^n} \equiv b^{p^n}$ (mod $p^n$)?
I think the answer will be yes, and I suspect that the way of proving it will involve writing  $a^{p^n}-b^{p^n}$ as a multiple of $(a-b)^n$.
I also noticed that $n<p^n$, and I'm wondering if this will make the proof easier or not.
Answer: $a=b+kp$ where $k$ is an integer
$(b+kp)^{p^n}=b^{p^n}+\binom{p^n}1b^{p^n-1}kp+\binom{p^n}2b^{p^n-2}(kp)^{2}+\cdots+(kp)^{p^n}$
$\equiv b^{p^n}\pmod{p^{n+1}}$
Comment: So simple yet so useful! Thank you!
Answer: There is following theorem (Lifting The Exponent Lemma).
We will use notation $p^{\alpha}||n$ for positive integer $n$, nonnegative integer $\alpha$ and prime $p$, which equivalent to $p^{\alpha}|n$ and $p^{\alpha+1}\nmid n$.
Theorem.
Let $a,b,n$ be a positive integers and $p^{\alpha}||a-b$, $p^{\beta}||n$. Then:

if $p>2$ and $\alpha\geq 1$ then $p^{\alpha+\beta}||a^n-b^n$;
if $p=2$ and $\alpha\geq 2$ then $2^{\alpha+\beta}||a^n-b^n$.

Note. If $p=2$ and $\alpha=1$ then $2^{\beta+1}||a^n-b^n$.
Your statement is a consequence of this theorem.
Some links about LTE lemma:
What can I do with the lifting the exponent lemma?
https://brilliant.org/wiki/lifting-the-exponent/


I do not know why that create function was not in the class extends BaseAdapter

Question: I do not know why that create function was not in the class extends BaseAdapter.
I want pick image from gallery to imageview in custom listView.
I try to add a function "onActivityResult" after function "getView" is not working.
CustomList.java
public class CustomList extends BaseAdapter {

    public static final int REQUEST_GALLERY = 1;

    Context mContext;
    String[] strText1;

    TextView Text1;
    public static ImageView imgView;

    public CustomList(Context context, String[] strText1) {
        this.mContext = context;
        this.strText1 = strText1;
    }

    public int getCount() {
        return strText1.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View view, ViewGroup parent) {
        LayoutInflater mInflater =
                (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (view == null)
            view = mInflater.inflate(R.layout.custom_listview, parent, false);

        Text1 = (TextView) view.findViewById(R.id.Text1);
        Text1.setText(strText1[position]);

        imgView = (ImageView) view.findViewById(R.id.imgView);
        imgView.setImageResource(R.drawable.ic_NoPhoto);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                ((Activity) mContext).startActivityForResult(Intent.createChooser(intent
                        , "Select Picture"), REQUEST_GALLERY);
            }
        });

        return view;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_GALLERY && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                imgView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

But I try to add a function "onActivityResult" to the class "MainActivity" it work.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CustomList.REQUEST_GALLERY && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                CustomList.imgView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

If I want to function "onActivityResult" in the class "CustomList". How to do?
Comment: `onActivityResult ` method is from `Activity`, so it's not possible to override it inside any other class which is not extending `Activity` or `FragmentActivity`. but you can archive require task using either by [creating custom listener using interface](https://guides.codepath.com/android/Creating-Custom-Listeners) or [LocalBroadcastManager](http://developer.android.com/intl/es/reference/android/support/v4/content/LocalBroadcastManager.html)
Answer: You CAN'T. onActivityResult is designed to work with classes that extends Activity, which is why it would work in your MainActivity class.


Como inserir date e datetime em uma tabela no MySQL?

Question:
O grande problema é que após o insert, todos os valores que tem data, ficam como zeros e no formato yyyy-dd-mm e não dd/mm/yyyy, como foi inserido inicialmente. Como eu posso inserir estes valores na formatação que eu desejo?
Comment: Pronto, coloquei o que uso, MySQL.
Comment: Sim, seu banco o formato é `yyyy-mm-dd` a configuração e você não respeito isso, então, ele colocou zeros, to achando que é Mysql tal comportamente, mas, seria legal colocar a linguagem (se tiver usando) e o nome do banco.
Comment: SQL, mysql? sql server? a data deve ser gravada como `yyyy-mm-dd` no select vc utilize alguma função que o banco fornece para formatar conforme necessario.
Answer: Você não pode inserir diretamente dados em qualquer formato que deseje no MySQL para campos datetime e timestamp. O formato que o MySQL utiliza é o padrão ISO: AAAA-MM-DD HH:MM:SS e algumas variantes na mesma ordem.
Entretanto, isto não impede o usuário de converter os formatos no momento da entrada e saída dos dados - lembrando que de qualquer forma, o formato de armazenamento vai se manter igual no DB.
Veja como fazer esta conversão utilizando as próprias funções do MySQL:
Para visualizar datas como dd/mm/aaaa no SELECT:
Com a função DATE_FORMAT( data, formato ) você pode converter uma data em uma string formatada.
Exemplo para sua tabela:
SELECT usr_idusuario, DATE_FORMAT( evn_dtevento, "%d/%m/%Y" ) AS data_evento FROM evn_evento;

Como utilizar uma string dd/mm/aaaa ao se fazer o INSERT:
A função que faz o inverso do exemplo acima é STR_TO_DATE( string, formato ).
Aplicando à sua tabela:
INSERT INTO usr_idusuario SET evn_dtevento = STR_TO_DATE( "31/05/2014", "%m/%d/%Y" ), ...

Como utilizar uma string dd/mm/aaaa na cláusula WHERE:
SELECT campos FROM tabela WHERE dia = STR_TO_DATE( "31/05/2014", "%m/%d/%Y" );

Ou para um intervalo:
SELECT campos FROM tabela
WHERE  dia BETWEEN
           STR_TO_DATE( "01/05/2014", "%m/%d/%Y" ) AND
           STR_TO_DATE( "31/10/2014", "%m/%d/%Y" ) ;

Placeholders dos formatos mais comuns para nosso locale:
%d   Dia (00..31)
%e   Dia (0..31)
%m   Mês (00..12)
%y   Ano (dois dígitos)
%Y   Ano (quatro dígitos)
%%   Caractere %
%H   Horas (00..23)
%i   Minutos (00..59)
%s   Segundos (00..59)
%T   Hora completa ( 24 horas, formato hh:mm:ss)

Os formatos estão listados na íntegra no manual do MySQL (en)
Comment: Em uma cláusula `WHERE` devo usar `DATE_FORMAT` ou `STR_TO_DATE`?
Comment: @Patrick depende do tipo do campo e do que você quer fazer. Eu normalmente trabalho sempre com a data no formato original do MySQL, então não uso função nenhuma. Só controlo na aplicação a exibição na tela.
Answer: O Formato padrão é YYYY-MM-DD, para extrair a informação deverá ser tratado na aplicação ou na consulta.
Criando o campo com valor padrão no banco, ou passando now() no INSERT.
Assim será completado com o valor atual.
Comment: Usar o `now()` só resolve o problema quando a data é a atual. Se for uma data retroativa ou futura, por exemplo, esta não seria uma opção viável. Talvez seja interessante dar mais contexto e explicar quais são outras alternativas e/ou como lidar com o formato de data sugerido pelo autor da pergunta, caso tenha algo mais a acrescentar ou melhorar além da resposta aceita. ;)


$f:\mathbb R^n \rightarrow \mathbb R^m$ If $n \ne m$ then f is not injective or surjective

Question: The title may be confusing but i want to show that if $f:\mathbb R^n \rightarrow \mathbb R^m$ $f \in C^1$ with $m<n$ then f is not injective and If $m>n$ f is not surjective.
If $f$ was a linear transformations things would be simpler, i tought about recouring to rank theorem but i don't know How, any hints?
Comment: Any conditions on $f$, e.g., continuity?  If not, then all Euclidean spaces of dimension $\geq 1$ are pairwise *equipotent*, so there to exist bijections (which are both injective and surjective), just not continuous ones.
Comment: $\mathbf{R}$ and $\mathbf{R}^2$ are equipotent, hence there exists a bijection between them. Did you want $f$ to be differentiable with differentiable inverse?
Comment: Sorry forgot to add $C^1$
Comment: Can you add this smoothness requirement to the question?
Comment: Edited It already
Answer: The statement you want is (without further hypotheses on $f$) false - this was observed by Cantor, and is similar to how there is a bijection between $\mathbb{N}$ and $\mathbb{N}\times\mathbb{N}$. See for example the discussion here.

As a quick explanation of why such a thing might be expected, consider the "interleaving" map $i:[0,1)^2\rightarrow [0,1)$ gotten by interleaving the non-trailing-$9$s decimal expansions of the inputs - e.g. $$i(0.101010..., 0.3333...)=0.13031303...$$ This isn't quite what you want, but it is a bijection. Now how different are $[0,1]$ (which is what Cantor originally phrased his theorem about, if I recall correctly), $[0,1)$, and $\mathbb{R}$ really (that is, in terms of cardinality)?

Now, if you demand that $f$ be continuous, you do indeed get what you want (as a corollary of invariance of domain). But there are in fact bijections between $\mathbb{R}^m$ and $\mathbb{R}^n$ for all integers $m,n>1$.
Comment: @DanielMoraes It should appear in any elementary set theory book, and I think it's in "little Rudin" too. I don't think it has a name, unfortunately. [This paper of Gouvea](http://vigo.ime.unicamp.br/MA327/AMM-March11_Cantor.pdf) may be of interest. (Incidentally, assuming the axiom of choice, *every* infinite set is in bijection with its square!)
Comment: Any references on this theorem? My analysis book omisses this i think
Answer: If $f$ is required to be ${\cal C}^{1}$, then you assume $f(0) = 0$ (where each zero denotes the zero vector of the appropriate dimension) and use the Implicit Function Theorem, which says that $f$ at $0$ is locally equivalent to its linear part.  This will reduce the problem to your preferred context: linear transformations.
A nice statement and method of proof of the Implicit Function Theorem can be found in V. Arnol'd's Ordinary Differential Equations (use the latest edition).
Comment: Actually seen general topology, but can only use results from analysis, this aproach on implicit function is what i was looking for
Comment: Even continuity is enough, per invariance of domain.
Comment: Thanks! Will look for It
Comment: @NoahSchweber, true, but invariance of domain may or may not be beyond the asker's level.  A likely situation is that they haven't taken general topology yet, and were given the extra smoothness allowance on $f$ to enable using the results that require it.


Scoring runs when a no ball is caught

Question: When a ball is batted in the air and then caught, but it was called a no ball (so they can't be dismissed caught), will the batting team score any regular runs of the ball they completed (and can they potentially be run out)?
Two similar situations happened in two different IPL matches, but was seemingly treated differently.
In ball 19.5 of the second innings of the 32nd IPL 2015 match between Mumbai Indians and Rajasthan Royals, there was a run-out after a no ball was caught (an additional run was also scored, the run-out happened when they attempted a second).

Vinay Kumar to Binny, (no ball) 1 run, OUT, another full toss, in the air again and he's caught at long-on. This was definitely over the waist, and is called no-ball. Pollard doesn't realise that and throws the ball late, which makes Southee comes back for the second. But his throw is accurate and Vinay takes the bails off casually, catching Southee's bat short despite the dive. A no ball, a run, a run out

In ball 19.4 of the first innings of the 19th IPL 2015 match between Sunrisers Hyderabad and Kolkata Knight Riders, the ball was caught, but replays showed that it was above waist height and it was called a no ball, and in addition a run was scored. This was shown on televsion and CricBuzz and CricInfo.
But then in the innings break the score was adjusted, and as CricInfo says "The target is 177, not 178. The run taken on the no-ball for height in the last over won't be taken into account as the catch was taken".

UT Yadav to Rahul, 1 no ball, high full toss swung high over midwicket, long on runs in to his right to take it, but replays show that is just above waist height, and it is a no-ball

IPL actually tweeted about this.
Was one of these two situations treated wrong, or am I misinterpreting or missing some extra information which makes the two situations different?
Answer: The Law on no-ball is available here.
Section 14 says "Any runs completed by the batsmen or any boundary allowance shall be credited to the striker if the ball has been struck by the bat; otherwise they shall also be scored as No ball extras." Therefore, they should have been awarded the completed runs.
They can be run out, according to the run out law (here), where section says he cannot be run out "if No ball has been called
and he is out of his ground not attempting a run
and the wicket is fairly put down by the wicket-keeper without the intervention of another fielder.". However, in the cases above the batsman was attempting a run and was therefore fair game.
Comment: "they should have been awarded the completed runs". This would match my reading of the rules - which is why the IPL tweet is particularly confusing, as you'd expect a professional league to know the laws of the game. I find it hard to believe they were wrong and nobody cared, but I don't have a better explanation.
Comment: keep in mind the second example, the no-ball was not called during normal play. The catch was taken so the play stops. You cannot make runs off that. However since it was later deemed a no-ball it would be unfair to the fielding team since they thought the play was stopped... so no batting runs were added

Scoring runs when a no ball is caught


What is the easiest way to create has_many association using activeadmin gem?

Question: I just using activeadmin gem:
rails generate active_admin:resource Team
rails generate active_admin:resource Players
app/models
class Team < ActiveRecord::Base
  has_many :players
  attr_accessible :description, :name
end

class Player < ActiveRecord::Base
  belongs_to :team
  attr_accessible :description, :name
end

app/controller/players_controller
class PlayersController < ApplicationController
    def create
        @team = Team.find(params[:team_id])
        @player = @team.players.create(params[:player])
    end
end

app/admin/
  ActiveAdmin.register Team do
  end

  ActiveAdmin.register Player do
  end

When I tried to create a new Player using the admin interface, I receive:

ActiveModel::MassAssignmentSecurity::Error in Admin::PlayersController#create

Can't mass-assign protected attributes: team_id

I know that I have to do something more, but what? Thanks a lot.
Answer: You need to add team_id to attr_accessible:
class Player < ActiveRecord::Base
    belongs_to :team
    attr_accessible :description, :name, :team_id
end

Comment: Easiest, like I said. Thanks.


Difference bewteen declaring a NSString with alloc and init and assigning with @"myString"

Question: Currently I'm troubled with a small understanding issue on Objective-C. As example following Aaron Hillegass's book, I'm wondering about assigning an NSString in the init method of a class a value like in this example (For people who know the book, this is used in the Person class of RaiseMan):
- (id)init
{
   if(![super init])
     return nil;
   myString = @"New entry";
   return self;
}

This string isn't allocated by me, so normally I shouldn't bother about releasing it.
BUT! What happens in a setter-method of this string? Following the memory management rules the method should look like:
- (void)setMyString:(NSString *)newString
{
    if(myString != newString) {
        [myString release];
        [newString retain];
        myString = newString;
    }
}

Why does [myString release] work? I've read somewhere, that with = @"bla" assigned strings can't be released.
And is initializing with = @"bla" the right way? Or should I use alloc and init instead?
Thanks for any help :)
Answer: AFAIK, string constants of the form @"..." are actually a child class of NSString that redefine retain and release as no-ops. This allows the compiler to store those string constants in the data segment of your executable instead of on the heap.
Comment: they do nothing (no operation)
Answer: NSString *constantString = @"constantString";

String like constantString are said to be from a private(?) class NSConstantString and they are alive through all your program life. Off-course release and  retain work, (in the mean that they won't give you a exception or crash) They just do nothing.
Read more here
Also you said in one of your comments that it would be a{@property(..., copy) NSString myString;But what you are showing us is a typical @property(..., retain)
Comment: Oops, sorry for the retain and copy mistake, it should be indeed retain in my comment! So that means, if I create several objects like in my given init Method, I will have a huge amount of undisposeable strings, right? (= memory leak?) EDIT: Ah found the answer of this in your link. Thanks!
Answer: Is myString declared in the header-file? Like: @property(nonatomic, retain) NSString myString. If that is the case, then myString is retained. Otherwise, it's not necessary to release it.
Comment: Since he is defining his own setter  then @properties attributes, like retain,  are only advisory. (Obviously, he should do as the attributes suggest) However I don't think that is not an answer for the string initialization.
Comment: It is not defined as a property. But would @property(readwrite, copy) not also try to release the old value first?


Custom Template Help

Question: I am making a custom module on Drupal 7 and I am into to use templates for showing the info. How can I pass values from the module to the template?
Answer: Well, You need to use theme() function, which will allow to define the template name to be called, and the variables (values) to be send over to the template file defined.
Please refer documentation here - https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7
<code>$read_more = theme('more_link', array('url' => 'aggregator/sources/' . $feed->fid, 'title' => t("View this feed's recent news.")));
</code>
In the above code "more_link" is template name and associative array of values to be passed. In Template, you will get value of $title as "View this feed's recent news."
Hope you got the point.
Comment: Awesome! This worked perfect for me! Thanks you so much!

Custom Template Help


Run code "partially" in debug mode in PyCharm

Question: I'd like to run some Python code in debugger mode in PyCharm. My code includes an API function call, and for some reason, that single function call takes forever in debugger mode.
I really do not care about debugging that specific function, and having debugger skip over that function (only run it in regular mode) is fine. However, I'd like to be able run the rest of my code in debug mode.
Is this doable in PyCharm or is there any Python workaround?
# some code to be run in debugger mode, e.g.
func_a(obj_a) #this function modifies obj_a

# some API function call, super slow in debugger mode. can I just run this part in run mode? e.g.
obj_b = api_func(obj_a)

# rest of the code to be run in debugger mode e.g.
func_c(obj_b)

Comment: can't you comment out the part you want to skip?
Comment: No, I cannot. The rest of the code depends on execution of the api function call. It is just that I do not specifically need the function to be run in debugger mode.
Comment: set a breakpoint before the call, a breakpoint after, then just execute normally (not stepping) till the next breakpoint.
Comment: @Srini I had already tried that with Resume Program (F9) when it hits the first breakpoint and it does not work. By executing normally, do you mean some other way to run the function call?
Comment: No I meant resume program, so it never reaches the breakpoint after the API call?
Comment: your question is too broad, be more specific, add more details, some example code with *super slow API function call* so we can help instead of guessing
Comment: @Srini yeah, it never reaches the breakpoint. It works just fine in regular run mode. I have confirmed the library I am using does not behave well in debugger mode.
Comment: @AzatIbrakov It really is irrelevant and would be more confusing. I'll try to update the question. Given the edit, I'd need to be able to watch obj_b content after api_fun() call
Answer: Potentially you could use sys.gettrace and sys.settrace to remove the debugger while your API call runs, though it's not recommended, and PyCharm will complain at you if you do:

PYDEV DEBUGGER WARNING:
  sys.settrace() should not be used when the debugger is being used.
  This may cause the debugger to stop working correctly.
  If this is needed, please check:
http://pydev.blogspot.com/2007/06/why-cant-pydev-debugger-work-with.html
  to see how to restore the debug tracing back correctly.

In your case, you'd do something like this:
import sys

# some code to be run in debugger mode, e.g.
func_a(obj_a) #this function modifies obj_a

# Remove the trace function (but keep a reference to it).
_trace_func = sys.gettrace()
sys.settrace(None)

# some API function call, super slow in debugger mode. can I just run this part in run mode? e.g.
obj_b = api_func(obj_a)

# Put the trace function back.
sys.settrace(_trace_func)

# rest of the code to be run in debugger mode e.g.
func_c(obj_b)

I would strongly recommend keeping the code you run while the debugger is disabled as short as possible.
Comment: Thank you for the detailed response, works fine for me now. I'm new to Python programming and I knew there should be a solution similar to this unless PyCharm blocks any manipulation of the debugger which they don't :)
Comment: Works like a charm!
Answer: You can right-click on a breakpoint and set condition


iOS 7 UITableView default separator gets weird after reordering

Question: I have a problem with the default separator on UITableView in iOS 7.
When used as default the first and last separators have no insets, others are a bit inset. The original situation can be seen below:

Everything is ok. The first and last separators spread through the entire width of the table while the others are a bit smaller. Now I have the table view set to editing and I allow the user to reorder cells. And when the user does so the separators get messed up and do not appear correctly. The situation can be seen on the images below:

Do I really need to reload the data in order to fix this issue or is it an iOS 7 bug or am I doing something wrong?
How to fix this?
EDIT
Added some info about my implementation. I return NO on - (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath and UITableViewCellEditingStyleNone on - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath. My - (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath is:
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (!cell)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    cell.shouldIndentWhileEditing = NO;
    cell.textLabel.font = [UIFont someFont];

    UIColor *color = [UIColor randomColor];
    cell.textLabel.text = @"Some text";

    CGRect rect = CGRectMake(0, 0, 15, 15);

    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    [color set];
    CGContextFillEllipseInRect(ctx, rect);

    cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return cell;
}

and
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    if (sourceIndexPath.row == destinationIndexPath.row) return;

    NSString *tmp = [itemOrder objectAtIndex:sourceIndexPath.row];
    [itemOrder removeObjectAtIndex:sourceIndexPath.row];
    [itemOrder insertObject:tmp atIndex:destinationIndexPath.row];
    didReorder = YES;
}

Comment: FYI: this bug has been **fixed in iOS 8**.
Comment: it happens cause you are recycling the cells, you would need to reload data first :)
Comment: Not sure if I fully understand you, when am I supposed to reload data? Is that good practice?

Also which is better? To use a new cell each time or to reload data?
Comment: please, post your table view delegate code
Comment: When you are moving the cell the recycled one is moved, so it moves the entire cell with the differente separator, you need to reload data after moving the cells so the large separators stay into the correct place...
Comment: If I reload the data immediately after the `moveRowAtIndexPath` gets called it flicks the cell and it looks ugly. If I do the `performSelector: withObject: afterDelay:` it feels like I'm hacking. Is this really the proper way to fix this issue?
Comment: @Majster check my answer.that's perfect and short solution for that.
Comment: how do you instantiate the 1st cell with long separator?
Answer: This seems to be a problem in the iOS SDK. One way to solve it would be to manually apply the correct separator insets to all cells. However, I personally prefer to let the system do that.
If you reload a cell after reordering, the correct separator insets will be applied by the system. Therefore, you should simply make sure to reload the relevant cells after reordering.
Fix for user reorderings
There's a private method tableView:didEndReorderingRowAtIndexPath: that's called on your table view's delegate after the reordering (animation) has ended. In this method you should reload the cells:
- (void)tableView:(UITableView *)tableView didEndReorderingRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]
                  withRowAnimation:UITableViewRowAnimationNone];
}

This fix only works if rows are only moved within a section (and not between sections).
(It would be more efficient to only reload the moved cell and the cell at the old location using the method reloadRowsAtIndexPaths:withRowAnimation:. However, you'd have to store the old location before the cell is moved. which would be more complex to implement. For small sections/simple cells reloading the whole section might be a little bit easier.)
Fix for programmatic moves
Unfortunately, the private delegate method used in the previous fix is only called after reorderings by the user, and not after programmatically moving a row (using moveRowAtIndexPath:toIndexPath:). Therefore, we'll have to use another fix for that.
Since table views internally use CALayer animations, we can use a CATransaction to get to know when the animation has ended. (You do need to add QuartzCore.framework to your project for this.) My fix looks like this:
UITableView+NicelyMoves.h
#import <UIKit/UIKit.h>

@interface UITableView (NicelyMoves)

- (void)nicelyMoveRowAtIndexPath:(NSIndexPath *)indexPath
                     toIndexPath:(NSIndexPath *)newIndexPath;

@end

UITableView+NicelyMoves.m
#import <QuartzCore/QuartzCore.h>
#import "UITableView+NicelyMoves.h"

@implementation UITableView (NicelyMoves)

- (void)nicelyMoveRowAtIndexPath:(NSIndexPath *)indexPath
                     toIndexPath:(NSIndexPath *)newIndexPath
{
    [CATransaction begin];

    [CATransaction setCompletionBlock:^{
        // This is executed after the animations have finished
        [self reloadRowsAtIndexPaths:@[indexPath, newIndexPath]
                    withRowAnimation:UITableViewRowAnimationNone];
    }];

    [self moveRowAtIndexPath:indexPath toIndexPath:newIndexPath];

    [CATransaction commit];
}

@end

Usage
Now, instead of using moveRowAtIndexPath:toIndexPath:, you should use the custom method nicelyMoveRowAtIndexPath:toIndexPath:. For example, you could do this:
#import "UITableView+NicelyMoves.h"

@implementation YourTableViewController

- (void)moveTheRow
{
    // Move row 0 to 2 in section 0
    NSIndexPath *from = [NSIndexPath indexPathForRow:0 inSection:0];
    NSIndexPath *to = [NSIndexPath indexPathForRow:2 inSection:0];
    [self.tableView nicelyMoveRowAtIndexPath:from toIndexPath:to];
}

@end

Comment: This is not working on iOS 8. Still can't find solution.
Comment: @SlavcoPetkovski It still works fine on iOS 8 in the app I built this fix for. Are you sure you've implemented it correctly?
Comment: Yes, it is working now, since I was using fetchedResultsController and he was hiding the checkmarks after refreshing him. So I'm not refreshing now and it is working fine. By refreshing I mean reloading the sections.
Answer: Please try forcing inset size or setting them to zero in the viewDidLoad to ensure tableView respects them.
This is going to set your tableView separator insets to 30.
- (void)viewDidLoad {
    [super viewDidLoad];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 30, 0, 0)];
    }
}

You can also set separator insets only on specific cells as:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCellId"];

    if (indexPath.section == 0 && indexPath.row == 0) {
       [cell setSeparatorInset:UIEdgeInsetsMake(0, 30, 0, 0)];
    } else {
       [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    return cell;
}

Comment: I do not want the inset on inner cells to be zero, I want it to be as it is and to appear properly after moving.
Comment: I changed my answer, you can set them to anything you want. Just change 30 to your desired number.
Comment: Well this makes all insets the same. I want the first and last one without insets and others inset, just the way iOS makes it by default. I want is for the table to stay the way it was before moving (separators of course).
Comment: Well, in that case you can set them on individual cells then `[cell setSeparatorInset:UIEdgeInsetsMake(0, 50, 0, 0)];` I've updated my answers to reflect this.


How to show that an analytic function can be written as $g(z)^k$?

Question: Let $f$ be an analytic function with $f(z_0) = 0$ and $f \neq 0$. Let $k = gr(f, z_0) \geq 1$. Show that there exists an analytic function $g$ such that locally, $g(z)^k = f(z)$.
I know that if $f(z) \neq 0$ for all $z$, then i could let $h$ be the antiderivative of $f'/f$, so that $f(z)e^{-h(z)}$ is a constant, and finally write $f$ as $f(z) = ce^{h(z)}$, and then lastly, i could let $g(z) = c^{1/k}e^{h(z)/k}$
But this technique doesn't work in this case, since f can't be written as $e^{h(z)}$.
How should i go on about this?
Thank you.
Comment: Please explain the terms in the first paragraph, like what $f\ne 0$ means, and what $gr(f,z_0) $ means.
Comment: Write $\frac{f(z)}{z^k} = e^{h(z)}$ for instance.
Comment: Looking at $f'/f$ and $\log f$ works even if $f$ has some zeros, just replace $f$ by $f/P_r$ where $P_r$ is a polynomial containing its zeros on $|z-z_0| < r$. You'll find that $f(z)^{1/k}$ is analytic on $|z-z_0| < r$ iff all the zeros are of order $mk$.
Comment: I'm also curious about the terms @zhw mentioned. Could you explain what they mean?
Comment: @Cary yes sure. f != 0 means that f is not the constant function 0. And gr(f, z_0) mean that when writing f in its taylor series, f(z) = a_0 + a_1x^n + ..., all of a_1, ..., a_{k-1} are zero and a_k is not zero.
Answer: I think i managed to solve it.
Since $f$ is analytic, it can be written as
$$f(z) = \sum_{n = 0}^{\infty} a_n (z - z_0)^n$$
And because $gr(f, z_0) = k$ we have that
$$f(z) = \sum_{n = k}^{\infty} a_n (z - z_0)^n$$
$$ = \sum_{n = 0}^{\infty} a_{n+ k} (z - z_0)^{n+k}$$
$$ = (z - z_0)^{k} \sum_{n = 0}^{\infty} a_{n+ k} (z - z_0)^{n}$$
$$ = (z - z_0)^{k} \sum_{n = 0}^{\infty} b_{n} (z - z_0)^{n}$$
where $b_n = a_{n+k}$. Let us name this new function as $r(z) = \sum_{n = 0}^{\infty} b_{n} (z - z_0)^{n}$. Now, since $b_0 = a_k \neq 0$, we have that $r(z_0) \neq 0$.
$r$ is clearly analytic, and since it is not $0$, then $\frac{r'}{r}$ is analytic. Let $h$ be it's antiderivative.
Now, notice that
$$(r(z)e^{-h(z)})' = r'(z)e^{-h(z)} - r(z)e^{-h(z)}h'(z) =r'(z)e^{-h(z)} - r(z)e^{-h(z)}\frac{r'(z)}{r(z)} = 0$$
Therefore, $r(z)e^{-h(z)} = c$, and we conclude that $r(z) = ce^{h(z)}$.
Replacing this in the expression of $f$ we conclude that
$f(z) = (z - z_0)^kce^{h(z)}$. Now writing $g(z) = (z - z_0)c^{1/k}e^{\frac{h(z)}{k}}$, we can see that $g(z)^k = f(z)$
Comment: I think this works. Is there a mistake here?
Comment: You give an answer to your own question after $30$ minutes?
Comment: @zhw I read orangeskid comment and tried it this way. Do you have a problem with this?
Comment: I have a problem with askers of questions answering their own questions so quickly. But fine, maybe I'm alone on this.


Are These Conjectures Regarding Sufficient Statistics True?

Question: I have these conjectures that I cannot quite prove (unless I impose another regularity condition of parameter-independent support for distribution, in which case, the conjectures are trivially true --- I think).
Would appreciate 1) confirmation (w/ proof ideally), or 2) rejection (w/ counter example ideally).
Conjectures:
Suppose $X_1, ..., X_n$ are IID scalar random variables with PDF $f(x; \theta_1, ..., \theta_k)$, where $k < n$ and $\theta_1, ..., \theta_k$ are well-identified without any constraints among them (I can make this technically precise if necessary). Suppose there are $s$ statistics, $T_1, ..., T_s$, each a scalar, that are jointly sufficient.  Then,
A) $s \ge k$;
B) If $s = k$, then the sufficient statistics are minimal;
C) If $s = k$, then the sufficient statistics are complete.
End of Conjectures
Notes: If I further assume that the support of $f(x)$ is independent of $(\theta_1, ..., \theta_k)$, it is my understanding that there is a theorem that shows that $f(x)$ must be from the exponential family and all the conjectures above are true.
Answer: Nice conjectures you got there; shame if something were to happen to them
(A) is false for all $k>1$ for the simple reason that any vector of real numbers $T_1,...,T_s$ can be reduced to a single real number without loss of information (i.e., $\mathbb{R}^s$ is cardinally equivalent to $\mathbb{R}$; see e.g., here).  For example (though there are many other mappings you could use), write the digits of the statistics when represented as decimal numbers as:
$$\begin{align}
T_1 &= \cdots d_{1,3} \ d_{1,2} \ d_{1,1} \ d_{1,0} \cdot d_{1,-1} \ d_{1,-2} \ d_{1,-3} \cdots \\[6pt]
T_2 &= \cdots d_{2,3} \ d_{2,2} \ d_{2,1} \ d_{2,0} \cdot d_{2,-1} \ d_{2,-2} \ d_{1,-3} \cdots \\[6pt]
&\ \ \vdots \\[6pt]
T_s &= \cdots d_{s,3} \ d_{s,2} \ d_{s,1} \ d_{s,0} \cdot d_{s,-1} \ d_{s,-2} \ d_{1,-3} \cdots \\[6pt]
\end{align}$$
and then agglomerate these into a single real number:
$$T_* \equiv \cdots d_{1,1} \cdots d_{s,1} \ d_{1,0} \cdots d_{s,0} \cdot d_{1,-1} \cdots d_{s,-1} \ d_{1,-2} \cdots d_{s,-2} \cdots$$
It is simple to reverse this process to create a mapping $T_* \mapsto (T_1,...,T_s)$, which means that $T_* \in \mathbb{R}$ is also a sufficient statistic.  Consequently, for any $k>1$ if $T_1,...,T_s$ is sufficient then we can formulate the sufficient statistic $T_*$ with length $s_* = 1 < k$.
(B) is false for all $k>1$ as a corollary of the above.  Reduce the sufficient statistic to $T_*$ and then add useless statistics $T_{*2},...,T_{*k}$.  This then gives you a vector $T_*,T_{*2},...,T_{*k}$ with length $k$ that is not minimal sufficient (since the latter elements contribute nothing to sufficiency).  More generally, sufficiency of a statistic does not imply minimal sufficiency, even if the statistic has the same dimension as the parameter vector.
(C) is false by virtue of the fact that you can construct a sufficient non-complete statistic for the dimension $k=1$.  For $k>1$ you can also apply the above to construct a sufficient statistic that is non-complete.
Comment: Thanks Ben.  I actually saw this math result (cardinal equivalency) before, but failed to think of it when trying to "prove" the conjectures.  Thanks for pointing it out.  Now I don't need to bother.  I knew these all but certain could not be true (otherwise, someone would have long ago done it).   So indeed, the number of scalars involved in the sufficient statistics, without context, is arbitrary.  It could be as few as one and as big as you like (even for complete sufficient stats).   Conjecture (C) implies (B).  So if (B) falls, (C) cannot stand.
Comment: Yes, unfortunately when dealing with real vectors, if we don't have any restriction on structure we can expand and contract them to any length $1 \leqslant \ell < \infty$ with the same information.  Results somewhat like your conjectures sometimes hold when we restrict structure heavily (e.g., dealing with linear equations in unknowns), so the next useful step might be to think about whether there is any restriction you can impose on the statistics to give those results.
Comment: I know there may be ways to repair such conjectures ... Barndoff/Pedersen (1968) paper got around your "trick" by requiring the sufficient stats be continuous mapping from the raw data, for example. But I will leave such attempts to the theoretical statisticians.  I am already too far off field.
Answer: $U[0,\theta]$ is a counterexample to C. $T_1=\max_i X_i$ is sufficient for $\theta$ but it is not complete because $$E\left[\frac{n+1}{n}T_1\right]=\theta=E[2\bar X]$$
(I believe A and B are true.)
Comment: Thanks Thomas.  "Theory of Point Estimation" by Lehmann and Casella, Example 6.23 proves that $T_1$ is complete sufficient.  Perhaps you were thinking about examples like $U(0.5\theta, 1.5\theta)$ where the minimum sufficient stats, (min, max), are not complete?


Expectations, Double Integrals and Jensen's Inequality

Question: Consider two random variables distributed $v\backsim G(.)$ and
$c \backsim F(.)$ with pdfs $g(.)$ and $f(.)$. Let the supports of $c$ and
$v$ be $[x,y]$. Let $x<a=E(v)<b<y$, so $[a,b]\subset\lbrack x,y]$. Now
consider a strictly concave (twice differentiable and continuous) function
$u(.)$, with $u^{\prime}(.)>0$, $u^{^{\prime\prime}}(.)<0$, and $u(0)=0$
(passes through the origin). Establish sufficient conditions such that the
expression $\int_{a}^{b}u(E(v)-c)f(c)dc-\int_{a}^{b}\int_{x}^{y}%
u(E(v)-v)g(v)f(c)dvdc\geq0$ $\forall$ $v,c$, where $E(v)=\int_{x}^{y}vg(v)dv.$
Things I've tried:

$\int_{0}^{\bar{v}}u(E(v)-v)g(v)dv\leq0$ by Jensen's inequality. To see
this, let $E(v)-v=t$. But $E(t)=E_{v}[E(v)-v]=0$, and so $E(u(t))\leq
u(E(t))=0$, since $u(0)=0$ by assumption.
Clearly, $\int_{a}^{b}u(E(v)-c)f(c)dc\leq0$, since we are integrating the
integrand $(E(v)-c)$ from $a=E(v)$ to $b$.
Intuitively, a variant of Jensen's inequality should apply if $c$ and $v$
are i.i.d. Let $c$ and $v$ be i.i.d. with identical supports. Then the
integrands are the same, and we have the expression $\int_{a}^{b}%
u(E(v)-v)f(c)dc-\int_{a}^{b}\int_{x}^{y}u(E(v)-v)g(v)f(c)dvdc$. However, we
can't apply Jensen's inequality directly since $\int_{a}^{b}u(E(v)-v)f(c)dc$
is not $u(E(x))$, even if we "factor out" the outer integrals. $\int_{x}%
^{y}u(.)g(v)dv$ seems to be a form of $E(u(x))$.

At a loss as to what to do here. Any help would be greatly appreciated. Thank you!
Comment: Are you sure there are such conditions? I mean, is this an exercise in a textbook or similar?
Answer: Starting with $E_g[v] := \int_{x}^{y}vg(v) = a$, and using only the linearity of integration we get
$$\Delta = \int_{a}^{b}  \left[u(a-c) -  \int_{x}^{y}u(a-v)g(v)\,dv\right] f(c) \, dc.$$
Let us define the following operator: $E_f^{[w, z]}[h] := \int_{w}^z h(x)f(x)\,dx$.
This inherits many of the properties of the usual expectation operator.
In particular, if we write $K = \int_{x}^{y}u(a-v)g(v)\,dv$, we get
$$ \Delta = E_f^{[a, b]}[u(a-c) - K] = E_f^{[a, b]}[u(a-c)]  - E_f^{[a, b]}[K] = E_f^{[a, b]}[u(a-c)] - [F(b)-F(a)]K. $$
So to have $\Delta \geq 0$ we need
$$ \frac{1}{[F(b)-F(a)]}\int_{a}^{b} u(a-c)f(c)\,dc \geq \int_{x}^{y}u(a-v)g(v)\,dv. $$
Since we know from your own work that $E_f^{[a, b]}[u(a-c)] \leq 0$ we can also write
$$ \int_{a}^{b} u(a-c)f(c)\,dc \geq \int_{x}^{y}u(a-v)g(v)\,dv, $$
because $0 < F(b)-F(a) < 1$. If we let $F \equiv G$ we arrive at
$$ \int_{a}^{b} u(a-c)f(c)\,dc \geq \int_{x}^{a}u(a-c)f(c)\,dc + \int_{a}^{b}u(a-c)f(c)\,dc + \int_{b}^{y}u(a-c)f(c)\,dc, $$
$$ \int_{x}^{a}u(a-c)f(c)\,dc + \int_{b}^{y}u(a-c)f(c)\,dc \leq 0, $$
which need not always hold true.
Comment: Suppose $c$ and $v$ are i.i.d with identical supports. Would it be sufficient to establish the above? It seems that it would be, given that $u(a-c)$ is monotone decreasing in $c$.
Comment: @carlogambino I've updated my answer to reflect your comment. If you're able to provide more details, maybe we can substantially improve this.