问:
How to encode an object to json in Flutter
I am trying to convert the object "Week" to json.

https://flutter.dev/docs/development/data-and-backend/json this is the source that i used

```<code>class Week{
  DateTime _startDate;
  DateTime _endDate;
  List<Goal> _goalList;
  String _improvement;

  Week(this._startDate, this._endDate){
    this._goalList = List<Goal>();
    this._improvement = "";
  }

  Week.fromJson(Map<String, dynamic> json)
    : _startDate =  json['startDate'],
      _endDate = json['endDate'],
      _goalList = json['goalList'],
      _improvement = json['improvement'];

  Map<String, dynamic> toJson() =>
  {
    'startDate': _startDate,
    'endDate': _endDate,
    'goalList': _goalList,
    'improvement': _improvement,
  };
}
</code>```

I used this:

```<code>DateTime startDate = currentDate.subtract(new Duration(days:(weekday-1)));
DateTime endDate = currentDate.add(new Duration(days:(7-weekday)));

Week week = new Week(startDate, endDate);
var json = jsonEncode(week);
</code>```

But the problem is that I get this result:

```<code>Unhandled Exception: Converting object to an encodable object failed: Instance of 'Week'
#0      _JsonStringifier.writeObject (dart:convert/json.dart:647:7)
#1      _JsonStringStringifier.printOn (dart:convert/json.dart:834:17)
#2      _JsonStringStringifier.stringify (dart:convert/json.dart:819:5)
#3      JsonEncoder.convert (dart:convert/json.dart:255:30)
#4      JsonCodec.encode (dart:convert/json.dart:166:45)
#5      jsonEncode (dart:convert/json.dart:80:10)
</code>```

答:
for anyone wondering: I got my solution.

To make my code work I needed to implement the toJson() methods at my class Goal as well (because I used List<Goal> in Week).

```<code>class Goal{
  String _text;
  bool _reached;

  Map<String, dynamic> toJson() =>
  {
    'text': _text,
    'reached': _reached,
  };
}
</code>```

Also, I needed to add .toIso8601String() to the DateTime objects like that in the Week class:

```<code>Map<String, dynamic> toJson() =>
  {
    'startDate': _startDate.toIso8601String(),
    'endDate': _endDate.toIso8601String(),
    'goalList': _goalList,
    'improvement': _improvement,
  };
</code>```

Now the output is:

```<code> {"startDate":"2019-05-27T00:00:00.000Z","endDate":"2019-06-02T00:00:00.000Z","goalList":[],"improvement":""}
</code>```

Body:
I am trying to convert the object "Week" to json.

https://flutter.dev/docs/development/data-and-backend/json this is the source that i used

class Week{
  DateTime _startDate;
  DateTime _endDate;
  List<Goal> _goalList;
  String _improvement;

  Week(this._startDate, this._endDate){
    this._goalList = List<Goal>();
    this._improvement = "";
  }

  Week.fromJson(Map<String, dynamic> json)
    : _startDate =  json['startDate'],
      _endDate = json['endDate'],
      _goalList = json['goalList'],
      _improvement = json['improvement'];

  Map<String, dynamic> toJson() =>
  {
    'startDate': _startDate,
    'endDate': _endDate,
    'goalList': _goalList,
    'improvement': _improvement,
  };
}

I used this:

DateTime startDate = currentDate.subtract(new Duration(days:(weekday-1)));
DateTime endDate = currentDate.add(new Duration(days:(7-weekday)));

Week week = new Week(startDate, endDate);
var json = jsonEncode(week);

But the problem is that I get this result:

Unhandled Exception: Converting object to an encodable object failed: Instance of 'Week'
#0      _JsonStringifier.writeObject (dart:convert/json.dart:647:7)
#1      _JsonStringStringifier.printOn (dart:convert/json.dart:834:17)
#2      _JsonStringStringifier.stringify (dart:convert/json.dart:819:5)
#3      JsonEncoder.convert (dart:convert/json.dart:255:30)
#4      JsonCodec.encode (dart:convert/json.dart:166:45)
#5      jsonEncode (dart:convert/json.dart:80:10)

Body:
for anyone wondering: I got my solution.

To make my code work I needed to implement the toJson() methods at my class Goal as well (because I used List<Goal> in Week).

class Goal{
  String _text;
  bool _reached;

  Map<String, dynamic> toJson() =>
  {
    'text': _text,
    'reached': _reached,
  };
}

Also, I needed to add .toIso8601String() to the DateTime objects like that in the Week class:

Map<String, dynamic> toJson() =>
  {
    'startDate': _startDate.toIso8601String(),
    'endDate': _endDate.toIso8601String(),
    'goalList': _goalList,
    'improvement': _improvement,
  };

Now the output is:

 {"startDate":"2019-05-27T00:00:00.000Z","endDate":"2019-06-02T00:00:00.000Z","goalList":[],"improvement":""}


来源: stackexchange

问:
Can I get "&&" or "-and" to work in PowerShell?
Note: This question originally asked in 2009, when powershell did not have support for the && operator.
In 2019, per Jay's answer, microsoft added support for && and || in Powershell 7.
https://stackoverflow.com/a/564092/234

Original Question

&& is notoriously hard to search for on Google Search, but the best I've found is this article which says to use -and.

Unfortunately it doesn't give any more information, and I can't find out what I'm supposed to do with -and (again, a notoriously hard thing to search for).

The context I'm trying to use it in is "execute cmd1, and if successful, execute cmd2", basically this:

```<code>csc /t:exe /out:a.exe SomeFile.cs && a.exe
</code>```

If you just want to run multiple commands on a single line and you don't care if the first one fails or not, you can use ; For most of my purposes this is fine.

For example: kill -n myapp; ./myapp.exe.

答:
In CMD, '&&' means "execute command 1, and if it succeeds, execute command 2".  I have used it for things like:

```<code>build && run_tests
</code>```

In PowerShell, the closest thing you can do is:

```<code>(build) -and (run_tests)
</code>```

It has the same logic, but the output text from the commands is lost.  Maybe it is good enough for you, though.

If you're doing this in a script, you will probably be better off separating the statements, like this:

```<code>build
if ($?) {
    run_tests
}
</code>```

2019/11/27: The &&operator is now available for PowerShell 7 Preview 5+:

```<code>PS > echo "Hello!" && echo "World!"
Hello!
World!

</code>```

OwnerDisplayName: Orion Edwards

ContentLicense: CC BY-SA 4.0

Body:
Note: This question originally asked in 2009, when powershell did not have support for the && operator.
In 2019, per Jay's answer, microsoft added support for && and || in Powershell 7.
https://stackoverflow.com/a/564092/234

Original Question

&& is notoriously hard to search for on Google Search, but the best I've found is this article which says to use -and.

Unfortunately it doesn't give any more information, and I can't find out what I'm supposed to do with -and (again, a notoriously hard thing to search for).

The context I'm trying to use it in is "execute cmd1, and if successful, execute cmd2", basically this:

csc /t:exe /out:a.exe SomeFile.cs && a.exe

If you just want to run multiple commands on a single line and you don't care if the first one fails or not, you can use ; For most of my purposes this is fine.

For example: kill -n myapp; ./myapp.exe.

LastEditorDisplayName: Orion Edwards

Body:
In CMD, '&&' means "execute command 1, and if it succeeds, execute command 2".  I have used it for things like:

build && run_tests

In PowerShell, the closest thing you can do is:

(build) -and (run_tests)

It has the same logic, but the output text from the commands is lost.  Maybe it is good enough for you, though.

If you're doing this in a script, you will probably be better off separating the statements, like this:

build
if ($?) {
    run_tests
}

2019/11/27: The &&operator is now available for PowerShell 7 Preview 5+:

PS > echo "Hello!" && echo "World!"
Hello!
World!

OwnerDisplayName: Jay Bazuzi

LastEditorDisplayName: Jay Bazuzi


问:
C++ alloc array of objects
I've got this issue with allocation of an array of some objects that I need to initialize with some constructor. Let me show what I mean:

```<code>ofstream* out = new ofstream[10];

for(int i = 0; i < 10; i++){
    stringstream ss;
    ss << "file" << i << ".txt";
    string str(ss.str());
    char *fileName = (char*)str.c_str();
    out[i] = ofstream(fileName); //Now, this is wrong
}
</code>```

And I need some help on the wrong marked line. How do I allocate each member of that array?

And thank you for not pointing me to other posts (I looked on a lot before posting)

答: Get rid of the fileName variable and use out[i].open(str.c_str()); - and remember to delete[] out;

ContentLicense: CC BY-SA 3.0

Title: C++ alloc array of objects

Body:
I've got this issue with allocation of an array of some objects that I need to initialize with some constructor. Let me show what I mean:

ofstream* out = new ofstream[10];

for(int i = 0; i < 10; i++){
    stringstream ss;
    ss << "file" << i << ".txt";
    string str(ss.str());
    char *fileName = (char*)str.c_str();
    out[i] = ofstream(fileName); //Now, this is wrong
}

And I need some help on the wrong marked line. How do I allocate each member of that array?

And thank you for not pointing me to other posts (I looked on a lot before posting)


问:
Should return empty list [] 200/204 or 404 in a Restful API design?
For example, there's a restful API GET http://luexu.com/users/{page} to list the users in Nth page. Suppose there're 20 users in each page. There're 100 users total in the database. GET http://luexu.com/users/5 returns the 80th to 100th users.

So how about query GET http://luexu.com/users/10? it's out of the total users. Which is a better design to return an empty list, empty array [] or 404?

200?

```<code>{
    "code": 200,
    "msg": "OK",
    "data": []
}
</code>```

or 204?

```<code>{
    "code": 204,
    "msg": "OK",
    "data": []
}
</code>```

or 404?

```<code>{
    "code": 404,
    "msg": "Not Found",
    "data": null
}
</code>```

答:
This is one of those questions that doesn't have a "best" answer.

All you can do is look at the options and choose what works best for your scenario.

As a rule of thumb, I personally avoid returning 404. The reason is that it is unclear why you got a 404. You could get a 404 because your URL is wrong, so if you make a design choice to return 404 when there is no data then you end up in an unclear situation. How do you know why you got 404? This is no good.

Returning a 200 with an empty array is perfectly fine.
Returning 204 perfectly fine as well.

The important bit is to make a choice, be consistent and document the choice so the users of your API know you made this choice and why.

Consistency and clarity, aim for that.

Body:
For example, there's a restful API GET http://luexu.com/users/{page} to list the users in Nth page. Suppose there're 20 users in each page. There're 100 users total in the database. GET http://luexu.com/users/5 returns the 80th to 100th users.

