text:
Q: Output Commas between Elements my question is similar to this one, but I don't want to use a library for this.
Imagine we have an array of names we want to output.
string names[] = { "Peter", "Max", "Jack", "Daniel", "Luke" };

for(int i = 0; i < sizeof(names); i++)
{
    cout << names[i];
}

Output: PeterMaxJackDanielLuke
This isn't exactly what we call user friendly so let's output commas between the names.
for(int i = 0; i < sizeof(names); i++)
{
    cout << names[i] << ", ";
}

Output: Peter, Max, Jack, Daniel, Luke,
The problem is the ending comma. With if I could check every loop of for if it is the last element, but this doesn't seems to be a clean solution.
What is the best way to insert commas between the elements without using a library?

A: First of all, there's a bug in your code, sizeof(names) will yield the wrong value.
To get the comma in the right places, the conventional way is as follows:
string names[] = { "Peter", "Max", "Jack", "Daniel", "Luke" };
bool first = true;

for(auto const& name : names) {
    if (first)
        first = false;
    else
        cout << ", ";
    cout << name;
}

Or, if you are not using C++11:
for (unsigned i = 0; i < sizeof(names) / sizeof(names[0]); ++i) {
    if (i > 0)
        cout << ", ";
    cout << names[i];
}

But this:

What is the best way to insert commas between the elements without using a library?

Is the wrong attitude. C++ specifically works well only when you use libraries. Without libraries, C++ is a bad language. Or, in the words of Stroustrup:

Without a good library, most interesting tasks are hard to do in C++; but given a good library, almost any task can be made easy.

A: Using boost::join:
std::cout << boost::join(names, ", ") << "\n";

because there is no point rewriting the function... although it certainly is simple enough.

A: Why not simply:
string names[] = { "Peter", "Max", "Jack", "Daniel", "Luke" };
int i;

for (i = 0; i < sizeof(names) / sizeof(names[0]) - 1; i++)
{
    cout << names[i] << ", ";
}
cout << names[i];

That is what I usually do.

A: It is not a clean solution, but it is the only solution.
for(int i = 0; i < sizeof(names); i++)
{
    cout << names[i] << (i==sizeof(names)-1)?"",", ";
}


text:
Q: Cognito respond to challenge always gives 'Invalid session for the user.' I have setup a custom authentication flow with cognito to enable email MFA. I am using the java sdk to make the api calls to log a user in with cognito.
My initiate auth works fine and my create challenge sends a verifcation code to the users email address.
However, when i am using the respondToAuthChallengeRequest to respond to the first challenge which is the custom challenge i get the error NotAuthorizedException: Invalid session for the user.
I am carrying over the session from the initiateAuthRequest so am i unsure what is going wrong here?
This is my code to begin the authentication process
       try {
           AWSCognitoIdentityProvider client = getAWSCognitoIdentityClient();

           String username = "testuser";
           String password = "password1";

           final Map<String, String> authParams = new HashMap<String, String>();
           authParams.put("USERNAME", username);
           authParams.put("PASSWORD", password);
           authParams.put("CHALLENGE_NAME", "CUSTOM_CHALLENGE");

           final AdminInitiateAuthRequest initiateAuthRequest = new AdminInitiateAuthRequest()
                   .withClientId("my client id")
                   .withUserPoolId("my user pool")
                   .withAuthFlow(AuthFlowType.CUSTOM_AUTH)
                   .withAuthParameters(authParams);

           final AdminInitiateAuthResult result = client.adminInitiateAuth(initiateAuthRequest);

           String mfaCode = getUserInput();

           authenticateMFA(result, mfaCode);

       } catch (Exception e) {
           e.printStackTrace();
       }
   }

public static void authenticateMFA(AdminInitiateAuthResult challenge, String mfaCode) throws Exception {

    AWSCognitoIdentityProvider client = getAWSCognitoIdentityClient();
    Map<String, String> challengeResponses = new HashMap<String, String>();

    challengeResponses.put("USERNAME", "testuser");
    challengeResponses.put("ANSWER", mfaCode);

    System.out.println(challenge.getSession());

    RespondToAuthChallengeRequest respondToAuthChallengeRequest = new RespondToAuthChallengeRequest();
    respondToAuthChallengeRequest.setSession(challenge.getSession());
    respondToAuthChallengeRequest.setChallengeName(challenge.getChallengeName());
    respondToAuthChallengeRequest.setClientId("my client id");
    respondToAuthChallengeRequest.setChallengeResponses(challengeResponses);

    //user logged in using email MFA
    RespondToAuthChallengeResult respondToAuthChallengeResult = client.respondToAuthChallenge(respondToAuthChallengeRequest);

    System.out.println(respondToAuthChallengeResult);
}

Define challenge

exports.handler = async(event, context, callback) => {
   if (event.request.session && event.request.session.length === 0) {
       event.response.issueTokens = false;
       event.response.failAuthentication = false;
       event.response.challengeName = 'CUSTOM_CHALLENGE';

   } else if (event.request.session && event.request.session.length === 1 && event.request.session[0].challengeName === 'CUSTOM_CHALLENGE' && event.request.session[0].challengeResult === true) {
       event.response.issueTokens = true;
       event.response.failAuthentication = false;
   } else {
       //user did not provide a correct answer yet.
       event.response.issueTokens = false;
       event.response.failAuthentication = false;
       event.response.challengeName = 'CUSTOM_CHALLENGE';
   }

   return event;
};

create challenge

const crypto = require("crypto");
var aws = require("aws-sdk");
var ses = new aws.SES({ region: "eu-west-2" });

exports.handler = async(event, context, callback) => {
   var verificationCode = 0;

       const n = crypto.randomInt(0, 100000);
       verificationCode = n.toString().padStart(6, "0");

       const minimumNumber = 0;
       const maximumNumber = 100000;

       verificationCode = Math.floor(Math.random() * maximumNumber) + minimumNumber;
       console.log('send email');
       console.log('verificationCode: '+ verificationCode);
       console.log('email: '+ event.request.userAttributes.email);

       const params = {
           Destination: { ToAddresses: [event.request.userAttributes.email] },
           Message: {
               Body: {
                   Html: {
                       Charset: 'UTF-8',
                       Data: `
This is your secret login code:

${verificationCode}
`
                   },
                   Text: {
                       Charset: 'UTF-8',
                       Data: `Your secret login code: ${verificationCode}`
                   }
               },
               Subject: {
                   Charset: 'UTF-8',
                   Data: 'Your secret login code'
               }
           },
           Source: 'my email'
       };
       await ses.sendEmail(params).promise().then((res) => {
           console.log(res);
       });

   //add to privateChallengeParameters, so verify auth lambda can read this. this is not sent to client.
   event.response.privateChallengeParameters = { "verificationCode": verificationCode };
   //add it to session, so its available during the next invocation.
   event.response.challengeMetadata = verificationCode;

   return event;
   };

redpajama_set_name: RedPajamaStackExchange


text:
Q: python-mysql connector table creation code import mysql.connector

x=mysql.connector.connect(host='localhost',user='root',passwd='subru',database='netflix')
print(x)
c=x.cursor()
a=1
def create_input():
    b=input('enter table name')
    n=int(input('enter number of columns'))
    s=''
    for i in range(n):
        if i==0:
            s=s+'(%s,'
        elif i==n-1:
            s=s+'%s)'
        else:
            s=s+'%s,'
    print(type(s))
    print(s)
    L=()
    for i in range(n):
        c1=input('enter column name')
        c2=input('enter column specs')
        z='{} {}'.format(c1,c2)
        L=L+(z,)
    print('create table {} {})'.format(b,s),L)

    c.execute("create table {}{})".format(b,s),L)
    a=1
    data=[]
    while a!=0:
        for i in range(n):
            print(L[i])
            temp=input('enter integer/string')
            if temp=='integer':
                o=int(input('enter the integer'))
                data.append(o)
            elif temp=='string':
                p=input('enter string')
                data.append(p)

        c.execute('insert into {} values{}'.format(b,s),data)
        a=int(input('enter 0 to stop adding values'))
    x.commit()

can anyone say what is wrong in this code which is intended to input and create the table in MYsql??
the error is syntax error? is the problem with the version of python used??
is there anything i can do?


text:
Q: DNS Setting for POP3 and SMTP email I'm new to server configuration, I have used rented webservers a lot, but I tried venturing myself with a VPS to run my own web/email server.
All is good, I installed VestaCP to help me with dealing with everything related, and I set up the DNS records on my .ovh domain (OVH manage panel) as follows (text format, replaced Server ip for [server_ip] and domain name for [my_domain], I kept the dots after the domain name though, so you know I'm using them [eg.: domain.ovh.]):
$TTL 3600
@   IN SOA dns109.ovh.net. tech.ovh.net. (2015082409 86400 3600 3600000 300)
                        IN NS     dns109.ovh.net.
                        IN NS     ns109.ovh.net.
                        IN MX 10  [my_domain].
                        IN A      [server_ip]
                        IN TXT    "1|www.[my_domain]"
_imaps._tcp             IN SRV    0 0 993 [my_domain].
_submission._tcp        IN SRV    0 0 465 [my_domain].
ftp                     IN CNAME  [my_domain].
pop                     IN CNAME  [my_domain].
smtp                    IN SRV    0 0 25 [my_domain].
smtp                    IN SRV    0 0 587 [my_domain].
www                     IN MX 10  [my_domain].
www                     IN A      [server_ip]
www                     IN TXT    "3|welcome"
www                     IN TXT    "l|pt"

Most of the configurations are default, I only set an A record to my server ip, and as I was trying to get email to work, I set an MX record priority 10 to point to my domain, which then points to my server because of the A record (at least that is what I understand...).
As of now, the email works and I am able to send and receive email through roundcube, what I can not do is use POP3/IMAP and SMTP to use a different email client...
I never really had to change DNS settings, so I dont even know what to look for when I search for help...
If any extra information is needed, just ask for it :)
Thanks,

A: You didn't mention the other email client you're trying to use, but since you have some SRV records, I'll assume it supports auto discovery.
It looks like there's a little bit of confusion with some of your records.
This one is fine, although some might frown upon using a CNAME, for non-autodiscovery (i.e. you manually enter pop.my_domain in your email client for the incoming server name):
pop                     IN CNAME  [my_domain].

To make it autodiscoverable, add the second line. For SRV records, the protocol should be included in the name, and the service name should begin with an underscore ("_"):
pop                     IN CNAME   [my_domain].
_pop3._tcp                 SRV     0 1 110 [my_domain].

Per RFC-6186, _submission is used to identify your SMTP server, so these are probably serving no useful purpose (and they are missing the ._protocol):
smtp                    IN SRV    0 0 25 [my_domain].
smtp                    IN SRV    0 0 587 [my_domain].

