Oracle sql delete on read

Question: The question i have is, how can i delete a record on read? I'm using Oracle ond AIX with the Roguewave DB Layer in a c++ application.
I have been searching on google for this answer but there seem only to be the simple examples. Is there a SQL Statement which returns the deleted rows?
This would greatly enhance performance on my application because only 0.1% of the cases will have a need to stay in this table, in other words i will insert 0.1% back into the table.
The only hint i have found is the "Into" clause, i would assume that using delete into would do the job but i have never used it.
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/returninginto_clause.htm
Answer: According to oracle documentation it is indeed possible to delete and read in one go:
DELETE FROM employees
   WHERE job_id = 'SA_REP'
   AND hire_date + TO_YMINTERVAL('01-00') < SYSDATE
   RETURNING salary INTO :bnd1;

I never used it myself...but you could give it a try.
Comment: I think this is what i like to have syntax wise, it doesn't run at the moment but i will try to make it work
Comment: Good answer. However, this will only work in a stored procedure, will it? Or can you use it directly from e.g. JDBC?
Comment: @sleske: I used the `returning` clause in `select` statements using OCCI without stored procedures and it worked just fine. Since this is a different scenario (other db layer) I can't be sure though.
Comment: It seems that the bnd1 needs to be turned into a rowtab and every single field requires extraction, there seems to be no trivial statement just to return the deleted rows
Comment: Actually you have served me what i asked for, it would have been awesome to have an actual query to return the table but your answer is correct
Answer: No, there is no SQL construct to read and delete a row in one go.
You could write a stored procedure which does this, though. Or you could cache the records you have already read in memory (so you do not read them again), then later do a bulk delete (DELETE FROM table WHERE id in (?)). That should be faster than many single DELETEs.
Or you might consider a different approach to the problem. Why do you need to delete so many rows on reading them? Are you using a DB table for passing messages? Is there maybe another technology that is more suited to your problem? If you feel you have to work against the established conventions of a technology, that may be an indication that you are not using the right tool for the job...
Answer: Have you tried something like building an audit trigger?
Good description to build an select trigger.
Creation:
begin
  dbms_fga.add_policy
  ( object_schema=>'SCOTT'
  , object_name=>'EMP'
  , policy_name=>'SAL_ACCESS_HANDLED'
  , audit_column => 'SAL'
  , audit_condition => 'SAL>= 1500'
  , handler_schema => 'SCOTT'
  , handler_module => 'AUDIT_HANDLER.HANDLE_EMP_SAL_ACCESS'
  );
end;
/

Function signature:
PROCEDURE HANDLE_EMP_SAL_ACCESS
( object_schema VARCHAR2
, object_name VARCHAR2
, policy_name VARCHAR2
);

Comment: How would that help OP? Where do the rows get deleted?
Comment: I actually haven't considered triggers as a solution, my assumption was that a trigger works like a fork Select --> Data (fork trigger) --> return Data to application, tell me if my understanding is not correct
Comment: By changing the insert to an delete inside the called procedure? I have to admit that I have not tried if it is possible to modify the table inside the function without firing again - so maybe a check should be added.
Comment: So you would have to parse the statement (get the WHERE clause) and modify it to a DELETE statement and do an execute immediate.

Oracle sql delete on read


Restrict Profile2 Profile Type on Role

Question: I would like to do a few things:

Limit the profile type a user has based on their role. When/if they change roles, their profile type would change and any fields that were the same are brought forward.
When accessing a user's profile page, the relevant profile type displays (one URL).
Allow users to display some of the fields in their core profile in the profile2 page that people see. (eg. birthday in core displayed as age in profile2 page).

Or am I thinking about this all wrong? Should I just think of profile types as different pages of the same profile that happen to have different fields?
Answer: You can use permissions to assign profile(s) to roles.
about:

When/if they change roles, their profile type would change and any
  fields that were the same are brought forward.

