问:
Maven won't run JUnit5 tests
(BTW: Yes, I am including the Maven surefire plugin in my pom.)

I can't persuade Maven to run my JUnit5 tests.

I am using the Maven surefire plugin version 2.22

I tried downgrading the surefire plugin to 2.19

I'm using the same dependencies and plugins as another project which runs fine

If I import the project into eclipse, eclipse finds and executes the tests

The class file for the test, app.AppTest.class, is in directory target\test-classes\app

I don't get any error messages from Maven; it just says "Tests run: 0, Failures: 0, Errors: 0, Skipped: 0"

I am including the contents of my pom, below. Can anyone tell me what I'm doing wrong? Thanks for the help.

```<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>uw.syp.java</groupId>
  <artifactId>Temp1</artifactId>
  <packaging>jar</packaging>
  <version>01</version>
  <name>Temp1</name>
  <url>http://maven.apache.org</url>

    <properties>
       <developer>JesseJW</developer>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.3.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.3.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgs>
                        <arg>-Xlint:all</arg>
                        <arg>-Xlint:-serial</arg>
                    </compilerArgs>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

As requested: source code including imports:
    package app;

```<code>import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

import java.net.URL;
import javax.swing.JOptionPane;

class AppTest
{
    void test()
    {
        System.out.println( "*************" );
        URL resURL  =  getClass().getClassLoader().getResource( "ResFile.txt" );
        System.out.println( resURL );
        assertNotNull( resURL );
        if ( resURL != null )
        {
            System.out.println( resURL.getPath() );
        }
    }
}
</code>```

答:
It seems that you missed the annotation on your test methods. Just adapt your code to:</p>

```<code>import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

import java.net.URL;
import javax.swing.JOptionPane;

class AppTest
{
    @Test
    void test()
    {
        System.out.println( "*************" );
        URL resURL  =  getClass().getClassLoader().getResource( "ResFile.txt" );
        System.out.println( resURL );
        assertNotNull( resURL );
        if ( resURL != null )
        {
            System.out.println( resURL.getPath() );
        }
    }
}
</code>```

Title: Maven won't run JUnit5 tests

Body:
(BTW: Yes, I am including the Maven surefire plugin in my pom.)

I can't persuade Maven to run my JUnit5 tests.

I am using the Maven surefire plugin version 2.22

I tried downgrading the surefire plugin to 2.19

I'm using the same dependencies and plugins as another project which runs fine

If I import the project into eclipse, eclipse finds and executes the tests

The class file for the test, app.AppTest.class, is in directory target\test-classes\app

I don't get any error messages from Maven; it just says "Tests run: 0, Failures: 0, Errors: 0, Skipped: 0"

I am including the contents of my pom, below. Can anyone tell me what I'm doing wrong? Thanks for the help.

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>uw.syp.java</groupId>
  <artifactId>Temp1</artifactId>
  <packaging>jar</packaging>
  <version>01</version>
  <name>Temp1</name>
  <url>http://maven.apache.org</url>

    <properties>
       <developer>JesseJW</developer>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.3.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.3.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgs>
                        <arg>-Xlint:all</arg>
                        <arg>-Xlint:-serial</arg>
                    </compilerArgs>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
</project>

As requested: source code including imports:
    package app;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

import java.net.URL;
import javax.swing.JOptionPane;

class AppTest
{
    void test()
    {
        System.out.println( "*************" );
        URL resURL  =  getClass().getClassLoader().getResource( "ResFile.txt" );
        System.out.println( resURL );
        assertNotNull( resURL );
        if ( resURL != null )
        {
            System.out.println( resURL.getPath() );
        }
    }
}

Body:
It seems that you missed the annotation on your test methods. Just adapt your code to:

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

import java.net.URL;
import javax.swing.JOptionPane;

class AppTest
{
    @Test
    void test()
    {
        System.out.println( "*************" );
        URL resURL  =  getClass().getClassLoader().getResource( "ResFile.txt" );
        System.out.println( resURL );
        assertNotNull( resURL );
        if ( resURL != null )
        {
            System.out.println( resURL.getPath() );
        }
    }
}


来源: stackexchange

问:
how to transpose a dataset from wide format to long format in R
The dataset is similar to the following:

```<code>ID SEX bloodpressure1 bloodpressure2 bloodpressure3 weight1 weight2 weight3
1   1     90              100           NA            100     105     112
2   0      101            120          115            140     NA     150
</code>```

*There are over 200 variables

I want the output to be as following:

```<code>ID SEX n bloodpressure weight
1   1  1      90        100
1   1  2      100       105
1   1  3      NA        112
2   0  1      101       140
2   0  2      120       NA
2   0  3      115       150
</code>```

I tried solutions offered in this link:
Using Reshape from wide to long in R
but since the variable names in my dataset does not have '_' between the letter and the number, I don't how to separate the column name to make it work.

Thank you in advance for any help!

答:
Using tidyr::pivot_longer :

```<code>tidyr::pivot_longer(df, cols = -c(ID, SEX),
                   names_to = c('.value', 'n'),
                   names_pattern = '(.*)(\\d+)')

# A tibble: 6 x 5
#     ID   SEX n     bloodpressure weight
#  <int> <int> <chr>         <int>  <int>
#1     1     1 1                90    100
#2     1     1 2               100    105
#3     1     1 3                NA    112
#4     2     0 1               101    140
#5     2     0 2               120     NA
#6     2     0 3               115    150
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The dataset is similar to the following:

ID SEX bloodpressure1 bloodpressure2 bloodpressure3 weight1 weight2 weight3
1   1     90              100           NA            100     105     112
2   0      101            120          115            140     NA     150

*There are over 200 variables

I want the output to be as following:

ID SEX n bloodpressure weight
1   1  1      90        100
1   1  2      100       105
1   1  3      NA        112
2   0  1      101       140
2   0  2      120       NA
2   0  3      115       150

I tried solutions offered in this link:
Using Reshape from wide to long in R
but since the variable names in my dataset does not have '_' between the letter and the number, I don't how to separate the column name to make it work.

Thank you in advance for any help!

Body:
Using tidyr::pivot_longer :

tidyr::pivot_longer(df, cols = -c(ID, SEX),
                   names_to = c('.value', 'n'),
                   names_pattern = '(.*)(\\d+)')

# A tibble: 6 x 5
#     ID   SEX n     bloodpressure weight
#  <int> <int> <chr>         <int>  <int>
#1     1     1 1                90    100
#2     1     1 2               100    105
#3     1     1 3                NA    112
#4     2     0 1               101    140
#5     2     0 2               120     NA
#6     2     0 3               115    150


问:
assigning the value to a list inside a class
I have following class. I have a list inside the class. How do I assign the values to the properties inside the list. Below is my code:

```<code>public class Identity
    {

        public Identity()
        {
            header = new List<Header>();
            control = new List<control>();
        }
        public List<Header> header { get; set; }
        public List<control> control{ get; set; }
        public string firstName { get; set; }
        public string LastName { get; set; }
  }
</code>```

Below is the header class:

```<code>  public class Header
    {
        public string tenantId { get; set; }
        public string test2{ get; set; }
        public string test2{ get; set; }
    }
</code>```

How can I assign the value of "Hello" to tenantId.

any help will be appreciated.

答:
```<code>// Adding to list inside the Identity class
public class Identity
{
    public Identity()
    {
        header = new List<Header>();
        control = new List<control>();
    }
    public List<Header> header { get; set; }
    public List<control> control { get; set; }
    public string firstName { get; set; }
    public string LastName { get; set; }

    public void AddToHeader(string tenantIdParam)
    {
        var newHeaderObject = new Header
        {
            tenantId = tenantIdParam
        };

        header.Add(newHeaderObject);
    }
}

//Adding to the list outside the Identity class (since header is public and has a setter)
public class OtherClass
{
   public void DoSomething()
   {
      var identity = new Identity();

      var newHeaderObject = new Header
      {
         tenantId = tenantIdParam
      };

      identity.Header.Add(newHeaderObject);
   }
}
</code>```

Body:
I have following class. I have a list inside the class. How do I assign the values to the properties inside the list. Below is my code:

public class Identity
    {

        public Identity()
        {
            header = new List();
            control = new List<control>();
        }
        public List header { get; set; }
        public List<control> control{ get; set; }
        public string firstName { get; set; }
        public string LastName { get; set; }
  }

Below is the header class:

  public class Header
    {
        public string tenantId { get; set; }
        public string test2{ get; set; }
        public string test2{ get; set; }
    }

How can I assign the value of "Hello" to tenantId.

any help will be appreciated.


问:
How to use Python XML findall to find '<v:imagedata r:id="rId7" o:title="1-REN"/>'
I'm trying to do a find all from a Word document for <v:imagedata r:id="rId7" o:title="1-REN"/> with namespace xmlns:v="urn:schemas-microsoft-com:vml" and I cannot figure out what on earth the syntax is.

The docs only cover the very straight forward case and with the URN and VML combo thrown in I can't seem to get any of the examples I've seen online to work. Does anyone happen to know what it is?

I'm trying to do something like this:

```<code>namespace = {'v': "urn:schemas-microsoft-com:vml"}

results = ET.fromstring(xml).findall("imagedata", namespace)
for image_id in results:
    print(image_id)
</code>```

Edit: What @aneroid wrote is 1000% the right answer and super helpful. You should upvote it. That said, after understanding all that - I went with the BS4 answer because it does the entire job in two lines exactly how I need it to . If you don't actually care about the namespaces it seems waaaaaaay easier.

答:
ET.findall() vs BS4.find_all():

ElementTree's findall() is not recursive by default*. It's only going to find direct children of the node provided. So in your case, it's only searching for image nodes directly under the root element.

* as per mzjn's comment below, prefixing the match argument (tag or path) with ".//" will search for that node anywhere in the tree, since it's supports XPath's.

