Finding the general equation to the two-body problem

Question: So, just finished reading the Three Body Problem by Cixin Liu (very good novel), and was curious about the two-body problem. Of course, the two-body scenario is much simpler and more predictable than the two-body problem, so I was hoping to find a general solution to the two-body problem but haven't found one online, just solutions of specific cases. I decided to try to go at it on my own for the 2-dimensional system, but I got stuck.
I started by saying the first planet, Planet $x$, had a 2-dimensional position vector $\vec{x}$ and a mass $m_x$, and the second (Planet $y$) had a position vector of $\vec{y}$ and mass $m_y$. With the generalization that the two bodies are point masses with the only force being gravity, and assuming that both the initial positions/velocities and the masses of the two bodies are known, I came up with these two second-order differential equations:
$$\frac{d^2\vec{x}}{dt^2}=\frac{Gm_y}{||\vec{x}-\vec{y}||^3}(\vec{y}-\vec{x}) \\
\frac{d^2\vec{y}}{dt^2}=\frac{Gm_x}{||\vec{x}-\vec{y}||^3}(\vec{x}-\vec{y}) \tag{1}$$
I got these from these classical physics equations:
$$\underbrace{F_{y \rightarrow x}}_\text{force of gravity on x} = \underbrace{\frac{G m_y m_x}{||\vec{x}-\vec{y}||^2}}_\text{gravitational force}=\underbrace{m_x\frac{d^2\vec{x}}{dt^2}}_\text{mass and acceleration}$$
Then, I saw that there was a lot similar in the terms $\frac{d^2\vec{x}}{dt^2}$ and $\frac{d^2\vec{y}}{dt^2}$, so I used substitution to get this relationship:
$$m_x\frac{d^2\vec{x}}{dt^2} + m_y\frac{d^2\vec{y}}{dt^2} = 0$$
And that makes sense with the equal and opposite forces. Then I integrated twice:
$$m_x\vec{x} + m_y\vec{y} = \vec{c}t + \vec{d} \tag{2}$$
... where $\vec{c}$ and $\vec{d}$ are vector integration constants (I realized that they'd need to be vectors and not just constants). Using initial conditions, this means:
$$\vec{c} = m_x\vec{x}'(0) + m_y\vec{y}'(0) \\
\vec{d} = m_x\vec{x}(0) + m_y\vec{y}(0) \tag{3}$$
I solved $(3)$ for $\vec{y}$ (and later for $\vec{x}$) to substitute into $\frac{d^2\vec{x}}{dt^2}$ and $\frac{d^2\vec{y}}{dt^2}$ and uncouple the two differential equations in $(1)$:
$$\frac{d^2\vec{x}}{dt^2}=\frac{-Gm_y^3}{||(m_x+m_y)\vec{x}-\vec{c}t-\vec{d}||^3}((m_x+m_y)\vec{x}-\vec{c}t-\vec{d}) \\
\frac{d^2\vec{y}}{dt^2}=\frac{-Gm_x^3}{||(m_x+m_y)\vec{y}-\vec{c}t-\vec{d}||^3}((m_x+m_y)\vec{y}-\vec{c}t-\vec{d}) \tag{4}$$
But this is where I got stuck. I coded something in Matlab that uses $(4)$ in the ode45 function to see how things move at least (code below), but I definitely have not been able to find any methods to solve either equation in $(4)$. Does such a closed form even exist? Of course that would mean that $\vec{x}$ and $\vec{y}$ aren't always functions, but I was wondering if maybe there's a parameterized solution or something like that. Thanks!
Here's the code for my demonstration, it's kinda janky:
% %%%%%%%%% Set stuff up %%%%%%%%%

% planet x
x_init = [6 9]';
dx_init = [0 -0.001]';
mx = 6900;

% planet y
y_init = [-6 -9]';
dy_init = [0 0]';
my = 420000;

% other things
tlength = 100000; % diffeq soln time length (bigger means longer duration)
scale = 300; % scale of velocity vectors
speed = 5; % speed of animation (bigger means faster)

% %%%%%%%%% Animate Motion %%%%%%%%%
plotPlanets([x_init dx_init y_init dy_init],[mx my tlength],scale,speed)

%% Functions
function [T,D] = getPositions(vecs, cons)
    % vecs := matrix containing info for the planet in this format:
    %    [[x0] [dx0] [y0] [dy0]]
    % cons := vector with relevant constants in this format:
    %    [[mass of x] [mass of y] [time length]]
    syms x1(t) x2(t) dx1(t) dx2(t) y1(t) y2(t) dy1(t) dy2(t)

    funcx = formula([x1 x2 dx1 dx2]);
    funcy = formula([y1 y2 dy1 dy2]);

    % Unpack
    x_init = vecs(:,1);
    dx_init = vecs(:,2);
    y_init = vecs(:,3);
    dy_init = vecs(:,4);

    mx = cons(1);
    my = cons(2);
    tlength = cons(3);
    c = mx*dx_init + my*dy_init;
    d = mx*x_init + my*y_init;

    eqnsx = getFormulas([c d],[mx my],[funcx t]);
    eqnsy = getFormulas([c d],[my mx],[funcy t]);
    eqns = [eqnsx eqnsy];
    vars = [funcx funcy];
    init = [x_init' dx_init' y_init' dy_init'];

    F = odeFunction(eqns,vars);
    [T, D] = ode45(F,[0 tlength],init);
end

function eqns = getFormulas(vecs, mass, funcs)
    % vecs := matrix containing info for the planet in this format:
    %    [[c] [d]]
    % mass := vector with relevant constants in this format:
    %    [[own mass] [other mass]]
    % funcs := symbolic functions in the format [z1 z2 dz1 dz2 t].

    % Set up
    G = 6.67408*10^(-11); % Gravitational constant

    % Unpack
    c = vecs(:,1);
    d = vecs(:,2);
    mz = mass(1);
    mw = mass(2);

    % fromz is vector between planets
    fromz = formula((mz+mw)*[funcs(1);funcs(2)] - c*funcs(5) - d);
    eqn1 = -G*mw^3/norm(fromz)^3*fromz(1);
    eqn2 = -G*mw^3/norm(fromz)^3*fromz(2);
    eqns = formula([funcs(3:4) eqn1 eqn2]);
end

function plotPlanets(vecs, cons, scale, speed)
    [T,D] = getPositions(vecs,cons);
    Dx = D(:,1:4);
    Dy = D(:,5:8);
    xmin = min([min(Dx(:,1)) min(Dy(:,1))]);
    xmax = max([max(Dx(:,1)) max(Dy(:,1))]);
    ymin = min([min(Dx(:,2)) min(Dy(:,2))]);
    ymax = max([max(Dx(:,2)) max(Dy(:,2))]);
    tlast = T(1);

    figure(1)
    hold on
    axis(sizeUp(xmin,xmax,ymin,ymax))
    pathx = plot(1);
    px = plot(Dx(1,1),Dx(1,2),"bo");
    vx = quiver(Dx(1,1),Dx(1,2),scale*Dx(1,3),...
        scale*Dx(1,4),"Color",[0 0 0]);
    pathy = plot(1);
    py = plot(Dy(1,1),Dy(1,2),"ro");
    vy = quiver(Dy(1,1),Dy(1,2),scale*Dy(1,3),...
        scale*Dy(1,4),"Color",[0 0 0]);
    pause(0.5)

    for i = 2:size(D,1)
        if ~any(findobj(allchild(0), 'flat', 'type', 'figure') == 1)
            break
        end
        delete(pathx);
        delete(px);
        delete(vx);
        delete(pathy);
        delete(py);
        delete(vy);

        pathx = plot(Dx(1:i,1),Dx(1:i,2),"b");
        px = plot(Dx(i,1),Dx(i,2),"bo");
        vx = quiver(Dx(i,1),Dx(i,2),scale*Dx(i,3),...
            scale*Dx(i,4),"Color",[0 0 0]);
        pathy = plot(Dy(1:i,1),Dy(1:i,2),"r");
        py = plot(Dy(i,1),Dy(i,2),"ro");
        vy = quiver(Dy(i,1),Dy(i,2),scale*Dy(i,3),...
            scale*Dy(i,4),"Color",[0 0 0]);
        pause((T(i)-tlast)/speed/1000)
        tlast = T(i);
    end
    if any(findobj(allchild(0), 'flat', 'type', 'figure') == 1)
        hold off
    end
end

function sizes = sizeUp(xmin, xmax, ymin, ymax)
    if xmax - xmin > ymax - ymin
        len = (xmax - xmin)/2;
        ymid = sum([ymax ymin])/2;
        ymin = ymid - len;
        ymax = ymid + len;
    elseif xmax - xmin < ymax - ymin
        len = (ymax - ymin)/2;
        xmid = sum([xmax xmin])/2;
        xmin = xmid - len;
        xmax = xmid + len;
    end
    pad = abs(len*0.1);
    sizes = [xmin-pad, xmax+pad, ymin-pad, ymax+pad];
end

Comment: Eventually, you get to [Kepler's equation](https://en.wikipedia.org/wiki/Kepler%27s_equation), $$M=E-e\sin E$$, where $e$ is eccentricity, $M$ is an angle linearly proportional to time, and $E$ is the central angle (which you need to find the body's position). There's no way to invert that equation (using elementary functions) to write $E$ in terms of $M$, but it's pretty easy to solve numerically (eg, using Newton-Raphson), or to approximate using a series.
Answer: The easiest way to solve the two-body problem is to reduce it into two independent one-body problems by introducing the center of mass.
This effectively decouples the motion of the two bodies into a (1) center of mass motion (= 1st one-body problem) and a (2) displacement vector motion (= 2nd one-body problem).
For detailed info, you may wish to refer to this Wikipedia link:
https://en.wikipedia.org/wiki/Two-body_problem#Center_of_mass_motion_(1st_one-body_problem)


Slowing Down To Transcribe

Question: Is there some consensus/study on whether one should slow down music which one cannot play just by hearing it a couple of times (if the goal is to improve as a musician)? If I got a fast run, I can either slow it down and get it easily, or attempt to transcribe it at full speed, resulting in often listening to it dozens or hundreds of times.
On one hand, there's the idea that if something's making your brain hurt, you're probably doing the right thing, as stepping outside your comfort zone is going to make you improve the most.
On the other hand, there's the prevalent idea in ear training that students should be helped in every possible way - i.e. playing the interval over and over, slowly, not pressing the student to answer right away. This seems to suggest "going outside your comfort zone", at least on some level, is not a good idea for ear training.
So: slow down or go at full speed? (if the latter is even possible, which sometimes is not)
Comment: [This question](http://music.stackexchange.com/questions/123/software-that-slows-down-music-to-help-in-transcribing) lists software that can be used to slow down music for transcription.
Answer: Always keep in mind the goal is to be able to more effectively write, improvise, and perform music. There's no street cred or punk rock points for the way you practice at home if it doesn't lead to a better performance. Both methods you outline are obviously valuable. The main benefit in slowing the music down, however, is not a matter of making it easier.
I find the one thing that gets glossed over in transcription is also the most important thing: Rhythm.
By slowing a piece down you make the rhythm far more obvious, playing the rhythm at slower tempos forces you to be far more exacting with the placement of the notes and their articulation, and I find it leads to a quicker comprehension of the phrase structure.
A general rule of thumb is practice slow to play fast. Getting the rhythms flawless with zero tension is the goal. You will tense up less with it slowed down, which will lead to the ability to improvise similar lines at any tempo you choose.
It doesn't require fancy software either. I use Windows Media Player because it came free with the computer.
Answer: I think there is a limit to how much you should position yourself out of your comfort zone. The time you waste on the really hard bits of what you are transcribing could be put to use in something else.
I don't have any studies to back me up here, but I do remember some great jazz artists saying that they would transcribe without 100% accuracy, so they could move on to the next record. The "wrong" phrases would still help them out in developing their own language. They could always return to those later, with better ears.
My advice to someone in this position: If you are trying to figure it out for several minutes without any success, you should allow yourself to slow it down a bit.
Just remember that full speed is your standard.
The really hard sections of a piece shouldn't be your focus when you first start transcribing, because they can strain your progress. Concentrate on what you can do. This means slowing down what is too hard so you can dedicate yourself to transcribing what is possible for you at full speed. With practice, everything will become easier and you will be able to concentrate on those hard bits without slowing down.
Comment: I feel like fast practice helps with muscle memory, and when used sparingly  (but intensively) the quest to nail a fast passage WITHOUT slowing it down can be hugely beneficial.  On the other hand, too much of this - or not stopping in extreme frustration IMMEDIATELY when you start to make a mistake - will teach you bad habits faster than it will teach you to improve.
Comment: "I think there is a limit to how much you should position yourself out of your comfort zone."  A bit of wisdom with more general application than this one: "skiing" leaps to mind.  :)
Answer: It's very hard to try to learn something at full speed in the beginning. Of course it can be done, but it's definitely not the fastest way.
So in a lot of cases (and depending on your ability) you may have to resort to slowing down to be able to practice. Also - this will enable you to transcribe better as well.
And lastly - if you practice something at different speeds - your skill will improve at the intended speed as well. This is a strange learning effect that works for all types of skills (e.g. if you learn a new language then your other languages will also improve etc.).
Our company owns a have a nifty tool on desktop and ios to slow down songs - it's been around since 2005.
Comment: If you are affiliated with Riffmaster you should make that clear. It's not clear who "we" is in your last sentence.
Comment: @ToddWilcox I've made it more clear now. Sorry, I thought it was clear the way I put it.

Slowing Down To Transcribe


Error 1006: Not a function

Question: I am getting the error in the title when trying to access a method in another class. I have the main class, ZombieBots, which is linked to a movie clip of the same name. I then have 3 more movie clips which all get added to the ZombieBots clip during runtime, and each of these have their own classes.
When I attempt to access a method within the ZombieBots class from one of the other 3 classes, I get error 1006.
The function I am attempting to access in the ZombieBots class, that cannot be accessed:
    package  {
    import flash.events.*;
    import flash.display.MovieClip;
    import flash.geom.Rectangle;

    public class ZombieBots extends MovieClip{

        private var pLives:int;
        private var pScore:int;
        private var pSkill:int;
        private var pItems:int;
        private var characterMC:Character;
        private var cGameObjs:Array;

        public function ZombieBots() {
            /*cGameObjs = new Array();
            addCharacter();
            addItems();
            addBots();

            pLives = 5 - pSkill;
            pScore = 0;

            pItems = pSkill + 5;*/
            resetGame();
        }

        private function  addCharacter():void{
            trace("Adding the character");

            if (!characterMC){
            var myBorder:Rectangle = new Rectangle(35,35,600,480);
            var myXY:Array = [38, 400];
            var myChar:int = Math.ceil(Math.random()*3);
            var myKeys:Array = [37,39,38,40];
            var myDistance:int = myChar * 3;
            characterMC = new Character(myBorder, myXY, myKeys, myChar, myDistance);
            addChild(characterMC);
            }
            else{

                characterMC.x = 38;
                characterMC.y = 510;

                characterMC.gotoAndStop(pSkill);

            }
        }

    private function  addItems():void{
        trace("yeah boi");
        var mySkill:int = Math.ceil(Math.random() *3);
        var myMaxItems:int = mySkill + 5;
        trace(mySkill);
        trace(myMaxItems);
        trace(this);
        for (var i:int = 0; i < myMaxItems; i++){
            var thisItem:Item = new Item(this, characterMC, mySkill);
            thisItem.name = "item" + i;
            cGameObjs.push(thisItem);
            addChild(thisItem);
        }

        pSkill = mySkill;
        updateScores();
    }

        private function  addBots():void{
            trace("adding the bots bra");
            var myBorder:Rectangle =  new Rectangle(100,100,400,350);
            var mySkill:int = Math.ceil(Math.random()*3);
            var myMaxBots:int = mySkill +10;
            for (var i:int = 0; i < myMaxBots; i++){
                var thisBot:Bot = new Bot(myBorder, characterMC, mySkill);
                thisBot.name = "bot" + i;
                cGameObjs.push(thisBot);
                addChild(thisBot);

            }
        }

        private function  updateScores():void{
            scoreDisplay.text = String(pScore);
            itemsDisplay.text = String(pItems);
            livesDisplay.text = String(pLives);
            msgDisplay.text = "Orc Invasion";

        }

        public function  updateLives(myBot:MovieClip):void{
            trace("update lives");
            pLives--;
            pScore -= myBot.getPts();
            var myIndex:int = cGameObjs.indexOf(myBot);
            cGameObjs.splice(myIndex, 1);
            if (pLives > 0){
                updateScores();

            }

            else{
                gameOver(false);
            }
        }

        public function updateItems(myItem:MovieClip):void{
        trace("update items");
        pItems--;
        pScore += myItem.getPts();
        var myIndex:int = cGameObjs.indexOf(myItem);
        cGameObjs.splice(myIndex, 1);
        if (pItems > 0){
            updateScores();
        }

        else{
            gameOver(true);
        }

    }

        private function  gameOver(bool:Boolean):void{
            trace("Game over dawg");
            updateScores();
            if(bool){
                msgDisplay.text = "Good job buddy";
            }
            else{
                msgDisplay.text = "You suck dawg";
            }
            removeLeftovers();
        }

        private function  resetGame():void{
            playAgainBtn.visible = false;
            playAgainBtn.removeEventListener(MouseEvent.CLICK,playAgain);
            cGameObjs = new Array();
            addCharacter();
            addItems();
            addBots();

            pLives = 5 - pSkill;
            pScore = 0;

            pItems = pSkill + 5;
            updateScores();
        }

        private function  playAgain(evt:MouseEvent):void{
            resetGame();
        }

        private function removeLeftovers():void{
            trace("Removing leftover items and bots");
            for each(var myObj in cGameObjs){
                myObj.hasHitMe();
                myObj = null;
            }
            playAgainBtn.visible = true;
            playAgainBtn.addEventListener(MouseEvent.CLICK, playAgain);
        }

    }

}

and this is the class where I am attempting to access this function within one of the other 3 classes:
    package  {
    import flash.display.MovieClip;
    import flash.events.*;
    import ZombieBots;

    public class Item extends MovieClip{
        private var cNumItem:int;
        private var cNumPts:int;
        private var characterMC:MovieClip;
        private var ZombieBot:ZombieBots;

        public function Item(myZB:ZombieBots, myChar:MovieClip, mySkill:int=1) {
            ZombieBot = myZB;
            cNumItem = Math.ceil(Math.random() * (mySkill * 3 + 1));
            characterMC = myChar;
            this.addEventListener(Event.ADDED_TO_STAGE,initItem);
            addEventListener(Event.ENTER_FRAME, checkCollision);
        }

        private function initItem(evt:Event):void{

            this.gotoAndStop(cNumItem);
            cNumPts = cNumItem * 25;
            setPosition();
            this.removeEventListener(Event.ADDED_TO_STAGE,initItem);
        }

        private function setPosition():void{

            this.x = (Math.ceil(Math.random() * 10)*50);
            this.y = (Math.ceil(Math.random()*10)*35);

        }

        private function checkCollision(evt:Event){
            if (characterMC.hitTestObject(this)){

                ZombieBot.updateItems(this);
                hasHitMe();
            }
        }

        public function hasHitMe():void{
            trace("remove");
            removeEventListener(Event.ENTER_FRAME, checkCollision);
            this.parent.removeChild(this);
        }

        public function getPts():int{
            return cNumPts;
        }
    }

}

can anyone help?
Comment: @prototypical looks like root type is not ZombieBots because of null object reference.like you said its not best way to achieve but as i said before just send ZombieBots instance to Item class when creating them. you can assign it in Item's constructor to private var in Item class then you can reach whenever you want ...
Comment: Have news for you. Your private var is not what is making it work. It's the import that was created that made it work. You aren't even using the ZombieBot property in your code, and it never gets assigned.
Comment: Based on the code you just posted, ZombieBots seems to be your document class, unless you are instantiating it in another class. What is the class that you are using as your document class, if not ZombieBots ? Yes, the problem is solved, but I have to believe you are completely misunderstanding why. If you are good with that, it's all good.
Comment: myItem.getPts(); you have no method like getPts() in Item class
Comment: @Bolzano, The entire class is 200 Lines. I am supplying an example of the problem.
Comment: yea but you have to add definition of your functions or methods or classes which used in main code ... otherwise how could we find your bug. its obvious you are calling something but its not defined as function.
Comment: @Bolzano Fair enough, but the problem is that when trying to access the updateItems class, it can't be found.
Comment: ok additionaly to "prototypical's answer" send your ZombieBots instance as owner (or displayContainer its up to you) to Item to reach that instance from Item class. like "var item:Item = new Item(this);//in ZombieBots Class"... or make your main class as singleton to reach instance easily. these are solutions but not the bests. it can be different depends on your pattern .
Comment: @rakeshisu I am not looking to play programming charades here. What I have posted will work, but as I said I am making some assumptions. Am I supposed to just question you about these assumptions one by one until we hit the right one ? Have you debugged to see what root is ? is it null ? I have no idea how you have things set up, because I can't see the code. You might not think some of it is relevant, but then again, you are the one with the broken code here. right ?
Comment: Also, are you sure that the null error is on the line you specified ? And not in the updateItems method ? Post the exact error message with line number.
Comment: @prototypical I apologize. I am just struggling to find out what code you need to see. I understand that I am the one having the problem and I am extremely grateful for your help. I traced root, which is returning "[object MainTimeline]." It is definitely not null.

Again, I apologize. I am really terrible at flash.
Comment: The error message: TypeError: Error #1009: Cannot access a property or method of a null object reference.
 at Item/checkCollision()[C:\Users\Jesse\Desktop\MainMenu\Item.as:39]
Comment: We are playing programming charades. Can you please post the code so we can see where ZombieBots is instantiated ? If it's not root, the implementation you chose is not going to work as Item will not have a reference to that class via root.  -- for the record, I don't think that's the best way to achieve what you want, but I'm working within your current implementation.
Comment: I posted all my code. Hopefully this will help with understanding. Sorry.
Comment: "Document class" is a new term to me, I am afraid. Is the document class the class which I have linked to the fla? Or is it something else? I do not have a .as linked to my .fla right now.
Comment: I posted the code that is working. After I created the private var I added it to my constructor as well as creating it as a parameter.
Answer: updateItems is not a MovieClip method. It's a method of your ZombieBots class.
Casting your ZombieBots instance (which I am assuming is root) as a MovieClip, will only allow you to use it's class methods or methods it has inherited.
Try this :
var zombieBotsInstance:ZombieBots = root as ZombieBots;
zombieBotsInstance.updateItems(this);

Comment: Woops, that's my mistake. edited original post with the correct code.
Comment: I tried this, but I am now getting null object reference on the zombieBotsInstance.updateItems(this) line.

I have a feeling that trying to access the root in this way is the problem, but I don't know how to fix it.
Comment: Post your updated code. I am making a few assumptions here. What is root ? Is it a ZombieBots instance - ie document class ?
Comment: The ZombieBots class is linked to a movie clip of the same name and within this MovieClip I add Items(another MovieClip linked to the Items class). The document class(if I am understanding the term correctly) is the class linked to the .fla file, which is not accessed or referred to in ZombieBots.
Comment: So... root is NOT your ZombieBots instance. Therefore, why would it be able to all a method in that instance ?? I gave you an answer based on the assumption that root was a ZombieBots instance.
Comment: Very good example of how code very relevant to this issue, was not seen as relevant to provide in the question.

Error 1006: Not a function


Unable to ping gateway from network

Question: I got the following route table :
#!/bin/bash
IP=/sbin/ip

# SST
echo "SST: Setting up SST network ..."
$IP route flush table 10
$IP route add table 10 to 10.45.13.0/26 dev eth0
$IP route add table 10 to default via 10.100.36.1 dev eth0
$IP rule add from 10.45.13.0/26 table 10 priority 10
$IP route flush cache
echo "SST: SST network routing in place."

# Expotools
echo "SST: Setting up Expotools network ..."
$IP route flush table 20
$IP route add table 20 to 10.45.15.0/26 dev eth3
$IP route add table 20 to default via 10.200.36.1 dev eth3
$IP rule add from 10.45.15.0/26 table 20 priority 20
$IP route flush cache
echo "SST: Expotools network routing in place."

echo "SST: Others routing settings...."
route add default gw 10.100.36.1

root@ROUTER-DEB:/sst/scripts# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
10.200.36.0     0.0.0.0         255.255.255.248 U     30     0        0 eth3
10.100.36.0     0.0.0.0         255.255.255.248 U     40     0        0 eth0
10.45.15.0      0.0.0.0         255.255.255.192 U     5      0        0 eth2
10.45.13.0      0.0.0.0         255.255.255.192 U     10     0        0 eth1
0.0.0.0         10.100.36.1     0.0.0.0         UG    0      0        0 eth0
0.0.0.0         10.45.15.1      0.0.0.0         UG    5      0        0 eth2
0.0.0.0         10.45.13.1      0.0.0.0         UG    10     0        0 eth1
0.0.0.0         10.200.36.1     0.0.0.0         UG    30     0        0 eth3
0.0.0.0         10.100.36.1     0.0.0.0         UG    40     0        0 eth0

All of my computers on 10.45.13.0/26 and 10.45.15.0/26 are unable to ping 10.45.13.1 and 10.45.15.1 but can be everyting on 10.100.36.0 and 10.200.36.0.
IPTables :
ET_BELL=eth0
ET_VIDEOTRON=eth3
ET_SST=eth1
ET_EXPOTOOLS=eth2

# On va vider le contenu de IPTables
echo "SST: Cleaning IPTables content..."
iptables -F
iptables -t nat -F
iptables -t mangle -F
iptables -X

echo "SST: Accepting all incoming lo data..."
iptables -A INPUT -i lo -j ACCEPT

iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A INPUT -m state --state NEW ! -i $ET_BELL -j ACCEPT
iptables -A FORWARD -i $ET_BELL -o $ET_SST -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -m state --state NEW ! -i $ET_VIDEOTRON -j ACCEPT
iptables -A FORWARD -i $ET_VIDEOTRON -o $ET_EXPOTOOLS -m state --state ESTABLISHED,RELATED -j ACCEPT

echo "SST: Opening ports..."
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 53 -j ACCEPT
iptables -A INPUT -p icmp -j ACCEPT
iptables -A INPUT -p igmp -j ACCEPT

echo "SST: Forwarding Bell to SST Network..."
iptables -A FORWARD -i $ET_BELL -o $ET_SST -j ACCEPT
echo "SST: Forwarding Videotron to Expotools Network..."
iptables -A FORWARD -i $ET_VIDEOTRON -o $ET_EXPOTOOLS -j ACCEPT

echo "SST: Activation of BELL/SST NAT..."
iptables -t nat -A POSTROUTING -o $ET_BELL -j MASQUERADE
echo "SST: Activation of Videotron/Expotools NAT..."
iptables -t nat -A POSTROUTING -o $ET_VIDEOTRON -j MASQUERADE

echo "SST: Forwarding SQUID3..."
iptables -t nat -A PREROUTING -i $ET_SST -p tcp --dport 80 -j DNAT --to 10.100.36.2:3128
iptables -t nat -A PREROUTING -i $ET_EXPOTOOLS -p tcp --dport 80 -j DNAT --to 10.200.36.2:3128

iptables -A FORWARD -i $ET_SST -o $ET_EXPOTOOLS -j REJECT
iptables -A FORWARD -i $ET_EXPOTOOLS -o $ET_SST -j REJECT
iptables -A FORWARD -i $ET_BELL -o $ET_BELL -j REJECT
iptables -A FORWARD -i $ET_VIDEOTRON -o $ET_VIDEOTRON -j REJECT

root@ROUTER-DEB:/etc/bind# ifconfig
eth0      Link encap:Ethernet  HWaddr 30:85:a9:ad:54:1e
          inet addr:10.100.36.2  Bcast:10.100.36.7  Mask:255.255.255.248
          inet6 addr: fe80::3285:a9ff:fead:541e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:4808477 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3617658 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:4984207655 (4.6 GiB)  TX bytes:972655869 (927.5 MiB)
          Interrupt:27 Base address:0xe000

eth1      Link encap:Ethernet  HWaddr a0:f3:c1:04:64:40
          inet addr:10.45.13.1  Bcast:10.45.13.63  Mask:255.255.255.192
          inet6 addr: fe80::a2f3:c1ff:fe04:6440/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:25385197 errors:0 dropped:9143 overruns:0 frame:0
          TX packets:15372440 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:32206688027 (29.9 GiB)  TX bytes:5934594299 (5.5 GiB)
          Interrupt:17 Base address:0x4000

eth2      Link encap:Ethernet  HWaddr a0:f3:c1:04:a0:2f
          inet addr:10.45.15.1  Bcast:10.45.15.63  Mask:255.255.255.192
          inet6 addr: fe80::a2f3:c1ff:fe04:a02f/64 Scope:Link
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:36936 errors:0 dropped:0 overruns:0 frame:0
          TX packets:45462 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:5640732 (5.3 MiB)  TX bytes:43909441 (41.8 MiB)
          Interrupt:18 Base address:0x8000

eth3      Link encap:Ethernet  HWaddr 28:10:7b:c9:58:76
          inet addr:10.200.36.2  Bcast:10.200.36.7  Mask:255.255.255.248
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:1619 errors:0 dropped:0 overruns:0 frame:0
          TX packets:7 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:233263 (227.7 KiB)  TX bytes:922 (922.0 B)
          Interrupt:19 Base address:0xc000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:8477 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8477 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1000859 (977.4 KiB)  TX bytes:1000859 (977.4 KiB)

Comment: If you are going to use advanced routing features, then stop using the `route` command.  It simply doesn't return useful information.  It doesn't understand multiple route tables.  It would be more useful if you gave the output of `ip route show table all`.  Likewise, stop using `ifconfig`, use `ip addr show`
Comment: Could you list the IP's on each interface? ip add sh ?
Comment: @SandorMarton Added.
Comment: My routing is working fine. I am not able to reach my server with the gateway address (10.45.13.1 and 10.45.15.1).
Answer: Try this instead of your rules.
But reboot the route first so all other routes/rules are cleaned (obviously don't load at boot that the previous script)
ip route flush table 10
ip route add 10.45.13.0/26 dev eth1 table 10
ip route add 10.100.36.0/29 dev eth0 table 10
ip route add default via 10.100.36.1 table 10
ip rule add from 10.45.13.0/26 table 10 prio 10

ip route flush table 20
ip route add 10.45.15.0/26 dev eth2 table 20
ip route add 10.200.36.0/29 dev eth3 table 20
ip route add default via 10.200.36.1 table 20
ip rule add from 10.45.15.0/26 table 20 prio 20

ip ro add default via 10.100.36.1

ip ro flush cache

Unable to ping gateway from network


find files with invalid predicates

Question: So, I'm trying to get all files older than 40 days.  (hence the -mtime -40), but can't find because some files have invalid predicates. (Need to find all files whether in current or descendant.
$ find . -name * -mtime -40 > FILE_LIST
find: invalid predicate `-file-name.xls'

And then...
$ find ./* -name * -mtime -40 > FILE_LIST
find: invalid predicate `-file-name.xls'

And neither of these seem to do it.
Answer: I think the problem is that the * in your -name * is being expanded to a file list by the shell which is then passed to find on it's command line. The find command then parses the command line and finds the -file-name.xls which it tries to interpret as a command line argument.
try
find .  -mtime -40 > FILE_LIST

which should do what you want.
Comment: This did exactly what I needed :).  I guess I tried to bite off more upfront than I needed to.  Thanks for the great explanation as well
Comment: this works since `-name *` doesn't do anything in this case (since it means "every possible name", its not changing the output.  Note that if you DID need to do something similar you should single-quote the * so that the shell doesn't try to do this expansion.  so `find . -name '*' -mtime -40` would have worked for you.
Comment: @stew: yup

find files with invalid predicates


Calculus u-substitution: Choosing between $\frac{dx}{du}$ and $\frac{du}{dx}$

Question: I searched and couldn't find any answers to this one. It's probably a dumb question but one that has been troubling me.
Let's say I have an integration:
 $$\int \frac{1}{3x+2}$$
It seems the correct way to solve it is by choosing $u=3x+2$.
So
$$\begin{align}u &= 3x + 2 \\
\frac{du}{dx} &= 3 \\
dx &= \frac{1}{3}du \end{align}$$
and so on the answer comes down to $\frac{1}{3}\ln(3x+2)$
My question is, why do I need to choose it specifically this way:
$ \frac{du}{dx} = 3$?
If I choose $ \frac{dx}{du} = 3$, I get $dx=3du$ , but it gives me an answer different from the above.
How do I choose which one I use as a denominator and nominator for my u substitution?
Thank you.
Comment: $\frac{du}{dx} = 3$ comes from differentiating $u=3x+2$ with respect to $x$.
Comment: It's a bad idea to omit the differentials from the integral, especially when you are just learning how to change variables.  Here you have $\int \frac {dx}{3x+2}$, I assume, so letting $u=3x+2$ we get $du=3dx$ and our integral becomes $\frac 13\times \int \frac {du}u=\frac 13\times \ln |u|+C=\frac 13\times \ln |3x+2|+C$.
Comment: You aren't "choosing" $\dfrac{du}{dx} = 3$.  It's forced by the fact that $u = 3x+2$, which is what peterwhy is saying.
Answer:
We want to  simplify  the  denominator and  set $u=u(x)=3x+2$. Here we  consider  $u=u(x)$ being a function in  $x$.
  \begin{align*}
u&=3x+2\\
\color{blue}{\frac{du}{dx}}=\frac{d}{dx}u(x)&=\frac{d}{dx}(3x+2)\color{blue}{=3}
\end{align*}
  On the other hand if we consider $x=x(u)$ as function in $u$ we have
  \begin{align*}
x&=\frac{1}{3}(u-2)\\
\color{blue}{\frac{dx}{du}}=\frac{d}{du}x(u)&=\frac{d}{du}\left(\frac{1}{3}u-\frac{2}{3}\right)\color{blue}{=\frac{1}{3}}
\end{align*}
  So, it is not reasonable to set $\frac{dx}{du}=3$.

Note: It's advisable to write $\int\frac{\color{blue}{dx}}{3x+2}$ which besides some other aspects indicates that $x$ is the integration variable.
Comment: @user603864: Correct.
Comment: So for u subs I can always use the du/dx ?
Comment: I see, thank you very much. This should help my performance on the  course!
Comment: @user603864: You're welcome.
Answer: You are incorrect in saying: $\frac{dx}{du} = 3$
You don't "choose" this.
This is a direct result of what your u-sub is.
If we let $u = 3x+2$, then differentiating both sides, we get:
$du=3 dx$
If you wanted t o have $\frac{dx}{du}$, following the equation, this must equal $1/3$, not $3$.


Probability of event depending on a variable with a given distribution

Question: Let $A$ be an event that happens with probability $1-\alpha$, where $\alpha$ has the density function $f_\alpha(x)=3(1-x)^2$ for $0\leq x \leq 1$.
Thinking analogous with the discrete case*, I came up with $$P(A)=\int_0^1(1-x)\cdot 3(1-x)^2\,dx=\frac{3}{4}.$$
Is this correct? In case, how do I show it more rigorously?
*(The probability that $\alpha=x$ is $3(1-x)^2\,dx$, so $P(\alpha=x\cup A)=(1-x)\cdot3(1-x)^2\,dx$. Integrate over $x$ to get the result.)
Answer: You've done everything correctly, so let's just formalize.
$$
P(A | \alpha) = 1 - \alpha \\
P(\alpha = x) = 3(1-x)^2: x \in [0,1] \\
P(A, \alpha = x) = P(A | \alpha = x) \cdot P(\alpha = x) = 3(1-x)^3: x \in [0,1] \\
$$
I think part of your confusion is that the first equality is a probability mass function (which can really be interpreted as "The probability A occurs given alpha is...") and the latter two probability density functions, which in order to give probabilistic interpretations require integration, as you have done.
What you have done in this integral is marginalized the distribution, removing $\alpha$ from the distribution through integration, to arrive at the marginal distribution,
$$
P(A) = \int_0^1 P(A, \alpha=x)dx.
$$
Comment: I'm sorry, but I don't think this really answers my question (it might be just me, though). What I was wondering about was more in the direction of how the result follows from axioms and definitions.

It might be that I ask for too much, that you would have to know more about the treatment in the book I use, etc. I'm not sure.
Comment: No problem G.  I was trying to rewrite your calculation in such a way that the reasoning was more clear.  The first two lines are a formulation of the problem in two distributions, one of which is conditional.  The third line follows from the definition of conditional probability, $P(A|B) = P(A,B)/P(B)$.  The final line, the marginalization, follows from the axiom of probability which dictates that the probability of a disjoint union of events is equal to the sum of the probability of the individual events.  Of course this is the continuous consequence of the axiom *waves hands*.
Comment: Although this certainly makes the solution more rigorous, part of it still appears problematic: in trying to apply your definition of conditional probability, $P(B)$ will be zero.
Comment: I don't really see this as a problem for several reasons.  First off, there's no reasonable interpretation of $P(A|B)$ when $P(B) = 0$.  Secondly, when our goal is to construct the marginal distribution, we are uninterested in the values of $B$ for which $P(B)=0$.  Thirdly, and pardon my informality but it's been a while since I took an analysis class, it's my understanding that a probability density function is really an equivalence class of functions under the equivalence relation $\int (f-g)d_{mu} = 0$, so because ${1}$ has Lebesgue measure zero we can say $f_{\alpha}(1) = 53$, and move on.


why am I getting error on compile time in magento 2

Question: I am having this error while executing the setup:di:compile command
$ php bin/magento s:d:c
PHP Fatal error:  Uncaught Error: Cannot instantiate interface Symfony\Component\Console\Output\OutputInterface in vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php:116
Stack trace:
#0 vendor/magento/framework/ObjectManager/Factory/Compiled.php(108): Magento\Framework\ObjectManager\Factory\AbstractFactory->createObject('Symfony\\Compone...', Array)
#1 vendor/magento/framework/ObjectManager/ObjectManager.php(70): Magento\Framework\ObjectManager\Factory\Compiled->create('Symfony\\Compone...')
#2 vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(160): Magento\Framework\ObjectManager\ObjectManager->get('Symfony\\Compone...')
#3 vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(246): Magento\Framework\ObjectManager\F in vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 116

Fatal error: Uncaught Error: Cannot instantiate interface Symfony\Component\Console\Output\OutputInterface in vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php:116
Stack trace:
#0 vendor/magento/framework/ObjectManager/Factory/Compiled.php(108): Magento\Framework\ObjectManager\Factory\AbstractFactory->createObject('Symfony\\Compone...', Array)
#1 vendor/magento/framework/ObjectManager/ObjectManager.php(70): Magento\Framework\ObjectManager\Factory\Compiled->create('Symfony\\Compone...')
#2 vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(160): Magento\Framework\ObjectManager\ObjectManager->get('Symfony\\Compone...')
#3 vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(246): Magento\Framework\ObjectManager\F in vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 116

Answer: i thing the issue is due any custom module di.xml file In case your interface still won't be loaded, check your di.xml and validate that a preference is available.
i hope you understand what i want to explain you
for info check below link Abstraction-implementation mappings topic
https://devdocs.magento.com/guides/v2.3/extension-dev-guide/build/di-xml-file.html


Haskell infix function application precedence

Question: Let f x y = x * y. We can apply this function in two ways: f 5 6, or, using infix notation, 5 `f` 6. Do the operator rules apply to this last expression? What precedence will this application have? Is it just another form of function application, and so will it also have the highest precedence?
I suppose that the compiler sees this special form (due to `` and/or the name starting with a  letter(?)), and actually treats this as ordinary function application, instead of considering it an operator.
Comment: The Haskell 98 syntax allows you choose the precedence level, see http://www.haskell.org/onlinereport/decls.html#fixity for details.
Answer: The Haskell 98 Report has a section on Operator Applications that clears it up:

An operator is either an operator symbol, such as + or $$, or is an
  ordinary identifier enclosed in grave accents (backquotes), such as
  `op`. For example, instead of writing the prefix application op x y,
  one can write the infix application x `op` y. If no fixity declaration
  is given for `op` then it defaults to highest precedence and left
  associativity (see Section 4.4.2).

As indicated by the other answers, the Report also has a section on Fixity Declarations that allows you to define your own fixity, for example:
infixl 7 `op`

Answer: If no explicit fixity declaration is given, as e.g.
infixl 7 `quot`

a backticked infix function has the default fixity of infixl 9, so will be treated like any other infix operator with the same fixity.
Comment: `$` needs a very low precedence because otherwise you'd still need parentheses when applying a function to a non-atomic argument, `foo $ a + b*c` would be pretty pointless if it meant `(foo a) + (b*c)`. The purpose of `$` demands that practically everything else has higher precedence. A lot of the [relative] precedences, `*` binds tighter than `+` etc., are common in mathematics and also other programming languages. Apart from prior conventions, considerations what would be most convenient for the [expected] common cases will have played a role deciding the precedences.
Comment: In a way, it's arbitrary of course. But since having it `infix` doesn't allow chaining without parentheses, it's more convenient to have a direction of associativity. Right-associativity is rarer, so `infixl` is the "least surprising" choice. The precedence level of 9 is closest to prefix application precedence, hence that changes the least in comparison to prefix application. I wasn't there when it was decided, but I think the idea is that `infixl 9` was chosen with the expectation that it is most convenient and causes least surprise.
Comment: Why does it default to infixl 9? Is there any reason behind this choice, or is it arbitrary?
Comment: I see, but what about things like `!!` and `$`. Is there any reason given for why `!!` has higher precedence than `$`? Just trying to understand the reasoning for all the placements of the operators in the table: https://www.haskell.org/onlinereport/decls.html#fixity


Meu footer não aparece na primeira página quando meu pdf tem várias páginas, apenas a partir da segunda - Laravel 8 DomPDF

Question: Olá, boa noite. Criei um layout para estar gerando os meus relatórios em PDF, neste layout o header e o footer são fixos, porque quero que eles se repitam em todas as páginas. Entretanto, quando o PDF gera várias páginas o footer começa a aperecer apenas na segunda página. Um adendo, quando tenho apenas uma página o footer aparece corretamente. Já li algumas perguntas parecidas aqui na comunidade, mas nada que resolvesse este meu problema. Desde já, agradeço.
Versão do DomPDF que estou usando:
https://github.com/barryvdh/laravel-dompdf
Meu código:
<!DOCTYPE html>

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="/public/assets/css/style.min.css" rel="stylesheet">
    <title>Teste para Relatório</title>

                    TOPO !!!

                    Nº Lab.

                    Identificação Amostra

                    Argila

                    Areia

                    Silte

                %
                %
                %

            @foreach ($physical as $item)

                    {{ $item->numero_lab_physical_analyses }}

                        @foreach ($deep as $value)
                            @if ($value->deep_id === $value->id)
                                {{ $value->name }}
                            @endif
                        @endforeach

            @endforeach

                    BASE !!!

Answer: Devido à maneira como o dompdf analisa/renderiza documentos, qualquer posição absoluta/fixa de CSS ou conteúdo page_text() de script embutido é renderizado a partir da página em que são encontrados. Portanto, se esse conteúdo estiver na parte inferior do documento, ele será renderizado apenas na última página. Logo, a solução é colocar o footer logo abaixo do header.

<!DOCTYPE html>

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="/public/assets/css/style.min.css" rel="stylesheet">
    <title>Teste para Relatório</title>

                    TOPO !!!

                    BASE !!!

                    Nº Lab.

                    Identificação Amostra

                    Argila

                    Areia

                    Silte

                %
                %
                %

            @foreach ($physical as $item)

                    {{ $item->numero_lab_physical_analyses }}

                        @foreach ($deep as $value)
                            @if ($value->deep_id === $value->id)
                                {{ $value->name }}
                            @endif
                        @endforeach

            @endforeach


Gravar dados de array

Question: Existe algum método mais simplificado para isso, ou essa solução é a mais correta? Tem algumas tabelas que tenho diversos campos e aí fica um pouco mais trabalhoso. Minha dúvida é se tenho que declarar todas as variáveis para depois passar para o array ou existe alguma outra maneira de simplificar?
<?php
require '../../vendor/autoload.php';
use App\Controllers\Controller\Create;
$Create = new Create;
$campo = filter_input_array(INPUT_POST, FILTER_DEFAULT);

$prodOperadora = $campo['produtoOperadora'];
$prodGB = $campo['produtoGB'];
$prodPreco = $campo['produtoPreco'];
$prodPConv = $campo['produtoPrecoConv'];
$prodDesc = $campo['produtoDesc'];
$prodOferta = $campo['produtoOferta'];
$prodStatus = $campo['produtoStatus'];

$Dados = array(
    'produtoOperadora' => $prodOperadora,
    'produtoGB' => $prodGB,
    'produtoPreco' => $prodPreco,
    'produtoPrecoConv' => $prodPConv,
    'produtoDesc' => $prodDesc,
    'produtoOferta' => $prodOferta,
    'produtoStatus' => $prodStatus
);

if($Create->getSyntax('tb_produto', $Dados)):
    echo '

               Produto cadastrado com sucesso!

    ';
else:
    echo '

               Erro ao cadastrar no banco!

    ';
endif;

Comment: Calma, você passa os dados de um array para variáveis e depois das variáveis para um array? Por quê já não utiliza o array original, sem definir as variáveis?
Comment: Em cadastros simples, você pode colocar o name nos campos do formulário cadastro com o mesmo nome que está no banco de dados.
Answer: Tem duas maneiras que vejo pra fazer isso:
$dados = [];
foreach ($campo as $key => $value) {
    $dados[$key] => $value;
 }

ou
$dados = [
    'prodOperadora' => $campo['produtoOperadora'],
    'prodPreco' => $campo['produtoPreco'],
    // e assim por diante
];

Answer: Para simplificar seu código, você pode fazer isso:
<?php
require '../../vendor/autoload.php';
use App\Controllers\Controller\Create;
$Create = new Create; $campo = filter_input_array(INPUT_POST, FILTER_DEFAULT);
if($Create->getSyntax('tb_produto', $campo)):
    echo '
    Produto cadastrado com sucesso!
 ';
else:
    echo '
    Erro ao cadastrar no banco!
 ';
endif;

Gravar dados de array


definition about $\{ f = -\infty \}$

Question:

Can someone tell me why I can't define
$\{ f = -\infty \}$ as $\cup_{n \geq 1} \{ f <-n \}$?
I know I will miss all the $f > -n$, but don't we just care about touching $-\infty$?
Also, why we take the closure for the second one but not the first?
Comment: At most, as $\bigcap_{n\in\Bbb N}\{f<-n\}$. And, in fact, $X\setminus \bigcup_{n\in\Bbb N} \{f>-n\}=\bigcap_{n\in\Bbb N}\{f\le-n\}$.
Comment: Yeah but $\{f < -2 \} \subset \{f <-1\}$?
Answer: It's not the closure they are taking, but the complement.
The set $\bigcup_{n\in \mathbb N} \{ f < -n\}$ is the set of $x$ such that, for some $n$, we have $f(x) < -n$. What you want is that $f(x)< -n$ for every $n$, so the correct definition is $\bigcap_{n\in \mathbb N} \{ f < -n\}$, or, what is the same, the complement of $\bigcup_{n\in \mathbb N} \{ f \geqslant  -n\}$.
Answer: First, as you have already been told, you should have written $\bigcap_{n\in\mathbb N}\{f<-n\}$.
Besides, $\mathcal C$ denotes complement, not closure.
Comment: But won't I get a decending chain of $\dots \subset \{f<-2\} \subset \{ f < -1 \} $?
Comment: Yes, you will. And... ?
Comment: Wouldn't the intersection be just $\{f < -1 \}$? Sorry if this sounds crazy
Comment: @Hawk No, it wouldn't and, yes, it sounds crazy.
Comment: AH nvm, the intersection is the smallest set, it can't be the $\{ f < -1 \}$.
Comment: @Hawk Quite rIght!

definition about $\{ f = -\infty \}$


I want to make a button that you can hold down to make a variable go up repeatadly BUT

Question: i want you to have to hold the button down for a second for it to start...
I've tried a couple of things like
function startHold1() {
  setTimeout(function(){
    startHold1A = setInterval(func1(), 250) }, 1000)
}

function endHold1() {
  setTimeout(function(){
    clearInterval(startHold1A, 950)
  })
}

func1 basically adds 1 to a variable and displays it on the screen also i have a button that initiates startHold1 onmousedown and endHold1 onmouseup
I'm a super noob at code please help!
Comment: Does this answer your question? [HTML button- when hold the button it will repeat the action](https://stackoverflow.com/questions/53347492/html-button-when-hold-the-button-it-will-repeat-the-action)
Comment: ` setInterval(func1(), 250)` => ` setInterval(func1, 250)` (no `()` after `func`), see the linked question's answers.
Answer:

var setint  = '';
$(document).ready(function() {
var val = 0;
$('#hold').on('mousedown',function (e) {
   clearInterval(setint);
   val = 0;
   setint = setInterval(function () {
       $("#putdata").val(++val);
        console.log("mousehold");
   },50);
});
$('#hold').on("mouseleave mouseup", function () {
   val = 0;
   $("#putdata").val(val);
   clearInterval(setint);
});
});
<!DOCTYPE html>

<input type="text" id="putdata" />
<input type="button" value="mouse-hold" id="hold" />

Comment: adding jquery isn't always the best answer to a javascript question.
Comment: yes.. adding jquery isnt always the best answer.. but it is an answer.  and it answers the question at hand...

Last time i checked jquery is javascript.
feel free to add alternative answers.


Combine observables to one single promise

Question: I have an Angular app and I need to do several API calls and merge all of them into one promise. This is what I tried:
getPromiseFromAllDays(dates):Promise<any>
{
  return this.getAll(dates).map(
    (arrayOfResults) =>
  {
    return new Promise((resolve, reject) =>
    {
      resolve(arrayOfResults);
    });
  }).toPromise();
}

getAll(dates):Observable<any>[]
{
  return dates.map(
    (day) => return this.getOneDay(day).first();
  );
}

getOneDay(day):Observable<any>
{
   let path = 'days/'+day;
   return this.db.list(path) as FirebaseListObservable<any>;
}

Looking for a solution I tried to slice the code into traceable pieces.
I think I need the first(), cause FirebaseObservables wont complete without.
I have been able to get several Promises but I could combine all of them. I'm really unsure about the new Promise - toPromise construct. Are my response definitions correct?
Answer: This should achieve your desired result:
getPromiseFromAllDays(dates: any[]):Promise<any>
{
  return this.getAll(dates).toPromise();
}

getAll(dates: any[]):Observable<any>
{
  return Observable.from(dates).flatMap(
    (day) => return this.getOneDay(day);
  );
}

getOneDay(day):Observable<any>
{
   let path = 'days/'+day;
   return this.db.list(path) as FirebaseListObservable<any>;
}

What this does is it takes in the array of dates and transforms it into an Observable sequence of all of the date values. We then use a flatMap to switch to a new observable created from each of these dates. Because of the from operator we just return one Observable from getAll and then use the toPromise method on the resulting Observable inside of the getPromiseFromAllDays method.
Answer: Use forkJoin to send getOne simultaneously:
i = 1000;

function getOne(date) {
  i = i - 500;
  return Rx.Observable.timer(i).mapTo('Date is' + date);
}

function getAllDates(dates) {
  let obsList$ = dates.map(date => getOne(date));
  return Rx.Observable.forkJoin(...obsList$);
}

function getPromiseFromAllDays(dates) {
 return getAllDates(dates).toPromise();
}

getPromiseFromAllDays([1,2,3]).then(x=>console.log(x))

Comment: thank you, Im getting the desired data but i get [[x,x,],[],[x,x,x,x,x]] instead of [x,x,x,x,x,x]. do i need to flatten the array afterwards?
Comment: u can do        let arrays = x.reduce((acc,i)=>{
        acc.push(...i); return acc;
       }, []);
Comment: thank you, got it to work with: `getPromiseFromAllDays(dates) {
  return getAllDates(dates).map((res)=>{
    return Array.prototype.concat(...res)
  }).toPromise();
}`


Is there a Mapkit Annotation event when the pin is done animating?

Question: I am having some issues with my Mapkit and userlocation events. I need to call a method when the user's location is found, however, using [locationManager startUpdatingLocation]; causes the method to call too early for what I am trying to do.
Ideally, I would like to make a call once the animation of the user location's pin is completed. Is there any way to watch for that?
Answer: In the delegate of your locationManager (which conforms to the CLLocationManagerDelegate protocol), implement your method call inside:
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation;

This will be called once the location is resolved.  You may want to make sure it is within your desired accuracy tolerances before taking action:
if (newLocation.accuracy <= locationManager.desiredAccuracy ){

You may want to perform your action after a delay to allow the animation for the current location to complete.  Apple seems to typically uses between 0.5 and 0.25 for animation durations.


Operation not supported. Unknown error: 0x80070057 - when tryng to run Roslyn source generator

Question: I have created a Roslyn source code generator.

Right-click project in Solution Explorer
Edit project
Inside <PropertyGroup> add <IsRoslynComponent>true</IsRoslynComponent>
Right-click project in Solution Explorer
Properties
Debug settings
Create new profile
Set type to "Roslyn Component"
Select a project that consumes the source generator
Run

---------------------------
Microsoft Visual Studio
---------------------------
Unable to start debugging.

Operation not supported. Unknown error: 0x80070057.
---------------------------
OK
---------------------------

Answer: The problem was that I had since right-clicked the consuming project and chosen "Unload project", which causes the above error upon running the project.
To fix it

Right-click project in Solution Explorer
Properties
Debug settings
Click the profile you made for your Roslyn debugging
In the dropdown, select the consuming project


Proving $u = \text{prox}_f(x) \iff x - u \in \partial f(u)$

Question: I want to show that $u = \text{prox}_f(x) \iff x - u \in \partial f(u)$, where $f$ is a proper, convex and lower semicontinuous function where $\partial$ is the subdifferential and
$$
\text{prox}_f(x)
= \text{argmin}_{y \in \mathbb R^d} \left\{ f(y) + \frac{1}{2} \| y - x \|_2^2 \right\}
$$
Here's my attempt.
If $u = \text{prox}_{f}(x)$, then
$$
f(u) + \frac{1}{2} \| u - x \|_2^2
\le f(y) + \frac{1}{2} \| y - x \|_2^2
\qquad \forall y \in \mathbb R^d
$$
and thus
$$
\frac{1}{2} \left(\| u - x \|_2^2 - \| y - x \|_2^2\right)
\le f(y) - f(u)
\qquad \forall y \in \mathbb R^d
$$
On the other hand,
$$
\partial f(u)
= \{ d \in \mathbb R^d : f(y) - f(u) \ge \langle d, y - u \rangle \ \forall y \in \mathbb R^d \}
$$
so, $x - u \in \partial f(u)$ means that
$$
f(y) - f(u) \ge \langle x - u, y - u \rangle
$$
Unfortunately,
$$
\langle x - u, y - u \rangle
\ne \frac{1}{2} \left(\| u - x \|_2^2 - \| y - x \|_2^2\right)
= \frac{\| u \|^2 - \| y \|^2}{2} + \langle x, y - u \rangle.
$$
What have I done wrong?
Comment: No, you need a two sided inclusion. If you want to prove that $a=b$ then we need $a\leq b,\, b\leq a$. However, $0\leq 2$ and $1\leq 2$ are both lower bounds of $2$, they are both correct, and they do not imply anything about the relation between $0$ and $1$.
Answer: Use Fermat's rule:
$$0\in \partial_u(f(u) + \frac{1}{2}\|u-x\|_2^2) = \partial f(u) + u-x\implies x-u\in\partial f(u)$$
The trick, then, is to justify the fact that we distributed the subdifferential operator through the sum. This is justified since the domain of $\frac{1}{2}\|\cdot\|_2^2$ is the whole space, assuming that $f\in\Gamma_0$.
Comment: I think it's more accurate to state that since $f, g$ are proper, convex and lower semicontinuous functions then $\partial (f(u)+g(u))=\partial f(u) + \partial g(u)$ where $g(u)=\frac{1}{2}\|x-u\|^2$
Comment: Even if the functions $f$ and $g$ belong to $\Gamma_0$, it's not the case that you can distribute the subdifferential, you're wrong if that's your claim. It comes from domain qualification conditions which are trivially satisfied because $\frac{1}{2}\|\cdot\|^2$ has full domain. Of course everything I am writing is under the premise that $f\in\Gamma_0$, I took this to be obvious and not worth writing.
Comment: I beg the differ. While it's not an if and only if statement, for $f, g \in \Gamma_0$ where $ri(dom(f)) \bigcap ri(dom(g)) \neq \emptyset$ we can decompose the subdifferential. This is exactly the case for the functions $f,g$ in the question. However if a squared norm would not be in  $\Gamma_0$, even having the entire space as domain would not allow this decomposition. In that case $\partial (f+g) \supseteq \partial f +\partial g$ only.
Comment: The condition $ri(dom(f))\cap ri(dom(g))\neq\emptyset$ is exactly the domain qualification condition I am talking about. It is trivially satisfied with the euclidean norm squared. This is what I've said, sorry if I omitted the subscript on the norm, is that what you disagree with? That is should $\|\cdot\|_2^2$? I thought it was obvious to be honest. I was assuming both $f$ and $g$ are in $\Gamma_0$, I didn't write it because I took to be obvious. By the way, the phrase is "I beg *to* differ".


why the derivative of a conformal mapping must be nonzero?

Question: I read that for a conformal map to preserve angles it is required to a have a nonzero derivative. I'm trying to convince myself that this is always true in a simple but detailed way. So far, I've followed the video Conformal Mapping in Complex Variables and the crucial step around minute 11 is that $arg(\frac {df} {dz_A} ) = arg (\frac {df} {dz_B})$ and it is said that the argument of zero is undefined, so the derivative must be nonzero.
I'm trying to visualize more in detail what is really happening in some simple examples.
Let's say we have to curves $z = t + i t$ and $z = t - i t$ meeting in the origin at an angle of $\frac \pi 2$ in a x-y plane (as usual x it the real part and y the imaginary part).
I can see that applying a map $w = z^2$ they transform into two curves along the positive and negative y axis with a cusp in the origin where the derivative (or the angle) is not defined.
So my understanding is that to represent the transformed curve in the w complex plane we need to invert the f mapping and the new angles are related to the derivative of the inverse function, but the inverse of the derivative is not defined when the derivative is zero and so the angles of the transformed curves (transformed by the mapping $w = f(z)$) represented in the w complex plane have a sort of a discontinuity and therefore I think that those transformed curves have a cusp or their angles are not defined in that point..
Does my reasoning make sense?
Anyway, I can also see that if I transform the two above said curves $z = t + i t$ and $z = t - i t$ by a map $w = f(z) = z^3$ - that should not be conformal at $t = 0$ since $f'(0) = 0$ - nonetheless I get these two graphs from Wolfram conformal mapping (follow the link to get the second picture below, for example)

Is there something wrong in the way I use the above widget from Wolfram or is it true that in some (even if rare) cases a map with a zero derivative in a certain point can preserve the angle between two curves intersecting at the point?
Comment: Very important that you have actual holomorphic function; by a translation of function, we can say $g(0)=0$   WLOG. Then the Taylor series has a first nonzero term. If this is $a_1 z$  it works. If  the linear coefficient is zero, there is some $k \geq 2$ such that $g(z) = z^k h(z)$  near the origin, where $h(0) = C \neq 0,$ and $g(z) \approx C z^k$  near the origin
Comment: added: the conclusion is that zero derivative implies not injective near the origin
Comment: Found an [interesting explanation](http://reedbeta.com/blog/conformal-texture-mapping/#invertibility-and-critical-points) with the **visualization**: "*In fact, graphing $z^n$ gives you $n$ copies of the plane, squished together into wedges around the origin. All of the copies are conformal mappings—but their scale becomes increasingly extreme as you approach the origin, and the function is not strictly conformal at the origin.*" . I have to study the Shader language to get the correct visual representation, starting from $z^2$ as shown [here](https://www.shadertoy.com/view/XdSfWW)
Answer: Let $f:U\subset \Bbb C\to \Bbb C$ a holomorphic function and $z_0\in U$, where $U$ is a region. Suppose $f'(z_0)=0$. This means that
$$\lim_{z\to z_0} \frac{f(z)-f(z_0)}{z-z_0}=0\iff f(z)-f(z_0)\ll z-z_0,$$ as $z\to z_0.$
The final result states that the difference of images of points $z,z_0$ vanishes much faster than the difference of the points, hence the vector $f(z)-f(z_0)$ has an argument in essence undefined relative to $z-z_0$ as $z\to z_0$. Therefore it is impossible for $f'(z_0)$ to rotate $z-z_0$ till $f(z)-f(z_0).$
On the contrary, if $f'(z_0)\neq 0,$ the limit above would equivalently gives
$$f(z)-f(z_0)\sim f'(z_0)(z-z_0),$$ as $z\to z_0,$ which clearly indicates that $f(z)-f(z_0)$ is approximately the rotation of $z-z_0$ at angle $\arg f'(z_0)$.
Comment: Thank you for your time, and I'm glad that this answer has reignited my interest in mathematics after nearly three years...
Comment: you are welcome! I strongly recommend you to read deeply differential geometry and complex analysis to get your interest on fire!


Consulta SQL - ORA-01795

Question: Estou precisando fazer um relatório a partir de uma consulta ao banco de dados. O problema é que a consulta retorna mais de 1000 expressões e apresenta o seguinte erro:

ORA-01795: o número máximo de expressões em uma lista é de 1000.

Segue a query:
        string idsAcoes = string.Join(",\n", listaAcoes.Select(a => a.IdAcao));

        var sql = "SELECT l.LOGM_CD_USUA_OPERACAO, "
                + "  l.LOGM_IN_OPERACAO, "
                + "  l.LOGM_DT_OPERACAO, "
                + "  l.LOGM_TX_DADO_INICIAL, "
                + "  l.LOGM_TX_DADO_FINAL "
                + "FROM LOG_GESTAO_MUDANCA l, ACAO_MUDANCA am "
                + "WHERE l.LOGM_DS_OPERACAO = 'AcaoMudanca' "
                + "  AND l.LOGM_TX_DADO_FINAL LIKE '<AcaoMudanca>%<Id>'||am.ACMU_SQ_ACAO_MDNC||'</Id>%<DataPrazo>%' "
                + "  AND am.ACMU_SQ_ACAO_MDNC IN (" + idsAcoes + ") ";

        resultado = _session
             .CreateSQLQuery(sql)
             .List<dynamic>();

Comment: Pergunta relacionada: https://pt.stackoverflow.com/questions/249313/como-resolver-o-erro-ora-01795-n%C3%BAmero-m%C3%A1ximo-de-express%C3%B5es-no-codeigniter
Comment: Melhor cenário seria uma subquery no lugar do IN trazendo os IDs da tabela de origem dele. A 'listaAcoes' traz os IDs de onde? É um select no BD mesmo?
Comment: Eu recebo como parâmetro no método, mas a lista vem de uma consulta no BD.
Answer:
Crie uma tabela temporária para conter os IDs desejados;
Modifique sua query para referenciar a tabela temporária.

Exemplo:
CREATE PRIVATE TEMPORARY TABLE ora$ptt_t_IDS (
    ID         NUMBER
);

Declaração WHERE modificada:
[...] AND am.ACMU_SQ_ACAO_MDNC IN (SELECT ID FROM ora$ptt_t_IDS);

Referência:
Private Temporary Tables in Oracle Database 18c
https://oracle-base.com/articles/18c/private-temporary-tables-18c
Comment: @GabrielGC talvez se seu código for modificado para consultar diretamente as fontes relevantes do conteúdo que, no lado C#, sofrem `string.join()`; a limitação de 1000 parâmetros, porém, é real e não modificável. Outra possibilidade é a geração da lista via `UNION` (`IN (1..1000) UNION (1001..2000) UNION [...]`), mas esta solução é tão subpar que só menciono como exercício mental.
Comment: Existe alguma outra solução em que não seja necessário criar essa tabela temporária? Pois imagino que teria que criar em todos os ambientes (teste, desenvolvimento, homologação e produção)
Answer: Se você criar um parâmetro do tipo CLOB e atribuir sua lista como sendo o valor deste parâmetro, você pode dividir esta lista em tempo de execução, através de uns truques com CONNECT BY e não haverá a necessidade de criar uma tabela temporária...
Exemplo:
SELECT TO_NUMBER(RPAD(lst.nro, INSTR(lst.nro || ',', ',') - 1)) valor
  FROM (SELECT SUBSTR(:p_acoes, INSTR(',' || :p_acoes, ',', 1, ROWNUM)) nro
          FROM dual
       CONNECT BY ROWNUM <= LENGTH(:p_acoes) - NVL(LENGTH(REPLACE(:p_acoes, ',')), 0) + 1) lst

Depois você colocar no seu IN essa query...
SELECT l.logm_cd_usua_operacao,
       l.logm_in_operacao,
       l.logm_dt_operacao,
       l.logm_tx_dado_inicial,
       l.logm_tx_dado_final
  FROM log_gestao_mudanca l, acao_mudanca am
 WHERE l.logm_ds_operacao = 'AcaoMudanca'
   AND l.logm_tx_dado_final LIKE
       '<AcaoMudanca>%<Id>' || am.acmu_sq_acao_mdnc || '</Id>%<DataPrazo>%'
   AND am.acmu_sq_acao_mdnc IN (SELECT TO_NUMBER(RPAD(lst.nro, INSTR(lst.nro || ',', ',') - 1)) valor
                                  FROM (SELECT SUBSTR(:p_acoes, INSTR(',' || :p_acoes, ',', 1, ROWNUM)) nro
                                          FROM dual
                                       CONNECT BY ROWNUM <= LENGTH(:p_acoes) - NVL(LENGTH(REPLACE(:p_acoes, ',')), 0) + 1) lst)

Comment: @BrunoWarmling exato - e o autor da pergunta especificou a tag C# em sua pergunta, por isso o comentário.
Comment: Vou testar essa solução e dou o retorno..
Comment: Pesquisando sobre, eu percebi que o mais indicado nessa situação é criar uma tabela temporária. Em questão de performance sabe me falar se tem um diferença significativa?
Comment: Depende de como você vai popular essa tabela temporária... Teria que testar. Além do mais, com tabela temporária você irá precisar ter uma transação. O que não é realmente necessário, já que você está fazendo apenas uma consulta. Pensando um pouco em segurança, esse exemplo poderia ser executada por um usuário que tem somente acesso à leitura.
Comment: @BrunoWarmling Existem 2 problemas - não com sua abordagem, mas com a implementação dos drivers para .NET (System.Data.OracleClient e Oracle.DataAccess). Payloads grandes geram ORA-06550/PLS-00172. O primeiro é o limite do parser (4kb) em queries, ou o limite em stored procedures (32kb). Referência: https://stackoverflow.com/questions/3557995/issues-calling-stored-procedure-from-c-sharp-with-large-clob
Comment: @OnoSendai Sim, mas esses são problemas da implementação em c# e não da query. O erro `ORA-06550/PLS-00172` só ocorre se você passar um maior que 4kb para um parâmetro do tipo `varchar`. Neste caso o parâmetro no c# deve ser definido como `CLOB`, assim como mencionado na resposta. E outra, que não é uma boa pratica concatenar "valores" de parâmetros no meio da query e sim fazer isso através de bindings.
Answer: Engane o Oracle.
Você pode pegar de mil em mil e juntar os vários INs com ORs, já que o Oracle não deixa pegar mais de mil,
const int qtde = 1000;

var sql = "SELECT l.LOGM_CD_USUA_OPERACAO, "
        + "  l.LOGM_IN_OPERACAO, "
        + "  l.LOGM_DT_OPERACAO, "
        + "  l.LOGM_TX_DADO_INICIAL, "
        + "  l.LOGM_TX_DADO_FINAL "
        + "FROM LOG_GESTAO_MUDANCA l, ACAO_MUDANCA am "
        + "WHERE l.LOGM_DS_OPERACAO = 'AcaoMudanca' "
        + "  AND l.LOGM_TX_DADO_FINAL LIKE '<AcaoMudanca>%<Id>'||am.ACMU_SQ_ACAO_MDNC||'</Id>%<DataPrazo>%' "
        + "  AND ( ";

string or = string.Empty;
for (int i = 0; i < listaAcoes.Count; i += qtde)
{
    var milItens = listaAcoes.Select(s => s.IdAcao).Skip(i).Take(qtde);
    string separadosPorVirgula = string.Join(',', milItens);
    sql += or + "am.ACMU_SQ_ACAO_MDNC IN (" + separadosPorVirgula + ")";
    or = " OR ";
}

sql += " )";

resultado = _session
     .CreateSQLQuery(sql)
     .List<dynamic>();

Consulta SQL - ORA-01795


How to assess goodness of fit of a particular nonlinear model?

Question: I have a nonlinear model $y=\Phi(f(x,a)) + \varepsilon$, where $\Phi$ is the cdf of the standard normal distribution and f is nonlinear (see below). I want to test the goodness of fit of this model with parameter $a$ to my data $(x_1,y_1),(x_2,y_2),\dots,(x_n,y_n)$, after having used maximum likelihood estimation to find $a$. What would be an appropriate test? I would like to use this test to label a bad fit as bad and determine whether more data should be collected.
I've looked into using deviance, which compares this model against the saturated model, with its corresponding test of goodness of fit using the $\chi^2_{n-1}$ distribution. Would this be appropriate? Most of what I have read about deviance applies it to GLMs, which is not what I have. If the deviance test is appropriate, what assumptions need to hold to make the test valid?
Update: $f = \frac{x-1}{a\sqrt{x^2+1}}$ for $x>1,a>0$ in case this helps.
Comment: The answer depends on the purpose of the analysis and on the underlying probability model you have used; there is no unique or best mathematical answer.  For example, we would measure goodness of fit differently for a model of the form $y=\Phi(f(x,a)+\varepsilon)$ than for one of the form $y=\Phi(f(x,a))+\varepsilon$ (with iid errors $\varepsilon$).
Comment: Is your target variable $y \in {0,1}$ or is it continuous?  If the former, then you could frame the model as $p(y=1) = \Phi(f(x,a))$ instead of having the additive error term, and compare predicted with actual $y=0$ and $y=1$ to get the true and false positive rates, or compare to a baseline model where $p(y=1) = \bar{y}$, or deviance, or several other alternatives.  If the latter, what's the distribution you're assuming for the residual?
Comment: Voting to close because the request for clarification has gone unanswered.
Comment: Thanks. I've clarified my question. I'm aware that there is no best answer, however, I'd still like to know whether deviance is appropriate for testing goodness-of-fit here, and if not, what is another test that would be appropriate for marking a fit as very poor and saying more data needs to be collected (assuming the model is correct) or saying the model does not describe the data.
Answer: Use the "npcmstest" package in library "NP" if you are using the R platform. Warning: The function may take several minutes to evaluate your model.
You can also consider an information-theoretic comparison of the response distribution and the predictive distribution (i.e. KL divergence, cross-entropy, etc.)
Comment: It seems that method requires a model from either `lm` or `glm`. How would this work for a nonlinear model? (Yes, I'm using R.) I've added what $f$ is to my question in case that helps.
Comment: @are you using `gam` or the like (`mgcv` package)? If not, you should check it out.
Answer: Here's how I would do it, basically a likelihood ratio test.  But remember they "key" to understanding a goodness of fit test, is to understand the class of alternatives that you are testing against.  Now we have the likelihood for each individual data point as:
$$p(y_i|x_i,a,I)=g(\epsilon_i)=g(y_i-f_i)$$
Where $g(\epsilon)$ is the likelihood of the error term in your model, and $f_i=\frac{x_i-1}{a\sqrt{x^2_i+1}}$ is the model prediction for the ith data point, given $x_i$ and $a$.  Now for each data point $(x_i,y_i)$ we can choose an $a$ such that $f_i=y_i$ - the "saturated model" as you call it.  So you're $\chi^2$ test is appropriate here, if you only want to test to alternatives within the class of those with the same error likelihood, $g(\epsilon)$, and you have independence of each of the likelihoods (i.e. knowing another $x_j,y_j$ would be of no help in predicting $y_i$, given $a$).
Comment: This is not going to work, since the degrees of freedom of the likelihood ratio test grows as $O(n)$ for the saturated model.
Answer: In linear regression context, goodness of fit testing is often conducted against a more complicated alternative. You have a linear regression -- throw in some polynomial terms to test if the linear form is enough. Since you already have a nonlinear functional form, the complicated alternative you would need to consider would have to be that of non-parametric regression. I won't try to provide an introduction to the topic, as it requires a mindset of its own, and it is worth a separate proper introduction. For the test of parametric vs. nonparametric regressions, Wooldridge (1992) or Hardle and Mammen (1993), they do very similar things. Hardle also wrote a great book on the topic.


Finding an original rectangle's dimensions from rotation and bounding box dimensions

Question: In AS3, I have a Sprite that has a Z axis rotation applied.
How do I calculate that Sprite's dimensions (it's original size) from Sprite.rotationZ and Sprite.getRect(...)?
Answer: sprite.width and sprite.height on sprite.rotationZ = 0 would give you the original size.
Comment: Haha! Yeah that's my intermediate hack.

I'd rather do it with the maths though, then I'll have learnt something universal rather than an AVM shortcut...
Comment: Seconds thoughts, it's obviously impossible! You win.
Answer: antpaw's answer is best / easiest.  It can also be done without ever seeing it visually if you switch the rotationZ back once you get your width and height, like so
var rotZ:Number = mySprite.rotationZ;
mySprite.rotationZ = 0;
var w:Number = mySprite.width;
var h:Number = mySprite.height;
mySprite.rotationZ = rotZ;

To do this mathematically you could look at this SO post and do the reverse.
Comment: The typical bounding box edge formula won't reverse because it's missing length plus missing length.

I'm sure there is something that'll look a bit like it though...


strongswan ikev2 with debian. EAP authentication failed. loading EAP_MSCHAPV2 method failed

Question: I can't get Strongswan to run on my Debian machine. I've already done a tutorial to get it to run on a Ubuntu machine but it seems impossible to me to get it to run on my Debian machine. I actually did everything like in the tutorial, except the part with the firewall at the bottom, because I don't have it on my server.
When I try to connect to my server, I get an error message that the user data is wrong. I have already created and installed three different certificates, tried different users but always get the message with the wrong user information. What am I doing wrong?
MYIPADDRESS = My Debian Server IP
Every cert file I created I appended "-vpn2" to the name.
ipsec statusall:
Status of IKE charon daemon (strongSwan 5.5.1, Linux 3.10.0-957.1.3.el7.x86_64, x86_64):
  uptime: 42 seconds, since Sep 23 03:30:26 2019
  malloc: sbrk 2699264, mmap 0, used 455168, free 2244096
  worker threads: 11 of 16 idle, 5/0/0/0 working, job queue: 0/0/0/0, scheduled: 1
  loaded plugins: charon aesni aes rc2 sha2 sha1 md5 random nonce x509 revocation constraints pubkey pkcs1 pkcs7 pkcs8 pkcs12 pgp dnskey sshkey pem openssl fips-prf gmp agent xcbc hmac gcm attr kernel-netlink resolve socket-default connmark stroke updown
Virtual IP pools (size/online/offline):
  10.10.10.0/24: 254/0/0
Listening IP addresses:
  MYIPADDRESS
Connections:
   ikev2-vpn:  %any...%any  IKEv2, dpddelay=300s
   ikev2-vpn:   local:  [MYIPADDRESS] uses public key authentication
   ikev2-vpn:    cert:  "CN=MYIPADDRESS"
   ikev2-vpn:   remote: uses EAP_MSCHAPV2 authentication with EAP identity '%any'
   ikev2-vpn:   child:  0.0.0.0/0 === dynamic TUNNEL, dpdaction=clear
Security Associations (0 up, 0 connecting):
  none

ipsec.secrets:
# This file holds shared secrets or RSA private keys for authentication.

# RSA private key for this host, authenticating it to any other host
# which knows the public part.

# this file is managed with debconf and will contain the automatically created $
#include /var/lib/strongswan/ipsec.secrets.inc
: RSA "server-key-vpn2.pem"
user1 : EAP "hallo1234"
user2 : EAP "hallo1234"

ipsec.conf:
config setup
    charondebug="ike 1, knl 1, cfg 2"
    uniqueids=no

conn ikev2-vpn
    auto=add
    compress=no
    type=tunnel
    keyexchange=ikev2
    fragmentation=yes
    forceencaps=yes
    dpdaction=clear
    dpddelay=300s
    rekey=no
    left=%any
    leftid=MYIPADDRESS
    leftcert=server-cert-vpn2.pem
    leftsendcert=always
    leftsubnet=0.0.0.0/0
    right=%any
    rightid=%any
    rightauth=eap-mschapv2
    rightsourceip=10.10.10.0/24
    rightdns=126.96.36.199,22.214.171.124
    rightsendcert=never
    eap_identity=%identity

Exportet Cert:
 cat /etc/ipsec.d/cacerts/ca-cert-vpn2.pem

Log from strongswan android app (user2 ; hallo1234):
Sep 23 09:43:37 00[DMN] +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Sep 23 09:43:37 00[DMN] Starting IKE service (strongSwan 5.8.0dr2, Android 9 - PKQ1.181121.001/2019-08-01, Mi 9T Pro - Xiaomi/raphael_eea/Xiaomi, Linux 4.14.83-perf-g7723fb1, aarch64)
Sep 23 09:43:37 00[LIB] loaded plugins: androidbridge charon android-log openssl fips-prf random nonce pubkey chapoly curve25519 pkcs1 pkcs8 pem xcbc hmac socket-default revocation eap-identity eap-mschapv2 eap-md5 eap-gtc eap-tls x509
Sep 23 09:43:37 00[JOB] spawning 16 worker threads
Sep 23 09:43:37 07[IKE] initiating IKE_SA android[15] to MYIPADDRESS
Sep 23 09:43:37 07[ENC] generating IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(REDIR_SUP) ]
Sep 23 09:43:37 07[NET] sending packet: from 10.105.74.60[44288] to MYIPADDRESS[500] (716 bytes)
Sep 23 09:43:37 10[NET] received packet: from MYIPADDRESS[500] to 10.105.74.60[44288] (38 bytes)
Sep 23 09:43:37 10[ENC] parsed IKE_SA_INIT response 0 [ N(INVAL_KE) ]
Sep 23 09:43:37 10[IKE] peer didn't accept DH group ECP_256, it requested MODP_3072
Sep 23 09:43:37 10[IKE] initiating IKE_SA android[15] to MYIPADDRESS
Sep 23 09:43:37 10[ENC] generating IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(REDIR_SUP) ]
Sep 23 09:43:37 10[NET] sending packet: from 10.105.74.60[44288] to MYIPADDRESS[500] (1036 bytes)
Sep 23 09:43:38 12[NET] received packet: from MYIPADDRESS[500] to 10.105.74.60[44288] (592 bytes)
Sep 23 09:43:38 12[ENC] parsed IKE_SA_INIT response 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(MULT_AUTH) ]
Sep 23 09:43:38 12[CFG] selected proposal: IKE:AES_CBC_128/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/MODP_3072
Sep 23 09:43:38 12[IKE] local host is behind NAT, sending keep alives
Sep 23 09:43:38 12[IKE] remote host is behind NAT
Sep 23 09:43:38 12[IKE] sending cert request for "CN=VPN root CA"
Sep 23 09:43:38 12[IKE] establishing CHILD_SA android{15}
Sep 23 09:43:38 12[ENC] generating IKE_AUTH request 1 [ IDi N(INIT_CONTACT) CERTREQ CPRQ(ADDR ADDR6 DNS DNS6) N(ESP_TFC_PAD_N) SA TSi TSr N(MOBIKE_SUP) N(NO_ADD_ADDR) N(MULT_AUTH) N(EAP_ONLY) N(MSG_ID_SYN_SUP) ]
Sep 23 09:43:38 12[NET] sending packet: from 10.105.74.60[45106] to MYIPADDRESS[4500] (464 bytes)
Sep 23 09:43:38 08[NET] received packet: from MYIPADDRESS[4500] to 10.105.74.60[45106] (96 bytes)
Sep 23 09:43:38 08[ENC] parsed IKE_AUTH response 1 [ IDr EAP/FAIL ]
Sep 23 09:43:38 08[IKE] received EAP_FAILURE, EAP authentication failed
Sep 23 09:43:38 08[ENC] generating INFORMATIONAL request 2 [ N(AUTH_FAILED) ]
Sep 23 09:43:38 08[NET] sending packet: from 10.105.74.60[45106] to MYIPADDRESS[4500] (80 bytes)

Edit:
I just tried this command:

ipsec up ikev2-vpn

unable to resolve %any, initiate aborted
tried to checkin and delete nonexisting IKE_SA
establishing connection 'ikev2-vpn' failed

car /var/log/syslog

Sep 23 04:17:42 Minecraft charon: 07[NET] received packet: from 126.96.36.199[38454] to MYIPADDRESS[500] (716 bytes)
Sep 23 04:17:42 Minecraft charon: 07[ENC] parsed IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(REDIR_SUP) ]
Sep 23 04:17:42 Minecraft charon: 07[IKE] 184.108.40.206 is initiating an IKE_SA
Sep 23 04:17:42 Minecraft charon: 07[IKE] remote host is behind NAT
Sep 23 04:17:42 Minecraft charon: 07[IKE] DH group ECP_256 inacceptable, requesting MODP_3072
Sep 23 04:17:42 Minecraft charon: 07[ENC] generating IKE_SA_INIT response 0 [ N(INVAL_KE) ]
Sep 23 04:17:42 Minecraft charon: 07[NET] sending packet: from MYIPADDRESS[500] to 18.104.22.168[38454] (38 bytes)
Sep 23 04:17:42 Minecraft charon: 16[NET] received packet: from 126.96.36.199[38454] to MYIPADDRESS[500] (1036 bytes)
Sep 23 04:17:42 Minecraft charon: 16[ENC] parsed IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(REDIR_SUP) ]
Sep 23 04:17:42 Minecraft charon: 16[IKE] 184.108.40.206 is initiating an IKE_SA
Sep 23 04:17:42 Minecraft charon: 16[IKE] remote host is behind NAT
Sep 23 04:17:42 Minecraft charon: 16[ENC] generating IKE_SA_INIT response 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(MULT_AUTH) ]
Sep 23 04:17:42 Minecraft charon: 16[NET] sending packet: from MYIPADDRESS[500] to 22.214.171.124[38454] (592 bytes)
Sep 23 04:17:42 Minecraft charon: 05[NET] received packet: from 220.127.116.11[41118] to MYIPADDRESS[4500] (464 bytes)
Sep 23 04:17:42 Minecraft charon: 05[ENC] parsed IKE_AUTH request 1 [ IDi N(INIT_CONTACT) CERTREQ CPRQ(ADDR ADDR6 DNS DNS6) N(ESP_TFC_PAD_N) SA TSi TSr N(MOBIKE_SUP) N(NO_ADD_ADDR) N(MULT_AUTH) N(EAP_ONLY) N(MSG_ID_SYN_SUP) ]
Sep 23 04:17:42 Minecraft charon: 05[IKE] received cert request for "CN=VPN root CA"
Sep 23 04:17:42 Minecraft charon: 05[CFG] looking for peer configs matching MYIPADDRESS[%any]...220.127.116.11[user]
Sep 23 04:17:42 Minecraft charon: 05[CFG] selected peer config 'ikev2-vpn'
Sep 23 04:17:42 Minecraft charon: 05[IKE] EAP-Identity request configured, but not supported
Sep 23 04:17:42 Minecraft charon: 05[IKE] loading EAP_MSCHAPV2 method failed
Sep 23 04:17:42 Minecraft charon: 05[IKE] received ESP_TFC_PADDING_NOT_SUPPORTED, not using ESPv3 TFC padding
Sep 23 04:17:42 Minecraft charon: 05[IKE] peer supports MOBIKE
Sep 23 04:17:42 Minecraft charon: 05[ENC] generating IKE_AUTH response 1 [ IDr EAP/FAIL ]
Sep 23 04:17:42 Minecraft charon: 05[NET] sending packet: from MYIPADDRESS[4500] to 188.8.131.52[41118] (96 bytes)

