Model estimation using ACF and PACF

Question: Can anyone help in model estimation ? The following are the ACF,PACF and the plot of the sample respectively.
Comment: What is your question ? What is your problem ? What do you wanna achieve ? You have to be way more precise.
Comment: @JulienD.- which arma/arima model would fit best? I cannot make out from the acf graph..
Comment: also from the first plot, does it need differencing? or can it be considered stationary?
Comment: If your series is stationary (it might be nearly so), and you're not worried about the discreteness problem, then it may be approximately AR(1)xSAR(12). But I'd fit the AR(1) and see what the residual looked like.
Answer: It seems that the time series is not stationary from the first figure.
We should see the time series should have a constant mean and constant variance stable no trend ...
On the other hand, some hypothesis test can be employed, like Ljung-Box test, Augmented Dickey–Fuller (ADF) t-statistic test, Kwiatkowski-Phillips-Schmidt-Shin (KPSS) test
Answer: Checking if your time series is stationary or not, see this post
Checking which ARMA/ARIMA model to fit, see this website
Answer: You can try fitting an AR(10) or AR(11) process. Run Ljung-Box tests for various lags on the residuals after fitting the model to see if the p-values of the Q statistic are less than a certain signifiance level (0.05 perhaps). If not, then your null hypothesis, i.e. that your fitted model describes the sample well, holds.

Model estimation using ACF and PACF


I need to show in console.log the complete name (name and surname) of objects using contructor object

Question: I have 3 objectos in an array.each object has two properties (name and surname). I need to show a console.log with completed name for each object but using a object construtor.

const people = [
        {
            nome:'Raquel',
            sobrenome:'Santos'
        },
        {
            nome:'André',
            sobrenome:'Almeida'
        },
        {
            nome:'Minerva',
            sobrenome:'McGonadall'
        }
    ]

    const Persons = function(name, surname) {
        this.nome = name
        this.sobrenome = surname
    }

    people.forEach(function(item) {
        // I stoped here
        return item = new Persons
    })

I want to show in console.log the existed objects by using a constructor object
Comment: *I want to show in console.log the existed objects by using a constructor object* - why? Constructors are not really related to printing.
Answer: I added a function for writing to log.

    const people = [
        {
            nome:'Raquel',
            sobrenome:'Santos'
        },
        {
            nome:'André',
            sobrenome:'Almeida'
        },
        {
            nome:'Minerva',
            sobrenome:'McGonadall'
        }
    ]

    const Persons = function(nome, surname) {
        this.nome = nome
        this.sobrenome = surname
    }

    Persons.prototype.log = function() {
      console.log(this.nome + " " + this.sobrenome);
    };

    people.forEach(function(item) {
        let person = new Persons(item.nome, item.sobrenome);
        person.log();
    })
Answer: You may create a class with a method getFullName.
You may have a look, as well, to the different languages of properties and choose only a single one for the whole code.
Your gioven data is converted in the callback for creating an instance of a person.

class Person {
    constructor (name, surname) {
        this.name = name;
        this.surname = surname;
    }

    getFullName () {
        return [this.surname, this.name].join(' ');
    }
}

const
    peoples = [{ nome: 'Raquel', sobrenome: 'Santos' }, { nome: 'André', sobrenome: 'Almeida' }, { nome: 'Minerva', sobrenome: 'McGonadall' }],
    persons = peoples.map(({ nome, sobrenome }) => new Person(nome, sobrenome));

persons.forEach(person => console.log(person.getFullName()));
Answer: in the foreach:
console.log(item.nome+' '+item.sobrenome)

Answer: const Persons = function(name, surname){
    this.nome = name
    this.sobrenome = surname
    return name + ' ' + surname
}

console.log(new Persons('Raquel', 'Santos'))

I'm unsure why you'd need to have to console log via the Object's constructor. Luca C.'s answer is more straight forward.
Comment: This is only an exercise. I am newbie .so I just wanted to see the result of my exercise and  sometimes I dont know how to see the result and where to insert the code
Answer: Starting with ES2015 you can also hack your way with Object.setPrototypeOf(). Also, providing an own toString() may be a natural choice for this kind of task, see how "Before" and "After" loops are identical.

const people = [
  {
    nome:'Raquel',
    sobrenome:'Santos'
  },
  {
    nome:'André',
    sobrenome:'Almeida'
  },
  {
    nome:'Minerva',
    sobrenome:'McGonadall'
  }
];

console.log("Before:");
people.forEach(function(folk,idx){
  console.log(idx+": "+folk);
});

function Person(){}
Person.prototype.toString=function(){
  return this.nome+" "+this.sobrenome;
};

const proto=new Person();

people.forEach(function(folk){
  Object.setPrototypeOf(folk,proto);
});

console.log("After:");
people.forEach(function(folk,idx){
  console.log(idx+": "+folk);
});

console.log("people[0] instanceof Person: "+(people[0] instanceof Person));

(There is a minor cheat with toString(): it gets invoked only when an object is converted to string, which is enforced here via prepending the index. A simple console.log(folk); would not do the job as JavaScript consoles usually support logging objects, and then they are not stringified.)
Answer: You can use console.log({item}); - that will give you all you need in a pretty and named style:


How to get "make" value from one HTML form to another?

Question: I'm having an issue sharing a value between my HTML forms. I'm a beginner so this is probably a very easy fix.
Newvehicle.html:

    <input class="form-control" id="inputMake" type="text" placeholder="Make..." style="width: 150px;"/>

Item1.html:
Make:

Newvehicle.js:
function getMake(){
    var make = document.getElementById("inputMake").value;
}

I would like the value inputted into the text field on Newvehicle.html to display as a list item on Item1.html. Can someone please advise?
Comment: If you need to pass variables to another html file you need to either use localstorage, cookies, or pass the variable as a url fragment. More info here: https://stackoverflow.com/questions/23213788/how-to-pass-variable-value-between-different-html-pages-in-javascript
Comment: Possible duplicate of [How to pass variable value between different html pages in javascript](https://stackoverflow.com/questions/23213788/how-to-pass-variable-value-between-different-html-pages-in-javascript)
Comment: Just to clarify - Newvehicle.html and Item1.html are both inside separate browser windows?
Answer: What you could do is, to save the value in localStorage and retrive it in the secound file.
A possible HTML solution would be:
Newvehicle.html:

   <input class="form-control" id="inputMake" type="text" placeholder="Make..." style="width: 150px;" onkeyup="localStorage.value1 = this.value" />

Item1.html:
Make:

Newvehicle.js:
not required for that, but nice to have the whole logic in a seperate JS file
Explanation:
the onkeyup event fires up each time the usert releases a key on the keyboard, so with each firing we create/replace the value1 in localStorage.
right after the list element will a javasript code be executed that reads the value from localStorage in your case value1 and replaces the innerHTML.
keep in mid that this only works if you work on the same domain.Localstorage keeps the data until you clear the localstorage whit localStorage.clear()
alternatively you can use sessionStorage instead of localStorage tho keep the data only for one browsing session.
See:
Webstorage on W3C Schools
Keep on going and soon you will master the Javasript language.
Comment: Thanks Stan, this code works great for what I asked for. Unfortunately, my web app was connected to a working Firebase database - when I clicked the submit button, it used to add this information to this database but having altered it, it no longer does. Do you know why this code may have caused this? I could always ask Stack Overflow again and provide code if needs be.
Comment: @DannyO'Sullivan i gues there are some issues with the logic. If you would provide me more code, i could help for sure. Or provide me a link to your app.
Comment: Think I got it working Stan, very very grateful for your help!


Duvida na resolução de um exercício utilizando while ou for

Question: Boa noite meus caros,
Minha duvida é referente a repetição (while e for).
Em um exercício eu quero imprimir os números de um a 10. Porem quero agrupa-los de 2 em 2, ou de 3 em 3 para seguir essa logica:

123
456
789
...

Muito obrigado pela atenção.
Att,
Comment: poderia [edit] seu post e adicionar o que ja tentou fazer até agora, assim fica mais fácil te ajudar :) Abraço
Comment: Não está claro o problema. Se você tentou alguma solução, poderia postar para facilitar
Comment: nao esta bem especifico sua pergunta, tem como postar o que voce ja fez para termos uma nocao do que precisa, e saber ate aonde chegou!
Answer: Olá, sua dúvida não está tão clara, tente apresentar um pedaço do codigo que tem.
Segue um algoritmo que resolve a questão (de acordo com o que entendi da sua pergunta) agrupando de 2 em 2, e quando chega em 10 reinicia a contagem:
<code>#include<stdio.h>

int main(void)
{
    int i = 0, j = 0, aux = 1;
    for (i = 1; i <= 10; i++){
        printf("%d. ", i);
        for (j = aux; j <= (aux + 1); j++){
            printf("%d ", j);
        }
        aux = j;
        if(aux > 9) aux = 1;
        printf("\n");
    }
    return 0;
}
</code>


How to bind events for new elements?

Question: How can I register an event for new elements programmatically? I'm using AutoComplete library and Data Table library (add row function) and the autocomplete event is only applied on the existing rows but not for new inserted rows. How can I fix that? Please help...
This is what I've tried...
$('#addRow').on('click', function () {

        let input = document.createElement("input")
        input.setAttribute("type", "text");
        input.setAttribute("class", "material_no");
        input.setAttribute("id", "material_no");
        input.setAttribute("placeholder", "Enter material no.");

        table.row.add( [
            '-',
            `
            <input type='text' class='material_no' id = 'material_no' placeholder = 'Enter Material No.'/>
            `,
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
        ] ).draw();

        counter++;
    } );
    // Automatically add a first row of data
    $('#addRow').click();

    //autocomplete library
    $('.material_no').each(function(i, e) {
        $(this).bind('change').autocomplete({
            source: '/mef/suggestions.php',
            change: function( event, ui ) {
                console.log($(this).val())

                console.log(table.row($(this).parent()).index())

                return false;
            },
        })
    })

Answer: I solved it by putting event inside the draw function in datatable. I don't know if it is good approach or can cause bugs in the future...
table.on('draw', function () {
        $('.material_no').each(function(i, e) {
            $(this).autocomplete({
                source: '/mef/suggestions.php',
                change: function( event, ui ) {
                    console.log($(this).val())

                    console.log(table.row($(this).parent()).index())

                    // $.ajax({
                    //     url: '/mef/ajax/part_names.php',
                    //     method: 'POST',
                    //     data: { part_code: $(this).val()},
                    //     success: data => {
                    //         $(`td:eq(${i})`).html(data)
                    //         console.log(data)
                    //     },
                    //     error: err => console.log(err)
                    // })

                    return false;
                },
            })
        })
    });

How to bind events for new elements?


How can I prove this problem on geometry?

Question: I need to prove the following:

If $P$ is an inner point of $\triangle ABC$, then there is a single transverse $EF$ of $\overleftrightarrow{AB}$ and $\overleftrightarrow{AC}$, where $E$ is on $\overleftrightarrow{AC}$ and $F$ is on $\overleftrightarrow{AB}$, such that P is the middle of the segment $XY$.

