问:
2D character movement, map updating, position updating
I'm a beginner programmer. How do i make the map update in this code. How do i make the players position update? I wanted to make him move by incrementing one of the values [x][y], but how do i do that? Is the code below a good start?</p>

```<code>#include <windows.h>

int map[5][5]={
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0}};

int m_print(int x) {
    int i, j;
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {
            printf("%d     ", map[i][j]);
        }
        printf("\n");
    }
}

struct player {
    int pos[i][j];
    int show;
    int movement;
};

int map_update(int x) {

}

int p_show(int x) {

}

main() {
    int game_running = true;
}
</code>```

答:
First of all I have absolutely no idea about what you are trying to accompish. However I saw that you are a begginer with C and I thought of assembling a very quick example on something hopefully similar on what you are trying to do.

Some notes on the things that I had to fix from your code:

int pos[i][j]; in the player struct makes no sense, if you need an array as a struct parameter, setup a pointer there and make sure to allocate it somewhere in your code to fit your needs. I replaced it with some int parameters for keeping track of the old and current player position

The main function needs to run something

By default there are no true/false values in C. Not sure about your compiler and compilation flags, but from linux I did some typedefs for a bool macro (which is actually handled as an int) just to show you how typedefs can be used

The code that I made does some very basic stuff. At first I allocate a player using the struct that we defined. Then I setup his position to 0,0 and also set map[0][0]=1 to indicate that the player is there.

I setup a while loop with a very simple input method that scanfs for input characters from the console. The accepted characters are w,a,s,d. These are passed to the move_player method which based on the input updates the position of the player struct. Then the map_update method gets a player struct as an argument and updates the map accordingly to show the player's new position. Note that both methods accept struct pointers as arguments. Using pointers we just pass the reference (a memory address of the struct) and not the actual value (a copy of all the data of the struct). Doing otherwise, we would not be able to update the player data as easily.

Finally, I print out the player's position and the map just to show to the user where he is at.

```<code>Round 32
Move Player [w,a,s,d]: a
Player Position [4,2]
Game Map
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 1 0 0
</code>```

Now I know that you're probably overwhelmed with information but I found it a very good start for a new C programmer like you to start with so I decided to help (PS: Compiling this answer took longer than writing/updating the code). I'm probably not doing everything as efficiently as possible, but for a case like this I think it has sufficient stuff to keep you occupied for a while. Have fun!

Here is the code

```<code>//#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

typedef int bool;
#define TRUE  1
#define FALSE 0

int map[5][5]={
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0}};

int m_print() {
    int i, j;
    printf("Game Map\n");
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {
            printf("%d ", map[i][j]);
        }
        printf("\n");
    }
}

struct player {
    int old_pos_x;
    int old_pos_y;
    int pos_x;
    int pos_y;
    int show;
    int movement;
};

void map_update(struct player *p) {
    map[p->old_pos_x][p->old_pos_y] -= 1;
    map[p->pos_x][p->pos_y] += 1;
}

void move_player(struct player *p, char move){
    //Save current player state
    p->old_pos_x = p->pos_x;
    p->old_pos_y = p->pos_y;

    switch(move) {
        case 'w':
            p->pos_x -= 1;
            break;
        case 's':
            p->pos_x += 1;
            break;
        case 'd':
            p->pos_y += 1;
            break;
        case 'a':
            p->pos_y -= 1;
            break;
    }
    //Fit position to map

    //Rotate right
    p->pos_x %= 5;
    p->pos_y %= 5;

    if (p->pos_x < 0)
        p->pos_x = 4;
    if (p->pos_y < 0)
        p->pos_y = 4;
}

void p_show(struct player *p) {
    //Report Player position
    printf("Player Position [%d,%d]\n", p->pos_x, p->pos_y);
}

int main() {
    bool game_running = TRUE;

    //Initialize Game
    struct player p;
    //Set player properties
    p.pos_x = 0;
    p.pos_y = 0;

    //Manually add player to map
    map[0][0] = 1;

    int counter = 0;
    char button;
    while (TRUE) {
        printf("Round %d\n", counter);
        //Get input
        printf("Move Player [w,a,s,d]: ");
        scanf(" %c", &button);

        //Update player position
        move_player(&p, button);

        //Update map
        map_update(&p);

        //Report Player
        p_show(&p);
        //Show map
        m_print();
        counter++;
    }

    return 0;
}
</code>```

Body:
I'm a beginner programmer. How do i make the map update in this code. How do i make the players position update? I wanted to make him move by incrementing one of the values [x][y], but how do i do that? Is the code below a good start?

#include <windows.h>

int map[5][5]={
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0}};

int m_print(int x) {
    int i, j;
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {
            printf("%d     ", map[i][j]);
        }
        printf("\n");
    }
}

struct player {
    int pos[i][j];
    int show;
    int movement;
};

int map_update(int x) {

}

int p_show(int x) {

}

main() {
    int game_running = true;
}

Body:
First of all I have absolutely no idea about what you are trying to accompish. However I saw that you are a begginer with C and I thought of assembling a very quick example on something hopefully similar on what you are trying to do.

Some notes on the things that I had to fix from your code:

int pos[i][j]; in the player struct makes no sense, if you need an array as a struct parameter, setup a pointer there and make sure to allocate it somewhere in your code to fit your needs. I replaced it with some int parameters for keeping track of the old and current player position

The main function needs to run something

By default there are no true/false values in C. Not sure about your compiler and compilation flags, but from linux I did some typedefs for a bool macro (which is actually handled as an int) just to show you how typedefs can be used

The code that I made does some very basic stuff. At first I allocate a player using the struct that we defined. Then I setup his position to 0,0 and also set map[0][0]=1 to indicate that the player is there.

I setup a while loop with a very simple input method that scanfs for input characters from the console. The accepted characters are w,a,s,d. These are passed to the move_player method which based on the input updates the position of the player struct. Then the map_update method gets a player struct as an argument and updates the map accordingly to show the player's new position. Note that both methods accept struct pointers as arguments. Using pointers we just pass the reference (a memory address of the struct) and not the actual value (a copy of all the data of the struct). Doing otherwise, we would not be able to update the player data as easily.

Finally, I print out the player's position and the map just to show to the user where he is at.

Round 32
Move Player [w,a,s,d]: a
Player Position [4,2]
Game Map
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 1 0 0

Now I know that you're probably overwhelmed with information but I found it a very good start for a new C programmer like you to start with so I decided to help (PS: Compiling this answer took longer than writing/updating the code). I'm probably not doing everything as efficiently as possible, but for a case like this I think it has sufficient stuff to keep you occupied for a while. Have fun!

Here is the code

//#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

typedef int bool;
#define TRUE  1
#define FALSE 0

int map[5][5]={
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0}};

int m_print() {
    int i, j;
    printf("Game Map\n");
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {
            printf("%d ", map[i][j]);
        }
        printf("\n");
    }
}

struct player {
    int old_pos_x;
    int old_pos_y;
    int pos_x;
    int pos_y;
    int show;
    int movement;
};

void map_update(struct player *p) {
    map[p->old_pos_x][p->old_pos_y] -= 1;
    map[p->pos_x][p->pos_y] += 1;
}

void move_player(struct player *p, char move){
    //Save current player state
    p->old_pos_x = p->pos_x;
    p->old_pos_y = p->pos_y;

    switch(move) {
        case 'w':
            p->pos_x -= 1;
            break;
        case 's':
            p->pos_x += 1;
            break;
        case 'd':
            p->pos_y += 1;
            break;
        case 'a':
            p->pos_y -= 1;
            break;
    }
    //Fit position to map

    //Rotate right
    p->pos_x %= 5;
    p->pos_y %= 5;

    if (p->pos_x < 0)
        p->pos_x = 4;
    if (p->pos_y < 0)
        p->pos_y = 4;
}

void p_show(struct player *p) {
    //Report Player position
    printf("Player Position [%d,%d]\n", p->pos_x, p->pos_y);
}

int main() {
    bool game_running = TRUE;

    //Initialize Game
    struct player p;
    //Set player properties
    p.pos_x = 0;
    p.pos_y = 0;

    //Manually add player to map
    map[0][0] = 1;

    int counter = 0;
    char button;
    while (TRUE) {
        printf("Round %d\n", counter);
        //Get input
        printf("Move Player [w,a,s,d]: ");
        scanf(" %c", &button);

        //Update player position
        move_player(&p, button);

        //Update map
        map_update(&p);

        //Report Player
        p_show(&p);
        //Show map
        m_print();
        counter++;
    }

    return 0;
}


来源: stackexchange

问:
Loop through entire array while excluding an item
I have an array of items that I'd like to loop through and apply some code to, excluding one item (the clicked-on item).  I've tried using splice but I don't want to remove the array item, just skip over it.  In this case, I'm trying to remove a CSS class for each item, except the excluded one.

I've tried a few methods, using splice for one which isn't what I need.  I've also tried something like if (array[i] == 3 || (i - 1) = 2) { continue; else { .... } but can't seem to get that to work.

```<code>   var array = ["item1", "item2", "item3"];
   var i;
   for (i = 0; i < items.length; i++) {
       if(array[i] is the excluded one){
               skip over}
    else { $(items[i]).removeClass('class');
    }
</code>```

No error messages, just not working as expected.

答:
are the array items the id of the elements? - if so you need the id indicator ("#") in the code

```<code>$('#' + items[i]).removeClass('class')
</code>```

EDIT - i just noticed that your array is called"array", but in the else block you refer to it as items

```<code>   var items= ["item1", "item2", "item3"];
   var i;
   for (i = 0; i < items.length; i++) {
       if(items[i] is the excluded one){
               skip over}
    else { $('#' + items[i]).removeClass('class');
    }
</code>```

I still think that there is a better way to do this - but try making the names the same and see if that works.

ContentLicense: CC BY-SA 4.0

Body:
I have an array of items that I'd like to loop through and apply some code to, excluding one item (the clicked-on item).  I've tried using splice but I don't want to remove the array item, just skip over it.  In this case, I'm trying to remove a CSS class for each item, except the excluded one.