So how about query GET http://luexu.com/users/10? it's out of the total users. Which is a better design to return an empty list, empty array [] or 404?

200?

{
    "code": 200,
    "msg": "OK",
    "data": []
}

or 204?

{
    "code": 204,
    "msg": "OK",
    "data": []
}

or 404?

{
    "code": 404,
    "msg": "Not Found",
    "data": null
}


问:
Perl: Split a mixed text and binary file after a specific string
I have files that start with unix-delimited text lines, then switch to binary. The text portion ends with a specific string followed by newline. After that it is binary.

I need to write the text portion into one file, then write the remainder of the binary data into another file.  Here's what I have so far, but I'm stuck on how to switch to binary and write the remainder.

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

use 5.010;
use strict;
use warnings;

my ($inputfilename, $outtextfilename, $outbinfilename) = @ARGV;
open(my $in, '<:encoding(UTF-8)', $inputfilename)
  or die "Could not open file '$inputfilename' $!";

open my $outtext, '>', $outtextfilename or die;

my $outbin;
open $outbin, '>', $outbinfilename or die;
binmode $outbin;

while (my $aline = <$in>) {
  chomp $aline;
  if($aline =~ /\<\/FileSystem\>/) {   # a match indicates the end of the text portion - the rest is binary
    print $outtext "$aline\n";  # last line of the text portion
    print  "$aline\n";  # last line of the text portion
    close ($outtext);

    binmode $in;  # change input file to binary?
    # what do I do here to copy all remaining bytes in file as binary to $outbin??
    die;
    } else {
    print $outtext  "$aline\n";   # a line of the text portion
    print "$aline\n";   # a line of the text portion
    }
}

close ($in);
close ($outbin);
</code>```

Edit - final code:

```<code>#!/usr/bin/perl
use 5.010;
use strict;
use warnings;

my ($inputfilename, $outtextfilename, $outbinfilename) = @ARGV;

open(my $in, '<', $inputfilename)
  or die "Could not open file '$inputfilename' $!";

open my $outtext, '>', $outtextfilename or die;

my $outbin;
open $outbin, '>', $outbinfilename or die;
binmode $outbin;

    print "Starting File\n";
while (my $aline = <$in>) {
  chomp $aline;
  if($aline =~ /\<\/FileSystem\>/) {   # a match indicates the end of the text portion - the rest is binary
    print $outtext "$aline\n";  # last line of the text portion
    print  "$aline\n";  # last line of the text portion
    close ($outtext);

    binmode $in;  # change input file to binary

    my $cont = '';
    print "processing binary portion";
    while (1) {
    my $success = read $in, $cont, 1000000, length($cont);
    die $! if not defined $success;
    last if not $success;
    print ".";
    }
    close ($in);
    print $outbin $cont;
    print "\nDone\n";
    close $outbin;
    last;

    } else {
    print $outtext  "$aline\n";   # a line of the text portion
    print "$aline\n";   # a line of the text portion
    }
}
</code>```

答:
The easiest way is probably to use binary I/O for everything. That way we don't have to worry about switching file modes halfway through, and on unix there is no difference between text and binary mode anyway (except when it comes to encodings, but here we just want to copy bytes unchanged).

Depending on how big the plain text portion of the file is, we could either process it line by line or read it all into memory at once.

```<code>#!/usr/bin/perl
use strict;
use warnings;

my ($inputfilename, $outtextfilename, $outbinfilename) = @ARGV;

open my $in_fh, '<:raw', $inputfilename
    or die "$0: can't open $inputfilename for reading: $!\n";

open my $out_txt_fh, '>:raw', $outtextfilename
    or die "$0: can't open $outtextfilename for writing: $!\n";

open my $out_bin_fh, '>:raw', $outbinfilename
    or die "$0: can't open $outbinfilename for writing: $!\n";

# process text part
while (my $line = readline $in_fh) {
    print $out_txt_fh $line;
    last if $line =~ m{</FileSystem>};
}

# process binary part
while (read $in_fh, my $buffer, 4096) {
    print $out_bin_fh $buffer;
}
</code>```

This version of the code processes the text part line by line and the binary part in chunks of 4096 bytes (not taking internal buffering into account).

Alternatively, if the character sequence marking the end of the text part is exactly "</FileSystem>\n", we can be a bit cheeky:

```<code># process text part
{
    local $/ = "</FileSystem>\n";
    if (my $line = readline $in_fh) {
        print $out_txt_fh $line;
    }
}
</code>```

We temporarily switch the end-of-line marker from "\n" to "</FileSystem>\n" and read a single "line", which encompasses all of the text part. This assumes the text part is small enough to comfortably fit into memory. The rest of the script is the same.

Body:
I have files that start with unix-delimited text lines, then switch to binary. The text portion ends with a specific string followed by newline. After that it is binary.

I need to write the text portion into one file, then write the remainder of the binary data into another file.  Here's what I have so far, but I'm stuck on how to switch to binary and write the remainder.

#!/usr/bin/perl

use 5.010;
use strict;
use warnings;

my ($inputfilename, $outtextfilename, $outbinfilename) = @ARGV;
open(my $in, '<:encoding(UTF-8)', $inputfilename)
  or die "Could not open file '$inputfilename' $!";

open my $outtext, '>', $outtextfilename or die;

my $outbin;
open $outbin, '>', $outbinfilename or die;
binmode $outbin;

while (my $aline = <$in>) {
  chomp $aline;
  if($aline =~ /\<\/FileSystem\>/) {   # a match indicates the end of the text portion - the rest is binary
    print $outtext "$aline\n";  # last line of the text portion
    print  "$aline\n";  # last line of the text portion
    close ($outtext);

    binmode $in;  # change input file to binary?
    # what do I do here to copy all remaining bytes in file as binary to $outbin??
    die;
    } else {
    print $outtext  "$aline\n";   # a line of the text portion
    print "$aline\n";   # a line of the text portion
    }
}

close ($in);
close ($outbin);

Edit - final code:

#!/usr/bin/perl
use 5.010;
use strict;
use warnings;

my ($inputfilename, $outtextfilename, $outbinfilename) = @ARGV;

open(my $in, '<', $inputfilename)
  or die "Could not open file '$inputfilename' $!";

open my $outtext, '>', $outtextfilename or die;

my $outbin;
open $outbin, '>', $outbinfilename or die;
binmode $outbin;

    print "Starting File\n";
while (my $aline = <$in>) {
  chomp $aline;
  if($aline =~ /\<\/FileSystem\>/) {   # a match indicates the end of the text portion - the rest is binary
    print $outtext "$aline\n";  # last line of the text portion
    print  "$aline\n";  # last line of the text portion
    close ($outtext);

    binmode $in;  # change input file to binary

    my $cont = '';
    print "processing binary portion";
    while (1) {
    my $success = read $in, $cont, 1000000, length($cont);
    die $! if not defined $success;
    last if not $success;
    print ".";
    }
    close ($in);
    print $outbin $cont;
    print "\nDone\n";
    close $outbin;
    last;

    } else {
    print $outtext  "$aline\n";   # a line of the text portion
    print "$aline\n";   # a line of the text portion
    }
}

Body:
The easiest way is probably to use binary I/O for everything. That way we don't have to worry about switching file modes halfway through, and on unix there is no difference between text and binary mode anyway (except when it comes to encodings, but here we just want to copy bytes unchanged).

Depending on how big the plain text portion of the file is, we could either process it line by line or read it all into memory at once.

#!/usr/bin/perl
use strict;
use warnings;

my ($inputfilename, $outtextfilename, $outbinfilename) = @ARGV;

open my $in_fh, '<:raw', $inputfilename
    or die "$0: can't open $inputfilename for reading: $!\n";

open my $out_txt_fh, '>:raw', $outtextfilename
    or die "$0: can't open $outtextfilename for writing: $!\n";

open my $out_bin_fh, '>:raw', $outbinfilename
    or die "$0: can't open $outbinfilename for writing: $!\n";

# process text part
while (my $line = readline $in_fh) {
    print $out_txt_fh $line;
    last if $line =~ m{</FileSystem>};
}

# process binary part
while (read $in_fh, my $buffer, 4096) {
    print $out_bin_fh $buffer;
}

This version of the code processes the text part line by line and the binary part in chunks of 4096 bytes (not taking internal buffering into account).

Alternatively, if the character sequence marking the end of the text part is exactly "</FileSystem>\n", we can be a bit cheeky:

# process text part
{
    local $/ = "</FileSystem>\n";
    if (my $line = readline $in_fh) {
        print $out_txt_fh $line;
    }
}

We temporarily switch the end-of-line marker from "\n" to "</FileSystem>\n" and read a single "line", which encompasses all of the text part. This assumes the text part is small enough to comfortably fit into memory. The rest of the script is the same.


问:
Running JAR file on Windows
I have a JAR file named helloworld.jar.
In order to run it, I'm executing the following command in a command-line window:

java -jar helloworld.jar
```

This works fine, but how do I execute it with double-click instead?
Do I need to install any software?

答:
Actually, I faced this problem too. I got around it by making a .bat runner for my jar file.

Here is the code:

```<code>class FileHandler{
   public static File create_CMD_Rnner(){
      int exitCode = -1625348952;
      try{
           File runner = new File(Main.batName);
           PrintWriter printer = new PrintWriter(runner);
           printer.println("@echo off");
           printer.println("title " + Main.applicationTitle);
           printer.println("java -jar " + Main.jarName + " " + Main.startCode );
           printer.println("PAUSE");
           printer.flush();
           printer.close();
           return runner;
       }catch(Exception e){
           System.err.println("Coudln't create a runner bat \n exit code: " + exitCode);
           System.exit(exitCode);
           return null;
       }
   }
}
</code>```

Then in Your Main application class do this:

```<code>public class Main{
    static String jarName = "application.jar";
    static String applicationTitle = "java Application";
    static String startCode = "javaIsTheBest";
    static String batName = "_.bat";

    public static void main(String args[]) throws Exception{
        if(args.length == 0 || !args[0].equals(startCode)) {
            Desktop.getDesktop().open(FilesHandler.create_CMD_Rnner());
            System.exit(0);
        }else{
            //just in case you wanted to hide the bat
            deleteRunner();
            // Congratulations now you are running in a cmd window ... do whatever you want
            //......
            System.out.println("i Am Running in CMD");
            //......
            Thread.sleep(84600);
        }
    }

    public static void deleteRunner(){
        File batRunner = new File(batName);
        if(batRunner.exists()) batRunner.delete();
    }
}
</code>```

Please Note that

this code (my code) works only with a jar file, not a class file.

the jar file must have the same name as the String "jarName" is the Main class