I tried for a longer time but nothing!! Some idea? Thanks in advance.
Answer: This answer is based on @noneEggs's suggestion.

1: Extend BP to Q such that BP = (0.5) BQ
2: (Can be skipped.) A circle (centered at P and radius = PB) is drawn cutting BP extended at Q.
3: A line through Q is drawn parallel to AB cutting AC (extended if necessary) at R.
4: Join BR.
5: A line through Q is drawn parallel to RB cutting AB at S.
6: Join SR.
According to the construction, SBRQ is a parallelogram with diagonals BQ and SR cutting each other at T.
Since the diagonals of a parallelogram bisect each other, BT = (0.5) BQ. This, together with the result in (1), means that T and P are the same point. Thus, RPS is a straight line with SP = PR.
R and S are then the required E and F respectively.
Comment: Thanks! Now I can see this more clear!
Comment: You are welcome.
Answer: Just a hint : You can always make a parallelogram out of A and P, where A is a vertex and P is the center of the parallelogram itself
Comment: In fact, you can always make many of this!! But what is the idea in your hint?


Showing that a map $f$ between connected $CW$-complexes is a homotopy equivalence.

Question: Showing that a map $f$ between connected $CW$-complexes is a homotopy equivalence if it induces an isomorphism on $\pi_{1}$ and if a lift $\tilde{f} : \tilde{X} \rightarrow \tilde{Y}$ to the universal covers induces an isomorphism in homology.
Could anyone give me a hint for the solution?
Answer: Relative hurewicz applied to $\tilde f$ shows that it is an isomorphism on homotopy groups, but $\pi_n \tilde X = \pi_n X$ for $n>1$, and this isomorphism commutes with the maps induced by $f$ and $\tilde f$.
So your map $f$ is an iso on all homotopy groups. Apply Whitehead.


Is this a valid proof that $ e^{\pi^2} $ is irrational?

Question: Proving the irrationality of $e^n$
This essentially proves $e^n \ $  is irrational for all possible values of n and
since $ e^{\pi^2} $   is essentially $e^{\pi\times\pi}$  and this fits the  $e^n \ $ category so does that make it irrational?
Comment: Huh???????????????
Comment: $n$ is supposed to be an integer. Is $\pi^2$ an integer?
Comment: No, this does not prove that $\mathrm{e}^{\pi^2}$ is irrational; the proof that you cite assumes that $n$ is a natural number.
Comment: That link shows that $e^n$ is irrational for positive integers $n$.  $\pi^2$ is not a positive integer
Comment: If $n$ was arbitrary, you could write $e^{\ln 2}=2$ irrational.
Comment: Ok thanks for the help
Comment: To the original question:  I, for one, don't know if the transcendence of $e^{\pi^2}$ has been shown (surely it is transcendental, but proving it is another matter). Of course, someone else may know more about it. The transcendence of $e^{\pi}$ follows from the [Gelfond-Schneider Theorem](https://en.wikipedia.org/wiki/Gelfond%E2%80%93Schneider_theorem).
Answer: No. The link shows that $e^n$ is irrational for any natural number $n$. But $\pi^2$ isn't a natural number, so that result doesn't apply. Note that there absolutely are exponents $x$ for which $e^x$ is rational - e.g. $e^{\ln 2}=2,$ and so on.
Answer: Well, $e^{\pi^2}$ isn't just "essentially" $e^{\pi\times\pi}$; they're the same thing. And the question to which you have posted a link is about the irrationality of the numbers of the form $e^n$, with $n$ natural. Since $\pi^2\notin\mathbb N$, no, $e^{\pi^2}$ doesn't fit this category.
Comment: Ok thanks for the help guys
Answer: No.  The answers to that question only show that $e^n$ is irrational for any positive integer $n$.  This would only apply to $e^{\pi^2}$ if $\pi^2$ were a positive integer, which it is not.


Saving information in my sql table depending on a select option value

Question: I have a form with a select option, to select the level of andmin.
And I have the value "1" for "Super Admin" and the value of "2" for "Admin".
And I want to save this info "Super Admin" and "Admin" in my sql table, but I dont understand why Im saving the values "1" and "2" and not "Super Admin" or "Admin" as I wanted.
Do you see something wrong?
if(isset($_POST['sendForm']))
  {
    if($f['admin_level'] == '1') { $f['admin_level'] == 'Super Admin'; }
    if($f['admin_level'] == '2') { $f['admin_level'] == 'Admin'; }
  }

        Select admin level:
        <select name="admin_level">
        <option value="">Select admin level</option>
        <option value="1">Super Admin</option>
        <option value="2">Admin</option>
        </select>

    <input type="submit" value="Save" name="sendForm"/>

</form>

Comment: post your complete script we cant work with just this
Answer: You are using == in your if statements for assignment. However this is a logical operator.
Change this:
if(isset($_POST['sendForm']))
{
  if($f['admin_level'] == '1') { $f['admin_level'] == 'Super Admin'; }
  if($f['admin_level'] == '2') { $f['admin_level'] == 'Admin'; }
}

To:
if(isset($_POST['sendForm']))
{
  if($f['admin_level'] == '1') { $f['admin_level'] = 'Super Admin'; }
  if($f['admin_level'] == '2') { $f['admin_level'] = 'Admin'; }
}

Comment: Thank you! you are right! But in my example I have like you said and its not working. I just put thins wrong doing the translation!
Comment: Thank you, after all I had wrong in my example! It was really that the problem. Thanks!
Comment: By the way, in my language Admin have an accent like "správce". And in sql appears like " správce". Do you know how to fix this accent problems with sql?
Comment: If you are having issues with accents, you're most likely course of action is to investigate the SQL Language collation settings. Something may not be playing nice with how the database stores your language.


Private nested class accessing private function of outer class

Question: Simplified version of my code
class Outer
{
private:
    double Foo(double a=0; double b=1);

    class Inner
    {
    public:
        Inner()
        {
            mX = Foo(2, 3);
        }
    private:
        double mX;
    };
};

My problem is, Inner cannot access the Foo function. I have looked around various sites regarding what needs to be done. I saw on one page that using the friend keyword could be useful, but I couldn't seem to apply it properly.
I'd like to keep the Inner class private in Outer because of how the rest of my code is structured.
I don't think this is a copy of another question, but if I'm wrong, my apologies.
Thanks for any advice!
Comment: Does this answer your question? [Nested class' access to enclosing class' private data members](https://stackoverflow.com/questions/1604853/nested-class-access-to-enclosing-class-private-data-members)
Answer: Outer::Foo is a non-static member function; you need an instance of Outer to be called on, the inner class doen't have it implicitly (like java). e.g.
class Outer
{
private:
    double Foo(double a=0; double b=1);

    class Inner
    {
    public:
        Inner()
        {
            Outer o;
            mX = o.Foo(2, 3);
        }
    private:
        double mX;
    };
};

Comment: I knew it was something simple. Thank you fo the helpful and speedy response, Out of curiosity, given I have an instance of Outer, how would I access a private member variable of Outer. Again, I'm sure it,s something simple.
Comment: @T.Smith I might not get your question correctly; inside `Inner`, you could access the `private` members of `Outer` directly, if you have an instance of `Outer`, as showed in my answer.
Answer: Some mistakes:
double Foo(double a=0; double b=1);

; is not a delimiter between function's parameters, use , instead.
mX = Foo(2, 3);

Foo is non-static function, which means it object interface related. You can't call it without specified which object it relates to.
To fix it you can both create an object and call this function of the related object, or make this function a static one.
Example of creating an object:
class Inner {
public:
    Inner() {
        Outer o; // Consider making it a class member object, so in each call / use it will relate to the same one. Be aware that in this case you will need to use a pointer to the outer class, due to 'incomplete type' error.
        mX = o.Foo(2, 3);
    }
private:
    double mX;
};

Example of making it a static function:
class Outer {
private:
    static double Foo(double a=0, double b=1);

    class Inner {
    public:
        Inner() {
            mX = Outer::Foo(2, 3);
        }
    private:
        double mX;
    };
};

Consider also the following ways of giving mX its value, in case of static function Foo:
class Inner {
public:
    Inner() {}
private:
    double mX = Outer::Foo(2, 3); // Recommended by Cpp guidelines.
};

Or:
class Inner {
public:
    Inner() : mX(Outer::Foo(2, 3)) {} // Using initialize list

private:
    double mX;
};

References:
C++ Core Guidelines


Simplex method — optimality criterion

Question: I have to show that if for a minimization problem, $z_j - c_j <0$, for all non-basic variables then it has a unique optimal solution. The proof says

If we start with a feasible point $x$ distinct from the current optimal solution $x^*$, then at least one of the non-basic component $x_j$ is positive, otherwise if all non-basic components are zero, $x$ would not be distinct from $x^*$.

Please explain how does the distinct nature ensure that one of the non-basic component is positive.
Comment: I don't like the proof your source states.  I think it's assuming what is to be proved (see my comment on Robert Israel's answer).  And I think showing the claim is trickier than it appears at first - perhaps depending on what you can assume.  Would you give your source?
Comment: @Tav: what are $z_j, c_j$? Could you give some more details?
Comment: @ Mike Spivey : My source Linear Programming and Network Flows: Bazaraa, Jarvis and Sherali .http://books.google.co.in/books?id=2KHfyWC_5-QC&lpg=PP1&dq=bazaraa%20%2C%20linear&pg=PA104#v=onepage&q&f=false
Comment: @ Mike Spivey: If possible, please do take a look at this result in the google book link given above.
Answer: The essential point is that the simplex tableau describes all solutions, not just the basic solution, giving the basic variables and the objective as functions of the values of the nonbasic variables.  The variables must be nonnegative in order for the solution to be feasible.  The basic solution $x^*$ is the one where the nonbasic variables are all 0.  If you have a solution that is not $x^*$, the nonbasic variables can't all be 0; if it is feasible, those nonbasic variables must all be nonnegative, so the ones that are not 0 will be positive.
Comment: Thanks for your reply. i agree with your reply. But I am confused thinking of the case of an alternative optima, where non basic variables may remain zero for the new solution. The values of the basic variables change but non basic variables remains the same.
Comment: Do you mean "optimal" instead of "basic" and "coefficients of the nonbasic variables" instead of "nonbasic variables" in the third sentence?  Otherwise, what you say doesn't make sense.  The nonbasic variables are always 0.  That's part of what it means for a variable to be nonbasic.
Comment: @ Robert Isarel: If possible, please do take a look at the result in the google book link given. http://books.google.co.in/books?id=2KHfyWC_5-QC&lpg=PP1&dq=bazaraa%20%2C%20linear&pg=PA104#v=onepage&q&f=false
Comment: @Mike Spivey: "...then the coefficients of the nonbasic variables can't all be 0 unless the other solution is also optimal" . Please explain how this works.
Comment: @Mike Spivey: Please take a look at the proof of the result in the link provided.
Comment: @Mike: no, nonbasic variables are 0 in a basic solution.  But the tableau describes all the solutions, expressing the basic variables as functions of the nonbasic variables.
If the basic variables are functions of the nonbasic variables, you can't change the basic variables without changing at least one nonbasic variable.
Comment: @Robert: Right.  I originally parsed your last sentence as "If you have a [basic] solution that is not $x^*$, the [new set of] nonbasic variables [for the new solution] can't all be $0$..., which of course is nonsense.  I figured out what you meant, though (see my answer).  My apologies.
Answer: Now that I see the context in which the argument appears, it makes sense.
If ${\bf x}^*$ is an optimal basic feasible solution with objective value $z^*$, and ${\bf x}$ is any other feasible solution with objective value $z$, then (from derivations earlier in the text), they say
$$z^* - z = \sum_{j \in J} (z_j - c_j) x_j,$$
where $J$ is the index set for the variables that are nonbasic for the optimal solution $x^*$ and not necessarily for any other basic solution.  For the rest of their argument (and the one below), $J$ retains this interpretation.
The other piece of information they are relying on (and this is the point I think Robert Israel is trying to make in his answer) is that the values of the basic variables for any basic solution are obtained by setting the nonbasic variables to $0$ and then solving the resulting set of linear equations.  (The simplex tableau makes this automatic for you, so that you can just read the solutions off of the right-hand side.)  The point is that if $x_j = 0$ for all $j \in J$ then ${\bf x}^*$ is the solution you get.  Thus if we have a feasible solution ${\bf x}$, distinct from ${\bf x}^*$, then there is at least one $x_j$ for $j \in J$ that is nonzero.
Since all the variables have to be nonnegative in order for ${\bf x}$ to be feasible, $x_j > 0$.  With the assumption that $z_j - c_j < 0$ the equation above forces $z^* < z$. Thus any other feasible solution has a strictly larger objective function value and so cannot be optimal.
Comment: @Tav: Any time you change the current basic feasible solution, the set of nonbasic variables and the set of basic variables has to change.  This is true regardless of whether the basic feasible solutions in question are optimal.  So, yes, it holds in the case of alternative optima.
Comment: @ Mike Spivey: Thanks ! I guess I was getting confused thinking of two interior optimal points on the line joining two optimal solutions. However, in this case, we need x* to be an extreme point (basic feasible solution) and x to be a feasible solution which can be an interior point (which is not basic). Then, of course, the set of basic and non basic variables will change. Many thanks for the explaining everything in detail. I appreciate your help :)
Comment: @ Mike Spivey: Thank you for the detailed and informative reply. I have a small doubt. I quote: "Thus if we have a feasible solution x, distinct from  x* , then there is at least one xj that is nonzero." Does this hold in case of alternative optima, where the set of non basic variables may remain the identical.

Simplex method — optimality criterion


Print CSS: Empty white space at top

Question: Struggling with what seems to be a common problem, but none of the suggestions I've found so far is working. I'm working on a stylesheet for printing, the page contains nothing more then a table and one h1 tag.
The problem is that I'm getting empty white space at the top of the page, about 1/4 of the page in portrait and half the page in landscape - neither is obviously not acceptable for my users.
I've tried zeroing margins on every possible element I can think off, including body, html, table, tr and tr. Pasting the HTML and CSS below (some tags is for other HTML not found below, these are for other pages also using the same CSS for print), hopefully it's a simple fix or missing margin :)
/*Print CSS template */
body, #content, #container {
   width: 100%;
   margin: 0;
   float: none;
   background: #fff url(none);
}

