问:
Sed inside a while read loop
I have been reading a lot of questions and answers about using sed within a while loop. I think I have the command down correctly, but I seem to get no output once I put all of the pieces together. Can someone tell me what I am missing?

I have an input file with 700 variables, one on each line. I need to use each of these 700 variables within a sed command. I run the following command to verify variables are outputting correctly:

cat Input_File.txt | while read var; do echo $var; done

I then try to add in the sed command as follows:

cat Input_File.txt | while read var; do sed -n "/$var/,+10p" Multi-BLAST_5814.txt >> Multi_BLAST_Subset; done

This command leaves me without an error, but a blinking cursor as if this is an infinite loop. It should use each of the 700 variables, find the corresponding line in Multi_BLAST_5814.txt and output the search variable line and the 10 lines after the search term into a new file, appending each as it goes. I can execute the sed command alone with a manually set single value variable successfully and I can execute the while loop successfully using the input file. Anyone have a thought as to why this is not working?

User, that is exactly what I have done to this point.

I have a large text file (128 MB) with BLAST output. I need to search through this for a subset of results for 769 samples (Out of the 5814 samples that are in the file).

I have created a .txt file with those 769 sample names.

To test grep and sed, I manually assigned a variable with one of the 769 samples names I need to search and can get the results I need as follows:

```<code>$ Otu="S41_Folmer_Otu96;size=12;"
$ grep $Otu -A 10 Multi_BLAST_5814.txt
            OR
</code>```

$ sed -n "/$Otu/,+10p" Multi_BLAST_5814.txt

The OUTPUT is exactly what I want as follows:

```<code>    Query= S41_Folmer_Otu96;size=12;
    Length=101

    Sequences producing significant alignments:       Score(Bits)  E Value

    gi|58397553|gb|AY830431.1|  Scopelocheirus schellenbergi clone...   180    1E-41
    gi|306447543|gb|HQ018876.1|  Liposcelis paeta isolate CZ cytoc...   174    6E-40
    gi|306447533|gb|HQ018871.1|  Liposcelis decolor isolate CQ cyt...   104    9E-19
    gi|1043259532|gb|KX130860.1|  Batocera rufomaculata isolate Br...   99    4E-17
    gi|987210821|gb|KR141076.1|  Psocoptera sp. BOLD:ACO1391 vouch...   81    1E-11
</code>```

To Test to make sure the input file contains the correct variables I run the following:

```<code>$ Cat Input_File.txt
$ while read Otu; do echo $Otu; done <Input_File.txt

    S41_Folmer_Otu96;size=12;
    S78_Folmer_Otu15;size=538;
    S73_Leray_Otu52;size=6;
    S66_Leray_Otu93;size=6;
    S10_Folmer_Otu10;size=1612;
    ... All 769 variables
</code>```

Again, this is exactly what I expect and is correct.

But, When I do either of the following commands, nothing is printed to the screen (if I leave off the write file/append action) or to the file I need to create.

$ cat Input_File.txt | while read Otu; do grep "$Otu" -A 10 Multi_BLAST_5814.txt >> Multi_BLAST_Subset.txt; done

$ cat Input_File.txt | while read Otu; do sed -n "/$Otu/,+10p" Multi_BLAST_5814.txt >> Multi_BLAST_Subset.txt; done

Sed hangs and never closes, leaving me at a blinking cursor. Grep finishes but also gives no output. I am at a loss as to why this is not working. Everything works inidividually, so I may be left with manually searching all 769 samples copy/paste.

答:
Not sure whether you have already attempted it but try breaking the problem into smaller chunks. Simple example below :</p>

```<code>$ cat Input_File.txt
one
two
three
$

$ cat file.txt
This is line one
This is line two
This is line three
This is another four
This is another five
This is another six
This is another seven
$

$ cat Input_File.txt | while read var ; do echo $var ; sed -n "/$var/,+1p" file.txt ; done
one
This is line one
This is line two
two
This is line two
This is line three
three
This is line three
This is another four
$
</code>```

Title: Sed inside a while read loop

Body:
I have been reading a lot of questions and answers about using sed within a while loop. I think I have the command down correctly, but I seem to get no output once I put all of the pieces together. Can someone tell me what I am missing?

I have an input file with 700 variables, one on each line. I need to use each of these 700 variables within a sed command. I run the following command to verify variables are outputting correctly:

cat Input_File.txt | while read var; do echo $var; done

I then try to add in the sed command as follows:

cat Input_File.txt | while read var; do sed -n "/$var/,+10p" Multi-BLAST_5814.txt >> Multi_BLAST_Subset; done

This command leaves me without an error, but a blinking cursor as if this is an infinite loop. It should use each of the 700 variables, find the corresponding line in Multi_BLAST_5814.txt and output the search variable line and the 10 lines after the search term into a new file, appending each as it goes. I can execute the sed command alone with a manually set single value variable successfully and I can execute the while loop successfully using the input file. Anyone have a thought as to why this is not working?

User, that is exactly what I have done to this point.

I have a large text file (128 MB) with BLAST output. I need to search through this for a subset of results for 769 samples (Out of the 5814 samples that are in the file).

I have created a .txt file with those 769 sample names.

To test grep and sed, I manually assigned a variable with one of the 769 samples names I need to search and can get the results I need as follows:

$ Otu="S41_Folmer_Otu96;size=12;"
$ grep $Otu -A 10 Multi_BLAST_5814.txt
            OR

$ sed -n "/$Otu/,+10p" Multi_BLAST_5814.txt

The OUTPUT is exactly what I want as follows:

    Query= S41_Folmer_Otu96;size=12;
    Length=101

    Sequences producing significant alignments:       Score(Bits)  E Value

    gi|58397553|gb|AY830431.1|  Scopelocheirus schellenbergi clone...   180    1E-41
    gi|306447543|gb|HQ018876.1|  Liposcelis paeta isolate CZ cytoc...   174    6E-40
    gi|306447533|gb|HQ018871.1|  Liposcelis decolor isolate CQ cyt...   104    9E-19
    gi|1043259532|gb|KX130860.1|  Batocera rufomaculata isolate Br...   99    4E-17
    gi|987210821|gb|KR141076.1|  Psocoptera sp. BOLD:ACO1391 vouch...   81    1E-11

To Test to make sure the input file contains the correct variables I run the following:

$ Cat Input_File.txt
$ while read Otu; do echo $Otu; done <Input_File.txt

    S41_Folmer_Otu96;size=12;
    S78_Folmer_Otu15;size=538;
    S73_Leray_Otu52;size=6;
    S66_Leray_Otu93;size=6;
    S10_Folmer_Otu10;size=1612;
    ... All 769 variables

Again, this is exactly what I expect and is correct.

But, When I do either of the following commands, nothing is printed to the screen (if I leave off the write file/append action) or to the file I need to create.

$ cat Input_File.txt | while read Otu; do grep "$Otu" -A 10 Multi_BLAST_5814.txt >> Multi_BLAST_Subset.txt; done

$ cat Input_File.txt | while read Otu; do sed -n "/$Otu/,+10p" Multi_BLAST_5814.txt >> Multi_BLAST_Subset.txt; done

Sed hangs and never closes, leaving me at a blinking cursor. Grep finishes but also gives no output. I am at a loss as to why this is not working. Everything works inidividually, so I may be left with manually searching all 769 samples copy/paste.

Body:
Not sure whether you have already attempted it but try breaking the problem into smaller chunks. Simple example below :

$ cat Input_File.txt
one
two
three
$

$ cat file.txt
This is line one
This is line two
This is line three
This is another four
This is another five
This is another six
This is another seven
$

$ cat Input_File.txt | while read var ; do echo $var ; sed -n "/$var/,+1p" file.txt ; done
one
This is line one
This is line two
two
This is line two
This is line three
three
This is line three
This is another four
$


来源: stackexchange

问:
Cron server being delayed by multiple minutes using setTimeout()
I currently have a running 'cron' server. It is supposed to execute all the timed commands whom need to be run in the future.
This is the only thing that server does.

What works: Running the functions on a my own laptop, everything is executed in time.

What is broken: Running functions over multiple days on the server.

My code is all placed in an express project(Node) so calls can be made by other servers to add more 'crons'

Folder layout:

```<code>app.js
-api/
--crons/
---router.js
---functions.js
--.../
</code>```

In the functions file my functions to add a cron and execute it are kept.

```<code>const _ = require('lodash');
const Crons = [];
const moment = require('moment');

const functions = {

 addCron: (toExecute, dateTime, id, name) => {
    console.log('Cron', dateTime, name, id);
    const now = new Date().getTime();
    const then = new Date(dateTime).getTime();
    const diff = Math.max(then - now, 0);

    let cronJob;
    if (diff >= Math.pow(2, 31)) {
      if(functions.get(name)) {

      }
      cronJob = setTimeout(() => {
        functions.remove(name);
        functions.addCron(toExecute, dateTime, id, name);
      }, diff);
      Crons.push({
        name: name,
        job: cronJob
      });
    } else {
      if(functions.get(name)) {
        functions.remove(name);
      }
      cronJob = setTimeout(() => {
        console.log(`Started cron: ${name} at ${new Date()}`);
        toExecute(id);
        functions.remove(name);
      }, diff);
      Crons.push({
        name: name,
        job: cronJob
      });
    }

  }
};

module.exports = functions;
</code>```

Currently my logs when I run this locally show me that all functions are executed approximately 1 millisecond too late(which is fine).
And the logs on the live server show me that functions are beign run 7 minutes more late each day.

The logs

```<code>1|cronserver | 2017-06-30 18:00:07.195000000: Cron 2017-07-01T17:00:00.000Z YQkWN6BmX8eqzQHC9startCheck YQkWN6BmX8eqzQHC9
1|cronserver | 2017-06-30 18:00:07.195000000: Cron 2017-07-01T17:30:00.000Z 7c2yPyfjKDuujKQjhstartCheck 7c2yPyfjKDuujKQjh
1|cronserver | 2017-06-30 18:00:07.196000000: Cron 2017-07-02T17:00:00.000Z PQKoboRpSkWeTufSdstartCheck PQKoboRpSkWeTufSd
1|cronserver | 2017-06-30 18:00:07.196000000: Cron 2017-07-02T17:30:00.000Z yLFaAjACB9uNPd4YvstartCheck yLFaAjACB9uNPd4Yv
1|cronserver | 2017-06-30 18:00:07.199000000: Cron 2017-07-01T17:30:00.000Z YQkWN6BmX8eqzQHC9start YQkWN6BmX8eqzQHC9
1|cronserver | 2017-06-30 18:00:07.199000000: Cron 2017-07-01T18:00:00.000Z 7c2yPyfjKDuujKQjhstart 7c2yPyfjKDuujKQjh
1|cronserver | 2017-06-30 18:00:07.199000000: Cron 2017-07-02T17:30:00.000Z PQKoboRpSkWeTufSdstart PQKoboRpSkWeTufSd
1|cronserver | 2017-06-30 18:00:07.199000000: Cron 2017-07-02T18:00:00.000Z yLFaAjACB9uNPd4Yvstart yLFaAjACB9uNPd4Yv
1|cronserver | 2017-07-01 17:07:32.253000000: Started cron: YQkWN6BmX8eqzQHC9startCheck at Sat Jul 01 2017 17:07:32 GMT+0000 (UTC)
1|cronserver | 2017-07-01 17:37:33.160000000: Started cron: 7c2yPyfjKDuujKQjhstartCheck at Sat Jul 01 2017 17:37:33 GMT+0000 (UTC)
1|cronserver | 2017-07-01 17:37:33.161000000: Started cron: YQkWN6BmX8eqzQHC9start at Sat Jul 01 2017 17:37:33 GMT+0000 (UTC)
1|cronserver | 2017-07-01 18:07:34.070000000: Started cron: 7c2yPyfjKDuujKQjhstart at Sat Jul 01 2017 18:07:34 GMT+0000 (UTC)
1|cronserver | 2017-07-02 17:14:24.678000000: Started cron: PQKoboRpSkWeTufSdstartCheck at Sun Jul 02 2017 17:14:24 GMT+0000 (UTC)
1|cronserver | 2017-07-02 17:44:25.587000000: Started cron: yLFaAjACB9uNPd4YvstartCheck at Sun Jul 02 2017 17:44:25 GMT+0000 (UTC)
1|cronserver | 2017-07-02 17:44:25.588000000: Started cron: PQKoboRpSkWeTufSdstart at Sun Jul 02 2017 17:44:25 GMT+0000 (UTC)
1|cronserver | 2017-07-02 18:14:26.496000000: Started cron: yLFaAjACB9uNPd4Yvstart at Sun Jul 02 2017 18:14:26 GMT+0000 (UTC)
</code>```