cat /var/log/auth.log

Sep 23 03:55:13 Minecraft ipsec_starter[25750]: Starting strongSwan 5.5.1 IPsec [starter]...
Sep 23 03:55:13 Minecraft ipsec_starter[25750]: charon is already running (/var/run/charon.pid exists) -- skipping daemon start
Sep 23 03:55:13 Minecraft ipsec_starter[25750]: no netkey IPsec stack detected
Sep 23 03:55:13 Minecraft ipsec_starter[25750]: no KLIPS IPsec stack detected
Sep 23 03:55:13 Minecraft ipsec_starter[25750]: no known IPsec stack detected, ignoring!
Sep 23 03:55:13 Minecraft ipsec_starter[25750]: starter is already running (/var/run/starter.charon.pid exists) -- no fork done
Sep 23 03:55:57 Minecraft charon: 04[IKE] 22.214.171.124 is initiating an IKE_SA
Sep 23 03:55:59 Minecraft charon: 15[IKE] 18.104.22.168 is initiating an IKE_SA
Sep 23 03:55:59 Minecraft charon: 06[IKE] 18.104.22.168 is initiating an IKE_SA
Sep 23 03:57:10 Minecraft charon: 12[IKE] 188.8.131.52 is initiating an IKE_SA
Sep 23 03:57:10 Minecraft charon: 11[IKE] 184.108.40.206 is initiating an IKE_SA
Sep 23 03:57:15 Minecraft charon: 16[IKE] 220.127.116.11 is initiating an IKE_SA
Sep 23 03:57:15 Minecraft charon: 05[IKE] 22.214.171.124 is initiating an IKE_SA
Sep 23 03:57:20 Minecraft charon: 06[IKE] 126.96.36.199 is initiating an IKE_SA
Sep 23 03:57:20 Minecraft charon: 10[IKE] 126.96.36.199 is initiating an IKE_SA
Sep 23 03:57:26 Minecraft charon: 12[IKE] 220.127.116.11 is initiating an IKE_SA
Sep 23 03:57:26 Minecraft charon: 11[IKE] 184.108.40.206 is initiating an IKE_SA
Sep 23 04:17:42 Minecraft charon: 07[IKE] 126.96.36.199 is initiating an IKE_SA
Sep 23 04:17:42 Minecraft charon: 16[IKE] 220.127.116.11 is initiating an IKE_SA