#topnav, #navbar, #nav, #sidebar, .ad, .noprint {
   display: none;
}
body {
   font: 1em Georgia, "Times New Roman", Times, serif;
   color: #000;
}

h1,h2,h3,h4,h5,h6 {
   font-family: Helvetica, Arial, sans-serif;
   color: #000;
}
h1 { font-size: 250%; }
h2 { font-size: 175%; }

a:link, a:visited {
   color: #00c;
   font-weight: bold;
   text-decoration: underline; }
#content a:link:after, #content a:visited:after {
   content: " (" attr(href) ") ";
}

/*Print CSS template END */

.r_main
{
    width: auto;
    padding: 0;
    margin: 0;

}

table{
   margin: 0;
   padding: 0;
}

.r_wrap
{
    margin: 0;
    width: 100%;
    display: block;
    min-height: 30px;
    float: left;
    display: block;
    border-bottom: 1px solid #000;
}

.r_left
{
    margin: 0;
    width: 300px;
    color: #000;
    display: block;
    float: left;
    font: 13px Arial, Helvetica,"Lucida Grande", serif; color: #000;
}

.r_right
{
    margin: 0;
    display: block;
    float: left;
    color: #000;
    font: 13px Arial, Helvetica,"Lucida Grande", serif; color: #000;
}

.r_right p
{
    padding: 0;
    margin: 7px 0 3px 0;
    font: 13px Arial, Helvetica,"Lucida Grande", serif; color: #000;
}

.r_left span, .r_right span
{
    display: block;

    margin: 0;
    padding: 5px 0 0 0;
}

.r_right ul
{

    margin: 3px 0 0 15px;
    padding: 0;
}

.r_right ul li
{
    margin: 0;
    padding: 3px 0 0 0;
}

.r_zeb1
{
    background-color: #f9f9f9;
}

.r_zeb2
{
    background-color: #e9e9e9;
}

HTML

Location
'.$frm->get_location($selectedE['e_location']).'