The only thing this server does is running those functions. Any help would be greatly appreciated.

TL;DR My setTimout functions are running late. How can I solve this problem

答:
setTimeout only gets executed once, so I would not consider this a "cron job", but instead a job you want to execute once sometime in the future. Leaving that aside, setTimeout is not meant to be exact and there are multiple known reasons why your setTimeout timer executes at the wrong time. how setTimeout works is that it creates an event in the event queue and it's not until the queue frees up that it executes your code, as explained here. I could easily see a situation where if you have multiple setTimeout functions running it will cause delays in when they execute. Or more likely you have some other memory leak issue, that is just bubbling up here.

Regardless there are many other options for accomplishing what you are trying to do. I've used node-cron for actual cron jobs and its pretty sweet. There are also multiple ways for running single jobs on their own queues such as Kue or RabbitMQ.

ContentLicense: CC BY-SA 3.0

Body:
I currently have a running 'cron' server. It is supposed to execute all the timed commands whom need to be run in the future.
This is the only thing that server does.

What works: Running the functions on a my own laptop, everything is executed in time.

What is broken: Running functions over multiple days on the server.

My code is all placed in an express project(Node) so calls can be made by other servers to add more 'crons'

Folder layout:

app.js
-api/
--crons/
---router.js
---functions.js
--.../

In the functions file my functions to add a cron and execute it are kept.

const _ = require('lodash');
const Crons = [];
const moment = require('moment');

const functions = {

 addCron: (toExecute, dateTime, id, name) => {
    console.log('Cron', dateTime, name, id);
    const now = new Date().getTime();
    const then = new Date(dateTime).getTime();
    const diff = Math.max(then - now, 0);

    let cronJob;
    if (diff >= Math.pow(2, 31)) {
      if(functions.get(name)) {

      }
      cronJob = setTimeout(() => {
        functions.remove(name);
        functions.addCron(toExecute, dateTime, id, name);
      }, diff);
      Crons.push({
        name: name,
        job: cronJob
      });
    } else {
      if(functions.get(name)) {
        functions.remove(name);
      }
      cronJob = setTimeout(() => {
        console.log(`Started cron: ${name} at ${new Date()}`);
        toExecute(id);
        functions.remove(name);
      }, diff);
      Crons.push({
        name: name,
        job: cronJob
      });
    }

  }
};

module.exports = functions;

Currently my logs when I run this locally show me that all functions are executed approximately 1 millisecond too late(which is fine).
And the logs on the live server show me that functions are beign run 7 minutes more late each day.

The logs

1|cronserver | 2017-06-30 18:00:07.195000000: Cron 2017-07-01T17:00:00.000Z YQkWN6BmX8eqzQHC9startCheck YQkWN6BmX8eqzQHC9
1|cronserver | 2017-06-30 18:00:07.195000000: Cron 2017-07-01T17:30:00.000Z 7c2yPyfjKDuujKQjhstartCheck 7c2yPyfjKDuujKQjh
1|cronserver | 2017-06-30 18:00:07.196000000: Cron 2017-07-02T17:00:00.000Z PQKoboRpSkWeTufSdstartCheck PQKoboRpSkWeTufSd
1|cronserver | 2017-06-30 18:00:07.196000000: Cron 2017-07-02T17:30:00.000Z yLFaAjACB9uNPd4YvstartCheck yLFaAjACB9uNPd4Yv
1|cronserver | 2017-06-30 18:00:07.199000000: Cron 2017-07-01T17:30:00.000Z YQkWN6BmX8eqzQHC9start YQkWN6BmX8eqzQHC9
1|cronserver | 2017-06-30 18:00:07.199000000: Cron 2017-07-01T18:00:00.000Z 7c2yPyfjKDuujKQjhstart 7c2yPyfjKDuujKQjh
1|cronserver | 2017-06-30 18:00:07.199000000: Cron 2017-07-02T17:30:00.000Z PQKoboRpSkWeTufSdstart PQKoboRpSkWeTufSd
1|cronserver | 2017-06-30 18:00:07.199000000: Cron 2017-07-02T18:00:00.000Z yLFaAjACB9uNPd4Yvstart yLFaAjACB9uNPd4Yv
1|cronserver | 2017-07-01 17:07:32.253000000: Started cron: YQkWN6BmX8eqzQHC9startCheck at Sat Jul 01 2017 17:07:32 GMT+0000 (UTC)
1|cronserver | 2017-07-01 17:37:33.160000000: Started cron: 7c2yPyfjKDuujKQjhstartCheck at Sat Jul 01 2017 17:37:33 GMT+0000 (UTC)
1|cronserver | 2017-07-01 17:37:33.161000000: Started cron: YQkWN6BmX8eqzQHC9start at Sat Jul 01 2017 17:37:33 GMT+0000 (UTC)
1|cronserver | 2017-07-01 18:07:34.070000000: Started cron: 7c2yPyfjKDuujKQjhstart at Sat Jul 01 2017 18:07:34 GMT+0000 (UTC)
1|cronserver | 2017-07-02 17:14:24.678000000: Started cron: PQKoboRpSkWeTufSdstartCheck at Sun Jul 02 2017 17:14:24 GMT+0000 (UTC)
1|cronserver | 2017-07-02 17:44:25.587000000: Started cron: yLFaAjACB9uNPd4YvstartCheck at Sun Jul 02 2017 17:44:25 GMT+0000 (UTC)
1|cronserver | 2017-07-02 17:44:25.588000000: Started cron: PQKoboRpSkWeTufSdstart at Sun Jul 02 2017 17:44:25 GMT+0000 (UTC)
1|cronserver | 2017-07-02 18:14:26.496000000: Started cron: yLFaAjACB9uNPd4Yvstart at Sun Jul 02 2017 18:14:26 GMT+0000 (UTC)

The only thing this server does is running those functions. Any help would be greatly appreciated.

TL;DR My setTimout functions are running late. How can I solve this problem


问:
How to efficiently store and use Authentication in Ionic 3
I'm currently developing an Ionic (3.4) app for iOS/Android.
I'm not familiar with authentification processes or with applications.

After using HTTP request in a provider, I get my object, the user. But I have absolutely no idea how to store it or to deal with it. What are the good practices:

Am I suppose to just store the object in the provider and call in in every single page I have?

Am I suppose to store it as a sort of global object in the app?