BeautifulSoup's find_all() searches all descendants. So it seaches for 'imagedata' nodes anywhere in the tree.

However, ElementTree.iter() does search all descendants. Using the 'working with namespaces' example in the docs:

```<code>>>> for char in root.iter('{http://characters.example.com}character'):
...     print(' |-->', char.text)
...
 |--> Lancelot
 |--> Archie Leach
 |--> Sir Robin
 |--> Gunther
 |--> Commander Clement
</code>```

Sadly, ET.iterfind() which works with namespaces as a dict (like ET.findall), also does not search descendants, only direct children by default*. Just like ET.findall. Apart from how empty strings '' in the tags are treated wrt the namespace, and one returns a list while the other returns an iterator, I can't say there's a meaningful difference between ET.findall and ET.iterfind.

* As above for ET.findall(), prefixing ".//" makes it search the entire tree (matches with any node).

When you use the namespaces with ET, you still need the namespace name with the tag. The results line should be:

```<code>namespace = {'v': "urn:schemas-microsoft-com:vml"}
results = ET.fromstring(xml).findall("v:imagedata", namespace)  # note the 'v:'
</code>```

Also, the 'v' doesn't need to be a 'v', you could change it to something more meaningful if needed:

```<code>namespace = {'image': "urn:schemas-microsoft-com:vml"}
results = ET.fromstring(xml).findall("image:imagedata", namespace)
</code>```

Of course, this still won't necessarily get you all the imagedata elements if they aren't direct children of the root. For that, you'd need to create a recursive function to do it for you. See this answer on SO for how. Note, while that answer does a recursive search, you are likely to hit Python's recursion limit if the descendant depth is too...deep.

To get all the imagedata elements anywhere in the tree, use the ".//" prefix:

```<code>results = ET.fromstring(xml).findall(".//v:imagedata", namespace)
</code>```

Body:
I'm trying to do a find all from a Word document for <v:imagedata r:id="rId7" o:title="1-REN"/> with namespace xmlns:v="urn:schemas-microsoft-com:vml" and I cannot figure out what on earth the syntax is.

The docs only cover the very straight forward case and with the URN and VML combo thrown in I can't seem to get any of the examples I've seen online to work. Does anyone happen to know what it is?

I'm trying to do something like this:

namespace = {'v': "urn:schemas-microsoft-com:vml"}

results = ET.fromstring(xml).findall("imagedata", namespace)
for image_id in results:
    print(image_id)

Edit: What @aneroid wrote is 1000% the right answer and super helpful. You should upvote it. That said, after understanding all that - I went with the BS4 answer because it does the entire job in two lines exactly how I need it to . If you don't actually care about the namespaces it seems waaaaaaay easier.

Body:
ET.findall() vs BS4.find_all():

ElementTree's findall() is not recursive by default*. It's only going to find direct children of the node provided. So in your case, it's only searching for image nodes directly under the root element.

* as per mzjn's comment below, prefixing the match argument (tag or path) with ".//" will search for that node anywhere in the tree, since it's supports XPath's.

BeautifulSoup's find_all() searches all descendants. So it seaches for 'imagedata' nodes anywhere in the tree.

However, ElementTree.iter() does search all descendants. Using the 'working with namespaces' example in the docs:

>>> for char in root.iter('{http://characters.example.com}character'):
...     print(' |-->', char.text)
...
 |--> Lancelot
 |--> Archie Leach
 |--> Sir Robin
 |--> Gunther
 |--> Commander Clement

Sadly, ET.iterfind() which works with namespaces as a dict (like ET.findall), also does not search descendants, only direct children by default*. Just like ET.findall. Apart from how empty strings '' in the tags are treated wrt the namespace, and one returns a list while the other returns an iterator, I can't say there's a meaningful difference between ET.findall and ET.iterfind.

* As above for ET.findall(), prefixing ".//" makes it search the entire tree (matches with any node).

When you use the namespaces with ET, you still need the namespace name with the tag. The results line should be:

namespace = {'v': "urn:schemas-microsoft-com:vml"}
results = ET.fromstring(xml).findall("v:imagedata", namespace)  # note the 'v:'

Also, the 'v' doesn't need to be a 'v', you could change it to something more meaningful if needed:

namespace = {'image': "urn:schemas-microsoft-com:vml"}
results = ET.fromstring(xml).findall("image:imagedata", namespace)

Of course, this still won't necessarily get you all the imagedata elements if they aren't direct children of the root. For that, you'd need to create a recursive function to do it for you. See this answer on SO for how. Note, while that answer does a recursive search, you are likely to hit Python's recursion limit if the descendant depth is too...deep.

To get all the imagedata elements anywhere in the tree, use the ".//" prefix:

results = ET.fromstring(xml).findall(".//v:imagedata", namespace)


问:
I am getting anCSRF token mismatch exception in Safari on Laravel 7.X when I post a form request using window.open
When I try to post a form request using window.open script, it will cause csrf token mismatch exception in Safari on Laravel 7.X. I've tested Chrome and Firefox and they're just fine. Safari also works perfectly with same code on Laravel 6.18.16.

Environments

Laravel Version: 7.13.0

PHP Version: 7.2.31

Database Driver & Version: n/a

macOS: 10.15.5

Safari: 13.1.1

Chrome: 83.0.4103.61

Firefox: 76.0.1

Steps To Reproduce:

Install a fresh laravel app

```<code>composer create-project --prefer-dist laravel/laravel popup7
</code>```

web.php

Route::get('/', function () {
    return view('welcome');
});

Route::post('/blank', function () {
    return 'blank page';
});
```

<ol start="3">
<li>welcome.blade.php</li>
</ol>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <script>
            function openPopup(target) {
                window.open("", target + "_popup", "width=430,height=640,scrollbar=yes");
                let form = document.getElementById(target);
                form.target = target + "_popup";
                form.submit();
            }
        </script>
    </head>
    <body>
    <form id="mobile" name="mobile" action="/blank" method="POST">
        @csrf
        <button onclick="openPopup('mobile');">
            open
        </button>
    </form>
    </body>
</html>
</code>```

click 'open' button

Additional Information

There is no proper cookie header for /blank request on Laravel 7.X

request/response header for /blank in Safari on Laravel 7.X
- request

response

request/response header for /blank in Safari on Laravel 6.18.16
- request

response

答:
Window.open is a GET request and without considering it's request method window.open can't carry your csrf token since csrf token is encrypted and stored in session so what you can do is to send an ajax request
Maybe this post can help you Laravel csrf token mismatch for ajax POST Request

Body:
When I try to post a form request using window.open script, it will cause csrf token mismatch exception in Safari on Laravel 7.X. I've tested Chrome and Firefox and they're just fine. Safari also works perfectly with same code on Laravel 6.18.16.

Environments

Laravel Version: 7.13.0

PHP Version: 7.2.31

Database Driver & Version: n/a

macOS: 10.15.5

Safari: 13.1.1

Chrome: 83.0.4103.61

Firefox: 76.0.1

Steps To Reproduce:

Install a fresh laravel app

composer create-project --prefer-dist laravel/laravel popup7

web.php

Route::get('/', function () {
    return view('welcome');
});

Route::post('/blank', function () {
    return 'blank page';
});

welcome.blade.php

<!DOCTYPE html>
getLocale()) }}">

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

    <form id="mobile" name="mobile" action="/blank" method="POST">
        @csrf
        <button onclick="openPopup('mobile');">
            open
        </button>
    </form>

click 'open' button

Additional Information

There is no proper cookie header for /blank request on Laravel 7.X

request/response header for /blank in Safari on Laravel 7.X
- request

response

request/response header for /blank in Safari on Laravel 6.18.16
- request

response


问:
android sqlite query error
I have this code to check if the values of (lang) and (lat) exist or not. If they don't exist the program crashed instead of the function returning true. Why?

```<code>public boolean pointNotExist(int lat, int lang)
{
    Cursor r= db.query(DATABASE_TABLE3, new String[] {
                    "_id",
                    "point_name",
                    "point_langtitude",
                    "point_latitude",
                    "No_of_visits"
                    },
                "point_langtitude"+"=" +lang+ " and " +"point_latitude"+ "="+lat,
                null,
                null,
                null,
                null);
    if(r==null)
    {
        r.close();
        return true;
    }
    else
    {
        r.moveToFirst();
        ContentValues args = new ContentValues();
        args.put("No_of_visits", 7);
        boolean d=db.update(DATABASE_TABLE3, args,
        "_id"  + "=" + r.getInt(0), null) > 0;
        return false;
    }
}
</code>```

This is the logCat :

```<code>ERROR/Database(32321):
    Error inserting points_counter=2 point_langtitude=-10084093 _id=16 point_latitude=37422005
ERROR/Database(32321):
    android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
</code>```

The inserting Points_Counter is a counter in another class and when this counter =2 this (pointNotExist) function invoked.

The problem occurred before else statement.

This is the inserting code:

```<code>public void insertPointOfIntrest(int lat, int lang,String name)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put("point_langtitude", lang);
    initialValues.put("point_latitude", lat);
    initialValues.put("point_name", name);
    initialValues.put("No_of_visits",1);
    db.insert(DATABASE_TABLE3, null, initialValues);
}
</code>```

This is the creating table code:

```<code>//creating table
track_pointOfInterest db.execSQL(
        "create table pointOfIntrest (_id integer primary key autoincrement, "
        +"point_name text,"
        + "point_langtitude integer, point_latitude integer, "
        + "No_of_visits );"
    );
</code>```

答:
Please replace this.

long d=db.update(DATABASE_TABLE3, args,
                    "_id"  + "=" + r.getInt(0), null) > 0;

ContentLicense: CC BY-SA 3.0

Title: android sqlite query error

Body:
I have this code to check if the values of (lang) and (lat) exist or not. If they don't exist the program crashed instead of the function returning true. Why?