(Edit: Although not defined in the RFC, I do see _smtp._tcp being used for this, so it's possible your client would support this.)
However, you could turn them into an A record for non-autodiscovery clients:
smtp                    IN A      [my_domain].

Unless you are sending mail to user@www.my_domain this record does nothing:
www                     IN MX 10  [my_domain].

Most of this is well described in RFC-6186


text:
Q: How to kill a unix process by grabbing its PID and not using awk? Killing a process can be done by grabbing the process pid and awk:
 kill $(ps aux | grep '[m]yprocess' | awk '{print $2}')

How can I achieve the exact same thing without using awk, pkill or anything else not available in Android's shell?

A: In most of the newer *nix systems you have pkill available. So just use:
pkill -f myprocess

to kill a process by name. (Use killall on OSX)
In absence of pkill you can do:
read s _ < <(ps ax | grep '[m]yprocess') && kill "$s"

OR if BASH isn't available then use:
ps ax | grep '[m]yprocess' | while read s _; do kill "$s"; done

A: use cut -cn1-n2 to cut everything but chars from n1 to n2 in place of awk call. Find the right columns by looking at the result of ps aux and counting char positions for the field PID.


text:
Q: Values of the Herbrand quotient For a finite cyclic group $G$, there is the Herbrand quotient in the theory of group cohomology. I calculated some of those quotients and I always came up with an Integer as solution. I failed at proving that for the Herbrand quotient $h(M)$ of a $G$-Module $M$ the following is true:
$$h(M)\in\mathbb{Z}\quad\text{for all $G$-Modules $M$}.$$
So my question is if this statement is true, or if there are examples for $G$-Modules $M$ with $h(M)\in\mathbb{Q}-\mathbb{Z}$?

A: No, there are examples with non-integer Herbrand quotient. Here I give two of them:
1- $G=\mathbb{Z}/n\mathbb{Z}$ and $M$ an $n$-divisible abelian group with finite nontrivial $n$-torsion elements. Then the Herbrand quotient of the trivial action is $\frac{1}{|\{x\in M:\,nx=0\}|}$.
2- Consider the only nontrivial action of $G=\mathbb{Z}/2\mathbb{Z}$ on $M=\mathbb{Z}$, (so the action of the nontrivial element is $x\to -x$). Then $H^2(G,M) = 0, H^1(G,M) = \mathbb{Z}/2\mathbb{Z}$ and $h(M)=\frac12$.


text:
Q: Does partition size on SSD affect speed SSD speeds depend mostly on the size of a specific drive.
So lets say if a single chip on SSD has 256GB and gives 256MB/s (R/W) speed,
then a drive made of 4 chips would have 1TB capacity and 1GB/s speed,
a drive made of 8 chips would have 2TB capacity and 2GB/s speed
and so on.
Now lets assume I took such a 2TB (8 chips) drive and split it into 8 equal partitions (256GB each).
Now if I will be performing writes into only a single partition,
will I be limited to 256MB/s, or will I be able to utilize the full 2GB/s speed?

A:
SSD speeds depend mostly on the size of a specific drive

It really isn't, though.
The physical structure the memory uses, the controller specs, and other factors are also involved, and have a more substantial impact on the speed of the drive.
Further, with an SSD you don't have access to the physical structure in the way you'd need to take advantage of any such partition/structure mapping.
Both practically and theoretically you are incorrect.


text:
Q: Using json data after loading it using jquery So I'm trying to load in a json file that has header and data attributes using Javascript, and then am trying to use the data for in other methods. The json file is loading just fine (evidenced by the "console.log(header.dx)" ), but the code isn't updating my outer array (as evidenced by the call to "console.log(productPoints.length, productPoints)" ). What am I doing wrong?
var productFile = "aJsonFile.json";
var productPoints = [];
$.getJSON(productFile)
  .done(function(json) {
    var data = json[0].data;
    var header = json[0].header;
    console.log(header.dx);
    k = 0;
    for (var j = 0; j < header.ny; j++) {
      for (var i = 0; i < header.nx; i++, k++) {
        var point = new ol.geom.Point(
          [floorMod(180 + header.lo1 + i * header.dx, 360) - 180,
          header.la1 - j * header.dy]
        );
        var feature = new ol.Feature({ geometry: point, value: data[k] });
        productPoints.push(feature);
      }
    }
  });
console.log(productPoints.length, productPoints);

var floorMod = function(a, n) {
  var f = a - n * Math.floor(a / n);
  return f === n ? 0 : f;
};

A: Ajax calls are asynchronous. The ajax call may end after you log the array. Try moving your console.log inside done() function.
var productFile = "aJsonFile.json";
var productPoints = [];
$.getJSON(productFile)
  .done(function(json) {
    var data = json[0].data;
    var header = json[0].header;
    console.log(header.dx);
    k = 0;
    for (var j = 0; j < header.ny; j++) {
      for (var i = 0; i < header.nx; i++, k++) {
        var point = new ol.geom.Point(
          [floorMod(180 + header.lo1 + i * header.dx, 360) - 180,
          header.la1 - j * header.dy]
        );
        var feature = new ol.Feature({ geometry: point, value: data[k] });
        productPoints.push(feature);
      }
    }
    console.log(productPoints.length, productPoints);
  });

var floorMod = function(a, n) {
  var f = a - n * Math.floor(a / n);
  return f === n ? 0 : f;
};


text:
Q: I can't understand the last second step.
It is known that $f(x)=\sum_{n=-\infty}^{\infty}c_{n}e^{inx}$, with $c_{n}:=\frac{1}{2\pi}\int_{-\pi}^{\pi}f(x)e^{-inx}\:dx$, for $n\in\mathbb{Z}$.
To prove: $$f(Nx)=\sum_{n=-\infty}^{\infty}c_{n}e^{iNnx}, \quad N\in\mathbb{Z}\setminus\{0\}$$
Lemma: $$\frac{1}{N}\sum_{k=0}^{N-1}e^{\frac{i2\pi\mu k}{N}}=\begin{cases}1, & k \mid \mu \\ 0, & k\not\mid\mu\end{cases}$$
Where $\mu\in\mathbb{Z}$ and $N>0$.
If $N\mid \mu$, $N=r\mu$ (say), $e^{\frac{2k\pi i}{N}}=e^{2k\pi r i}=1$ for all $k\in\mathbb{Z}$.
If $N \not \mid \mu$, $\sum_{k=0}^{N-1}e^{\frac{i2\pi\mu k}{N}}=\dfrac{\left(e^{\frac{i2\pi \mu k}{N}}\right)^{N}-1}{e^{\frac{i2\pi\mu k}{N}}-1}=\dfrac{e^{i2\pi\mu k}-1}{e^{\frac{i2\pi\mu k}{N}}-1}=0$ as $e^{\frac{i2\pi\mu k}{N}}-1\neq0$ as $N \not\mid \mu$.
Proof: $$\int_{0}^{2\pi}f(Nx)e^{-inx}\:dx=\int_{0}^{2Nx}f(y)e^{-\frac{iny}{N}}\:\frac{dy}{N}=\int_{0}^{2\pi}f(y)e^{-\frac{iny}{N}}\left(\frac{1}{N}\sum_{k=0}^{N-1}e^{\frac{-2\pi i k n}{N}}\right)\:dy,\quad y=Nx$$
$$=\begin{cases}2\pi c_{n}, & \frac{n}{N}\in\mathbb{Z} \\ 0, & \frac{n}{N}\not\in\mathbb{Z}\end{cases}$$

In the course of the proof,I can't understand the second step.I need a detailed derivation.

A: As far as I can see, the proof shows the following: given a $2\pi$ periodic function $f(x)$ and its Fourier coefficients $c_n$, how can we obtain the Fourier coefficients of the function $f(Nx)$ in terms of the coefficients $c_n$? Here is how I would show what the Fourier coefficients of $f(Nx)$ are:
$$d_n=\frac{N}{2\pi}\int_{0}^{2\pi/N}f(Nx)e^{-inx}\;dx =\\
=\frac{1}{2\pi}\int_{0}^{2\pi}f(y)e^{-iy\frac{n}{N}}\;dy$$
where I've substituted $y=Nx$ and used the fact that $f(Nx)$ is $2\pi /N$ periodic. Now we replace $f(y)$ in the integral by its series representation:
$$\frac{1}{2\pi}\int_{0}^{2\pi}f(y)e^{-iy\frac{n}{N}}\;dy=\\
=\frac{1}{2\pi}\int_{0}^{2\pi}\sum_k c_k e^{iky} e^{-iy\frac{n}{N}}\;dy=\\
=\frac{1}{2\pi}\sum_k c_k \int_{0}^{2\pi} e^{iy(k-\frac{n}{N})}\;dy$$
The integral can easily be shown to evaluate to
$$\int_{0}^{2\pi} e^{iy(k-\frac{n}{N})}\;dy =
\left\{ \begin{array}{l}2\pi,\quad n=kN\\0,\quad \text{otherwise}\end{array}\right.$$
So for $d_n$ we get
$$d_n = \left\{\begin{array}{l} c_{n/N},\quad n=kN\\
0,\quad\text{otherwise}\end{array} \right.$$
EDIT: thanks Shaktal, now I can finally read the proof well, but I guess it's similar to what I have shown. Anyway, the result remains the same.
EDIT 2: Concerning the original proof, there is a mistake in the upper integration limit. It must be $2N\pi$ instead of $2Nx$. With this in mind, the integral from $0$ to $2\pi N$ is split up in $N$ integrals like this:
$$\int_{0}^{2N\pi}f(y)e^{-\frac{iny}{N}}\frac{dy}{N}=
\sum_{k=0}^{N-1}\int_{2k\pi}^{2(k+1)\pi}f(y)e^{-\frac{iny}{N}}\frac{dy}{N}=\\
\sum_{k=0}^{N-1}\int_{0}^{2\pi}f(y)e^{-\frac{in(y+2k\pi)}{N}}\frac{dy}{N}=\\
\int_{0}^{2\pi}f(y)e^{-\frac{iny}{N}}\frac{1}{N}
\sum_{k=0}^{N-1}e^{-\frac{2\pi ikn}{N}}dy$$
where we have used the fact that $f(y)$ is $2\pi$ periodic.


text:
Q: Two functions with a given difference quotient composition (motivated by the MVT) We are looking for an example of a function $f:\mathbb{R}\to \mathbb{R}$ such that there exist (at least) two functions $g:\mathbb{R}\to \mathbb{R}$ and some functions $h:\mathbb{R}^2\to \mathbb{R}$  with $\min\{x,y\}<h(x,y)<\max\{x,y\}$ (if $x\neq y$) and satisfying the functional equation $$g(h(x,y))= \frac{f(y)-f(x)}{y-x}, \;\;\; x\neq y.$$
Note. If $f$ is differentiable, $f'$ is invertible and $f'^{^{-1}}$ is continuous (e.g., if $f'$ is strictly increasing and continuous), then the mean value theorem (MVT) implies that $g=f'$ is a unique solution of the above functional equation (for some $h$ with the mentioned properties). Therefore, we should look for some examples in the following two cases:
Case 1) $f$ is differentiable and $f'$ is not invertible (e.g., $f(t)=t^3$)
Case 1) $f$ is not differentiable at some points (e.g., $f(t)=|t|, sgn(t)$).
Our prefer is examples with  explicit formulas.
Thanks in advance


text:
Q: Laravel 5.2 Entrust migrate error, cannot add foreign key constraints I installed and configure the Laravel 5.2, its working fine, for User ACL I installed the zizaco/entrust package while running this command php artisan migrate (for creating roles, permissions table etc) getting following error

[Illuminate\Database\QueryException]   SQLSTATE[HY000]: General
  error: 1215 Cannot add foreign key constraint (SQL: alter table
  role_user add constraint role_user_user_id_foreign foreign key
  (user_id) references ``    (id) on delete cascade on update
  cascade)
[PDOException]   SQLSTATE[HY000]: General error: 1215 Cannot add
  foreign key constraint

What could be the reason ? am I missing something ? I followed the step wise guideline from entrust site

A: I get same error sometimes when I'm trying to add foreign keys in the same migration (same Schema::create block). If I'm creating migration where I'm creating new column:
Schema::create(...
    ...
    $table->integer('categories_id')->unsigned();
    ...
});

And then in the same file I'm setting this column as foreign key:
Schema::table('sub_categories', function (Blueprint $table) {
    $table->foreign('categories_id')->references('id')->on('main_categories');
});

It works perfectly.
Hope this will help you.

A: I fixed the issue, in entrust migration file, there was users table name missing. see following line

$table->foreign('user_id')->references('id')->on(' ')->onUpdate('cascade')->onDelete('cascade');

So I changed to this,

$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');

I added the users table name, and issue is fixed.
Reason, Why I got this issue?
in config/auth.php file, there was not a 'table'=>'users' key/pair mentioned in providers array, see below (this is default, means when fresh laravel is installed)
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

while php artisan entrust:migration command runs, it pulls the users table name from above providers array, if there is no table mentioned then in migration file, relationship sets empty like this.

$table->foreign('user_id')->references('id')->on('')->onUpdate('cascade')->onDelete('cascade');

So, add table in provider array like this.
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
        'table'=>'users'
    ],