Or am I suppose (as bellow) to transfer it as a Navigation variable from one page to another? (I guess that's not the right answer)

And finally, how will the application react on reloading/restarting: how to avoid people to fill the form again and again?

Here is my service:

```<code>@Injectable()
export class UserProvider {
    data = {};
    username: string;
    password: string;

    constructor(private _http: Http) {
        console.log('Hello UserProvider Provider');
    }

    getUser(username:string, password:string){

        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('username', username);
        urlSearchParams.append('password', password);
        let params = urlSearchParams.toString()

        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

        return this._http
        .post("http://api.minesdedouai.fr/user/login", params, {headers:headers} )
        .map(response => response.json())

    }

}
</code>```

I'm aware that a login request is supposed to use some token, but as I said, this is a small student's API, we're not pro and it's working.

And this is the method that uses the service, somewhere in a component (a page).

```<code>onLogin(form: NgForm) {
  if (form.valid) {
    this._userProvider.getUser(this.login.username, this.login.password)
    .subscribe((response) => {
      this.user = response;
      console.log("Authentification Success");
      this.navCtrl.push(TabsPage, {user: this.user});
    },
    (error) => {
      if (error.status===403){
        console.log("Wrong User")
      }
      else{
        console.log(error);
      }

    });
  }
}
</code>```

Thank you very much

答: If you want to persist the data durably, you can use ionic-storage : http://ionicframework.com/docs/storage/</p>

Body:
I'm currently developing an Ionic (3.4) app for iOS/Android.
I'm not familiar with authentification processes or with applications.

After using HTTP request in a provider, I get my object, the user. But I have absolutely no idea how to store it or to deal with it. What are the good practices:

Am I suppose to just store the object in the provider and call in in every single page I have?

Am I suppose to store it as a sort of global object in the app?

Or am I suppose (as bellow) to transfer it as a Navigation variable from one page to another? (I guess that's not the right answer)

And finally, how will the application react on reloading/restarting: how to avoid people to fill the form again and again?

Here is my service:

@Injectable()
export class UserProvider {
    data = {};
    username: string;
    password: string;

    constructor(private _http: Http) {
        console.log('Hello UserProvider Provider');
    }

    getUser(username:string, password:string){

        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('username', username);
        urlSearchParams.append('password', password);
        let params = urlSearchParams.toString()

        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

        return this._http
        .post("http://api.minesdedouai.fr/user/login", params, {headers:headers} )
        .map(response => response.json())

    }

}

I'm aware that a login request is supposed to use some token, but as I said, this is a small student's API, we're not pro and it's working.

And this is the method that uses the service, somewhere in a component (a page).

onLogin(form: NgForm) {
  if (form.valid) {
    this._userProvider.getUser(this.login.username, this.login.password)
    .subscribe((response) => {
      this.user = response;
      console.log("Authentification Success");
      this.navCtrl.push(TabsPage, {user: this.user});
    },
    (error) => {
      if (error.status===403){
        console.log("Wrong User")
      }
      else{
        console.log(error);
      }

    });
  }
}

Thank you very much


问:
Running Idlex 1.13 on Python 3.6.1
I wanted to get horizontal scrolling for the Python IDLE, and that led me to downloading idlex 1.13. Unzipping it went fine, but I wasn't able to run idlex.py

Every time I try, I get a message like this:

```<code>Unable to located "idlexlib".
Make sure it is located in the same directory as "idlexlib" or run setup.py
to install IdleX.
</code>```

```<code>python setup.py install --user
</code>```

I'm not sure if 1.13 just doesn't work on Python 3.6.1, or if I'm missing something like folder placement or if I should be running a different file.

I am using Windows 10 on a 64-bit operating system.

答:
It turns out that Idlex is not compatible with Python 3.6.0 and Python 3.6.1. It is, however, compatible with Python 3.5.3 32-bit and before. I had the same issue, until I found another post on StackOverflow:
Idlex 1.13 : Unable to located "idlexlib"</p>

Title: Running Idlex 1.13 on Python 3.6.1

Body:
I wanted to get horizontal scrolling for the Python IDLE, and that led me to downloading idlex 1.13. Unzipping it went fine, but I wasn't able to run idlex.py

Every time I try, I get a message like this:

Unable to located "idlexlib".
Make sure it is located in the same directory as "idlexlib" or run setup.py
to install IdleX.

python setup.py install --user

I'm not sure if 1.13 just doesn't work on Python 3.6.1, or if I'm missing something like folder placement or if I should be running a different file.

I am using Windows 10 on a 64-bit operating system.


答:
Solution was provided in one of the comments. Here's full solution plus some explanatory notes:

```<code>z <- cbind(XTS1, XTS2)
colnames(z) <- c("XTS1", "XTS2")
plot.zoo(z, plot.type = "single", col = 1:2)

legend("topright", inset=c(0,0), y.intersp = 1, legend = c("XTS1", "XTS2"),  lty = 1, bty = "n", col = c(1,2), cex = .5)

#cex: font size
#col: color
#bty: box around legends
#pch: symbol for legends (eg pch = c(1,2) => circle, triangle)
#lty: lines for legends (eg: lty = c(1,2) => solid, dash)
#y.intersp: vert interspacing (wout it legends may be far apart from each other)
#inset: for adjusting pos relative to eg "topright" (useful for xts as x coord in posixct format)
</code>```

Title: Legend for plot.zoo

Body:
The code below uses plot.zoo function to plot two variables (in xts format) on the same panel with different colors. I need to generate a legend for variables, showing variable name and associated color (to distinguish one from the other). I could not find any examples. How can this be achieved?

library(xts)

XTS1 <- structure(c(0.228369333217119, 0.228289904084397, 0.228447230658951, 0.228791576808238, 0.230747528582736, 0.231930951391005, 0.23218095279688, 0.232655671733178, 0.232780332790686, 0.232737419368931, 0.232662430253128, 0.232742568778743, 0.233149068581523, 0.233801848401534, 0.233772492034511, 0.234624948258082, 0.23483556890299, 0.234796321794256, 0.23604671397228, 0.236133475815726, 0.236165665606426, 0.236028593613328, 0.23653404809854, 0.236405363926972, 0.236289501951192, 0.23595748354442, 0.235856148573546, 0.236430492268466, 0.236509873541663, 0.236320952959145, 0.236324663117125, 0.236230849130264, 0.236256142711785, 0.236443262637705, 0.236474635240435, 0.236478152698594, 0.236446010557742, 0.236433585738065, 0.236318823709326, 0.236343709733496, 0.236353484497234, 0.236293047785645, 0.236299398621113, 0.23632602130195, 0.236415592036867, 0.23644183016732, 0.236410860513062, 0.236407738860613, 0.236488620207848, 0.236521885178186, 0.236524525976254, 0.236543261190294, 0.236545852954505, 0.236554043549182, 0.236558510962661, 0.236500857781485, 0.236456811183667, 0.236429475415132, 0.23640238691203, 0.236406136067832, 0.236417470442709, 0.236338677460503, 0.236460106937516, 0.236499259900878, 0.236586474063617, 0.236543271644404, 0.236513672740977, 0.236369639034221, 0.236362697687712, 0.236797843111073, 0.237345016578261, 0.23783668813706, 0.237923216897962, 0.238248672738757, 0.23827277432708, 0.238353796658431, 0.238432929684165, 0.238426329912625, 0.238345183139418, 0.238458037645863, 0.238479196815153, 0.238658887053061, 0.238465939669501, 0.238523649852224, 0.238510811967291, 0.238618072611544, 0.238704138338676, 0.238707447338575, 0.23996516914318, 0.239424589962875, 0.239561518553478, 0.239421256904757, 0.239816852104079, 0.239445276547969, 0.239609107802299, 0.240012364436436, 0.24002458654273, 0.240130590848021, 0.239736081751086, 0.239857898122929, 0.249230991607954, 0.239805445609213, 0.220333558462471, 0.210410600760776, 0.210378078591145, 0.240399004222477, 0.239804814201628, 0.240033060931268, 0.240089397482534, 0.240197041264942, 0.239940687229403, 0.239983219836939, 0.240022917769706, 0.240337756345468, 0.240638638953238, 0.240145924499555, 0.240402820873626, 0.240634154733532, 0.240611140050359, 0.240534865617682, 0.240951950137048, 0.241127845406939, 0.241125700147753, 0.241126235785769, 0.24107570794763, 0.241088551839332, 0.241092988182315, 0.241086472173767, 0.241083390403282, 0.241091888348645, 0.241083158087253, 0.241064751836135, 0.241064210485496, 0.241091022867438, 0.240953810187424, 0.240481188224338, 0.240621074487305, 0.240541023392083, 0.240396295416436, 0.240434646218793, 0.240610526667198, 0.240808207542551, 0.240631718256586, 0.24064699063015, 0.24068954416015, 0.240711128194114, 0.240723728654195, 0.240775499747258, 0.24076580240029, 0.240772143433637, 0.240793451595961, 0.240796153528682, 0.240819395590463, 0.240807928484687, 0.241070198676456, 0.241015031342511, 0.240992277437459, 0.241067975400449, 0.241065024303712, 0.241163875314065, 0.241210015023487, 0.24111104460957, 0.241143389170502, 0.241126406233165, 0.241236385470386, 0.241216017627354, 0.241242224901225, 0.241204855537627, 0.241161113202215, 0.241188009018793, 0.241155655393916, 0.241104796660299, 0.241229168370518, 0.241187912977691, 0.241205571324508, 0.241275488693839, 0.241201890756208, 0.241062150030789, 0.241056667454678, 0.241020382598737, 0.241011174472952, 0.241075153997628, 0.240860609085096, 0.241671867834864, 0.242222875244792, 0.242105277990476, 0.242789197437053, 0.24262651942461, 0.242835209836078, 0.242065722773181, 0.242128191776504, 0.241866750527435, 0.242222755781399, 0.242405920724485, 0.242704642796114, 0.243681731065406, 0.243823985845211, 0.244075416453679, 0.244168166839201), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(
  formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000, 1413990900, 1413991800, 1413992700, 1413993600, 1413994500, 1413995400, 1413996300, 1413997200, 1413998100, 1413999000, 1413999900, 1414000800, 1414001700, 1414002600, 1414003500, 1414004400, 1414005300, 1414006200, 1414007100, 1414008000, 1414009800, 1414010700, 1414011600, 1414015200, 1414016100, 1414017000, 1414017900, 1414018800, 1414019700, 1414020600, 1414021500, 1414022400, 1414023300, 1414024200, 1414025100, 1414026000, 1414026900, 1414027800, 1414028700, 1414029600, 1414030500, 1414031400, 1414032300, 1414033200, 1414034100, 1414035000, 1414035900, 1414036800, 1414037700, 1414038600, 1414039500, 1414040400, 1414041300, 1414042200, 1414043100, 1414044000, 1414044900, 1414045800, 1414046700, 1414047600, 1414048500, 1414049400, 1414050300, 1414051200, 1414052100, 1414053000, 1414053900, 1414054800, 1414055700, 1414056600, 1414057500, 1414058400, 1414059300, 1414060200, 1414061100, 1414062000, 1414062900, 1414063800, 1414064700, 1414065600, 1414066500, 1414067400, 1414068300, 1414069200, 1414070100, 1414071000, 1414071900, 1414072800, 1414073700, 1414074600, 1414075500, 1414076400, 1414077300, 1414078200, 1414079100, 1414080000, 1414080900, 1414081800, 1414082700, 1414083600, 1414084500, 1414085400, 1414086300, 1414087200, 1414088100, 1414089000, 1414089900, 1414090800, 1414091700, 1414092600, 1414093500, 1414094400, 1414096200, 1414097100, 1414098000, 1414101600, 1414102500, 1414103400, 1414104300, 1414105200, 1414106100, 1414107000, 1414107900, 1414108800, 1414109700, 1414110600, 1414111500, 1414112400, 1414113300, 1414114200, 1414115100, 1414116000, 1414116900, 1414117800, 1414118700, 1414119600, 1414120500, 1414121400, 1414122300, 1414123200, 1414124100, 1414125000, 1414125900, 1414126800, 1414127700, 1414128600, 1414129500, 1414130400, 1414131300, 1414132200, 1414133100, 1414134000, 1414134900, 1414135800, 1414136700, 1414137600, 1414138500, 1414139400, 1414140300, 1414141200, 1414142100, 1414143000, 1414143900, 1414144800, 1414145700, 1414146600, 1414147500, 1414148400, 1414149300, 1414150200, 1414151100, 1414152000, 1414152900, 1414153800, 1414154700, 1414155600, 1414156500, 1414157400, 1414158300, 1414159200, 1414160100, 1414161000, 1414161900, 1414162800, 1414163700, 1414164600, 1414165500, 1414166400, 1414167300), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(199L, 1L))

XTS2 <- structure(c(0.238369333217119, 0.238289904084397, 0.238447230658951, 0.238791576808238, 0.230747528582736, 0.231930951391005, 0.23218095279688, 0.232655671733178, 0.232780332790686, 0.232737419368931, 0.232662430253128, 0.232742568778743, 0.233149068581523, 0.233801848401534, 0.233772492034511, 0.234624948258082, 0.23483556890299, 0.234796321794256, 0.23604671397238, 0.236133475815726, 0.236165665606426, 0.236028593613328, 0.23653404809854, 0.236405363926972, 0.236289501951192, 0.23595748354442, 0.235856148573546, 0.236430492368466, 0.236509873541663, 0.236320952959145, 0.236324663117125, 0.236230849130264, 0.236256142711785, 0.236443262637705, 0.236474635240435, 0.236478152698594, 0.236446010557742, 0.236433585738065, 0.236318823709326, 0.236343709733496, 0.236353484497234, 0.236293047785645, 0.236299398621113, 0.23632602130195, 0.236415592036867, 0.23644183016732, 0.236410860513062, 0.236407738860613, 0.236488620207848, 0.236521885178186, 0.236524525976254, 0.236543261190294, 0.236545852954505, 0.236554043549182, 0.236558510962661, 0.236500857781485, 0.236456811183667, 0.236429475415132, 0.23640238691203, 0.236406136067832, 0.236417470442709, 0.236338677460503, 0.236460106937516, 0.236499259900878, 0.236586474063617, 0.236543271644404, 0.216513672740977, 0.216369639034221, 0.216362697687712, 0.216797843111073, 0.217345016578261, 0.21783668813706, 0.217921216897962, 0.218248672738757, 0.21827277432708, 0.218353796658431, 0.218432929684165, 0.218426329912625, 0.218345183139418, 0.218458037645863, 0.218479196815153, 0.238658887053061, 0.238465939669501, 0.238523649852224, 0.238510811967291, 0.238618072611544, 0.238704138338676, 0.238707447338575, 0.23996516914318, 0.239424589962875, 0.239561518553478, 0.239421256904757, 0.239816852104079, 0.239445276547969, 0.239609107802299, 0.240012364436436, 0.24002458654273, 0.240130590848021, 0.239736081751086, 0.239857898122929, 0.239230991607954, 0.239805445609213, 0.240333558462471, 0.240410600760776, 0.240378078591145, 0.240399004222477, 0.239804814201628, 0.240033060931268, 0.240089397482534, 0.240197041264942, 0.239940687229403, 0.239983219836939, 0.240022917769706, 0.240337756345468, 0.240638638953238, 0.240145924499555, 0.240402820873626, 0.240634154733532, 0.240611140050359, 0.240534865617682, 0.240951950137048, 0.241127845406939, 0.241125700147753, 0.241126235785769, 0.24107570794763, 0.241088551839332, 0.241092988182315, 0.241086472173767, 0.241083390403282, 0.241091888348645, 0.241083158087253, 0.241064751836135, 0.241064210485496, 0.241091022867438, 0.240953810187424, 0.240481188224338, 0.240621074487305, 0.240541023392083, 0.240396295416436, 0.240434646218793, 0.240610526667198, 0.240808207542551, 0.240631718256586, 0.24064699063015, 0.24068954416015, 0.240711128194114, 0.240723728654195, 0.240775499747258, 0.24076580240029, 0.240772143433637, 0.240793451595961, 0.240796153528682, 0.240819395590463, 0.240807928484687, 0.241070198676456, 0.241015031342511, 0.240992277437459, 0.241067975400449, 0.241065024303712, 0.241163875314065, 0.241210015023487, 0.24111104460957, 0.241143389170502, 0.241126406233165, 0.241236385470386, 0.241216017627354, 0.241242224901225, 0.241204855537627, 0.241161113202215, 0.241188009018793, 0.241155655393916, 0.241104796660299, 0.241229168370518, 0.241187912977691, 0.241205571324508, 0.241275488693839, 0.241201890756208, 0.241062150030789, 0.241056667454678, 0.241020382598737, 0.241011174472952, 0.241075153997628, 0.240860609085096, 0.241671867834864, 0.242222875244792, 0.242105277990476, 0.242789197437053, 0.24262651942461, 0.242835209836078, 0.242065722773181, 0.242128191776504, 0.241866750527435, 0.242222755781399, 0.242405920724485, 0.242704642796114, 0.243681731065406, 0.243823985845211, 0.244075416453679, 0.244168166839201), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(
  formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000, 1413990900, 1413991800, 1413992700, 1413993600, 1413994500, 1413995400, 1413996300, 1413997200, 1413998100, 1413999000, 1413999900, 1414000800, 1414001700, 1414002600, 1414003500, 1414004400, 1414005300, 1414006200, 1414007100, 1414008000, 1414009800, 1414010700, 1414011600, 1414015200, 1414016100, 1414017000, 1414017900, 1414018800, 1414019700, 1414020600, 1414021500, 1414022400, 1414023300, 1414024200, 1414025100, 1414026000, 1414026900, 1414027800, 1414028700, 1414029600, 1414030500, 1414031400, 1414032300, 1414033200, 1414034100, 1414035000, 1414035900, 1414036800, 1414037700, 1414038600, 1414039500, 1414040400, 1414041300, 1414042200, 1414043100, 1414044000, 1414044900, 1414045800, 1414046700, 1414047600, 1414048500, 1414049400, 1414050300, 1414051200, 1414052100, 1414053000, 1414053900, 1414054800, 1414055700, 1414056600, 1414057500, 1414058400, 1414059300, 1414060200, 1414061100, 1414062000, 1414062900, 1414063800, 1414064700, 1414065600, 1414066500, 1414067400, 1414068300, 1414069200, 1414070100, 1414071000, 1414071900, 1414072800, 1414073700, 1414074600, 1414075500, 1414076400, 1414077300, 1414078200, 1414079100, 1414080000, 1414080900, 1414081800, 1414082700, 1414083600, 1414084500, 1414085400, 1414086300, 1414087200, 1414088100, 1414089000, 1414089900, 1414090800, 1414091700, 1414092600, 1414093500, 1414094400, 1414096200, 1414097100, 1414098000, 1414101600, 1414102500, 1414103400, 1414104300, 1414105200, 1414106100, 1414107000, 1414107900, 1414108800, 1414109700, 1414110600, 1414111500, 1414112400, 1414113300, 1414114200, 1414115100, 1414116000, 1414116900, 1414117800, 1414118700, 1414119600, 1414120500, 1414121400, 1414122300, 1414123200, 1414124100, 1414125000, 1414125900, 1414126800, 1414127700, 1414128600, 1414129500, 1414130400, 1414131300, 1414132200, 1414133100, 1414134000, 1414134900, 1414135800, 1414136700, 1414137600, 1414138500, 1414139400, 1414140300, 1414141200, 1414142100, 1414143000, 1414143900, 1414144800, 1414145700, 1414146600, 1414147500, 1414148400, 1414149300, 1414150200, 1414151100, 1414152000, 1414152900, 1414153800, 1414154700, 1414155600, 1414156500, 1414157400, 1414158300, 1414159200, 1414160100, 1414161000, 1414161900, 1414162800, 1414163700, 1414164600, 1414165500, 1414166400, 1414167300), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(199L, 1L))

z <- cbind(XTS1, XTS2)
colnames(z) <- c("XTS1", "XTS2")
plot.zoo(z, plot.type = "single", col = 1:2, xy.labels = "text")

Please note I need to use plot.zoo rather than plot.

Body:
Solution was provided in one of the comments. Here's full solution plus some explanatory notes:

z <- cbind(XTS1, XTS2)
colnames(z) <- c("XTS1", "XTS2")
plot.zoo(z, plot.type = "single", col = 1:2)

legend("topright", inset=c(0,0), y.intersp = 1, legend = c("XTS1", "XTS2"),  lty = 1, bty = "n", col = c(1,2), cex = .5)

#cex: font size
#col: color
#bty: box around legends
#pch: symbol for legends (eg pch = c(1,2) => circle, triangle)
#lty: lines for legends (eg: lty = c(1,2) => solid, dash)
#y.intersp: vert interspacing (wout it legends may be far apart from each other)
#inset: for adjusting pos relative to eg "topright" (useful for xts as x coord in posixct format)


问:
How to serve up a JSON response using Go?
Question: Currently I'm printing out my response in the func Index
like this fmt.Fprintf(w, string(response)) however, how can I send JSON properly in the request so that it maybe consumed by a view?

```<code>package main

import (
    "fmt"
    "github.com/julienschmidt/httprouter"
    "net/http"
    "log"
    "encoding/json"
)

type Payload struct {
    Stuff Data
}
type Data struct {
    Fruit Fruits
    Veggies Vegetables
}
type Fruits map[string]int
type Vegetables map[string]int

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    response, err := getJsonResponse();
    if err != nil {
        panic(err)
    }
    fmt.Fprintf(w, string(response))
}

func main() {
    router := httprouter.New()
    router.GET("/", Index)
    log.Fatal(http.ListenAndServe(":8080", router))
}

func getJsonResponse()([]byte, error) {
    fruits := make(map[string]int)
    fruits["Apples"] = 25
    fruits["Oranges"] = 10

    vegetables := make(map[string]int)
    vegetables["Carrats"] = 10
    vegetables["Beets"] = 0

    d := Data{fruits, vegetables}
    p := Payload{d}

    return json.MarshalIndent(p, "", "  ")
}
</code>```

答:
In gobuffalo.io framework I got it to work like this:

```<code>// say we are in some resource Show action
// some code is omitted
user := &models.User{}
if c.Request().Header.Get("Content-type") == "application/json" {
    return c.Render(200, r.JSON(user))
} else {
    // Make user available inside the html template
    c.Set("user", user)
    return c.Render(200, r.HTML("users/show.html"))
}
</code>```

and then when I want to get JSON response for that resource I have to set "Content-type" to "application/json" and it works.

I think Rails has more convenient way to handle multiple response types, I didn't see the same in gobuffalo so far.

Body:
Question: Currently I'm printing out my response in the func Index
like this fmt.Fprintf(w, string(response)) however, how can I send JSON properly in the request so that it maybe consumed by a view?

package main

import (
    "fmt"
    "github.com/julienschmidt/httprouter"
    "net/http"
    "log"
    "encoding/json"
)

type Payload struct {
    Stuff Data
}
type Data struct {
    Fruit Fruits
    Veggies Vegetables
}
type Fruits map[string]int
type Vegetables map[string]int

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    response, err := getJsonResponse();
    if err != nil {
        panic(err)
    }
    fmt.Fprintf(w, string(response))
}

func main() {
    router := httprouter.New()
    router.GET("/", Index)
    log.Fatal(http.ListenAndServe(":8080", router))
}

func getJsonResponse()([]byte, error) {
    fruits := make(map[string]int)
    fruits["Apples"] = 25
    fruits["Oranges"] = 10

    vegetables := make(map[string]int)
    vegetables["Carrats"] = 10
    vegetables["Beets"] = 0

    d := Data{fruits, vegetables}
    p := Payload{d}

    return json.MarshalIndent(p, "", "  ")
}

Body:
In gobuffalo.io framework I got it to work like this:

// say we are in some resource Show action
// some code is omitted
user := &models.User{}
if c.Request().Header.Get("Content-type") == "application/json" {
    return c.Render(200, r.JSON(user))
} else {
    // Make user available inside the html template
    c.Set("user", user)
    return c.Render(200, r.HTML("users/show.html"))
}

and then when I want to get JSON response for that resource I have to set "Content-type" to "application/json" and it works.

I think Rails has more convenient way to handle multiple response types, I didn't see the same in gobuffalo so far.


问:
Nicely formatted numbers in SQL Server
How do I do the following in Microsoft SQL Server 2005?

```<code>DECLARE @PCT Decimal(4,1)
SET @PCT=3.1
SELECT
WHEN @PCT = CAST(@PCT AS Int) THEN CAST(CAST(@PCT AS Int) AS Varchar)
ELSE CAST(@PCT AS Varchar) END AS newPct
</code>```

I'm trying to drop the .0 if the percent ends in a whole number.

答:
What you have will work if you add the CASE keyword</p>

```<code>DECLARE @PCT Decimal(4,1)
SET @PCT=3.1
SELECT
    CASE WHEN @PCT = CAST(@PCT AS Int) THEN CAST(CAST(@PCT AS Int) AS Varchar)
    ELSE CAST(@PCT AS Varchar) END AS newPct
</code>```

ContentLicense: CC BY-SA 2.5

Title: Nicely formatted numbers in SQL Server

Body:
How do I do the following in Microsoft SQL Server 2005?

DECLARE @PCT Decimal(4,1)
SET @PCT=3.1
SELECT
WHEN @PCT = CAST(@PCT AS Int) THEN CAST(CAST(@PCT AS Int) AS Varchar)
ELSE CAST(@PCT AS Varchar) END AS newPct

I'm trying to drop the .0 if the percent ends in a whole number.

Body:
What you have will work if you add the CASE keyword

DECLARE @PCT Decimal(4,1)
SET @PCT=3.1
SELECT
    CASE WHEN @PCT = CAST(@PCT AS Int) THEN CAST(CAST(@PCT AS Int) AS Varchar)
    ELSE CAST(@PCT AS Varchar) END AS newPct


问:
Sort file by key with awk or perl like a join without presorting
I want to join two tab separated files, but they are in a different order. I know that it is doable with awk, but I don't know how. Here is the equivalent toy python code (python is too memory inefficient for this task without crazy workarounds):

```<code>import pandas as pd
from random import shuffle

a = ['bar','qux','baz','foo','spam']
df = pd.DataFrame({'nam':a,'asc':[1,2,3,4,5],'desc':[5,4,3,2,1]})

shuffle(a)
print(a)

dex = pd.DataFrame({'dex' : a})
df_b = pd.DataFrame({'VAL1' :[0,1,2,3,4,5,6]})

pd.merge(dex, df,left_on='dex',right_on='nam')[['asc','desc','nam']]
</code>```

I have two files:
For file one, column 2 holds the identifier for each row, there 5 columns I don't need, and then there are about 3 million columns of data.

For file two, There are 12 columns, with the second column containing the same identifiers in a different order, along with additional ids.

I want to sort file one to have the same identifiers and order as file two, with the other columns appropriately rearranged.

File one is potentially multiple gigabytes.

Is this easier with awk and/or other GNU tools, or should I use perl?

答:
The important thing is not to split any more than necessary. If you have enough memory, putting the smaller file in a hash, and then reading through the second file ought to work.

Consider the following example (note the run time of this script includes the time it takes to create sample data):

```<code>#!/usr/bin/env perl

use strict;
use warnings;

# This is a string containing 10 lines corresponding to your "file one"
# Second column has the record ID
# Normally, you'd be reading this from a file

my $big_file = join "\n",
    map join("\t", 'x', $_, ('x') x 3_000_000),
    1 .. 10
;

# This is a string containing 10 lines corresponding to your "file two"
# Second column has the record ID

my $small_file = join "\n",
    map join("\t", 'y', $_, ('y') x 10),
    1 .. 10
;

# You would normally pass file names as arguments

join_with_big_file(
    \$small_file,
    \$big_file,
);

sub join_with_big_file {
    my $small_records = load_small_file(shift);
    my $big_file = shift;

    open my $fh, '<', $big_file
        or die "Cannot open '$big_file': $!";

    while (my $line = <$fh>) {
        chomp $line;
        my ($first, $id, $rest) = split /\t/, $line, 3;
        print join("\t", $first, $id, $rest, $small_records->{$id}), "\n";
    }

    return;
}

sub load_small_file {
    my $file = shift;
    my %records;

    open my $fh, '<', $file
        or die "Cannot open '$file' for reading: $!";

    while (my $line = <$fh>) {
        # limit the split
        my ($first, $id, $rest) = split /\t/, $line, 3;
        # I drop the id field here so it is not duplicated in the joined
        # file. If that is not a problem, $records{$id} = $line
        # would be better.
        $records{$id} = join("\t", $first, $rest);
    }

    return \%records;
}
</code>```

Body:
I want to join two tab separated files, but they are in a different order. I know that it is doable with awk, but I don't know how. Here is the equivalent toy python code (python is too memory inefficient for this task without crazy workarounds):

import pandas as pd
from random import shuffle

a = ['bar','qux','baz','foo','spam']
df = pd.DataFrame({'nam':a,'asc':[1,2,3,4,5],'desc':[5,4,3,2,1]})

shuffle(a)
print(a)

dex = pd.DataFrame({'dex' : a})
df_b = pd.DataFrame({'VAL1' :[0,1,2,3,4,5,6]})

pd.merge(dex, df,left_on='dex',right_on='nam')[['asc','desc','nam']]

I have two files:
For file one, column 2 holds the identifier for each row, there 5 columns I don't need, and then there are about 3 million columns of data.

For file two, There are 12 columns, with the second column containing the same identifiers in a different order, along with additional ids.

I want to sort file one to have the same identifiers and order as file two, with the other columns appropriately rearranged.

File one is potentially multiple gigabytes.

Is this easier with awk and/or other GNU tools, or should I use perl?

Body:
The important thing is not to split any more than necessary. If you have enough memory, putting the smaller file in a hash, and then reading through the second file ought to work.

Consider the following example (note the run time of this script includes the time it takes to create sample data):

#!/usr/bin/env perl

use strict;
use warnings;

# This is a string containing 10 lines corresponding to your "file one"
# Second column has the record ID
# Normally, you'd be reading this from a file

my $big_file = join "\n",
    map join("\t", 'x', $_, ('x') x 3_000_000),
    1 .. 10
;

# This is a string containing 10 lines corresponding to your "file two"
# Second column has the record ID

my $small_file = join "\n",
    map join("\t", 'y', $_, ('y') x 10),
    1 .. 10
;

# You would normally pass file names as arguments

join_with_big_file(
    \$small_file,
    \$big_file,
);

sub join_with_big_file {
    my $small_records = load_small_file(shift);
    my $big_file = shift;

    open my $fh, '<', $big_file
        or die "Cannot open '$big_file': $!";

    while (my $line = <$fh>) {
        chomp $line;
        my ($first, $id, $rest) = split /\t/, $line, 3;
        print join("\t", $first, $id, $rest, $small_records->{$id}), "\n";
    }

    return;
}

sub load_small_file {
    my $file = shift;
    my %records;

    open my $fh, '<', $file
        or die "Cannot open '$file' for reading: $!";

    while (my $line = <$fh>) {
        # limit the split
        my ($first, $id, $rest) = split /\t/, $line, 3;
        # I drop the id field here so it is not duplicated in the joined
        # file. If that is not a problem, $records{$id} = $line
        # would be better.
        $records{$id} = join("\t", $first, $rest);
    }

    return \%records;
}


问:
Winform : How to show error icon on empty fields?
I have a VB.Net application with forms with some bound fields.

When I type some wrong data in fields, the ErrorProvider shows a red ico automatically.

Is there any way that it shows the same icon when some required fields are empty ?

Here is the binding code of my controls :

```<code>Dim MyDataTable as datatable = GetDT
Me.Control.DataBindings.Add(New Binding(Me.BindingProperty, MyDataTable, FieldName, True, DataSourceUpdateMode.OnValidation))

Function GetDT() As DataTable
    Dim DT As New DataTable

    Dim i As Integer = 0
    DT.Columns.Add(New DataColumn("C1", i.GetType))
    DT.Columns(0).AllowDBNull = False

    Dim R As DataRow = DT.NewRow
    R.Item(0) = 15
    DT.Rows.Add(R)

    Return DT
End Function
</code>```

The method ErrorProvider.SetError is not an option since the controls are created in a separate process and do not have access to the ErrorProvider.

Thanks.

答:
You can use a custom class in your case:

```<code>Public Class customdatatable
        Implements IDXDataErrorInfo

        Private _value As String
        Public Sub New()
            MyBase.New()
        End Sub
        Public Property C1() As String
            Get
                Return _value
            End Get
            Set(ByVal value As String)
                _value = value
            End Set
        End Property

        Public Sub GetPropertyError(ByVal name As String, ByVal errorinfo As ErrorInfo) _
          Implements IDXDataErrorInfo.GetPropertyError
            If (name = "C1" And C1 = "") Then
                errorinfo.ErrorText = String.Format("Empty value")
            End If
        End Sub

        Public Sub GetError(ByVal errorinfo As ErrorInfo) Implements IDXDataErrorInfo.GetError
        End Sub
    End Class
</code>```

then apply it to your form:

```<code>Dim DT = New customdatatable With {.C1 = 5} ''GetDT()
TextEdit1.DataBindings.Add(New Binding("EditValue", DT ,"C1", True))
DxErrorProvider1.DataSource = DT
</code>```

If you don't care to lose focus control on your textfield just use this in your main.

```<code>Dim field2 = GetDT()
TextEdit1.DataBindings.Add(New Binding("EditValue", field2,"C1", True))
DxErrorProvider1.DataSource = field2
</code>```

Body:
I have a VB.Net application with forms with some bound fields.

When I type some wrong data in fields, the ErrorProvider shows a red ico automatically.

Is there any way that it shows the same icon when some required fields are empty ?

Here is the binding code of my controls :

Dim MyDataTable as datatable = GetDT
Me.Control.DataBindings.Add(New Binding(Me.BindingProperty, MyDataTable, FieldName, True, DataSourceUpdateMode.OnValidation))

Function GetDT() As DataTable
    Dim DT As New DataTable

    Dim i As Integer = 0
    DT.Columns.Add(New DataColumn("C1", i.GetType))
    DT.Columns(0).AllowDBNull = False

    Dim R As DataRow = DT.NewRow
    R.Item(0) = 15
    DT.Rows.Add(R)

    Return DT
End Function

The method ErrorProvider.SetError is not an option since the controls are created in a separate process and do not have access to the ErrorProvider.

Thanks.

Body:
You can use a custom class in your case:

Public Class customdatatable
        Implements IDXDataErrorInfo

        Private _value As String
        Public Sub New()
            MyBase.New()
        End Sub
        Public Property C1() As String
            Get
                Return _value
            End Get
            Set(ByVal value As String)
                _value = value
            End Set
        End Property

        Public Sub GetPropertyError(ByVal name As String, ByVal errorinfo As ErrorInfo) _
          Implements IDXDataErrorInfo.GetPropertyError
            If (name = "C1" And C1 = "") Then
                errorinfo.ErrorText = String.Format("Empty value")
            End If
        End Sub

        Public Sub GetError(ByVal errorinfo As ErrorInfo) Implements IDXDataErrorInfo.GetError
        End Sub
    End Class

then apply it to your form:

Dim DT = New customdatatable With {.C1 = 5} ''GetDT()
TextEdit1.DataBindings.Add(New Binding("EditValue", DT ,"C1", True))
DxErrorProvider1.DataSource = DT

If you don't care to lose focus control on your textfield just use this in your main.

Dim field2 = GetDT()
TextEdit1.DataBindings.Add(New Binding("EditValue", field2,"C1", True))
DxErrorProvider1.DataSource = field2


问:
Can't Sign up with firebase
I am trying to create a sign up form with firebase and login as well, I have tried so many things but it won't work. I keep getting this error when I click the signup button which calls the method auth.createUserWithEmailAndPassword(email, pass).

A network error (such as timeout, interrupted connection or unreachable host) has occurred.

Below here is part of my HTML

```<code><div class="col l7" id="signup">
      <h4>Signup</h4>
      <div class="form card">
        <br>
        <div class="switch">
          <label>
                Student
                <input name="student_" id="student_" type="checkbox">
                <span class="lever"></span>
                Staff
              </label>
        </div>
        <div class="container">
          <input type="text" placeholder="Name" id="signup_fullname">
          <!--student/staff-->
          <input type="text" placeholder="Matric Number/Staff no." id="signup_matric">
          <input type="email" placeholder="Email" id="signup_email">
          <div class="input-field col s12">
            <select id="signup_dept">
                  <option value="" disabled selected>Select your department</option>
                  <option value="ics">ICS</option>
                  <option value="masscomm">Mass Comm.</option>
                  <option value="lis">Library Science</option>
                  <option value="tcs">Telecomm Science</option>
                  <option value="csc">Computer Science</option>
                </select>
          </div>
          <div class="input-field col s12">
            <select id="signup_level">
                  <option value="" disabled selected>Select your Level</option>
                  <option value="100">100 Level</option>
                  <option value="200">200 Level</option>
                  <option value="300">300 Level</option>
                  <option value="400">400 Level</option>
                  <option value="500">500 Level</option>
                </select>
          </div>
          <div class="input-field col s12">
            <select id="signup_religion">
                  <option value="" disabled selected>Select your religion</option>
                  <option value="1">Islam</option>
                  <option value="2">Christianity</option>
                </select>
          </div>
          <input type="password" placeholder="password" id="signup_password">
          <!--<input type="password" placeholder="Confirm password" id="signup_confirm_password">-->
          <button class="btn-large second-color" id="btnSignUp">signup</button></a>
        </div>
      </div>
      <br>
    </div>
</code>```

and my JS code

```<code>readystatemode = false;
(function () {
  var config = {
    apiKey: "<my API key>",
    authDomain: "<my auth domain>",
    databaseURL: "<my database url>",
    storageBucket: "<my storage bucket url>",
  };
  firebase.initializeApp(config);

  // Get Elements
  var student_ = document.getElementById('student_'); // check whether is a student or staff; expect on or off
  var student__;
  if (student_.value == "on") {
    student__ = "student";
  } else {
    student__ = "staff";
  }
  var signup_fullname = document.getElementById('signup_fullname');
  var signup_matric = document.getElementById('signup_matric');
  var signup_email = document.getElementById('signup_email');
  var signup_dept = document.getElementById('signup_dept');
  var signup_level = document.getElementById('signup_level');
  var signup_religion = document.getElementById('signup_religion');
  var signup_password = document.getElementById('signup_password');
  var login_email = document.getElementById('login_email');
  var login_password = document.getElementById('login_password');
  // buttons
  var btnLogin = document.getElementById("btnLogin");
  var btnSignUp = document.getElementById("btnSignUp");

  // signup event
  btnSignUp.addEventListener('click', e => {
    // Get Email and pass
    //TODO: check for real emails
    console.log("just clicked the signup button");

    var email = signup_email.value;
    var pass = signup_password.value;
    var auth = firebase.auth();
    // sign up
    const promise = auth.createUserWithEmailAndPassword(email, pass);
    promise
      .catch(e => console.log(e.message));

    if (auth.currentUser != null) {
      auth.currentUser.updateProfile({
        displayName: signup_fullname,
        userCategory: student__,
        matric: signup_matric,
        department: signup_dept,
        level: signup_level,
        religion: signup_religion
      }).then(function () {
        console.log("update successful");
        window.readystatemode = true;
      }, function (error) {
        console.log("update failed");
      });
    }
  });

  firebase.auth().onAuthStateChanged(firebaseUser => {
    if (firebaseUser && window.readystatemode) {
      console.log(firebaseUser);
      btnLogout.classList.remove('hide');
      window.location('./dashboard.html');
    } else {
      console.log("not logged in");
      btnLogout.classList.add('hide');
    }
  });

})();
</code>```

答: If you are using Cordova (which I am not sure if you are or not, but some answers imply that you may be), including the cordova-plugin-network-information corrected this issue for me. I confirmed that the 'navigator.onLine' was occasionally 'false', which I believe was causing Firebase to think there was an issue. Once I added the cordova-plugin-network-information to my project, the problem went away. I didn't dig deep into why, but I suspect this plugin has a better wrapper around the navigator which may be giving Firebase better information. I did confirm this problem came back after removing the plugin, but re-applying it fixes it. I will update this if I dig deeper. I hope this helps.</p>

Title: Can't Sign up with firebase

Body:
I am trying to create a sign up form with firebase and login as well, I have tried so many things but it won't work. I keep getting this error when I click the signup button which calls the method auth.createUserWithEmailAndPassword(email, pass).

A network error (such as timeout, interrupted connection or unreachable host) has occurred.

Below here is part of my HTML

Signup

                Student
                <input name="student_" id="student_" type="checkbox">

                Staff

          <input type="text" placeholder="Name" id="signup_fullname">

          <input type="text" placeholder="Matric Number/Staff no." id="signup_matric">
          <input type="email" placeholder="Email" id="signup_email">

            <select id="signup_dept">
                  <option value="" disabled selected>Select your department</option>
                  <option value="ics">ICS</option>
                  <option value="masscomm">Mass Comm.</option>
                  <option value="lis">Library Science</option>
                  <option value="tcs">Telecomm Science</option>
                  <option value="csc">Computer Science</option>
                </select>

            <select id="signup_level">
                  <option value="" disabled selected>Select your Level</option>
                  <option value="100">100 Level</option>
                  <option value="200">200 Level</option>
                  <option value="300">300 Level</option>
                  <option value="400">400 Level</option>
                  <option value="500">500 Level</option>
                </select>

            <select id="signup_religion">
                  <option value="" disabled selected>Select your religion</option>
                  <option value="1">Islam</option>
                  <option value="2">Christianity</option>
                </select>

          <input type="password" placeholder="password" id="signup_password">

          <button class="btn-large second-color" id="btnSignUp">signup</button>

and my JS code

readystatemode = false;
(function () {
  var config = {
    apiKey: "<my API key>",
    authDomain: "<my auth domain>",
    databaseURL: "<my database url>",
    storageBucket: "<my storage bucket url>",
  };
  firebase.initializeApp(config);

  // Get Elements
  var student_ = document.getElementById('student_'); // check whether is a student or staff; expect on or off
  var student__;
  if (student_.value == "on") {
    student__ = "student";
  } else {
    student__ = "staff";
  }
  var signup_fullname = document.getElementById('signup_fullname');
  var signup_matric = document.getElementById('signup_matric');
  var signup_email = document.getElementById('signup_email');
  var signup_dept = document.getElementById('signup_dept');
  var signup_level = document.getElementById('signup_level');
  var signup_religion = document.getElementById('signup_religion');
  var signup_password = document.getElementById('signup_password');
  var login_email = document.getElementById('login_email');
  var login_password = document.getElementById('login_password');
  // buttons
  var btnLogin = document.getElementById("btnLogin");
  var btnSignUp = document.getElementById("btnSignUp");

  // signup event
  btnSignUp.addEventListener('click', e => {
    // Get Email and pass
    //TODO: check for real emails
    console.log("just clicked the signup button");

    var email = signup_email.value;
    var pass = signup_password.value;
    var auth = firebase.auth();
    // sign up
    const promise = auth.createUserWithEmailAndPassword(email, pass);
    promise
      .catch(e => console.log(e.message));

    if (auth.currentUser != null) {
      auth.currentUser.updateProfile({
        displayName: signup_fullname,
        userCategory: student__,
        matric: signup_matric,
        department: signup_dept,
        level: signup_level,
        religion: signup_religion
      }).then(function () {
        console.log("update successful");
        window.readystatemode = true;
      }, function (error) {
        console.log("update failed");
      });
    }
  });

  firebase.auth().onAuthStateChanged(firebaseUser => {
    if (firebaseUser && window.readystatemode) {
      console.log(firebaseUser);
      btnLogout.classList.remove('hide');
      window.location('./dashboard.html');
    } else {
      console.log("not logged in");
      btnLogout.classList.add('hide');
    }
  });

})();


问:
Angular2 observable http get conditional repeat
I'm using angular2 observable pattern to make http requests.
I'm trying to conditional repeat the http get: I want to execute the http get until a condition is met:

```<code>http.get('url')
.map(res => {
     // if the condition is met I should repeat the http get request
})
.subscribe()
</code>```

Is there a way to conditional repeat the http get request?

Thanks,
Marco

答:
You can use expand operator. Here's an example:

let request$ = http.get('url');

request$.expand(value => {
  return value !== 0 ? request$ : Rx.Observable.empty()
})
.map(res => {
  //Do mapping here
})
.subscribe()
```

Body:
I'm using angular2 observable pattern to make http requests.
I'm trying to conditional repeat the http get: I want to execute the http get until a condition is met:

http.get('url')
.map(res => {
     // if the condition is met I should repeat the http get request
})
.subscribe()

Is there a way to conditional repeat the http get request?

Thanks,
Marco


问:
What's the cleanest way to extract URLs from a string using Python?
Although I know I could use some hugeass regex such as the one posted here I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on?

Simple question, but nothing jumped out on Google (or Stackoverflow).

Look forward to seeing how y'all do this!

答:
There is another way how to extract URLs from text easily. You can use urlextract to do it for you, just install it via pip:

```<code>pip install urlextract
</code>```

and then you can use it like this:

```<code>from urlextract import URLExtract

extractor = URLExtract()
urls = extractor.find_urls("Let's have URL stackoverflow.com as an example.")
print(urls) # prints: ['stackoverflow.com']
</code>```

You can find more info on my github page: https://github.com/lipoja/URLExtract

NOTE: It downloads list of TLDs from iana.org to keep you up to date. But if the program does not have internet access then its not for you.

This approach is similar as in urlextractor (mentioned above), but my code is recent, maintained and I am open for any suggestions (new features).

OwnerDisplayName: jkp

ContentLicense: CC BY-SA 4.0

Body:
There is another way how to extract URLs from text easily. You can use urlextract to do it for you, just install it via pip:

pip install urlextract

and then you can use it like this:

from urlextract import URLExtract

extractor = URLExtract()
urls = extractor.find_urls("Let's have URL stackoverflow.com as an example.")
print(urls) # prints: ['stackoverflow.com']

You can find more info on my github page: https://github.com/lipoja/URLExtract

NOTE: It downloads list of TLDs from iana.org to keep you up to date. But if the program does not have internet access then its not for you.

This approach is similar as in urlextractor (mentioned above), but my code is recent, maintained and I am open for any suggestions (new features).


问:
How do I store a rating in a song?
I want to be able to store information about a song that has been opened using my application. I would like for the user to be able to give the song a rating and this rating be loaded every time the users opens that file using my application.

I also need to know whether I should store the ratings in a database or an xml file.

答:
If the song format supports suitable meta data (eg. MP3), then follow Kevin's advice of using the meta data. This is by far the best way of doing it, and it is what the meta data is intended for.

If not, then it really depends on your application. If you want to share the rating information - especially over a web service, then I would go for XML: it would be trivial to supply your XML listings as one big feed, for example.

XML (or most other text formats) also have the advantage that they can be easily edited by a human in a text editor.

The database would have its advantages if you had a more closed system, you wanted speed and fast indexing, and/or have other tables you might want to store as well (eg. data about albums and bands).

Title: How do I store a rating in a song?


问:
How to select minimum TRUE values sorted by other variables
I have a very large set of data, that is sorted by facility number, year, and month. In the final column I have a set of TRUE/FALSE statements. I have this final column set up so that for each unique set of (facility number, year, and month) the column will start off as FALSE, but transitions to some point at TRUE (which is determined elsewhere in my program).

I am looking to find the minimum row number in each unique set of (facility number, year, and month) where the final column switches from FALSE to TRUE.

Here is a sample of the table:

```<code>     fac_num year month     t
  1:       1 2017     1 FALSE
  2:       1 2017     1 FALSE
  3:       1 2017     1 FALSE
  4:       1 2017     1 FALSE
  5:       1 2017     1 FALSE
 ---
2466726:      62 2017     4  TRUE
2466727:      62 2017     4  TRUE
2466728:      65 2017     1  TRUE
2466729:      65 2017     5  TRUE
2466730:      65 2017     5  TRUE
</code>```

So far I have been able to manage only how to get the lowest row number of TRUE value overall, but not for each unique set of (facility number, year, and month).

```<code>min(which(dat0a$t))
</code>```

The above code returns

```<code>64
</code>```

Which is the correct row number for the lowest TRUE value in (fac_num = 1, year = 2017, month = 1), but I would like to know how to repeat this for any (facility number, year, and month) combination without having to manually enter every combination as there are hundreds of potential combinations.

答:
Here's a solution using dplyr:

```<code>library(dplyr)

dat0a %>%
  group_by(fac_num, year, month) %>%
  summarize(row_n = min(row_number()[t == TRUE]))
</code>```

First setup your groups using group_by, then take the minimum row_number() where t == TRUE within each group.

Body:
I have a very large set of data, that is sorted by facility number, year, and month. In the final column I have a set of TRUE/FALSE statements. I have this final column set up so that for each unique set of (facility number, year, and month) the column will start off as FALSE, but transitions to some point at TRUE (which is determined elsewhere in my program).

I am looking to find the minimum row number in each unique set of (facility number, year, and month) where the final column switches from FALSE to TRUE.

Here is a sample of the table:

     fac_num year month     t
  1:       1 2017     1 FALSE
  2:       1 2017     1 FALSE
  3:       1 2017     1 FALSE
  4:       1 2017     1 FALSE
  5:       1 2017     1 FALSE
 ---
2466726:      62 2017     4  TRUE
2466727:      62 2017     4  TRUE
2466728:      65 2017     1  TRUE
2466729:      65 2017     5  TRUE
2466730:      65 2017     5  TRUE

So far I have been able to manage only how to get the lowest row number of TRUE value overall, but not for each unique set of (facility number, year, and month).

min(which(dat0a$t))

The above code returns

64

Which is the correct row number for the lowest TRUE value in (fac_num = 1, year = 2017, month = 1), but I would like to know how to repeat this for any (facility number, year, and month) combination without having to manually enter every combination as there are hundreds of potential combinations.

Body:
Here's a solution using dplyr:

library(dplyr)

dat0a %>%
  group_by(fac_num, year, month) %>%
  summarize(row_n = min(row_number()[t == TRUE]))

First setup your groups using group_by, then take the minimum row_number() where t == TRUE within each group.


问:
Cannot catch toolbar home button click event
I've implemented the newest appcompat library and using the Toolbar as action bar. But the problem is I cannot catch the home button / hamburger icon click event. I've tried and looked everything but doesn't seem to find a similar problem.

This is my Activity class :

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Set up the drawer.
    navDrawerFragment =
        (NavigationDrawerFragment) getSupportFragmentManager()
        .findFragmentById(R.id.navigation_drawer);
    navDrawerFragment.setUp(
        R.id.navigation_drawer,
        (DrawerLayout) findViewById(R.id.drawer_layout),
        toolbar);
}
</code>```

And this is my NavigationDrawerFragment class :

```<code>public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        currentSelectedPosition = savedInstanceState.getInt(
            STATE_SELECTED_POSITION);
        fromSavedInstanceState = true;
    }

    // Select either the default item (0) or the last selected item.
    selectItem(currentSelectedPosition);
}

@Override
public void onActivityCreated (Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // Indicate that this fragment would like
    // to influence the set of actions in the action bar.
    setHasOptionsMenu(true);
}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        drawerListView = (ListView) inflater.inflate(
            R.layout.fragment_navigation_drawer, container, false);
        drawerListView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent,
                View view, int position, long id) {
                selectItem(position);
            }
        });
        //mDrawerListView.setAdapter();
        //mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
        return drawerListView;
}

public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
    fragmentContainerView = getActivity().findViewById(fragmentId);
    this.drawerLayout = drawerLayout;

    // set a custom shadow that overlays the main
    // content when the drawer opens
    drawerLayout.setDrawerShadow(
        R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view
    // with items and click listener

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the navigation drawer and the action bar app icon.
    drawerToggle = new ActionBarDrawerToggle(
        getActivity(),
        drawerLayout,
        toolbar,
        R.string.navigation_drawer_open,
        R.string.navigation_drawer_close) {
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
        }

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }
    };

    // If the user hasn't 'learned' about the drawer,
    // open it to introduce them to the drawer,
    // per the navigation drawer design guidelines.
    if (!userLearnedDrawer && !fromSavedInstanceState) {
        drawerLayout.openDrawer(fragmentContainerView);
    }

    // Defer code dependent on restoration of previous instance state.
    drawerLayout.post(new Runnable() {
        @Override
        public void run() {
            drawerToggle.syncState();
        }
    });

    drawerLayout.setDrawerListener(drawerToggle);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_SELECTED_POSITION, currentSelectedPosition);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    drawerToggle.onConfigurationChanged(newConfig);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.d("cek", "item selected");
    if (drawerToggle.onOptionsItemSelected(item)) {
        Log.d("cek", "home selected");
        return true;
    }

    return super.onOptionsItemSelected(item);
}
</code>```

when I clicked a menu item, the log "item selected" gets called. But when I click on the home button, it opens navigation drawer but the log "home selected" never get called. I've set onOptionsItemSelected method inside my Activity as well, but it still doesn't get called.

答:
For anyone looking for a Xamarin implementation (since events are done differently in C#), I simply created this NavClickHandler class as follows:

```<code>public class NavClickHandler : Java.Lang.Object, View.IOnClickListener
{
    private Activity mActivity;
    public NavClickHandler(Activity activity)
    {
        this.mActivity = activity;
    }
    public void OnClick(View v)
    {
        DrawerLayout drawer = (DrawerLayout)mActivity.FindViewById(Resource.Id.drawer_layout);
        if (drawer.IsDrawerOpen(GravityCompat.Start))
        {
            drawer.CloseDrawer(GravityCompat.Start);
        }
        else
        {
            drawer.OpenDrawer(GravityCompat.Start);
        }
    }
}
</code>```

Then, assigned a custom hamburger menu button like this:

```<code>        SupportActionBar.SetDisplayHomeAsUpEnabled(true);
        SupportActionBar.SetDefaultDisplayHomeAsUpEnabled(false);
        this.drawerToggle.DrawerIndicatorEnabled = false;
        this.drawerToggle.SetHomeAsUpIndicator(Resource.Drawable.MenuButton);
</code>```

And finally, assigned the drawer menu toggler a ToolbarNavigationClickListener of the class type I created earlier:

```<code>        this.drawerToggle.ToolbarNavigationClickListener = new NavClickHandler(this);
</code>```

And then you've got a custom menu button, with click events handled.

Body:
I've implemented the newest appcompat library and using the Toolbar as action bar. But the problem is I cannot catch the home button / hamburger icon click event. I've tried and looked everything but doesn't seem to find a similar problem.

This is my Activity class :

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Set up the drawer.
    navDrawerFragment =
        (NavigationDrawerFragment) getSupportFragmentManager()
        .findFragmentById(R.id.navigation_drawer);
    navDrawerFragment.setUp(
        R.id.navigation_drawer,
        (DrawerLayout) findViewById(R.id.drawer_layout),
        toolbar);
}

And this is my NavigationDrawerFragment class :

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        currentSelectedPosition = savedInstanceState.getInt(
            STATE_SELECTED_POSITION);
        fromSavedInstanceState = true;
    }

    // Select either the default item (0) or the last selected item.
    selectItem(currentSelectedPosition);
}