public boolean pointNotExist(int lat, int lang)
{
    Cursor r= db.query(DATABASE_TABLE3, new String[] {
                    "_id",
                    "point_name",
                    "point_langtitude",
                    "point_latitude",
                    "No_of_visits"
                    },
                "point_langtitude"+"=" +lang+ " and " +"point_latitude"+ "="+lat,
                null,
                null,
                null,
                null);
    if(r==null)
    {
        r.close();
        return true;
    }
    else
    {
        r.moveToFirst();
        ContentValues args = new ContentValues();
        args.put("No_of_visits", 7);
        boolean d=db.update(DATABASE_TABLE3, args,
        "_id"  + "=" + r.getInt(0), null) > 0;
        return false;
    }
}

This is the logCat :

ERROR/Database(32321):
    Error inserting points_counter=2 point_langtitude=-10084093 _id=16 point_latitude=37422005
ERROR/Database(32321):
    android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed

The inserting Points_Counter is a counter in another class and when this counter =2 this (pointNotExist) function invoked.

The problem occurred before else statement.

This is the inserting code:

public void insertPointOfIntrest(int lat, int lang,String name)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put("point_langtitude", lang);
    initialValues.put("point_latitude", lat);
    initialValues.put("point_name", name);
    initialValues.put("No_of_visits",1);
    db.insert(DATABASE_TABLE3, null, initialValues);
}

This is the creating table code:

//creating table
track_pointOfInterest db.execSQL(
        "create table pointOfIntrest (_id integer primary key autoincrement, "
        +"point_name text,"
        + "point_langtitude integer, point_latitude integer, "
        + "No_of_visits );"
    );


问:
Can you get all positive numbers in python?
So I am playing around in python and I thought:

"Is there a built in list or function that already has infinite numbers, if not how could I build one?"

I did some research and found...
Nothing
That is why I am here!
If you don't know what I mean it would be this but infinite:

b = [1,2,3,4,5,6,7,8,9]

etc;

If there is please tell me! Thank you!
Edit: Thank you!

答:
You can define your own infinite list using a generator function without any module imports.

```<code>def infinite_list():
    n = 1
    while True:
         yield n
         n += 1

my_list = infinite_list()
</code>```

Each time you want the next number call the next method:

```<code>next(my_list)

</code>```

You can also iterate over it but it will, of course, be an infinite loop:

```<code>for elem in my_list:
    //infinite loop
</code>```

Body:
You can define your own infinite list using a generator function without any module imports.

def infinite_list():
    n = 1
    while True:
         yield n
         n += 1

my_list = infinite_list()

Each time you want the next number call the next method:

next(my_list)

You can also iterate over it but it will, of course, be an infinite loop:

for elem in my_list:
    //infinite loop


问:
Nextjs dynamic routes - how to pass props from parent to dynamic route child
Using next@latest, and their dynamic routing features. I have

/pages/index.tsx and /pages/department/[slug]/index.tsx. The first index.tsx is using getStaticProps to pull in a bit of data. During dev this data is an auto-generated array of objects. I am then rendering these objects via props.departments in the index component.

I am showing a list of departments, and want to link an item to a single page:

```<code>{departments.map(dept => (
  <Link
    as={`/department/${dept.slug}`}
    href="/department/[slug]"
  >
    ...
  </Link>
)}
</code>```

There seems to be no way to pass down props since there is no obvious parent/child connection.

Do I have to query a single department in the [slug]/index.tsx, should I use react useContext, or is there a better design approach which would take care of the issue?

Thanks for any guidance.

答:
If you choose to use context API to share state between the two routes /pages/index.tsx and /pages/department/[slug]/index.tsx you have to wrap your App component with the context provider in _app.tsx. Which will lead to another problem, if you have three more routes which don't need the data they will also be children to the context provider without using the values from the context.

I suggest querying the data in data fetching methods i.e. getStaticPaths and getStaticProps if using static generation and getServerSideProps is using server-side rendering for a single department.

Here is what some pseudo-code might look like for /pages/department[slug]/index.tsx

if using static generation

export const getStaticPaths: GetStaticPaths = async () => {
  let paths: {params: { slug: string;}}[] = [];

  // generate the paths for the pages you want to render
  return {
    paths,
    fallback: false // false if you know all the slugs that you want to generate ahead of time
  }

}

interface IProps {
  // props for your page
}

export const getStaticProps: GetStaticProps<IProps> = async (context) => {
   // get the slug
   const slug = context.params?.slug;

   // query the data based on slug

   return {
     props: {
       // return the queried data as props
     }
   }
}

```

<h3>If using server-side-rendering</h3>

<pre class="lang-js prettyprint-override"><code>interface IProps {
  // data you need as props
}

export const getServerSideProps: GetServerSideProps<IProps> = async (context) => {
  // get the slug
  const slug = context.params.slug

  // query the data

  return {
    props: {
       // return the queried data
    }

  }

}

</code>```

P.S- getStaticProps will be called once for each path returned from getStaticPaths at build time. getServerSideProps will be called as per request basis, so choose how do you want to fetch the data based on your need.

Body:
Using next@latest, and their dynamic routing features. I have

/pages/index.tsx and /pages/department/[slug]/index.tsx. The first index.tsx is using getStaticProps to pull in a bit of data. During dev this data is an auto-generated array of objects. I am then rendering these objects via props.departments in the index component.

I am showing a list of departments, and want to link an item to a single page:

{departments.map(dept => (
  <Link
    as={`/department/${dept.slug}`}
    href="/department/[slug]"
  >
    ...
  </Link>
)}

There seems to be no way to pass down props since there is no obvious parent/child connection.

Do I have to query a single department in the [slug]/index.tsx, should I use react useContext, or is there a better design approach which would take care of the issue?

Thanks for any guidance.

Body:
If you choose to use context API to share state between the two routes /pages/index.tsx and /pages/department/[slug]/index.tsx you have to wrap your App component with the context provider in _app.tsx. Which will lead to another problem, if you have three more routes which don't need the data they will also be children to the context provider without using the values from the context.

I suggest querying the data in data fetching methods i.e. getStaticPaths and getStaticProps if using static generation and getServerSideProps is using server-side rendering for a single department.

Here is what some pseudo-code might look like for /pages/department[slug]/index.tsx

if using static generation

export const getStaticPaths: GetStaticPaths = async () => {
  let paths: {params: { slug: string;}}[] = [];

  // generate the paths for the pages you want to render
  return {
    paths,
    fallback: false // false if you know all the slugs that you want to generate ahead of time
  }

}

interface IProps {
  // props for your page
}

export const getStaticProps: GetStaticProps<IProps> = async (context) => {
   // get the slug
   const slug = context.params?.slug;

   // query the data based on slug

   return {
     props: {
       // return the queried data as props
     }
   }
}

If using server-side-rendering

interface IProps {
  // data you need as props
}

export const getServerSideProps: GetServerSideProps<IProps> = async (context) => {
  // get the slug
  const slug = context.params.slug

  // query the data

  return {
    props: {
       // return the queried data
    }

  }

}

P.S- getStaticProps will be called once for each path returned from getStaticPaths at build time. getServerSideProps will be called as per request basis, so choose how do you want to fetch the data based on your need.


问:
String confusion in Javascript with regard to dynamically loading a path
I've encountered something very peculiar in Javascript, which I can't explain.  Simply put, I'm building a dynamic Button component in React in which one can optionally pass in the path of an icon file.

This approach works perfectly:

```<code>const image = require('../styling/assets/images/search-icon.svg');

<button className='button' onClick={props.handleButtonClick}>
  <img className='button-icon' src={image} />
  <p>{props.label}</p>
</button>
</code>```

But it fails if I change the first line to these two:

```<code>const path = '../styling/assets/images/search-icon.svg';
const image = require(path);
</code>```

In this second case I get this error: Error: Cannot find module '../styling/assets/images/search-icon.svg'

Fundamentally the two approaches seem equivalent to me but apparently not.

Why does the 2nd approach fail?

答:
According to the internet: "require is resolved during packaging not during runtime".

https://github.com/facebook/react-native/issues/6391

Body:
I've encountered something very peculiar in Javascript, which I can't explain.  Simply put, I'm building a dynamic Button component in React in which one can optionally pass in the path of an icon file.

This approach works perfectly:

const image = require('../styling/assets/images/search-icon.svg');

<button className='button' onClick={props.handleButtonClick}>

{props.label}

</button>

But it fails if I change the first line to these two:

const path = '../styling/assets/images/search-icon.svg';
const image = require(path);

In this second case I get this error: Error: Cannot find module '../styling/assets/images/search-icon.svg'

Fundamentally the two approaches seem equivalent to me but apparently not.

Why does the 2nd approach fail?


问:
Vscode indent guide: how can I lessen (not hide) vertical lines that is too many / aggresive?

I am new to vscode, how can I get only one vertical line for each indented block, or... just mask it less ugly... like this...

答:
I know this is not a perfect solution, but

According to vscode doc of ThemeColor,
there is

editorIndentGuide.background: Color of the editor indentation guides.

editorIndentGuide.activeBackground: Color of the active editor indentation guide.

So I set editorIndentGuide.background to the value of editor.background

```<code>{
  ...other thing...
  "workbench.colorCustomizations": {
    "editorIndentGuide.background": "#F3F3F3",
  }
}
</code>```

So only the non-active indentguides "diappear".

Body:
I know this is not a perfect solution, but

According to vscode doc of ThemeColor,
there is

editorIndentGuide.background: Color of the editor indentation guides.

editorIndentGuide.activeBackground: Color of the active editor indentation guide.

So I set editorIndentGuide.background to the value of editor.background

{
  ...other thing...
  "workbench.colorCustomizations": {
    "editorIndentGuide.background": "#F3F3F3",
  }
}

So only the non-active indentguides "diappear".


问:
python code number_list = [1, 239, 949, 0, 84, 0, 1] output: True number_list = [1, 239, 949, 0, 84, 0, 13] output: False
This function should return true if the value at the beginning and the end of the list are equal. False otherwise.

Example:

number_list = [1, 239, 949, 0, 84, 0, 1]
```

<p>output:</p>

<pre class="lang-py prettyprint-override"><code>True
</code>```

number_list = [1, 239, 949, 0, 84, 0, 13]
```

<p>output:</p>

<pre class="lang-py prettyprint-override"><code>False
</code>```

答:
```<code>def check(list_):
    if list_[0]==list_[-1]:
        return True
    else:
        return False
</code>```

Hope this helps

Body:
This function should return true if the value at the beginning and the end of the list are equal. False otherwise.

Example:

number_list = [1, 239, 949, 0, 84, 0, 1]

output:

True

number_list = [1, 239, 949, 0, 84, 0, 13]

output:

False

Body:
def check(list_):
    if list_[0]==list_[-1]:
        return True
    else:
        return False

Hope this helps


问:
Got "there is no books attribute in the dict" in Python when use dot to get the dict value like I do in Jinja template
I'm having a problem with accessing the response data from my http request. I'm able to get it if I pass the response through to my html and then take the specific data I want out of it but if I try to take that same part of the response in my python file and pass that through to my html it says "there is no books attribute in the dict".

my html

```<code>{% extends "layout.html" %}

{% block heading %}
Search Page
{% endblock %}

{% block body %}

the result of the http request:
<p>  {{res}} </p>

I want to add this info from the request
<p>{{res.books[0].average_rating}}
{{res.books[0].work_ratings_count}}</p>

to this dictionary

{{apiDict}}

but the when I use the same syntax to access the average rating and ratings count
from
'res' in my python file it says the respose has no book object, why does this
happen?

{% endblock %}
</code>```

Here is my python/flask code:

```<code>@app.route("/api/<isbn>", methods=["GET"])
def apiacc(isbn):
res = requests.get("https://www.goodreads.com/book/review_counts.json", params=.
{"key": "lzhHXUd9kUpum244vufV2Q", "isbns": isbn}).json()
# avg = res.books[0].average_rating
# rc = res.books[0].work_ratings_count
book = db.execute("SELECT * FROM books WHERE isbn = :i", {"i": isbn}).fetchone()
db.commit()

apiDict = {
    "title": book.title,
    "author": book.author,
    "year": book.year,
    "isbn": isbn
}
# apiDict["average_score"] = res.books[0].average_rating
# apiDict["review_count"] = res.books[0].work_ratings_count

return render_template("api.html", res = res, apiDict=apiDict)
</code>```

I would like to have the python code like this:

```<code> apiDict = {
    "title": book.title,
    "author": book.author,
    "year": book.year,
    "isbn": isbn,
    "average_score": avg,
    "review_count": rc
 }
</code>```

and just pass in the apiDict to api.hmtl as the only value but I get the error I mentioned earlier.enter image description here

答:
The res returned by requests will be a dict. In the template, Jinja support to get the dict value with the dot operator, like:

```<code>{{ res.books }}
</code>```

But in Python, you have to use the bracket operator to get the value in a dict (dot operator used to get the attribute):

```<code>data = res['books']
</code>```

Body:
I'm having a problem with accessing the response data from my http request. I'm able to get it if I pass the response through to my html and then take the specific data I want out of it but if I try to take that same part of the response in my python file and pass that through to my html it says "there is no books attribute in the dict".

my html

{% extends "layout.html" %}

{% block heading %}
Search Page
{% endblock %}

{% block body %}

the result of the http request:

  {{res}}

I want to add this info from the request

{{res.books[0].average_rating}}
{{res.books[0].work_ratings_count}}

to this dictionary

{{apiDict}}

but the when I use the same syntax to access the average rating and ratings count
from
'res' in my python file it says the respose has no book object, why does this
happen?

{% endblock %}

Here is my python/flask code:

@app.route("/api/<isbn>", methods=["GET"])
def apiacc(isbn):
res = requests.get("https://www.goodreads.com/book/review_counts.json", params=.
{"key": "lzhHXUd9kUpum244vufV2Q", "isbns": isbn}).json()
# avg = res.books[0].average_rating
# rc = res.books[0].work_ratings_count
book = db.execute("SELECT * FROM books WHERE isbn = :i", {"i": isbn}).fetchone()
db.commit()

apiDict = {
    "title": book.title,
    "author": book.author,
    "year": book.year,
    "isbn": isbn
}
# apiDict["average_score"] = res.books[0].average_rating
# apiDict["review_count"] = res.books[0].work_ratings_count

return render_template("api.html", res = res, apiDict=apiDict)

I would like to have the python code like this:

 apiDict = {
    "title": book.title,
    "author": book.author,
    "year": book.year,
    "isbn": isbn,
    "average_score": avg,
    "review_count": rc
 }

and just pass in the apiDict to api.hmtl as the only value but I get the error I mentioned earlier.enter image description here

Body:
The res returned by requests will be a dict. In the template, Jinja support to get the dict value with the dot operator, like:

{{ res.books }}

But in Python, you have to use the bracket operator to get the value in a dict (dot operator used to get the attribute):

data = res['books']


问:
Applying formatting to a Doughnut chart done with python pptx
I am working on an automated ppt through a python-pptx. I am interested in applying character formatting to the data label through the next function but it does not work. I need help with figuring out why.</p>

```<code>def apply_data_labels(self, chart):
        plot = chart.plots[0]
        plot.has_data_labels = True
        for series in plot.series:
            values = series.values
            counter = 0
            for point in series.points:
                data_label = point.data_label
                data_label.has_text_frame = True
                data_label.text_frame.text = str(values[counter])
                data_label.font.size = Pt(22)
                data_label.font.color.rgb = RGBColor(255,160,122)
                counter = counter + 1
</code>```

答:
Try:

```<code>data_label.text_frame.paragraphs[0].font.size = Pt(22)
</code>```

Things work a little differently when you're setting the font of an individual data label rather than all of them at once.

Body:
I am working on an automated ppt through a python-pptx. I am interested in applying character formatting to the data label through the next function but it does not work. I need help with figuring out why.

def apply_data_labels(self, chart):
        plot = chart.plots[0]
        plot.has_data_labels = True
        for series in plot.series:
            values = series.values
            counter = 0
            for point in series.points:
                data_label = point.data_label
                data_label.has_text_frame = True
                data_label.text_frame.text = str(values[counter])
                data_label.font.size = Pt(22)
                data_label.font.color.rgb = RGBColor(255,160,122)
                counter = counter + 1

Body:
Try:

data_label.text_frame.paragraphs[0].font.size = Pt(22)

Things work a little differently when you're setting the font of an individual data label rather than all of them at once.


问:
Python socket server can't decode redirect from OAUTH
I'm not sure how much of the code I can show, but the concept is simple. I am writing a python script that works with the TD Ameritrade API. I am getting a url for the portal from the API, and opening it in the browser. Next, I'm setting up a socket server to handle the redirect of the portal. Below is the code for the server:

```<code>serversocket = socket.socket(
                socket.AF_INET, socket.SOCK_STREAM)

    # get local machine name
    host = "localhost"

    port = 10120
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # bind to the port
    serversocket.bind((host, port))

    print("listening")
    # queue up to 5 requests
    serversocket.listen(5)

    allData = ""

    while True:
        # establish a connection
        try:
            conn,addr = serversocket.accept()
        except KeyboardInterrupt:
            break

        print("Got a connection from %s" % str(addr))
        while True:
            data = conn.recv(4096)

            if not data:
                print("done")
                break

            print(data.decode('utf-8', "ignore"))
        conn.close()
</code>```

When I go through the portal and get redirected, in the console I see the following:

```<code>Got a connection from ('127.0.0.1', 65505)
  |,?2!c[N': [?`XAn] "::+/,0̨̩   / 5
 jj         localhost
     3 + )http/1.1
    ej\E<zpִ_<%q\r)+ -  +
jj   zz
</code>```

However, if I were to copy the URL, open a new tab, paste it and go, I get the following (correct) response:

```<code>Got a connection from ('127.0.0.1', 49174)
GET /?code=<RESPONSE_TOKEN> HTTP/1.1
Host: localhost:10120
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.125
Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-
exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
</code>```

When I go to the network overview of my browser, I see the following warning when trying to view the request headers: Provisional headers are shown

And the only difference between the http request from the redirect, and the request when I manually paste the url in is the initiator column in the network viewer is "oath" for the redirect, and "other" when manually pasted in.

I hope I've provided enough information and code. I can try to make a copy for reproducing if needed, but a TD Ameritrade Developer account would be needed to connect with the API.

Thanks in advance for any help. I've been researching for over 6 hours and wasn't able to find anything. Hopefully I didn't miss something obvious.

答:
I think, socket is not required to handle an oauth redirect. Socket is for another kind of requeriments.

Also when you manually hit the redirect, a socket is not invoked. Just a simple http endpoint.

Try with this snippet which has the oauth code extract:

```<code>from urlparse import urlparse,parse_qsl
class Handler(BaseHTTPRequestHandler):

    def do_GET(self):
        url = urlparse(self.path)
        code = parse_qsl(url.query)['code']
</code>```

Or this:

https://gist.github.com/willnix/daed2b57ab8d613f6bfa53c6d0b46fd3

You can get more snippets of simple http get endpoints here:

https://gist.github.com/search?q=def+do_GET+python&ref=searchresults

Body:
I'm not sure how much of the code I can show, but the concept is simple. I am writing a python script that works with the TD Ameritrade API. I am getting a url for the portal from the API, and opening it in the browser. Next, I'm setting up a socket server to handle the redirect of the portal. Below is the code for the server:

serversocket = socket.socket(
                socket.AF_INET, socket.SOCK_STREAM)

    # get local machine name
    host = "localhost"

    port = 10120
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # bind to the port
    serversocket.bind((host, port))

    print("listening")
    # queue up to 5 requests
    serversocket.listen(5)

    allData = ""

    while True:
        # establish a connection
        try:
            conn,addr = serversocket.accept()
        except KeyboardInterrupt:
            break

        print("Got a connection from %s" % str(addr))
        while True:
            data = conn.recv(4096)

            if not data:
                print("done")
                break

            print(data.decode('utf-8', "ignore"))
        conn.close()

When I go through the portal and get redirected, in the console I see the following:

Got a connection from ('127.0.0.1', 65505)
  |,?2!c[N': [?`XAn] "::+/,0̨̩   / 5
 jj         localhost
     3 + )http/1.1
    ej\E<zpִ_<%q\r)+ -  +