after that run command for entrust migration php artisan entrust:migration this will generate the proper migration file.

A: If U Use All Other Solution that given in GitHub or StackOverflow and not resolve your issue then delete users table from database admin panel and make some changes in the users migration file. Change the bigIncrements('id'); to Increment('id').
Or
Goto Database admin panel like if you use MySQL goto PHPmyadmin panel here goto database and then users here change the datatype of id from bigint(20) into int(10).


text:
Q: Footer.php being inserted before article closing tag? I have set up a child theme to 2016. I must have done -something- because the footer.php in the child theme is being inserted immediately after the .entry-footer tag (immediately before the closing article tag) and NOT where I expect it.
The net effect is that I'm having the same footer.php code occurring after each article on the blog page and -not- at the true page footer as I expect.
How do I determine why this is occurring?
Here is the code for my INDEX.PHP (Although I want to make it clear that the code is appearing in the wrong spot -also- on single pages and posts.)
<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link http://codex.wordpress.org/Template_Hierarchy
 *
 * @package WordPress
 * @subpackage Twenty_Sixteen
 * @since Twenty Sixteen 1.0
 */

get_header(); ?>

        <?php if ( have_posts() ) : ?>

            <?php if ( is_home() && ! is_front_page() ) : ?>

<?php single_post_title(); ?>

            <?php endif; ?>

            <?php
            // Start the loop.
            while ( have_posts() ) : the_post();

                /*
                 * Include the Post-Format-specific template for the content.
                 * If you want to override this in a child theme, then include a file
                 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
                 */
                get_template_part( 'template-parts/content', get_post_format() );

            // End the loop.
            endwhile;

            // Previous/next page navigation.

        // If no content, include the "No posts found" template.
        else :
            get_template_part( 'template-parts/content', 'none' );

        endif;
        ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>


text:
Q: React I get some errors which I am not able to solve When I am running my React app I get 2 errors, which look like this:
react.development.js:220 Warning: Failed prop type: Cannot read properties of undefined (reading 'hasOwnProperty')
    at Popper (http://localhost/static/js/bundle.js:16103:72)
    at http://localhost/static/js/bundle.js:2143:66
    at Tooltip (http://localhost/static/js/bundle.js:18448:83)
    at li
    at ul
    at ReactSwipe (http://localhost/static/js/bundle.js:65432:7)
    at div
    at div
    at div
    at Carousel (http://localhost/static/js/bundle.js:67196:5)
    at div
    at http://localhost/static/js/bundle.js:2143:66
    at Box (http://localhost/static/js/bundle.js:21860:72)
    at App (http://localhost/static/js/bundle.js:89:76)
    at Routes (http://localhost/static/js/bundle.js:69559:5)
    at Router (http://localhost/static/js/bundle.js:69492:15)
    at BrowserRouter (http://localhost/static/js/bundle.js:68972:5)

Could you please help me with solving this error ?


text:
Q: Hadoop on Openstack vs physical servers I'm new to Hadoop and trying to understand how it should be installed/configured. From the documentation I see that Hadoop normally should be aware about physical servers configuration (e.g replicating data between racks). So it is not clear for me, what if Hadoop installed on top of some hypervisor layer (e.g. using OpenStack), how to achieve correct replication in this case. Could you please point to articles/documentation for this?

A: That depends on your topology.
If you are spreading your OpenStack environment across multiple racks/switches and plan on moving Hadoop HDFS nodes around, then well, you can't specify a topology (or you need to change it after each move of a VM).
It will still work correctly, it will just not be as efficient as on bare metal servers and less outage resistant.
For more information you should read: http://wiki.apache.org/hadoop/Virtual%20Hadoop
Which also states:

The most significant implication is in storage. A core architectural
  design of both Google's GFS and Hadoop's GFS is that three-way
  replication onto local storage is a low-cost yet reliable way of
  storing Petabytes of data. This design is based on physical topology
  (rack and host) awareness of hadoop so it can smartly place data block
  across rack and host to get survival from host/rack failure. In some
  cloud vendors' infrastructure, this design may no longer valid as they
  don't expose physical topology (even abstracted) info to customer. In
  this case, you will be disappointed when one day all your data
  disappears and please do not complain if this happens after reading
  this page: you have been warned. If your cloud vendor do expose this
  info in someway (or promise they are physical but not virtual) or you
  own your cloud infrastructure, the situation is different that you
  still can have a reliable Hadoop cluster like in physical environment.


text:
Q: Agrupar resultado por columna en respuesta de AJAX PHP Tengo la siguiente Tabla en la base de datos, quiero recuperarla para generar un reporte:

La estoy recuperando con la siguiente sentencia función en php:
#BUSCAR CAJA Y BOLSAS
     public function todoReporteModel($datos, $tabla){
        $stmt = Conexion::conectar() -> prepare("SELECT bolsa, caja FROM $tabla WHERE lote=:lotes");
        $stmt -> bindParam(":lotes", $datos["loteAll"], PDO::PARAM_INT);
        $stmt->execute();
        return  $stmt -> fetchAll();
        $stmt->close();
   }

La respuesta que obtengo es la siguiente:

Mi consulta es:
¿Como puedo ordenar cuando recibo la respuesta, de tal manera que se agrupen los valores de las bolsas en cada caja, en funcion del numero de cajas que haya? Por ejemplo:
caja1=[1,2,3,40];
caja2=[89,78,968,125,963];
caja0=[10];

A: Puede intentar lo siguiente para obtener arrays donde la clave será la primera columna PDO::FETCH_GROUP de su SELECT el resto serán valores como normalmente se usa asociativo FETCH_ASSOC.
if ($stmt = $mysqli->prepare("SELECT caja , bolsa FROM cajas WHERE lote= :lotes")){
    $stmt->bindParam(":lotes", $datos["loteAll"], PDO::PARAM_INT);
    $stmt->execute();
    $total = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
    print_r($total[0]); // obtenemos los de la caja 0
}

Otra forma sería crear un array e ir añadiendo los elementos según su clave
$data = array();
if ($stmt = $mysqli->prepare("SELECT caja , bolsa FROM cajas WHERE lote= :lotes")){
    $stmt->bindParam(":lotes", $datos["loteAll"], PDO::PARAM_INT);
    $stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC )){
         //Insertamos nuevo array en el Indice según la columna caja
         $data[$row['caja']][] = $row;
    }
    echo json_encode($data);

}

En su método Ajax en el success o done puede recuperar los datos de la siguiente forma haciendo uso de Object.entries
$.ajax({

})
.done(function(respuesta ) {
    let result = Object.entries(respuesta );
    console.log(result[1]);//caja1
    console.log(result[0][1]);//Elementos de caja 1
})

A: Si lo que necesitas es sumar el total que tiene cada bolsa por su número de caja, puedes aplicar un GROUP BY.
SELECT SUM(bolsa), caja FROM info GROUP BY caja;

Lo que hace es ir sumando lo que tiene cada bolsa agrupado por su ID de caja.
Aquí esta un ejemplo:
http://sqlfiddle.com/#!9/37f112/7


text:
Q: Complex conditional removal/extraction of rows I have a dataframe, and I wish to run some complex 'if' statements.
To give some background - this is data for different regions in the EU.  I want to look at within country variation in 'results'.  In the EU, we have different levels of administrative boundaries (called 'region' in the table) - 1 and 2 ('level' in the table).  Preferably I want to explore variability at level '1', but some countries have smaller populations and therefore I will have to look at variability at level 2.  I have created a shortened dataset to illustrate my point.
df >- structure(list(region = structure(c(2L, 4L, 6L, 8L, 9L, 13L,
16L, 17L, 18L, 21L, 23L, 26L, 27L, 33L, 34L, 41L, 37L, 43L, 48L,
50L, 56L, 54L, 59L, 3L, 1L, 7L, 5L, 10L, 11L, 12L, 14L, 15L,
20L, 19L, 22L, 24L, 25L, 28L, 29L, 30L, 31L, 32L, 35L, 36L, 42L,
38L, 40L, 39L, 45L, 44L, 46L, 49L, 51L, 47L, 52L, 53L, 57L, 58L,
55L, 61L, 60L), .Label = c("AT13", "AT2", "AT22", "AT3", "BE10",
"BE2", "BE21", "BE3", "CH0", "CH01", "CH02", "CH03", "CZ0", "CZ01",
"CZ02", "DE4", "DEC", "DK0", "DK02", "DK04", "EE0", "EE00", "FI1",
"FI19", "FI1D", "FI2", "FR1", "FR10", "FR21", "FR22", "FR23",
"FR24", "FR8", "IE0", "IE01", "IE02", "NL1", "NL23", "NL31",
"NL33", "NL4", "NL41", "NO0", "NO01", "NO03", "NO07", "PL11",
"PL2", "PL21", "PL3", "PL41", "PL52", "PL62", "SE1", "SE11",
"SE2", "SE22", "SE32", "SI0", "SI01", "SI02"), class = "factor"),
    result = c(24.43, 20.37, 23.53, 25.51, 17.73, 30.61, 46.2,
    43.75, 25.32, 53.32, 34.25, 46.15, 34.59, 38.06, 18.6, 32.29,
    28.57, 22.36, 40.98, 34.53, 21.09, 23.89, 43.15, 25.73, 30.06,
    26.64, 16.78, 18.75, 17.51, 19.58, 28.63, 25.44, 24.29, 30.73,
    53.32, 37.31, 38.19, 34.59, 53.33, 39.02, 22.92, 35.44, 19.07,
    18.38, 29.26, 38.6, 31.51, 21.54, 22.93, 17.86, 30.77, 39.87,
    44.7, 36.8, 37.5, 33.33, 19.05, 30.77, 17.98, 39.71, 45.66
    ), level = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L), country = structure(c(1L, 1L, 2L, 2L,
    3L, 4L, 5L, 5L, 6L, 7L, 8L, 8L, 9L, 9L, 10L, 11L, 11L, 12L,
    13L, 13L, 14L, 14L, 15L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 4L,
    4L, 6L, 6L, 7L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 10L, 10L, 11L,
    11L, 11L, 11L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 13L, 14L,
    14L, 14L, 15L, 15L), .Label = c("AT", "BE", "CH", "CZ", "DE",
    "DK", "EE", "FI", "FR", "IE", "NL", "NO", "PL", "SE", "SI"
    ), class = "factor")), .Names = c("region", "result", "level",
"country"), class = "data.frame", row.names = c(NA, -61L))

So,

*

*I want an if statement to remove rows IF level = 1 AND there is only one record for a country at level = 1 (i.e. it would remove countries CH, CZ, DK, EE, IE, NO and SI).  (so rows 5, 6, 9, 10, 15, 18 and 23 would be removed)
Then:

*I want a second if statement to remove rows IF level == 2 AND the country IS represented in the data frame at level 1 (having applied statement 1).
I can do simple conditioning if statements:
df<-nuts1_2[!(df$level==1),]

... but am struggling on the second part (i.e. nuts1_2$level==1 & df$country 'only appears once'??)
I should be left with a dataframe, as detailed below:
       region result level country
1     AT2  24.43     1      AT
2     AT3  20.37     1      AT
3     BE2  23.53     1      BE
4     BE3  25.51     1      BE
5     DE4  46.20     1      DE
6     DEC  43.75     1      DE
7     FI1  34.25     1      FI
8     FI2  46.15     1      FI
9     FR1  34.59     1      FR
10    FR8  38.06     1      FR
11    NL4  32.29     1      NL
12    NL1  28.57     1      NL
13    PL2  40.98     1      PL
14    PL3  34.53     1      PL
15    SE2  21.09     1      SE
16    SE1  23.89     1      SE
17   CH01  18.75     2      CH
18   CH02  17.51     2      CH
19   CH03  19.58     2      CH
20   CZ01  28.63     2      CZ
21   CZ02  25.44     2      CZ
22   DK04  24.29     2      DK
23   DK02  30.73     2      DK
24   EE00  53.32     2      EE
25   IE01  19.07     2      IE
26   IE02  18.38     2      IE
27   NO03  22.93     2      NO
28   NO01  17.86     2      NO
29   NO07  30.77     2      NO
30   SI02  39.71     2      SI
31   SI01  45.66     2      SI

In an ideal world, if these rows could be subset into another dataframe called 'deleted' - this would help my record keeping.
Any help on the above would be gratefully appreciated.

A: With the data.table package you could do it as follows:
library(data.table)
setDT(df1)[, if(!(level==1 & .N==1)) .SD, by = .(country,level)
           ][, unlev := uniqueN(level), by = country
             ][!(unlev==2 & level==2)][,unlev:=NULL][]

which gives:

    country level region result
 1:      AT     1    AT2  24.43
 2:      AT     1    AT3  20.37
 3:      BE     1    BE2  23.53
 4:      BE     1    BE3  25.51
 5:      DE     1    DE4  46.20
 6:      DE     1    DEC  43.75
 7:      FI     1    FI1  34.25
 8:      FI     1    FI2  46.15
 9:      FR     1    FR1  34.59
10:      FR     1    FR8  38.06
11:      NL     1    NL4  32.29
12:      NL     1    NL1  28.57
13:      PL     1    PL2  40.98
14:      PL     1    PL3  34.53
15:      SE     1    SE2  21.09
16:      SE     1    SE1  23.89
17:      CH     2   CH01  18.75
18:      CH     2   CH02  17.51
19:      CH     2   CH03  19.58
20:      CZ     2   CZ01  28.63
21:      CZ     2   CZ02  25.44
22:      DK     2   DK04  24.29
23:      DK     2   DK02  30.73
24:      EE     2   EE00  53.32
25:      IE     2   IE01  19.07
26:      IE     2   IE02  18.38
27:      NO     2   NO03  22.93
28:      NO     2   NO01  17.86
29:      NO     2   NO07  30.77
30:      SI     2   SI02  39.71
31:      SI     2   SI01  45.66

You can apply the same logic with dplyr:
library(dplyr)
df1 %>%
  group_by(country,level) %>%
  mutate(n = n()) %>%
  filter(!(level==1 & n==1)) %>%
  group_by(country) %>%
  mutate(unlev = length(unique(level))) %>%
  filter(!(unlev==2 & level==2)) %>%
  select(-n, -unlev)

A: We can use dplyr
library(dplyr)
df %>%
   group_by(country,level) %>%
   filter(!(level==1 & n()==1)) %>%
   group_by(country) %>%
   filter(!(n_distinct(level)==2 & level==2)) %>%
   as.data.frame()
#    region result level country
#1     AT2  24.43     1      AT
#2     AT3  20.37     1      AT
#3     BE2  23.53     1      BE
#4     BE3  25.51     1      BE
#5     DE4  46.20     1      DE
#6     DEC  43.75     1      DE
#7     FI1  34.25     1      FI
#8     FI2  46.15     1      FI
#9     FR1  34.59     1      FR
#10    FR8  38.06     1      FR
#11    NL4  32.29     1      NL
#12    NL1  28.57     1      NL
#13    PL2  40.98     1      PL
#14    PL3  34.53     1      PL
#15    SE2  21.09     1      SE
#16    SE1  23.89     1      SE
#17   CH01  18.75     2      CH
#18   CH02  17.51     2      CH
#19   CH03  19.58     2      CH
#20   CZ01  28.63     2      CZ
#21   CZ02  25.44     2      CZ
#22   DK04  24.29     2      DK
#23   DK02  30.73     2      DK
#24   EE00  53.32     2      EE
#25   IE01  19.07     2      IE
#26   IE02  18.38     2      IE
#27   NO03  22.93     2      NO
#28   NO01  17.86     2      NO
#29   NO07  30.77     2      NO
#30   SI02  39.71     2      SI
#31   SI01  45.66     2      SI


text:
Q: Load Image in Android Studio I want to show image in ImageView from my database... but I was failed.. and no error showing...
this is my MainFragment (By the way Detailtxt is working normally..)
public class MainFragment extends Fragment {

    ProgressDialog pDialog;
    JSONArray str_json = null;
    private static final String TAG_URL = "http://192.168.1.118/symanlub/readpromo.php";
    public static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    JSONParser jsonParser = new JSONParser();

    TextView detailtxt;
    ImageView img;

    View rootview;

    public MainFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootview = inflater.inflate(R.layout.fragment_main, container, false);
        new Bukaprofil().execute();
        return rootview;
    }

    class Bukaprofil extends AsyncTask<String, String, String>
    {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Sedang menampilkan...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... arg) {

            new Thread(new Runnable() {
                @Override
                public void run() {

                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    Log.d("request!", "starting");

                    JSONObject json = jsonParser.makeHttpRequest(
                            TAG_URL, "GET", params);

                    // checking  log for json response
                    Log.d("Proses ambil data", json.toString());

                    try {
                        str_json = json.getJSONArray("hasil");

                        JSONObject ar = str_json.getJSONObject(0);

                        //fetch data
                        final String edetail = ar.getString("detail");
                        final String egambar = ar.getString("img");

                        //label
                        detailtxt = (TextView)rootview.findViewById(R.id.detailtxt);
                        //gambar
                        img = (ImageView)rootview.findViewById(R.id.gambar);

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //gambar
                                ImageLoader imgLoader = new ImageLoader(getActivity());
                                imgLoader.DisplayImage(egambar, img);

                                detailtxt.setText(edetail);
                            }
                        });

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            pDialog.dismiss();
        }
    }

}

this is my fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fff">

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="vertical">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="10dp">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginBottom="15dp">

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/gambar"
                    android:layout_width="match_parent"
                    android:layout_height="450dip"
                    android:src="@drawable/pertamina222"
                    android:background="#fff"/>

            </LinearLayout>

        </LinearLayout>

        <TextView
            android:id="@+id/detailtxt"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="Test"
            android:layout_marginBottom="5dp"
            android:textStyle="bold"
            android:textSize="16sp"/>

    </LinearLayout>
</ScrollView>

</LinearLayout>

and this is my DisplayImage in Imageloader.java
final int stub_id=R.drawable.gg;
    public void DisplayImage(String url, ImageView imageView)
    {
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }

you can see "stub_id=R.drawable.gg;".. and the image that show in fragment_main.xml is gg.jpg from drawable.....
is like bitmapp result is null.. I dont't know how to fix that...
please help me!! Thanks before and sorry for my bad english...

A: You can use a third party library named  Picasso  to display image .
First add the gradle dependency  in your build.gradle  file
compile 'com.squareup.picasso:picasso:2.5.2'
After adding , your build.gradle file may look like this
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
}

Then instead of this
getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //gambar
                            ImageLoader imgLoader = new ImageLoader(getActivity());
                            imgLoader.DisplayImage(egambar, img);

                            detailtxt.setText(edetail);
                        }
                    });

Use this
getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //gambar
       Picasso.with(getActivity()).load(egambar).into(img);
                        }
                    });