@Override
public void onActivityCreated (Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // Indicate that this fragment would like
    // to influence the set of actions in the action bar.
    setHasOptionsMenu(true);
}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        drawerListView = (ListView) inflater.inflate(
            R.layout.fragment_navigation_drawer, container, false);
        drawerListView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent,
                View view, int position, long id) {
                selectItem(position);
            }
        });
        //mDrawerListView.setAdapter();
        //mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
        return drawerListView;
}

public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
    fragmentContainerView = getActivity().findViewById(fragmentId);
    this.drawerLayout = drawerLayout;

    // set a custom shadow that overlays the main
    // content when the drawer opens
    drawerLayout.setDrawerShadow(
        R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view
    // with items and click listener

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the navigation drawer and the action bar app icon.
    drawerToggle = new ActionBarDrawerToggle(
        getActivity(),
        drawerLayout,
        toolbar,
        R.string.navigation_drawer_open,
        R.string.navigation_drawer_close) {
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
        }

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }
    };

    // If the user hasn't 'learned' about the drawer,
    // open it to introduce them to the drawer,
    // per the navigation drawer design guidelines.
    if (!userLearnedDrawer && !fromSavedInstanceState) {
        drawerLayout.openDrawer(fragmentContainerView);
    }

    // Defer code dependent on restoration of previous instance state.
    drawerLayout.post(new Runnable() {
        @Override
        public void run() {
            drawerToggle.syncState();
        }
    });

    drawerLayout.setDrawerListener(drawerToggle);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_SELECTED_POSITION, currentSelectedPosition);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    drawerToggle.onConfigurationChanged(newConfig);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.d("cek", "item selected");
    if (drawerToggle.onOptionsItemSelected(item)) {
        Log.d("cek", "home selected");
        return true;
    }

    return super.onOptionsItemSelected(item);
}