jj   zz

However, if I were to copy the URL, open a new tab, paste it and go, I get the following (correct) response:

Got a connection from ('127.0.0.1', 49174)
GET /?code=<RESPONSE_TOKEN> HTTP/1.1
Host: localhost:10120
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.125
Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-
exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

When I go to the network overview of my browser, I see the following warning when trying to view the request headers: Provisional headers are shown

And the only difference between the http request from the redirect, and the request when I manually paste the url in is the initiator column in the network viewer is "oath" for the redirect, and "other" when manually pasted in.

I hope I've provided enough information and code. I can try to make a copy for reproducing if needed, but a TD Ameritrade Developer account would be needed to connect with the API.

Thanks in advance for any help. I've been researching for over 6 hours and wasn't able to find anything. Hopefully I didn't miss something obvious.

Body:
I think, socket is not required to handle an oauth redirect. Socket is for another kind of requeriments.

Also when you manually hit the redirect, a socket is not invoked. Just a simple http endpoint.

Try with this snippet which has the oauth code extract:

from urlparse import urlparse,parse_qsl
class Handler(BaseHTTPRequestHandler):

    def do_GET(self):
        url = urlparse(self.path)
        code = parse_qsl(url.query)['code']

Or this:

https://gist.github.com/willnix/daed2b57ab8d613f6bfa53c6d0b46fd3

You can get more snippets of simple http get endpoints here:

https://gist.github.com/search?q=def+do_GET+python&ref=searchresults


问:
Chek if an element is x times in some array of a 2D array
I want something that returns True if 0 appears x times in some array of a 2D array withou using for loop

```<code>a= [[1,2,0,4],[1,0,0,4],[0,2,3,4]]
b= [[1,2,0,4],[1,0,3,4],[0,2,3,4]]
x= 2
</code>```

for a the function will return True and for b the function will return False
Or at least i need to find the max number of zeroes, for a it is 2 and for b it is 1
I dont want to use for loop because i have arrays with million elements and i have to do it many times

答:
Try

```<code>zeros = arr.shape[1] - np.count_nonzero(arr, axis = 1)
np.any(zeros >= x)
</code>```

Works only if the arrays are non-jagged.

UPDATE:

Timing this code with %timeit in Jupyter for arr of shape (10000, 100), we get:

```<code>2.27 ms ± 21.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

As per the comments, since the code is supposed to run on these ~1M elements for  ~100K times, in my opinion, a good bet is to use cupy to achieve this. Since cupy requires CUDA, if you do not wish to install it locally, you can use it on Google Colab (you have to install it there, though). On Google Colab, one run takes on an average with cupy:

```<code>10000 loops, best of 3: 103 µs per loop
</code>```

That's more than a 10 times improvement. The code is same (since cupy is supposed to be a drop-in replacement for numpy):

```<code>import cupy as cp
arr = cp.random.choice(cp.arange(-3, 3), size = (10000, 100))
zrs = cp.count_nonzero(x, axis = 1); cp.any(zrs >= x)
</code>```

Body:
I want something that returns True if 0 appears x times in some array of a 2D array withou using for loop

a= [[1,2,0,4],[1,0,0,4],[0,2,3,4]]
b= [[1,2,0,4],[1,0,3,4],[0,2,3,4]]
x= 2

for a the function will return True and for b the function will return False
Or at least i need to find the max number of zeroes, for a it is 2 and for b it is 1
I dont want to use for loop because i have arrays with million elements and i have to do it many times

Body:
Try

zeros = arr.shape[1] - np.count_nonzero(arr, axis = 1)
np.any(zeros >= x)

Works only if the arrays are non-jagged.

UPDATE:

Timing this code with %timeit in Jupyter for arr of shape (10000, 100), we get:

2.27 ms ± 21.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

As per the comments, since the code is supposed to run on these ~1M elements for  ~100K times, in my opinion, a good bet is to use cupy to achieve this. Since cupy requires CUDA, if you do not wish to install it locally, you can use it on Google Colab (you have to install it there, though). On Google Colab, one run takes on an average with cupy:

10000 loops, best of 3: 103 µs per loop

That's more than a 10 times improvement. The code is same (since cupy is supposed to be a drop-in replacement for numpy):

import cupy as cp
arr = cp.random.choice(cp.arange(-3, 3), size = (10000, 100))
zrs = cp.count_nonzero(x, axis = 1); cp.any(zrs >= x)


问:
Trouble with bot.wait_for() Discord.py
So modern documentation on the bot.wait_for() coroutine is not super detailed, and I'm having trouble getting it to work with reactions. Would appreciate feedback.

Python 3 with Discord.py

```<code>## Test Role Add
@kelutralBot.command(name='testreaction')
async def testReaction(ctx):
    member = ctx.message.author
    message = await ctx.send("This is a test message.")
    emojis = ['\u2642','\u2640','\u2716']
    for emoji in emojis:
        await message.add_reaction(emoji)

    def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '\u2642'

    try:
        reaction, user = await kelutral.wait_for('reaction_add', timeout=60.0, check=check)
    except asyncio.TimeoutError:
        await ctx.send("Window has passed to self-assign pronouns. Please DM a mod if you would still like to do so.")
    else:
        print(reaction)
        male = get(member.guild.roles, name="He/Him")
        await member.add_roles(male)
        print("Assigned " + member.name + " He/Him pronouns.")
</code>```

答:
Two things were wrong.

First, don't use Client and Bot in the same command. Bot is sufficient for both.

Second, Unicode Emoji for Discord are treated as '\U000#####', which was the biggest problem.

Once we solved that, everything worked as intended.

Title: Trouble with bot.wait_for() Discord.py

Body:
So modern documentation on the bot.wait_for() coroutine is not super detailed, and I'm having trouble getting it to work with reactions. Would appreciate feedback.

Python 3 with Discord.py

## Test Role Add
@kelutralBot.command(name='testreaction')
async def testReaction(ctx):
    member = ctx.message.author
    message = await ctx.send("This is a test message.")
    emojis = ['\u2642','\u2640','\u2716']
    for emoji in emojis:
        await message.add_reaction(emoji)

    def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '\u2642'

    try:
        reaction, user = await kelutral.wait_for('reaction_add', timeout=60.0, check=check)
    except asyncio.TimeoutError:
        await ctx.send("Window has passed to self-assign pronouns. Please DM a mod if you would still like to do so.")
    else:
        print(reaction)
        male = get(member.guild.roles, name="He/Him")
        await member.add_roles(male)
        print("Assigned " + member.name + " He/Him pronouns.")


答:
Since your Identity contains list of header. Create an instance of Identity and Header. Then Assign the value to header class variables. And Header instance to list of Header.</p>

```<code>var myIdentity = new Identity();
var myHeader = new Header();
myHeader.tenantId = "Hello";
myIdentity.Header.Add(myHeader);
</code>```

Title: assigning the value to a list inside a class

Body:
I have following class. I have a list inside the class. How do I assign the values to the properties inside the list. Below is my code:

public class Identity
    {

        public Identity()
        {
            header = new List();
            control = new List<control>();
        }
        public List header { get; set; }
        public List<control> control{ get; set; }
        public string firstName { get; set; }
        public string LastName { get; set; }
  }

Below is the header class:

  public class Header
    {
        public string tenantId { get; set; }
        public string test2{ get; set; }
        public string test2{ get; set; }
    }

How can I assign the value of "Hello" to tenantId.

any help will be appreciated.

Body:
Since your Identity contains list of header. Create an instance of Identity and Header. Then Assign the value to header class variables. And Header instance to list of Header.

var myIdentity = new Identity();
var myHeader = new Header();
myHeader.tenantId = "Hello";
myIdentity.Header.Add(myHeader);


问:
What is the most pythonic way to check if multiple variables are not None?
If I have a construct like this:

```<code>def foo():
    a=None
    b=None
    c=None

    #...loop over a config file or command line options...

    if a is not None and b is not None and c is not None:
        doSomething(a,b,c)
    else:
        print "A config parameter is missing..."
</code>```

What is the preferred syntax in python to check if all variables are set to useful values?  Is it as I have written, or another better way?

This is different from this question:
not None test in Python ... I am looking for the preferred method for checking if many conditions are not None.  The option I have typed seems very long and non-pythonic.

答:
EDIT:
As noted by Mo2, this solution will fail if any variable is set to 0 and 0 is considered a 'useful' value.

For the specific case presented by the OP

```<code>if not all([a, b, c])
</code>```

will be enough.

```<code>all([a, b, c])
</code>```

evaluates to False if any parameter is missing.

Body:
If I have a construct like this:

def foo():
    a=None
    b=None
    c=None

    #...loop over a config file or command line options...

    if a is not None and b is not None and c is not None:
        doSomething(a,b,c)
    else:
        print "A config parameter is missing..."

What is the preferred syntax in python to check if all variables are set to useful values?  Is it as I have written, or another better way?

This is different from this question:
not None test in Python ... I am looking for the preferred method for checking if many conditions are not None.  The option I have typed seems very long and non-pythonic.

Body:
EDIT:
As noted by Mo2, this solution will fail if any variable is set to 0 and 0 is considered a 'useful' value.

For the specific case presented by the OP

if not all([a, b, c])

will be enough.

all([a, b, c])

evaluates to False if any parameter is missing.


问:
Pass complex type to AWS API gateway endpoint
I have an aws api gateway endpoint that I am trying to test using Mock Lambda Test Tool command. The aws api gateway endpoint expects a input type which has NoOFHours, AutoRecharge properties. I am passing the body as "body": "{"NoOFHours":51&"\AutoRecharge":false}" but the aws framework throws a "Error deserializing the input JSON to type APIGatewayProxyRequest" error.

How should a complex type be passed to a aws api gateway for testing?

```<code> public async Task<APIGatewayProxyResponse> CreatePaymentIntent(APIGatewayProxyRequest apiGatewayProxyRequest, ILambdaContext context)
      {

      }