EDIT
If you do not want cache
   getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //gambar
                              Picasso.with(getActivity())
                                .load(egambar)
                                .memoryPolicy(MemoryPolicy.NO_CACHE)
                                .into(img);
                            }
                        });


text:
Q: Grails unit testing help needed I want to test a Grails controller which calls a service.  I'd like to mock the service.  The Service has a method:
JobIF JobServiceIF.getJob(int)
and JobIF has a method:
String JobIF.getTitle()
Here's my controller

def workActivities = {
   JobIF job = jobService.getJob(params.id)
   [career:job]
}

I understand that I need to mock the service and the job class (there are concrete implementations for both) but I'm struggling to get my head around the Groovy mocking object syntax.  How do I mock a job and set the title to something, say "Architect" and then test the code?
So far I have:

void testWorkActivities() {
   def controller = new CareersController()
   ... // Mocking stuff I don't know how to do
   controller.params.id = 12
   def model = controller.workActivities()
   assertEquals "Architect", model["career"].getTitle()
}

A: You basically have two choices

*

*Use the Groovy mocking classes, i.e. MockFor and StubFor

*Use the Grails mock classes by calling the mockFor method of GrailsUnitTestCase. The class returned by this method is an instance of GrailsMock
Personally, I have found the Groovy mock objects to a bit more reliable than the Grails mocks. On occasions, I've found that my Grails mock objects were bypassed, even though I appeared to be setting everything up correctly.
Here's an example of how to use the Groovy mocks:
void testCreateSuccess() {

    def controller = new CareersController()

    // Create a mock for the JobService implementation class
    def mockJobServiceFactory = new MockFor(JobService)

    mockJobServiceFactory.demand.getJob {def id ->
        // Return the instance of JobIF that is used when the mock is invoked
        return new Job(title: "architect")
    }

    // Set the controller to use the mock service
    controller.jobService = mockJobServiceFactory.proxyInstance()

    // Do the test
    controller.params.id = 12
    def model = controller.workActivities()
    assertEquals "Architect", model["career"].getTitle()
}

The process is basically the same when using the Grails mocks, but you call the mockFor method of the test class, instead of instantiating MockFor.


text:
Q: SharePoint 2013 - YouTube embed full screen not working in IE 11 Youtube embed iframe full screen option is not working in IE 11 . I have done some troubleshooting and below are some key facts.

*

*Full screen option works if I change the compatibility mode to Edge. But SP Seattle masterpage defaults to IE 10 compatibility mode and full screen does not work

*I have tried allowfullscreen attribute but no luck with IE 11.

*The full screen option works in Chrome and other browsers.
4.Another interesting observation from a user is that this used to work before.

*Tried same thing in SharePoint online and same result in IE 11.

Have anyone of you experienced this problem in SharePoint lately.

A: I had the same issue with IE11.  I had to modify both master pages (Seattle & Oslo) to change compatibility mode to "edge" (current version):
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>

SharePoint (2013, at least) strips out the "allowfullscreen" tag, whether it's via Edit Source (HTML Source) or Embed Code (Snippet) or Content Editor Web Part (where it says "click here to add add new content").  I couldn't get it to stick (not even allowfullscreen="allowfullscreen").
However, SharePoint doesn't tamper with embedded files when using a Content Link in the Content Editor Web Part.  So, set your Content Link to a text file (any extension): "../SiteAssets/inc/PageName.html" (I used ".html" so that Visual Studio Code would use HTML highlighting.)
<iframe src="https://www.youtube.com/embed/M7lc1UVf-VE?rel=0" width="100%" height="800" allowfullscreen frameborder="0"></iframe>