I've tried a few methods, using splice for one which isn't what I need.  I've also tried something like if (array[i] == 3 || (i - 1) = 2) { continue; else { .... } but can't seem to get that to work.

   var array = ["item1", "item2", "item3"];
   var i;
   for (i = 0; i < items.length; i++) {
       if(array[i] is the excluded one){
               skip over}
    else { $(items[i]).removeClass('class');
    }

No error messages, just not working as expected.

Body:
are the array items the id of the elements? - if so you need the id indicator ("#") in the code

$('#' + items[i]).removeClass('class')

EDIT - i just noticed that your array is called"array", but in the else block you refer to it as items

   var items= ["item1", "item2", "item3"];
   var i;
   for (i = 0; i < items.length; i++) {
       if(items[i] is the excluded one){
               skip over}
    else { $('#' + items[i]).removeClass('class');
    }

I still think that there is a better way to do this - but try making the names the same and see if that works.


问:
Shopify GraphQL – How to pull abandoned checkouts
I am in the process of converting our project from the Shopify REST API over to the GraphQL API, however, I can't seem to find a way to pull "Abandoned checkouts".

This is the REST API documentation for abandoned checkouts that I am currently using and referencing:
https://help.shopify.com/en/api/reference/orders/abandoned-checkouts

I can't seem to find the equivalent using GraphQL.

答: Schema has nothing on that. Probably a better idea to direct your question at Shopify API dev forums. At least there you're bound to get an answer from Shopify, whereas here, you're bound to hear crickets chirping.</p>


问:
how to avoid memory wastage when storing UTF-8 characters (8 bit) in Java character (16 bit). two in one?
I'm afraid I have a question on a detail of a rather oversaturated topic, I searched aroudn a lot, but couldn't find a clear answer to that specific obvious -imho- important, problem:

When converting byte[] to String using UTF-8, each byte (8bit) becomes a 8 bit character encoded by UTF-8, but each UTF-8 character is saved as a 16 bit character in java. Is that correct?
If yes, this means, that each stupid java character only uses the first 8 bits, and consumes double the memory? Is that correct too? I wonder how this wasteful behaviour is acceptable..

Isn't there some trick to have a pseudo String that is 8 bit?  Would that actually result in less memory consumption?
Or maybe, is there a way to store >two< 8bit characters in one java 16bit character to avoid this memory waste?

thanks for any deconfusing answers...

EDIT:
hi, thanks everybody for answering. I was aware of the variable-length property of UTF-8. However, since my source is byte which is 8 bit, I understood (apparently wrongly) that it needs only 8-bit UTF-8 words. Is UTF-8 conversion actually saving the strange symbols that you see when on the CLI you do "cat somebinary" ? I thought UTF-8 was just somehow used to map each of the possible 8bit words of byte to one particular 8 bit word of UTF-8. Wrong? I thought about using Base64 but it's bad because it uses only 7 bit..

questions reformulated: is there a smarter way to convert byte to something String?
May favorite was to just cast byte[] to char[], but then I still have 16bit words.

additional use case info:

I'm adapting Jedis (java client for the NoSQL Redis) as the  "primitive storage layer" for hypergraphDB. So, jedis is a database for another "database".
My problem is that I have to feed jedis with byte[] data all the time, but internally, >Redis< (the actual server)  is dealing only with "binary safe" Strings. Since Redis is written in C, a char is 8 bit long, AFAIK not ASCIII which is 7 bit. In Jedis however, java world, every character is 16 bit long internally. I don't understand this code (yet), but I suppose jedis then converts this java 16 bit strings to a Redis conforming 8 bit string (([here][3]). It says it extends FilterOutputStream. My hope is to bypass the byte[] <-> string conversion altogether and use that Filteroutputstream...?  )

now I wonder: if I had to interconvert byte[] and String all the time, with datasizes ranging from very small to potentially very big, isn't there a huge waste of memory to have each 8 bit character passed around as 16bit within java?

答:
Maybe it is this what you want:

```<code>// Store them into the 16 bit datatype.
char c1_8bit = 'a';
char c2_8bit = 'h';
char two_chars = (c1_8bit << 8) + c2_8bit;

// extract them
char c1_8bit = two_chars >> 8;
char c2_8bit = two_chars & 0xFF;
</code>```

Of course this trick only works with ASCII chars (chars in the range [0-255]). Why?
Because you want to store your chars this way:

xxxx xxxx  yyyy yyyy with x is char 1 and y is char 2. So this means you have only 8 bit per char. And what is the biggest integer you can make with 8 bit? Answer: 255

255 = 0000 0000 1111 1111 (8 bit). And when you are using a char > 255, then you will have this:

256 = 0000 0001 0000 0000 (more than 8 bit), which doesn't fit in the 8 bit you provide for 1 char.

Plus: Keep in mind Java is a language, developed by clever people. They knew what they where doing. Thrust the Java API

ContentLicense: CC BY-SA 3.0

Body:
Maybe it is this what you want:

// Store them into the 16 bit datatype.
char c1_8bit = 'a';
char c2_8bit = 'h';
char two_chars = (c1_8bit << 8) + c2_8bit;

// extract them
char c1_8bit = two_chars >> 8;
char c2_8bit = two_chars & 0xFF;

Of course this trick only works with ASCII chars (chars in the range [0-255]). Why?
Because you want to store your chars this way:

xxxx xxxx  yyyy yyyy with x is char 1 and y is char 2. So this means you have only 8 bit per char. And what is the biggest integer you can make with 8 bit? Answer: 255

255 = 0000 0000 1111 1111 (8 bit). And when you are using a char > 255, then you will have this:

256 = 0000 0001 0000 0000 (more than 8 bit), which doesn't fit in the 8 bit you provide for 1 char.

Plus: Keep in mind Java is a language, developed by clever people. They knew what they where doing. Thrust the Java API


问:
Using maven, how to concat final name of war with project version in a specific format?
The functionality of Parallel Deployment from Tomcat requires that the .war file name be in a specific format.

For example: If we have the version 1 of the project running and we need to hot deploy the version 2, it is needed that the .war name be "project-name##2.war".

We use in our project semantic versioning. So our versions are for example 5.31.6 .

When we deploy a new version through Tomcat manager we build the project using maven, rename the file name to project-name##053106.war and upload it to server. This process is manual and susceptible to errors.

Our version is set in pom.xml like this:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>br.com.group</groupId>
    <artifactId>project-name</artifactId>
    <version>5.31.6</version>
    <packaging>war</packaging>
    <name>Project Name</name>
    <description>Project Description</description>
    ...
</project>
</code>```

We set the final name in profiles, for example:

```<code><profiles>
    <profile>
        <id>local</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <profilelabel>LOCAL</profilelabel>
        </properties>
        <build>
            <finalName>project-name-local</finalName>
        </build>
    </profile>
    <profile>
        <id>production</id>
        <properties>
            <profilelabel>PRODUCTION</profilelabel>
        </properties>
        <build>
            <finalName>project-name</finalName>
        </build>
    </profile>
</profiles>
</code>```

My question is: With the examples above, how can I build the war file with the final name concatenated with version number without the dots and if possible with each "part" of version "str_pad"ed (5.31.6 becomes 053106)?

Using profile local: project-name-local##053106.war

Using profile prod: project-name##053106.war

答:
You can use gmaven plugin to mangle project.version in any desired way and assign it to a property (all during initialization phase). Here is an example,
it handles versions with -SUFFIX part (to be safe, it handles the case of multiple dashes):

<build>
    <finalName>yourProjectName-${paddedVersion}</finalName>
    <plugins>
        <plugin>
            <groupId>org.codehaus.gmaven</groupId>
            <artifactId>gmaven-plugin</artifactId>
            <version>1.4</version>
            <executions>
                <execution>
                    <phase>initialize</phase>
                    <goals>
                        <goal>execute</goal>
                    </goals>
                    <configuration>
                        <source>
                            println('Mangling project version: ' + project.version)
                            String[] versionParts = project.version.split("-")
                            paddedVersion = versionParts[0].split("\\.").collect { it.padLeft(2,"0") }.join()
                            if (versionParts.size() > 1) {
                                paddedVersion += "-" + versionParts[1..-1].join("-")
                            }
                            println('Padded version version: ' + paddedVersion)
                            project.properties["paddedVersion"] = paddedVersion
                        </source>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
```

Body:
The functionality of Parallel Deployment from Tomcat requires that the .war file name be in a specific format.

For example: If we have the version 1 of the project running and we need to hot deploy the version 2, it is needed that the .war name be "project-name##2.war".

We use in our project semantic versioning. So our versions are for example 5.31.6 .

When we deploy a new version through Tomcat manager we build the project using maven, rename the file name to project-name##053106.war and upload it to server. This process is manual and susceptible to errors.

Our version is set in pom.xml like this:

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>br.com.group</groupId>
    <artifactId>project-name</artifactId>
    <version>5.31.6</version>
    <packaging>war</packaging>
    <name>Project Name</name>
    <description>Project Description</description>
    ...
</project>

We set the final name in profiles, for example:

<profiles>
    <profile>
        <id>local</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <profilelabel>LOCAL</profilelabel>
        </properties>
        <build>
            <finalName>project-name-local</finalName>
        </build>
    </profile>
    <profile>
        <id>production</id>
        <properties>
            <profilelabel>PRODUCTION</profilelabel>
        </properties>
        <build>
            <finalName>project-name</finalName>
        </build>
    </profile>
</profiles>

My question is: With the examples above, how can I build the war file with the final name concatenated with version number without the dots and if possible with each "part" of version "str_pad"ed (5.31.6 becomes 053106)?

Using profile local: project-name-local##053106.war

Using profile prod: project-name##053106.war


答:
Presumably the array in the question is the result of a computation
using floating-point values, in which case some non-integers entries
might have turned out non-integer due to rounding errors.

Consider using exact numbers for the computation, rather than
floating-point approximations, if that is an option. Note that
one can use Sage number types as data types for NumPy arrays.

If some of the computations involve transcendent functions,
Arb might give a way to work in arbitrary precision.

Finally, replacing is_integer by a test whether the distance
to the nearest integer is less than some threshold might be an
option, if one suspects this might be due to rounding errors.

Title: numpy.float64 type and is_integer() issues

Body:
I am writting some python code in sagemath. I just want to parse some values to check if they are integers or not. I'm doing it with is_integer() function. However, only some numbers are matched as integers.

I have this array:

[[  1.26975000e+03   7.02493619e-14  -1.65645275e-13   5.00000000e+00
    2.50000000e+00   3.54050123e-13  -2.91373674e+00   1.06841761e+00]
 [ -5.00000000e+00   9.49393038e-01   5.00000000e+00  -5.00000000e+00
   -1.33475906e+00  -2.51708718e+00   4.98747803e-01  -2.21681235e+00]
 [  3.13790751e+00   4.17443857e-14   2.09099026e+00   1.48894747e+00
   -1.98140835e-01  -3.11027406e+00  -1.73743687e+00   5.68322944e-02]
 [ -5.00000000e+00  -5.15698595e-14   2.46634986e+00  -3.01863014e-01
   -1.64657626e+00   2.47085900e+00  -5.88213961e-01  -2.89145373e-02]
 [  5.00000000e+00   5.12235598e-01  -1.48149016e+00   2.94309857e-01
    4.75000000e+00  -5.33661417e-01   3.43055265e-01  -4.12203856e+00]
 [ -1.22979595e-01  -2.99512587e-01   2.86838294e+00  -2.54014737e-01
   -1.07441346e+00   2.81962997e+00   1.28837244e-01   2.07388351e-01]
 [ -1.57036190e+00   2.13573146e-01  -7.37436867e-01   5.22145920e+00
    2.78805312e+00   2.34402605e+00  -1.09099026e+00  -3.34248259e-02]
 [ -2.44284969e+00  -4.44168609e+00   9.51259207e-01   7.49320230e-01
    4.77326511e-01   2.99085430e+00  -2.39859298e+00  -1.96715999e+00]]

I have this code:

for row in dct_block:
    for frec in row:
        print frec,frec.is_integer(),type(frec)

And i'm getting these results:

1269.75 False <type 'numpy.float64'>
7.02493618832e-14 False <type 'numpy.float64'>
-1.65645275274e-13 False <type 'numpy.float64'>
5.0 False <type 'numpy.float64'>
2.5 False <type 'numpy.float64'>
3.54050122553e-13 False <type 'numpy.float64'>
-2.91373674111 False <type 'numpy.float64'>
1.06841760838 False <type 'numpy.float64'>
-5.0 True <type 'numpy.float64'>
0.94939303763 False <type 'numpy.float64'>
5.0 False <type 'numpy.float64'>
...

As you can see, only the number "-5" is matched as integer. There are some others, such as two "5.0", which should be matched as well.

What am i doing wrong?


问:
How to bind configuration to array of JSON Objects .Net Core
I'm trying to bind a JSON file to a model for configuration settings in a dotnet core project.

The json looks like:

```<code>"Settings": {
  "Values": [
  { "Value1": "1" },
  { "Value2": "2" }
]}
</code>```

My model looks like:

```<code>public class Settings
{
    public List<Value> Values{ get; set; }
}

public class Value
{
    public string Value1 { get; set; }

    public string Value2 { get; set; }
}
</code>```

I bind with the following:

```<code>var settings = _configuration.GetSection("Settings").Get<Settings>();
</code>```

But this results in settings containing two Value objects in the list - the first Value object has Value1 = 1 & Value2 = null, and the second Value object has Value1 = null & Value2 = 2. How can I bind such that it settings only has one Value object in Values with both properties populated?

This is not the same as suggested here:
 https://stackoverflow.com/questions/51488845/how-to-read-a-string-array-in-appsettings-json

This is because each object in the array in this case have different properties whereas in the proposed duplicate all objects are consistent.

答:
Ok, so it actually needs to look like:

```<code>public class Settings
{
    public List<Dictionary<string, string>> Values{ get; set; }
}
</code>```

Since the JSON Values is actually an array of dictionaries.

For the following to work:

```<code>public class Settings
{
    public Dictionary<string, string> Values{ get; set; }
}
</code>```

The JSON would need to look like:

```<code>"Settings": {
    "Values": {
        "Value1": "1",
        "Value2": "2"
    }
}
</code>```

Body:
I'm trying to bind a JSON file to a model for configuration settings in a dotnet core project.

The json looks like:

"Settings": {
  "Values": [
  { "Value1": "1" },
  { "Value2": "2" }
]}

My model looks like:

public class Settings
{
    public List<Value> Values{ get; set; }
}

public class Value
{
    public string Value1 { get; set; }

    public string Value2 { get; set; }
}

I bind with the following:

var settings = _configuration.GetSection("Settings").Get<Settings>();

But this results in settings containing two Value objects in the list - the first Value object has Value1 = 1 & Value2 = null, and the second Value object has Value1 = null & Value2 = 2. How can I bind such that it settings only has one Value object in Values with both properties populated?

This is not the same as suggested here:
 https://stackoverflow.com/questions/51488845/how-to-read-a-string-array-in-appsettings-json

This is because each object in the array in this case have different properties whereas in the proposed duplicate all objects are consistent.

Body:
Ok, so it actually needs to look like:

public class Settings
{
    public List<Dictionary<string, string>> Values{ get; set; }
}

Since the JSON Values is actually an array of dictionaries.

For the following to work:

public class Settings
{
    public Dictionary<string, string> Values{ get; set; }
}

The JSON would need to look like:

"Settings": {
    "Values": {
        "Value1": "1",
        "Value2": "2"
    }
}


问:
How can I get the model created by super().create() in a ModelViewSet?
I'm trying to get a copy of the model created by super().create() in my ModelViewSet's create() method. What's the simplest way to do that?

I have a ModelViewSet that takes a generic POST request, which I know is good because I end up with a new record in my DB. What I want to do is get the object that was just created so I can return its pk to the client. However, the following will not work:

class ItemViewSet(viewsets.ModelViewSet):
    model = Item
    # ...
    def create(self, request, *args, **kwargs):
        super().create(request, *args, **kwargs)  # Successfully creates instance
        instance = self.get_object()  # Throws error
        return Response({'status': 'success', 'pk': instance.pk})
```

Like with other DRF ModelViewSet methods, I'd expect self.get_object() to get me the instance created, though this is usually only usable in a "detail route". What I get instead is the following error:
AssertionError: Expected view CultivarStockViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.

Any insight is appreciated!

答:
You can indeed not obtain the object by using get_object [classy-doc], since Django uses parameters to perform a filtering. Indeed, the get_object implementation looks like:

```<code>def get_object(self):
    # ...
    queryset = self.filter_queryset(self.get_queryset())

    # Perform the lookup filtering.
    lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

    # ...

    filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
    obj = get_object_or_404(queryset, **filter_kwargs)

    # May raise a permission denied
    self.check_object_permissions(self.request, obj)

    return obj</code>```

these  self.kwargs are not available, so the get_object call fails.

We can however patch the create [classy-doc] function and use the serializer.instance [drf-doc] here:

```<code>class ItemViewSet(viewsets.ModelViewSet):
    model = Item
    # ...

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response({'status': 'success', 'pk': <b>serializer.instance.pk</b>})</code>```

Body:
I'm trying to get a copy of the model created by super().create() in my ModelViewSet's create() method. What's the simplest way to do that?

I have a ModelViewSet that takes a generic POST request, which I know is good because I end up with a new record in my DB. What I want to do is get the object that was just created so I can return its pk to the client. However, the following will not work:

class ItemViewSet(viewsets.ModelViewSet):
    model = Item
    # ...
    def create(self, request, *args, **kwargs):
        super().create(request, *args, **kwargs)  # Successfully creates instance
        instance = self.get_object()  # Throws error
        return Response({'status': 'success', 'pk': instance.pk})

Like with other DRF ModelViewSet methods, I'd expect self.get_object() to get me the instance created, though this is usually only usable in a "detail route". What I get instead is the following error:
AssertionError: Expected view CultivarStockViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.

Any insight is appreciated!

Body:
You can indeed not obtain the object by using get_object [classy-doc], since Django uses parameters to perform a filtering. Indeed, the get_object implementation looks like:

def get_object(self):
    # ...
    queryset = self.filter_queryset(self.get_queryset())

    # Perform the lookup filtering.
    lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

    # ...

    filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
    obj = get_object_or_404(queryset, **filter_kwargs)

    # May raise a permission denied
    self.check_object_permissions(self.request, obj)

    return obj

these  self.kwargs are not available, so the get_object call fails.

We can however patch the create [classy-doc] function and use the serializer.instance [drf-doc] here:

class ItemViewSet(viewsets.ModelViewSet):
    model = Item
    # ...

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response({'status': 'success', 'pk': serializer.instance.pk})


问:
Image won't change when key is pressed
I am making my own little copy of Mario that I started today, and I am stuck on a little animation.

When UP is pressed, Mario jumps, but the sprite won't change.

I have tried if-else to set it, but it's not working:

PImage brick1;
PImage bg;
PImage Flag;
float playerX;
float playerY;
float brickX;
float Lives;
float Level;
float Time;
void setup(){

size(1000,800);
smooth();
if (keyPressed){
    if (keyCode == UP){
        bg = loadImage("Mario3.png");
    }
}else{
    bg = loadImage("Mario1.png");
}
```

I expect the image to change while UP is held down, but it says the "Mario1.png" sprite.

答:
You've to implement a draw function.

Load the images in setup:

PImage bg1, bg3;
void setup() {

  size(1000, 800);
  smooth();

  bg1 = loadImage("Mario1.png");
  bg3 = loadImage("Mario3.png");
}
```

<p>And draw the proper image dependent on the state of <code>keyPressed</code> and <code>keyCode</code>.<br>
Use <code>image()</code> to draw an image to the display:</p>

<p>e.g.</p>

<pre class="lang-py prettyprint-override"><code>void draw() {

    background(0);

    if (keyPressed && keyCode == UP) {
        image(bg3, 0, 0);
    } else {
        image(bg1, 0, 0);
    }
}
</code>```

Title: Image won't change when key is pressed

Body:
I am making my own little copy of Mario that I started today, and I am stuck on a little animation.

When UP is pressed, Mario jumps, but the sprite won't change.

I have tried if-else to set it, but it's not working:

PImage brick1;
PImage bg;
PImage Flag;
float playerX;
float playerY;
float brickX;
float Lives;
float Level;
float Time;
void setup(){

size(1000,800);
smooth();
if (keyPressed){
    if (keyCode == UP){
        bg = loadImage("Mario3.png");
    }
}else{
    bg = loadImage("Mario1.png");
}

I expect the image to change while UP is held down, but it says the "Mario1.png" sprite.

Body:
You've to implement a draw function.

Load the images in setup:

PImage bg1, bg3;
void setup() {

  size(1000, 800);
  smooth();

  bg1 = loadImage("Mario1.png");
  bg3 = loadImage("Mario3.png");
}

And draw the proper image dependent on the state of keyPressed and keyCode.

Use image() to draw an image to the display:

e.g.

void draw() {

    background(0);

    if (keyPressed && keyCode == UP) {
        image(bg3, 0, 0);
    } else {
        image(bg1, 0, 0);
    }
}


问:
Return Count Value back as 0 if emtpy or none
I am running the following query in our database and I am trying to get the count value back as 0 if none are present, but having problems doing so. Could someone help assist and explain how to accomplish this

```<code>select state, count(phone_number) from VOIP_PHONE_NUMBER_POOL
where status = 3
group by state
order by state asc;
</code>```

For example, currently my query is returning something back like this

```<code>State  Count

AZ     25
</code>```

When I want it to return the empty values and look like this

```<code>State  Count

AZ     25
CA     0
</code>```

答:
This mimics what you have now:

```<code>SQL> with voip_phone_number_pool (state, phone_number, status) as
  2    (select 'AZ', 1234, 3 from dual union all
  3     select 'AZ', 2232, 3 from dual union all
  4     select 'AZ', 4444, 3 from dual union all
  5     select 'AZ', 7756, 1 from dual union all
  6     --
  7     select 'CA', 9999, 1 from dual
  8    )
  9  select state,
 10         count(phone_number)
 11  from voip_phone_number_pool
 12  where status = 3
 13  group by state
 14  order by state;

ST COUNT(PHONE_NUMBER)
-- -------------------
AZ                   3

SQL>
</code>```

There's no row for the CA state which has status = 3, so it isn't returned by that query.

What you could do, is to use outer self-join in such a manner:

```<code>SQL> with voip_phone_number_pool (state, phone_number, status) as
  2    (select 'AZ', 1234, 3 from dual union all
  3     select 'AZ', 2232, 3 from dual union all
  4     select 'AZ', 4444, 3 from dual union all
  5     select 'AZ', 7756, 1 from dual union all
  6     --
  7     select 'CA', 9999, 1 from dual
  8    ),
  9  states as
 10    (select distinct state from voip_phone_number_pool)
 11  select s.state,
 12         count(v.phone_number)
 13  from states s left join voip_phone_number_pool v on v.state = s.state
 14                                                  and v.status = 3
 15  group by s.state
 16  order by s.state;

ST COUNT(V.PHONE_NUMBER)
-- ---------------------
AZ                     3
CA                     0

SQL>
</code>```

the states CTE selects all states

it is then used in outer join with voip_phone_number_pool

note that condition (status = 3) has to be moved into join (line #14); if you leave it in the where clause, you won't get desired result

Body:
I am running the following query in our database and I am trying to get the count value back as 0 if none are present, but having problems doing so. Could someone help assist and explain how to accomplish this

select state, count(phone_number) from VOIP_PHONE_NUMBER_POOL
where status = 3
group by state
order by state asc;

For example, currently my query is returning something back like this

State  Count

AZ     25

When I want it to return the empty values and look like this

State  Count

AZ     25
CA     0

Body:
This mimics what you have now:

SQL> with voip_phone_number_pool (state, phone_number, status) as
  2    (select 'AZ', 1234, 3 from dual union all
  3     select 'AZ', 2232, 3 from dual union all
  4     select 'AZ', 4444, 3 from dual union all
  5     select 'AZ', 7756, 1 from dual union all
  6     --
  7     select 'CA', 9999, 1 from dual
  8    )
  9  select state,
 10         count(phone_number)
 11  from voip_phone_number_pool
 12  where status = 3
 13  group by state
 14  order by state;

ST COUNT(PHONE_NUMBER)
-- -------------------
AZ                   3

SQL>

There's no row for the CA state which has status = 3, so it isn't returned by that query.

What you could do, is to use outer self-join in such a manner:

SQL> with voip_phone_number_pool (state, phone_number, status) as
  2    (select 'AZ', 1234, 3 from dual union all
  3     select 'AZ', 2232, 3 from dual union all
  4     select 'AZ', 4444, 3 from dual union all
  5     select 'AZ', 7756, 1 from dual union all
  6     --
  7     select 'CA', 9999, 1 from dual
  8    ),
  9  states as
 10    (select distinct state from voip_phone_number_pool)
 11  select s.state,
 12         count(v.phone_number)
 13  from states s left join voip_phone_number_pool v on v.state = s.state
 14                                                  and v.status = 3
 15  group by s.state
 16  order by s.state;

ST COUNT(V.PHONE_NUMBER)
-- ---------------------
AZ                     3
CA                     0

SQL>

the states CTE selects all states

it is then used in outer join with voip_phone_number_pool

note that condition (status = 3) has to be moved into join (line #14); if you leave it in the where clause, you won't get desired result


问:
Alternate color with Angular Material mat-table with parent child rows
I have an Angular Material mat-table which I used CSS styling for alternate row colors. Here is the CSS styling:

.mat-row:nth-child(even){
    background-color: #e4f0ec;
}

.mat-row:nth-child(odd){
    background-color:#ffffff;
}
```

<p>This works when my mat-table does not have defined child rows. When I added another <code>ng-container</code> which is specified with "expandedDetail", this does not work anymore. All the rows is white but the expanded child rows are colored.</p>

<p>I followed the example from material.angular.io</p>

<p>I see other example for row styling but they use tr tags. In the example and my code, I used an <code>ng-container</code>, th and td tags for each column.</p>

<p>Any help is appreciated.</p>

<p>I added the project to stackblitz</p>

<p>https://stackblitz.com/edit/angular-4bcxtv</p>

<p>Here is the HTML code I used</p>

<pre class="lang-html prettyprint-override"><code><table mat-table
       [dataSource]="dataSource" multiTemplateDataRows
       class="mat-elevation-z8">
  <ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay">
    <th mat-header-cell *matHeaderCellDef> {{column}} </th>
    <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
  </ng-container>

  <!-- Expanded Content Column - The detail row is made up of this one column that spans across all columns -->
  <ng-container matColumnDef="expandedDetail">
    <td mat-cell *matCellDef="let element" [attr.colspan]="columnsToDisplay.length">
      <div class="example-element-detail"
           [@detailExpand]="element == expandedElement ? 'expanded' : 'collapsed'">
        <div class="example-element-diagram">
          <div class="example-element-position"> {{element.position}} </div>
          <div class="example-element-symbol"> {{element.symbol}} </div>
          <div class="example-element-name"> {{element.name}} </div>
          <div class="example-element-weight"> {{element.weight}} </div>
        </div>
        <div class="example-element-description">
          {{element.description}}
          <span class="example-element-description-attribution"> -- Wikipedia </span>
        </div>
      </div>
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
  <tr mat-row *matRowDef="let element; columns: columnsToDisplay;"
      class="example-element-row"
      [class.example-expanded-row]="expandedElement === element"
      (click)="expandedElement = expandedElement === element ? null : element">
  </tr>
  <tr mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></tr>
</table>
</code>```

答:
dang it - this took me too long to find out and the worse.. I don't know excatly why it's working..

```<code>.mat-row:nth-child(2n+1){
  background-color: #e4f0ec;
}
.mat-row:not(:nth-child(4n+1)){
  background-color:#ffffff;
}
</code>```

I hope I could help you :)

Body:
I have an Angular Material mat-table which I used CSS styling for alternate row colors. Here is the CSS styling:

.mat-row:nth-child(even){
    background-color: #e4f0ec;
}

.mat-row:nth-child(odd){
    background-color:#ffffff;
}

This works when my mat-table does not have defined child rows. When I added another ng-container which is specified with "expandedDetail", this does not work anymore. All the rows is white but the expanded child rows are colored.

I followed the example from material.angular.io

I see other example for row styling but they use tr tags. In the example and my code, I used an ng-container, th and td tags for each column.

Any help is appreciated.

I added the project to stackblitz

https://stackblitz.com/edit/angular-4bcxtv

Here is the HTML code I used

  <ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay">
     {{column}}
     {{element[column]}}
  </ng-container>

  <ng-container matColumnDef="expandedDetail">

 {{element.position}}

 {{element.symbol}}

 {{element.name}}

 {{element.weight}}

          {{element.description}}
           -- Wikipedia

  </ng-container>

Body:
dang it - this took me too long to find out and the worse.. I don't know excatly why it's working..

.mat-row:nth-child(2n+1){
  background-color: #e4f0ec;
}
.mat-row:not(:nth-child(4n+1)){
  background-color:#ffffff;
}

I hope I could help you :)


问:
C# Server side DateTime
Please tell me, is it good to store DateTime, for example createtime of posts, on server in ticks?</p>

```<code>DateTime.Ticks
</code>```

答: If there is no chance that anybody might ever want to view the stored data manually, or there is a particular requirement for that level of precision then fine. But generally, I don't like it, It's a pain to look at a days data in a database when the date is in some obscure format!</p>

Title: C# Server side DateTime

Body:
Please tell me, is it good to store DateTime, for example createtime of posts, on server in ticks?

DateTime.Ticks


问:
Audio WMA incorrectly reported as video/x-ms-wma
Having to handle audio WMA files as part of an upload script but I've run across a really annoying bug with the file type.

I need to only allow audio, NOT video but it seems that all WMA files have the type of :

```<code>video/x-ms-wma
</code>```

Whether they contain video or not.

I was expecting :

```<code>audio/x-ms-wma
</code>```

But this doesn't seem to be the case and it means that I can't validate the type correctly with javascript as :

```<code>file.type.match('audio.*')
</code>```

Which is obviously failing here.

Are there any workarounds for this?

答:
I had the same issue. It was a Chrome bug in my case.

Solved using regex: file.type.match(/audio|wma/)

This matches the text audio or wma.

Body:
Having to handle audio WMA files as part of an upload script but I've run across a really annoying bug with the file type.

I need to only allow audio, NOT video but it seems that all WMA files have the type of :

video/x-ms-wma

Whether they contain video or not.

I was expecting :

audio/x-ms-wma

But this doesn't seem to be the case and it means that I can't validate the type correctly with javascript as :

file.type.match('audio.*')

Which is obviously failing here.

Are there any workarounds for this?


问:
how to stack image files in to one file and how to resize black and white images
here my images look like this enter image description here
I am trying to stack the images files into one file and also resizing black white images 1000X1000. But I didn't get, I have images with size 600X400, but I need it's to 1000 pixels size, please help me how to do.
Here my images loading:

```<code> import cv2
    import glob
    img= [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack1/*jpg')]
img2= [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack2/*jpg')]
img3= [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack3/*jpg')]
img4= [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack4/*jpg')]
</code>```

here I am taking all images into one list:

```<code>img=img1+img2+img3+img4
</code>```

Here my resize the images :

```<code>im_g=cv2.resize(img,(1000,1000))
--------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-69-56a6794f0ec5> in <module>()
----> 1 im_g=cv2.resize(img,(1000,1000))

TypeError: src is not a numpy array, neither a scalar
</code>```

答:
In your code, img1, img2, img3, img4 are lists. When you use the + operator, they are stacked in the list way.

For example, N images with size (h,w) in each folder (stack1, stack2, ...), the shape of img1 is (N, h, w). However, the shape of img1+img2 is (2N, h, w). Use numpy array instead.

```<code>import cv2
import glob
import numpy as np

img1 = np.array([cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack1/*jpg')])
img2 = np.array([cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack2/*jpg')])
img3 = np.array([cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack3/*jpg')])
img4 = np.array([cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack4/*jpg')])

imgs = list(img1+img2+img3+img4)

for img in imgs:
    im_g = cv2.resize(img,(1000,1000))
</code>```

How many files are there in the folder (stack1, stack2, ...)?
In your way of using glob, the result will be multiple files. You have to add one more step that stack files in the folder.

If the desired result is only one file, try this.

```<code>import cv2
import glob
import numpy as np

img1 = [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack1/*jpg')]
img2 = [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack2/*jpg')]
img3 = [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack3/*jpg')]
img4 = [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack4/*jpg')]

imgs = (img1+img2+img3+img4)
stacked_img = np.array(img1[0])
for img in imgs[1:]:
    stacked_img += np.array(img)
im_g = cv2.resize(stacked_img,(1000,1000))
</code>```

Note: you may want to normalize(average) the value of the stacked image.

Body:
here my images look like this enter image description here
I am trying to stack the images files into one file and also resizing black white images 1000X1000. But I didn't get, I have images with size 600X400, but I need it's to 1000 pixels size, please help me how to do.
Here my images loading:

 import cv2
    import glob
    img= [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack1/*jpg')]
img2= [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack2/*jpg')]
img3= [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack3/*jpg')]
img4= [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack4/*jpg')]

here I am taking all images into one list:

img=img1+img2+img3+img4

Here my resize the images :

im_g=cv2.resize(img,(1000,1000))
--------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-69-56a6794f0ec5> in <module>()
----> 1 im_g=cv2.resize(img,(1000,1000))

TypeError: src is not a numpy array, neither a scalar

Body:
In your code, img1, img2, img3, img4 are lists. When you use the + operator, they are stacked in the list way.

For example, N images with size (h,w) in each folder (stack1, stack2, ...), the shape of img1 is (N, h, w). However, the shape of img1+img2 is (2N, h, w). Use numpy array instead.

import cv2
import glob
import numpy as np

img1 = np.array([cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack1/*jpg')])
img2 = np.array([cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack2/*jpg')])
img3 = np.array([cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack3/*jpg')])
img4 = np.array([cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack4/*jpg')])

imgs = list(img1+img2+img3+img4)

for img in imgs:
    im_g = cv2.resize(img,(1000,1000))

How many files are there in the folder (stack1, stack2, ...)?
In your way of using glob, the result will be multiple files. You have to add one more step that stack files in the folder.

If the desired result is only one file, try this.

import cv2
import glob
import numpy as np

img1 = [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack1/*jpg')]
img2 = [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack2/*jpg')]
img3 = [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack3/*jpg')]
img4 = [cv2.imread(file) for file in glob.glob('C:/Users/NanduCn/jupter1/deepl/challenges-master/ML/stack4/*jpg')]

imgs = (img1+img2+img3+img4)
stacked_img = np.array(img1[0])
for img in imgs[1:]:
    stacked_img += np.array(img)
im_g = cv2.resize(stacked_img,(1000,1000))

Note: you may want to normalize(average) the value of the stacked image.


问:
Julia only imports names from first homemade Module
I have made two modules in Julia. One is for plotting graphs of trees structures, and one is for estimating entropy from simbolic secuences.
The first one has this first lines:

```<code>  module ArbolGrafosTikz

using LightGraphs, TikzGraphs

abstract type LabelledDiGraph
end

export LabelledTree, Nodo, Subarbol, Arbol,
       walk_tree, walk_tree!, tikz_representation

struct LabelledTree <: LabelledDiGraph
    g::DiGraph
    labels::Vector{Any}
end
</code>```

etcetera.
The second one has this header:

```<code>module EntropySymb

using Base.Iterators

export simboliza, problock, ncartprod, issubvec, allprobsn

function simboliza(x, delta=epsi)
    # funcion que pasa floats a tres simbolos.
    result=0
    if x>delta
</code>```

etcetera.

In my main program I have the first lines as thus:

```<code>push!(LOAD_PATH,".")
include("EntropySymb.jl")
include("ArbolGrafosTikz.jl")
using ArbolGrafosTikz
using EntropySymb
</code>```

but I can only have direct access to the names of objects in ArbolGrafosTikz
directly, for EntropySymb I have to use the name prefixed with the module, or Julia REPL doesn't seem to know about them.
Why is this?

答:
The problem in your code is that you first include the files, which already loads the modules into Main so that Main.EntropySymb exists. This makes the subsequent import statement using EntropySymb return an error

```<code>ERROR: importing EntropySymb into Main conflicts with an existing identifier
</code>```

If you already add the current directory (or the directory that contains the modules) to LOAD_PATH, you do not need the calls to include in order to import the module with using or import. You can simply write

```<code>push!(LOAD_PATH, ".")
using ArbolGrafosTikz
using EntropySymb
</code>```

If you want to use include instead you should use using with Main.ModuleName or .ModuleName to bring the exported names into scope.

```<code>include("EntropySymb.jl")
include("ArbolGrafosTikz.jl")
using .ArbolGrafosTikz
using .EntropySymb
</code>```

Note that you should also face the issue for the first module but I guess the reason why you do not is because the code is run in somewhat different order than the one given in the question or you did not actually run the first include statement. Maybe try the same code in a new session to reproduce the issue for the first module, as well.

Body:
I have made two modules in Julia. One is for plotting graphs of trees structures, and one is for estimating entropy from simbolic secuences.
The first one has this first lines:

  module ArbolGrafosTikz

using LightGraphs, TikzGraphs

abstract type LabelledDiGraph
end

export LabelledTree, Nodo, Subarbol, Arbol,
       walk_tree, walk_tree!, tikz_representation

struct LabelledTree <: LabelledDiGraph
    g::DiGraph
    labels::Vector{Any}
end

etcetera.
The second one has this header:

module EntropySymb

using Base.Iterators

export simboliza, problock, ncartprod, issubvec, allprobsn

function simboliza(x, delta=epsi)
    # funcion que pasa floats a tres simbolos.
    result=0
    if x>delta

etcetera.

In my main program I have the first lines as thus:

push!(LOAD_PATH,".")
include("EntropySymb.jl")
include("ArbolGrafosTikz.jl")
using ArbolGrafosTikz
using EntropySymb

but I can only have direct access to the names of objects in ArbolGrafosTikz
directly, for EntropySymb I have to use the name prefixed with the module, or Julia REPL doesn't seem to know about them.
Why is this?

Body:
The problem in your code is that you first include the files, which already loads the modules into Main so that Main.EntropySymb exists. This makes the subsequent import statement using EntropySymb return an error

ERROR: importing EntropySymb into Main conflicts with an existing identifier

If you already add the current directory (or the directory that contains the modules) to LOAD_PATH, you do not need the calls to include in order to import the module with using or import. You can simply write

push!(LOAD_PATH, ".")
using ArbolGrafosTikz
using EntropySymb

If you want to use include instead you should use using with Main.ModuleName or .ModuleName to bring the exported names into scope.

include("EntropySymb.jl")
include("ArbolGrafosTikz.jl")
using .ArbolGrafosTikz
using .EntropySymb

Note that you should also face the issue for the first module but I guess the reason why you do not is because the code is run in somewhat different order than the one given in the question or you did not actually run the first include statement. Maybe try the same code in a new session to reproduce the issue for the first module, as well.


问:
How to send cookies in CreateView?
I am trying to implement signed cookie sending in CreateView, but I have encountered with the trouble. Following code works in UpdateView but in CreateView we dont  have self.object in  render_to_response method and basically we cant get  a pk there or at least  I dont know how to do it.

Question is how to get pk or id of a freshly created object or maybe alternatively in which method I could move my code to get access to pk from there?

Thanks.

def render_to_response(self, context, **response_kwargs):

    response = CreateView.render_to_response(self, context, **response_kwargs)
    existing_allowed_comments = self.request.get_signed_cookie('allowed_comments', default=None)
    if not self.request.user.is_authenticated:
        if existing_allowed_comments and str(self.object.pk) not in \
                existing_allowed_comments:
            response.set_signed_cookie('allowed_comments',
                 ", ".join([existing_allowed_comments, str(self.object.pk)])
        elif not existing_allowed_comments:
            response.set_signed_cookie('allowed_comments', self.object.pk
    return response
```

method should add pk of created objects to signed cookies in case user is not authenticated.

self.get_object() doesn't work as well – 404

答:
You may be better to override the form_valid() method for this. This method creates an object from the validated form data so you will have access to self.object after calling the method in the base class:

```<code>def form_valid(self, form):
    response = super().form_valid(form)
    existing_allowed_comments = self.request.get_signed_cookie('allowed_comments', default=None)
    if not self.request.user.is_authenticated:
        if existing_allowed_comments and str(self.object.pk) not in \
                existing_allowed_comments:
            response.set_signed_cookie('allowed_comments',
                 ", ".join([existing_allowed_comments, str(self.object.pk)])
        elif not existing_allowed_comments:
            response.set_signed_cookie('allowed_comments', self.object.pk
    return response
</code>```

Note that if the form is not valid because of bad data, no object will be created and this method will not get called.

Title: How to send cookies in CreateView?

Body:
I am trying to implement signed cookie sending in CreateView, but I have encountered with the trouble. Following code works in UpdateView but in CreateView we dont  have self.object in  render_to_response method and basically we cant get  a pk there or at least  I dont know how to do it.

Question is how to get pk or id of a freshly created object or maybe alternatively in which method I could move my code to get access to pk from there?

Thanks.

def render_to_response(self, context, **response_kwargs):

    response = CreateView.render_to_response(self, context, **response_kwargs)
    existing_allowed_comments = self.request.get_signed_cookie('allowed_comments', default=None)
    if not self.request.user.is_authenticated:
        if existing_allowed_comments and str(self.object.pk) not in \
                existing_allowed_comments:
            response.set_signed_cookie('allowed_comments',
                 ", ".join([existing_allowed_comments, str(self.object.pk)])
        elif not existing_allowed_comments:
            response.set_signed_cookie('allowed_comments', self.object.pk
    return response

method should add pk of created objects to signed cookies in case user is not authenticated.

self.get_object() doesn't work as well – 404

Body:
You may be better to override the form_valid() method for this. This method creates an object from the validated form data so you will have access to self.object after calling the method in the base class:

def form_valid(self, form):
    response = super().form_valid(form)
    existing_allowed_comments = self.request.get_signed_cookie('allowed_comments', default=None)
    if not self.request.user.is_authenticated:
        if existing_allowed_comments and str(self.object.pk) not in \
                existing_allowed_comments:
            response.set_signed_cookie('allowed_comments',
                 ", ".join([existing_allowed_comments, str(self.object.pk)])
        elif not existing_allowed_comments:
            response.set_signed_cookie('allowed_comments', self.object.pk
    return response

Note that if the form is not valid because of bad data, no object will be created and this method will not get called.


问:
Powershell Select-String to include a wildcard
I need to use Select-String to find something is a known string of characters, followed by either a / or $ followed by another known string of characters.

So suppose literal string 1 is X and literal string 2 is Y, how do I look for the string X/Y or X$Y in powershell?

答:
```<code>PS C:\users\js> Echo a/b | Select-String a.b

a/b

PS C:\users\js> Echo 'a$b' | Select-String a.b

a$b
</code>```


问:
Install Google API PHP Client Without Composer
I am trying to do YouTube API calls and I have no idea what folder to upload from the google-api-php-client-2.2.2.zip file.

There is both a "src" and "vendor" folder. Most api call examples do a request to the vendor folder, so I tried uploading this one first.

I then include one the autoload file found in it and the first thing I discover is that "Google_Client" class does not exist. I look everywhere for the file to create it and it's not there. the only file outside of other directories is the "autoload.php", with the "client.php" file missing.

So, I go the other route and upload the "src" directory and include once the "autoload.php" file from that.

This time I get this error:

Uncaught exception 'Exception' with message 'This library must be installed via composer or by downloading the full package. See the instructions at https://github.com/google/google-api-php-client#installation

The only thing this page says is user composer or download the zip I'm having issues with.

What exactly should I upload to my server?

```<code>require_once $_SERVER['DOCUMENT_ROOT'] .'/inc/google-api-php-client/autoload.php';
</code>```

答: It looks like although you can download the source and pop that in your web application folder, the files still assume you've got composer and it's autoloader in your application. So, on your local dev maching install composer, follow their instructions and that will get the files into your web app, then upload those files to your production site. You're just using composer to get the files and provide it's autoloader. That is the auto loader it's referring to.</p>

Body:
I am trying to do YouTube API calls and I have no idea what folder to upload from the google-api-php-client-2.2.2.zip file.

There is both a "src" and "vendor" folder. Most api call examples do a request to the vendor folder, so I tried uploading this one first.

I then include one the autoload file found in it and the first thing I discover is that "Google_Client" class does not exist. I look everywhere for the file to create it and it's not there. the only file outside of other directories is the "autoload.php", with the "client.php" file missing.

So, I go the other route and upload the "src" directory and include once the "autoload.php" file from that.

This time I get this error:

Uncaught exception 'Exception' with message 'This library must be installed via composer or by downloading the full package. See the instructions at https://github.com/google/google-api-php-client#installation

The only thing this page says is user composer or download the zip I'm having issues with.

What exactly should I upload to my server?

require_once $_SERVER['DOCUMENT_ROOT'] .'/inc/google-api-php-client/autoload.php';


问:
Finding a key recursively in a dictionary
I'm trying to write a very simple function to recursively search through a possibly nested (in the most extreme cases ten levels deep) Python dictionary and return the first value it finds from the given key.

I cannot understand why my code doesn't work for nested dictionaries.

```<code>def _finditem(obj, key):
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            _finditem(v, key)

print _finditem({"B":{"A":2}},"A")
</code>```

It returns None.

It does work, however, for _finditem({"B":1,"A":2},"A"), returning 2.

I'm sure it's a simple mistake but I cannot find it. I feel like there already might be something for this in the standard library or collections, but I can't find that either.

If you are looking for a general explanation of what is wrong with code like this, the canonical is Why does my recursive function return None?. The answers here are mostly specific to the task of searching in a nested dictionary.

答:
I had to create a general-case version that finds a uniquely-specified key (a minimal dictionary that specifies the path to the desired value) in a dictionary that contains multiple nested dictionaries and lists.

For the example below, a target dictionary is created to search, and the key is created with the wildcard "???". When run, it returns the value "D"

```<code>def lfind(query_list:List, target_list:List, targ_str:str = "???"):
    for tval in target_list:
        #print("lfind: tval = {}, query_list[0] = {}".format(tval, query_list[0]))
        if isinstance(tval, dict):
            val = dfind(query_list[0], tval, targ_str)
            if val:
                return val
        elif tval == query_list[0]:
            return tval

def dfind(query_dict:Dict, target_dict:Dict, targ_str:str = "???"):
    for key, qval in query_dict.items():
        tval = target_dict[key]
        #print("dfind: key = {}, qval = {}, tval = {}".format(key, qval, tval))
        if isinstance(qval, dict):
            val =  dfind(qval, tval, targ_str)
            if val:
                return val
        elif isinstance(qval, list):
            return lfind(qval, tval, targ_str)
        else:
            if qval == targ_str:
                return tval
            if qval != tval:
                break

def find(target_dict:Dict, query_dict:Dict):
    result = dfind(query_dict, target_dict)
    return result

target_dict = {"A":[
    {"key1":"A", "key2":{"key3": "B"}},
    {"key1":"C", "key2":{"key3": "D"}}]
}
query_dict = {"A":[{"key1":"C", "key2":{"key3": "???"}}]}

result = find(target_dict, query_dict)
print("result = {}".format(result))
</code>```

Body:
I'm trying to write a very simple function to recursively search through a possibly nested (in the most extreme cases ten levels deep) Python dictionary and return the first value it finds from the given key.

I cannot understand why my code doesn't work for nested dictionaries.

def _finditem(obj, key):
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            _finditem(v, key)

print _finditem({"B":{"A":2}},"A")

It returns None.

It does work, however, for _finditem({"B":1,"A":2},"A"), returning 2.

I'm sure it's a simple mistake but I cannot find it. I feel like there already might be something for this in the standard library or collections, but I can't find that either.

If you are looking for a general explanation of what is wrong with code like this, the canonical is Why does my recursive function return None?. The answers here are mostly specific to the task of searching in a nested dictionary.

Body:
I had to create a general-case version that finds a uniquely-specified key (a minimal dictionary that specifies the path to the desired value) in a dictionary that contains multiple nested dictionaries and lists.

For the example below, a target dictionary is created to search, and the key is created with the wildcard "???". When run, it returns the value "D"

def lfind(query_list:List, target_list:List, targ_str:str = "???"):
    for tval in target_list:
        #print("lfind: tval = {}, query_list[0] = {}".format(tval, query_list[0]))
        if isinstance(tval, dict):
            val = dfind(query_list[0], tval, targ_str)
            if val:
                return val
        elif tval == query_list[0]:
            return tval

def dfind(query_dict:Dict, target_dict:Dict, targ_str:str = "???"):
    for key, qval in query_dict.items():
        tval = target_dict[key]
        #print("dfind: key = {}, qval = {}, tval = {}".format(key, qval, tval))
        if isinstance(qval, dict):
            val =  dfind(qval, tval, targ_str)
            if val:
                return val
        elif isinstance(qval, list):
            return lfind(qval, tval, targ_str)
        else:
            if qval == targ_str:
                return tval
            if qval != tval:
                break

def find(target_dict:Dict, query_dict:Dict):
    result = dfind(query_dict, target_dict)
    return result

target_dict = {"A":[
    {"key1":"A", "key2":{"key3": "B"}},
    {"key1":"C", "key2":{"key3": "D"}}]
}
query_dict = {"A":[{"key1":"C", "key2":{"key3": "???"}}]}

result = find(target_dict, query_dict)
print("result = {}".format(result))


问:
Cannot control looping when converting video to gif in FFMPEG
I am trying to create a gif that loops twice from a movie, but whatever I try it loops continuously:

```<code>ffmpeg -i animation.mov -loop 2 animation.gif
</code>```

Using ffmpeg version 4.1.3 on Mac

答: Solved by not previewing using Quicklook (spacebar) in OS X </p>

Body:
I am trying to create a gif that loops twice from a movie, but whatever I try it loops continuously:

ffmpeg -i animation.mov -loop 2 animation.gif

Using ffmpeg version 4.1.3 on Mac


问:
How to get element like eg. h1 from data passed to view
I have to fetch one element from data passed to view.
I have div with content like this:

```<code><div class="disc" id="content">
    {!! $clause->contents !!}
</div>
</code>```

It shows some text where i have element with heading 1 - h1.
How can I fetch only this h1 element which I could use in somewhere else in view?

答:
Better practice would be to have additional column for that heading in your database. Eg. $clause->title or $clause->heading, but since you're dealing with that problem you will have to extract that heading through DOM parser.

You can find detailed solution to this on this question which you can integrate into your controller.

Body:
I have to fetch one element from data passed to view.
I have div with content like this:

    {!! $clause->contents !!}

It shows some text where i have element with heading 1 - h1.
How can I fetch only this h1 element which I could use in somewhere else in view?


问:
How to use react-jss with MaterialUI 4?
I've used react-jss with material-ui for a while now. The material-ui 3.x -> 4.x migration guide says that MUI 4 isn't compatible with React JSS 9.x:

https://material-ui.com/guides/migration-v3/

Furthermore, it looks like the react-jss project has been archived:

https://github.com/cssinjs/react-jss

...but JSS is up to at least version 10:

https://cssinjs.org/?v=v10.0.0-alpha.16

So I'm completely confused on how to use React-JSS with MUI 4. Is the import something other than "react-jss": "8.6.1", in package.json? Should I switch to Emotion or Styled Components? So confused.

答:
You can use:

```<code>"react-jss": "10.0.0-alpha.16"
</code>```

https://github.com/cssinjs/react-jss is archived because of it being restructured to be part of the jss monorepo (multiple packages in one GitHub repository): https://github.com/cssinjs/jss/tree/master/packages/react-jss.

Whenever you upgrade Material-UI, you should check to see if the jss version in Material-UI has changed so that you can stay in sync; otherwise you'll be pulling in two versions of jss. You can check the Material-UI jss version here: https://github.com/mui-org/material-ui/blob/master/packages/material-ui-styles/package.json#L48

You should also look into whether you need to be using react-jss directly vs. just using the jss wrappers in Material-UI (e.g. withStyles, makeStyles, etc.).

Title: How to use react-jss with MaterialUI 4?

Body:
You can use:

"react-jss": "10.0.0-alpha.16"

https://github.com/cssinjs/react-jss is archived because of it being restructured to be part of the jss monorepo (multiple packages in one GitHub repository): https://github.com/cssinjs/jss/tree/master/packages/react-jss.

Whenever you upgrade Material-UI, you should check to see if the jss version in Material-UI has changed so that you can stay in sync; otherwise you'll be pulling in two versions of jss. You can check the Material-UI jss version here: https://github.com/mui-org/material-ui/blob/master/packages/material-ui-styles/package.json#L48

You should also look into whether you need to be using react-jss directly vs. just using the jss wrappers in Material-UI (e.g. withStyles, makeStyles, etc.).


问:
Flex: streaming video from YouTube
Is it possible to use the VideoPlayer or VideoDisplay components in Flex 4 to stream a video from YouTube rather than just use the custom YouTube player? How?

I want to serve a video inside a banner.

Thank you.

答: I don't think that's possible from what I know.  If you really want your own video in a banner, why not put the video up on your own server instead of using Google's?</p>

Title: Flex: streaming video from YouTube


问:
running an excel macro via cmd
I wrote a VBA code that takes an excel file and unmerge all the cells in it and copy the value from the merged cell to the newly unmerged cells.
when I'm running the code in the excel it is working well.
when I'm trying to run the cod via the cmd I'm getting an error.
I the code executed from the cmd because it need to run on multiple excel files via SAS.

the VBS code is:

```<code>Sub UnMergeFill(ByVal ws As Worksheet)

Dim cell As Range, joinedCells As Range

For Each cell In ws.UsedRange
    If cell.MergeCells Then
        Set joinedCells = cell.MergeArea
        cell.MergeCells = False
        joinedCells.Value = cell.Value
    End If
Next

End Sub

sub UnMergeFillAllSheets()
    Dim ws As Worksheet
    for Each ws In Worksheets
         UnMergeFill ws
    Next
End Sub
</code>```

The cmd command to run the code:

```<code>"C:\Users\sm\Documents\work\excel_macro\UnMergeFill.vbs" "C:\User\sm\Documents\work\excel_macro\r.xlsx"
</code>```

the error messege I'm getting is:

script:
c:..\UnMergefill.vbs

line: 1

char: 26

error: expectef ')'

code 800A03EE

source Microsoft VBScript compilation error

Thank you all for helping

答:
I could be wrong, but looking at the error code as well as your VBA code, I think that the issue (or at least one of the issues) is that you are missing some parentheses.

```<code>sub UnMergeFillAllSheets()
    Dim ws As Worksheet
    for Each ws In Worksheets
         UnMergeFill(ws) 'Added parentheses
    Next
End Sub
</code>```

Try running your code with those and see if it helps. Thanks and Good Luck!

Title: running an excel macro via cmd

Body:
I wrote a VBA code that takes an excel file and unmerge all the cells in it and copy the value from the merged cell to the newly unmerged cells.
when I'm running the code in the excel it is working well.
when I'm trying to run the cod via the cmd I'm getting an error.
I the code executed from the cmd because it need to run on multiple excel files via SAS.

the VBS code is:

Sub UnMergeFill(ByVal ws As Worksheet)

Dim cell As Range, joinedCells As Range

For Each cell In ws.UsedRange
    If cell.MergeCells Then
        Set joinedCells = cell.MergeArea
        cell.MergeCells = False
        joinedCells.Value = cell.Value
    End If
Next

End Sub

sub UnMergeFillAllSheets()
    Dim ws As Worksheet
    for Each ws In Worksheets
         UnMergeFill ws
    Next
End Sub

The cmd command to run the code:

"C:\Users\sm\Documents\work\excel_macro\UnMergeFill.vbs" "C:\User\sm\Documents\work\excel_macro\r.xlsx"

the error messege I'm getting is:

script:
c:..\UnMergefill.vbs

line: 1

char: 26

error: expectef ')'

code 800A03EE

source Microsoft VBScript compilation error

Thank you all for helping

Body:
I could be wrong, but looking at the error code as well as your VBA code, I think that the issue (or at least one of the issues) is that you are missing some parentheses.

sub UnMergeFillAllSheets()
    Dim ws As Worksheet
    for Each ws In Worksheets
         UnMergeFill(ws) 'Added parentheses
    Next
End Sub

Try running your code with those and see if it helps. Thanks and Good Luck!


问:
How can the values from one dataframe be used to calculate the total number of values that are greater than or lesser than it in a second dataframe?
I have different dataframes named: step1, step2,step5 and so on and each one of them has a column named BackGas_Flow_sccm.

I used the .describe() on the BackGas_Flow_sccm column of every dataframe in order to use the 25% & the 75% to create new features like the IQR, Max & Min . After doing it, I dropped all the other columns and just kept the IQR, Max & Min columns in the dataframe giving the result as follows:

```<code>                    Max                 Min
step1   0.0061032863849765275   0.0023474178403755843
step2   0.0061032863849765275   0.0023474178403755843
step5   0.43849765258215967     0.4309859154929577
step7   0.4394366197183098      0.43192488262910805
step12  0.44178403755868545     0.43051643192488265
step15  0.44413145539906096     0.4291079812206573
step16  0.44272300469483566     0.43145539906103286
step19  0.8201877934272299      0.5610328638497655
step24  0.008450704225352117    0.0009389671361502306
step25  0.0061032863849765275   0.0023474178403755843
step26  0.0061032863849765275   0.0023474178403755843
step27  0.0061032863849765275   0.0023474178403755843
</code>```

Now, I would like to use the values from this dataframe and calculate the number of values that are above the Max value or below the Min value, in the dataframes like step1, step2,step5.

I could do:

```<code>step1[step1['BacksGas_Flow_sccm'] > 0.0061032863849765275]
step1[step1['BacksGas_Flow_sccm'] < 0.0023474178403755843]
</code>```

and it would give me the result as 424 and 135 respectively; meaning that there are 424 values in the step1 df that are above 0.0061032863849765275 and 135 values that are below 0.0023474178403755843. But entering the numbers like 0.0061032863849765275 can be tedious.

So, is there a way this can be achieved in a more efficient manner?

Edit 1

答:
First you should store those dfs into either list or dict

```<code>d={'step1':step1,'step2':step2....}
</code>```

Then we can concat it

```<code>s=pd.concat(d)['BacksGas_Flow_sccm'].unstack(0).describe().loc[['25%','75%']].T
</code>```

After this we can then call for loop

```<code>for x in x.index:
    (d[x]['BacksGas_Flow_sccm'] > s.loc[x,'75%']).sum()
    (d[x]['BacksGas_Flow_sccm'] < s.loc[x,'25%']).sum()
</code>```

Or without for loop

```<code>pd.concat(d)['BacksGas_Flow_sccm'].gt(s['75%'],level=0).sum(level=0)

pd.concat(d)['BacksGas_Flow_sccm'].lt(s['25%'],level=0).sum(level=0)
</code>```

Body:
I have different dataframes named: step1, step2,step5 and so on and each one of them has a column named BackGas_Flow_sccm.

I used the .describe() on the BackGas_Flow_sccm column of every dataframe in order to use the 25% & the 75% to create new features like the IQR, Max & Min . After doing it, I dropped all the other columns and just kept the IQR, Max & Min columns in the dataframe giving the result as follows:

                    Max                 Min
step1   0.0061032863849765275   0.0023474178403755843
step2   0.0061032863849765275   0.0023474178403755843
step5   0.43849765258215967     0.4309859154929577
step7   0.4394366197183098      0.43192488262910805
step12  0.44178403755868545     0.43051643192488265
step15  0.44413145539906096     0.4291079812206573
step16  0.44272300469483566     0.43145539906103286
step19  0.8201877934272299      0.5610328638497655
step24  0.008450704225352117    0.0009389671361502306
step25  0.0061032863849765275   0.0023474178403755843
step26  0.0061032863849765275   0.0023474178403755843
step27  0.0061032863849765275   0.0023474178403755843

Now, I would like to use the values from this dataframe and calculate the number of values that are above the Max value or below the Min value, in the dataframes like step1, step2,step5.

I could do:

step1[step1['BacksGas_Flow_sccm'] > 0.0061032863849765275]
step1[step1['BacksGas_Flow_sccm'] < 0.0023474178403755843]

and it would give me the result as 424 and 135 respectively; meaning that there are 424 values in the step1 df that are above 0.0061032863849765275 and 135 values that are below 0.0023474178403755843. But entering the numbers like 0.0061032863849765275 can be tedious.

So, is there a way this can be achieved in a more efficient manner?

Edit 1

Body:
First you should store those dfs into either list or dict

d={'step1':step1,'step2':step2....}

Then we can concat it

s=pd.concat(d)['BacksGas_Flow_sccm'].unstack(0).describe().loc[['25%','75%']].T

After this we can then call for loop

for x in x.index:
    (d[x]['BacksGas_Flow_sccm'] > s.loc[x,'75%']).sum()
    (d[x]['BacksGas_Flow_sccm'] < s.loc[x,'25%']).sum()

Or without for loop

pd.concat(d)['BacksGas_Flow_sccm'].gt(s['75%'],level=0).sum(level=0)

pd.concat(d)['BacksGas_Flow_sccm'].lt(s['25%'],level=0).sum(level=0)


问:
Error 400 when trying to copy/paste between workbooks
I'm having trouble with Excel VBA with the following: I'm trying to open an existing empty workbook template (pn), copy data from an existing sheet (wb) and paste it into "pn", but I keep getting all kinds of error such as Error 400, Subscript out of range and constant freezing.

I've tried the code with many variations, but mostly (and in my last attempt below) the error happens in the following line:

Workbooks(pn).Sheets("data").Select

Does it have to do with VBA properly getting the opened file name or switching between workbooks? How to properly switch between different workbooks and copy/paste data?

EDIT: also, when running the code on debug mode using ("Step into") it works just fine. I've noticed that the real opened file name only appears when the code waits for the workbook to open entirely or when I alt+tab into it, else its name keeps showing as "Excel" and the error happens!

```<code>'opens template
fileName = Application.GetOpenFilename("Excel-files,*.xlsx", 1, "OPEN TEMPLATE", , False)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error GoTo Err1
Workbooks.Open (fileName)
pn = ActiveWorkbook.Name

'copy and paste between workbooks
Windows(wb).Activate
Workbooks(wb).Sheets("Info").Select
Workbooks(wb).Worksheets("Info").Range("A4:Z1000").Select
Selection.Copy 'Destination:=Workbooks(pn).Sheets("data").Cells(3, 1)
Workbooks(pn).Sheets("data").Select
Range("A3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
</code>```

答:
That worked nicely. From now on I am generally using the following structure in the code:

```<code>Dim wb As Workbook
Dim hld As Workbook
Set wb = ThisWorkbook
...
wb.Sheets("Info1").Range("A2:AP1500").Copy Destination:=hld.Sheets("Info1").Cells(1, 1)
...
</code>```

Sometimes I can only get Copy/Paste or Copy/Destination to work instead of direct assignment of values, for some reason, but still way better than what I was doing before. Thanks!

Body:
I'm having trouble with Excel VBA with the following: I'm trying to open an existing empty workbook template (pn), copy data from an existing sheet (wb) and paste it into "pn", but I keep getting all kinds of error such as Error 400, Subscript out of range and constant freezing.

I've tried the code with many variations, but mostly (and in my last attempt below) the error happens in the following line:

Workbooks(pn).Sheets("data").Select

Does it have to do with VBA properly getting the opened file name or switching between workbooks? How to properly switch between different workbooks and copy/paste data?

EDIT: also, when running the code on debug mode using ("Step into") it works just fine. I've noticed that the real opened file name only appears when the code waits for the workbook to open entirely or when I alt+tab into it, else its name keeps showing as "Excel" and the error happens!

'opens template
fileName = Application.GetOpenFilename("Excel-files,*.xlsx", 1, "OPEN TEMPLATE", , False)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error GoTo Err1
Workbooks.Open (fileName)
pn = ActiveWorkbook.Name

'copy and paste between workbooks
Windows(wb).Activate
Workbooks(wb).Sheets("Info").Select
Workbooks(wb).Worksheets("Info").Range("A4:Z1000").Select
Selection.Copy 'Destination:=Workbooks(pn).Sheets("data").Cells(3, 1)
Workbooks(pn).Sheets("data").Select
Range("A3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Body:
That worked nicely. From now on I am generally using the following structure in the code:

Dim wb As Workbook
Dim hld As Workbook
Set wb = ThisWorkbook
...
wb.Sheets("Info1").Range("A2:AP1500").Copy Destination:=hld.Sheets("Info1").Cells(1, 1)
...

Sometimes I can only get Copy/Paste or Copy/Destination to work instead of direct assignment of values, for some reason, but still way better than what I was doing before. Thanks!


问:
in VHDL, how to check if file exists before opening it?
In Verilog, I can check if a file exists by opening the file and then checking if the file descriptor is zero, and if it is not to assume the file doesn't exist.  For example, as follows:

```<code>    module testbench;

    function file_exists;
        input [80*8:0] filename;
        integer        file;
        integer        error;
    begin
        file = $fopen(filename, "r");
        if (!file) begin
           $display("\nFile Open Failed with Error Code = %x", error);
           file_exists = 0;
        end
        else begin
           $fclose(file);
           file_exists = 1;
        end
    end
    endfunction

    integer x;
    initial begin
       x = file_exists("sdfsdf.txt");
       $display("x: %0b", x);
    end

    endmodule
</code>```

How can I do the same thing in vhdl?

答:
```<code>use ieee.std_logic_1164.all;
use std.textio.all;

entity testebench is
end entity;

architecture sim of testbench is

    impure function file_exists(
        filename : in string
    ) return boolean is
        variable open_status :FILE_OPEN_STATUS;
        file     infile      :text;
    begin
        file_open(open_status, infile, filename, read_mode);
        if open_status /= open_ok then
            return false;
        else
            file_close(infile);
            return true;
        end if;
    end function;

begin

    process
        f1 :boolean;
    begin
        f1 = file_exists("fgsfgsdfg.txt")
        report "found: " & boolean'image(f1);
    end process;

end architecture;
</code>```

Body:
In Verilog, I can check if a file exists by opening the file and then checking if the file descriptor is zero, and if it is not to assume the file doesn't exist.  For example, as follows:

    module testbench;

    function file_exists;
        input [80*8:0] filename;
        integer        file;
        integer        error;
    begin
        file = $fopen(filename, "r");
        if (!file) begin
           $display("\nFile Open Failed with Error Code = %x", error);
           file_exists = 0;
        end
        else begin
           $fclose(file);
           file_exists = 1;
        end
    end
    endfunction

    integer x;
    initial begin
       x = file_exists("sdfsdf.txt");
       $display("x: %0b", x);
    end

    endmodule

How can I do the same thing in vhdl?


问:
How to do two events with one button
I need to do 2 events with 1 button in my react-native app

This is my code

```<code>onPress={navigation.getParam('HVentana2')} onPress={(ref) => this._menu.hide()}
</code>```

答:
Call to one function that contains what you want:

```<code>onPress={this.onClick}
</code>```

and create `onClick function:

```<code>onClick = () => {
    navigation.getParam('HVentana2')
    this._menu.hide()
}
</code>```

Title: How to do two events with one button

Body:
I need to do 2 events with 1 button in my react-native app

This is my code

onPress={navigation.getParam('HVentana2')} onPress={(ref) => this._menu.hide()}

Body:
Call to one function that contains what you want:

onPress={this.onClick}

and create `onClick function:

onClick = () => {
    navigation.getParam('HVentana2')
    this._menu.hide()
}


问:
how to send mail from .net?
i wrote the method as below i got the error as The specified string is not in the form required for an e-mail address. pls help me</p>

```<code>SendMail("xyz@gmail.com","hi","heloo");

public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
    {

         string smtphost ="smtp.gmail.com";
            int smtpport = 100;
            string smtpuser ="xyz";
            string smtppwd = "xyz";
            SmtpClient client = null;

            string MessageBody = string.Empty;
            try
            {

                message = new MailMessage();
                message.From = new MailAddress(smtpuser);
                message.To.Add(toMailAddress);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = mailSubject;
                message.Body = mailMessage.ToString();

                message.IsBodyHtml = true;

                client = new SmtpClient();
                client.Host = smtphost;

                client.Port = smtpport;
                client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
                client.Send(message);
            }
            catch (Exception ex)
            {
                string x = ex.Message;
            }
            return true;
        }
</code>```

答:
Make sure the toMailAddress, and smtpuser are valid email address.
Try, Using smtpport = 587; provided by Gmail for Outgoing Mails (SMTP).
Hope this will make it work fine. Please list out the errors you encounter. </p>

Title: how to send mail from .net?

Body:
i wrote the method as below i got the error as The specified string is not in the form required for an e-mail address. pls help me

SendMail("xyz@gmail.com","hi","heloo");

public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
    {

         string smtphost ="smtp.gmail.com";
            int smtpport = 100;
            string smtpuser ="xyz";
            string smtppwd = "xyz";
            SmtpClient client = null;

            string MessageBody = string.Empty;
            try
            {

                message = new MailMessage();
                message.From = new MailAddress(smtpuser);
                message.To.Add(toMailAddress);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = mailSubject;
                message.Body = mailMessage.ToString();

                message.IsBodyHtml = true;

                client = new SmtpClient();
                client.Host = smtphost;

                client.Port = smtpport;
                client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
                client.Send(message);
            }
            catch (Exception ex)
            {
                string x = ex.Message;
            }
            return true;
        }


问:
Is there a way to read EC2InstanceId in Lambda Function(Boto3) passed by SNS
I am looking to get EC2InstanceId from my Lambda function but somehow I am getting an error string indices must be integers: TypeError
Here is the code:

```<code>from __future__ import print_function
import json
import re
import boto3

def lambda_handler(event, context):
    """
    lambda handler function.
    """
    message = event['Records'][0]['Sns']['Message']
    print(message)
    ec2InstanceId = event['Records'][0]['Sns']['Message']['EC2InstanceId']
    print(ec2InstanceId)
</code>```

However, I am getting the following output from print(message):

```<code>{
    "Progress": 50,
    "AccountId": "*****************",
    "Description": "Launching a new EC2 instance: i-0316df8d5159ee6a7",
    "RequestId": "4b15abf1-7b48-4e9b-528a-891992eabc86",
    "EndTime": "2019-05-28T02:57:46.975Z",
    "AutoScalingGroupARN": "arn:aws:autoscaling:us-east-1:*****************:autoScalingGroup:*****************:autoScalingGroupName/dynamic-host-asg",
    "ActivityId": "*****************",
    "StartTime": "2019-05-28T02:57:13.747Z",
    "Service": "AWS Auto Scaling",
    "Time": "2019-05-28T02:57:46.975Z",
    "EC2InstanceId": "i-0316df8d5159ee6a7",
    "StatusCode": "InProgress",
    "StatusMessage": "",
    "Details": {
        "Subnet ID": "*****************",
        "Availability Zone": "us-east-1b"
    },
    "AutoScalingGroupName": "dynamic-host-asg",
    "Cause": "At 2019-05-28T02:56:47Z a user request update of AutoScalingGroup constraints to min: 1, max: 2, desired: 1 changing the desired capacity from 0 to 1.  At 2019-05-28T02:57:11Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 1.",
    "Event": "autoscaling:EC2_INSTANCE_LAUNCH"
}
</code>```

But print(ec2InstanceId) is giving me following error:

```<code>string indices must be integers: TypeError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 27, in lambda_handler
ec2InstanceId = event['Records'][0]['Sns']['Message']['EC2InstanceId']
TypeError: string indices must be integers
</code>```

Could you please help me to correct this ?

答:
I got it working like this</p>

```<code>    message = event['Records'][0]['Sns']['Message']
    if isinstance(message, str):
        try:
            message = json.loads(message)
        except Exception as e:
            print(e)
    elif isinstance(message, list):
        message = message[0]
    asg_instances_list=message['EC2InstanceId']
</code>```

Body:
I am looking to get EC2InstanceId from my Lambda function but somehow I am getting an error string indices must be integers: TypeError
Here is the code:

from __future__ import print_function
import json
import re
import boto3

def lambda_handler(event, context):
    """
    lambda handler function.
    """
    message = event['Records'][0]['Sns']['Message']
    print(message)
    ec2InstanceId = event['Records'][0]['Sns']['Message']['EC2InstanceId']
    print(ec2InstanceId)

However, I am getting the following output from print(message):

{
    "Progress": 50,
    "AccountId": "*****************",
    "Description": "Launching a new EC2 instance: i-0316df8d5159ee6a7",
    "RequestId": "4b15abf1-7b48-4e9b-528a-891992eabc86",
    "EndTime": "2019-05-28T02:57:46.975Z",
    "AutoScalingGroupARN": "arn:aws:autoscaling:us-east-1:*****************:autoScalingGroup:*****************:autoScalingGroupName/dynamic-host-asg",
    "ActivityId": "*****************",
    "StartTime": "2019-05-28T02:57:13.747Z",
    "Service": "AWS Auto Scaling",
    "Time": "2019-05-28T02:57:46.975Z",
    "EC2InstanceId": "i-0316df8d5159ee6a7",
    "StatusCode": "InProgress",
    "StatusMessage": "",
    "Details": {
        "Subnet ID": "*****************",
        "Availability Zone": "us-east-1b"
    },
    "AutoScalingGroupName": "dynamic-host-asg",
    "Cause": "At 2019-05-28T02:56:47Z a user request update of AutoScalingGroup constraints to min: 1, max: 2, desired: 1 changing the desired capacity from 0 to 1.  At 2019-05-28T02:57:11Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 1.",
    "Event": "autoscaling:EC2_INSTANCE_LAUNCH"
}

But print(ec2InstanceId) is giving me following error:

string indices must be integers: TypeError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 27, in lambda_handler
ec2InstanceId = event['Records'][0]['Sns']['Message']['EC2InstanceId']
TypeError: string indices must be integers

Could you please help me to correct this ?

Body:
I got it working like this

    message = event['Records'][0]['Sns']['Message']
    if isinstance(message, str):
        try:
            message = json.loads(message)
        except Exception as e:
            print(e)
    elif isinstance(message, list):
        message = message[0]
    asg_instances_list=message['EC2InstanceId']