OwnerDisplayName: BlackPanther

Title: Running JAR file on Windows

Body:
I have a JAR file named helloworld.jar.
In order to run it, I'm executing the following command in a command-line window:

java -jar helloworld.jar

This works fine, but how do I execute it with double-click instead?
Do I need to install any software?

Body:
Actually, I faced this problem too. I got around it by making a .bat runner for my jar file.

Here is the code:

class FileHandler{
   public static File create_CMD_Rnner(){
      int exitCode = -1625348952;
      try{
           File runner = new File(Main.batName);
           PrintWriter printer = new PrintWriter(runner);
           printer.println("@echo off");
           printer.println("title " + Main.applicationTitle);
           printer.println("java -jar " + Main.jarName + " " + Main.startCode );
           printer.println("PAUSE");
           printer.flush();
           printer.close();
           return runner;
       }catch(Exception e){
           System.err.println("Coudln't create a runner bat \n exit code: " + exitCode);
           System.exit(exitCode);
           return null;
       }
   }
}

Then in Your Main application class do this:

public class Main{
    static String jarName = "application.jar";
    static String applicationTitle = "java Application";
    static String startCode = "javaIsTheBest";
    static String batName = "_.bat";

    public static void main(String args[]) throws Exception{
        if(args.length == 0 || !args[0].equals(startCode)) {
            Desktop.getDesktop().open(FilesHandler.create_CMD_Rnner());
            System.exit(0);
        }else{
            //just in case you wanted to hide the bat
            deleteRunner();
            // Congratulations now you are running in a cmd window ... do whatever you want
            //......
            System.out.println("i Am Running in CMD");
            //......
            Thread.sleep(84600);
        }
    }

    public static void deleteRunner(){
        File batRunner = new File(batName);
        if(batRunner.exists()) batRunner.delete();
    }
}

Please Note that

this code (my code) works only with a jar file, not a class file.

the jar file must have the same name as the String "jarName" is the Main class


问:
INVALID_REQUEST_BODY in EnvelopeRecipients::update
Im getting the envelopes recipients using the GET envelopes/{envelope_id}/recipients endpoint.

After that i add the field clientUserId and try to update the envelope, using the POST envelopes/{envelope_id}/recipients' endpoint with the very same array that i got from return from GET method as body.

But is returned the following error:

"The request body is missing or improperly formatted. Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'API_REST.Models.v2.recipientIdentityVerification' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

Path 'signers[0].identityVerification', line 1, position 120."

Obs: This was working last time i tested (december/2018)

UPDATE:

I enabled the Log, but seems that the error is not being logged, as you can see, all the requests in log are "OK", and I didn't find the POST envelopes/{envelope_id}/recipients.

Here are the logs files:

Content of 07_OK_GetEnvelopeRecipients.txt:

答:
Since you don't see the error in the DocuSign logs, and also from the wording of the error, I suspect that the problem is happening within your machine, before the request is sent to DocuSign.

So the solution is to debug within your application. For more help, please provide your code which causes the error to be raised.


问:
Can you use AWS Route 53 latency based routing to resolve servers outside AWS?
I use AWS Route 53 for DNS management and I have servers and load balancers running on-premise or in any cloud outside AWS. I want to do global load balancing using AWS Route 53 latency-based routing. Is this achievable and a common use case?</p>

答:
Route53 latency record has nothing to do with the record value or target IP, when you choose the latency based routing, you define regions and Route53 just looks the resolver IP which is making dns query and looks which is good to them in terms of latency with respective to the region and give that result.
You need to make sure your your records are correct, means the mapping of DC IP is associated with correct regions, the rest of it, Route53 will has all information e.g: resolver, latency etc </p>


问:
Node app.get not found when trying to make a post request towards it, but works in browser
I created an API for logins in Nodejs. When i try to make a jquery post request for it, it says 404 Not found, but when i open the same page in the browser, it finds the file.

My code to request:

```<code>$.post("http://localhost:8000/api/login", {"username": "username", "password": "password"}, function(response) {

    console.log(response);

});
</code>```

My code for the API (simplified):

```<code>app.get("/api/login", function(req, res) {

  var username = req.body.username,
  password = req.body.password;

  //login chechks but basically this is what it returns

  res.send({

    "error": 0,
    "loggedIn": 1

  });
  res.end();

});
</code>```

答:
app.get creates a route that accepts GET requests.
change it to app.post to accept POST requests.

https://expressjs.com/en/4x/api.html#app.get.method

Body:
I created an API for logins in Nodejs. When i try to make a jquery post request for it, it says 404 Not found, but when i open the same page in the browser, it finds the file.

My code to request:

$.post("http://localhost:8000/api/login", {"username": "username", "password": "password"}, function(response) {

    console.log(response);

});

My code for the API (simplified):

app.get("/api/login", function(req, res) {

  var username = req.body.username,
  password = req.body.password;

  //login chechks but basically this is what it returns

  res.send({

    "error": 0,
    "loggedIn": 1

  });
  res.end();

});


问:
How to fetch Resting energy value from HealthKit which has same value as Health App's value?
I'm using apple's HealthKit sample however resting energy value shown in Health app in iPhone doesn't match with the value fetched in sample app.

As per apple docs, HKQuantityTypeIdentifierBasalEnergyBurned is representing resting energy so I fetched this value from the HealthKit but the value I received doesn't match with the resting energy shown in Health App.

So I came across the apple's HealthKit sample where they are calculating resting energy based on formula:

```<code>// Calculates the user's total basal (resting) energy burn based off of their height, weight, age,
    // and biological sex. If there is not enough information, return an error.
    private func fetchTotalBasalBurn(completion: @escaping (HKQuantity?, Error?) -> Void)
    {
        let todayPredicate: NSPredicate = self.predicateForSamplesToday()

        let weightType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!
        let heightType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!

        let queryWeigth: HKCompletionHandle = {
            (weight, error) -> Void in

            guard let weight = weight else {
                completion(nil, error)

                return
            }

            let queryHeigth: HKCompletionHandle = {
                (height, error) -> Void in

                if height == nil {
                    completion(nil, error)

                    return;
                }

                var dateOfBirth: Date!

                do {

                    dateOfBirth = try self.healthStore!.dateOfBirth()

                } catch {

                    completion(nil, error)

                    return
                }

                var biologicalSexObjet: HKBiologicalSexObject!

                do {

                    biologicalSexObjet = try self.healthStore!.biologicalSex()

                } catch {

                    completion(nil, error)

                    return
                }

                // Once we have pulled all of the information without errors, calculate the user's total basal energy burn
                let basalEnergyButn: HKQuantity? = self.calculateBasalBurnTodayFromWeight(weight, height: height, dateOfBirth: dateOfBirth!, biologicalSex: biologicalSexObjet)

                completion(basalEnergyButn, nil)
            }

            if let healthStore = self.healthStore {

                healthStore.mostRecentQuantitySample(ofType: heightType, predicate: todayPredicate, completion: queryHeigth)
            }
        }

        if let healthStore = self.healthStore {
            healthStore.mostRecentQuantitySample(ofType: weightType, predicate: nil, completion: queryWeigth)
        }
    }

    private func calculateBasalBurnTodayFromWeight(_ weight: HKQuantity?, height: HKQuantity?, dateOfBirth: Date, biologicalSex: HKBiologicalSexObject) -> HKQuantity?
    {
        // Only calculate Basal Metabolic Rate (BMR) if we have enough information about the user
        guard let weight = weight, let height = height else {

            return nil
        }

        // Note the difference between calling +unitFromString: vs creating a unit from a string with
        // a given prefix. Both of these are equally valid, however one may be more convenient for a given
        // use case.
        let heightInCentimeters: Double = height.doubleValue(for: HKUnit(from:"cm"))
        let weightInKilograms: Double = weight.doubleValue(for: HKUnit.gramUnit(with: HKMetricPrefix.kilo))

        let nowDate = Date()
        let ageComponents: DateComponents = Calendar.current.dateComponents([Calendar.Component.year], from: dateOfBirth, to: nowDate)
        let ageInYears: Int = ageComponents.year!

        // BMR is calculated in kilocalories per day.
        let BMR: Double = self.calculateBMRFromWeight(weightInKilograms: weightInKilograms, height: heightInCentimeters, age: ageInYears, biologicalSex: biologicalSex.biologicalSex)

        // Figure out how much of today has completed so we know how many kilocalories the user has burned.
        let (startOfToday, endOfToday): (Date, Date) = self.datesFromToday()

        let secondsInDay: TimeInterval = endOfToday.timeIntervalSince(startOfToday)
        let percentOfDayComplete: Double = nowDate.timeIntervalSince(startOfToday) / secondsInDay

        let kilocaloriesBurned: Double = BMR * percentOfDayComplete

        let basalBurn = HKQuantity(unit: HKUnit.kilocalorie(), doubleValue: kilocaloriesBurned)

        return basalBurn
    }

/// Returns BMR value in kilocalories per day. Note that there are different ways of calculating the
    /// BMR. In this example we chose an arbitrary function to calculate BMR based on weight, height, age,
    /// and biological sex.
    private func calculateBMRFromWeight(weightInKilograms: Double, height heightInCentimeters: Double, age ageInYears: Int, biologicalSex: HKBiologicalSex) -> Double
    {
        var BMR: Double = 0

        if biologicalSex == .male {
            BMR = 66.0 + (13.8 * weightInKilograms) + (5.0 * heightInCentimeters) - (6.8 * Double(ageInYears))

            return BMR
        }

        BMR = 655 + (9.6 * weightInKilograms) + (1.8 * heightInCentimeters) - (4.7 * Double(ageInYears))

        return BMR
    }
</code>```

I'm tried the sample app to fetch resting energy however still resting energy value shown in health app and sample app doesn't have same value.

Could any body tell me how to fetch resting energy or what is the calculation used by Health App to find resting energy?

It would be great if someone can give me some pointers on it, I'm pretty new to HealthKit.

Thanks.

答:
It seems that Apple's sample is outdated. As of iOS 8 and watchOS 2 there's a call to retrieve this information in the same way that active calories are retrieved; simply change the identifier. Apple Documentation

```<code>HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.basalEnergyBurned)
</code>```

Don't forget to include the additional permission to read this data as well.

Body:
I'm using apple's HealthKit sample however resting energy value shown in Health app in iPhone doesn't match with the value fetched in sample app.

As per apple docs, HKQuantityTypeIdentifierBasalEnergyBurned is representing resting energy so I fetched this value from the HealthKit but the value I received doesn't match with the resting energy shown in Health App.

So I came across the apple's HealthKit sample where they are calculating resting energy based on formula:

// Calculates the user's total basal (resting) energy burn based off of their height, weight, age,
    // and biological sex. If there is not enough information, return an error.
    private func fetchTotalBasalBurn(completion: @escaping (HKQuantity?, Error?) -> Void)
    {
        let todayPredicate: NSPredicate = self.predicateForSamplesToday()

        let weightType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!
        let heightType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!

        let queryWeigth: HKCompletionHandle = {
            (weight, error) -> Void in

            guard let weight = weight else {
                completion(nil, error)

                return
            }

            let queryHeigth: HKCompletionHandle = {
                (height, error) -> Void in

                if height == nil {
                    completion(nil, error)

                    return;
                }

                var dateOfBirth: Date!

                do {

                    dateOfBirth = try self.healthStore!.dateOfBirth()

                } catch {

                    completion(nil, error)

                    return
                }

                var biologicalSexObjet: HKBiologicalSexObject!

                do {

                    biologicalSexObjet = try self.healthStore!.biologicalSex()

                } catch {

                    completion(nil, error)

                    return
                }

                // Once we have pulled all of the information without errors, calculate the user's total basal energy burn
                let basalEnergyButn: HKQuantity? = self.calculateBasalBurnTodayFromWeight(weight, height: height, dateOfBirth: dateOfBirth!, biologicalSex: biologicalSexObjet)

                completion(basalEnergyButn, nil)
            }

            if let healthStore = self.healthStore {

                healthStore.mostRecentQuantitySample(ofType: heightType, predicate: todayPredicate, completion: queryHeigth)
            }
        }

        if let healthStore = self.healthStore {
            healthStore.mostRecentQuantitySample(ofType: weightType, predicate: nil, completion: queryWeigth)
        }
    }

    private func calculateBasalBurnTodayFromWeight(_ weight: HKQuantity?, height: HKQuantity?, dateOfBirth: Date, biologicalSex: HKBiologicalSexObject) -> HKQuantity?
    {
        // Only calculate Basal Metabolic Rate (BMR) if we have enough information about the user
        guard let weight = weight, let height = height else {

            return nil
        }

        // Note the difference between calling +unitFromString: vs creating a unit from a string with
        // a given prefix. Both of these are equally valid, however one may be more convenient for a given
        // use case.
        let heightInCentimeters: Double = height.doubleValue(for: HKUnit(from:"cm"))
        let weightInKilograms: Double = weight.doubleValue(for: HKUnit.gramUnit(with: HKMetricPrefix.kilo))

        let nowDate = Date()
        let ageComponents: DateComponents = Calendar.current.dateComponents([Calendar.Component.year], from: dateOfBirth, to: nowDate)
        let ageInYears: Int = ageComponents.year!

        // BMR is calculated in kilocalories per day.
        let BMR: Double = self.calculateBMRFromWeight(weightInKilograms: weightInKilograms, height: heightInCentimeters, age: ageInYears, biologicalSex: biologicalSex.biologicalSex)

        // Figure out how much of today has completed so we know how many kilocalories the user has burned.
        let (startOfToday, endOfToday): (Date, Date) = self.datesFromToday()

        let secondsInDay: TimeInterval = endOfToday.timeIntervalSince(startOfToday)
        let percentOfDayComplete: Double = nowDate.timeIntervalSince(startOfToday) / secondsInDay

        let kilocaloriesBurned: Double = BMR * percentOfDayComplete

        let basalBurn = HKQuantity(unit: HKUnit.kilocalorie(), doubleValue: kilocaloriesBurned)

        return basalBurn
    }

/// Returns BMR value in kilocalories per day. Note that there are different ways of calculating the
    /// BMR. In this example we chose an arbitrary function to calculate BMR based on weight, height, age,
    /// and biological sex.
    private func calculateBMRFromWeight(weightInKilograms: Double, height heightInCentimeters: Double, age ageInYears: Int, biologicalSex: HKBiologicalSex) -> Double
    {
        var BMR: Double = 0

        if biologicalSex == .male {
            BMR = 66.0 + (13.8 * weightInKilograms) + (5.0 * heightInCentimeters) - (6.8 * Double(ageInYears))

            return BMR
        }

        BMR = 655 + (9.6 * weightInKilograms) + (1.8 * heightInCentimeters) - (4.7 * Double(ageInYears))

        return BMR
    }

I'm tried the sample app to fetch resting energy however still resting energy value shown in health app and sample app doesn't have same value.

Could any body tell me how to fetch resting energy or what is the calculation used by Health App to find resting energy?

It would be great if someone can give me some pointers on it, I'm pretty new to HealthKit.

Thanks.

Body:
It seems that Apple's sample is outdated. As of iOS 8 and watchOS 2 there's a call to retrieve this information in the same way that active calories are retrieved; simply change the identifier. Apple Documentation

HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.basalEnergyBurned)

Don't forget to include the additional permission to read this data as well.


问:
Why are Python lists implemented as dynamic arrays instead of ring buffers?
A list in Python is now implemented as dynamic array of pointers, so it's not suitable for insertion and deletion at the front end. However, ring buffer also supports O(1) indexing. It can also expand and shrink like a dynamic array to support O(1) amortized insertion and deletion at both end. Why didn't CPython choose this implementation, or what's the main disadvantage of it?

答:
With a ring buffer, you'd need some index transformation on every access, unless the start position happens to be at index 0. But even then, you'd have to check for the start position to be 0.

O(1) just means that the operation has fixed cost, but it doesn't tell you whether that fixed cost is high or low. With a dynamic array, the cost of accessing an element by index is as low as it can get: check the range, then access the item.

The Python FAQ on the topic doesn't discuss alternative implementation techniques, but it does mention accessing elements by index as an optimization target:
https://docs.python.org/3/faq/design.html#how-are-lists-implemented-in-cpython


问:
How to fix: This factory function only works once
This function only works once and then not again can someone tell me what I'm doing wrong?

```<code>from vpython import *
def create_cube(pos,size,front,back,left,right,bottom,top):
    c = [ pyramid(pos=pos-vector(0.5,0,0),size=size,color=left),
    pyramid(pos=pos+vector(0.5,0,0),size=size,color=right).rotate(angle=radians(180),axis=vector(0,1,0)),
    pyramid(pos=pos+vector(0,0,0.5),size=size,color=front).rotate(angle=radians(90),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0,0.5),size=size,color=back).rotate(angle=radians(270),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0.5,0),size=size,color=bottom).rotate(angle=radians(90),axis=vector(0,0,1)),
    pyramid(pos=pos+vector(0,0.5,0),size=size,color=top).rotate(angle=radians(270),axis=vector(0,0,1)),
    box(pos=pos,size = vector(0.9,0.9,0.9),color=color.black)]
    return compound(c)

topleftfrontcorner = create_cube(vector(-1,1,1),vector(0.5,0.90,0.90),color.red,color.black,color.blue,color.black,color.black,color.yellow)
topmiddlefrontside = create_cube(vector(0,0,0),vector(0.5,0.90,0.90),color.red,color.black,color.black,color.black,color.black,color.yellow)
</code>```

I expect this function to output a custom 'cube' every time I call it not just once.

答:
You should return c, and use compound on both topleftfrontcorner and topmiddlefrontside:

```<code>from vpython import *
def create_cube(pos,size,front,back,left,right,bottom,top):
    c = [ pyramid(pos=pos-vector(0.5,0,0),size=size,color=left),
    pyramid(pos=pos+vector(0.5,0,0),size=size,color=right).rotate(angle=radians(180),axis=vector(0,1,0)),
    pyramid(pos=pos+vector(0,0,0.5),size=size,color=front).rotate(angle=radians(90),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0,0.5),size=size,color=back).rotate(angle=radians(270),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0.5,0),size=size,color=bottom).rotate(angle=radians(90),axis=vector(0,0,1)),
    pyramid(pos=pos+vector(0,0.5,0),size=size,color=top).rotate(angle=radians(270),axis=vector(0,0,1)),
    box(pos=pos,size = vector(0.9,0.9,0.9),color=color.black)]
    return c

topleftfrontcorner = create_cube(vector(-1,1,1),vector(0.5,0.90,0.90),color.red,color.black,color.blue,color.black,color.black,color.yellow)
topmiddlefrontside = create_cube(vector(0,0,0),vector(0.5,0.90,0.90),color.red,color.black,color.black,color.black,color.black,color.yellow)
compound(topleftfrontcorner, topmiddlefrontside)
</code>```

Doing so gives me:

Maybe someone more familiar with vpython can explain more, but in general there's a difference between creating a cube and rendering a cube. The reason why you don't see two cubes in your snippet is that the program is still rendering the first cube (a blocking operation), and hasn't even evaluated the second function call. You can see that's the case by putting a print("hello!") between the two function calls; "hello!" never gets printed because the program is still busy rendering topleftfrontcorner.

In the updated code snippet, we construct two cubes, then render them at the same time.

Body:
This function only works once and then not again can someone tell me what I'm doing wrong?

from vpython import *
def create_cube(pos,size,front,back,left,right,bottom,top):
    c = [ pyramid(pos=pos-vector(0.5,0,0),size=size,color=left),
    pyramid(pos=pos+vector(0.5,0,0),size=size,color=right).rotate(angle=radians(180),axis=vector(0,1,0)),
    pyramid(pos=pos+vector(0,0,0.5),size=size,color=front).rotate(angle=radians(90),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0,0.5),size=size,color=back).rotate(angle=radians(270),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0.5,0),size=size,color=bottom).rotate(angle=radians(90),axis=vector(0,0,1)),
    pyramid(pos=pos+vector(0,0.5,0),size=size,color=top).rotate(angle=radians(270),axis=vector(0,0,1)),
    box(pos=pos,size = vector(0.9,0.9,0.9),color=color.black)]
    return compound(c)

topleftfrontcorner = create_cube(vector(-1,1,1),vector(0.5,0.90,0.90),color.red,color.black,color.blue,color.black,color.black,color.yellow)
topmiddlefrontside = create_cube(vector(0,0,0),vector(0.5,0.90,0.90),color.red,color.black,color.black,color.black,color.black,color.yellow)

I expect this function to output a custom 'cube' every time I call it not just once.

Body:
You should return c, and use compound on both topleftfrontcorner and topmiddlefrontside:

from vpython import *
def create_cube(pos,size,front,back,left,right,bottom,top):
    c = [ pyramid(pos=pos-vector(0.5,0,0),size=size,color=left),
    pyramid(pos=pos+vector(0.5,0,0),size=size,color=right).rotate(angle=radians(180),axis=vector(0,1,0)),
    pyramid(pos=pos+vector(0,0,0.5),size=size,color=front).rotate(angle=radians(90),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0,0.5),size=size,color=back).rotate(angle=radians(270),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0.5,0),size=size,color=bottom).rotate(angle=radians(90),axis=vector(0,0,1)),
    pyramid(pos=pos+vector(0,0.5,0),size=size,color=top).rotate(angle=radians(270),axis=vector(0,0,1)),
    box(pos=pos,size = vector(0.9,0.9,0.9),color=color.black)]
    return c

topleftfrontcorner = create_cube(vector(-1,1,1),vector(0.5,0.90,0.90),color.red,color.black,color.blue,color.black,color.black,color.yellow)
topmiddlefrontside = create_cube(vector(0,0,0),vector(0.5,0.90,0.90),color.red,color.black,color.black,color.black,color.black,color.yellow)
compound(topleftfrontcorner, topmiddlefrontside)

Doing so gives me:

Maybe someone more familiar with vpython can explain more, but in general there's a difference between creating a cube and rendering a cube. The reason why you don't see two cubes in your snippet is that the program is still rendering the first cube (a blocking operation), and hasn't even evaluated the second function call. You can see that's the case by putting a print("hello!") between the two function calls; "hello!" never gets printed because the program is still busy rendering topleftfrontcorner.

In the updated code snippet, we construct two cubes, then render them at the same time.


问:
how to set up Back button for Switch Navigator
I am developing a react native program I am using Switch Navigator inside it. but I want to know how to set up a back button for Switch Navigator. I don't want to use a stack navigator. here is my navigation page code </p>

```<code>            import createAnimatedSwitchNavigator from 'react-navigation-animated-switch';
            import {createAppContainer } from 'react-navigation';
            import { Transition } from 'react-native-reanimated';
            import React from 'react';

            import Login   from "./Login/Login";
            import SignUp  from './SignUp/SignUp';

            //====================================================

            //====================================================
            const Navigate = createAnimatedSwitchNavigator({

            Login:         {screen:Login},
            SignUp:        {screen:SignUp},

            },
            {
                transition: (
                <Transition.Together>
                    <Transition.Out
                    type="slide-left"
                    durationMs={200}
                    interpolation="easeIn"
                    />
                    <Transition.In type="fade" durationMs={300} />
                    </Transition.Together>
                ),
            }
            )

            export const AppContainer = createAppContainer(Navigate)
</code>```

答:
"The purpose of SwitchNavigator is to only ever show one screen at a time. By default, it does not handle back actions and it resets routes to their default state when you switch away. This is the exact behavior that we want from the authentication flow."

From React Navigation documentation: https://reactnavigation.org/docs/en/switch-navigator.html

SwitchNavigator was designed to handle authentication (login, logout and signup). After navigating away from an authentication screen you do not want the user to jump back to that screen. So SwitchNavigator removes that feature. If you want a back button or function use any navigator except for the SwitchNavigator.

"createAnimatedSwitchNavigator" is identical to createSwitchNavigator except for the animations. So it also does not have a back function.

Body:
I am developing a react native program I am using Switch Navigator inside it. but I want to know how to set up a back button for Switch Navigator. I don't want to use a stack navigator. here is my navigation page code

            import createAnimatedSwitchNavigator from 'react-navigation-animated-switch';
            import {createAppContainer } from 'react-navigation';
            import { Transition } from 'react-native-reanimated';
            import React from 'react';

            import Login   from "./Login/Login";
            import SignUp  from './SignUp/SignUp';

            //====================================================

            //====================================================
            const Navigate = createAnimatedSwitchNavigator({

            Login:         {screen:Login},
            SignUp:        {screen:SignUp},

            },
            {
                transition: (
                <Transition.Together>
                    <Transition.Out
                    type="slide-left"
                    durationMs={200}
                    interpolation="easeIn"
                    />
                    <Transition.In type="fade" durationMs={300} />
                    </Transition.Together>
                ),
            }
            )

            export const AppContainer = createAppContainer(Navigate)


问:
TVN_SELCHANGING not received
I have a WTL81 app. CMainFrame has a child CPaneContainer, that has a child window CTreeViewCtrl. The problem is CTreeViewCtrl doesn't receive TVN_SELCHANGING message.

I have "spied" CTreeViewCtrl and his parent (CPaneContainer) and no notification code is received.

CMainFrame is implemented from public CFrameWindowImpl<CMainFrame>

CPaneContainer is implemented like this

```<code>class PaneContainerReflectNotif : public CPaneContainer
{
    BEGIN_MSG_MAP(PaneContainerReflectNotif)
        CHAIN_MSG_MAP(CPaneContainer)
        REFLECT_NOTIFICATIONS()
    END_MSG_MAP()
};
</code>```

Tree is implemented like this

```<code>class MyTreeView :
    public CWindowImpl<CatalogTreeView, CTreeViewCtrl>,
    public CCustomDraw<CatalogTreeView>,
    public CTheme

   ...

BEGIN_MSG_MAP_EX(MyTreeView )
    MSG_WM_CREATE(OnCreate)
    MSG_WM_DESTROY(OnDestroy)
    REFLECTED_NOTIFY_CODE_HANDLER_EX(NM_DBLCLK, OnDblClick)
    REFLECTED_NOTIFY_CODE_HANDLER_EX(TVN_ITEMEXPANDING, OnItemExpanding)
    REFLECTED_NOTIFY_CODE_HANDLER_EX(TVN_SELCHANGING, OnSelChanged)
</code>```

OnDblClick - works fine

OnItemExpanding - works fine

OnSelChanged -  doesn't work

any ideas on what could be the problem ?

答: Solved. My problem was that treeview was multi-selct and that kind of tree doesn't send TVN_SELCHANGING notifications</p>

Title: TVN_SELCHANGING not received

Body:
I have a WTL81 app. CMainFrame has a child CPaneContainer, that has a child window CTreeViewCtrl. The problem is CTreeViewCtrl doesn't receive TVN_SELCHANGING message.

I have "spied" CTreeViewCtrl and his parent (CPaneContainer) and no notification code is received.

CMainFrame is implemented from public CFrameWindowImpl<CMainFrame>

CPaneContainer is implemented like this

class PaneContainerReflectNotif : public CPaneContainer
{
    BEGIN_MSG_MAP(PaneContainerReflectNotif)
        CHAIN_MSG_MAP(CPaneContainer)
        REFLECT_NOTIFICATIONS()
    END_MSG_MAP()
};

Tree is implemented like this

class MyTreeView :
    public CWindowImpl<CatalogTreeView, CTreeViewCtrl>,
    public CCustomDraw<CatalogTreeView>,
    public CTheme

   ...

BEGIN_MSG_MAP_EX(MyTreeView )
    MSG_WM_CREATE(OnCreate)
    MSG_WM_DESTROY(OnDestroy)
    REFLECTED_NOTIFY_CODE_HANDLER_EX(NM_DBLCLK, OnDblClick)
    REFLECTED_NOTIFY_CODE_HANDLER_EX(TVN_ITEMEXPANDING, OnItemExpanding)
    REFLECTED_NOTIFY_CODE_HANDLER_EX(TVN_SELCHANGING, OnSelChanged)

OnDblClick - works fine

OnItemExpanding - works fine

OnSelChanged -  doesn't work

any ideas on what could be the problem ?


问:
How to use React Router to route to another url AND re-render page with NEW component?
In App.js, I have a button that if you click, should redirect users using React-Route to another URL, /landingpagehahaha, and should render a component called LandingPage. However, neither the URL is being changed in my browser nor the correct component being rendered. The behavior right now when you click the button is that the current page gets re-rendered, not the correct LandingPage component.

The React-Route logic is placed in a function called routeChange(). I put 2 alert() statements in it which get called, telling me that it is getting inside that function. However, nothing else changes.

I have tried using this.props.history.push("./LandingPage"); in routeChange() but it doesn't get past that statement. It appears like it behaves like response.json(), which returns from the function after it runs.

I have also tried using withRouter(), but I get a weird error that I can't call Route inside Router. I was unable to resolve that issue.

```<code>// Changes route
  routeChange() {
    alert("HELLO BEFORE");
    alert("HELLo");
    return (
      <div>
        <Route path="/landingpagehahaha" component={LandingPage} />;
      </div>
    );
  }

</code>```

```<code>// The button that is supposed to bring user to next page
<button onClick={this.routeChange}>Go To Next Page</button>
</code>```

答:
You need to return the Redirect component from your render function, or as use the history api to push the route into your navigation stack.
The first thing you should do, is move out the route declaration, and play it higher up in your component hierachy, you have to make sure the route declaration is rendered, when you're trying to go to the route.
Instead of using the history api, you could also use the Redirect component provided by react-router. I've made a small example here.
https://codesandbox.io/s/bold-paper-kxcri</p>

Body:
In App.js, I have a button that if you click, should redirect users using React-Route to another URL, /landingpagehahaha, and should render a component called LandingPage. However, neither the URL is being changed in my browser nor the correct component being rendered. The behavior right now when you click the button is that the current page gets re-rendered, not the correct LandingPage component.

The React-Route logic is placed in a function called routeChange(). I put 2 alert() statements in it which get called, telling me that it is getting inside that function. However, nothing else changes.

I have tried using this.props.history.push("./LandingPage"); in routeChange() but it doesn't get past that statement. It appears like it behaves like response.json(), which returns from the function after it runs.

I have also tried using withRouter(), but I get a weird error that I can't call Route inside Router. I was unable to resolve that issue.

// Changes route
  routeChange() {
    alert("HELLO BEFORE");
    alert("HELLo");
    return (

        <Route path="/landingpagehahaha" component={LandingPage} />;

    );
  }

// The button that is supposed to bring user to next page
<button onClick={this.routeChange}>Go To Next Page</button>


问:
What is the correct way to layer if statements in order to get the desired results
[enter image description here]

IMAGE 2 (results)
enter image description here

2I'm working with data manipulation in csvs using python + pandas.
Example #s

PL       T

0.569999695

0.960002899

1.729999542

1.590000153

1.450000763

1.530002594
1.530002594

1.770000458

0.890003204

0.490001678

1.11000061

1.340000153

2.390003204
2.390003204

2.470001221

2.760002136

3.200000763

2.880001068

2.479999542
2.479999542

3.100002289

1.269996643

1.269996643

1.590000153

2.13999939

I have used if statements in the past however this one is very specific and I can't seem to get the syntax working correctly.

If you look at the code I want column 'T' to be calculated like this
there are a few numbers filled into the row already from previous code and the rest are blank.

The code working will hypothetically run through the rows in column t.