Remember each profile form is independent, so what you want could be done with code.  Or you can use only one profile form and use the field permissions module to assign role(s) per field (even if this is the case, maybe you don't need profile2).
Using only profile 2 (and turning off profile2 page),  you would see your core profile fields and the profile2 fields together.

Restrict Profile2 Profile Type on Role


Copy Operator not working properly

Question: Hello I am working on a polyminal class. I have a problem with the copy (=) operator overloading.Let me give some examples.
Let's say i have:

P = 2x^6 + 4x^5 + 2x^3 + 3x^2 + 2x + 1

if i do P=P I get:

P 4x^6 + 8x^5 + 4x^3 + 6x^2 + 4x + 2

I also get the thing with P = Q*P. I don't think my method has any problems, maybe something else.
#include <iostream>
#include <cmath>

using namespace std;

class Polynomial {
protected:
    class Term {
    public:
        int exponent;
        int coefficient;
        Term *next;

        Term(int exp, int coeff, Term *n) {
            exponent = exp;
            coefficient = coeff;
            next = n;
        }
        ~Term(){
            delete next;
        }

        friend class Polynomial;

        friend ostream;
    };

public:
    Polynomial() {
        root = NULL;
    }

    Polynomial(const Polynomial &p) {
        Term *target = p.root;
        root = NULL;
        while (target != NULL) {
            this->addTerm(target->exponent, target->coefficient);
            target = target->next;
        }
    }

    ~Polynomial() {
        delete root;
    }

    Polynomial & operator = (const Polynomial &p){
        Term *target = p.root;
        while (target!=NULL){
            this->addTerm(target->exponent , target->coefficient);
            target = target->next;
        }
        return *this;
    }

    void addTerm(int expon, int coeff) {

        Term *prev = root;
        Term *target = root;

        if (root == NULL) {
            Term *p = new Term(expon, coeff, target);
            //Term *p = &tmp;
            root = p;
            return;
        }

        while (target != NULL && target->exponent > expon) {
            prev = target;
            target = target->next;
        }

        if (target && target->exponent == expon) {
            target->coefficient += coeff;
            if (target->coefficient == 0) {
                prev->next = target->next;
            }
            return;
        }

        if (target == root) {
            Term *p = new Term(expon, coeff, target);
            root = p;   //Set p as root
        } else {

            Term *p = new Term(expon, coeff, target);
            prev->next = p;

        }

    }

    double evaluate(double x) {
        Term *target = root;
        double sum=0;
        while (target != NULL) {
            sum += target->coefficient * pow(x, target->exponent);
            target = target->next;
        }
        return sum;
    }

    friend Polynomial operator+(const Polynomial &p, const Polynomial &q) {
        Polynomial tmp;
        Term *target = p.root;

        while (target != NULL) {
            tmp.addTerm(target->exponent, target->coefficient);
            target = target->next;

        }
        target = q.root;
        while (target != NULL) {
            tmp.addTerm(target->exponent, target->coefficient);
            target = target->next;
        }
        return tmp;

    }

    friend Polynomial operator * (const Polynomial &p, const Polynomial &q) {
        Polynomial tmp;
        Term *target_1 = p.root;
        Term *target_2 = q.root;
        while (target_1 != NULL) {
            while (target_2 != NULL) {

                tmp.addTerm(target_1->exponent + target_2->exponent, target_1->coefficient * target_2->coefficient);

                target_2 = target_2->next;
            }
            target_2 = q.root;
            target_1 = target_1->next;
        }
        return tmp;
    }

    friend ostream &operator << (ostream &out, const Polynomial &p) {
        Term *target = p.root;
        if (target!=NULL && target->coefficient < 0) cout<<"- ";

        while (target != NULL) {
            if (target->exponent){
                if (abs(target->coefficient) != 1) out << abs(target->coefficient);
            }
            else {
                out << abs(target->coefficient);
            }
            out << (target->exponent ? (target->exponent != 1 ? "x^" : "x") : "");
            if (target->exponent) {
                if (target->exponent != 1) out << target->exponent;
            }
            target = target->next;
            if (target!= NULL) {
                if (target->coefficient > 0){
                    out<<" + ";
                }
                else{
                    out <<" - ";
                }
            }

        }

        return out;
    }

private:
    Term *root;
};

#ifndef CONTEST
int main(){

    Polynomial P;
    P.addTerm(6,2);
    P.addTerm(5,4);
    P.addTerm(3,2);
    P.addTerm(2,2);
    P.addTerm(1,2);
    P.addTerm(2,1);
    P.addTerm(0,1);

    cout<<P<<endl;

    cout<<P.evaluate(0)<<endl;
   // Polynomial Q = P;

    //Polynomial S = Q*P;
    P = P;

    //cout<<S<<endl;
    cout<<P<<endl;
}

#endif

Comment: Maybe it's just me, but in your copyconstructor and in your `=` operator definition, you do `Term *target = p.root;` and then do `while (target!=NULL){
            this->addTerm(target->exponent , target->coefficient);`. Doesn;t that add the RHS to the LHS if the LHS is not an empty polynomial?
Answer: Your operator= is incorrect: assignment should replace the terms in the current polynomial, not add to them. You need to first clear the object being assigned to:
delete root;
root = nullptr;

Doing this requires protecting against self-assignment. So start your assignment operator with this:
if (this == &p) return *this;

Then clear *this, and then copy p as you do.

An alternative solution would be to reuse the work you already did for the copy constructor and use the copy-and-swap idiom for the assignment operator. This requires:

Defining a swap function for your class:
friend void swap(Polynomial &lhs, Polynomial &rhs)
{
  std::swap(lhs.root, rhs.root);
}

Changing the operator= to take its argument by value, and swap with it inside:
Polynomial& operator=(Polynomial p)
{
  swap(*this, p);
  return *this;
}

This way, the object p will initialised created by the copy constructor, then just swapped with the polynomial being assigned to (transferring its value along the way), and finally destroyed when operator= ends, conveniently taking care of cleaning up the old value of the assigned-to polynomial.
Comment: I get what I said. Could i just create a new Polyminal in the operator= ?. Which is more optimal
Comment: @StavrosAvramidis One common way of easily implementing `operator=` is the [copy-and-swap idiom](https://stackoverflow.com/q/3279543/1782465). You'd just need to implement `swap` for your class (dead simple swap of the two roots), take the `operator=` argument by value, and swap with it.
Comment: Ok, thank you!!, By the my destructor is ok right?? I had one guy complaining about it but deleted his answer..?

Copy Operator not working properly


$G$ is an $(x,y)$-graph if $x>C(G)$ and $y>I(G)$

Question: I dont understand this definition, I'm new in this topic.
Definition 1: $I(G)$, the independence number of the graph $G$, is the maximum number of point of $G$ thath can be chosen so that no two are joined by an edge.
Definition 2: $C(G)$, the clique number of the graph $G$, is the maximum number of point in any complete subgraph of $G$.
I understand the definition 1 and 2, then I am not understanding.>..

Definition 3: $G$ is an $(x,y)$-graph if $x>C(G)$ and $y>I(G)$

could you give me an example to understand, please?
Answer: The following graph is $(4,4)$ I think as the max clique subgraph is $K_3$ and $I(G)=3$. It is also $(n,m)$ for $n\geq4 ,m \geq 4$.

And this one is $(5,5)$ as $C(G)=4$ and $I(G)=4$. It is also $(n,m)$ for $n\geq5 ,m \geq 5$


Power series and shifting index

Question: First I have to find the power series represantion for the following function:
$$\ f(x) = \ln(1+x)$$
I tried the following:
$$\ \frac{d}{dx}\Big(\ln(1+x)\Big) = \frac{1}{1+x} = \sum_{n=0}^\infty(-x)^n$$
Therefore,
$$\ f(x) = \ln(1+x) = \int\sum_{n=0}^\infty{}(-x)^n = \sum_{n=0}^\infty\frac{(-x)^{n+1}}{n+1} $$
Up to this point I think my answer is correct, but I have to shift the index by one so it starts from
n = 1 and I get:
$$\sum_{n=1}^\infty \frac{(-x)^n}{n}$$
I need some help in this last part if everything above is correct
Comment: You forgot a minus sign...
Comment: @Peter I'm just asked to write the power series representation of the function starting at n = 1. The software for the homework is not giving me full points for that answer so I guess is wrong but you say is right :S... I also found the radius of convergence which is 1, and for that I'm getting all points
Comment: absolutely!!!!!
Comment: Try writing out the first few terms
Comment: Yes it looks familiar. Just add a $dx$ to the integral and there is a theorem for when one is allowed to move integrals in under sum signs, but I forgot the name for it, but I am kind of sure you are allowed to do that there.
Comment: @qbert what first terms?
Comment: If the indices are increased by $c$, you have to replace $n$ by $n-c$. Your approach is perfectly right.
Comment: @c2J of your series. It should help make clear that the series with the shifted index is the same
Comment: @Peter so is my answer correct? I am not getting full points for that answer :(
Comment: which part is wrong? can you write the answer to this post?
Comment: @c2J Did my answer help you understanding what went wrong ?
Answer: Index shifting is simple:
$$\sum_{n=a}^b f(n)$$
can be rewritten with a variable substitution, for instance $n\to m+s$
$$\sum_{m+s=a}^b f(m+s)$$ or
$$\sum_{m=a-s}^{b-s} f(m+s).$$
If you want a specific starting value, choose the suitable $s$.
Answer: You have to write $$(-x)^n=(-1)^{n}\cdot x^n$$ If you integrate that you have $${(-1)}^n\cdot \frac{x^{n+1}}{n+1}$$ Shifting gives $${(-1)}^{n-1}\cdot \frac{x^n}{n}=(-1)^{n+1}\cdot \frac{x^n}{n}$$ So your approach was correct, but you forgot to seperate the sign before integrating.
Comment: You are right, but that is not a problem if he instead remembers the internal derivative (chain rule). $D(f(g(x))) = g'(x)f'(g(x))$
Comment: Yes it is a good explanation.
Comment: @mathreadler Yes, but I think this way it is easier.

Power series and shifting index


Find the sum of the infinite series $\sum n(n+1)/n!$

Question: How do find the sum of the series till infinity?
$$ \frac{2}{1!}+\frac{2+4}{2!}+\frac{2+4+6}{3!}+\frac{2+4+6+8}{4!}+\cdots$$
I know that it gets reduced to $$\sum\limits_{n=1}^∞ \frac{n(n+1)}{n!}$$
But I don't know how to proceed further.
Comment: Everybody knows
$$
e=\frac 1 {0!} +\frac 1 {1!} +\frac 1 {2!} +\frac 1 {3!} +\frac 1 {4!} +\frac 1 {5!} +\cdots.
$$
So you're series is
\begin{align}
& 0\cdot e \\
{} + {} & 2 \left( e - \frac 1 {0!} \right) \\
{} + {} & 4 \left( e - \frac 1 {0!} - \frac 1 {1!} \right) \\
{} + {} & 6 \left( e - \frac 1 {0!} - \frac 1 {1!} - \frac 1 {2!} \right) \\
{} + {} & 8 \left( e - \frac 1 {0!} - \frac 1 {1!} - \frac 1 {2!} - \frac 1 {3!} \right) \\
{} + {} & \cdots \cdots \\
\vdots\  \
\end{align} It would be amusing if one could use the "fact" that $2+4+6+8+\cdots = \dfrac{-1}6\qquad$.
Comment: I see I wrote "you're" where "your" should appear.  Doubtless if I run for office this will be brought up. $\qquad$
Comment: think about the Eulerian number
Answer: Define $f$ by $$f(x) = \sum_{n=0}^\infty \frac{x^{n+1}}{n!}$$ for $x\in\mathbb{R}$. (It is easy to check that the radius of convergence of this function is infinite.)
In particular:

For all $x\in\mathbb{R}$, $f''(x) = \sum_{n=1}^\infty \frac{(n+1)n}{n!}x^{n-1}$, so you are looking for $f''(1)$;
For all $x\in\mathbb{R}$, $f(x) = x e^x$ using the known power series for $\exp$, so that $f''(x) = (x+2)e^x$.

Therefore, $f''(1) = 3e$.
Comment: Clear and concise.  +1
Answer: Note that for $n\ge 2$ we have
$$\frac{n(n+1)}{n!}= \frac{1}{(n-2)!} + \frac{2}{(n-1)!}. $$
This lets us rewrite the sum as
$$
\frac{2}{0!} + \left(\frac{1}{0!} + \frac{2}{1!} \right)
+ \left(\frac{1}{1!} + \frac{2}{2!} \right)
+ \left(\frac{1}{2!} + \frac{2}{3!} \right)
+ \left(\frac{1}{3!} + \frac{2}{4!} \right)
+ \cdots
$$
Rearranging in the obvious way gives the sum as $3e$.
Comment: short and clear , nice answer ...
Answer: $$xe^x = \sum\frac{x^{n+1}}{n!}\\
\frac d{dx} x e^x = e^x + x e^x = \sum \frac{(n+1)x^n}{n!}\\
\frac {d^2}{dx^2} x e^x =2 e^x + x e^x =\sum \frac{n(n+1)x^{n-1}}{n!}$$
and as $x$ approaches $1$
$$3 e=\sum \frac{n(n+1)}{n!}$$
Answer: As you observed $$\sum_{n=1}^{\infty} \frac{n(n+1)}{n!}$$ further reduces to,
$$\begin{align}
&\sum_{n=1}^{\infty} \frac{n(n+1)}{n(n-1)!} \\
=&\sum_{n=1}^{\infty} \frac{n+1}{(n-1)!}\\
=&\sum_{n=1}^{\infty} \frac{n}{(n-1)!}+\frac{1}{(n-1)!}\\
=&\sum_{n=1}^{\infty} \frac{(n-1)}{(n-1)!} + \frac{2}{(n-1)!}\\
=&\sum_{n=1}^{\infty} \frac{1}{(n-2)!} +\sum_{n=1}^{\infty} \frac{2}{(n-1)!},
\end{align}$$
Both summations equal $e$(euler's number) whose expansion is given by,
$$e=\sum_{n=1}^{\infty} \frac{1}{(n-1)!}.
$$
So $$\sum_{n=1}^{\infty} \frac{n(n+1)}{n!} = 3e$$
Comment: Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: Specifically, [aligned equations](http://meta.math.stackexchange.com/a/5024/1473570)
Answer: $$\begin{eqnarray*} \sum_{n\geq 1}\frac{n(n+1)}{n!} &=& \sum_{n\geq 1}\frac{1}{(n-1)!}+\sum_{n\geq 1}\frac{n-1}{(n-1)!}+\sum_{n\geq 1}\frac{1}{(n-1)!}\\&=&2\sum_{m\geq 0}\frac{1}{m!}+\sum_{n\geq 2}\frac{n-1}{(n-1)!}=\color{red}{3e}.\tag{1}\end{eqnarray*}$$

An alternative approach.
$$ \sum_{n\geq 1}\frac{n(n+1)}{n!} = \sum_{n\geq 0}\frac{n+2}{n!} = \left.\frac{d}{dx}\left(x^2 e^x\right)\right|_{x=1}=\left.(x^2+2x)\,e^x\right|_{x=1}=\color{red}{3e}.\tag{2} $$

Yet another way.
$$\begin{eqnarray*}e^{-1}\sum_{n\geq 0}\frac{n+2}{n!}=\sum_{m\geq 0}\frac{(-1)^m}{m!}\sum_{n\geq 0}\frac{n+2}{n!} &=& \sum_{a\geq 0} \sum_{n=0}^{a}\frac{(-1)^n (a-n+2)}{(a-n)!n!}\\&=&\sum_{a\geq 0}\frac{1}{a!}\sum_{n=0}^{a}\binom{a}{n}(-1)^n (a+2-n)\tag{3}\end{eqnarray*}$$
where the innermost sum is non-zero only for $a=0$ and $a=1$ by the theory of the forward difference operator: $(a+2-n)$ is a polynomial in $n$ with degree $1$.
Answer: You could also consider that $$A(x)=\sum\limits_{n=1}^∞ \frac{n(n+1)}{n!}x^n=\sum\limits_{n=0}^∞ \frac{n(n+1)}{n!}x^n=\sum\limits_{n=0}^∞ \frac{n(n-1)+2n}{n!}x^n$$ $$A(x)=\sum\limits_{n=0}^∞ \frac{n(n-1)}{n!}x^n+2\sum\limits_{n=0}^∞ \frac{n}{n!}x^n=x^2\sum\limits_{n=0}^∞ \frac{n(n-1)}{n!}x^{n-2}+2x\sum\limits_{n=0}^∞ \frac{n}{n!}x^{n-1}$$ $$A(x)=x^2 \left(\sum\limits_{n=0}^∞ \frac{x^n}{n!} \right)''+2x\left(\sum\limits_{n=0}^∞ \frac{x^n}{n!} \right)'=x^2e^x+2x e^x=x(x+2)e^x$$ Now, compute $A(1)$.


How many n-digit numbers with strictly increasing digits do exist?$(n<10)$

Question: How many n-digit numbers with strictly increasing digits do exist?$(n<10)$
We mean numbers like: $13458$,these numbers do not have $0$ as a digit.How can we count them??
I used trees to distinguish and count each case of these numbers,but is there any combinatorial technique to count such numbers???
Comment: is 112233 valid? Repetitions of same digit allowed? Or has to be increasing for every successive place value.
Comment: @sanketalekar it says **strictly** increasing.
Comment: 112233 is not valid
Answer: Such a number is just a $n$ size subset of $\{1,\ldots,9\}$. Such a subset has a unique increasing order (which is the number representation).
So there are $\binom{9}{n}$ such numbers.
Comment: The digits in the number form a subset of size $n$. And if we have any subset of size $n$, there is only one way to write the subset in increasing order. So there is a bijection between your increasing numbers and subsets of size $n$ (and $0$ is not allowed). The binomial coefficient counts those subsets.
Comment: Can you explain more please?


CentOS default ssl.conf file

Question: Does anybody have a default ssl.conf file for the latest version of CentOS?
I am trying to understand if I can use the auto-generated SSL certificate, but I accidentally overwrote it with another ssl.conf file.
Answer: Just try to re install mod_ssl.x86_64 package.
[sgeorge@sgeorge-ld ~]$ sudo rpm -ql mod_ssl.x86_64
[sudo] password for sgeorge:
/etc/httpd/conf.d/ssl.conf
/usr/lib64/httpd/modules/mod_ssl.so
/var/cache/mod_ssl
/var/cache/mod_ssl/scache.dir
/var/cache/mod_ssl/scache.pag
/var/cache/mod_ssl/scache.sem

I moved ssl.conf to my home directory and removed this package and then re installed. :) I got that file back.
[sgeorge@sgeorge-ld ~]$ sudo mv /etc/httpd/conf.d/ssl.conf ~/

[sgeorge@sgeorge-ld ~]$ sudo rpm -ql mod_ssl.x86_64
/etc/httpd/conf.d/ssl.conf
/usr/lib64/httpd/modules/mod_ssl.so
/var/cache/mod_ssl
/var/cache/mod_ssl/scache.dir
/var/cache/mod_ssl/scache.pag
/var/cache/mod_ssl/scache.sem

[sgeorge@sgeorge-ld ~]$ sudo rpm -ev mod_ssl.x86_64

[sgeorge@sgeorge-ld ~]$ sudo rpm -ql mod_ssl.x86_64
package mod_ssl.x86_64 is not installed

[sgeorge@sgeorge-ld ~]$ ls -l /etc/httpd/conf.d/ssl.conf
ls: cannot access /etc/httpd/conf.d/ssl.conf: No such file or directory

[sgeorge@sgeorge-ld ~]$ sudo yum install mod_ssl.x86_64
Loaded plugins: downloadonly, product-id, refresh-packagekit, rhnplugin, subscription-manager
Updating Red Hat repositories.
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package mod_ssl.x86_64 1:2.2.15-9.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================================================================================================================================================================================================================================================================
 Package                                                             Arch                                                               Version                                                                       Repository                                                                                Size
=============================================================================================================================================================================================================================================================================================================================
Installing:
 mod_ssl                                                             x86_64                                                             1:2.2.15-9.el6                                                                release-rhel-x86_64-workstation-6-r1                                                              86 k

Transaction Summary
=============================================================================================================================================================================================================================================================================================================================
Install       1 Package(s)

Total download size: 86 k
Installed size: 0
Is this ok [y/N]: y
Downloading Packages:
mod_ssl-2.2.15-9.el6.x86_64.rpm                                                                                |  86 kB     00:00
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Warning: RPMDB altered outside of yum.
  Installing : 1:mod_ssl-2.2.15-9.el6.x86_64                                                                                1/1
duration: 170(ms)
Installed products updated.

Installed:
  mod_ssl.x86_64 1:2.2.15-9.el6

Complete!
[sgeorge@sgeorge-ld ~]$ ls -l /etc/httpd/conf.d/ssl.conf
-rw-r--r-- 1 root root 9473 Dec  8  2009 /etc/httpd/conf.d/ssl.conf

Answer: #
# This is the Apache server configuration file providing SSL support.
# It contains the configuration directives to instruct the server how to
# serve pages over an https connection. For detailing information about these
# directives see <URL:http://httpd.apache.org/docs/2.2/mod/mod_ssl.html>
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.
#

LoadModule ssl_module modules/mod_ssl.so

#
# When we also provide SSL we have to listen to the
# the HTTPS port in addition.
#
Listen 443

##
##  SSL Global Context
##
##  All SSL configuration in this context applies both to
##  the main server and all SSL-enabled virtual hosts.
##

#   Pass Phrase Dialog:
#   Configure the pass phrase gathering process.
#   The filtering dialog program (`builtin' is a internal
#   terminal dialog) has to provide the pass phrase on stdout.
SSLPassPhraseDialog  builtin

#   Inter-Process Session Cache:
#   Configure the SSL Session Cache: First the mechanism
#   to use and second the expiring timeout (in seconds).
SSLSessionCache         shmcb:/var/cache/mod_ssl/scache(512000)
SSLSessionCacheTimeout  300

#   Semaphore:
#   Configure the path to the mutual exclusion semaphore the
#   SSL engine uses internally for inter-process synchronization.
SSLMutex default

#   Pseudo Random Number Generator (PRNG):
#   Configure one or more sources to seed the PRNG of the
#   SSL library. The seed data should be of good random quality.
#   WARNING! On some platforms /dev/random blocks if not enough entropy
#   is available. This means you then cannot use the /dev/random device
#   because it would lead to very long connection times (as long as
#   it requires to make more entropy available). But usually those
#   platforms additionally provide a /dev/urandom device which doesn't
#   block. So, if available, use this one instead. Read the mod_ssl User
#   Manual for more details.
SSLRandomSeed startup file:/dev/urandom  256
SSLRandomSeed connect builtin
#SSLRandomSeed startup file:/dev/random  512
#SSLRandomSeed connect file:/dev/random  512
#SSLRandomSeed connect file:/dev/urandom 512

#
# Use "SSLCryptoDevice" to enable any supported hardware
# accelerators. Use "openssl engine -v" to list supported
# engine names.  NOTE: If you enable an accelerator and the
# server does not start, consult the error logs and ensure
# your accelerator is functioning properly.
#
SSLCryptoDevice builtin
#SSLCryptoDevice ubsec

##
## SSL Virtual Host Context
##

<VirtualHost _default_:443>

# General setup for the virtual host, inherited from global configuration
#DocumentRoot "/var/www/html"
#ServerName www.example.com:443

# Use separate log files for the SSL virtual host; note that LogLevel
# is not inherited from httpd.conf.
ErrorLog logs/ssl_error_log
TransferLog logs/ssl_access_log
LogLevel warn

#   SSL Engine Switch:
#   Enable/Disable SSL for this virtual host.
SSLEngine on

#   SSL Protocol support:
# List the enable protocol levels with which clients will be able to
# connect.  Disable SSLv2 access by default:
SSLProtocol all -SSLv2

#   SSL Cipher Suite:
# List the ciphers that the client is permitted to negotiate.
# See the mod_ssl documentation for a complete list.
SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW

#   Server Certificate:
# Point SSLCertificateFile at a PEM encoded certificate.  If
# the certificate is encrypted, then you will be prompted for a
# pass phrase.  Note that a kill -HUP will prompt again.  A new
# certificate can be generated using the genkey(1) command.
SSLCertificateFile /etc/pki/tls/certs/localhost.crt

#   Server Private Key:
#   If the key is not combined with the certificate, use this
#   directive to point at the key file.  Keep in mind that if
#   you've both a RSA and a DSA private key you can configure
#   both in parallel (to also allow the use of DSA ciphers, etc.)
SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

#   Server Certificate Chain:
#   Point SSLCertificateChainFile at a file containing the
#   concatenation of PEM encoded CA certificates which form the
#   certificate chain for the server certificate. Alternatively
#   the referenced file can be the same as SSLCertificateFile
#   when the CA certificates are directly appended to the server
#   certificate for convinience.
#SSLCertificateChainFile /etc/pki/tls/certs/server-chain.crt

#   Certificate Authority (CA):
#   Set the CA certificate verification path where to find CA
#   certificates for client authentication or alternatively one
#   huge file containing all of them (file must be PEM encoded)
#SSLCACertificateFile /etc/pki/tls/certs/ca-bundle.crt

#   Client Authentication (Type):
#   Client certificate verification type and depth.  Types are
#   none, optional, require and optional_no_ca.  Depth is a
#   number which specifies how deeply to verify the certificate
#   issuer chain before deciding the certificate is not valid.
#SSLVerifyClient require
#SSLVerifyDepth  10

#   Access Control:
#   With SSLRequire you can do per-directory access control based
#   on arbitrary complex boolean expressions containing server
#   variable checks and other lookup directives.  The syntax is a
#   mixture between C and Perl.  See the mod_ssl documentation
#   for more details.
#<Location />
#SSLRequire (    %{SSL_CIPHER} !~ m/^(EXP|NULL)/ \
#            and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \
#            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \
#            and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 \
#            and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20       ) \
#           or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/
#</Location>

#   SSL Engine Options:
#   Set various options for the SSL engine.
#   o FakeBasicAuth:
#     Translate the client X.509 into a Basic Authorisation.  This means that
#     the standard Auth/DBMAuth methods can be used for access control.  The
#     user name is the `one line' version of the client's X.509 certificate.
#     Note that no password is obtained from the user. Every entry in the user
#     file needs this password: `xxj31ZMTZzkVA'.
#   o ExportCertData:
#     This exports two additional environment variables: SSL_CLIENT_CERT and
#     SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
#     server (always existing) and the client (only existing when client
#     authentication is used). This can be used to import the certificates
#     into CGI scripts.
#   o StdEnvVars:
#     This exports the standard SSL/TLS related `SSL_*' environment variables.
#     Per default this exportation is switched off for performance reasons,
#     because the extraction step is an expensive operation and is usually
#     useless for serving static content. So one usually enables the
#     exportation for CGI and SSI requests only.
#   o StrictRequire:
#     This denies access when "SSLRequireSSL" or "SSLRequire" applied even
#     under a "Satisfy any" situation, i.e. when it applies access is denied
#     and no other module can change it.
#   o OptRenegotiate:
#     This enables optimized SSL connection renegotiation handling when SSL
#     directives are used in per-directory context.
#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
<Files ~ "\.(cgi|shtml|phtml|php3?)$">
    SSLOptions +StdEnvVars
</Files>
<Directory "/var/www/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>

#   SSL Protocol Adjustments:
#   The safe and default but still SSL/TLS standard compliant shutdown
#   approach is that mod_ssl sends the close notify alert but doesn't wait for
#   the close notify alert from client. When you need a different shutdown
#   approach you can use one of the following variables:
#   o ssl-unclean-shutdown:
#     This forces an unclean shutdown when the connection is closed, i.e. no
#     SSL close notify alert is send or allowed to received.  This violates
#     the SSL/TLS standard but is needed for some brain-dead browsers. Use
#     this when you receive I/O errors because of the standard approach where
#     mod_ssl sends the close notify alert.
#   o ssl-accurate-shutdown:
#     This forces an accurate shutdown when the connection is closed, i.e. a
#     SSL close notify alert is send and mod_ssl waits for the close notify
#     alert of the client. This is 100% SSL/TLS standard compliant, but in
#     practice often causes hanging connections with brain-dead browsers. Use
#     this only for browsers where you know that their SSL implementation
#     works correctly.
#   Notice: Most problems of broken clients are also related to the HTTP
#   keep-alive facility, so you usually additionally want to disable
#   keep-alive for those clients, too. Use variable "nokeepalive" for this.
#   Similarly, one has to force some clients to use HTTP/1.0 to workaround
#   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
#   "force-response-1.0" for this.
SetEnvIf User-Agent ".*MSIE.*" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0

#   Per-Server Logging:
#   The home of a custom SSL log file. Use this when you want a
#   compact non-error SSL logfile on a virtual host basis.
CustomLog logs/ssl_request_log \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

</VirtualHost>

CentOS default ssl.conf file


How to use DataDefinition::create('list')?

Question: This answer links to a list of all possible types that can be used with DataDefinition::create().
One plugin that can be used is ItemList.
But I can't find any documentation on how to define what items are on the list.
I would have expected something like this:
$status_definition = DataDefinition::create('list')
  ->setLabel(new TranslatableMarkup('Status'))
  ->setRequired(TRUE)
  ->setListItems([
    1 => 'One',
    2 => 'Two',
    3 => 'Three',
  ]);

But the method setListItems (or anything similar) does not exist.
For some more context I'm following this article on how to extend the entity reference field type but instead of adding an integer field I want to add a list field.
Answer: ItemList is a generic base class. List is used here in the context of multivalued field items. Because Drupal has no separate class for single value fields (they are multivalued fields restricted to one value), this generic list data type is used in all Drupal fields.
When you look at the list of field types
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21Annotation%21FieldType.php/class/annotations/FieldType/8.4.x
you'll find ListStringItem, where List is used in the context you are probably looking for and you can use this as an example for this kind of field types implementing OptionsProviderInterface.


How to solve this definite integral? It cannot be solved using simple integration by parts.

Question: $$\int_0^1 \frac{x}{1+x^2} \ln{(x+1)}\ dx$$
I encountered this in Issac Physics, so it should be solved just using high school calculus knowledge.
Comment: You'll find [another technique](https://en.wikipedia.org/wiki/Leibniz_integral_rule#Proof_of_basic_form) more useful. Evaluate$$\int_0^1\left[\frac{d}{dc}\left(\int_0^1\frac{x}{1+x^2}\ln(1+cx)dx\right)\right]dc.$$
Comment: Have you tried anything? Any thoughts, do share it here!
Comment: Which $u,\,v$ did you try in integration by parts? Show us what happened.
Comment: Basically when I first saw it I tried integration by parts(that's what you usually do when there is $\ln{f(x)}$ right?). But if you do $u = \ln{(x+1)}$ and $v' = \frac{x}{1+x^2}$ then you would see that another $\ln{f(x)}$ comes out as $\int \frac{x}{1+x^2}\ dx$ evaluates to $\frac{1}{2} \ln{(1+x^2)}$
Comment: @J.G. That seems confusing, differentiating a definite integral should give a result of $0$ isn't it?
Comment: There are various techniques applicable here: double integrals, series, differentiation under the integral sign, etc. But I don't think there is a "high school calculus" solution involving simple substitutions or integration by parts. This integral is more advanced.
Comment: @RyanHu The inner integral over $x$ has a $c$-dependent integrand, so the integral's $c$ derivative is nonzero. In fact, that derivative is$$\int_0^1\frac{x^2dx}{(1+cx)(1+x^2)},$$which you can evaluate by partial fractions. The resulting function of $c$ needs to be integrated from $0$ to $1$.
Comment: @bjorn93 Oh, that's unfortunate, thanks for telling me tho.
Comment: @J.G. Thank you! I'll try
Comment: A further hint at @bjorn93's suggested complexity: [the answer](https://www.wolframalpha.com/input/?i=integral+of+x*ln%281%2Bx%29%2F%281%2Bx%5E2%29+from+0+to+1) is $\frac{\pi^2+12\ln^22}{96}$, so an integral representation of $\zeta(2)$ will come up.
Answer: Using integration by parts, we can get
$$\begin{align}
\int_0^1{\frac{x}{x^2+1}\ln \left( 1+x \right) \mathrm{d}x}=&\frac{1}{2}\int_0^1{\frac{1}{x^2+1}\ln \left( 1+x \right) \mathrm{d}\left( x^2+1 \right)}
\\
=&\frac{1}{2}\int_0^1{\ln \left( 1+x \right) \mathrm{d}\ln \left( x^2+1 \right)}
\\
=&\frac{1}{2}\left( \ln ^22-\int_0^1{\frac{\ln \left( 1+x^2 \right)}{1+x}\mathrm{d}x} \right)
\end{align}$$
And the second integral $\int_0^1{\frac{\ln \left( 1+x^2 \right)}{1+x}\mathrm{d}x}$ can be found in this cite, for example, from here we can get that
$$
\int_{0}^{1}\frac{\ln(x^{2}+1)}{x+1}\mathrm{d}x=\frac{3}{4}\ln^{2}(2)-\frac{{\pi}^{2}}{48}
$$
So combining them, we can get
$$\begin{align}
\int_0^1{\frac{x}{x^2+1}\ln \left( 1+x \right) \mathrm{d}x}=&\frac{1}{2}\left( \ln ^22-\left( \frac{3}{4}\ln ^22-\frac{\pi ^2}{48} \right) \right)
\\
=&\frac{\pi ^2}{96}+\frac{1}{8}\ln ^22
\end{align}$$
Comment: @RyanHu What's more, I am curious about the range of your so called "high school calculus knowledge", as we are in the different provinces(seen from your profile) for college entrance examination. Knowledge such as integration by parts and variable substitution are beyond what we had to learn in high school.
Comment: The integration by parts here simply swaps one integral with another integral of roughly the same complexity. It doesn't simplify the problem. Notice that the technique used in solving the second integral can be applied directly to the given integral.
Comment: @SHBooKP By high school calculus knowledge, I mean what you would expect from a AP calculus BC student or an a level further math student(Im the latter one). Cuz I'm in an international school.


ASP.NET MVC parsing variables wihout URL query string

Question: Heading
I want to pass some variables from one page to another but I don't want them to appear in the URL. When I use a form to post the an ActionResult it works fine. However, when I do this
<code>return RedirectToAction("Trackers",new{page = 1, orderby=desc});
</code>
I get the URL:
http://examplesite.com/Trackers?page=1&orderby=desc
Is there any way I can get the following URL instead but still pass the page and orderby variables "behind the scenes"?
http://examplesite.com/Trackers
Thanks
TheLorax
Answer: I'm not sure it's a good idea to do what you're suggesting, however, you might be able to use the TempData (same place as the ViewData) to save your information before the redirect. I believe that after your next request, anything in the temp data is cleared out.
Comment: Hi HBoss, thanks for your response it was exactly what I wanted. The variable I wanted to pass was something I didn't want the user to see and is the reason I wanted to pass it invisibly.

Your answer was exactly what I was looking for. I didn't even know anything about TempData before but now I do, so Thank You again.
Answer: You could pass a Model object containing the page number and the orderby instead of an anonymous object, and have your view inherit the model class of the object you are passing.  Your model object with the page number and orderby then becomes available to the view, without employing a query string
This is not, however, the preferred method of doing this.  Your model objects should be reserved for their intended purpose, which is passing actual data to your view.
Answer: When you use RedirectToAction method the browser will recieve an http redirect response from the server and then will do a GET request to the new URL.
I think there is no way to make the browser make a POST request when redirecting.
Also it is better to pass these variables through the query string in order for the user to be able to bookmark the page.


Number of ways to have lights of equal distances on a street

Question:
The city wants to have street lights along a street that is $64$ yards long. If the street lights are going to be apart at equal distances that are whole numbers of yards, how may different ways can the city do it?

Can someone please shed some lights on this question (no pun intended)? I divided 64 yards by $1$ to $64$ and the whole numbers from the division are $1$ yard, $2$ yards, $4$ yards, $8$ yards, $16$ yards, $32$ yards and $64$ yards. Is there a much quicker way to do this for any number $n$ of yards, i.e. a formula perhaps?
Thank you very much for your help.
Comment: The question just wants you to find the number of divisors of 64. perhaps a smarter a way was to recognize that 64 is a power of 2, $(2^6)$, and then find different combinations of it by combinatorics eg;  $$2^6 = 2^3 × 2^3$$
Answer: The question is asking how many  factors does $64$ have
$$64=2^6$$
Hence the factors are $2^0, 2^1, \ldots, 2^6$. There are $7$ factors.
In general I will consider the prime factorization of the number $n$.
$$n = \prod_{i=1}^q p_i^{m_i}$$
and the number of factors would be $\prod_{i=1}^q (m_i + 1)$


Use of the Gamma parameter with support vector machines

Question: When using libsvm, the parameter $\gamma$ is a parameter for the kernel function. Its default value is setup as $$\gamma = \frac{1}{\text{number of features.}}$$
Is there any theoretical guidance for setting up this parameter besides existing methods, e.g., grid search?
Answer: I would suggest the following theoretical guidance. When you are using Gaussian RBF kernel, your separating surface will be based on a combination of bell-shaped surfaces centered at each support vector. The width of each bell-shaped surface will be inversely proportional to $\gamma$. If this width is smaller than the minimum pair-wise distance for your data, you essentially have overfitting. If this width is larger than the maximum pair-wise distance for your data, all your points fall into one class and you don't have good performance either. So the optimal width should be somewhere between these two extremes.
Comment: `pair-wise distance for your data` = simple Euclidean distance after scaling?
Answer: No, it is essentially data dependent.  Grid search (over log-transformed hyper-parameters) is a very good method if you only have a small number of hyper-parameters to tune, but don't make the grid resolution too fine or you are likely to over-fit the tuning criterion.  For problems with a larger number of kernel parameters, I find the Nelder-Mead simplex method works well.
Comment: Essentially "data dependent" just means the best settings will vary according to the particular structure of the data and there isn't generally any better way to set them than minimising the cross-validation error.  Kernel methods could really do with more theoretical analysis of how to go about learning the kernel, but unfortunately this is mathematically very difficult.
Comment: Dikran, thanks for the answer. Can you elaborate more on the "data-dependent"? What's the relationship between r and a set of data? Or in other words, given a set of data, is there a way to define r based on these data?


How to solve Real Analysis

Question: Find the Fouries series of the function given below
$$
f(x) = \lvert\cos t\rvert \quad\hbox{for all $t$}.
$$
What does it means for all $x$? Can someone show me some  work done so that I can understand better?
Comment: Sketch the function $|\cos x|$ for all $x$. It will be periodic (that is, the same shape will repeat over and over), and thus can be represented by a Fourier series. Do you know how to compute the Fourier coefficients of a function that has (least) period different from $2\pi$?
Comment: To find the Fourier series is to find the coefficients of the Fourier series representation of $|\cos x|$. Have you covered how to find the coefficients? You need to multiply $|\cos x|$ against an integer-multiple-of-$2\pi$ dilate of a trigonometric function (either a complex exponential or sine, cosine, depending on what kind of series you're in search of) and then integrate over a fundamental interval (like $(0,2\pi)$ or $(-\pi,\pi)$ or whatever) and normalize by dividing by $2\pi$. You can evaluate the integral by splitting it into two pieces based on when $\cos$ is positive or negative...
Comment: Hi Dilip and anon.Thanks for the hints and tips
Answer: We treat the function $f$ as a $2\pi$-periodic function, so that we can apply the most basic formulae for the Fourier coefficients. The function $f$ is even; whence all sine coefficients $b_k$ are $=0$, and
$$a_k={1\over\pi}\int_{-\pi}^\pi f(x)\ \cos(k x)\ dx={2\over\pi}\int_0^\pi f(x)\ \cos(k x)\ dx\qquad(k\geq0)\ .$$
In addition, $f$ is even with respect to the point $x={\pi\over2}$, and this implies that $a_k$ is $=0$ for odd $k$ (to see this draw the graphs of $f$ and of $x\mapsto\cos\bigl((2j+1)x\bigr)$ in the same figure). In the interval $\bigl[0,{\pi\over2}\bigr]$ our function is just $x\mapsto\cos x$. Therefore we get
$$\eqalign{a_{2j}&={4\over\pi}\int_0^{\pi/2}\cos x\cos(2j x)\ dx={2\over\pi}\int_0^{\pi/2}\bigl(\cos((2j+1)x)+\cos((2j-1))x\bigr)\ dx\cr
&={2\over\pi}\left.\biggl({1\over2j+1}\sin((2j+1)x)+{1\over2j-1}\sin((2j-1)x)\biggr)\right|_0^{\pi/2} \cr
&={2\over\pi}\biggl({(-1)^j\over 2j+1} -{(-1)^j\over 2j-1}\biggr)={4\over\pi}{(-1)^{j-1}\over 4j^2-1}\ .\cr}$$
In particular $a_0={4\over\pi}$. All in all we obtain
$$|\cos x|={a_0\over2}+\sum_{j=1}^\infty a_{2j}\cos(2j x)={2\over\pi}-{4\over\pi}\sum_{j=1}^\infty{(-1)^j\over 4j^2-1}\cos(2jx)\ ,$$
and the resulting series is uniformly convergent on ${\mathbb R}$.
Comment: Hi Christian you are awesome.Thanks man for your effort to help me
Answer: The Fourier series of a function $f(x)$ is a series on the form
$${1\over 2}a_0 +\sum_{n=1}^\infty \bigl(a_n \cos(nx) + b_n \sin(nx)\bigr)$$
where the coefficients $a_n$ and $b_n$ are given by the formulas $$a_n ={1\over\pi}\int_{-\pi}^{\pi}f(x)\cos(nx)\,{\rm d}x\qquad n=0,1,2,\dots$$ $$b_n ={1\over\pi}\int_{-\pi}^\pi f(x)\sin(nx)\,{\rm d}x\qquad n=1,2,\dots$$
Since your function $f(x)=|\cos(x)|$ is an even function, all $b_n=0$. (You are integrating an odd function over a symmetric interval about 0.)
For the same reason, you get that
$$a_n ={2\over\pi}\int_0^\pi f(x)\cos(nx)\,{\rm d}x$$
Your function $f(x)$ is defined by $f(x)=\cos(x)$ for $0\leq x\leq {\pi\over 2}$, and by $f(x)=-\cos(x)$ for ${\pi\over 2}\leq x\leq \pi$, so it might be wise to divide this integral in two parts when computing it.
When you have computed the Fourier coefficients, try to plot $f(x)$ and the series you get by using the first few terms of the Fourier series. You should get two reasonably similar-looking graphs.
Comment: Hi Per Manne.Thanks for your effort for showing some work done.You really help me out
Answer: Note that the Fourier coefficients of a function $f(x)$ are given by
$$c_n=\frac{1}{2\pi}\int_0^{2\pi}e^{-inx}f(x)dx.$$
For $f(x)=|\cos x|$ we have
$$\begin{align}
c_n &=\frac{1}{2\pi}\int_0^{2\pi}e^{-inx}|\cos x|dx\\
&=\frac{1}{2\pi}\int_0^{\pi}e^{-inx}|\cos x|dx+\frac{1}{2\pi}\int_{\pi}^{2\pi}e^{-inx}|\cos x|dx\\
\end{align}$$
and if $n$ is odd we have $e^{-in(x+\pi)}=-e^{-inx}$ so the two integrals cancel. If $n$ is even then $e^{-in(x+\pi)}=e^{-inx}$ so both integrals agree and
$$\begin{align}
c_n&=\frac{1}{\pi}\int_0^{\pi}e^{-inx}|\cos x|dx\\
&=\frac{1}{\pi}\int_0^{\pi/2}e^{-inx}\cos xdx+\frac{1}{\pi}\int_{\pi/2}^{\pi}e^{-inx}\cos xdx\\
\end{align}$$
and if $\frac{n}{2}$ is odd we have $e^{-in(x+\pi/2)}=e^{-inx+(n/2)\pi}=-e^{-inx}$ so the integrals again cancel. Thus if $n\neq 4m$ the Fourier coefficient $c_n$ is $0$. If $n=4m$ then we have $e^{-in(x+\pi/2)}=e^{-inx}$ so both integrals agree and
$$\begin{align}
c_n&=\frac{2}{\pi}\int_0^{\pi/2}e^{-inx}\cos xdx\\
&=\frac{2}{\pi}\int_0^{\pi/2}\cos nx\cos xdx+\frac{2i}{\pi}\int_0^{\pi/2}\sin nx\cos xdx\\
\end{align}$$
and both of these integrals can be found in many tables, or on Wolfram|Alpha.
Comment: Hi Alex thanks for your help for this question.It really helps me for your suggestion
Answer: One can use Fourier series on a general interval $[a, a + L]$,
$$ \sum _{n=-\infty }^{\infty }{\it c\_n}\,{{\rm e}^{{\frac {2\,inx\pi }{
L}}}} \,,$$
where $c_n$ are given by,
$$ c_n = \int _{a}^{a+L}\!f \left( x \right) {{\rm e}^{{\frac {-2\,in\pi \,x}{L
}}}}{dx}$$
Applying this to our problem, first we note that |cos(x)| is a periodic function of period $\pi$ and $\cos(x)$ is positive on the interval $[-\frac{\pi}{2},\frac{\pi}{2}]$,
$$ c_n = \int _{-\frac{\pi}{2}}^{-\frac{\pi}{2}+\pi} \cos(x) {{\rm e}^{{\frac {-2\,in\pi \,x}{L
}}}}{dx} = 2\,{\frac { \left( -1 \right) ^{1+n}}{\pi \, \left( 4\,{n}^{2}-1
 \right) }}
\,.$$
Then the Fourier series of $|\cos(x)|$ is given by,
$$ |\cos(x)| =  \sum _{n=-\infty }^{\infty }2\,{\frac { \left( -1 \right) ^{1+n}}{\pi \, \left( 4\,{n}^{2}-1\right) }}\,{{\rm e}^{{\frac {2\,inx\pi }{L}}}}\,. $$
Writing the sum as,
$$ |\cos(x)| =  2\,{\pi }^{-1}+\sum _{n=1}^{\infty}2\,{\frac { \left( -1 \right) ^{1+n}
 \left( {{\rm e}^{2\,inx}}+{{\rm e}^{-2\,inx}} \right) }{\pi \,
 \left( 4\,{n}^{2}-1 \right) }}
= 2\,{\pi }^{-1}+\sum _{n=1}^{\infty}4\,{\frac { \left( -1 \right) ^{1+n}
\cos \left( 2\,nx \right) }{\pi \, \left( 4\,{n}^{2}-1 \right) }}
\,, $$
which gives the desired result.
Comment: Thank you Mhenni Benghorbal. You really help me on this particular problem. You just so kind to help me. Thanks once again
Comment: @Garett:Any time. You are welcome. I am very happy that you benefitted from my answer and the other ones.

How to solve Real Analysis


Angular2 rc.5 how to inject HTTP_PROVIDERS now that Http is module

Question: Angular2 rc.5 how to inject HTTP_PROVIDERS now that all are modules...
 var injector = ReflectiveInjector.resolveAndCreate(
            [
                TodoService,
                TodoAction,
                HTTP_PROVIDERS, // <----- no longer injectable
                TodoStatsModel,
                {provide: CommBroker, useClass: CommBroker},
                {provide: AppStore, useValue: th[![i][1]][1]s.appStore}
            ]);

regards,
Sean
Answer: For RC5 you have to add the HttpModule in imports array inside @NgModule for more detail check this link
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';

@NgModule({
  imports: [BrowserModule, HttpModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

Comment: yes it works now ... will soon stop working (if using TypeScript with Web Storm for example you will see an error as HTTP_PROVIDERS  are now deprecated)
Comment: any other solutions?
Comment: i m also searching
Comment: ya :( http://stackoverflow.com/questions/38903607/ng2-rc5-http-providers-is-deprecated
Comment: What if we don't have @ngModue at the time of creation of injector using ReflectiveInjector ??

I need to create injector and call a service (which depends on http) before the root module bootstraps.


Criar stored procedure com MySQL

Question: Eu faço EAD de banco e tenho muito pouco material para me ajudar a fazer minhas atividades. Eu estou com essa questão para resolver, se alguém puder me ajudar ou me ajudar com algum caminho de material de estudo eu fico muito agradecido.
Crie uma stored procedure chamada sp_generate_quartos que gera uma carga de 10 novos quartos de cada um dos 4 tipos de quartos existentes. Quanto aos números dos quartos, deve ser aleatórios de acordo com a seguinte regra:
Tipo de Quarto Número do Quarto
1              Entre 1000 e 1999
2              Entre 2000 e 2999
3              Entre 3000 e 3999
4              Entre 4000 e 4999

No script, no enquanto, deve ser feito da tal maneira que, se for
criado um quinto tipo de quarto, o script geraria 10 quartos para
ele também, entre os intervalos de 5000 e 5999, e assim por
diante.
TABELA TIPO QUARTO
CREATE TABLE tb_tipo_quarto
  (
    cd_tipo_quarto        TINYINT NOT NULL AUTO_INCREMENT,
    nm_tipo_quarto        VARCHAR(50) NOT NULL ,
    vl_tipo_quarto_diaria NUMERIC(7,2) NOT NULL,
    PRIMARY KEY(cd_tipo_quarto)
  ) ;

Comment: O que você fez da consulta até agora?  Compartilha seu progresso para que possa ser ajudado...
Comment: Eu só consegui a estrutura do do Stored, as condições impostas no enunciado eu não sei fazer.
Answer: Bom vamos lá, primeiro você terá que criar uma tabela de quartos para armazenar essas informações:
CREATE TABLE tb_quarto(
    cd_quarto INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    cd_tipo_quarto INT NOT NULL,
    nm_quarto INT
);

Depois criamos a procedure onde passaremos o numero do quarto 1,2,3 etc... e ele irá inserir na tb_quartos 10 quartos randomicos entre os números que você passou(milhar de cada número), caso os quartos já possuam 10 quartos a procedure não faz nada, segue:
DROP PROCEDURE IF EXISTS sp_gera_carga_quarto;
DELIMITER |
CREATE PROCEDURE sp_gera_carga_quarto(
    p_cd_tipo_quarto INT
)
BEGIN

    DECLARE v_n_quarto INT;
    DECLARE v_qtd_quarto INT;
    DECLARE v_cont INT DEFAULT 1;
    DECLARE v_quarto_existe TINYINT;
    DECLARE v_inicio INT;
    DECLARE v_fim INT;

    WHILE v_cont <= 10 DO

        SET v_inicio = p_cd_tipo_quarto * 1000;
        SET v_fim = v_inicio + 999;

        SELECT
                COUNT(*)
        INTO v_qtd_quarto
        FROM tb_quarto
        WHERE cd_tipo_quarto = p_cd_tipo_quarto;

        IF v_qtd_quarto = 10 THEN

            SET v_cont = 11;

        ELSE

            SET v_n_quarto = (select floor(v_inicio+(rand()*(v_fim-v_inicio))));

            SELECT
                    IF(COUNT(*) > 0,1,0)
            INTO v_quarto_existe
            FROM tb_quarto
            WHERE nm_quarto = v_n_quarto;

            IF v_quarto_existe = 0 THEN
                INSERT INTO tb_quarto(cd_tipo_quarto,nm_quarto)
                VALUES(p_cd_tipo_quarto,v_n_quarto);
                SET v_cont = v_cont + 1;
            END IF;

        END IF;

    END WHILE;

    SELECT 'carga de quartos geradas';

END
|
DELIMITER ;

Ex carga gerada do quarto 1 do número 1000 ao 1999;
CALL sp_gera_carga_quarto(1);

Retornando os quartos:
SELECT
    *
FROM tb_quarto
WHERE cd_tipo_quarto = 1;

Resultado:

Criar stored procedure com MySQL


If $p$ divides $a^n$, how to prove/disprove that $p^n$ divides $a^n$?

Question: The only thing I know for this problem is that an integer is a product of primes.
Comment: First show that $p$ divides $a$ [(Euclid's Lemma).](http://en.wikipedia.org/wiki/Euclid%27s_lemma)
Comment: Recall that a prime divides a product iff it divides some factor (by The Fundamental Theorem of Arithmetic, i.e. *existence* and *uniqueness* of prime factorizations).
Comment: @SonicFancy Right $\,a = pb\,$ so $\ a^n = (pb)^n = p^n b^n\,$ is divisible by $\,p^n.\ $ You can post your answer and accept it.
Comment: What are the prime factors of $a$?
Comment: @BillDubuque Yes, then I have p|a, so now I can say p is a prime factor of a, then p^n certainly divides a^n. Thank you guys
Answer: Thanks for the comments.
Since we have $p$$|$$a^n$
By The Fundamental Theorem of Arithmetic, p|a
then a = pq
hence $a^n=$(pq)$^n$ $=$ $p^n$$q^n$.
Now it is obvious that $p^n$$|$$a^n$
Answer: If $p|a^n$ then the factorization of $a^n$ must look something like this: $a^n = p^n q^n r^n \ldots$ where the various bases on the right hand side are either primes or $1$, and the exponents are all $n$.
Suppose that $p^n$ does NOT divide $a^n$. Then the factorization of $a^n$ must be something like $a^n = p^m q^n r^n \ldots$, with $m < n$. But then the equation would be false, because then $p^m q^n r^n \ldots = p^m b^n$, where $b$ is some integer. If $1 < m < n$, then $p^m b^n$ is an Achilles number (see http://mathworld.wolfram.com/AchillesNumber.html), and not a perfect power, contradicting what we supposed earlier.
This may all seem very abstract, but examples should make it crystal clear. So, for example, we have $p = 2$ and $6^3 = 216$. Since $2$ divides $216$, we know that $2^3$ is also a divisor of $216$.
Of course in my answer so far I've been assuming that we're only dealing with integers. Let's try $p = 2$ like before and $a^3 = 108$. Does $2^3$ also divide $108$? It does not, but $a$ is not an integer. $a \approx 4.7622$ (or $a$ could also be one of two complex numbers that differ only in the sign of the imaginary part).


Logs not being directed to error.log for a virtual host in apache2

Question: I have an entry in virtual hosts for apache2 as
ErrorLog /var/www/example.com/logs/error.log

The file is created at this locaiton, but logs are written to /var/log/apache2/error.log
I am using ubuntu 10.04
Appreciate any help
Answer: Usually this is caused by an improper Vhost config. Make sure that the requests you're sending to the server are actually being served by the vhost instead of the default apache process.
Another possibility is that apache2 wasn't restarted after adding the ErrorLog config.
Comment: Thanks for your response, I am using mod wsgi for django which runs as apache child process may be that is the cause! Let me change the config and see how it behaves.
Comment: Thats it, I used  mod_wsgi daemon mode and it worked.


Input visibility dont change in javascript

Question: This program calculate the avarege of numbers. The number inputs appear according with the "input7", that represent the quantity of inputs. But for some reason the inputs dont change it visibility (They dont appear).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajuda Matemática</title>
<link rel="stylesheet" href="style2.css" type="text/css"/>

Ajuda Matemática

Ajuda para exercicios matemáticos

Média

Porcentagem

R. de Três

Média

     <input type="text" class="numE" id="input1"/>
        <input type="text" class="numD" id="input2"/>

        <input type="text" class="numE" id="input3"/>
       <input type="text" class="numD" id="input4"/>

        <input type="text" class="numE" id="input5"/>
        <input type="text" class="numD" id="input6"/>

       Quantidade de números: <input type="number" id="input7"/>

       <button onclick="calcNota()">Calcular</button>

Resultado:

* IMPORTANTE: Escreva os valores na tabela e digite a quantidade de valores em "Quantidade de números". Também no caso de números decimais use um ponto (.) ao invés de uma vírgula (,). Do contrário resultará um erro.

Comment: inputs are already `visible`, so what is going to change?
Comment: @nmnsud I assumed the non posted CSS took care of that, but of course, that's correct.
Comment: moreover `input7.value` is `string` not `number`
Comment: @nmnsud Yes, which I already posted an answer with
Comment: @LGSon Ah! sorry I posted comment late...
Comment: Could you let me know what is not working with the answer a gave, so I will be able to adjust and you to accept?
Answer: As the input value is a String, do like this
if(parseInt(input7.value) === 1){

or
if(input7.value === "1"){

Based on a comment, here is a sample from your code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Ajuda Matemática</title>
  <link rel="stylesheet" href="style2.css" type="text/css" />

Média

  <input type="text" class="numE" id="input1" />
  <input type="text" class="numD" id="input2" />

  <input type="text" class="numE" id="input3" />
  <input type="text" class="numD" id="input4" />

  <input type="text" class="numE" id="input5" />
  <input type="text" class="numD" id="input6" />

    Quantidade de números:
    <input type="number" id="input7" />

    <button onclick="calcNota()">Calcular</button>

Comment: I have tried your answer. It didn't did nothing. And input7 type is set to number.
Comment: @RafaelBorges I updated my answer with a sample showing it does work
Comment: It keeps the same.
Comment: @RafaelBorges As you can see it works in this snippet, so if not in your own code you missed something from mine. Give me a link to a page and I'll have a look


Find three positive numbers $x$, $y$, $z$ whose sum is $10$ such that $x^2y^2z$ is a maximum

Question: I'm self learning from the Vector Calculus book available online in PDF form (page 88). The question is: Find three positive numbers $x$, $y$, $z$ whose sum is $10$ such that $x^2y^2z$ is a maximum. Searching around for similar questions I see Lagrange multipliers mentioned as helpful, but that is subsequent material in the book so not meant to be applied here. Here's what I've done:
Rewrite the product as a function of two variables $x$ and $y$ because we know $z = 10 - x - y$:
$$f(x,y) = x^2y^2(10-x-y)$$
Compute $\frac{\partial{f}}{\partial{x}} = xy^2(20-3x-2y)$ and $\frac{\partial{f}}{\partial{y}} = x^2y(20-2x-3y)$
Now I know I need to set these to $0$ and solve simultaneously then look at the possible values of $x$ and $y$. I'm stuck here as I don't know how to solve this system:
$$xy^2(20-3x-2y) = 0$$
$$x^2y(20-2x-3y) = 0$$
I thought as they're both equal to $0$ then they're both equal to each other. Then I thought I could cancel out $x$ and $y$ but then figured I'd be losing solutions. Perhaps someone can tell me a good way to approach this?
Comment: Hint: A product is zero, iff at least one of the factors is zero.. your system will be mouch easier..
Comment: Use Lagrange Multipliers, they're useful for any sort of optimisation problem like this, they're in section 2 of that book on page 96 and they are really very useful.
Answer: Your solution is perfect. Non of $x$ and $y$ could be $0$, since then the multiplication will be $0$ as well, so with this assumption that non of $x$ and $y$ is $0$ is zero then we cancel out and $xy^2$ and $x^2y$ and we have these equations:
$2y+3x=20$
$3y+2x=20$
which implies $x=y=4$
by this we have $z=2$ and hence we have the desired multiplication to be equal to 512.
Answer: A solution without calculus: By the AM-GM inequality, we have $$x \cdot x \cdot y \cdot y \cdot 2z \leq \left( \frac{x+x+y+y+2z}{5} \right)^5 = 4^5 = 2^{10},$$ hence $x^2y^2z$ is at most $2^9$. Equality holds for $x=4$, $y=4$ and $z=2$.
Answer: As you know $x,y$ are both not zero, you can divide by them, giving $2x+3y=20=3x+2y$ Subtracting gives $x-y=0,$ so $x=y=4, z=2$


Probability of RGB cube with identically coloured opposite faces?

Question: I was given a really interesting problem at an interview. It seems like an elementary question but I just can't think about it it properly. Apologies if the wording is a bit odd, I can't think of better ways the phrase the question:

The six faces of a cube can be painted red, green or blue. What is the probability that each pair of opposite faces is coloured a distinct colour (i.e. one pair opposite faces is painted red, another pair painted green, the last pair painted blue) if:
  a) the colour for each face is randomly chosen with probability $\frac13$?
  b) the cube has exactly 2 red, 2 green, and 2 blue faces?

I am not too sure how to begin because of the geometry/symmetry involved. For example, for a), is the probability of a fully red cube $\frac1{3^6}$ or $\frac6{3^6}$? In fact, is the number of ways to have three pairs of identically coloured opposite faces of distinct colours $3!$, or is there more geometry involved? I feel like I'm overthinking somewhere.
Tldr; how do I account for overcounting due to the symmetry in the problem? Am I even overcounting in the first place?
Comment: When you say "each pair of opposite faces is coloured a distinct colour" does that mean the two sides *in each pair* have the same colour - so there is a pair of red sides, a pair of green sides and a pair of blue side ? Or does it mean the two sides in each pair of opposite sides have different colours ?
Comment: @gandalf61 the former!
Answer: The fact that these faces are on a cube is irrelevant for the problem. The only thing that matters is, you have 3 pairs of faces to paint.
(a) There are $3^6 = 729$ ways to paint the cube. There are $3!$ ways to assign the colors to the three pairs. Therefore the probability is $\frac{6}{729} = \frac{2}{243}$.
(b) Now there are only ${6 \choose 2} \cdot {4 \choose 2} = 90$ ways to paint the cube. Therefore the answer to (b) is $\frac{6}{90} = \frac{1}{15}$.
Comment: Hi, could you explain a bit more on why the geometry is irrelevant?
Comment: @user107224 Because you could just peel off the faces and put them on the table. The problem would remain the same, right?
Comment: wow didn't think of it that way! Spent so long dividing things by 6 and 2 that I lost track of everything! Thanks!
Comment: It really depends on the probability space. If one understands the second question as "probability of every possible cube is the same", then geometry plays role, and the answer is 1/6


Linear algebra : Why $C_{n+1} - A^{-1} = (C_n - A^{-1})NM^{-1}$ and why $(C_n)$ converges to $A^{-1}$?

Question: Let $ A \in M_d(\mathbb{R})$ an invertible matrix. We suppose $A=M-N$ with $M \in M_d(\mathbb{R})$ is invertible. We want to approach $A^{-1}$ with a sequence of matrix $(C_n)_{n \in \mathbb{N}}$ by the recurrence relation :
$C_{n+1} = C_n + (I_d -C_n A)M^{-1}$.
We want a necessary condition to prove that $(C_n)_{n \in \mathbb{N}}$ converges to $A^{-1}$ for all choice of $C_0$.
We have the following equality $C_{n+1} - A^{-1} = (C_n - A^{-1})NM^{-1}$ that I don't understand, and we deduce $C_n - A^{-1} = (C_0 - A^{-1})(NM^{-1})^n$.
Someone could explain the two previous equals ? I begin in linear algebra so it's not intuitive to me... Thank you in advance !
Comment: But...what is $\;C_0\;$ , or $\;C_1\;$ ?
Comment: @DonAntonio Perhaps $C_0$ is arbitrary.
Comment: @MichaelBurr Yes, perhaps....and if not? Let's hope the OP addresses the question...
Comment: Oh, sorry, I edited. The real question is : "Deduce a necessary condition for $(C_n)$ converges to $A^{-1}$ for all choice of $C_0$".
Answer: Observe that since
$$
C_{n+1}=C_n+(I_d-C_nA)M^{-1},
$$
we can subtract $A^{-1}$ from both sides to get
$$
C_{n+1}-A^{-1}=C_n+(I_d-C_nA)M^{-1}-A^{-1}.
$$
Since $A^{-1}A=I_d$, we can rewrite this as
$$
C_{n+1}-A^{-1}=C_n+(I_d-C_nA)A^{-1}AM^{-1}-A^{-1}.
$$
Distributing the $A^{-1}$ and regrouping results in
$$
C_{n+1}-A^{-1}=(C_n-A^{-1})+(A^{-1}-C_n)AM^{-1}.
$$
Since multiplying by $I_d$ doesn't change anything, this is the same as
$$
C_{n+1}-A^{-1}=(C_n-A^{-1})I_d+(A^{-1}-C_n)AM^{-1}.
$$
Factoring the $C_n-A^{-1}$ on the RHS gives
$$
C_{n+1}-A^{-1}=(C_n-A^{-1})(I_d-AM^{-1}).
$$
Since $A=M-N$,
$$
C_{n+1}-A^{-1}=(C_n-A^{-1})(I_d-(M-N)M^{-1}),
$$
and by multiplying this out,
$$
C_{n+1}-A^{-1}=(C_n-A^{-1})(I_d-I_d+NM^{-1})=(C_n-A^{-1})NM^{-1},
$$
as desired.
The second equality is treating this as you might deal with a geometric series/induction.  In other words, by substituting the previous line into the next line,
\begin{align}
C_0-A^{-1}&=(C_0-A^{-1})I_d=(C_0-A^{-1})(NM^{-1})^0\\
C_1-A^{-1}&=(C_0-A^{-1})NM^{-1}=(C_0-A^{-1})(NM^{-1})^1\\
C_2-A^{-1}&=(C_1-A^{-1})NM^{-1}=(C_0-A^{-1})(NM^{-1})^2\\
C_3-A^{-1}&=(C_2-A^{-1})NM^{-1}=(C_0-A^{-1})(NM^{-1})^3
\end{align}
and so on.
Comment: Thank you so much. It's very clear !


How to create a view grid that changes content type per row

Question: Goal: Create a Grid that shows mixed content types and have control how those types are added to grid (ie. by row)
I have 3 content types and would like control over how they are added to a view.
Case 1: inject a row of Content Type B or C into a view of Type A based on row number.
Case 2: intersperse view with (possibly random) Content type C (think adding images to liven it up.)
Some approaches I've explored:

Display Suite View Display
Views Context Display
Panels with Context
Views embeded in views
NodeQueue

For case 1 I could just create seperate blocks but then I need to keep the view order consistent (perahps using nodequeue?) across blocks.  Do I need to pass the current node queue position as an argument to each block?
For case 2 how do I insert Content Type C images every few rows?  (I could even use css but need the grid to wrap around it.)
Important note: I'm a system builder, not a developer so prefer something that can be maintained without managing custom code but a basic views template would be fine.
Case 1
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type B
Content Type B
Content Type B
Content Type B
Content Type B
Content Type B
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type C
Content Type C
Content Type C
Content Type C
Content Type C
Content Type A
Case 2
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type C
Content Type A
Content Type A
Content Type C
Content Type A
Content Type B
Content Type B
Content Type B
Content Type C
Content Type B
Content Type B
Content Type A
Content Type A
Content Type C
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type C
Content Type A
Content Type A
Comment: It gets even worse as Views is not letting me mix hte content types.  https://www.drupal.org/project/views_field_view could be helpful, but what I'd really like is to create a View that acts as a Content Type to views.  This way I could do the ordering and avoid having to code a template to insert.
Answer: sounds doable with Views Field View, I have done something a bit similar using Views Field View with Contextual filters. if it did't work the way you want, so you need to code it checkout this answer


Exporting Blocks from Drupal 6 to 7

Question: Can anyone tell me the best way to export blocks from Drupal 6 to 7?
Boxes? Features? A Straight field for filed export?
Answer: Assuming they are straight up Blocks with body content (not View blocks or other contrib generated blocks), I would create a module that scripts and creates them on install. If you have many blocks, do them in small batches (breaking them up across update_n hooks).
That way you can also test them in small batches and get it right. Once up, you can disable the module and remove it.
See:

https://drupal.stackexchange.com/a/72946/57
https://www.drupal.org/node/1709954#comment-8592077

Exporting Blocks from Drupal 6 to 7


Diophantine Equations with Factor Exponents

Question: I'm trying to prove that the following equations have no solutions to finish a problem. They're intuitively impossible but I'm looking for rigorous arguments (if they are actually possible, then prove that too).
Let $d(n)$ be the number of positive divisors of a positive integer $n$.
For positive integers $a$ and $b$ that aren't perfect squares, prove that there are no solutions to the equation $$a^{d(a)/2} = b^{d(b)/2}$$
For positive integers $a^2$, $b^2$, prove that there are no solutions to the equation $$a^{2d(a) + 1} = b^{2d(b) + 1}$$
For positive integers $a^2$, $b$ where $b$ isn't a perfect square, prove that there are no solutions to the equation $$a^{2d(a) + 1} = b^{d(b)/2}$$
Comment: You need to exclude $a=b$. Do you have perfect squares with $a^{d(a)/2}=b^{d(b)/2}$ ?
Answer: Let us solve the first equation we can assume that $a>1,b>1$:
$$a^{d(a)}=b^{d(b)} \tag{1}$$
Given a prime $p$ let $v_p(x)$ the greatest integer $k$ such that $p^k$ divides $x$, and let $\omega(x)$ be the number of prime factors of $a$, in other words $\omega(x)$ is the number of primes $p$ such that $v_p(x)\neq 0$, Now the equation $(1)$ is equivalent to: for every prime $p$
$$v_p(a)d(a)=v_p(b)d(b) \tag2$$
whence $\omega(a)=\omega(b)$, we want to prove that $d(a)=d(b)$, WLOG we can assume that  $d(a)\leq d(b)$ so using $(2)$ we obtain for every prime $p$:
$$v_p(b)\leq v_p(a)\tag3$$
But using the formulas :
$$d(a)=\prod_{p\in P}(v_p(a)+1)\text{ and }d(b)=\prod_{p\in P}(v_p(b)+1)\tag4$$
we conclude using $(3)$ that
$$d(b)\leq d(a) $$
finally $d(a)=d(b)$ and from $(1)$ we conclude that $a=b$.
you can apply the same method for the other equations


why is admin not bypassing restrictions at views?

Question: I have a problem of admin not having full access to content nodes.
I wanted to create a view so that a user can see nodes he created and cannot see other users' nodes. However, 'admin' should be able to see all available nodes without any restricts, even if made.
My problem is that, when it comes to restricting the users to see only their nodes posted. Strangely the admin was included to see only his own posts as well!
(even though the settings where telling me that whatever setting I make, the admins will not be affected) but that doesn't seem to be the case.
Does any one have any idea or suggestion?
I have gone to permissions, and checked ALL values to be selected. I rebuild the permission. Yet, this is happening.
Just in case I thought some module might be interfering, I had NodeAccessdisabled and some other modules, but the result is the same! The admin is not getting a full view as supposed to when restricting!
Here's a screen shot of a user view and admin, currently as an admin (aziz here), this is what I see (3 nodes created by admin):

and those are the setting:

While on the other hand, when I created another view WITHOUT restrictions, it shows all nodes:

and here are the settings for it:

Anyone has any idea why the admin is included in restriction?
Let me know if you think there's anything wrong here. Because based on my other question is the post " how to view data row table related to user only?"
I was advised to follow these setting  (as in image, and the user who advised is working very well with him). But I think that there's something interfering with my admin role for not letting it bypass restrictions made (at least, even when I do restrict the view for users, admin shouldn't have been included).
My last hope in the admin restriction is creating 2 views for every content type, which is quite troublesome.
I hope I gave clear picture.
Answer: In your 2nd screenprint, within "filter criteria", the last line of it is says "Content: Author uid (=aziz)". That doesn't seem to be correct ...
Make sure the filter criteria only has "Content: Author uid" without "Author user: current". And keep the ID blank for the author uid, because specifying the user will only refer to the nodes published by THAT user only.
Comment: When filtering on Content:Author UID, it presents an autocomplete of user names, which then get translated, the instructions: "Enter a comma separated list of user names.". Entering a number gives an error
Comment: Thanks for the note guys..but it seemed to me that the "content:author id" was asking which username to write down!!
based on the suggestions given by you guys, i removed the username and left it blank for author uid, adding that i mistakenly removed  (author) current user..and IT WORKED!! .. now with only "content :author uid" just like that it shows the data based on user role as i wanted.
Comment: @Pierre.Vriens i noticed something as well which seems related! the content types' access control settings! .. i think the access control was not set to "view own"..so even though at permissions at everywhere says view own data only..but that access control at content type was the one leaking the permission for everyone to see, cuz it was not set!!


unique_ptr vs shared_ptr - design

Question: I'm writing a card game. I have the following classes: Card, Deck, Player, Board, GameLogic.
Deck holds a vector of unique_ptr Cards. Then a card is drawn from the deck and passed to a player. Then player picks a card and puts... Here I have a design problem. Because up to now it's totally fine to have a unique_ptr. But then I want to pass a card to both Board and GameLogic.
Currently I converted a unique_ptr to shared_ptr. But I find it either ugly and not logical.
I believe that proper usage of pointers is very important and should tell you about the lifetime of a variable. I'm doing something wrong but don't know what...
Do you have some suggestion about how to solve it?
Comment: My usual recommendation is not to see the smart pointers as just some simple self-deleting pointer, but in terms of *ownership*. Will a "resource" have multiple owners (`std::shared_ptr`) or just one owner (`std::unique_ptr`)? Perhaps smart pointers aren't correct here, but you should use plain *non-owning* pointers? Or think up a design where you *don't need* pointers?
Comment: Why do you use pointers and not just card values?
Comment: Why do you have `unique_ptr`s? Is Card polymorphic (and why)? You could just have a `vector` and copy them around by value.
Comment: @Someprogrammerdude Nothing wrong with one owner having a shared pointer, and then non-owners getting weak pointers to it.  Sure you could be writing in Java for the syntax you end up with, but it'll work perfectly well.
Comment: @UKMonkey You have to have a specific reason to need weak pointers because they're slow. But when they're needed, they are great!
Comment: So does your game logic need the card for more than a function?  (i.e. does your logic engine need to own the card at all?)  If not, why not just pass it a raw pointer while the player owns the card with its unique ptr?  If that's the case, perhaps passing the card by reference is a cleaner solution?
Comment: @Galik Very good in multithreading observer pattern, where you can't figure out when an observer is gone.
Comment: Without further information, if you **must** use pointers (and I don't see why you would) then it seems to me the cards need only **one** owner (at a time) that will last the duration of the game (because you never duplicate cards). That would suggest a `std::unique_ptr` and you can pass the *raw pointers* to the various game logic functions.
Comment: Regarding using a pointer: I have different type of cards. Only some of them can be put on a board. That's why I use pointers/polymorphism. And about using a copy. I thought that using a unique pointer I can guarantee that a card won't "cloned", used twice etc.
Answer: To use objects with specific life spans:

Prefer values over pointers.  Copy the values or pass references as needed, but don't store the references as the referenced value can be removed.
When pointers are needed, prefer unique_pointer if you can identify one owner. Pass references as needed, but don't store them.
Use shared_pointer when there are multiple owners or when "references" need to be stored. Pass weak_pointers, which can be stored and locked as needed.

Remark that you could also give some id as reference so later on, you could access objects that could have been removed.  If your Card is nothing more than an id (queen of hearts), just pass a copy of it.
Comment: No, my card is more than that. There are many different types of cards. Some of them can be put on the board, some can be used to fight, some to block, some to free... etc. There are many parameters that describe every type of card. So I don't think I would be a good idea to put them all into one class. Do you?
Answer: Following your own words:

Deck holds a vector of unique_ptr Cards. Then a card is drawn from the
  deck and passed to a player. Then player picks a card and puts... Here
  I have a design problem. Because up to now it's totally fine to have a
  unique_ptr. But then I want to pass a card to both Board and
  GameLogic.

Probably you create each card in the constructor. Though it is perfectly feasible, I don't see the point. Provided there are always the same, fixed, number of cards. I mean, you don't create new cards of each type or whatever.
I would just create the deck of cards as a simple array, and pass average pointers to players and so on. The cards will be just destroyed when the deck is destroyed.
class Deck {
public:
    const static int NumCards = ...;
...
private:
    Card cards[NumCards];
};

class Player {
public:
    void dealt(Card*[] cards);
};

One of the advantages of C++ is that lets you choose between storing objects in the heap or the stack. While the former is more flexible (when the number of available cards changes over time, for example), the latter is much more efficient, provided you know the number of items beforehand, as apparently you do in this case.
Hope this helps.
Comment: As you can see my other comments I need polimorphizm. But besides that what I do not like in such a solution is that I need some other variable to manage drawing cards from deck. When I have pointers I can get a card from a deck.
Comment: I suppose you need polymorphism because you have one class for each type of card. That can be done differently, simplifying to just one Card class, but anyway. About "another variable", yes, you need another collection in order to store in Player which cards have been dealt. However, that's much better than moving cards from one place to another one.
Answer: While I agree with the sentiment in the other answers that pointers aren't strictly necessary here, the simplest way to go if you do use pointers is to employ references:
class Deck
{
private:
    std::vector<unique_ptr<Card>> cards;
public:
    const Card& get_card(unsigned index); // returns cards[index]
}

A const reference allows you to reference it without having to convert it to shared_ptr (and without the risk of other parts of the code modifying it).
Comment: Aah, if that's what you want you can do so! `std::move` the `unique_ptr` from the `Deck` to the `Player`, then it's obviously owned by the player and no longer in the deck. After that you can pass it by reference to `Board` (using the solution above)!
Comment: OK. I got your solution. I just thought that taking a card from a deck is a good idea. Like mimic the real world where if you draw a card then it's no longer in the deck. And I hoped it would help me to avoid mistakes. When you copy a value then you have to remember to remove it from all the places.
Comment: OK. But then a player can put a card (he does not hold it no longer). So maybe then I should `std::move` it to some managing object and pass a raw pointer to both `Logic` and `Board`. What do you think?
Comment: Well, it sounds like any card is always part of either the `Deck`, a `Player`, or the `Board`. So it would make sense to keep a `unique_ptr` in one of those classes, and pass a reference to the `Logic` (or have the `Logic` read out the other classes, depends on the implementation).
Comment: Aside from that, you could also use raw pointers rather than references – the main difference here is that a reference can't be `null`, which sounds like what you want here.
Answer: if you are not satisfied with both shared pointer and unique pointer, there is no better option than normal pointer. Use observer pattern which is helpful when one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

unique_ptr vs shared_ptr - design


Given the vectors a and b orthogonal to each other find the vector V in terms of a and b where V.a=0 ,V.b=1 and [V a b]=1 ??

Question: Given the vectors a and b orthogonal to each other find the  vector V in terms of a and b where V.a=0 ,V.b=1 and [V a b]=1 ?? I am not getting any way to solve this cud u pls help me with this and pls give proper and full explanation.
Comment: What is $[V \, a \, b]$?
Comment: If your $[V \, a \, b]$ is for the determinant with $V, a$ and $b$ as the column vectors. Then $V$ cannot lie in the plane of $a$ and $b$. That means you cannot simply express $V$ as a linear combination of $a$ and $b$. You need a third component $a \times b$.
Comment: @Anurag A I think it means the scalar triple product.
Comment: That's going to be tough if $b$ is the zero vector (which is consistent with the problem statement).
Comment: @John Hughes If either of $a$ or $b$ is zero vector then it will not satisfy all the requirements of the problem (assuming Rohan's interpretation of OP's symbol). Because $[V \, a \, b]$ will denote the volume of the parallelopiped with $V, a$ and $b$ as the edges.
Comment: The *requirements* are that $a$ and $b$ are orthogonal.In my book, that doesn't entail either being nonzero. (Your definition may vary, of course). Roughly speaking: I'm criticizing the sloppy formulation of the problem.
Answer: Hope I understood properly.

We have $\vec a. \vec v =0$. Also $\vec a\times \vec b$ is perpendicular to both $\vec a, \vec b$ and $\vec a\times \vec b$ are mutually perpendicular vectors. We also know that $[\vec a\vec a\vec b] = [\vec b \vec a\vec b] = 0$.
Therefore $$\vec v = p\vec a+q\vec b+r(\vec a\times \vec b)...(1)$$ Now, as $\vec v. \vec a=0 \Rightarrow p=0$. Also, $\vec v.\vec b=1\Rightarrow 0+q|b^2|+0=1 \Rightarrow q=\frac{1}{|b^2|}$.
We have $\vec v.(\vec a\times \vec b) = p.0 + q.0 + r|\vec a\times \vec b|^2 =1 \Rightarrow [\vec v \vec a \vec b] = r|\vec a\times \vec b|^2 = 1\Rightarrow r= \frac{1}{|\vec a\times \vec b|^2}$.
Now substitute in $(1)$. Hope it helps.
Comment: Thanx a lot ,but cud pls again explain how did you get eq1 and after that??
Comment: That I understood but cud u pls give brief explanation,how did u get the values of p and q???
Comment: Yea That is fine but how with the dot product of v.a we will get value of p??
Comment: Then to find r how did u take a=0 and b=0??
Comment: I understood this but just wanted to ask if there is any other way to sove this.
Comment: So, the long explanations of mine just for this statement of yours that you know this method? Then why did you ask? Very disappointing.
Comment: I really did not wanted to disappoint you bro . After your proper explanations i got this one and thank you very  much for that but just was asking if there was any other method too.
Comment: Thank you. I feel there is no other easy method than this. Happy it helped.


locust ignoring extended sub classes and instantiates base classes

Question: i want to write base http user class and base load test shape and then extend them in sub classes but locust doesn't under stands extended classes and instatiate bas classes
these are base classes
helpers.py:
from locust.contrib.fasthttp import FastHttpUser
import  string
from locust import LoadTestShape, constant_pacing
from dotenv import load_dotenv
import os
load_dotenv()
# init parameters
host_address = "127.0.0.1"
class BaseHttpUser(FastHttpUser):
    host = host_address
    wait_time = constant_pacing(5)
    chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
    start_time = 0

class BaseRps(LoadTestShape):
    time_limit = 600
    user_spawn = {1: (1500, 10)}

    def tick(self):
        step = len(self.user_spawn.keys())
        run_time = self.get_run_time()
        print(step, )
        for idx in range(1, step+1):
            print(run_time , idx , self.time_limit)
            if run_time < idx * self.time_limit / step:
                print("here", self.user_spawn.get(idx))
                return self.user_spawn.get(idx)
        return None

and this is the file that I run
minio.py
from locust import task
from helpers import BaseHttpUser, BaseRps
import os

host_address = "127.0.0.1"
test_name = "minio"
log_file_path = 'log.log'
base_url = os.getenv("MINIO_URL")

class HttpUser(BaseHttpUser):
    host = host_address
    base_url = base_url

    @task
    def download(self):
        self.client.get(f'{self.base_url}/magnix-server-media/ads-images/ff.png', name='download')

class Rps(BaseRps):
    user_spawn = {1: (10000, 100)}

Answer: Base User classes need an attribute abstract = True to not be instantiated. https://docs.locust.io/en/stable/api.html#locust.User.abstract
I dont think you can do the same with load shape classes, but you can use class attributes (which you can manipulate in your locustfile after importing it)
Like removing Rps class and instead just doing
BaseRps.user_spawn = {1: (10000, 100)}


Find $n$ such that polynomial is divisible

Question: Find $n \in N$, such that:
$$(x^2+x+1)^2 | x^n+(x+1)^n+1 = P(x)$$
If I let $Q(x) = x^2 + x + 1$, I have that $x^3 \equiv 1$ mod$Q(x)$, so I can work out the cases for remainder of $n$ when divided by $3$ ..
But what to do next, because I need $Q^2(x)$ dividing $P(x)$ ?
I suppose this could be done with complex zeroes, but is there a faster way ?
Answer: Since $(x^2+x+1)^2$ divides $P(x):=x^n+(x+1)^n+1$, we get that $Q(x):=x^2+x+1$ divides its derivative $P'(x)=n(x^{n-1}+(x+1)^{n-1})$.
Let us see when $n(x^{n-1}+(x+1)^{n-1})$ is divisible by $Q$ by working modulo $Q(x)$. Since $x^2+x+1=0$ we get $x^2=-(x+1)$ and
$$x^3=x^2x=-(x+1)x=-x^2-x=(x+1)-x=1,$$
hence
$$x^{3k}=1, x^{3k+1}=x, x^{3k+2}=x^2=-(x+1)$$
for all $k\in\mathbb{N}$, and similarly
$$(x+1)^k=(-1)^kx^{2k}.$$
Then we get
$$n(x^{3k}+(x+1)^{3k})=n(1+(-1)^{3k}),$$
so it is $0$ iff $k$ is odd, i.e., if $3k=6k'+3$,
and $$n(x^{3k+1}+(x+1)^{3k+1})=n(x+(-1)^{3k+1}x^2),$$
$$n(x^{3k+2}+(x+1)^{3k+2})=n(x^2+(-1)^{3k+2}x),$$
which can never be zero.
Hence $Q(x)^2$ divides $P(x)$ iff $n\equiv 4\pmod{6}$.
Comment: How come that $Q(x)$ divides derivative of $P(x)$ ?
Comment: @someone Since $Q(x)^2$ divides $P(x)$, we have $P(x)=Q(x)^2R(x)$ for some polynomial $R$. Then by the product rule we get $P'(x)=2Q(x)Q'(x)R(x)+Q(x)^2R'(x)=Q(x)(2Q'(x)R(x)+Q(x)R'(x))$, so $Q$ divides $P'$.
Comment: I thought you somehow derived that from this theorem:
"If a is a root of multiplicity k of a polynomial, then it is a root of multiplicity k – 1 of its derivative". (This is completely different thing, right ?)
Thanks!
Comment: @someone No, it is the same thing, for the particular case $k=2$! The proof of the theorem is the same, just considering $k$ instead of $2$. I'll let it to you as a practising exercise!
Comment: I was somehow thinking that root of a polynomial is $a \in C$ and not a polynomial
Comment: @someone Well, you know the Factor Lemma: $a\in\mathbb{C}$ is a root of $P(x)$ if and only if $x-a$ divides $P$. What I mean is that the two proofs are analogous and equivalent, since a polynomial is a product of its linear factors, and the proof works for linear factors, so it works for polynomials more in general.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/88762/discussion-between-someone-and-jose-brox).
Answer: Since the LHS is $(x-w)^{2}(x-w^{2})^{2}$ where $w = e^{2\pi i /3}$, we need to find $n$ such that $P(w) = P(w^{2}) = 0$ and $P'(w) = P'(w^{2}) = 0$. You may use the identity $w^{2} + w + 1 = 0$ for this.
Comment: I'm not quite familiar with that type of complex exponentation
Answer: Let's call your polynomial $P_n(x)$, to indicate the dependence on $n$.  If $\omega$ is a root of $x^2 + x + 1$, we want
$\omega$ to be a root of $P_n(x)$ of multiplicity $\ge 2$,
which means both $P_n(\omega) = \omega^n + (\omega+1)^n + 1 = 0$ and
$P_n'(\omega) = n \omega^{n-1} + n (\omega+1)^{n-1} = 0$.  This last
simplifies to $$\left(1 + \frac{1}{\omega}\right)^{n-1} = -1$$
Now if $\omega^2 + \omega+1 = 0$ we have $\omega + 1 + 1/\omega = 0$, i.e. $1+1/\omega = -\omega$.  Since the powers of $\omega$ repeat $1, \omega, \omega^2$, we see that this is true if and only if $n-1 \equiv 3 \mod 6$, i.e. $n \equiv 4 \mod 6$.  For such $n$ we also have
$P_n(\omega) = \omega^n + (-\omega^2)^n + 1 = \omega + \omega^2 + 1 = 0$, so both conditions are true.
Answer: Hint $ $ A double root is a root of $P,P'$ so also $\, \frac{1}{n}(x\!+\!1)P'\!-\!P = x^{\large n-1}\!-\!1\,\Rightarrow\, 3\mid n\!-\!1,\,$ by $\,x^{\large 3}\!=1$
Comment: @someone Modular arithmetic makes it easy - as I explain in the linked answer. The above is essentially an extension of that to deal with double factors.
Comment: See also [this answer.](https://math.stackexchange.com/a/2012356/242)
Comment: It seems like you are familiar with every generalization


"mount: RPC: Timed out" when attempting to mount NFS filesystem

Question: Following a reboot of an NFS server, client machines are unable to mount it, returning the message"mount: RPC: Timed out"

I've ruled out iptables rules by clearing them
/etc/exports on the server is unchanged
rpcinfo -p from the client to the server looks OK:

    program vers proto   port
    100000    2   tcp    111  portmapper
    100000    2   udp    111  portmapper
    100003    2   udp   2049  nfs
    100003    3   udp   2049  nfs
    100003    2   tcp   2049  nfs
    100003    3   tcp   2049  nfs
    100021    1   udp  32791  nlockmgr
    100021    3   udp  32791  nlockmgr
    100021    4   udp  32791  nlockmgr
    100021    1   tcp  32768  nlockmgr
    100021    3   tcp  32768  nlockmgr
    100021    4   tcp  32768  nlockmgr
    100005    1   udp    618  mountd
    100005    1   tcp    621  mountd
    100005    2   udp    618  mountd
    100005    2   tcp    621  mountd
    100005    3   udp    618  mountd
    100005    3   tcp    621  mountd
    100024    1   udp  32765  status
    100024    1   tcp  32765  status

Advice for further diagnostics much appreciated!
Answer: I resolved this by restarting some of the client side components with
<code>/etc/init.d/nfs-common restart
</code>
I was then able to mount the filesystem just fine. Phew ;)
Comment: This script does not exist on SuSE, Fedora, Centos (and by extension is Redhat).
Answer: You need to make sure that both the client and the server have a working portmap service, visible from the client. It's possible that you don't have a working portmap on the client.


How can i bypass a CSRF protection on Website

Question: I would like to receive information with a script from one page. For this purpose I have to search for a product number on the website. FOR EXAMPLE (5000112547801)
https://www.codecheck.info

First call on the Website is this one:
https://www.codecheck.info/product.search?q=5000112547801&r=03AGdBq25ElLW_QY-SeuWMNv0aF8pr3pttdXfqkhnosSWP_vnQDw6m0h0dK53eyf9dHe5TsKrFS0zz5NVDnHjuSclFb2CcuhSjhkndgsfBoiaQsB1w0EZR543rdA0WYsf2Y21fJl8yRQOfWsTCG-H4rlhZkBRB2Myrb_zDlYoJsUuI69LDZkCHY0g0O99fPikqeYE7Vy7_gQsIEyW8zACJF03VLppqp7ZyLeq_0Gr0IrlO1hWouITd6I6SHjezQf82BdDOnquMZQ-C2hfGNd38pP7BHJdVn-Pgvnjyo9Atl4-f4fsXSVEHSj1cGTdn5HE1MI7yu1ow8aTSvkF2k2EZKMDeBtZdPfmKy3ROWF

q = product code
r = crypt I cant know.
This call gives me a link to the required website.
So my questions are:
- How can i bypass the CSRF protection?
-- If not: Is there a other way to get the content automatically?
- Is there a way that i can control a normal browser via code? so the call is made with script but with a normal browser.
thanks for your attention.
Comment: You will need use paid service to resolve the captcha then use Node with Puppeteer.
Comment: Thank you:) can you recommend a service?
Comment: Use 2captcha.com
Answer: What you want is called a 'headless browser.' It'll act like a normal browser without needing to render the content.
There's multiple options for this, so select the one that best suites your needs and current language.
https://www.keycdn.com/blog/headless-browsers
If you're in Javascript world, the Node module puppeteer may be perfect for you.
https://github.com/puppeteer/puppeteer


What is the proper way to address this result?

Question: Reading a paper I came through an argument proving the following:

Let be given a smooth action of $\mathbb{R}^n$ on a manifold $M$, such
  that it is infinitesimally free and its orbits are pairwise diffeomorphic.
  If the orbits of this action are the fibers of a surjective submersion
  $\pi:M\to P$ then $\pi$ is a locally trivial fiber bundle whose standard
  fiber is $\mathbb{T}^k\times\mathbb{R}^{n-k}$.

Is this just an easy exercise? or is a special case of some other result? and in such a case is there a useful reference?
I am asking this question in order to have a proper way to refer to this result.
Comment: If you don't get an answer here, you might consider asking at http://mathoverflow.net .
Comment: Dear Qiaochu Yuan, thanks for the attention. Probably just after your comment, Ryan Budney posted his answer. Thanks to him, I find the confirm of the argument in the paper, and that it is not special case of some other result but just a combination of standard constructions.
Answer: That the action is infinitesimally free tells you the orbits are diffeomorphic to $\mathbb R^n / G$ for various discrete subgroups $G$ of $\mathbb R^n$.   This is just general nonsense with Lie group actions.  And $\mathbb R^n/G$ is diffeomorphic to $\mathbb T^k \times \mathbb R^{n-k}$, that's pretty much just linear algebra -- take a basis for $G$ as a $\mathbb Z$-module, and extend that to a basis for $\mathbb R^n$, that gives you your diffeomorphism. In this argument $k$ need not be constant.
The last thing you're interested in is showing $k$ is constant and that the orbit types are constant.  This apparently is the reason for the assumption of the bundle.  The main thing this seems to be telling you is that the orbits are closed.  Because if the orbit is closed you can construct a transversal and apply the above argument.  This tells your your manifold $M$ fibers over something with fiber is $\mathbb T^k \times \mathbb R^{n-k}$, and that something would be $P$.
So I don't think there's a real reference for this result, it's just a standard putting-together of basic results about group actions.  Take a look at Conlon's book on manifolds -- he gives some similar (but not quite the same) types of arguments concerning actions, commuting vector fields and such.
Comment: "I don't think there's a real reference for this result, it's just a standard putting-together of basic results about group actions."  Dear Ryan Budney. Thank you for the attention. I just started learning analysis on Smooth manifolds.  Again the proof you sketched help me to consolidate the comprehension of the argument exposed in the paper.  P.S.:Thank also for the suggestion of Conlon, I like it very much.