text:
Q: traverse and update hash of hashes ruby I Need Help in writing script which help me cleaning hash of hashes before saving it. Which ever level title is empty it need to be deleted. Below is Example hash.
Before running Script
  Questions= {
        "0"=>
                {
                     "title"=>"Question checkbox",
                     "id"=>"1",
                     "options_attributes"=>
                         {
                             "0"=>{"title"=>"1", "id"=>"1"},
                             "1"=>{"title"=>"2", "id"=>"2"}
                        },
                    "question_type_id"=>"4"
                },
        "1"=>
               {
                    "title"=>"Question Radio",
                    "id"=>"2",
                    "options_attributes"=>
                         {
                             "0"=>
                                 {
                                     "title"=>"yes", "id"=>"3"
                                 },
                             "1"=>
                                 {
                                     "title"=>"no", "id"=>"4"
                                 },
                             "2"=>
                                 {
                                     "title"=>"", "id"=>""
                                 }
                         },
                     "question_type_id"=>"3"
               },
        "2"=>
               {
                     "title"=>"",
                     "options_attributes"=>
                         {
                             "0"=>{"title"=>"", "id"=>""},
                             "1"=>{"title"=>"", "id"=>""}
                        },
                    "question_type_id"=>"1"
               }
    }

After Running script Required Result
Questions= {
    "0"=>
            {
                 "title"=>"Question checkbox",
                 "id"=>"1",
                 "options_attributes"=>
                     {
                         "0"=>{"title"=>"1", "id"=>"1"},
                         "1"=>{"title"=>"2", "id"=>"2"}
                    },
                "question_type_id"=>"4"
            },
    "1"=>
           {
                "title"=>"Question Radio",
                "id"=>"2",
                "options_attributes"=>
                     {
                         "0"=>
                             {
                                 "title"=>"yes", "id"=>"3"
                             },
                         "1"=>
                             {
                                 "title"=>"no", "id"=>"4"
                             }
                     },
                 "question_type_id"=>"3"
           },
}

A: Here's a script that prunes your tree of any hashes that contain "title" => "".
def prune hash
  if hash.class == Hash
    hash.delete_if{|k,v| v["title"] == ""}
    hash.each{|k,v| prune v}
  else
    hash
  end
end

result = prune Questions