The first rows are mostly blank so it will skip those until it hits a row that has a number in it. if(df['T'].iat[x-1] != "")

once it hits the row with a number in it the script will check the logical (if the cell in the row next to it is greater than the cell above it)(if

```<code>df['PL'].iat[x] > df['PL'].iat[x-1]
</code>```

if that logical is true it will print the cell from next to it over into the column. df['T'].iat[x] = df['PL'].iat[x]
and if the logical is false then the cell stays blank

I think the real issue is how it iterates after that step. Right now I think its going back and just checking the last if statement again but I want it to iterate through all of them for each row.

It should read the column above to see if it is blank or filled in and then go through the if statements again only printing a number when all are met.

I have tried multiple arrangements as well as using and/or statements. I just can't seem to get it to print the right results.

```<code>

import pandas as pd
import csv

df=pd.read_csv(filename)

len1 = len(df)

for x in range(len3):

       if (df['T'].iat[x-1] != ""):

                if(df['T'].iat[x] == ""):

                    if (df['PL'].iat[x] > df['PL'].iat[x-1]):

                        df['T'].iat[x] = df['PL'].iat[x]
</code>```

The code displays no error messages however it is not printing the right results. Please let me know if I can explain it any better or if anyone has any ideas. Thanks!

答:
What is df?
if df is a dictionary like object of 2 elements, T and PL, then len(df) will return 2.

perhaps you have meant len(df["T"]) or len(df["PL"])?

Body:
[enter image description here]

IMAGE 2 (results)
enter image description here

2I'm working with data manipulation in csvs using python + pandas.
Example #s

PL       T

0.569999695

0.960002899

1.729999542

1.590000153

1.450000763

1.530002594
1.530002594

1.770000458

0.890003204

0.490001678

1.11000061

1.340000153

2.390003204
2.390003204

2.470001221

2.760002136

3.200000763

2.880001068

2.479999542
2.479999542

3.100002289

1.269996643

1.269996643

1.590000153

2.13999939

I have used if statements in the past however this one is very specific and I can't seem to get the syntax working correctly.

If you look at the code I want column 'T' to be calculated like this
there are a few numbers filled into the row already from previous code and the rest are blank.

The code working will hypothetically run through the rows in column t.

The first rows are mostly blank so it will skip those until it hits a row that has a number in it. if(df['T'].iat[x-1] != "")

once it hits the row with a number in it the script will check the logical (if the cell in the row next to it is greater than the cell above it)(if

df['PL'].iat[x] > df['PL'].iat[x-1]

if that logical is true it will print the cell from next to it over into the column. df['T'].iat[x] = df['PL'].iat[x]
and if the logical is false then the cell stays blank

I think the real issue is how it iterates after that step. Right now I think its going back and just checking the last if statement again but I want it to iterate through all of them for each row.

It should read the column above to see if it is blank or filled in and then go through the if statements again only printing a number when all are met.

I have tried multiple arrangements as well as using and/or statements. I just can't seem to get it to print the right results.

import pandas as pd
import csv

df=pd.read_csv(filename)

len1 = len(df)

for x in range(len3):

       if (df['T'].iat[x-1] != ""):

                if(df['T'].iat[x] == ""):

                    if (df['PL'].iat[x] > df['PL'].iat[x-1]):

                        df['T'].iat[x] = df['PL'].iat[x]

The code displays no error messages however it is not printing the right results. Please let me know if I can explain it any better or if anyone has any ideas. Thanks!


问:
Pass variable to Google Custom Search Engine
Is it possible to pass a search variable into the Google Custom Search Engine that I have embedded on my website? I can get the search engine to work, but I can't pass it a term via POST (it's coming from a search button on other pages of the website)

I tried to hack the code I found here: http://code.google.com/apis/ajax/playground/?exp=search#hello_world

And this is what I have so far... ($q is the term I am passing to it)

```

Thanks

答:
This is to help anyone using PHP trying to accomplish this same goal. The example above uses...

```<code>customSearchControl.execute("$q");
</code>```

to read the parameter being passes in. On a PHP site you would use...

```<code>customSearchControl.execute("<?php echo $_POST['your_paramter_name_here'];?>");
</code>```

You could use $_GET or $_REQUEST if your parameter is not in the post.

Of course you should should sanitize the input first.  Something like this is pretty weak but it's a start...

```<code>customSearchControl.execute("<?php echo htmlentities( trim( $_POST['your_paramter_name_here'] ), ENT_QUOTES );?>");
</code>```

Body:
Is it possible to pass a search variable into the Google Custom Search Engine that I have embedded on my website? I can get the search engine to work, but I can't pass it a term via POST (it's coming from a search button on other pages of the website)

I tried to hack the code I found here: http://code.google.com/apis/ajax/playground/?exp=search#hello_world

And this is what I have so far... ($q is the term I am passing to it)

Thanks

Body:
This is to help anyone using PHP trying to accomplish this same goal. The example above uses...

customSearchControl.execute("$q");

to read the parameter being passes in. On a PHP site you would use...

customSearchControl.execute("<?php echo $_POST['your_paramter_name_here'];?>");

You could use $_GET or $_REQUEST if your parameter is not in the post.

Of course you should should sanitize the input first.  Something like this is pretty weak but it's a start...

customSearchControl.execute("<?php echo htmlentities( trim( $_POST['your_paramter_name_here'] ), ENT_QUOTES );?>");


问:
Conda environments not showing up in Jupyter Notebook
I installed Anaconda (with Python 2.7), and installed Tensorflow in an environment called tensorflow. I can import Tensorflow successfully in that environment.

The problem is that Jupyter Notebook does not recognize the new environment I just created. No matter I start Jupyter Notebook from the GUI Navigator or from the command line within the tensorflow env, there is only one kernel in the menu called Python [Root], and Tensorflow cannot be imported. Of course, I clicked on that option multiple times, saved file, re-opened, but these did not help.

Strangely, I can see the two environments when I open the Conda tab on the front page of Jupyter. But when I open the Files tab, and try to new a notebook, I still end up with only one kernel.

I looked at this question:
Link Conda environment with Jupyter Notebook
But there isn't such a directory as ~/Library/Jupyter/kernels on my computer! This Jupyter directory only has one sub-directory called runtime.

I am really confused. Are Conda environments supposed to become kernels automatically? (I followed https://ipython.readthedocs.io/en/stable/install/kernel_install.html to manually set up the kernels, but was told that ipykernel was not found.)

答:
The nb_conda_kernels package is the best way to use jupyter with conda. With minimal dependencies and configuration, it allows you to use other conda environments from a jupyter notebook running in a different environment. Quoting its documentation:

Installation

This package is designed to be managed solely using conda. It should be installed in the environment from which you run Jupyter Notebook or JupyterLab. This might be your base conda environment, but it need not be. For instance, if the environment  notebook_env contains the notebook package, then you would run

conda install -n notebook_env nb_conda_kernels

Any other environments you wish to access in your notebooks must have an appropriate kernel package installed. For instance, to access a Python environment, it must have the ipykernel package; e.g.

conda install -n python_env ipykernel

To utilize an R environment, it
  must have the r-irkernel package; e.g.

conda install -n r_env r-irkernel

For other languages, their corresponding kernels must be installed.

Then all you need to do is start the jupyter notebook server:

```<code>conda activate notebook_env  # only needed if you are not using the base environment for the server
# conda install jupyter # in case you have not installed it already
jupyter
</code>```

Despite the plethora of answers and @merv's efforts to improve them, it still hard to find a good one. I made this one CW, so please vote it to the top or improve it!

Body:
The nb_conda_kernels package is the best way to use jupyter with conda. With minimal dependencies and configuration, it allows you to use other conda environments from a jupyter notebook running in a different environment. Quoting its documentation:

Installation

This package is designed to be managed solely using conda. It should be installed in the environment from which you run Jupyter Notebook or JupyterLab. This might be your base conda environment, but it need not be. For instance, if the environment  notebook_env contains the notebook package, then you would run

conda install -n notebook_env nb_conda_kernels

Any other environments you wish to access in your notebooks must have an appropriate kernel package installed. For instance, to access a Python environment, it must have the ipykernel package; e.g.

conda install -n python_env ipykernel

To utilize an R environment, it
  must have the r-irkernel package; e.g.

conda install -n r_env r-irkernel

For other languages, their corresponding kernels must be installed.

Then all you need to do is start the jupyter notebook server:

conda activate notebook_env  # only needed if you are not using the base environment for the server
# conda install jupyter # in case you have not installed it already
jupyter

Despite the plethora of answers and @merv's efforts to improve them, it still hard to find a good one. I made this one CW, so please vote it to the top or improve it!


问:
Load Region On Application Startup
I'm having some trouble gaining a working understanding of how Region Navigation works in Prism. I'm trying to create an MVVM based app that loads a main window, and displays a view generated by a login form. After the login form is submitted, I then want to navigate to a new UserControl. I'd like to know if this is also possible without using modules, however for the current implementation, it's modular.

With this current code, the menu bar with a button displays, but not the Login view.

Main Module

App.xaml.cs

```<code>protected override Window CreateShell()
        {
           return Container.Resolve<MainWindow>();
        }

protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {

        }

protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            moduleCatalog.AddModule<LoginModule.ModuleLoginModule>();
        }
</code>```

MainWindow.xaml:

```<code><Window x:Class="PrismMVVM.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        xmlns:local="clr-namespace:PrismMVVM"
        mc:Ignorable="d"

        Title="PrismMVVM" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="10*"/>
        </Grid.RowDefinitions>
        <DockPanel Grid.Row="0">
            <Button Content="Code is Poetry" HorizontalAlignment="Left" Width="Auto"/>
        </DockPanel>
        <ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegion">
        </ContentControl>
    </Grid>
</Window>
</code>```

MainWindowViewModel.cs

```<code>namespace PrismMVVM.ViewModels
{
    class MainWindowViewModel : BindableBase
    {
        public IRegionManager _regionManager;
        public MainWindowViewModel(IRegionManager regionManager)
        {
            _regionManager = regionManager;
            regionManager.RequestNavigate("LoginRegion", "Login");
        }
    }
}
</code>```

Login Module

ModuleLoginModule.cs:

```<code>namespace LoginModule
{
    public class ModuleLoginModule : IModule
    {
        public void OnInitialized(IContainerProvider containerProvider)
        {
            var regionManager = containerProvider.Resolve<IRegionManager>();
            regionManager.RegisterViewWithRegion("LoginRegion", typeof(Login));
        }

        public void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<Login>();
        }
    }
}
</code>```

Login.xaml:

```<code><UserControl x:Class="LoginModule.Views.Login"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:LoginModule.Views"
             xmlns:prism="http://prismlibrary.com/"
             prism:ViewModelLocator.AutoWireViewModel="True"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid Background="White" prism:RegionManager.RegionName="LoginRegion">
        <StackPanel Panel.ZIndex="1" Margin="150">
            <TextBox HorizontalAlignment="Center" VerticalAlignment="Center">Text</TextBox>
            <PasswordBox HorizontalAlignment="Center" VerticalAlignment="Center"/>
            <Button Background="LightBlue" Content="Login" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </StackPanel>

        <Rectangle Panel.ZIndex="0" HorizontalAlignment="Center" VerticalAlignment="Center" Fill="LightGray" Height="300" Width="400" />
    </Grid>