public class CreatePaymentIntentInput
    {
        [JsonProperty(Required = Required.Always)]
        public int NoOFHours { get; set; }
        [JsonProperty(Required = Required.Always)]
        public bool AutoRecharge { get; set; }=false;
      }
</code>```

Stack Trace:

```<code>System.Exception: Error deserializing the input JSON to type APIGatewayProxyRequest
   at Amazon.Lambda.TestTool.Runtime.LambdaExecutor.BuildParameters(ExecutionRequest request, ILambdaContext context) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:line 214
   at Amazon.Lambda.TestTool.Runtime.LambdaExecutor.ExecuteAsync(ExecutionRequest request) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:line 52
---------------- Inner 1 Exception ------------
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Amazon.Lambda.TestTool.Runtime.LambdaExecutor.BuildParameters(ExecutionRequest request, ILambdaContext context) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:line 202
---------------- Inner 2 Exception ------------
Amazon.Lambda.Serialization.Json.JsonSerializerException: Error converting the Lambda event JSON payload to type Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest: After parsing a value an unexpected character was encountered: \. Path 'body', line 2, position 24.
   at Amazon.Lambda.Serialization.Json.JsonSerializer.Deserialize[T](Stream requestStream)
---------------- Inner 3 Exception ------------
Newtonsoft.Json.JsonReaderException: After parsing a value an unexpected character was encountered: \. Path 'body', line 2, position 24.
   at Newtonsoft.Json.JsonTextReader.ParsePostValue()
   at Newtonsoft.Json.JsonTextReader.Read()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader)
   at Amazon.Lambda.Serialization.Json.JsonSerializer.Deserialize[T](Stream requestStream)
</code>```

Sample Input to test API gateway endpoint:

```<code>{
  "body": "{\"NoOFHours"\:51&"\AutoRecharge"\:false}",
  "resource": "/items/{proxy+}",
  "path": "/payments",
  "httpMethod": "POST",
  "isBase64Encoded": true,
  "queryStringParameters": {
    "foo": "bar"
  },
  "multiValueQueryStringParameters": {
    "foo": ["bar"]
  },
  "pathParameters": {
    "proxy": "/payments"
  },
  "stageVariables": {
    "baz": "qux"
  },
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Encoding": "gzip, deflate, sdch",
    "Accept-Language": "en-US,en;q=0.8",
    "Cache-Control": "max-age=0",
    "CloudFront-Forwarded-Proto": "https",
    "CloudFront-Is-Desktop-Viewer": "true",
    "CloudFront-Is-Mobile-Viewer": "false",
    "CloudFront-Is-SmartTV-Viewer": "false",
    "CloudFront-Is-Tablet-Viewer": "false",
    "CloudFront-Viewer-Country": "US",
    "Host": "1234567890.execute-api.us-east-1.amazonaws.com",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Custom User Agent String",
    "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
    "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
    "X-Forwarded-For": "127.0.0.1, 127.0.0.2",
    "X-Forwarded-Port": "443",
    "X-Forwarded-Proto": "https"
  },
  "multiValueHeaders": {
    "Accept": ["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"],
    "Accept-Encoding": ["gzip, deflate, sdch"],
    "Accept-Language": ["en-US,en;q=0.8"],
    "Cache-Control": ["max-age=0"],
    "CloudFront-Forwarded-Proto": ["https"],
    "CloudFront-Is-Desktop-Viewer": ["true"],
    "CloudFront-Is-Mobile-Viewer": ["false"],
    "CloudFront-Is-SmartTV-Viewer": ["false"],
    "CloudFront-Is-Tablet-Viewer": ["false"],
    "CloudFront-Viewer-Country": ["US"],
    "Host": ["0123456789.execute-api.us-east-1.amazonaws.com"],
    "Upgrade-Insecure-Requests": ["1"],
    "User-Agent": ["Custom User Agent String"],
    "Via": ["1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)"],
    "X-Amz-Cf-Id": ["cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA=="],
    "X-Forwarded-For": ["127.0.0.1, 127.0.0.2"],
    "X-Forwarded-Port": ["443"],
    "X-Forwarded-Proto": ["https"]
  },
  "requestContext": {
    "accountId": "123456789012",
    "resourceId": "123456",
    "stage": "prod",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
    "requestTime": "09/Apr/2015:12:34:56 +0000",
    "requestTimeEpoch": 1428582896000,
    "identity": {
      "cognitoIdentityPoolId": null,
      "accountId": null,
      "cognitoIdentityId": null,
      "caller": null,
      "accessKey": null,
      "sourceIp": "127.0.0.1",
      "cognitoAuthenticationType": null,
      "cognitoAuthenticationProvider": null,
      "userArn": null,
      "userAgent": "Custom User Agent String",
      "user": null
    },
    "path": "/payments",
    "resourcePath": "/items/{proxy+}",
    "httpMethod": "GET",
    "apiId": "1234567890",
    "protocol": "HTTP/1.1"
  }
}
</code>```

答: I was able to get this working by changing the "body" to "{'NoOFHours':51,'AutoRecharge':false}".

Body:
I have an aws api gateway endpoint that I am trying to test using Mock Lambda Test Tool command. The aws api gateway endpoint expects a input type which has NoOFHours, AutoRecharge properties. I am passing the body as "body": "{"NoOFHours":51&"\AutoRecharge":false}" but the aws framework throws a "Error deserializing the input JSON to type APIGatewayProxyRequest" error.

How should a complex type be passed to a aws api gateway for testing?

 public async Task<APIGatewayProxyResponse> CreatePaymentIntent(APIGatewayProxyRequest apiGatewayProxyRequest, ILambdaContext context)
      {

      }

public class CreatePaymentIntentInput
    {
        [JsonProperty(Required = Required.Always)]
        public int NoOFHours { get; set; }
        [JsonProperty(Required = Required.Always)]
        public bool AutoRecharge { get; set; }=false;
      }

Stack Trace:

System.Exception: Error deserializing the input JSON to type APIGatewayProxyRequest
   at Amazon.Lambda.TestTool.Runtime.LambdaExecutor.BuildParameters(ExecutionRequest request, ILambdaContext context) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:line 214
   at Amazon.Lambda.TestTool.Runtime.LambdaExecutor.ExecuteAsync(ExecutionRequest request) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:line 52
---------------- Inner 1 Exception ------------
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Amazon.Lambda.TestTool.Runtime.LambdaExecutor.BuildParameters(ExecutionRequest request, ILambdaContext context) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:line 202
---------------- Inner 2 Exception ------------
Amazon.Lambda.Serialization.Json.JsonSerializerException: Error converting the Lambda event JSON payload to type Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest: After parsing a value an unexpected character was encountered: \. Path 'body', line 2, position 24.
   at Amazon.Lambda.Serialization.Json.JsonSerializer.Deserialize[T](Stream requestStream)
---------------- Inner 3 Exception ------------
Newtonsoft.Json.JsonReaderException: After parsing a value an unexpected character was encountered: \. Path 'body', line 2, position 24.
   at Newtonsoft.Json.JsonTextReader.ParsePostValue()
   at Newtonsoft.Json.JsonTextReader.Read()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader)
   at Amazon.Lambda.Serialization.Json.JsonSerializer.Deserialize[T](Stream requestStream)

Sample Input to test API gateway endpoint:

{
  "body": "{\"NoOFHours"\:51&"\AutoRecharge"\:false}",
  "resource": "/items/{proxy+}",
  "path": "/payments",
  "httpMethod": "POST",
  "isBase64Encoded": true,
  "queryStringParameters": {
    "foo": "bar"
  },
  "multiValueQueryStringParameters": {
    "foo": ["bar"]
  },
  "pathParameters": {
    "proxy": "/payments"
  },
  "stageVariables": {
    "baz": "qux"
  },
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Encoding": "gzip, deflate, sdch",
    "Accept-Language": "en-US,en;q=0.8",
    "Cache-Control": "max-age=0",
    "CloudFront-Forwarded-Proto": "https",
    "CloudFront-Is-Desktop-Viewer": "true",
    "CloudFront-Is-Mobile-Viewer": "false",
    "CloudFront-Is-SmartTV-Viewer": "false",
    "CloudFront-Is-Tablet-Viewer": "false",
    "CloudFront-Viewer-Country": "US",
    "Host": "1234567890.execute-api.us-east-1.amazonaws.com",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Custom User Agent String",
    "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
    "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
    "X-Forwarded-For": "127.0.0.1, 127.0.0.2",
    "X-Forwarded-Port": "443",
    "X-Forwarded-Proto": "https"
  },
  "multiValueHeaders": {
    "Accept": ["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"],
    "Accept-Encoding": ["gzip, deflate, sdch"],
    "Accept-Language": ["en-US,en;q=0.8"],
    "Cache-Control": ["max-age=0"],
    "CloudFront-Forwarded-Proto": ["https"],
    "CloudFront-Is-Desktop-Viewer": ["true"],
    "CloudFront-Is-Mobile-Viewer": ["false"],
    "CloudFront-Is-SmartTV-Viewer": ["false"],
    "CloudFront-Is-Tablet-Viewer": ["false"],
    "CloudFront-Viewer-Country": ["US"],
    "Host": ["0123456789.execute-api.us-east-1.amazonaws.com"],
    "Upgrade-Insecure-Requests": ["1"],
    "User-Agent": ["Custom User Agent String"],
    "Via": ["1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)"],
    "X-Amz-Cf-Id": ["cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA=="],
    "X-Forwarded-For": ["127.0.0.1, 127.0.0.2"],
    "X-Forwarded-Port": ["443"],
    "X-Forwarded-Proto": ["https"]
  },
  "requestContext": {
    "accountId": "123456789012",
    "resourceId": "123456",
    "stage": "prod",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
    "requestTime": "09/Apr/2015:12:34:56 +0000",
    "requestTimeEpoch": 1428582896000,
    "identity": {
      "cognitoIdentityPoolId": null,
      "accountId": null,
      "cognitoIdentityId": null,
      "caller": null,
      "accessKey": null,
      "sourceIp": "127.0.0.1",
      "cognitoAuthenticationType": null,
      "cognitoAuthenticationProvider": null,
      "userArn": null,
      "userAgent": "Custom User Agent String",
      "user": null
    },
    "path": "/payments",
    "resourcePath": "/items/{proxy+}",
    "httpMethod": "GET",
    "apiId": "1234567890",
    "protocol": "HTTP/1.1"
  }
}


问:
Custom validation error message on hapi with joi
I'm implementing custom validation error message on hapi with joi.

```<code>    server.route({
        path: '/test/inputname',
        method: ['PUT','POST'],
        handler: async (request, h) => {
            try{
                const created =  await MemberSchema.addUser(
                    {"input_name": request.payload.input_name}
                )
                return h.response(created).code(201);
            } catch(err){
                console.log(err.message);
                return h.response(err.message).code(400);
            }
        },
        options: {
            validate: {
                payload: Joi.object({
                    input_name: Joi.string()
                        .min(2)
                        .max(30)
                        .required()
                        .messages({
                            'string.base' : `"input_name" should be a type of 'text'`,
                            'string.empty' : `"input_name" cannot be an empty field`,
                            'string.min' : `"input_name" should have a minimum length of {#limit}`,
                            'any.required' : `"input_name" is a required field`,
                        }),
                }),
                options:{
                    allowUnknown: true
                    ,abortEarly: false
                }
            }
        }
    });