when I clicked a menu item, the log "item selected" gets called. But when I click on the home button, it opens navigation drawer but the log "home selected" never get called. I've set onOptionsItemSelected method inside my Activity as well, but it still doesn't get called.

Body:
For anyone looking for a Xamarin implementation (since events are done differently in C#), I simply created this NavClickHandler class as follows:

public class NavClickHandler : Java.Lang.Object, View.IOnClickListener
{
    private Activity mActivity;
    public NavClickHandler(Activity activity)
    {
        this.mActivity = activity;
    }
    public void OnClick(View v)
    {
        DrawerLayout drawer = (DrawerLayout)mActivity.FindViewById(Resource.Id.drawer_layout);
        if (drawer.IsDrawerOpen(GravityCompat.Start))
        {
            drawer.CloseDrawer(GravityCompat.Start);
        }
        else
        {
            drawer.OpenDrawer(GravityCompat.Start);
        }
    }
}

Then, assigned a custom hamburger menu button like this:

        SupportActionBar.SetDisplayHomeAsUpEnabled(true);
        SupportActionBar.SetDefaultDisplayHomeAsUpEnabled(false);
        this.drawerToggle.DrawerIndicatorEnabled = false;
        this.drawerToggle.SetHomeAsUpIndicator(Resource.Drawable.MenuButton);

And finally, assigned the drawer menu toggler a ToolbarNavigationClickListener of the class type I created earlier:

        this.drawerToggle.ToolbarNavigationClickListener = new NavClickHandler(this);

And then you've got a custom menu button, with click events handled.


问:
how to run different array on my map function for my nav component
Pretty new at coding so sorry if my question looks ridiculous...

I am building a menu on my website which is divided in several categories.

In this example, we have Theory and Video categories ( Video only 1 level and Theory is going deeper on 2 levels).

The code below is working for only 1 category at time (thats why the comments).

I would like to ask you how to build a more generic function that can run whatever the array is (for the map function) and avoid this: "Cannot read property 'map' of undefined".

```<code>  render() {
const theories = this.props.menuTheory;
const videos = this.props.menuVideos;

// const menuTheory = theories.map((theory, i) => (
//
//   <div className="nav__category" key={i} onClick={() => this.onSelect(theory.category)}>
//
//     <div className={this.state.isSelected === theory.category
//       ? "nav__category__dropdown nav__category__dropdown--isSelected"
//       : "nav__category__dropdown"}>
//       <span className="nav__category__text">{theory.category}</span>
//       <span className="checked"><img src={'../static/icons/nav__check.svg'}/></span>
//     </div>
//       <ul className={this.state.isExpanded === theory.category
//         ? "nav__chapterBox"
//         : "nav__chapterBox nav__chapterBox--isNotExpanded"}>
//         {theory.chapters && theory.chapters.map((chapter, i) => <NavChapter key={i} id={chapter.objectId} title={chapter.name} onClick={() => this.onSelect1(chapter.objectId)}/>)}
//       </ul>
//   </div>
// ))

const menuVideo = videos.map((video, i) => (

  <div className="nav__category" key={i} onClick={() => this.onSelect(video.category)}>

    <div className={this.state.isSelected === video.category
      ? "nav__category__dropdown nav__category__dropdown--isSelected"
      : "nav__category__dropdown"}>
      <span className="nav__category__text">{video.category}</span>
      <span className="checked"><img src={'../static/icons/nav__check.svg'}/></span>
    </div>
  </div>
))

return (
  <nav className="nav__categoryBox">
    {/* {menuTheory} */}
    {menuVideo}
  </nav>
)
</code>```

}