</UserControl>

</code>```

答:
I'd like to know if this is also possible without using modules

For sure it is. Modules are completely optional, you can do all the registrations from the bootstrapper / PrismApplication, if you like.

There's nothing wrong with something like this:

```<code>public class MyApplication : PrismApplication
{
    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterForNavigation<Login>();
    }
}

internal class MainWindowViewModel
{
    public MainWindowViewModel( IRegionManager regionManager )
    {
        regionManager.RequestNavigate( "ContentRegion", "Login" );
    }
}
</code>```

Title: Load Region On Application Startup

Body:
I'm having some trouble gaining a working understanding of how Region Navigation works in Prism. I'm trying to create an MVVM based app that loads a main window, and displays a view generated by a login form. After the login form is submitted, I then want to navigate to a new UserControl. I'd like to know if this is also possible without using modules, however for the current implementation, it's modular.

With this current code, the menu bar with a button displays, but not the Login view.

Main Module

App.xaml.cs

protected override Window CreateShell()
        {
           return Container.Resolve<MainWindow>();
        }

protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {

        }

protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            moduleCatalog.AddModule<LoginModule.ModuleLoginModule>();
        }

MainWindow.xaml:

<Window x:Class="PrismMVVM.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        xmlns:local="clr-namespace:PrismMVVM"
        mc:Ignorable="d"

        Title="PrismMVVM" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="10*"/>
        </Grid.RowDefinitions>
        <DockPanel Grid.Row="0">
            <Button Content="Code is Poetry" HorizontalAlignment="Left" Width="Auto"/>
        </DockPanel>
        <ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegion">
        </ContentControl>
    </Grid>
</Window>

MainWindowViewModel.cs

namespace PrismMVVM.ViewModels
{
    class MainWindowViewModel : BindableBase
    {
        public IRegionManager _regionManager;
        public MainWindowViewModel(IRegionManager regionManager)
        {
            _regionManager = regionManager;
            regionManager.RequestNavigate("LoginRegion", "Login");
        }
    }
}

Login Module

ModuleLoginModule.cs:

namespace LoginModule
{
    public class ModuleLoginModule : IModule
    {
        public void OnInitialized(IContainerProvider containerProvider)
        {
            var regionManager = containerProvider.Resolve<IRegionManager>();
            regionManager.RegisterViewWithRegion("LoginRegion", typeof(Login));
        }

        public void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<Login>();
        }
    }
}

Login.xaml:

<UserControl x:Class="LoginModule.Views.Login"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:LoginModule.Views"
             xmlns:prism="http://prismlibrary.com/"
             prism:ViewModelLocator.AutoWireViewModel="True"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid Background="White" prism:RegionManager.RegionName="LoginRegion">
        <StackPanel Panel.ZIndex="1" Margin="150">
            <TextBox HorizontalAlignment="Center" VerticalAlignment="Center">Text</TextBox>
            <PasswordBox HorizontalAlignment="Center" VerticalAlignment="Center"/>
            <Button Background="LightBlue" Content="Login" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </StackPanel>

        <Rectangle Panel.ZIndex="0" HorizontalAlignment="Center" VerticalAlignment="Center" Fill="LightGray" Height="300" Width="400" />
    </Grid>
</UserControl>

Body:
I'd like to know if this is also possible without using modules

For sure it is. Modules are completely optional, you can do all the registrations from the bootstrapper / PrismApplication, if you like.

There's nothing wrong with something like this:

public class MyApplication : PrismApplication
{
    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterForNavigation<Login>();
    }
}

internal class MainWindowViewModel
{
    public MainWindowViewModel( IRegionManager regionManager )
    {
        regionManager.RequestNavigate( "ContentRegion", "Login" );
    }
}


问:
How to implement routing from and to root (index.js) in react with redux
I'm programming a react server webpage, trying to redirect from index.js (i.e: localhost:3000) to Login page: (localhost:3000/login), and from login to index (in case of failed login). What do I need to write in index.js and login.js?

This is for a react based app, using also redux framework. I've tried a few ways including setting up a BrowserRouter etc. All won't really do the redirecting.

My current code is this:

in index.js:

```<code>class Index extends Component {
    static getInitialProps({store, isServer, pathname, query}) {
    }

    render() {
        console.log(this.props);
        //const hist = createMemoryHistory();
        if (!this.props.isLoggedIn){
            return(<Switch><Route exact path = "/login"/></Switch>)
        }
                else{...}
</code>```

in login.js:

```<code>render() {
        console.log(this.props);
        if (fire.auth().currentUser != null) {
            var db = fire.firestore();
            db.collection("users").doc(fire.auth().currentUser.uid).get().then((doc) => {
                this.props.dispatch({ type: 'LOGIN', user: doc.data() });
            })
        }
        const { isLoggedIn } = this.props
        console.log(isLoggedIn)

        if (isLoggedIn) return <Redirect to='/' />
</code>```

I except the root to redirect to login if no session is on, and login to redirect to root once there is a successful login.
I am currently getting "You should not use <Switch> outside a <Router>" at index (I have tried to wrap with BrowserRouter, ServerRouter, Router. the first says it needs DOM history. adding history does not change error. two others do not error but are blank display on browser.)
and "ReferenceError: Redirect is not defined" at login.

Any help will be appreciated.

答:
you can use a HOC (Higher-Order Components)
something like this</p>

```<code>export default ChildComponent => {
    class ComposedComponent extends Component {

        componentWillMount() {
            this.shouldNavigateAway();
        }
        componentWillUpdate() {
            this.shouldNavigateAway();
        }
        shouldNavigateAway() {
            if (!this.props.authenticated) {
                this.props.history.push('/')
            }
        }

        render() {
            return <ChildComponent {...this.props} />
        }
    }
}
</code>```

Body:
I'm programming a react server webpage, trying to redirect from index.js (i.e: localhost:3000) to Login page: (localhost:3000/login), and from login to index (in case of failed login). What do I need to write in index.js and login.js?

This is for a react based app, using also redux framework. I've tried a few ways including setting up a BrowserRouter etc. All won't really do the redirecting.

My current code is this:

in index.js:

class Index extends Component {
    static getInitialProps({store, isServer, pathname, query}) {
    }

    render() {
        console.log(this.props);
        //const hist = createMemoryHistory();
        if (!this.props.isLoggedIn){
            return(<Switch><Route exact path = "/login"/></Switch>)
        }
                else{...}

in login.js:

render() {
        console.log(this.props);
        if (fire.auth().currentUser != null) {
            var db = fire.firestore();
            db.collection("users").doc(fire.auth().currentUser.uid).get().then((doc) => {
                this.props.dispatch({ type: 'LOGIN', user: doc.data() });
            })
        }
        const { isLoggedIn } = this.props
        console.log(isLoggedIn)

        if (isLoggedIn) return <Redirect to='/' />

I except the root to redirect to login if no session is on, and login to redirect to root once there is a successful login.
I am currently getting "You should not use <Switch> outside a <Router>" at index (I have tried to wrap with BrowserRouter, ServerRouter, Router. the first says it needs DOM history. adding history does not change error. two others do not error but are blank display on browser.)
and "ReferenceError: Redirect is not defined" at login.

Any help will be appreciated.

Body:
you can use a HOC (Higher-Order Components)
something like this

export default ChildComponent => {
    class ComposedComponent extends Component {

        componentWillMount() {
            this.shouldNavigateAway();
        }
        componentWillUpdate() {
            this.shouldNavigateAway();
        }
        shouldNavigateAway() {
            if (!this.props.authenticated) {
                this.props.history.push('/')
            }
        }

        render() {
            return <ChildComponent {...this.props} />
        }
    }
}


问:
Python Flask jinja2 include page
I'm having a problem with include in jinja using Flask:
I have a list page with Actions buttons like this :

The black button has href  and toggle a div (show/hide) using JQuery the graph page into div section (see below)

```<code>...
...
...

<a href="/cycle/graph/{{account.id}}/{{account.aid}}/{{c.id}}" class="btn btn-dark btn-circle"
                           data-toggle="tooltip" title="Graph" id="sh_chart"><i class="fas fa-chart-line"></i></a>

...
...
...
<div id="chart" style="display:none">
    {% include "/cycle/chart.html" %}
</div>
{% endblock %}
</code>```

and here is my JQuery :

```<code>$("#account_detail").on("click", "#sh_chart", function() {
        $("#chart").toggle();

        var current_row = $(this).closest('tr')
        var cid = current_row.find('td:eq(0)').text();
        $("p#chart_cid").text(cid);

        $("#chart").load('/cycle/chart');
    });
</code>```

When clicking I got chart page in a new page, this is the problem.
Do you have any idea how to include this chart in the same page ?

Thank you

end point :

```<code>@bpGraph.route('/graph/<string:id>/<string:aid>/<string:cid>', methods=['GET', 'POST'])
@is_log_in
def getGraph(id, aid, cid):
    graph = pygal.Line()
    graph.title = 'Evolution of Cycle'
    # prepare detail for Charting
    xlabel = []
    balance = []
    detail = list(get_cycle_detail_by_date(id, aid, cid))
    for d in detail:
        for dd in d['details']:
            xlabel.append(dd['create_date'])
            balance.append(dd['balance'])

    graph.x_labels = xlabel
    graph.add('Balance', balance)
    graph_data = graph.render_data_uri()

    return render_template('cycle/chart.html', detail=graph_data)
</code>```

答:
Create an endpoint that returns the rendered HTML, and then load it using JavaScript (XHR) when user clicks #account_detail button.

Flask example:

@app.route('/chart')
def chart():
    return render_template('chart.html')
```

<p>JavaScript:</p>

```$("#account_detail").on("click", "#sh_chart", function() {
        $("#chart").toggle();

        var current_row = $(this).closest('tr')
        var cid = current_row.find('td:eq(0)').text();
        $("p#chart_cid").text(cid);

        $.get('/chart', function (data) {
            $('#chart').html(data);
        });

       // Edit, i guess you could also do it like this:
       // $('#chart').load('/chart');
    });
```

<p>HTML:</p>

<pre class="lang-html prettyprint-override"><code><div id="chart" style="display:none"></div>
</code>```

Title: Python Flask jinja2 include page

Body:
I'm having a problem with include in jinja using Flask:
I have a list page with Actions buttons like this :

The black button has href  and toggle a div (show/hide) using JQuery the graph page into div section (see below)

...
...
...

...
...
...

    {% include "/cycle/chart.html" %}

{% endblock %}

and here is my JQuery :

$("#account_detail").on("click", "#sh_chart", function() {
        $("#chart").toggle();

        var current_row = $(this).closest('tr')
        var cid = current_row.find('td:eq(0)').text();
        $("p#chart_cid").text(cid);

        $("#chart").load('/cycle/chart');
    });

When clicking I got chart page in a new page, this is the problem.
Do you have any idea how to include this chart in the same page ?

Thank you

end point :

@bpGraph.route('/graph/<string:id>/<string:aid>/<string:cid>', methods=['GET', 'POST'])
@is_log_in
def getGraph(id, aid, cid):
    graph = pygal.Line()
    graph.title = 'Evolution of Cycle'
    # prepare detail for Charting
    xlabel = []
    balance = []
    detail = list(get_cycle_detail_by_date(id, aid, cid))
    for d in detail:
        for dd in d['details']:
            xlabel.append(dd['create_date'])
            balance.append(dd['balance'])

    graph.x_labels = xlabel
    graph.add('Balance', balance)
    graph_data = graph.render_data_uri()

    return render_template('cycle/chart.html', detail=graph_data)

Body:
Create an endpoint that returns the rendered HTML, and then load it using JavaScript (XHR) when user clicks #account_detail button.

Flask example:

@app.route('/chart')
def chart():
    return render_template('chart.html')

JavaScript:

$("#account_detail").on("click", "#sh_chart", function() {
        $("#chart").toggle();

        var current_row = $(this).closest('tr')
        var cid = current_row.find('td:eq(0)').text();
        $("p#chart_cid").text(cid);

        $.get('/chart', function (data) {
            $('#chart').html(data);
        });

       // Edit, i guess you could also do it like this:
       // $('#chart').load('/chart');
    });

HTML:

<div id="chart" style="display:none"></div>


问:
Take care my Linux Memory Usage Summary in console
I recently saw my AWS EC2 instance's states at SSH helper program (Not a putty program).

I saw below.

```<code>[centos@ip-172-31-xx-xx ~]$ free -h
             total       used       free     shared    buffers     cached
Mem:          1.8G       1.0G       869M       144K       137M       267M
-/+ buffers/cache:       600M       1.2G
Swap:           0B         0B         0B
</code>```

I understand buffers and cached usage are reserved usage, so it is empty usage. But, I didn't understand this.

-/+ buffers/cache:       600M       1.2G

What does it mean?

答:
As an alternative look at the contents of: /proc/meminfo

For example:

grep MemAvailable /proc/meminfo

and:

cat /proc/meminfo

Notice that MemAvailable is only available in modern Linux kernels (not RHEL/CentOS 6 unless you run it with a newer kernel, Like Oracle Unbreakable Linux does)

For fun and education look also at: https://www.linuxatemyram.com/

For a more convenient info on your systems resource usage you may be interested in something like atop: https://haydenjames.io/use-atop-linux-server-performance-analysis/ or one of the other top tools like these: https://haydenjames.io/alternatives-top-htop/

I'm just no big fan of free so I avoid it like the plague ;-)

Body:
I recently saw my AWS EC2 instance's states at SSH helper program (Not a putty program).

I saw below.

[centos@ip-172-31-xx-xx ~]$ free -h
             total       used       free     shared    buffers     cached
Mem:          1.8G       1.0G       869M       144K       137M       267M
-/+ buffers/cache:       600M       1.2G
Swap:           0B         0B         0B

I understand buffers and cached usage are reserved usage, so it is empty usage. But, I didn't understand this.

-/+ buffers/cache:       600M       1.2G

What does it mean?


答:
Sample input and expected results would help, as it is I'm not really sure I know what your looking for.

If your just matching on one pattern you might be able to split the string:

```<code>my $string = "text\n1\ttest\n2\tend\n";
my @matches = split /^(\d+)\t/m, $string;
shift @matches; # remove the text before the first number
print "[$_]\n" for @matches;

__END__
Output:
[1]
[test
]
[2]
[end
]
</code>```

If your matching multiple patterns Perl has special variables that can let you find where a match starts and finishes. Which can be used to extract what was between two matches.

```<code>use English qw(-no_match_vars);

my $string = "1\ttestEND\n2\ttextEND\n";
if ($string =~ /^\d+\t/) {
    my $last_match_end = $LAST_MATCH_END[0];

    if ($string =~ /END/cg) {
        my $last_match_start = $LAST_MATCH_START[0];
        my $len = $last_match_start - $last_match_end;
        print substr($string, $last_match_end, $len) . "\n"
    }
}
__END__
Output:
test
</code>```

Title: Regex - match up to next match

Body:
I would like to iterate matches over a text, the blocks I want to match start with a number then a tab character.

My beginning match is ^\d+\t, but is there a way to indicate that I want all text including this match up until the next match?

Input data:

1       111.111.111.111
111.111.111.111
                    Host IP     111.111.111.111
111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow
2       111.111.111.111
111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow
3       111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111
111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow
4       111.111.111.111
111.111.111.111
111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow

I'm using Perl.

Body:
Sample input and expected results would help, as it is I'm not really sure I know what your looking for.

If your just matching on one pattern you might be able to split the string:

my $string = "text\n1\ttest\n2\tend\n";
my @matches = split /^(\d+)\t/m, $string;
shift @matches; # remove the text before the first number
print "[$_]\n" for @matches;

__END__
Output:
[1]
[test
]
[2]
[end
]

If your matching multiple patterns Perl has special variables that can let you find where a match starts and finishes. Which can be used to extract what was between two matches.

use English qw(-no_match_vars);

my $string = "1\ttestEND\n2\ttextEND\n";
if ($string =~ /^\d+\t/) {
    my $last_match_end = $LAST_MATCH_END[0];

    if ($string =~ /END/cg) {
        my $last_match_start = $LAST_MATCH_START[0];
        my $len = $last_match_start - $last_match_end;
        print substr($string, $last_match_end, $len) . "\n"
    }
}
__END__
Output:
test


问:
"Connection is already closed." error with python WebSocket client
I've been trying to use the python websocket-client module to receive and store continuous updates from an exchange. Generally, the script will run smoothly for a day or so before raising the following error: websocket._exceptions.WebSocketConnectionClosedException: Connection is already closed.

I've looked at the websocket-client source code and apparently the error is being raised in line 92 by the code if not bytes_:. Furthermore, the WebSocketConnectionClosedException is supposed to be raised "If remote host closed the connection or some network error happened".

Can anybody tell me why this is happening, and what I could do to stop or handle it.

答:
Most likely, the remote host closed the connection. You cannot stop it. You can handle it by re-connecting.

People running web servers will implement automatic cleanup to get rid of potentially stale connections. Closing a connection that's been open for 24 hours sounds like a sensible approach. And there's no harm done, because if the client is still interested, it can re-establish the connection. That's also useful to re-authenticate the client, if authentication is required.

On second thought, it might be a network disconnect as well. Some DSL providers used to disconnect and re-assign a new IP every 24 hours, to prevent users from running permanent services on temporarily assigned IP addresses. Don't know if they still do that.


问:
current page refresh problem in framework7
Framework7 version: Framework7 3.1.1

I am using component template

I tried solutions but current page is not refresh

Solution 1:

```<code>app.on('pageInit', function (page) {
  if (page.name === 'single-question') {
  var mainView = app.view.create('#single-page');
  mainView.router.refreshPage();
}
</code>```

when I console page name and click to open single-page it returns “null” and then app is not working without refresh.

Solution: 2

```<code>router.navigate(router.currentRoute.url, {
  reloadCurrent: true,
  ignoreCache: true,
});
</code>```

But I got error: “Uncaught (in promise) ReferenceError: currentRoute is not defined”

I aslo try

```<code>Cache:false,
cacheDuration: 0,
template7Pages = false
</code>```

but still facing same problem.

答:
You can refresh the whole page using this</p>

```<code>setTimeout("location.reload(true);",1000);
</code>```

Body:
Framework7 version: Framework7 3.1.1

I am using component template

I tried solutions but current page is not refresh

Solution 1:

app.on('pageInit', function (page) {
  if (page.name === 'single-question') {
  var mainView = app.view.create('#single-page');
  mainView.router.refreshPage();
}

when I console page name and click to open single-page it returns “null” and then app is not working without refresh.

Solution: 2

router.navigate(router.currentRoute.url, {
  reloadCurrent: true,
  ignoreCache: true,
});

But I got error: “Uncaught (in promise) ReferenceError: currentRoute is not defined”

I aslo try

Cache:false,
cacheDuration: 0,
template7Pages = false

but still facing same problem.

Body:
You can refresh the whole page using this

setTimeout("location.reload(true);",1000);


问:
Is there any way to change the radius of specific corner of Material design CardView
I am using material design in my android app and normally for changing the radius of the corner of card i use  app:cardCornerRadius, but this will change all the four corner of card. I want to change any specific corner of the card. I dont want to use drawable only for changing the corner. Is there any way through xml or programatically.

```<code> <com.google.android.material.card.MaterialCardView
        style="@style/Widget.MaterialComponents.CardView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/colorWhite"
        app:cardCornerRadius="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginStart="16dp" android:layout_marginEnd="16dp">
    <androidx.constraintlayout.widget.ConstraintLayout
            android:visibility="visible"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
</code>```

答:
I am not pretty sure about Material design cardview to have that functionality or not. But I don't think that default cardview have that kind of functionality so on behalf of that material cardview you can use

This Library (click here).

It is just my opinion may be there is another good solution for that.

Body:
I am using material design in my android app and normally for changing the radius of the corner of card i use  app:cardCornerRadius, but this will change all the four corner of card. I want to change any specific corner of the card. I dont want to use drawable only for changing the corner. Is there any way through xml or programatically.

 <com.google.android.material.card.MaterialCardView
        style="@style/Widget.MaterialComponents.CardView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/colorWhite"
        app:cardCornerRadius="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginStart="16dp" android:layout_marginEnd="16dp">
    <androidx.constraintlayout.widget.ConstraintLayout
            android:visibility="visible"
            android:layout_width="match_parent"
            android:layout_height="match_parent">