Comment: If you go to another computer, are you seeing the same problem?
Comment: Fix your html please, i don't think all those `'` can pass through the w3c validator.
Comment: The ' are left overs from PHP echo. But, I'll remove them :)
Comment: I'm not seeing the problem you're describing here (using Firefox, IE9 and Chrome): http://jfcoder.com/test/printcss.html
Comment: I'm thinking you've selected in your printer setup settings something that centers vertically. Check your printer settings in the browser.
Comment: Embarrassing, the problem seems to be localized to my computer and only Firefox. Was so sure this was a global problem that I didn't check it on another computer or browser. Thank you all for replies :)
Answer: Assuming that the h1 is before the table, it could be the issue. You might want to zero the margins & padding on it. It could also help to switch to 'pt' for your font-size instead of using a %.
h1{
   margin:0;
   padding:0;
   font-size: 36pt;
   }

Answer: Agree with user401183, I think its the font size
h1 { font-size: 250%; }
h2 { font-size: 175%; }

Print CSS: Empty white space at top


I cant add row in my Database

Question: I am trying to build a CMS for my portfolio site. I created all the forms in the back end. Everything works except I cant add a column in my portfolio database in Mysqli. I have tried to echo the form data in another PHP page. Everything works fine. Even the uploaded image is moved to site directory. The only problem is Inserting the data in the Database Table. Here is my code
<?php
session_start();
?>

<?php

if(isset($_POST['submit']))
{

    $title=$_POST['title'];
    $description=$_POST['description'];
    $duration=$_POST['duration'];
    $category=$_POST['category'];

    $nImage=$_FILES['nImage']['name'];
    $file_tmp=$_FILES['nImage']['tmp_name'];
    $filesize=$_FILES['nImage']['size'];
    $file_ext=strtolower(pathinfo($nImage,PATHINFO_EXTENSION));
    $supported=array('jpg','jpeg','png');

    //Rename File
    $rand=sha1(time());
    $newname=$rand.".".$file_ext;
    $portfolio_img_dir="images/portfolio/".$newname;

    //Check If FileSize is more than 2 MB
    if($filesize<2097152)
    {

        //Check if Extension Matches
        if(in_array($file_ext,$supported))
        {
            //Move Uploaded Image
            if(move_uploaded_file($file_tmp,$portfolio_img_dir))
            {
                $qry=mysqli_query($link,"INSERT INTO `p_o_r_t_f_o_l_i_o`(`title`,`description`,`duration`,`category`,`image`) values('$title','$description','$duration','$category','$portfolio_img_dir')");

                    if($qry)
                    {

                        $_SESSION['add_port_msg_success']="Portfolio Item Successfully Added";
                        header('location:add_portfolio.php');

                    }

                    else
                    {
                        $_SESSION['add_portfolio_msg']="Portfolio Item Failed to Add";
                        header('location:add_portfolio.php');
                    }

            }
            else
            {
                $_SESSION['add_port_msg']="File Failed to Move";
                header('location:add_portfolio.php');
            }
        }

        else
        {
            $_SESSION['add_port_msg']="File Extension not Supported";
            header('location:add_portfolio.php');
        }

    }

    else
    {
        $_SESSION['add_port_msg']="Filesize too Large";
        header('location:add_portfolio.php');
    }

}

else
{
    $_SESSION['add_port_msg']="Invalid Attempt to Access Page";
    header('location:add_portfolio.php');
}
?>

and this is my HTML FORM

                    <form class="form-horizontal" method="post" enctype="multipart/form-data" action="act_newp.php">
                    <fieldset>

                    <legend>Add New Portfolio Item</legend>

                      Item Title

                      <input name="title" type="text" placeholder="Enter Title For the Item" class="form-control input-md" required="">

                      Description

                        <textarea class="form-control" name="description">Enter Description of Portfolio Item</textarea>

                         Select Category

                          <?php
                                $sel="SELECT cat_id,cat_name from categories order by  cat_name asc";
                                $query=mysqli_query($link,$sel);
                                while($row=mysqli_fetch_array($query))
                                {

                                    echo "
";
                                    echo "";
                                    echo "<input type='radio' name='category' value='".$row['cat_id']."'>";
                                    echo $row['cat_name'];
                                    echo "";
                                    echo "
";

                                }
                            ?>

                      Duration of Project

                      <input name="duration" type="text" placeholder="Enter Duration in Hrs" class="form-control input-md" required="">

                      File Button

                        <input name="nImage" class="input-file" type="file">

                        <button id="submit" name="submit" class="btn btn-success">Add New Portfolio Item</button>

                    </fieldset>
                    </form>

here is my database table image :

Any help would be highly appreciated. Thanks in advance :-)
Comment: You're not only wide open to sql injection, it's very simple to inject you with bad files, too
Comment: echo the insert query and try to directly execute from mysql(or phpMyAdmin) ...
Comment: To your question, do you have any error messages?
Comment: Where are you creating the connection?
Comment: The Database is connected on the other file which is linked to the page. Database connection is not the problem....
Comment: I get no error messages but add_portfolio.php refreshes. This is the Add New Portfolio form page. @baao
Comment: You get no error messages because you don't check for them.
Answer: To submit data from HTML form, you are using button, that clearly does not send form data,you have to use input type="submit", so change this line of code
<button id="submit" name="submit" class="btn btn-success">Add New Portfolio Item</button>

to
<input type="submit" id="submit" name="submit" class="btn btn-success" value="Add New Portfolio Item" />

Answer: You should probably use a lot less nested ifs, especially when they all do the same result of 'else'.
if ( ( $a=3 )
  && ( $b=7 )
  && ($car >= 9)
  && ( $name == 'steve' )
  && ( $more == 'stuff' ) ) {
  // Run stuff here
) else {
  exit('error');
}

After your mysqli_query(); for inserting, run an error check with mysqli_error($link); It will tell you of any problems. mysqli_query doesn't return any errors, only 'true' or 'false' depending on how it ran.
Answer: My Problem is solved. I used concatenation in the query. Here is how my working code looks like(just query) :
$qry=mysqli_query($link,"INSERT INTO `p_o_r_t_f_o_l_i_o`(`title`,`description`,`duration`,`category`,`image`) values('".$title."','".$description."','".$duration."','".$category."','".$portfolio_img_dir."')");

Thanks a lot for everyone who tried to help. Cheers!!

I cant add row in my Database


How can I set the view mode of a node through rules

Question: I'd like to change the view mode of a node based on the role of a user and another flag in the node, and by using the Rules module.
Since a call to display the node by default is full content, I wrote a rule that on Content is Viewed for that node type, it then checks the conditions and sets data value view-mode to teaser.
However, even when the conditions are met properly the node still displays full text.
From this I am assuming that Content is Viewed is being executed after rendering or am I missing something in my approach?
Comment: Nope, you are basically right. Content is Viewed is being executed at the point when altering view mode is pretty much useless. At least if I understand it properly, that is. And don't forget caching - maybe you have node display cached and that's why it is ignored? Why not to simply do it on theme level?
Answer: What "Content is viewed" actually means, seems to be like so:

The event Content is viewed is what it is: the user has (already) started viewing the content.
The (system) event Drupal is initializing is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" BEFORE the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to
How to specify a Rules event like "Content is 'going to be' viewed"?
Be aware: this applies to D7 ... and D6 is another story (from the question context I'm not sure if this is fopr D6 or D7 ...).
Answer: For such a simple task don't use Rules. Or any other dependency-heavy module. Getting to the root of your problem, you want to switch the view mode depending on some custom logic. Then all you need is one small snippet placed in a basic custom module: hook_entity_view_mode_alter().

Change the view mode of an entity that is being displayed.

You can easily add any custom logic inside this sample code:
function hook_entity_view_mode_alter(&$view_mode, $context) {

  // Render node in a different view mode when accessed as teaser.
  if ($context['entity_type'] == 'node' && $view_mode == 'teaser') {
    $view_mode = 'teaser_foo';
  }
}

Answer: You might alternatively try the combination of Display Suite and Contextual View Modes (for setting the view mode) and Context (for getting the condition) modules.
Obviously this is an overkill for what you and me want to achieve plus for some reason Contextual View Modes doesn't work for me right as I'm getting errors.
If you manage to use rules, please make sure to share the rule you wrote to change the view mode!
Edit: OK this setup actually does work very well and the errors don't interfere with functionality. Regarding your specific problem (I know it's a lot of modules but what the hell):

Install Display Suite, Contextual View Mode, Context
Set up your custom view modes with display suite
Add invisible taxonomy term to content type
Make rules trigger a term change in that taxonomy field when node is flagged (this is needed because context module doesn't listen to flags - the sandbox modules intended for that don't work for me either)
Create a taxonomy and user role context (as per your requirements)
Set up Contextual View Modes module (see module page for instructions)

This should work.
BTW I was using the latest development releases.
Answer: This isn't good for performance I guess but try changing the view mode using the rule, then force entity save and redirect to the page again..
I'd consider the other solutions given here or panels with different variants.


Will high school competition math materials help me prepare for the Putnam?

Question: I am a graduating high school senior, and I will be starting college this September. During my middle and high school years, I have done introductory math competitions like Mathcounts, AMC, AIME, etc., but I have never gotten far (USA(J)MO, MOP, etc.). Now, since I am entering college, I am thinking of seriously preparing for the Putnam. Yes, I know that I have a lot to catch up, but I still want to try.
Thanks to some older students who gave their used books to me, besides my own materials, I have tons of high school competition math preparation books and resources. Just to mention a "few":

Art of Problem Solving books (volume 1, 2, introduction, intermediate, etc.)
"_ _ Problems" series (e.g. 104 Number Theory Problems, 105 Algebra Problems, 110 Geometry Problems)
Lemmas in Olympiad Geometry
Titu's Problems from the Book (and Straight from the Book)
Engel's Problem-Solving Strategies
Past AMC/AIME/USA(J)MO/IMO problems and solutions
Titu's Topics in Functional Equations
Titu's Mathematical Olympiad Challenges
Notes from summer programs like AMSP
The IMO Compendium
Evan Chen's EGMO

These are tons of unused resources, so I was just wondering if these books are useful in my preparation for the Putnam. Or, are the Putnam and the high school competitions too unrelated that it would likely be a waste of time to spend my time on these books? I guess it is possible that some of these books are relevant, while others aren't. If someone with experience in these resources and Putnam could answer this question, I would appreciate it. Thank you for any help that you are able to provide.
Comment: They involve very different topics, like the Putnam doesn't cover Euclidean geometry to the extent that the olympiads do, while requiring knowledge of abstract algebra and analysis. If are new to proof writing (esp if you didn't get far in USAJMO), then I'd recommend getting started with Engel's Problem solving strategies (or Paul's Art and Craft of problem solving). If you're confident (and know what it means to write a complete solution), then I'd suggest Titu's Putnam and Beyond.
Comment: It helps to 1) categorize problems and work on similar ones to learn about the various techniques/tricks/ideas, and when you've built up your knowledge/confidence then 2) take a 2000+ Putnam and start working through A/B 1/2(maybe 3) and solve them completely (write up your solution, then have a friend read it without you around).
Answer: The USAMO and USAJMO questions will only help you with proof writing. You should focus more on calculus, abstract algebra, etc. The IMO focuses on high school material while the Putnam is more college material. You should focus on the basic of IMO prep such as basic euclidean geometry, basic combinatorics and more Putnam style questions such as matrices. Good luck and have fun!!


Formulating a simple combinatorics problem in a 3x3 grid

Question: I have a 3x3 grid, and I want to move from a point A in the left corner below, to a point B in the right corner above. I can move 2 times horizontally, and 2 times vertically. The number of paths that allow me to do this are 6 (the combinations of 4 in 2).
Now I would like to put the restriction of finding the paths that go from A to B WITHOUT passing through the central vertex of the grid. The result should be 2, but I know this because i did drawings. I would like to know how to formulate the problem algebraically, so that then i could be able to generalize it for an nxn grid.
I don't have a clue about how to do this...
Thanks in advance.
Answer: Suppose more generally that we wish to move $a$ to the right, and $b$ up. We want to avoid a certain point $X$ which is $p$ to the right, and $q$ up.
Let us count the paths that go through $X$. There are $\binom{p+q}{p}\binom{a+b-p-q}{a-p}$ of these. For there are $\binom{p+q}{p}$ ways to go to $X$, and for each of these ways there are $\binom{a+b-p-q}{a-p}$ ways to go the rest of the way.
Subtract this number of bad paths from the total $\binom{a+b}{a}$.
Answer: The easiest way to handle something like this is to note that if $P$ is the set of all such paths, $P_G$ ("$P$ Good") is the set that don't go through the center vertex, and $P_B$ ("$P$ Bad") is the set that DO go through the center vertex, then
$$
\lvert P_G\rvert=\lvert P\rvert-\lvert P_B\rvert.
$$
Can you see how to count the paths that go through the center vertex?  Note that choosing such a path consists of (1) choosing a path to the center vertex from the start and (2) choosing a path to the end from the center vertex.


Consumindo API ReactJs

Question: Sou novo em ReactJs, quando tento consumir uma API local eu não consigo, acredito que seja essa mensagem:

localhost You need to enable JavaScript to run this app.

Meu código:
 export default class App extends React.Component {
      state = {
        api: []
      }

      componentDidMount() {
        axios.get('http://localhost:3010/teste')
          .then(res => {
            const api = res.data;
            this.setState({ api  });
          })
      }

      render() {
        return (

            { this.state.api.map(apiaux =>

{apiaux.id}

            )}

        )
      }

Answer: Verifique se o endereço http://localhost:3010/test está funcionando normalmente no browser (se ele retorna dados ou não). Mas acredito que algo está faltando no seu ambiente React. Se o plugin de javascript está ativado no seu browser, w se você utilizou boilerplate (que é uma estrutura inicial), verifique se está configurado corretamente. Minha sugestão é que você utilize o gerador de app
Que é mais ou menos parecido com isso
npx create-react-app my-app
cd my-app
npm start
Outra alternativa é utilizar Rekit Studio. Ele ja vem com as principais bibliotecas e até com um editor próprio. Quando eu comecei utilizei ele, e ainda utilizo. Ainda estou aprendendo, tem muitos conceitos interessantes, que vai te ajudar na programação javascript ES6 e código JSX (que usam aquelas marcações pseudo Html como  e outros.
Answer: Boa tarde,
Confira este link da microsoft, basicamente você terá de habilitar o JS no seu pc
https://support.microsoft.com/en-us/topic/how-to-enable-javascript-in-windows-88d27b37-6484-7fc0-17df-872f65168279

Consumindo API ReactJs


Modulo with negative numbers

Question: When I input this in wolfram I get false

-347 mod 6 = 5

When I input this I get true

-347 mod 6 = 1

And yet I know

$-5 \equiv 1$

And additionally

$-6*57 - 5 = -347$

but

$-6*57 - 1 \neq   -347$

So it's strange that Wolfram's answer is true for +1
Why does Wolfram answer it that way?
Comment: What's so strange? $6 \times -57 + (-5) = -347$ so $-347\equiv -5\equiv +1$.
Comment: Well, isn't this what you'd expect?  -5 = 1 so 6x-57 -5 =1
Answer:
$a\equiv b\pmod c$ means $c|(a-b)$

$-347\equiv1\pmod6$ is true because $6$ divides $(-347-1)=-348$
But,$-347\equiv5\pmod 6$ is not true because $6$ does no divide $(-347-5)=-352$.
Comment: So if the dividend is negative, I add the remainder to the modulus?
Comment: @the_prole It depends on the sign of the divisor....
Answer: $$-347=5\pmod6\iff -347-5=0\pmod 6\iff 6\,\mid\,-352$$
and we can easily check that in fact $\;6\,\nmid\,-352\;$.
Yet
$$-347=1\pmod6\iff -347-1=3-248=0\pmod 6\;,\;\;\text{and}\;\;-348=(-58)\cdot6$$
What you say would be odd if we had $\;5=1\pmod6\;$ (in fact, it'd impossible), but we don't. We have $\;5=-1\pmod6\;$, and $\;1\neq-1\pmod6\;$
Answer: $-347 \pmod 6$ cannot be congruent to both 5 and 1 because these two numbers differ by 4 (and not by 6).
You can always subtract or add multiples of 6 to either side of an equation and it will still hold. For example, since $-347 \pmod 6 = 1$, repeatedly adding 6 to -347 (i.e. -341, -335, -329, etc) will eventually hit 1.  Before reaching 1, it was equal to -5. The next number after 1 is 7.  So we will never the number 5 in such a sequence.

Modulo with negative numbers


How can I conditionally display something in Views header area depending on the argument in URL?

Question: The URL of my page view looks like my-view/%1/%2
The first argument %1 is term id of either vocabulary A or B or C and all of them are hierarchical taxonomy.
How can I conditionally display something in Views header global text area depending on which vocabulary %1 is or if it's parent term or child term?
Answer: I don't know if it's standard practice to answer such an old post, but another solution may be helpful to those who don't want to do any coding.  You can conditionally attach a header by using Views Attachments. This may not be the best practice for a production site, but that's another discussion. This answer is just to let you know of the possibilities.
Add an Attachment display for each Vocabulary you want a separate header for, and set their properties according to the images below. Notice that all attachment properties are overridden, in order to not affect your main Page or Master (default) display.
Edit: The images displayed below are for Views 3.x. Hopefully, they are helpful for Views 2.x, as well.

Add Attachment:

Add an attachment for each header you want displayed conditionally (as shown above).

Attachment Filter:

The above filter will ensure no records are displayed by the attachment, only the header.

Contextual Filter (1/2):

Set the contextual filter for each attachment (as shown above and below).

Contextual Filter (2/2):

Set the term to be used for this attachment (my example is "Glossary"). Be sure Action to take if filter value does not validate is set to 'hide', so that only the desired header is displayed.

Attach To Page:

Be sure to attach your attachment to something (here, attached to the "Page" display). Click on Global: Text Area to set your header.

Set Global: Text Area (in Attachment Header):

Click Global: Text Area (prev image) and set your desired header. Notice: still overridden. Also be sure to check Display even if view has no result since the filter for the attachment excludes all records.

Page/default Contextual Filter:

Last, but not least, set the Contextual Filter for the main page itself (not an attachment) according to your needs.
Answer: I would suggest to use the panels module: there you can create a page that contains the view and add optional content based on available contexts.
Answer:
add an essentially blank global header text area to the view.
use hook_views_pre_render() for the view to inspect the url arguments and insert the necessary content into the global header.
profit.
Answer: You have done half of the thing. If there is too much code then, I guess the best option is to write a function inside a module, call the function in Global Text Area and pass the arguments.
Answer: I'd add the Views PHP module, the add the header as a PHP header.
From there I would user the argument from the URL for my conditional.
Ex: if your path is my-view/%1/%2 and your condition is based on %1 you'd do
if (arg(1) == 'foo'): print 'this'; else: print 'that'; endif;

if your path is my-view/%1/%2 and your condition is based on %2 you'd do
if (arg(2) == 'foo'): print 'this'; else: print 'that'; endif;


Spliting dataframe into chunks by the rows that satisfy the given condition

Question: I have a dataframe similar to:
 col1   col2
 1      10
 1      30
 2      60
 3      20
 3      12
 3      51
 3      11

I want to divide this dataframe into chanks when the value in col2 is bigger than 50:
dataframe #1
col1   col2
1      10
1      30
2      60

dataframe #2
col1   col2
3      20
3      12
3      51

dataframe #3
col1   col2
3      11

I have tried split function but it would not serve for this task. I wonder if there is a generic function to achieve this?
Comment: I was wondering how you want to handle if there are multiple values above 50 in a row. I.e., if `col2 = c(10, 30, 60, 61, 20)` do you want to have 2 chunks `10, 30, 60, 61` and `20` or 3 chunks `10, 30, 60`, `61`, and `20`.?
Answer: You can use cumsum in split, with a lot of reving to include the rows where col2 > 50 in the previous group
rev(split(df, rev(cumsum(rev(df$col2 > 50)))))
#@joran method, (same result, except for names):
split(df, cumsum(df$col2 > 50) - (df$col2 > 50))

Output:
# $`2`
#    col1 col2
# 1:    1   10
# 2:    1   30
# 3:    2   60
#
# $`1`
#    col1 col2
# 1:    3   20
# 2:    3   12
# 3:    3   51
#
# $`0`
#    col1 col2
# 1:    3   11

without all the revs you get this
split(df, cumsum(df$col2 > 50))

# $`0`
#    col1 col2
# 1:    1   10
# 2:    1   30
#
# $`1`
#    col1 col2
# 1:    2   60
# 2:    3   20
# 3:    3   12
#
# $`2`
#    col1 col2
# 1:    3   51
# 2:    3   11

Comment: An alternative, probably no more/less complicated: `cumsum(df$col2 > 50) - (df$col2 > 50)`.
Comment: thanks! Without help, it was really impossible to figure this out myself..


What does the kCF prefix mean?

Question: Many constants in CoreFoundation have the kCF prefix. What does it mean?
Comment: "[…] constants in CoreFoundation" – well, just that. `k` for "constant", `CF` for "CoreFoundation".
Comment: @TheParamagneticCroissant Any references? Thanks.
Answer: In both OS X Frameworks and
iOS Frameworks
you find a list of system frameworks together with the key prefixes used by the classes, methods, functions, types, or constants of the framework.
This list contains

Name                      Prefix
--------------------------------
...
CFNetwork.framework       CF
...
CoreFoundation.framework  CF
...

So there are actually several frameworks using the "CF" prefix, but
Core Foundation is the most "prominent" one.
The "k" prefix for constants is documented in
Naming Conventions
in "Introduction to Core Foundation Design Concepts"
(emphasis added):

A major programming-interface convention in Core Foundation is to use
  the name of the opaque type that is most closely related to a symbol
  as the symbol's prefix. For functions, this prefix identifies not only
  the type to which the function "belongs" but usually the type of
  object that is the target of the function's action. (An exception to
  this convention are constants, which put "k" before the type prefix.)

As an example, kCFAllocatorMalloc is a constant related to
the CFAllocator type  which is part of the Core Foundation framework.
Comment: Thank you so much for your patient!
Answer: k stands for Constant & CF stands for Core Foundation
Comment: Any references? Thanks.
Comment: I'm a little curious about that why don't use first characters `c` of constant.
Comment: I think `k` stands for `key`
Comment: check the definition...  (An exception to this convention are constants, which put "k" before the type prefix.)
Comment: discussion for 'k' naming - http://stackoverflow.com/questions/9064794/what-does-the-k-stand-for-in-cocoa-constant-names

What does the kCF prefix mean?


Explaining why $f(x)=\log_{1.1}(x)$ and $g(x)=x$ intersect in more than one point without using a calculator

Question:
The functions $f(x)=\log_{1.1}(x)$ and  $g(x)=x$ are represented in
  the picture below:
In this representation it can be seen one point of intersection of the
  two functions.
Without using the calculator, explain that that is not the only point
  of intersection of the two functions.

My book says the solution is:

The graphs have to intersect at least one more time because
  $$\lim_{x
\rightarrow +\infty}\frac{f(x)}{g(x)} = 0$$

What I don't understand exactly is the meaning of $\frac{f(x)}{g(x)}$ in this context.
Is it some sort of ratio or perhaps diference than decreases as $x$ increases?
That would explain that, since this "ratio" gets smaller and in the picture $f(x)$ is greater than $g(x)$ after the intersection, $f(x)$ would have to decrease thus making this ratio decrease, until it becomes smaller than $g(x)$, therefore having to intersect it again.
Am I correct? Can someone explain to me better what $\frac{f(x)}{g(x)}$ means in this context, or what this "ratio" represents exactly?
Answer: Sorry to use base $e$ logarithms (they are the only I know !).
Consider the function $$f(x)=\frac{\log (x)}{\log \left(\frac{11}{10}\right)}-x$$ and its derivatives $$f'(x)=\frac{1}{x \log \left(\frac{11}{10}\right)}-1 \qquad f''(x)=-\frac{1}{x^2 \log \left(\frac{11}{10}\right)}$$ The first derivative cancels at $$x_*=\frac{1}{\log \left(\frac{11}{10}\right)}\implies f(x_*)=-\frac{1+\log \left(\log \left(\frac{11}{10}\right)\right)}{\log
   \left(\frac{11}{10}\right)}\qquad f''(x_*)=-\log \left(\frac{11}{10}\right)$$ So, the point $x_*$ corresponds to a maximum (by the second derivative test) and then two roots to the equation $f(x)=0$ since $f(x_*)>0$.
Edit
If you make the problem more general for $f(x)=\log_a(x)-x$, the derivative will cancel at $x_*=\frac{1}{\log (a)}$ for which $f(x_*)=\frac{\log \left(\frac{1}{\log (a)}\right)-1}{\log (a)}$ and there will be two roots if $f(x_*)>0$ that is to say if $a<e^{\frac{1}{e}} \approx 1.44467$.
Answer: "since this "ratio" gets smaller and in the picture $f(x)$ is greater than $g(x)$ after the intersection, $f(x)$ would have to decrease thus making this ratio decrease, until it becomes smaller than $g(x)$, therefore having to intersect it again": you are correct as far as I can tell. When we say $\lim_{x \to \infty} \frac{f(x)}{g(x)} = 0$, we intuitively mean that $f(x)$ is much, much smaller than $g(x)$ in the long run and continues to get smaller in comparison as $x$ approaches larger values. In the rough figure, $f(x)$ is greater than $g(x)$, so it would have to eventually intersect and go below.
Answer: I don't think your initial intuition is a bad way of looking at it. If $\lim_{x
\rightarrow +\infty}\frac{f(x)}{g(x)} = 0$, then at some point it must be that $g(x) > f(x)$ (in the top left quadrant). Since $g(x) < f(x)$ in the diagram currently, then eventually, if the functions are continuous, they must intersect.
A slightly more formal way to think about this is by considering the function $h(x) = f(x) - g(x)$ and considering its roots. We know $h(x) = 0$ at the point of intersection in the diagram and after this root, $h(x) > 0$. Also since $\lim_{x \rightarrow +\infty}\frac{f(x)}{g(x)} = 0$, we know at some point $g(x) > f(x)$ i.e $h(x) < 0$.
Since we have $x_1$ and $x_2$ such that $h(x_1) > 0$ and $h(x_2) < 0$, by the intermediate value theorem, there must be some point $x$ with $x_1 < x < x_2$ where $h(x) = 0$ or in other words, there must be some point where $f(x) = g(x)$.
Answer: One way to interpret your ratio and limit is that if that limit is 0, then $g(x)$ "grows faster" than $f(x)$. Have you heard your teacher use that language? If not, it more or less means that for a large values of $x$, $g(x)$ is much larger than $f(x)$.
With that in mind, your picture shows one intersection point. More important, you see that $f(x)$ is on top.
But now that you know that your limit implies $g(x)$ is eventually larger than $f(x)$, you can reason that there must be a point (off to the right, not seen on the picture) where $g(x)$ overtakes/crosses over/necessarily intersects $f(x)$.
Does that make any sense?
Comment: Yes, that makes sense


What does it mean for two field extensions over $\mathbb{Q}$ to be "$\mathbb{Q}$-isomorphic?"

Question: I have seen this terminology in two texts and for whatever reason cannot find a source for what this means. Does this mean the two extensions are field isomorphic? Thanks.
Comment: You cannot find a source? Search stackexchange next time, e.g., [here](https://math.stackexchange.com/questions/4067132/f-homomorphism-between-two-field-extensions?rq=1).
Comment: No problem. I think one also has to get experience in searching. I found it rather quickly. You can try it next time.
Comment: Apologies. Understood if this question should be closed, but I spent a decent bit looking and didn't find anything.
Answer: If $L_1$ and $L_2$ are two extensions of $K$ then they are called $K$-isomorphic if there is an isomorphism of fields $\varphi: L_1\to L_2$ such that $\varphi(k)=k$ for all $k\in K$. Equivalently, this means that $L_1, L_2$ are isomorphic as $K$-algebras.
Note that in the special case $K=\mathbb{Q}$ this just means there is an isomorphism of fields between $L_1$ and $L_2$. (since any homomorphism leaves the elements of $\mathbb{Q}$ fixed)


Extracting Prepositional Phrases from Sentence

Question: I'm trying to extract prepositional phrases from sentences using NLTK. Is there a way for me to do this automatically (e.g. feed a function a sentence and get back its prepositional phrases)?
The examples here seem to require that you start with a grammar before you can get a parse tree. Can I automatically get the grammar and use that to get the parse tree?
Obviously I could tag a sentence, pick out prepositions and the subsequent noun, but this is complicated when the prepositional complement is compound.
Comment: Maybe this post will help http://stackoverflow.com/questions/6115677/english-grammar-for-parsing-in-nltk
Answer: What you really want to do is to fully parse your sentence with a robust statistical parser (e.g. like Stanford), and then look for constituents marked with PP:
<code>(ROOT
  (S
    (NP (NNP John))
    (VP (VBZ lives)
      (PP (IN in)
        (NP (DT a) (NN house)))
      (PP (IN by)
        (NP (DT the) (NN sea))))))
</code>
I am not sure about the parsing abilities of NLTK and how accurate is the parsing if this feature exists, but it's not much of a problem to call an external parser from Python and then process the output. Using a parser will save you much time and effort (since the parser takes care of everything), and is the only reliable way to do this job.
Comment: I wouldn't say an overkill but a necessary complication. If you try to build a rule-based PP-recognizer, you will end up spending a lot of time and effort for mediocre results.
Comment: Obviously a full parse is an overkill, but it would get to the end goal. I'll give it a shot. Looks like there is [at least one](http://projects.csail.mit.edu/spatial/Stanford_Parser) Python interface to the Stanford parser.
Answer: I know the answer was already accepted, but a shallow parser will return the NLP chunks with minimal syntactic structure. This fairly linear result may be easier to work with. Here's an online demo of the CLiPS parser: http://www.clips.ua.ac.be/cgi-bin/webdemo/MBSP-instant-webdemo.cgi
Here's an example:
John gave the book to Mary

The [PNP] is easy to extract.
Comment: I tested this against multiple types of datasets seems to perform better in the extraction of NPs and PNPs - especially for biomedical text.


How to create a REST request using the Shopify Node JS API for a Private App?

Question: I'm trying to use the Shopify API to query all the orders of a selected Shopify store, using the private app instead of the OAUTH method. Below I have added the code, can't seem to figure out how to get it to work cause there isn't much documentation for the use of the private apps. Does anyone know how I can achieve this or has done this before? I think I maybe wrong but there maybe an error in creating the session.
Upon running the below code I get the below error:
Error: Missing adapter implementation for 'abstractRuntimeString' - make sure to import the appropriate adapter for your platform
const { shopifyApi, ApiVersion, Session, LATEST_API_VERSION } = require('@shopify/shopify-api');
const { randomUUID } = require('crypto');
const { restResources } = require('@shopify/shopify-api/rest/admin/2022-10');

const selectedStore = {
shop: "store.myshopify.com",
api_secret: "",
api_key: "",
private_admin_key: ""
};

const shopify = shopifyApi({
    apiKey: selectedStore.api_key,
    apiSecretKey: selectedStore.api_secret,
    scopes: ['read_orders', 'read_analytics', 'read_customers'],
    hostName: '<ngrok_url>',
    apiVersion: LATEST_API_VERSION,
    isEmbeddedApp: false,
    isPrivateApp: true,
    restResources
});

const session = new Session({
    id: randomUUID(),
    state: 'state',
    shop: selectedStore.shop,
    accessToken: selectedStore.private_admin_key,
    isOnline: true,
})

console.log(session)

const getOrders = async () => {
    const orders = await shopify.rest.Order.all({
        session,
        status: "all"
    })
    return orders
}

getOrders()

Answer: In regards to the following errors:
Error: Missing adapter implementation for 'abstractRuntimeString' - make sure to import the appropriate adapter for your platform

You will need to add the following line
import '@shopify/shopify-api/adapters/node'

Before
import ... from '@shopify/shopify-api'

This is only lightly touched upon in their migration guide
Shopify developer experience with this library has definitely been rough
Source: https://github.com/Shopify/shopify-api-js/issues/400#issuecomment-1363021024
Answer: If you have a Auth Token from a private App (inside the Shopify Admin), with permissions to read orders, you make a call to the Shopify store using that token. Look up the end point you call. Formulate your call. Make a GET or POST. Nothing hard to do there. Shopify assumes you know how to make a GET request with JS. Provide the Auth Token you gave yourself, and you'll get back all the orders you asked for. You cannot skip out on learning paging etc.. but again, that is also pretty standard stuff not special to Shopify.
Comment: Hi David, thanks for the response do you know of any way to do this through the Shopify library, I am familiar with the REST API approach and was able to get that to work but was wondering whether there is a method to do this using the library instead
Comment: I have no idea what the Shopify library is. Sorry. I know Shopify well, but I have never heard of the library!


Disable clear at start of screen via .screenrc?

Question: Is there any way to disable the behavior of gnu-screen, of issuing a clear at startup?
I'm using screen merely as a backstop, so that if disconnected, the session isn't HUP'ed. And I've got my shell (bash) config'd to "exec screen -A" on login, so that I get right into screen automatically.
However, screen immediately issues a clear and then I've got to scroll back up to see whatever login messages there might have been.
Similarly, at exit, I'd like to skip the clear there too, so I can see the results of my .bash_logout.
(If it's any help, my term is usually xterm-color (via Mac OS X's Terminal.app) though I do sometimes come in via ssh from some other node. And I'm generally connecting to an Ubuntu box/instance.)
Answer: Because screen takes over the entire screen, its not possible to have it leave the terminal buffer unprocessed.  If you're interested in the motd specifically, you can always have your .bash_profile call cat /etc/motd, which would give you the same functionality.
Another option is to just call screen manually, which sounds like it might be the behaviour you want anyway--since you're not actively using the screens to do work.  This is even further recommended if you're worried about having a compromised account--since the login screen also shows your last login location.
Comment: I *do* want screen to run automatically - so I don't have to remember to do so -- probably right *after* I get disconnected and remember I haven't. :/
Comment: I'm already using "termcapinfo xterm*|xterms|xs|rxvt ti@:te@" (in .screenrc) to capture everything via my terminal buffer (vs. screen's), so I'm close; I just want to skip the clear at startup (and exit).
Comment: BTW: Using screen seems the only way to *automatically* keep sessions active in case of disconnect - though I'm happy to be proven wrong here. This is the primary functionality I'm looking for.
Comment: You can `nohup` and background the command, but once you logout with the session, you will never be able to bring it to the foreground, so make sure you pipe output to a file to be read later.
Answer: As mentioned by Redmumba, screen takes over the entire terminal so you can't have it take over the existing buffer and display.
What I have done is changed my .screenrc to display a status bar at the bottom of the terminal window, and trained my fingers to say screen -ADR if I don't see that status bar.  That way you have a visual cue that you are in fact running screen, and a reflex that will start it for you before you start to do anything which might not survive accidental disconnecting.
(Also, if you have the current time being displayed in the screen status bar, this acts as a keep-alive signal that can prevent connections from disconnecting due to being idle too long.)
Comment: Right; I don't want it to take over the existing buffer - I'd actually prefer it do nothing at all to the buffer/display. :)
Comment: I appreciate the other suggestions - though of course a fully automatic method is preferable.
Comment: Perhaps screen isn't the right tool for what I'm looking for; I just want something that will *by default* leave my session open if there's a disconnection, so I can pick up where I left off.


Phpmyadmin timestamp currenttimestamp

Question: I've set my date_added column to timestamp and default value to current_timestamp.
Does this mean each new row the date_added value will automatically be the current timestamp?
For example: Comments table.

comment_id{PK][AI],user_id[FK],content,date_added

Every new comment i insert, i also need to add in a date for when it was posted so when viewing the comment i can print out an " months/hours ago" using timespan();in CI.
$now = time();
$data['user_id'] = $user_id;
$data['content'] = $content;
$data['date_added'] = mdate("%Y-%m-%d h:i:a",$now);
$this->db->insert('comments',$data);

instead i can just remove the date added part.
This should be a shortcut to manually inserting the current time via date_helper in CI whenever i insert a new row. However, i would like to ask if my logic is correct or if i am misusing the current_timestamp function of phpmyadmin?
Comment: Correct, each new row will be filled with the current timestamp
Comment: In your view, am i misusing the phpmyadmin function for my laziness? or is it a sound logic?
Comment: No, not lazy, it's a convenience in my point of view..
Answer: The current_timestamp is not a function of phpmyadmin, it's a feature of MySQL.  It's not lazy, it's perfectly acceptable to use it in the way you are.

Phpmyadmin timestamp currenttimestamp


How to create Line charts?

Question: I would like to create Line charts (2-D Line with Markers) for a set of records.
Screenshot of Excel tab

(a) Every three rows represent a set to be charted. The fourth column, though it appears, need not be charted. In the screenshot there are 18 rows, which is six sets of records.
(b) One Line chart required for each set of records. Hence a total of six charts to be created automatically.
(c) Also, the charts are to be created in different Excel tabs. Three charts per tab, hence this should create two Excel tabs with three charts placed in each tab.
Comment: Check here https://stackoverflow.com/questions/26674275/excel-macro-to-create-line-chart-excluding-columns-in-between
Comment: Possible duplicate of [Excel macro to create line chart excluding columns in between](https://stackoverflow.com/questions/26674275/excel-macro-to-create-line-chart-excluding-columns-in-between)
Answer: I have prepared some code for automatic charts generation using VBA macro in excel see if this helps.
Below code will generate charts for data available in excel:
<code>Dim Startrow As String
Dim Lastrow As String
Dim Lastcolumn As String
Dim ws1 As String
Dim cs2 As String
Dim cs3 As String
Dim ws(100)
Dim count As String
Dim i As Integer

Sub Final()
For j = 2 To Sheets.count
    count = Sheets.count
    Sheet1.Activate
    Cells(i, 1) = Sheets(i).Name
    'ws(i) = Sheets(i).Name
    'MsgBox Sheets.Count
    'MsgBox count
    'MsgBox ws(i)
Next

For i = 2 To count
    MsgBox count
    MsgBox i
    Sheet1.Activate
    ws(i) = Cells(i, 1)
    Sheets(ws(i)).Activate
    'Sheets(ws(i)).Activate
    MsgBox ws(i)
    'MsgBox Range("B1")
    'MsgBox IsEmpty(Range("B2"))
    If IsEmpty(Range("B1")) = False Then
        Startrow = 2
        'MsgBox Startrow
        Lastrow = Cells(Rows.count, 1).End(xlUp).Row
        'MsgBox Lastrow
        Lastcolumn = Split(Columns(Range("A1").End(xlToRight).Column).Address(, False), ":")(1)
        'MsgBox Lastcolumn
        Call test1
        MsgBox i
    End If
Next

End Sub

Function test1()

Dim letter As String
Dim letter1 As String
Dim letter2 As String
Dim letter3 As String

Dim x As Integer
MsgBox ws(i)
x = Range(Lastcolumn & 1).Column
'MsgBox x

Dim cs As Worksheet
Set cs = ThisWorkbook.Sheets.Add
'ws.name = "PrivateBytes_000005_Charts"
'ws2 = "PrivateBytes_000005_Charts"
cs.Name = ws(i) + "_Charts"
'MsgBox ws.Name
cs2 = ws(i) + "_Charts"
MsgBox cs2
cs3 = ws(i)
MsgBox cs3

If x < 27 Then

    For i = 2 To x

        letter3 = Chr(64 + i)

        'chart command

          Sheets(cs2).Activate
          ActiveSheet.Shapes.AddChart2(227, xlLineStacked).Select
          ActiveChart.SetSourceData Source:=Sheets(cs3).Range("A" & Startrow & ":A" & Lastrow & "," & letter3 & Startrow & ":" & letter3 & Lastrow)

          With ActiveChart
              .HasTitle = True
              Sheets(cs3).Activate
              .ChartTitle.Text = Range(letter3 & "1").Value
              .Axes(xlCategory, xlPrimary).HasTitle = False
              .Axes(xlValue, xlPrimary).HasTitle = False
          End With

    Next

End If

If x >= 27 Then

    For i = 2 To 26

        letter3 = Chr(64 + i)

        'chart command

        Sheets(cs2).Activate
        ActiveSheet.Shapes.AddChart2(227, xlLineStacked).Select
        ActiveChart.SetSourceData Source:=Sheets(cs3).Range("A" & Startrow & ":A" & Lastrow & "," & letter3 & Startrow & ":" & letter3 & Lastrow)

          With ActiveChart
              .HasTitle = True
              Sheets(cs3).Activate
              .ChartTitle.Text = Range(letter3 & "1").Value
              .Axes(xlCategory, xlPrimary).HasTitle = False
              .Axes(xlValue, xlPrimary).HasTitle = False
          End With

    Next

    For i = 27 To x

        letter3 = Chr(Int((i - 1) / 26) + 64) & Chr(((i - 1) Mod 26) + 65)
        'MsgBox letter3

        'chart command

        Sheets(cs2).Activate
        ActiveSheet.Shapes.AddChart2(227, xlLineStacked).Select
        ActiveChart.SetSourceData Source:=Sheets(cs3).Range("A" & Startrow & ":A" & Lastrow & "," & letter3 & Startrow & ":" & letter3 & Lastrow)

          With ActiveChart
              .HasTitle = True
              Sheets(cs3).Activate
              .ChartTitle.Text = Range(letter3 & "1").Value
              .Axes(xlCategory, xlPrimary).HasTitle = False
              .Axes(xlValue, xlPrimary).HasTitle = False
          End With

    Next
End If

Sheets(cs.Name).Activate
ActiveChart.Parent.Name = "Test1"
Call AutoSpace_Shapes_Vertical
'Return
'Unload UserForm1
End Function
Function AutoSpace_Shapes_Vertical()

'Automatically space and align shapes
    Sheets(cs2).Activate
    ActiveSheet.ChartObjects("Test1").Activate
    ActiveSheet.Shapes.SelectAll

Dim shp As Shape
Dim lCnt As Long
Dim dTop As Double
Dim dLeft As Double
Dim dHeight As Double
Const dSPACE As Double = 8

  'Check if shapes are selected
  If TypeName(Selection) = "Range" Then
    MsgBox "Please select shapes before running the macro."
    Exit Function
  End If

  'Set variables
  lCnt = 1

  'Loop through selected shapes (charts, slicers, timelines, etc.)
  For Each shp In Selection.ShapeRange
    With shp
      'If not first shape then move it below previous shape and align left.
      If lCnt > 1 Then
        .Top = dTop + dHeight + dSPACE
        .Left = dLeft
      End If

      'Store properties of shape for use in moving next shape in the collection.
      dTop = .Top
      dLeft = .Left
      dHeight = .Height
    End With

    'Add to shape counter
    lCnt = lCnt + 1

  Next shp
End Function
'End Sub
'End Sub
</code>
enter image description here

How to create Line charts?


Why i'm getting Win32Exception when trying to get info from process inside a backgroundworker?

Question: DoWork event:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (true)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    Stopwatch sw = Stopwatch.StartNew();
                    PopulateApplications();
                    sw.Stop();
                    int msec = 1000 - (int)sw.ElapsedMilliseconds;
                    if (msec < 1) msec = 1;   // Don't consume 100% CPU
                    System.Threading.Thread.Sleep(msec);
                }
            }
        }

The PopulateApplications method:

private void PopulateApplications()
        {
            this.BeginInvoke(new MethodInvoker(delegate
            {
            var icon = Icon.ExtractAssociatedIcon(GetProcessInfo(GetProcessIntptr()).ProcessFileName);
            Image ima = icon.ToBitmap();
            ima = resizeImage(ima, new Size(25, 25));
            ima = (Image)(new Bitmap(ima, new Size(25, 25)));
            String status = GetProcessInfo(GetProcessIntptr()).ProcessResponding ? "Running" : "Not Responding";
            }));
        }

GetProcessInfo method:
public ProcessInfo GetProcessInfo(IntPtr hwnd)
        {
            uint pid = 0;
            GetWindowThreadProcessId(hwnd, out pid);
            Process proc = Process.GetProcessById((int)pid);

            return new ProcessInfo
            {
                ProcessFileName = proc.MainModule.FileName.ToString(),
                ProcessName = proc.ProcessName,
                ProcessTitle = proc.MainWindowTitle,
                ProcessResponding = proc.Responding
            };
        }

And last ProcessInfo class:
public class ProcessInfo
        {
            public string ProcessName { get; set; }
            public string ProcessFileName { get; set; }
            public string ProcessTitle { get; set; }
            public bool ProcessResponding { get; set; }
        }

If i'm calling the method PopulateApplications in the DoWork event I will get the exception if I will not call the method it will not throw the exception and i'm using the GetProcessInfo in other places in my program and only when I call it from the DoWork event the PopulateApplications method then it throw the exception.
System.ComponentModel.Win32Exception was unhandled
  HResult=-2147467259
  Message=A 32 bit processes cannot access modules of a 64 bit process.
  Source=System
  ErrorCode=-2147467259
  NativeErrorCode=299
  StackTrace:
       at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId, Boolean firstModuleOnly)
       at System.Diagnostics.NtProcessManager.GetFirstModuleInfo(Int32 processId)
       at System.Diagnostics.Process.get_MainModule()
       at Automation.Form1.GetProcessInfo(IntPtr hwnd) in d:\C-Sharp\Automation\Automation\Automation\Form1.cs:line 573
       at Automation.Form1.<PopulateApplications>b__1() in d:\C-Sharp\Automation\Automation\Automation\Form1.cs:line 616
       at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at Automation.Program.Main() in d:\C-Sharp\Automation\Automation\Automation\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

Comment: _A 32 bit processes cannot access modules of a 64 bit process._ try to disable `prefer 32-bit` in your project options.also make sure solution platform is set to AnyCpu. see if it works
Comment: Disabling the prefere 32-bit seems to be working.
Comment: be aware! this works only on 64bit cpu. so if you want to release your application later you have to release for both 32 bit and 64 bit users ;)
Answer: It's not possible because there is no "legal" way to manage 64bit memory space from 32bit application. (some differences in memory managing model, different pointer size etc.)
You should change your target platform from x32 (or mixed/anycpu) to x64. You can do this in project properties.


Como ver a quantidade de resultados com PDO

Question: Boa noite,
Como uso, faço para contar a quantidade de resultados de um select no banco de dados usando PDO?
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-  requested-with');

include_once("conPDO.php");
$pdo = conectar();

$data = file_get_contents("php://input");
$data = json_decode($data);

$email = $data->email;
$senha = $data->senha;

$login=$pdo->prepare("SELECT * FROM usuarios WHERE email=:email AND senha=:senha");
$login->bindValue("email", $email);
$login->bindValue("senha", $senha);
$login->execute();

$count = $login->fetch(PDO::FETCH_NUM);
print_r($count);

Comment: tenta $nRows = $pdo->query('select count(*) from blah')->fetchColumn();
echo $nRows;
Answer: Um dos jeitos que eu utilizaria pra fazer essa contagem sem afetar os registros seria com o FETCH_ASSOC.
Tenta fazer assim, ao invés de FETCH_NUM use $login->fetch(PDO::FETCH_ASSOC); e atribua para $result. Depois faça count($result) e você terá o número de elementos no array de retorno. Que equivale ao número de linhas. Dessa forma você pode pegar o número total sem mexer na quantidade de registros ou no modelo que você está retornando.
Comment: Não, ficaria algo do tipo `if(count($result) > 0) { ..... }`
Comment: Só count($result)? Não ta faltando nada nessa parte?
Comment: Lembrando que você vai atribuir o valor do login para o `$result`, como em `$result = $login->fetch(....)`
Comment: Qualquer coisa você pode se referir ao manual do count também http://php.net/manual/en/function.count.php


NSComparisonResult failed same NSDate

Question: There is a object called Place. user can add place to favorite and also user can remove place from the favorite. once user added to the favorite I save date on the database. when user remove from the favorite I retrieve date from the db. and compare particular object with array of objects. but it gives NSOrderedAscending when comparing same object.
NSDate *date1 = obj1.date; // same date
NSDate *date2 = obj2.date; // same date
// compare using date
NSComparisonResult result = [date2 compare:date1];

any help would be appreciate. Thanks.
Comment: These dates may have different values of milliseconds?
Comment: Indeed; the debugger is rounding to the nearest second.
Comment: I would log the dates to the console, there may be more information that isn't being showed to you the way you are examining the dates.
Comment: Just saying: Your question is completely fine and reasonable. Don't worry about down votes.
Comment: Please update your question with your code as formatted text. Do not post images of code.
Answer: Try do this:
-(NSDate *)clearSecondsFromDate:(NSDate *)date
{
NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
timeInterval -= fmod(timeInterval, 60);
NSDate *clearDate = [NSDate dateWithTimeIntervalSinceReferenceDate:: timeInterval];
return clearDate;
}

Comment: @user2160335 Have you tested this code properly?  Do you want the seconds removed from the dates?
Comment: @trojanfoe It is fine with me. because first I compare the dates. if order is same then I compare with Id. anyway in my app cannot add two date at same second. so it won't be a problem.
Comment: @user2160335 You didn't make that clear in your question. And you say "my app cannot add two date at same second" (which I don't quite understand), but this code will assume any time within the same **minute** as being equal.
Comment: What I meant was, there is a place. user can add place to favorite and user can remove from favorite. when user add I store current date on the db. when user remove I retrieve the same date from the db. but when comparing its says NSOrderedAscending sometimes NSOrderedDecending. hope you can understand.
Answer: If you want to compare two dates are equivalent to the same second, then get the number of seconds since some epoch and round off the fractional part:
BOOL same = round([date1 timeIntervalSince1970]) ==
            round([date2 timeIntervalSince1970]);

Or convert to an integer:
BOOL same = (unsigned long)[date1 timeIntervalSince1970] ==
            (unsigned long)[date2 timeIntervalSince1970];

(you can also use [NSDate timeIntervalSinceReferenceDate] if you like, as well).
Comment: I suspect that there is a revenge downvoting going on.
Comment: @gnasher729 By who?  I haven't downvoted anyone here.
Comment: I have down voted an incorrect answer, and then someone down voted all the correct answers as well.
Comment: Just noticed this will do the job with seconds also.
Answer: NSDate doesn't just contain day and seconds, it has a resolution better than microseconds. Your NSDates are probably some fraction of a second apart. Try to log [date1 timeIntervalSinceDate:date2].
So most likely your dates are just not the same. If you are sorting dates, and you want to have dates within the same second considered equal, take
double seconds1 = round ([date1 timeIntervalSinceReferenceDate]);
double seconds2 = round ([date2 timeIntervalSinceReferenceDate]);

which takes the time in a date and rounds it to the nearest second, and compare those values.

NSComparisonResult failed same NSDate


What's the point of a half-point line?

Question: In football betting, a "line" is provided by which the favorite team needs to win, in order for bettors to win that game.
Sometimes the line is x.5 points. If it's impossible to gain half-points in football, why have a half-point line?
Answer: This is done to ensure that there is not a push when the game is over.  A push is when no one wins, and the sportsbook gives everyone their wager back.
Here is an example:
For this week's Pittsburgh at Baltimore game, one sportsbook lists the point spread as 3, with Pittsburgh favored to win.  Let's say you decide to bet on Pittsburgh.  If Pittsburgh wins by 4 points, you win.  If Pittsburgh wins by 2 points, you lose.  If Pittsburgh wins by 3, you get your money back, along with everyone who bet on Baltimore.
Another sportsbook lists the point spread as 2.5.  If you bet on Pittsburgh, and they win by 3, you win, and if they win by 2, you lose.  There is no possibility of a push in this case.
Further reading: Maddux: How NFL Lines Work

What's the point of a half-point line?


Backup e Restore utilizando PostgreSQL em C#

Question: Para realizar o backup ou restore de uma base de dados através de uma aplicação C# utilizando o SGBD PostgreSQL, é necessário o envio de um comando para o pg_dump. É possível realizar a execução do mesmo através de um select enviando um ExecuteNonQuery (da mesma forma que é executada no SQLSERVER?) ao invés de enviar os dados para o pg_dump?
Comment: os pg_dump é um executável, que deve ser executado diretamente no servidor ou de um terminal informando o endereço do servidor, então pra isso, é bem provável que será necessário enviar alguns executáveis e dll do postgresql junto da aplicação (para executar por um terminal)
Answer: Existe um pergunta parecida com a sua, você já tentou utilizar este método abaixo? (https://stackoverflow.com/questions/23026949/how-to-backup-restore-postgresql-using-code)
<code>public void PostgreSqlDump(
        string pgDumpPath,
        string outFile,
        string host,
        string port,
        string database,
        string user,
        string password)
    {
        String dumpCommand = "\"" + pgDumpPath + "\"" + " -Fc" + " -h " + host + " -p " + port + " -d " + database + " -U " + user + "";
        String passFileContent = "" + host + ":" + port + ":" + database + ":" + user + ":" + password + "";

        String batFilePath = Path.Combine(
            Path.GetTempPath(),
            Guid.NewGuid().ToString() + ".bat");

        String passFilePath = Path.Combine(
            Path.GetTempPath(),
            Guid.NewGuid().ToString() + ".conf");

        try
        {
            String batchContent = "";
            batchContent += "@" + "set PGPASSFILE=" + passFilePath + "\n";
            batchContent += "@" + dumpCommand + "  > " + "\"" + outFile + "\"" + "\n";

            File.WriteAllText(
                batFilePath,
                batchContent,
                Encoding.ASCII);

            File.WriteAllText(
                passFilePath,
                passFileContent,
                Encoding.ASCII);

            if (File.Exists(outFile))
                File.Delete(outFile);

            ProcessStartInfo oInfo = new ProcessStartInfo(batFilePath);
            oInfo.UseShellExecute = false;
            oInfo.CreateNoWindow = true;

            using (Process proc = System.Diagnostics.Process.Start(oInfo))
            {
                proc.WaitForExit();
                proc.Close();
            }
        }
        finally
        {
            if (File.Exists(batFilePath))
                File.Delete(batFilePath);

            if (File.Exists(passFilePath))
                File.Delete(passFilePath);
        }
    }
</code>


Finding the shortest distance between two lines

Question: I know how to find the distance between a point and a line, not between two lines.
Find the shortest distance between the lines $(-1,1,4) + t(1,1,-1)$ and $(5,3,-3) + s(-2,0,1)$
Any help would be appreciated.
Comment: Can you use differential calculus?
Comment: No, I cannot, I think I may have figured it out by doing the do product of the vectors t and s with the cross product of s and t, then subtracting them. Incidentally the shortest distance is 0, I believe.
Answer: The distance between two lines in $ \Bbb R^3 $ is equal to the distance between parallel planes that contain these lines.
To find that distance first find the normal vector of those planes - it is the cross product of directional vectors of the given lines. For the normal vector of the form (A, B, C) equations representing the planes are:
$
Ax + By + Cz + D_1 = 0
$
$
Ax + By + Cz + D_2 = 0
$
Take coordinates of a point lying on the first line and solve for D1. Similarly for the second line and D2.
The distance we're looking for is:
$$d = \frac{|D_1 - D_2|}{\sqrt{A^2 + B^2 + C^2}}$$
Answer: Let $x_1$ and $y_1$ be 2 points on the line 1 and line 2 respectively. Form the difference vector $d=x_1-y_1$. Take another point $x_2$ on the line 1. Form the direction vector $x=x_1-x_2$. Project $d$ on to the direction vector $x$.
\begin{align}
x_{parallel}= \frac{(d.x)}{||x||^2}x
\end{align}
Now the norm of the following vector (the euclidean distance from the origin), will give you the required minimum distance.
\begin{align}
x_{perp}= d-x_{parallel}
\end{align}
(if they are not parallel, this will not work, instead it gives the shortest distance between the point $x_1$ and line 2.)
Comment: This method does not give the correct answer because $x_{perp}$ is not guaranteed to be orthogonal to line 2. In fact, there are infinitely many lines that pass through $y_1$ and give a different distance. Counterexample: Consider lines $f: x=(0,0,0)+(1,0,0)t$ and $g: x=(0,0,1)+(0,1,0)t$. Choose $x_1=(2,0,0)$, $x_2=(1,0,0)$, $y_1=(0,1,1)$. Then $d=(2,-1,-1)$, $x=(1,0,0)$, $x_{para}=(2,0,0)$, $x_{perp}=(0,-1,-1)$, which has norm $\sqrt{2}$, but the correct answer is clearly $1$.
Answer: The answer is a little tricky, first use the cross product to find $n$ by using the two direction vector.
$(d_1 \times d_2)$
\begin{bmatrix}
    \hat{i}       & \hat{j}  & \hat{k}  \\
    1       & 1 & -1 \\
    -2       & 0 & 1
\end{bmatrix}
= $i+j+2k$.
Then (with points $P$ and $S$, a point from each line) find vector $\vec{PS}. = (5,3,-3)-(-1,1,4) = (6,2,-7)$; then find the projection of $\vec{PS}$ onto $n$ and find the length of the projection. $(6,2,-7) \cdot \frac{(1,1,2)}{||1,1,2||^2}= 6^{1/2},$ or $2.44949$
Answer: Here is a working translation using SymPy to calculate the distance as suggested by @user287699 (but the answer here agrees with wolframalpha.com):
<code>def separation(l1, l2):
    """return separation of two skew lines

    Examples
    ========

    >>> from sympy import Line
    >>> a, b, c, d = (0, 0, 0), (1, 2, 3), (1, 1, 1), (2, 3, 5)
    >>> separation(Line(a, b), Line(c, d))
    sqrt(5)/5
    >>> a, b, c, d = (-1, 1, 4), (1, 1, -1), (5, 3, -3), (-2, 0, 1)
    >>> separation(Line(a, b), Line(c, d))
    sqrt(110)/55
    """
    from sympy import Matrix, Point
    n = Matrix(l1.direction.unit).cross(Matrix(l2.direction.unit))
    ps = l2.p1 - l1.p1
    return n.dot(ps)/Point(0,0,0).distance(n)
</code>


What's the structure that's a combination of "Time" and "Time differences" called?

Question: Let's say we call 2021/03/11 12:34:56 a Time
And let's call 30 minutes a TimeDiff
Then we have the following operations.
Time - Time -> TimeDiff
Time + TimeDiff -> Time
Time - TimeDiff -> Time
TimeDiff + TimeDiff -> TimeDiff
TimeDiff - TimeDiff -> TimeDiff
TimeDiff * Scalar -> TimeDiff

Note, we for example, can't add Times. Nor can we multiply TimeDiffs with each other but we can multiply TimeDiffs by scalars.
Is there a general name for this sort of structure?
TimeDiff on it's own I think would just be called a Vector, as you can add, subtract and multiply by scalars.
But what would the combination of Time+TimeDiff be called? I feel like this should have a name, as it's a combination that might come up in other places (although I am finding it hard to find as good an example as "time").
Comment: It is called an "affine space" (where "time" need not be 1-dimensional).
Comment: Interesting question, I've never really thought about this from a mathematical sense, only a programming sense (where I still struggle with correctly naming the different concepts).
Answer: It is called an affine space.
Answer: The space of all different possible Time is called an affine space, and the operation of adding a TimeDiff to a Time is called a translation of (more generally a vector space action on) the affine space.
Answer: More generally, this kind of structure is called a torsor. See Torsors Made Easy by John Baez.

A torsor is like a group that has forgotten its identity.

An affine space is a torsor for a vector space.

An affine space is like a vector space that has forgotten its origin.