Edit: One line in the server log says:

Sep 23 04:17:42 Minecraft charon: 05[IKE] loading EAP_MSCHAPV2 method
  failed

I think this is the reason for this.. Anyone know how to fix this?

Edit:
I changed the strongswan.conf and added this line:
load = aes des sha1 sha2 md4 md5 pem pkcs1 gmp random nonce x509 curl revocation hmac xcbc stroke kernel-netlink socket-default fips-prf eap-mschapv2 eap-identity updown

and now I I see the EAP_MSCHAPV2 plugin loaded with ipsec statusall but when I tried to connect, I get this in my syslog:
Sep 23 05:03:44 Minecraft charon: 14[NET] received packet: from 18.104.22.168[46425] to MYIPADDRESS[500] (716 bytes)
Sep 23 05:03:44 Minecraft charon: 14[ENC] parsed IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(REDIR_SUP) ]
Sep 23 05:03:44 Minecraft charon: 14[IKE] 22.214.171.124 is initiating an IKE_SA
Sep 23 05:03:44 Minecraft charon: 14[IKE] remote host is behind NAT
Sep 23 05:03:44 Minecraft charon: 14[IKE] DH group ECP_256 inacceptable, requesting MODP_3072
Sep 23 05:03:44 Minecraft charon: 14[ENC] generating IKE_SA_INIT response 0 [ N(INVAL_KE) ]
Sep 23 05:03:44 Minecraft charon: 14[NET] sending packet: from MYIPADDRESS[500] to 22.214.171.124[46425] (38 bytes)
Sep 23 05:03:44 Minecraft charon: 15[NET] received packet: from 22.214.171.124[46425] to MYIPADDRESS[500] (1036 bytes)
Sep 23 05:03:44 Minecraft charon: 15[ENC] parsed IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(REDIR_SUP) ]
Sep 23 05:03:44 Minecraft charon: 15[IKE] 126.96.36.199 is initiating an IKE_SA
Sep 23 05:03:44 Minecraft charon: 15[IKE] remote host is behind NAT
Sep 23 05:03:44 Minecraft charon: 15[ENC] generating IKE_SA_INIT response 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(MULT_AUTH) ]
Sep 23 05:03:44 Minecraft charon: 15[NET] sending packet: from MYIPADDRESS[500] to 184.108.40.206[46425] (592 bytes)
Sep 23 05:03:44 Minecraft charon: 10[NET] received packet: from 188.8.131.52[39639] to MYIPADDRESS[4500] (464 bytes)
Sep 23 05:03:44 Minecraft charon: 10[ENC] parsed IKE_AUTH request 1 [ IDi N(INIT_CONTACT) CERTREQ CPRQ(ADDR ADDR6 DNS DNS6) N(ESP_TFC_PAD_N) SA TSi TSr N(MOBIKE_SUP) N(NO_ADD_ADDR) N(MULT_AUTH) N(EAP_ONLY) N(MSG_ID_SYN_SUP) ]
Sep 23 05:03:44 Minecraft charon: 10[IKE] received cert request for "CN=VPN root CA"
Sep 23 05:03:44 Minecraft charon: 10[CFG] looking for peer configs matching MYIPADDRESS[%any]...126.96.36.199[user1]
Sep 23 05:03:44 Minecraft charon: 10[CFG] selected peer config 'ikev2-vpn'
Sep 23 05:03:44 Minecraft charon: 10[IKE] initiating EAP_IDENTITY method (id 0x00)
Sep 23 05:03:44 Minecraft charon: 10[IKE] received ESP_TFC_PADDING_NOT_SUPPORTED, not using ESPv3 TFC padding
Sep 23 05:03:44 Minecraft charon: 10[IKE] peer supports MOBIKE
Sep 23 05:03:44 Minecraft charon: 10[IKE] authentication of 'MYIPADDRESS' (myself) with RSA_EMSA_PKCS1_SHA2_384 successful
Sep 23 05:03:44 Minecraft charon: 10[IKE] sending end entity cert "CN=MYIPADDRESS"
Sep 23 05:03:44 Minecraft charon: 10[ENC] generating IKE_AUTH response 1 [ IDr CERT AUTH EAP/REQ/ID ]
Sep 23 05:03:44 Minecraft charon: 10[ENC] splitting IKE message with length of 1920 bytes into 2 fragments
Sep 23 05:03:44 Minecraft charon: 10[ENC] generating IKE_AUTH response 1 [ EF(1/2) ]
Sep 23 05:03:44 Minecraft charon: 10[ENC] generating IKE_AUTH response 1 [ EF(2/2) ]
Sep 23 05:03:44 Minecraft charon: 10[NET] sending packet: from MYIPADDRESS[4500] to 188.8.131.52[39639] (1236 bytes)
Sep 23 05:03:44 Minecraft charon: 10[NET] sending packet: from MYIPADDRESS[4500] to 18.104.22.168[39639] (756 bytes)
Sep 23 05:03:44 Minecraft charon: 06[NET] received packet: from 220.127.116.11[39639] to MYIPADDRESS[4500] (80 bytes)
Sep 23 05:03:44 Minecraft charon: 06[ENC] parsed IKE_AUTH request 2 [ EAP/RES/ID ]
Sep 23 05:03:44 Minecraft charon: 06[IKE] received EAP identity 'user1'
Sep 23 05:03:44 Minecraft charon: 06[IKE] initiating EAP_MSCHAPV2 method (id 0xEC)
Sep 23 05:03:44 Minecraft charon: 06[ENC] generating IKE_AUTH response 2 [ EAP/REQ/MSCHAPV2 ]
Sep 23 05:03:44 Minecraft charon: 06[NET] sending packet: from MYIPADDRESS[4500] to 22.214.171.124[39639] (112 bytes)
Sep 23 05:03:45 Minecraft charon: 04[NET] received packet: from 220.127.116.11[39639] to MYIPADDRESS[4500] (144 bytes)
Sep 23 05:03:45 Minecraft charon: 04[ENC] parsed IKE_AUTH request 3 [ EAP/RES/MSCHAPV2 ]
Sep 23 05:03:45 Minecraft charon: 04[IKE] no EAP key found for hosts 'MYIPADDRESS' - 'user1'
Sep 23 05:03:45 Minecraft charon: 04[IKE] EAP-MS-CHAPv2 verification failed, retry (1)
Sep 23 05:03:47 Minecraft charon: 04[ENC] generating IKE_AUTH response 3 [ EAP/REQ/MSCHAPV2 ]
Sep 23 05:03:47 Minecraft charon: 04[NET] sending packet: from MYIPADDRESS[4500] to 188.8.131.52[39639] (128 bytes)
Sep 23 05:03:47 Minecraft charon: 05[NET] received packet: from 188.8.131.52[39639] to MYIPADDRESS[4500] (144 bytes)
Sep 23 05:03:47 Minecraft charon: 05[ENC] parsed IKE_AUTH request 3 [ EAP/RES/MSCHAPV2 ]
Sep 23 05:03:47 Minecraft charon: 05[IKE] received retransmit of request with ID 3, retransmitting response
Sep 23 05:03:47 Minecraft charon: 05[NET] sending packet: from MYIPADDRESS[4500] to 18.104.22.168[39639] (128 bytes)
Sep 23 05:03:47 Minecraft charon: 07[NET] received packet: from 18.104.22.168[39639] to MYIPADDRESS[4500] (80 bytes)
Sep 23 05:03:47 Minecraft charon: 07[ENC] parsed INFORMATIONAL request 4 [ N(AUTH_FAILED) ]
Sep 23 05:03:47 Minecraft charon: 07[ENC] generating INFORMATIONAL response 4 [ N(AUTH_FAILED) ]
Sep 23 05:03:47 Minecraft charon: 07[NET] sending packet: from MYIPADDRESS[4500] to 188.8.131.52[39639] (80 bytes)