Thanks.

答:
Okay, so it sounds like you're looking for a way to do conditional rendering in React. What you need to do is add some state to the component. I've added showVideos as a bool (true|false). Use showVideos in the render method to determine which menu to show. You still create the menus using map, but in the return block, check this.state.showVideos to determine which content to return. To get this fully working, you'll also need to add a button that calls toggleMenu onClick that will update your state and switch which menu is being shown.

```<code>toggleMenu(){
    this.setState({
        showVideos: !this.state.showVideos
    });
}
render() {
    const theories = this.props.menuTheory;
    const videos = this.props.menuVideos;

    const menuTheory = theories.map((theory, i) => (
        <div className="nav__category" key={i} onClick={() => this.onSelect(theory.category)}>
            <div className={this.state.isSelected === theory.category ? "nav__category__dropdown nav__category__dropdown--isSelected" : "nav__category__dropdown"}>
                <span className="nav__category__text">{theory.category}</span>
                <span className="checked"><img src={'../static/icons/nav__check.svg'}/></span>
            </div>
            <ul className={this.state.isExpanded === theory.category ? "nav__chapterBox" : "nav__chapterBox nav__chapterBox--isNotExpanded"}>
                {theory.chapters && theory.chapters.map((chapter, i) => <NavChapter key={i} id={chapter.objectId} title={chapter.name} onClick={() => this.onSelect1(chapter.objectId)}/>)}
            </ul>
        </div>
    ))

    const menuVideo = videos.map((video, i) => (

        <div className="nav__category" key={i} onClick={() => this.onSelect(video.category)}>
            <div className={this.state.isSelected === video.category ? "nav__category__dropdown nav__category__dropdown--isSelected" : "nav__category__dropdown"}>
              <span className="nav__category__text">{video.category}</span>
              <span className="checked"><img src={'../static/icons/nav__check.svg'}/></span>
            </div>
      </div>
    ))

    return (
      <nav className="nav__categoryBox">
        <button onClick={this.toggleMenu}>Toggle Menu</button>
        {this.state.showVideos ? menuVideo : menuTheory}
      </nav>
    )
}
</code>```