</code>```

However when I post invalid data, it always displayed as follows.

```<code>"statusCode": 400,
"error": "Bad Request",
"message": "Invalid request payload input"
</code>```

How can it be solved?

p.s
I'm using the following version.

```<code>node v12.16.2
"@hapi/hapi": "^19.1.1",
"@hapi/joi": "^17.1.1",
</code>```

答:
FailAction might be required.

```<code>    options: {
        validate: {
            payload:  MemberSchema.memberSchema
            ,options:{
                allowUnknown: true
                ,abortEarly: false
            }
            ,failAction: async (request, h, err) => {
                console.log(err);
                throw err;
            }
        }
    },
</code>```

Then message changed as follows.

```<code>{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "\"input_name\" should have a minimum length of 2",
    "validation": {
        "source": "payload",
        "keys": [
            "input_name"
        ]
    }
}
</code>```

Body:
I'm implementing custom validation error message on hapi with joi.

    server.route({
        path: '/test/inputname',
        method: ['PUT','POST'],
        handler: async (request, h) => {
            try{
                const created =  await MemberSchema.addUser(
                    {"input_name": request.payload.input_name}
                )
                return h.response(created).code(201);
            } catch(err){
                console.log(err.message);
                return h.response(err.message).code(400);
            }
        },
        options: {
            validate: {
                payload: Joi.object({
                    input_name: Joi.string()
                        .min(2)
                        .max(30)
                        .required()
                        .messages({
                            'string.base' : `"input_name" should be a type of 'text'`,
                            'string.empty' : `"input_name" cannot be an empty field`,
                            'string.min' : `"input_name" should have a minimum length of {#limit}`,
                            'any.required' : `"input_name" is a required field`,
                        }),
                }),
                options:{
                    allowUnknown: true
                    ,abortEarly: false
                }
            }
        }
    });

However when I post invalid data, it always displayed as follows.

"statusCode": 400,
"error": "Bad Request",
"message": "Invalid request payload input"

How can it be solved?

p.s
I'm using the following version.

node v12.16.2
"@hapi/hapi": "^19.1.1",
"@hapi/joi": "^17.1.1",

Body:
FailAction might be required.

    options: {
        validate: {
            payload:  MemberSchema.memberSchema
            ,options:{
                allowUnknown: true
                ,abortEarly: false
            }
            ,failAction: async (request, h, err) => {
                console.log(err);
                throw err;
            }
        }
    },

Then message changed as follows.

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "\"input_name\" should have a minimum length of 2",
    "validation": {
        "source": "payload",
        "keys": [
            "input_name"
        ]
    }
}


问:
Why is -1 returned if the character is not found in a string?
This returns -1 Why is that?

a = "apples"

print(a.find("g"))
```

This can be generated if you try to find a character that is nonexistent to the string.

答: That's what it's documented to do. If you don't like it, you can always use .index, which behaves identically when the value is found, and raises an exception when it isn't found, removing the need to explicitly check the return value.

Body:
This returns -1 Why is that?

a = "apples"

print(a.find("g"))

This can be generated if you try to find a character that is nonexistent to the string.


问:
Should I have been returning a promise all along?
I have been calling a method MediaNext() from several points in my PlayersController code to chain the next Media playback if any.

This MediaNext() method returns a Media object from some of the various playlists I have from memory.  So it tries to encapsulate the notion of getting the next Media object if any left.

However, recently I revised MediaNext() that for some new condition X I now have to load external data in order to return this alternative Media object.

```<code>MediaNext():any {  // any could be typed like Media_I
   if(cond1) {
      ...
      return Media1
    }
   if(cond2) {
      ...
      return Media1
    }
    //
    if(! AutoPlayNext) return null;
    //
    if(NoMoreMedia) return null;
    //
    If (condX) {
      // in order to wait for the Load() method I am subscribing to its promise
      this.Service1.Load(Media).then(() => {
         ...processing...
         return Media
      })
      ??? what do I return here, it does not make sense to return null, since potentially a Media is on its way ???
    }
    return null // safe catch. nomore media should not happen.
}
</code>```

The questions I have

By subscribing to the promise of the .Load(), the execution from what I gather in JS should not be blocked waiting for the media data to return.  Instead the execution needs to flow and the call to MediaNext() has to return.  However, what could I be returning where indicated in the code above "???".

Should MediaNext() have been coded to return a promise for all conditions?

I mostly do guess work when I code promises and observables as they remain a beast to understand and master so feel free to advise alternatives.

Thank you for your help.

答:
If you deal with .Load asynchronously and immediately return, there's no good reason for that function to return anything. The operation is still happening in the backend.

However, if you want the caller to get more information about if the operation was successful or not, you should return a promise.

If you want to return a promise, you might find it much easier to write this as an async function, and use await this.Service1.Load(). instead of then().

Body:
I have been calling a method MediaNext() from several points in my PlayersController code to chain the next Media playback if any.

This MediaNext() method returns a Media object from some of the various playlists I have from memory.  So it tries to encapsulate the notion of getting the next Media object if any left.

However, recently I revised MediaNext() that for some new condition X I now have to load external data in order to return this alternative Media object.

MediaNext():any {  // any could be typed like Media_I
   if(cond1) {
      ...
      return Media1
    }
   if(cond2) {
      ...
      return Media1
    }
    //
    if(! AutoPlayNext) return null;
    //
    if(NoMoreMedia) return null;
    //
    If (condX) {
      // in order to wait for the Load() method I am subscribing to its promise
      this.Service1.Load(Media).then(() => {
         ...processing...
         return Media
      })
      ??? what do I return here, it does not make sense to return null, since potentially a Media is on its way ???
    }
    return null // safe catch. nomore media should not happen.
}

The questions I have

By subscribing to the promise of the .Load(), the execution from what I gather in JS should not be blocked waiting for the media data to return.  Instead the execution needs to flow and the call to MediaNext() has to return.  However, what could I be returning where indicated in the code above "???".

Should MediaNext() have been coded to return a promise for all conditions?

I mostly do guess work when I code promises and observables as they remain a beast to understand and master so feel free to advise alternatives.

Thank you for your help.


答:
You method is now asynchronous and you are using a Promise. You then need to return a promise which your consumers can wait on to get a result. Either:

1) Return the promise

```<code>    If (condX) {
      return this.Service1.Load(Media);
    }
</code>```

2) Set your method as async and await the promise used internally

```<code>async MediaNext():any {  // any could be typed like Media_I
    // ...

    If (condX) {
      return await this.Service1.Load(Media);
    }

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

Title: Should I have been returning a promise all along?

Body:
You method is now asynchronous and you are using a Promise. You then need to return a promise which your consumers can wait on to get a result. Either:

1) Return the promise

    If (condX) {
      return this.Service1.Load(Media);
    }

2) Set your method as async and await the promise used internally

async MediaNext():any {  // any could be typed like Media_I
    // ...

    If (condX) {
      return await this.Service1.Load(Media);
    }

    // ...


问:
Scala - Handle empty strings when instantiating a class
I have a case class with a couple of String fields. I use the values result of a string split to instantiate the class, but want to get an error when any of the fields is an empty string. For example:

```<code>case class SomeClass(a: String, b: String)
val line = ",a"
val values = line.split(",")
SomeClass(values(0), values(1))
</code>```

Would result in:

```<code>SomeClass = SomeClass(,a)
</code>```

Obviously I can check if each element is empty individually, but is there any more elegant and practical way to prevent instantiating when there is an empty field?

答:
This answer requires external libraries and may not work for you if you want to stick to core Scala but I am going to encourage this mainly because, a constructor is a contract. Here it says You give me 2 strings and I will give you SomeClass i.e. ::String -> String -> SomeClass. The fact that this may not be honored even when the input meets the criteria breaks the soundness in my opinion. There are a few things, I would suggest

1) Use Refined Types