where the row

Sep 23 05:03:45 Minecraft charon: 04[IKE] no EAP key found for hosts
  'MYIPADDRESS' - 'user1'

is strange because this is my secret file:
# This file holds shared secrets or RSA private keys for authentication.

# RSA private key for this host, authenticating it to any other host
# which knows the public part.

# this file is managed with debconf and will contain the automatically created $
#include /var/lib/strongswan/ipsec.secrets.inc
: RSA "server-key-vpn2.pem"
user1: EAP "1234"
user2 : EAP "hallo1234"

And yes, after each change of one of the config files, I do sudo systemctl restart strongswan and ipsec restart.
New android log:
Sep 23 11:07:57 00[DMN] +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Sep 23 11:07:57 00[DMN] Starting IKE service (strongSwan 5.8.0dr2, Android 9 - PKQ1.181121.001/2019-08-01, Mi 9T Pro - Xiaomi/raphael_eea/Xiaomi, Linux 4.14.83-perf-g7723fb1, aarch64)
Sep 23 11:07:57 00[LIB] loaded plugins: androidbridge charon android-log openssl fips-prf random nonce pubkey chapoly curve25519 pkcs1 pkcs8 pem xcbc hmac socket-default revocation eap-identity eap-mschapv2 eap-md5 eap-gtc eap-tls x509
Sep 23 11:07:57 00[JOB] spawning 16 worker threads
Sep 23 11:07:57 11[IKE] initiating IKE_SA android[29] to MYIPADDRESS
Sep 23 11:07:57 11[ENC] generating IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(REDIR_SUP) ]
Sep 23 11:07:57 11[NET] sending packet: from 10.105.74.60[49105] to MYIPADDRESS[500] (716 bytes)
Sep 23 11:07:57 12[NET] received packet: from MYIPADDRESS[500] to 10.105.74.60[49105] (38 bytes)
Sep 23 11:07:57 12[ENC] parsed IKE_SA_INIT response 0 [ N(INVAL_KE) ]
Sep 23 11:07:57 12[IKE] peer didn't accept DH group ECP_256, it requested MODP_3072
Sep 23 11:07:57 12[IKE] initiating IKE_SA android[29] to MYIPADDRESS
Sep 23 11:07:57 12[ENC] generating IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(REDIR_SUP) ]
Sep 23 11:07:57 12[NET] sending packet: from 10.105.74.60[49105] to MYIPADDRESS[500] (1036 bytes)
Sep 23 11:07:57 07[NET] received packet: from MYIPADDRESS[500] to 10.105.74.60[49105] (592 bytes)
Sep 23 11:07:57 07[ENC] parsed IKE_SA_INIT response 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(MULT_AUTH) ]
Sep 23 11:07:57 07[CFG] selected proposal: IKE:AES_CBC_128/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/MODP_3072
Sep 23 11:07:57 07[IKE] local host is behind NAT, sending keep alives
Sep 23 11:07:57 07[IKE] remote host is behind NAT
Sep 23 11:07:57 07[IKE] sending cert request for "CN=VPN root CA"
Sep 23 11:07:57 07[IKE] establishing CHILD_SA android{29}
Sep 23 11:07:57 07[ENC] generating IKE_AUTH request 1 [ IDi N(INIT_CONTACT) CERTREQ CPRQ(ADDR ADDR6 DNS DNS6) N(ESP_TFC_PAD_N) SA TSi TSr N(MOBIKE_SUP) N(NO_ADD_ADDR) N(MULT_AUTH) N(EAP_ONLY) N(MSG_ID_SYN_SUP) ]
Sep 23 11:07:57 07[NET] sending packet: from 10.105.74.60[49611] to MYIPADDRESS[4500] (464 bytes)
Sep 23 11:07:58 14[NET] received packet: from MYIPADDRESS[4500] to 10.105.74.60[49611] (1236 bytes)
Sep 23 11:07:58 14[ENC] parsed IKE_AUTH response 1 [ EF(1/2) ]
Sep 23 11:07:58 14[ENC] received fragment #1 of 2, waiting for complete IKE message
Sep 23 11:07:58 15[NET] received packet: from MYIPADDRESS[4500] to 10.105.74.60[49611] (756 bytes)
Sep 23 11:07:58 15[ENC] parsed IKE_AUTH response 1 [ EF(2/2) ]
Sep 23 11:07:58 15[ENC] received fragment #2 of 2, reassembled fragmented IKE message (1920 bytes)
Sep 23 11:07:58 15[ENC] parsed IKE_AUTH response 1 [ IDr CERT AUTH EAP/REQ/ID ]
Sep 23 11:07:58 15[IKE] received end entity cert "CN=MYIPADDRESS"
Sep 23 11:07:58 15[CFG]   using certificate "CN=MYIPADDRESS"
Sep 23 11:07:58 15[CFG]   using trusted ca certificate "CN=VPN root CA"
Sep 23 11:07:58 15[CFG] checking certificate status of "CN=MYIPADDRESS"
Sep 23 11:07:58 15[CFG] certificate status is not available
Sep 23 11:07:58 15[CFG]   reached self-signed root ca with a path length of 0
Sep 23 11:07:58 15[IKE] authentication of 'MYIPADDRESS' with RSA_EMSA_PKCS1_SHA2_384 successful
Sep 23 11:07:58 15[IKE] server requested EAP_IDENTITY (id 0x00), sending 'user1'
Sep 23 11:07:58 15[ENC] generating IKE_AUTH request 2 [ EAP/RES/ID ]
Sep 23 11:07:58 15[NET] sending packet: from 10.105.74.60[49611] to MYIPADDRESS[4500] (80 bytes)
Sep 23 11:07:58 11[NET] received packet: from MYIPADDRESS[4500] to 10.105.74.60[49611] (112 bytes)
Sep 23 11:07:58 11[ENC] parsed IKE_AUTH response 2 [ EAP/REQ/MSCHAPV2 ]
Sep 23 11:07:58 11[IKE] server requested EAP_MSCHAPV2 authentication (id 0x3C)
Sep 23 11:07:58 11[ENC] generating IKE_AUTH request 3 [ EAP/RES/MSCHAPV2 ]
Sep 23 11:07:58 11[NET] sending packet: from 10.105.74.60[49611] to MYIPADDRESS[4500] (144 bytes)
Sep 23 11:08:00 13[IKE] retransmit 1 of request with message ID 3
Sep 23 11:08:00 13[NET] sending packet: from 10.105.74.60[49611] to MYIPADDRESS[4500] (144 bytes)
Sep 23 11:08:00 07[NET] received packet: from MYIPADDRESS[4500] to 10.105.74.60[49611] (128 bytes)
Sep 23 11:08:00 07[ENC] parsed IKE_AUTH response 3 [ EAP/REQ/MSCHAPV2 ]
Sep 23 11:08:00 07[IKE] EAP-MS-CHAPv2 failed with error ERROR_AUTHENTICATION_FAILURE: '(null)'
Sep 23 11:08:00 07[IKE] EAP_MSCHAPV2 method failed
Sep 23 11:08:00 07[ENC] generating INFORMATIONAL request 4 [ N(AUTH_FAILED) ]
Sep 23 11:08:00 07[NET] sending packet: from 10.105.74.60[49611] to MYIPADDRESS[4500] (80 bytes)