text:
Q: AsyncTask not called in service Am presently trying to call an AsyncTask from my service, but every  time the service is called the AsyncTask that it is meant to perform is not called or not working. i have tried using this same service to call a text message method and it works but it is not working for the AsyncTask. My service class is below.
public class TimerLocationService extends Service {

private static boolean isRunning = false;
@Override
public void onCreate() {
    // TODO Auto-generated method stub
    //Toast.makeText(this, "Timer onCreate()", Toast.LENGTH_LONG).show();
    stopSelf();
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    //Toast.makeText(this, "Timer onBind()", Toast.LENGTH_LONG).show();
    return null;
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    stopSelf();
    isRunning = false;
   // Toast.makeText(this, "Timer onDestroy()", Toast.LENGTH_LONG).show();

}

@Override
public void onStart(Intent intent, int startId) {
    // TODO Auto-generated method stub
    super.onStart(intent, startId);
    isRunning = true;
    HttpGetAsyncTask g = new HttpGetAsyncTask();
    g.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    Toast.makeText(this, R.string.timer_message_sent, Toast.LENGTH_LONG).show();
    showNotification();
    onUnbind(intent);
    onDestroy();
    quit();
   // stopService(new Intent(this,TimerLocationService.class));

}

@Override
public boolean onUnbind(Intent intent) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "Timer onUnbind()", Toast.LENGTH_LONG).show();
    return super.onUnbind(intent);

}
public void quit() {
    int pid = android.os.Process.myPid();
    android.os.Process.killProcess(pid);
    System.exit(0);
}

    private class HttpGetAsyncTask extends AsyncTask<String, Void, String> {

        String body ="test";
        String number ="123456789";
        @Override
        protected String doInBackground(String... params) {
            URL url;
            HttpURLConnection urlConnection = null;
            String paramMessage = body;
            String paramNumber = number;
            try {
                paramMessage = URLEncoder.encode(paramMessage, "UTF-8");
            } catch (Exception e) {}
            System.out.println("body" + paramMessage + " to :" + paramNumber);
            try {
                url = new URL("https://" + paramMessage + "&to=" + paramNumber +"&from=G.A.T.E.S&reference=your_reference");

                urlConnection = (HttpURLConnection) url
                        .openConnection();

                InputStream in = urlConnection.getInputStream();

                InputStreamReader isw = new InputStreamReader(in);

                int data = isw.read();
                while (data != -1) {
                    char current = (char) data;
                    data = isw.read();
                    System.out.print(current);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

            return paramMessage;
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Toast.makeText(getApplicationContext(), R.string.get_working, Toast.LENGTH_LONG).show();

        }

}

}


text:
Q: How to make Single Responsibility Principle work with my Strategy class? How do I make my "complex" Strategy class fulfill Single Responsibility Principal? Is there any other pattern that I can apply instead?
I thought about Decorator pattern that can add more responsibility/operations to my "algorithm", but it does not seem to fit.
See this SimpleStrategy class. It gets cached and latest records, compares them and updates if required, and then performs any post processing.
class SimpleStrategy {
    private DbRecordFetcher dbRecordFetcher;
    private LatestRecordFetcher latestRecordFetcher;
    private RecordComparator recordComparator;
    private DataUpdater dataUpdater;
    private PostProcessor postProcessor;

    public void process(Input input) {
        I cached = dbRecordFetcher.fetch(input);
        I latest = latestRecordFetcher.fetch(input);

        boolean isChanged = recordComparator.compare(cached, latest);

        if (isChanged) {
            dataUpdater.update(input, latest);
        }

        postProcessor.process(input, latest);
    }
}

All the classes that SimpleStrategy is composed off are interfaces, so I can inject different implementations, for example, to fetch db and latest records.
How do I refactor it to make it follow SRP?


text:
Q: "save link as" bulk download I have a list of links in an html file and I want to perform a "save link as" for all of them so it downloads all the files into one folder.
Is this possible? I need to do this from within firefox or chrome as I am required to be logged in to the website,
Thanks,
A

A: Whilst it's possible to do this with curl (including the login), I would recommend using a browser extension. Flashgot for Firefox is excellent, you can tell it to download all files of a certain extension, or do things like pattern matching.
http://flashgot.net/


text:
Q: character tables and solubility I am currently going through a past exam paper for a group theory module and am unable to answer the following section of a question. The copy of my lecture notes doesn't seem to have a section on soluble groups but I would still like to know that if i am given the character table of this group
The how would i determine whether the group is:

*

*soluble?

*Simple?

*Isomorphic to a subgroup of $GL(n, \mathbb{C})$?

Any help would be much appreciated and thanks in advance

A: Note that number of the linear character is $1$ hence $\lvert G/G'\rvert =1$. Thus, $G$ is not solvable.
$g_2\in \ker \chi_4$ hence $G$ is not simple.
$\ker\chi_2=1$ hence $G$ is isomorphic to a subgroup of $\mathrm{GL}(2,\mathbb C)$.


text:
Q: Maximum value for a particular ID I have a data frame:
df = pd.DataFrame({"id": [1,1,1,2,2,2,3,3,3], "elev": [10,11,2,45,5,4,4,4,9], "year": [2009,2010,2010,2009,2010,2011,2006,2007,2007]})

id  elev   year
1    10    2009
1    11    2010
1    2     2010
2    45    2009
2     5    2010
2     4    2011
3     4    2006
3     4    2007
3     9    2007

I want to keep only the maximum year rows for each ID:
id  elev   year
1     11    2010
1     2     2010
2     4     2011
3     4     2007
3     9     2007

I tried the following code:
df = df.groupby("id")

df = df.max('year')
df = df.reset_index()

But its keeps only single row for each ID.

A: You need to create a boolean to filter the original dataframe with; this is possible with transform:
In [164]: df.loc[df.year.eq(df.groupby('id').year.transform('max'))]
Out[164]:
   id  elev  year
1   1    11  2010
2   1     2  2010
5   2     4  2011
7   3     4  2007
8   3     9  2007

Breakdown: This generates the max for each ID, and appends to each relevant index.
In [165]: df.groupby('id').year.transform('max')
Out[165]:
0    2010
1    2010
2    2010
3    2011
4    2011
5    2011
6    2007
7    2007
8    2007
Name: year, dtype: int64

Step2: Compare the year with the max
df.year.eq(df.groupby('id').year.transform('max'))

0    False
1     True
2     True
3    False
4    False
5     True
6    False
7     True
8     True
Name: year, dtype: bool

Step3 : Indexing
In [164]: df.loc[df.year.eq(df.groupby('id').year.transform('max'))]
Out[164]:
   id  elev  year
1   1    11  2010
2   1     2  2010
5   2     4  2011
7   3     4  2007
8   3     9  2007


text:
Q: How to pipeline CPU instructions in sequence? I am designing a 16 bit CPU in Logisim Evolution.
I have already designed single clock cycle instructions.
I have 19 bits to control.
I tried using the register and clock divider circuit to send data in a pipeline. It works, but it outputs a floating value between two parts of a sequence. Also it takes 6 clock cycles to split 38 bits of data and send it in sequence. Basically I'm saying it doesn't work.
I need a way to mask 38-bit data and send it in a sequence of two 19-bit frames in 2 clock cycles.

A: Split it into 2x19 bits using a wiring splitter, then use a multiplexer to select the current part.
You already know how to make a signal that changes on every clock cycle. So use that signal in a multiplexer to select the low part on even clock cycles and the high part on odd clock cycles (or vice versa).


text:
Q: Name for a matrix selecting one eigenvalue of an eigendecomposition Let $\mathbf A$ be a square diagonalizable matrix and its eigendecomposition be given by
$$\mathbf A = \mathbf Q \mathbf \Lambda \mathbf Q^{-1} ,$$
where $\mathbf Q$ is a matrix of eigenvectors of $\mathbf A$, and  $\mathbf \Lambda$ is the diagonal matrix whose diagonal elements are the corresponding eigenvalues of $\mathbf A$. Let $\mathbf E_i$ be a matrix of the same size as $\mathbf A$ with zeros everywhere, except for the $(i,i)$th element being equal to $1$.

Does the matrix $\mathbf Q \mathbf E_i \mathbf Q^{-1}$ have a name?

A: The matrix $P= QE_iQ^{-1}$ is a projection matrix (since $P^2=P$). It plucks out the component of any vector along the $i$th eigenvector $Q_i$: if $v = \sum_j \alpha_j Q_j,$ then
$$Pv = \alpha_i Q_i.$$
When $Q$ is orthogonal, $P$ is simple Euclidean projection onto the vector $Q_i$. Otherwise, $P$ is projection onto $Q_i$ with respect to the inner product $Q^{-T}Q^{-1}$.


text:
Q: Hyperledger FabCar Network issue via Visual Studio Code While reproducing steps from an interesting tutorial found online - Hyperledger Fabric 1.4 Tutorial - FabCar Sample Application, I have installed all Hyperledger Fabric binaries via the Curl command:
curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/master/scripts/bootstrap.sh | bash -s

From the Command Prompt window one can see that, the scripts are run correctly leading to the pull of hyperledger-docker images.

However, while launching the network from Visual Studio Code through the execution of
./startFabric.sh javascript from the fabcar sub-directory, one ends up with Fabric Images issues, which seems paradoxical.

A similar issue has been encountered, while attempting to bring up the network via the command
./network.sh up

from the test-network sub-directory too.
Thus, any relevant feedback would indeed be appreciated, given an absence of rationale to justify this matter.
[EDIT]
As a matter of fact, a synchronization issue might have caused the previously reported issue, since fabric-samples v.1.4.9 is not found from Curl command documented online. Thus the script automatically installs the latest Fabric binaries 2.x.
To rule out this issue, I have re-executed the Curl command by specifying the version 1.4.4 instead.
Therefore I can confirm, that the test-network sub-directory is not part of the Fabric binaries pertaining to the version 1.4x.
Furthermore, before the installation of this binaries, I had removed all containers, and related images, yielding to:

Back to the fabcar sub-directory, running:
./startFabric.sh javascript has still led to the following network issue :

What strikes me the most is:

*

*firstly, that configtxlator can be found on my C:\Users\...\Documents\test4\fabric-samples\bin as opposed to the path highlighted on the command window.

*secondly, I do not see the matter of version's incompatibility by scrutinizing byfn.sh:

Eventually, the manual amendment of IMAGETAG has not improved the situation.
Best

A: You seem to have the different version.
In hyperledger/fabric-samples, the test-network does not exist in version 1.4. In other words, you are running the code for the master version of fabric-samples (currently the version 2.x version). Since you're running the 1.4 tutorial, run the commands based on the 1.4 documentation and code.

*

*fabric/docs/release-1.4

*fabric/samples/release-1.4

[NOTE] It is also very likely that the different version binary has been installed. In the fabric document, the version can be specified and downloaded, so to download the binary of the corresponding version, you need to execute the command including the input parameter (version) below.
curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/master/scripts/bootstrap.sh | bash -s - 1.4.9 1.4.9 0.4.21

[EDIT - 1]
Prior to the explanation, in 1.4.x, first-network/byfn.sh exists, not test-network/network.sh. Change the branch of your fabric-samples to release-1.4.
Do not run 2.x code while doing the 1.4 tutorial.
./byfn.sh basically executes the image tag as latest. That is, if you have pulled the 2.x version of the image, even if you proceed to 1.4.x, it will run as 2.x.
cd fabric-samples
git checkout release-1.4

There are two ways.

*

*tag the latest with 1.4.x image
Untag all hyperledger latest image tags, and tag 1.4.x images as latest.
(In fact, the easiest way is to delete both the 2.x and 1.4.x images and execute the command again.)

*Or edit in byfn.sh
There is a part to set IMAGE_TAG in byfn.sh.

*

*byfn.sh

# default image tag
# IMAGETAG="latest"
IMAGETAG="1.4.9"

Make sure the value of that part matches your 1.4.x version

[EDIT - 2]
For binary I don't know where and how you built it. However, you can easily build it on the fabric github.

*

*make binaries

cd $GOPATH/src/github.com/hyperledger
git clone http://github.com/hyperledger/fabric
cd fabric
git checkout release-1.4
make native

*

*Makefile
native - ensures all native binaries are available
configtxgen - builds a native configtxgen binary
configtxlator - builds a native configtxlator binary
cryptogen  -  builds a native cryptogen binary
idemixgen  -  builds a native idemixgen binary
peer - builds a native fabric peer binary
orderer - builds a native fabric orderer binary

*Path setting

mv $GOPATH/src/github.com/hyperledger/fabric/.build/bin/* <your_bin_path>

# in my case
# mv $GOPATH/src/github.com/hyperledger/fabric/.build/bin/* usr/local/bin

or
export PATH=$PATH:$GOPATH/src/github.com/hyperledger/fabric/.build/bin


text:
Q: Angular - How can I access an outside app element? I'm using Angular 4.3.1.
Suppose I have this index.html file :
<!DOCTYPE html>
<html>
  <head>
    <base href="." />
     ...
     ...
  </head>

  <body>
    <my-app>
    loading...
  </my-app>
  </body>
</html>

An App "domain" is starting from the <my-app> elements and its inner elements.
But what if I want to access the <head> element and set one of it's attribute to some value ?
Something like :
  <head [myVal]="myObjectVal">

Sure I can access the DOM via Document.querySelector()  , But I wonder if there's a better way ( Angular way maybe?)
Question:
Suppose I have a service (@Injectable) and it has an object , how can I set <head [myVal]="myObjectVal"> in the Angular way ?
PLUNKER

A: Angular doesn't support binding to elements outside the root element.
You can use plain TS/JS like
document.querySelector('head')...

There is also the Meta service that allows to set meta tags.


text:
Q: how to find out which child of a WPF container the contextmenu was opened for? Because ToolbarTray does not support proper ItemsSource binding I'm doing things in code behind. Namely filling the tray. How can I tell which toolbar the contextmenu was opened for (with CommandParameter)?
<UserControl.Resources>
    <ContextMenu x:Key="ToolbarContextMenu">
        <MenuItem Header="Move to top" Command="{ui:CommandHandler MoveToTop}" />
        <MenuItem Header="Move to left" Command="{ui:CommandHandler MoveToLeft}" />
        <MenuItem Header="Make float" Command="{ui:CommandHandler MakeFloat}" />
    </ContextMenu>
</UserControl.Resources>
<ToolBarTray x:Name="MainToolbarTray" Orientation="{Binding Orientation}" ContextMenu="{StaticResource ToolbarContextMenu}"/>

In example above I use a toolkit where commands in ViewModel are decorated with attribute and in xaml command can be defined like this.
(Not the same as suggested. I don't want to find ToolbarTray, but the Toolbar)
EDIT: I just assigned the ContextMenu to Toolbar in code behind and used PlacementTarget as suggested.


text:
Q: Quantum harmonic oscillators with momentum-position coupling I have two coupled quantum harmonic oscillators given by the following Hamiltonian:
$$H=\frac{p_{x}^{2}}{2}+\frac{\omega^{2} x^{2}}{2}+\frac{p_{y}^{2}}{2}+\frac{\Omega^{2} y^{2}}{2}+\frac{C p_{x} y}{2}.$$
As you can see, the coupling is done over the position variable of one oscillator and the momentum of the other. I need to find the wavefunction of states where either of the two oscillators (or both) is excited.
What I tried to do:
In general when I have couple harmonic oscillators where the coupling term is of the form $C (x_1-x_2)^2$ I start by diagonalising the Hamiltonian, then define normal coordinates and write down the Hamiltonian using those. I.e., I write the Hamiltonian under the form
$$H=\frac{1}{2} \sum_{i=1}^{2} p_{i}^{2}+\frac{1}{2} \sum_{i, j=1}^{2} x_{i} K_{i j} x_{j}.$$
Then I diagonalise $K$,
$$K_D = UKU^T.$$
And define normal coordinates
$$\left(\begin{array}{l}
x_{+} \\
x_{-}
\end{array}\right) \equiv U\left(\begin{array}{l}
x_{1} \\
x_{2}
\end{array}\right),$$
leading to
$$H=\frac{1}{2}\left[p_{+}^{2}+p_{-}^{2}+\omega_{+}^{2} x_{+}^{2}+\omega_{-}^{2} x_{-}^{2}\right].$$
I am unable to use this here since I do not know how to diagonalise this Hamiltonian with the term $C p_x y$ present.

A: Your problem is basically  that of a charged particle in a magnetic field in the Landau gauge, but
I'll explain the general theory for such systems as it's both interesting and suprisingly complicated --- and seldom found in textbooks. It's essentially  the theory of Bose Bogoluibov transformations.
Suppose we are given classical (or quantum) quadratic  Hamiltonian
$$
{\mathcal H}[{\bf p},{\bf x}]= \frac 12 M_{ij} p_ip_j+ \frac 12 V_{ij} x_ix_j +  K_{ij}\,p_i x_j \nonumber\\
=\frac 12  \left[\matrix{{\bf p}^T& {\bf x}^T}\right] H \left[\matrix{ {\bf p}\cr {\bf x}}\right], \nonumber
$$
where  and  $H$ is the real, positive definite, symmetric $2N$-by-$2N$ matrix
$$
H= \left[\matrix{M& K\cr K^T &V}\right].
$$
(If $H$ is not positive definite the diagonalization is not possible   as the energy of the system is not bounded below and the eigenfrequencies are pure imaginary.)
We seek a  transformation
$$
 \left[\matrix{ {\bf p}\cr {\bf x}}\right]= S \left[\matrix{ {\bf P}\cr {\bf X}}\right]
$$
that diagonalizes $H$ via  the congruence transformation ${H}\to S^T HS $ and preserves the classical Poisson brackets and/or the quantum commutation relations. This preservation   requires
$$
S^T JS=J, \quad J= \left[\matrix{0&- {\mathbb I}_n \cr {\mathbb I}_n&\phantom{-} 0}\right],
$$
so $S\in {\rm Sp}[2N, {\mathbb R}]$, the non-compact symplectic group of linear canonical transformations.   That positive definiteness of $H$ is sufficient to ensure that we can find such an $S$ is the statement  of Williamson's theorem. The resulting frequencies are called the symplectic spectrum of $H$. They are unrelated to the eigenvalues of $H$. Further  matrix $S$ is neither orthogonal nor unitary, and so does not obey $S^{-1}=S^\dagger$
We observe  that $H$ being positive definite ensures that the matrices $H^{\pm 1/2}$ are well defined. We then see that
the matrix
$$
\tilde J= H^{-1/2}JH^{-1/2}
$$
is skew symmetric and hence an element of $\mathfrak{so}[2N]$. Therefore  there exists an     $R\in {\rm O}(2N)$  that conjugates $\tilde J$ into the Cartan algebra  of $\mathfrak{so}(2n)$ --- i.e.
$$
R^TH^{-1/2} J H^{-1/2} R= \left[\matrix{0&- \Omega^{-1} \cr \Omega^{-1} &0}\right],
$$
with  $\Omega^{-1}$ diagonal. As we are allowing  $R\in {\rm O}[2N]$ rather than demanding  $  R\in {\rm SO}[2N]$,  we can ensure that   $\Omega^{-1}$   possesses  strictly positive entries. This being so, we define
$$
 D= \left[\matrix{\Omega^{1/2}&0 \cr 0& \Omega^{1/2}}\right],
 $$
so that
$$
 DR^T H^{-1/2} J H^{-1/2} RD=J,\nonumber\\
 DR^T H^{-1/2}H H^{-1/2} R D= D^2.\nonumber
$$
Thus
$$
 S= H^{-1/2} RD \in {\rm Sp}[2N, {\mathbb R}],
 $$
and
$$
 S^T HS= D^2 = \left[\matrix{\Omega&0 \cr 0& \Omega}\right]
 $$
where  $\Omega= {\rm diag}(\omega_1,\ldots \omega_N)$.  We have
$$
{\mathcal H}[{\bf P}, {\bf Q}]=\frac 12  \left[\matrix{ {\bf P}^T& {\bf X}^T}\right]\left[\matrix{ \Omega &0\cr 0&\Omega}\right]\left[\matrix{ {\bf P}\cr {\bf X}}\right]=
\sum_i \frac {\omega_i}{2} (P_i^2+X_i^2),
$$
which is a set of
decoupled harmonic oscillators with frequency $\omega_i$.
We can of course scale $X_i\to \sqrt{\omega} X_i$ and $P_i\to P_i/\sqrt{\omega}$ without changing the commutation relations, and so
$$
\sum_i \frac {\omega_i}{2} (P_i^2+X_i^2)\to \sum_i \frac {1}{2} (P_i^2+\omega_i^2X_i^2),
$$
which probably looks more familiar.
The eigenvalues $\omega_i$ are most easily found from those of   $JH$ which are  $\pm i\omega_i$.
Note added: I see that this same strategy is discussed in a math stack exchange answer: https://math.stackexchange.com/questions/1171842/finding-the-symplectic-matrix-in-williamsons-theorem

A: I am liking the answers which have been posted, but figure to offer an answer which uses more primitive means.
This system has a classical analog with Lagrangian of the form:
$$
L=\frac{1}{2}\cdot \dot{x}\cdot M\cdot \dot{x}-\frac{1}{2}\cdot x\cdot K\cdot x\mp \frac{1}{2}\cdot \dot{x}\cdot C\cdot x
$$
I say $\mp \frac{1}{2}\cdot \dot{x}\cdot C\cdot x$ since I am not 100 % certain that the $p_x y$ term is to be considered momentum - potential energy as is the case in electrodynamics.
Lagrange' s equation $\frac{d}{dt}\cdot \frac{\partial L}{\partial \dot{x}}=\frac{\partial L}{\partial x}$ produces:
$$
\left( M^T+M \right) \cdot \ddot{x}  \mp C\cdot \dot{x}=\mp C^T\cdot \dot{x}-\left(K^T+K\right)\cdot x
$$
Which produces an eigenvalue equation and I assume that all who are reading this know how to find the normal modes of this system such that the Lagrangian becomes:
$$
L=\frac{1}{2} \underset{\alpha }{\Sigma } \left(\dot{Q}_{\alpha }^2-\omega _{\alpha }^2 Q_{\alpha }^2\right)
$$
where the $\left\{\overset{\to }{Q}_{\alpha }\right\}$ and $\left\{\omega _{\alpha }\right\}$ are the eigenmodes and eigenfrequencies.
And so the classical Hamiltonian is:
$$
H=\frac{1}{2} \underset{\alpha }{\Sigma } \left(p_{\alpha }^2+\omega _{\alpha }^2 Q_{\alpha }^2\right)
$$
And the only step left is to use canonical quantization :
$$
Q_{\alpha }\to \hat{Q}_{\alpha },p_{\alpha }\to \hat{p}_{\alpha }=-i\hbar \cdot \frac{\partial }{\partial Q_{\alpha }}
$$
where I use the hats to indicate that $\hat{Q}$ and $\hat{p}$ are quantum operators.

A: I started off by assuming a general transformation of the form:
$$\left\{\begin{array}{l}
p_{x}=v p_{-}+c p_{+}+d x_{+}, \\
p_{y}=k p_{-}+l p_{+}, \\
x=n x_{+}+q x_{-}, \\
y=u x_{+}+ax_{-}+b p_{+} ,
\end{array}\right.$$
with ${p_+, p_-,x_+, x_-}$ the new variables. To avoid confusion, I am also renaming the coupling coefficient $C$ to $\gamma$. Next I plugged the above transformations in the Hamiltonian and demanded that no off-diagonal terms survive. This constraints the transformation coefficients. I also demand that the coefficients next to $p_+^2 $ and $p_-^2$ in the Hamiltonian be $1$. This leads to the set of transformations
$$\left\{\begin{array}{l}
p_{x}=-\sqrt{1-l^{2}} p_{+}+l p_{m}-\frac{a \gamma}{2} x_{-}, \\
p_{y}=k p_{+}+\sqrt{1-l^{2}} p_{-}, \\
x=n x_{+}, \\
y=a x_{-} .
\end{array}\right.$$
We are now left with the set of coefficients ${a, l, n}$ to be determined. This can be done by enforcing the canonical commutation relations on the new and old sets of coordinates. We then find
$$[x, p_y]=0 \Rightarrow l=0, \\
[x, p_x]=i \hbar \Rightarrow n=-1, \\
[y, p_y] = i \hbar \Rightarrow a=1.$$
The resulting set of transformations is hence
$$\left\{\begin{array}{l}
p_{x}=-p_{+}- \frac{\gamma}{ 2} x . \\
p_{y}=p_{-}, \\
x=-x_{+}, \\
y=x .
\end{array}\right.$$
leading to the Hamiltonian
$$H = p_{+}^{2}+p_{-}^{2}+\omega^{2} x_{+}^{2}+\left(\Omega^{2}-\gamma^{2} / 4\right) x_{-}^{2}.$$
The normal modes are obviously
$$\omega_+ = \pm \omega, \,\,\,\,\,\,\,\, \omega_- = \sqrt{\left(\Omega^{2}-\gamma^{2} / 4\right)}.$$


text:
Q: If P = NP can asymmetric key exchanges still exist? One functions are easy to compute (ie polynomial time checking) but hard to reverse. if P = NP does that mean that asymmetric key exchanges will be reduced from polynomial computation time and exponential inversion time to polynomial computation time and "worse" polynomial inversion time.
If P = BQP can there still be secure asymmetric key exchanges using quantum computers?


text:
Q: What could I do to recover javamail Folder when a "Socket is closed" is received? I have a simple server which listen for incoming email messages from more than one folder, in this scenario for example it is listening from 2 folders.
I have two threads x folder which keep alive the connection.
I had a situation where only one folder has received a "socket is closed", while the other was alive, I would have expected that if connection (with Store?) had been closed then the other folder too has thrown exception.
Follows stacktrace:
"javax.mail.MessagingException: * BYE JavaMail Exception: java.net.SocketException: Socket is closed
        at com.sun.mail.imap.IMAPFolder.open(IMAPFolder.java:1064)
        at com.sun.mail.imap.IMAPFolder.open(IMAPFolder.java:973)
        at ....MyClass.open(MyClass.java:112)
        at ....MyClass$MyClassSynchThread.run(MyClass.java:668)
        at java.lang.Thread.run(Thread.java:748)
Caused by: com.sun.mail.iap.ConnectionException: * BYE JavaMail Exception: java.net.SocketException: Socket is closed
        at com.sun.mail.iap.Protocol.handleResult(Protocol.java:401)
        at com.sun.mail.imap.protocol.IMAPProtocol.select(IMAPProtocol.java:1184)
        at com.sun.mail.imap.IMAPFolder.open(IMAPFolder.java:1030)
        ... 4 common frames omitted

Thanks guys


text:
Q: no wifi in Ubuntu 15.04 I cannot see WiFi option in my Ubuntu 15.04. What should I do? Revert asap
lspci -nnk | grep 0280 -A2 output:-
03:00.0 Network controller [0280]: Qualcomm Atheros Device [168c:0042] (rev 30)
Subsystem: Foxconn International, Inc. Device [105b:e09a]

rfkill list output:-
0: hci0: Bluetooth
Soft blocked: no
Hard blocked: no
1: acer-wireless: Wireless LAN
Soft blocked: no
Hard blocked: no

    dmesg | grep ath
[    9.545199] ath10k_pci 0000:03:00.0: pci irq msi-x interrupts 8 irq_mode 0 reset_mode 0
[   10.029684] ath10k_pci 0000:03:00.0: Direct firmware load for ath10k/cal-pci-0000:03:00.0.bin failed with error -2
[   10.029701] ath10k_pci 0000:03:00.0: Direct firmware load for ath10k/QCA9377/hw1.0/firmware-5.bin failed with error -2
[   10.029704] ath10k_pci 0000:03:00.0: could not fetch firmware file 'ath10k/QCA9377/hw1.0/firmware-5.bin': -2
[   10.029711] ath10k_pci 0000:03:00.0: Direct firmware load for ath10k/QCA9377/hw1.0/firmware-4.bin failed with error -2
[   10.029713] ath10k_pci 0000:03:00.0: could not fetch firmware file 'ath10k/QCA9377/hw1.0/firmware-4.bin': -2
[   10.029719] ath10k_pci 0000:03:00.0: Direct firmware load for ath10k/QCA9377/hw1.0/firmware-3.bin failed with error -2
[   10.029721] ath10k_pci 0000:03:00.0: could not fetch firmware file 'ath10k/QCA9377/hw1.0/firmware-3.bin': -2
[   10.029726] ath10k_pci 0000:03:00.0: Direct firmware load for ath10k/QCA9377/hw1.0/firmware-2.bin failed with error -2
[   10.029728] ath10k_pci 0000:03:00.0: could not fetch firmware file 'ath10k/QCA9377/hw1.0/firmware-2.bin': -2
[   10.029733] ath10k_pci 0000:03:00.0: Direct firmware load for ath10k/QCA9377/hw1.0/firmware.bin failed with error -2
[   10.029735] ath10k_pci 0000:03:00.0: could not fetch firmware (-2)
[   10.029737] ath10k_pci 0000:03:00.0: could not fetch firmware files (-2)
[   10.029739] ath10k_pci 0000:03:00.0: could not probe fw (-2)

A: Your device is covered by default in Ubuntu 15.10 although it requires firmware that is not installed by default but can be added later. My first suggestion is to install 15.10.
If, however, you choose to remain with 15.04, you can compile the later driver. With a temporary working internet connection, by ethernet, tethered or whatever means possible, open a terminal and do:
sudo apt-get update
sudo apt-get install linux-headers-generic build-essential
cd ~
wget https://www.kernel.org/pub/linux/kernel/projects/backports/2015/11/20/backports-20151120.tar.gz
tar -zxvf backports-20151120.tar.gz
cd ~/backports-20151120
make defconfig-ath10k
make
sudo make install

Reboot and let us see:
dmesg | grep ath

This will tell us which firmware is missing and I will amend my answer to show how to download and install it.


text:
Q: Overriding components without interfering with other sections (SimpleResponsiveBannerComponent) I want to change what is in Section1 and from the spartacus videos what I should do is overriding the component used in that section. However that component is the SimpleResponsiveBannerComponent and it exists at least in Section1, Section2A and Section2B. So if I override that component I'm also "deleting" the content in others sections. How can I only change (by code) what is in Section1 without interfering with others sections?

A: Since Spartacus is fully CMS-driven and everything in Slots depends on CMS data, following this methodology - best way, to prevent side effects during data manipulation via CMS, that's why, I think that you have only one "right" way to figure it out.
If you change component's UI/UX behaviour - it means that you start provide new component that will be different from what you have inside another Slots (Section1, Section2A and Section2B).
Create another CMS component with custom typeCode to implement something different from SimpleResponsiveBannerComponent. Add custom component where you need and leave SimpleResponsiveBannerComponent inside Section1, Section2A and Section2B.
I believe, that other possible way to implement it on frontend code-base side (if they really exist) - wrong way and can born additional problems during manipulating with data via SmartEdit.


text:
Q: htaccess rewrite behavior (document root?) I have a htaccess/apache Rewrite Problem, but it's a little bit trickier:
I have a domain like www.example.org and all content files are in
/var/www/www.example.org/content

every file must be accessed over an index.php which is saved in
/var/www/www.example.org/start1

so there is an .htaccess which rewrite everything to the index.php (no problem).
on apache is a host definied with:
ServerName  www.example.org
DocumentRoot /var/www/www.example.org/start1

that all works pretty fine, but now I have a second requirement:
there are sepcial files in content which should be accessed over another index.php(no way to use the same index.php as before),
so i put the second index.php in
/var/www/www.example.org/start2

and let the .htaccess rewrite everything to the new index.php.
in apache I defined an Alias
Alias /special /var/www/www.example.org/start2

when i now access www.example.org/special/file the .htaccess from /var/www/www.example.org/start2 is first in the rewrite log.
But it rewrite it to the index.php in the start1 folder not, as I expected, to the index.php of start2-folder.
I think its because of the document root, but I dont know what I can do. VHost is no option, because theres only one domain

A: In the start2 folder, you probably need to do something like this:
RewriteRule ^(.*) /special/index.php [L]

Because you've aliased /special to  /var/www/www.example.org/start2.


text:
Q: Some users can run the VBA and others get the error "subscript out of range" It's my first time using VBA, so, I'm not sure if I'm going to explain my issue in the best way.
So, I have a pivot table that should be updated using the VBA code, however, every time I try to run it, it shows an error "subscript out of range". What is strange is that some people in my company can run it and we have access to the same databases. I'm not sure I was able to run it some months ago but I know that a colleague was and now, he is getting the same error and we didn't change the code. I believe that all of us have the same power pivot version.
When I debut the code, it failed in the next part:
' Update pivot table
Sheets("Pivot").Activate
Sheets("Pivot").Range("E6").Select

    ActiveWorkbook.ShowPivotTableFieldList = True
    **ActiveSheet.PivotTables("BM_Pivot").CubeFields.GetMeasure _
        "[" & dppNameStr & "].[TOTAL_ARREARS]",xlSum, "Sum of TOTAL_ARREARS"**

I am sure that the code is correct since some people can run it...Does someone know how to solve this?


text:
Q: Can i use one calculated field to "Computed column Specification" for other field calculation? I have two Child tables 1. Borrower list, 2. Return list.
i have following fields in  Return list table :
1.RETURNLISTID-->PKEY
2.MEMBERSHIPID -->FKEY
3.BOOKREFID--FKEY
4.MEMBERFULLNAME-->CALCULATED FIELD(FOR THE CORRESPONDING MEMBERSHIPID GET    VALUE FROM MEMBERS TABLE)
5.BORROWDATE-->CALCULATED FIELD(FOR THE CORRESPONDING MEMBERSHIPID,BOOKREFID GET VALUE FROM BORROWERLIST TABLE)
6.ACTUALRETURNDATE--> CALCULATED FIELD(FOR THE CORRESPONDING MEMBERSHIPID,BOOKREFID GET VALUE FROM BORROWERLIST TABLE)
7.USERRETURNDATE-->USER WILL ENTER
8.FINEAMT-->IT SHOULD BE A CALCULATED FIELD.I HAVE CREATED A FUNCTION.

i have created one function to calculate fineamt using ACTUALRETURNDATE AND USERRETURNDATE. I AM GETTING ERROR WHEN I CALL MY FUNCTION IN THE FIELD.
SO,My doubt is can i use one calculated field to function ?
find my function below.
create function dbo.GETFINEAMT(@ACTUALRETURNDATE DATETIME ,@USERRETURNDATE    DATETIME)
RETURNS INT
AS
BEGIN
DECLARE @FINEAMT INT
DECLARE @DATEDIFF INT
SET @DATEDIFF=CONVERT(INT,(DATEDIFF(DD,'@ACTUALRETURNDATE','@USERRETURNDATE')))
SET @DATEDIFF = ABS(@DATEDIFF)
SET @FINEAMT=@DATEDIFF *10
RETURN @FINEAMT
END
GO

A: if all computed columns value are coming from UDF then you must be making mistake somewhere.So will hv to see your code.
See this straight exmple throw error,
Declare @t table(col int,col2 as col+1 PERSISTED,col3 as col2+1)
insert into @t values(1)
select * from @t


text:
Q: EditText doesn't keep the text entered, ie it deletes I have a list of items as follows:

 private void getProducts() {
        List<Product> listProducts = Product.getListProduct(true);
        if (listProducts != null && listProducts.size() > 0) {
            ProductAdapter m_adapterProduct = new ProductAdapter(this, listProducts);
            mlvwProducts.setAdapter(m_adapterProduct);
        }
    }

The ProductAdapter class is as follows:

public class ProductAdapter extends ArrayAdapter<Product> {

    private Context context;
    private List<Product> mdata;

    public ProductAdapter(Context context, List<Product> mdata) {
        super(context, R.layout.act_item_product_adapter, mdata);
        this.context = context;
        this.mdata = mdata;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View item = LayoutInflater.from(context).inflate(R.layout.act_item_product_adapter,null);
        TextView m_product_name = (TextView) item.findViewById(R.id.adapter_product_nameProduct);
        TextView m_product_cost = (TextView) item.findViewById(R.id.adapter_product_cost);
        TextView m_product_stock = (TextView) item.findViewById(R.id.adapter_product_stock);
        EditText m_product_amount = (EditText) item.findViewById(R.id.adapter_product_amount);
        ImageView m_product_photo = (ImageView) item.findViewById(R.id.adapter_product_photo);

        m_product_name.setText(datos.get(position).getNombreProducto());
        m_product_cost.setText(" Cost: " + String.format("%.2f",mdata.get(position).getCostSold()));
        m_product_stock.setText(" Stock: " + Integer.toString(mdata.get(position).getStock()));
        //m_product_amout.setText("0");

        if (datos.get(position).getimagenProduct() != null){
            byte[] decodedString = Base64.decode(mdata.get(position).getimagenProduct(), Base64.DEFAULT);
            m_product_photo.setImageBitmap(BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length));
        }

        return  item;
    }
}

Everything works very well, I can retrieve the information of the products and display them in the list, but when in the EditText (m_product_amount) I enter a value and clicking another object of the activity, the number entered is deleted and remains at 0 that was The default number that is in the layout.
What am I doing wrong?
Any ideas or suggestions are welcome
Thanks
============= Question updates ===============
act_item_product_adapter.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/adapter_product_photo"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:scaleType="centerInside"
        android:background="@android:color/white"
        android:cropToPadding="true"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_toRightOf="@id/adapter_product_photo"
        android:id="@+id/linearLayout2">
        <TextView
            android:id="@+id/adapter_product_nameProducto"
            android:layout_width = "match_parent"
            android:layout_height = "37dp"
            android:gravity="center"
            android:textSize="20dp"
            android:text="Name of product"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width= "170dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/linearLayout3"
        android:layout_below="@+id/linearLayout2"
        android:layout_toRightOf="@+id/adapter_product_photo"
        android:layout_alignBottom="@+id/adapter_product_photo">
        <TextView
            android:id="@+id/adapter_product_cost"
            android:layout_width = "170dp"
            android:layout_height = "wrap_content"
            android:text="cost"/>
        <TextView
            android:id="@+id/adapter_product_stock"
            android:layout_width="170dp"
            android:layout_height="wrap_content"
            android:text="stock"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_below="@+id/linearLayout2"
        android:layout_toEndOf="@+id/linearLayout3"
        android:layout_toRightOf="@+id/linearLayout3"
        android:orientation="horizontal"
        android:layout_alignBottom="@+id/linearLayout3">
        <TextView
            android:layout_width = "wrap_content"
            android:layout_height = "match_parent"
            android:gravity="center"
            android:textSize="20dp"
            android:text="Amount"/>
        <EditText
            android:layout_width = "match_parent"
            android:layout_height = "match_parent"
            android:inputType="number"
            android:id="@+id/adapter_product_amount"
            android:gravity="center"
            android:text="0"/>
    </LinearLayout>
</RelativeLayout>

A: I suspect ListView doesn't display multiple items, it is a single item in which it displays temporary information (a few milliseconds) on the objects it contains and then displays the next item that is the same but with other values.
It is for this reason that when pointing to another part the information is deleted and the one that was assigned in public View getView.
Then I create an array of type string for the value of EditText according to the number of the item as follows:

public class ProductAdapter extends ArrayAdapter<Producto> {

    private Context context;
    private List<Product> mdata;

    private EditText m_product_amount;
    private String[] m_amounts;

    public ProductAdapter(Context context, List<Product> mdata) {
       super(context, R.layout.act_item_product_adapter, mdata);
       this.context = context;
        this.mdata = mdata;
        m_amounts = new String[mdata.size()];

    }

    ...
 }

Then I initialize the editText with the values contained in the array as follows:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View item = LayoutInflater.from(context).inflate(R.layout.act_item_product_adapter,null);

        ....

        if (null != m_amounts[position]) m_product_amount.setText(m_amounts[position]);

        ....

        return item;
}

And finally to update the values of each element of the array I do the following:

   @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

    ....

    m_product_amount.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                switch (v.getId()) {
                    case R.id.adapter_product_amount:{
                        if (false == hasFocus && m_product_amount.getText().length() > 0) {
                            m_amounts[position] = m_product_amount.getText().toString();
                        }
                    }
                }
            }
        });

    ...

    return item;

 }


text:
Q: Query Wordpress Posts by string with GraphQL I'm have a headless wordpress installation with a React front end that queries wordpress for posts. I'm trying to create a search feature, that allows me to load posts by search term from the url query string (retrieved by using const searchQuery = window.location.search.split("?q=")[1]), which gives me the string to search on.
However, I get the error "ERROR: GraphQL error: No post exists with this id:".
My GraphQL query is as follows:
 query postQuery($slug: String) {
  postBy(slug: $slug) {
    id
    slug
    status
    title
    content
    blocks {
        tagName
        type
        attributes,
        innerHtml
    }
  }
}

I have tried implementing the example here: https://graphql-search-api.readthedocs.io/en/latest/search-parameters/#fulltext, but it doesn't seem the request is what I need. I have also tried this example: https://docs.wpgraphql.com/getting-started/posts/#arguments, but again, this does not work.
There are two issues here: 1) How do I use the search term from my variable searchQuery in my GraphQL request, and 2) How do I form the query correctly, so that the term can be used to search for and return any post with the search term in either the post title or content of the post?
UPDATE
I have updated my code with a separate query from the rest of the application, but now receiving the error on the page GraphQL error: Cannot query field "title" on type "RootQueryToPostConnection". GraphQL error: Cannot query field "content" on type "RootQueryToPostConnection
const SEARCH_QUERY = gql`
        query searchPostQuery($searchStr: String) {
          posts(where: {search: $searchStr}) {
            title
            content
          }
        }
    `;

    const APP_QUERY = gql`
      query appQuery($locationId: MenuLocationEnum!) {
       ...
    }`;

    const searchQuery = window.location.search.split("?q=")[1];
    function App(props) {
      return (
        <ApolloProvider client={graphClient}>
            <Query query={window.location.pathname === "/search-results" ? SEARCH_QUERY : APP_QUERY} variables={{ locationId: "HEADER_MENU", searchStr: searchQuery }}>
              {({ data, loading, error, client }) => {
                if (loading) return "loading...";
                if (error) return
ERROR: {error.message}
;
                     return (
                  <>
                    <Query query={HEADER_QUERY}>
                      {({ data, client: headerClient }) => {
                      return (
                      <>
                      <Router>
                         ...
                        <SearchResults
                           path="/search-results"
                        />
                      </Router>
                  </>
                 );
                }}
         </Query>
      </ApolloProvider>
   );
}

A: Search is not standarized ... it depends on implementation, provider intentions etc.
postBy(slug: $slug) will return [only one] post identified by key/value, slug in this case
General (found on github) WP search query shape:
{
  posts(where: {search: "cats"}) {
    nodes {
      id
      title
      content
    }
  }
}

searchQuery can be read from location or from react-router... you can pass it into query using variables, f.e.:
query searchPostQuery($searchStr: String) {
  posts(where: {search: $searchStr) {
    nodes {
      id
      slug
      status
      title

...
variables = { searchStr: searchQuery };

Of course you can test query (before using in frontend) in /graphiql - variables can be defined below query.


text:
Q: mojarra is not defined I'm developing JSF application with mojarra.
I'm getting javascript error "mojarra is not defined".
After deploy everything is ok, ajax call works properly.
But after refreshing page, error appears.
There is lack of javascript include in head tag after refreshing.
It seems to be working very moody.
Same behavior I have on Tomcat and Glassfish, Mojarra is in version 2.0.3.

A: One of the reason this error can appear is by using .. and ... tags instead of <h:head>...</h:head> and <h:body>...</h:body>.
Namespace - xmlns:h="http://java.sun.com/jsf/html"