```<code>import eu.timepit.refined.types.string._
import eu.timepit.refined._
import eu.timepit.refined.auto._

case class SomeClass(a: NonEmptyString, b: NonEmptyString)
</code>```

Would make it impossible to construct this with an empty string. You can do whatever you want with the error.

2) If you don't want to use refined types => I think Either gives you more power, as to why things failed. A good option would be Validated semigroup.

```<code>import cats.data._
import cats.data.Validated._
import cats.implicits._

sealed trait ValidationError {
  def error: String
}

case object StringIsEmptyError extends ValidationError{
  def error = "Argument Can't Be Empty String"
}

type ValidationResult[A] = ValidatedNec[ValidationError, A]

def validateArgument(s: String): ValidationResult[String] = if (s.nonEmpty) s.validNec else StringIsEmptyError.invalidNec

object SomeClass {
  def apply(a: String, b: String) = (validateArgument(a), validateArgument(b)).mapN(SomeClass).toEither
}
</code>```

This is a little bit more code than you might want but I think it is easier to reason about + easily extensible should you have more requirements about the arguments in the future.

One good thing about Validated, as opposed to Option or Either is that, it allows you to accumulate errors. So in this case, if both arguments were empty, you could collect both errors and report to the user, rather than ambiguously failing

Body:
I have a case class with a couple of String fields. I use the values result of a string split to instantiate the class, but want to get an error when any of the fields is an empty string. For example:

case class SomeClass(a: String, b: String)
val line = ",a"
val values = line.split(",")
SomeClass(values(0), values(1))

Would result in:

SomeClass = SomeClass(,a)

Obviously I can check if each element is empty individually, but is there any more elegant and practical way to prevent instantiating when there is an empty field?

Body:
This answer requires external libraries and may not work for you if you want to stick to core Scala but I am going to encourage this mainly because, a constructor is a contract. Here it says You give me 2 strings and I will give you SomeClass i.e. ::String -> String -> SomeClass. The fact that this may not be honored even when the input meets the criteria breaks the soundness in my opinion. There are a few things, I would suggest

1) Use Refined Types

import eu.timepit.refined.types.string._
import eu.timepit.refined._
import eu.timepit.refined.auto._

case class SomeClass(a: NonEmptyString, b: NonEmptyString)

Would make it impossible to construct this with an empty string. You can do whatever you want with the error.

2) If you don't want to use refined types => I think Either gives you more power, as to why things failed. A good option would be Validated semigroup.

import cats.data._
import cats.data.Validated._
import cats.implicits._

sealed trait ValidationError {
  def error: String
}

case object StringIsEmptyError extends ValidationError{
  def error = "Argument Can't Be Empty String"
}

type ValidationResult[A] = ValidatedNec[ValidationError, A]

def validateArgument(s: String): ValidationResult[String] = if (s.nonEmpty) s.validNec else StringIsEmptyError.invalidNec

object SomeClass {
  def apply(a: String, b: String) = (validateArgument(a), validateArgument(b)).mapN(SomeClass).toEither
}

This is a little bit more code than you might want but I think it is easier to reason about + easily extensible should you have more requirements about the arguments in the future.

One good thing about Validated, as opposed to Option or Either is that, it allows you to accumulate errors. So in this case, if both arguments were empty, you could collect both errors and report to the user, rather than ambiguously failing


问:
nodejs+mongodb access node.js object with document's _id field value in query
I am learning Mongodb to use with NodeJS. The below is my code:

```<code>let configMap = {
    '1': 10,
    '2': 12,
    '3': 13
}
let myData = await mongo_groups_collection.find({
    _id: {
        $in: [1,2,3]
    },
    active: true
}).project({
    '_id': 1,
    'name': 1,
    'members': 1,
    'messages': {
        $slice: [-(configMap[_id]), (DEFAULT_PAGE_SIZE_FILL * PAGE_SIZE) + (PAGE_SIZE - ((configMap[_id]) % PAGE_SIZE))] //Need to use _id to get configMap value

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

I am using "configMap" nodeJS variable in Mongo slice function to retrieve certain number of elements from the array. To retrieve I need to lookup using "_id" field value which I am not getting and encounter  _id "undefined" error.

答:
That's because (configMap[_id]) gets compiled in node.js code but not on database as a query. So in code when this query gets compiled it's not able to find _id since you've not declared it as the way you did it for configMap variable.

You're expecting _id value to be actual _id from document. So, in case if you use (configMap[$_id]) it doesn't work that way cause you can't club a javascript object with documents field.

You can still do this using aggregate query like below - where we actually add needed v value as a field to document for further usage  :

```<code> /** Make `configMap` an array of objects */
var configMap = [
  { k: 1, v: 10 },
  { k: 2, v: 12 },
  { k: 3, v: 13 },
];

let myData = await mongo_groups_collection.aggregate([
  {
    $match: { _id: { $in: [1, 2, 3] }, active: true }
  },
  /** For each matched doc we'll iterate on input `configMap` array &
   *  find respective `v` value from matched object where `k == _id`  */
  {
    $addFields: {
      valueToBeSliced: {
        $let: {
          vars: { matchedK: { $arrayElemAt: [ { $filter: { input: configMap, cond: { $eq: ["$$this.k", "$_id"] } } }, 0 ] } },
          in: "$$matchedK.v",
        }
      }
    }
  },
  {
    $project: {
      messages: { $slice: ["$messages", { $subtract: [0, "$valueToBeSliced"] }, someInputValue ] },
      name: 1, members: 1
    }
  }
]).toArray();
</code>```

Ref : $let

Note :

In projection you don't need to mention this '_id': 1 as it's included by default.

Since your query is using .find() you might be using $slice-projection-operator which can't be used in aggregation, instead we need to use $slice-aggregation-operator, both does same thing but have syntax variation, you need to refer to docs for that.

Also in someInputValue you need to pass in value of (DEFAULT_PAGE_SIZE_FILL * PAGE_SIZE) + (PAGE_SIZE - ((configMap[_id]) % PAGE_SIZE)) - So try to use aggregation operators $divide to get the value. We're doing { $subtract: [0, "$valueToBeSliced"] } to convert positive valueToBeSliced to negative as we can't just do like -valueToBeSliced which we usually do in javaScript.

Body:
I am learning Mongodb to use with NodeJS. The below is my code:

let configMap = {
    '1': 10,
    '2': 12,
    '3': 13
}
let myData = await mongo_groups_collection.find({
    _id: {
        $in: [1,2,3]
    },
    active: true
}).project({
    '_id': 1,
    'name': 1,
    'members': 1,
    'messages': {
        $slice: [-(configMap[_id]), (DEFAULT_PAGE_SIZE_FILL * PAGE_SIZE) + (PAGE_SIZE - ((configMap[_id]) % PAGE_SIZE))] //Need to use _id to get configMap value

    }
}).toArray();

I am using "configMap" nodeJS variable in Mongo slice function to retrieve certain number of elements from the array. To retrieve I need to lookup using "_id" field value which I am not getting and encounter  _id "undefined" error.

Body:
That's because (configMap[_id]) gets compiled in node.js code but not on database as a query. So in code when this query gets compiled it's not able to find _id since you've not declared it as the way you did it for configMap variable.

You're expecting _id value to be actual _id from document. So, in case if you use (configMap[$_id]) it doesn't work that way cause you can't club a javascript object with documents field.

You can still do this using aggregate query like below - where we actually add needed v value as a field to document for further usage  :

 /** Make `configMap` an array of objects */
var configMap = [
  { k: 1, v: 10 },
  { k: 2, v: 12 },
  { k: 3, v: 13 },
];

let myData = await mongo_groups_collection.aggregate([
  {
    $match: { _id: { $in: [1, 2, 3] }, active: true }
  },
  /** For each matched doc we'll iterate on input `configMap` array &
   *  find respective `v` value from matched object where `k == _id`  */
  {
    $addFields: {
      valueToBeSliced: {
        $let: {
          vars: { matchedK: { $arrayElemAt: [ { $filter: { input: configMap, cond: { $eq: ["$$this.k", "$_id"] } } }, 0 ] } },
          in: "$$matchedK.v",
        }
      }
    }
  },
  {
    $project: {
      messages: { $slice: ["$messages", { $subtract: [0, "$valueToBeSliced"] }, someInputValue ] },
      name: 1, members: 1
    }
  }
]).toArray();

Ref : $let

Note :

In projection you don't need to mention this '_id': 1 as it's included by default.

Since your query is using .find() you might be using $slice-projection-operator which can't be used in aggregation, instead we need to use $slice-aggregation-operator, both does same thing but have syntax variation, you need to refer to docs for that.

Also in someInputValue you need to pass in value of (DEFAULT_PAGE_SIZE_FILL * PAGE_SIZE) + (PAGE_SIZE - ((configMap[_id]) % PAGE_SIZE)) - So try to use aggregation operators $divide to get the value. We're doing { $subtract: [0, "$valueToBeSliced"] } to convert positive valueToBeSliced to negative as we can't just do like -valueToBeSliced which we usually do in javaScript.


问:
glaux.lib in Visual Studio 2008
I'm porting some code from Visual Studio 2005 to Visual Studio 2008.

Can i use the glaux.lib found in Visual Studio 2005 found in \PlatformSDK\Lib folder in Visual Studio 2008 ?
I don't want to change my APIs and have the requirement to use glaux.h

as said here , does this work

looks like glaux.lib is deprecated.
  Instead link to kernel32.lib,
  user32.lib, gdi32.lib and advapi32.lib

答:
Download gluax.h from http://www.songho.ca/opengl/files/glaux.h
and gluax.lib from http://www.songho.ca/opengl/files/glaux.lib.

Set the path and you are done.

ContentLicense: CC BY-SA 2.5

Title: glaux.lib in Visual Studio 2008