Body:
Pretty new at coding so sorry if my question looks ridiculous...

I am building a menu on my website which is divided in several categories.

In this example, we have Theory and Video categories ( Video only 1 level and Theory is going deeper on 2 levels).

The code below is working for only 1 category at time (thats why the comments).

I would like to ask you how to build a more generic function that can run whatever the array is (for the map function) and avoid this: "Cannot read property 'map' of undefined".

  render() {
const theories = this.props.menuTheory;
const videos = this.props.menuVideos;

// const menuTheory = theories.map((theory, i) => (
//
//
 this.onSelect(theory.category)}>
//
//

//       {theory.category}
//
//

//

//         {theory.chapters && theory.chapters.map((chapter, i) => <NavChapter key={i} id={chapter.objectId} title={chapter.name} onClick={() => this.onSelect1(chapter.objectId)}/>)}
//

//

// ))

const menuVideo = videos.map((video, i) => (

 this.onSelect(video.category)}>

      {video.category}

))

return (

    {/* {menuTheory} */}
    {menuVideo}

)

}

Thanks.

Body:
Okay, so it sounds like you're looking for a way to do conditional rendering in React. What you need to do is add some state to the component. I've added showVideos as a bool (true|false). Use showVideos in the render method to determine which menu to show. You still create the menus using map, but in the return block, check this.state.showVideos to determine which content to return. To get this fully working, you'll also need to add a button that calls toggleMenu onClick that will update your state and switch which menu is being shown.