Answer: I hate me. In my secret file I needed a space after my username:
From this:
user1: EAP "1234"

to this:
user1 : EAP "1234"

Now it works.
Comment: Oh my goodness, that was my problem too. If the space is that important, StrongSwan should at least output an error message that the conf file is not formatted properly.


How to get count(max(marks)) , marks, subject from info_table group by subject , marks;

Question: I need a query which can display count of max marks score in each subject.
say 3 students scored 98 in science by output needs to be
count marks subject
3      98    Maths

Answer: First find the max mark for each subject and use this result set as a sub-query and use EXISTS to find the count from the table which having the max mark.
Query
select `subject`,
count(*) as `count`,
max(`marks`) as `marks`
from `student` t1
where exists(
  select 1 from (
    select `subject`,
    max(`marks`) as `max_marks`
    from `student`
    group by `subject`
  ) t2
  where t1.`subject` = t2.`subject`
  and t1.`marks` = t2.`max_marks`
)
group by `subject`;

Answer: You could use the SQL below if your question is on Hive
v_max_marks gets the max mark for each subject. This view is then joined to the main table to get the student count.
WITH v_max_marks
AS
(SELECT subject, MAX(marks) AS marks
  FROM my_table
 GROUP BY subject)
SELECT my_table.subject,
       my_table.marks,
       COUNT(*) AS student_count
  FROM my_table JOIN v_max_marks
                  ON (my_table.subject = v_max_marks.subject AND
                      my_table.marks = v_max_marks.marks)
 GROUP BY my_table.subject,
          my_table.marks;