toggleMenu(){
    this.setState({
        showVideos: !this.state.showVideos
    });
}
render() {
    const theories = this.props.menuTheory;
    const videos = this.props.menuVideos;

    const menuTheory = theories.map((theory, i) => (
        <div className="nav__category" key={i} onClick={() => this.onSelect(theory.category)}>
            <div className={this.state.isSelected === theory.category ? "nav__category__dropdown nav__category__dropdown--isSelected" : "nav__category__dropdown"}>
                <span className="nav__category__text">{theory.category}</span>
                <span className="checked"><img src={'../static/icons/nav__check.svg'}/></span>
            </div>
            <ul className={this.state.isExpanded === theory.category ? "nav__chapterBox" : "nav__chapterBox nav__chapterBox--isNotExpanded"}>
                {theory.chapters && theory.chapters.map((chapter, i) => <NavChapter key={i} id={chapter.objectId} title={chapter.name} onClick={() => this.onSelect1(chapter.objectId)}/>)}
            </ul>
        </div>
    ))

    const menuVideo = videos.map((video, i) => (

        <div className="nav__category" key={i} onClick={() => this.onSelect(video.category)}>
            <div className={this.state.isSelected === video.category ? "nav__category__dropdown nav__category__dropdown--isSelected" : "nav__category__dropdown"}>
              <span className="nav__category__text">{video.category}</span>
              <span className="checked"><img src={'../static/icons/nav__check.svg'}/></span>
            </div>
      </div>
    ))

    return (
      <nav className="nav__categoryBox">
        <button onClick={this.toggleMenu}>Toggle Menu</button>
        {this.state.showVideos ? menuVideo : menuTheory}
      </nav>
    )
}


问:
jQuery: first callback isn't fluent (slidedown effect)
I know this probably must be a newbie question, but since I don't know much about jquery I have to ask it here:

I have a  element that has to toggle different content on clicking on different buttons.Now i'll post here just how I call my javascript:

onclick="javascript:gotoSubonderdeelmenu(this);"

This gets the div element, and with this i'll get the right id for the content to show.
Now my jQuery code:

```<code>function gotoSubonderdeelmenu(obj) {
    displaySubMenu(obj.id);
}

function displaySubMenu(niveauId) {
    $.get("submenu.htm", { niveau : niveauId }, function(data) {
        $('#submenu').html(data);
        $('#submenu').slideDown('slow',function(){
            $('#overzicht').fadeTo(500,0.25,function(){});
            $('#terugknop').show();
        });
    });
}
</code>```

It always just fluently slides down like you would expect, except the first time it's being called.

Anyone got a clue on how to solve this?

答:
You need to .hide() the content so it slides/expands from nothing, like this:

```<code>$.get("submenu.htm", { niveau : niveauId }, function(data) {
    $('#submenu').html(data).hide().slideDown('slow',function(){
        $('#overzicht').fadeTo(500,0.25,function(){});
        $('#terugknop').show();
    });
});
</code>```

Body:
I know this probably must be a newbie question, but since I don't know much about jquery I have to ask it here:

I have a  element that has to toggle different content on clicking on different buttons.Now i'll post here just how I call my javascript:

onclick="javascript:gotoSubonderdeelmenu(this);"

This gets the div element, and with this i'll get the right id for the content to show.
Now my jQuery code:

function gotoSubonderdeelmenu(obj) {
    displaySubMenu(obj.id);
}

function displaySubMenu(niveauId) {
    $.get("submenu.htm", { niveau : niveauId }, function(data) {
        $('#submenu').html(data);
        $('#submenu').slideDown('slow',function(){
            $('#overzicht').fadeTo(500,0.25,function(){});
            $('#terugknop').show();
        });
    });
}

It always just fluently slides down like you would expect, except the first time it's being called.

Anyone got a clue on how to solve this?

Body:
You need to .hide() the content so it slides/expands from nothing, like this:

$.get("submenu.htm", { niveau : niveauId }, function(data) {
    $('#submenu').html(data).hide().slideDown('slow',function(){
        $('#overzicht').fadeTo(500,0.25,function(){});
        $('#terugknop').show();
    });
});


问:
Diagonal Background Structure [CSS]
Currently working on a web design project for a client where I designed a multi-layered diagonal background. I solved a single diagonal with;

```<code>background-color: #dbebde;
background-image: -webkit-linear-gradient(120deg, #dbebde 50%, #f8f8f8 45%);
min-height: 400px;
</code>```

However, as seen in the image below, I need to add a smaller diagonal on the left side.

Does anyone have an idea on how to solve this specific issue?

答:
You can use a single HTML element, let's say a
, and use pseudo-elements, particularly ::before and ::after, to create those shapes, without writing additional HTML elements.

You would draw the red one first:

body {
  margin: 0;
}

.fullBox {
  position: relative;
  height: 100vh;
}

.diagonalBox {
  background: #FFF;
  overflow: hidden;
}

.diagonalBox::before,
.diagonalBox::after {
  content: '';
  position: absolute;
  width: 200%;
  height: 200%;
  left: 0;
}

.diagonalBox::before {
  background: #D00;
  top: 10%;
  transform: rotate(30deg);
  transform-origin: top left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="fullBox diagonalBox"></div></code>```

And then add the light mint green one on top of that:

body {
  margin: 0;
}

.fullBox {
  position: relative;
  height: 100vh;
}

.diagonalBox {
  background: #FFF;
  overflow: hidden;
}

.diagonalBox::before,
.diagonalBox::after {
  content: '';
  position: absolute;
  width: 200%;
  height: 200%;
  left: 0;
}

.diagonalBox::before {
  background: #D00;
  top: 10%;
  transform: rotate(30deg);
  transform-origin: top left;
}

.diagonalBox::after {
  background: #DFD;
  top: 100%;
  transform: rotate(-30deg);
  transform-origin: bottom left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="fullBox diagonalBox"></div></code>```

Keep in mind that your may need to adjust the dimensions and positions of the pseudo-elements.

Title: Diagonal Background Structure [CSS]

Body:
Currently working on a web design project for a client where I designed a multi-layered diagonal background. I solved a single diagonal with;

background-color: #dbebde;
background-image: -webkit-linear-gradient(120deg, #dbebde 50%, #f8f8f8 45%);
min-height: 400px;

However, as seen in the image below, I need to add a smaller diagonal on the left side.

Does anyone have an idea on how to solve this specific issue?

Body:
You can use a single HTML element, let's say a <div>, and use pseudo-elements, particularly ::before and ::after, to create those shapes, without writing additional HTML elements.

You would draw the red one first:

body {
  margin: 0;
}

.fullBox {
  position: relative;
  height: 100vh;
}

.diagonalBox {
  background: #FFF;
  overflow: hidden;
}

.diagonalBox::before,
.diagonalBox::after {
  content: '';
  position: absolute;
  width: 200%;
  height: 200%;
  left: 0;
}

.diagonalBox::before {
  background: #D00;
  top: 10%;
  transform: rotate(30deg);
  transform-origin: top left;
}

<div class="fullBox diagonalBox"></div>

And then add the light mint green one on top of that:

body {
  margin: 0;
}

.fullBox {
  position: relative;
  height: 100vh;
}

.diagonalBox {
  background: #FFF;
  overflow: hidden;
}

.diagonalBox::before,
.diagonalBox::after {
  content: '';
  position: absolute;
  width: 200%;
  height: 200%;
  left: 0;
}

.diagonalBox::before {
  background: #D00;
  top: 10%;
  transform: rotate(30deg);
  transform-origin: top left;
}

.diagonalBox::after {
  background: #DFD;
  top: 100%;
  transform: rotate(-30deg);
  transform-origin: bottom left;
}

<div class="fullBox diagonalBox"></div>

Keep in mind that your may need to adjust the dimensions and positions of the pseudo-elements.


问:
how to make height responsive screens in ionic 2?
I know we can make horizontally responsive content in ionic 2. What i want to know is how to make pages height responsive for all type of screens for example if a screen cover whole area on iphone 5 then it should cover whole height wisie area in iphone 7 also ? whats the best approach to achieve this ?</p>

答:
I hope I have understood your question correctly, you want to make the page height the same as the height of the device viewing it?

Well, let me introduce you to....

viewport height (or vh)

One vh is equal to 1% of the height of the viewport. So, as you can probably imagine, 100vh would be equal to 100% of the height of the viewport! The viewport is basically the view of the page. However beware, the vh unit is not support in Internet Explorer 8 or earlier.