问:
Lambda: Value of property Layers must be of type List of String
I'm getting started trying to write a lambda function with node and puppeteer. I'm using the serverless framework

I've been trying to follow https://codissimo.sinumo.tech/2019/12/27/serverless-puppeteer-with-aws-lambda-layers-and-node-js/ to utilize the provisioned chrome at https://github.com/shelfio/chrome-aws-lambda-layer . My function is working as expected locally.

My Yaml file contains:

```<code>provider:
  name: aws
  runtime: nodejs12.x
  region: us-east-1
  # here we put the layers we want to use
  layers:
    # Google Chrome for AWS Lambda as a layer
    # Make sure you use the latest version depending on the region
    # https://github.com/shelfio/chrome-aws-lambda-layer
    - arn:us-east-1: arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:10
</code>```

When I run:

```<code>$ serverless deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Installing dependencies for custom CloudFormation resources...
Serverless: Safeguards Processing...
Serverless: Safeguards Results:

Summary --------------------------------------------------

passed - no-secret-env-vars
passed - allowed-regions
passed - framework-version
warned - require-cfn-role
passed - no-unsafe-wildcard-iam-permissions
passed - allowed-stages
passed - allowed-runtimes

Details --------------------------------------------------

1) Warned - no cfnRole set
    details: http://slss.io/sg-require-cfn-role
    Require the cfnRole option, which specifies a particular role for CloudFormation to assume while deploying.

Serverless: Safeguards Summary: 6 passed, 1 warnings, 0 errors
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service thelandnow.zip file to S3 (43.66 MB)...
Serverless: Uploading custom CloudFormation resources...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
.......
Serverless: Operation failed!
Serverless: View the full error output: https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stack/detail?stackId=arn%3Aaws%3Acloudformation%3Aus-east-1%3A155754363046%3Astack%2Fsellthelandnow-dev%2F943f00e0-9d21-11ea-a8a3-12498e67507f
Serverless: Publishing service to the Serverless Dashboard...
Serverless: Successfully published your service to the Serverless Dashboard: https://dashboard.serverless.com/tenants/myaccount/applications/seller/services/thelandnow/stage/dev/region/us-east-1

Serverless Error ---------------------------------------

An error occurred: MainLambdaFunction - Value of property Layers must be of type List of String.

Get Support --------------------------------------------
    Docs:          docs.serverless.com
    Bugs:          github.com/serverless/serverless/issues
    Issues:        forum.serverless.com

Your Environment Information ---------------------------
    Operating System:          win32
    Node Version:              11.5.0
    Framework Version:         1.70.1
    Plugin Version:            3.6.11
    SDK Version:               2.3.0
    Components Version:        2.30.10
</code>```

How can I fix this?

Edit:

Now getting:

So I guess in future I'll use a tool like https://www.convertjson.com/yaml-to-json.htm. Thank you. I changed to :

```<code>layers:
  - arn:us-east-1:arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:10
</code>```

Now I'm seeing:

```<code> An error occurred: MainLambdaFunction - 1 validation error detected: Value '[arn:us-east-1:arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:10]' at 'layers' failed to satisfy constraint: Member must satisfy constraint: [Member must have length less than or equal to 140, Member must have length greater than or equal to 1, Member must satisfy regular expression pattern: (arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+)|(arn:[a-zA-Z0-9-]+:lambda:::awslayer:[a-zA-Z0-9-_]+)] (Service: AWSLambdaInternal; Status Code: 400; Error Code: ValidationException; Request ID: a5fae73b-67b5-4910-8020-c283673e55f2).
</code>```

Any ideas?

答:
There is a space in your layer ARN.

Your config in YAML:

```<code>provider:
  name: aws
  runtime: nodejs12.x
  region: us-east-1
  # here we put the layers we want to use
  layers:
    # Google Chrome for AWS Lambda as a layer
    # Make sure you use the latest version depending on the region
    # https://github.com/shelfio/chrome-aws-lambda-layer
    - arn:us-east-1: arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:10
</code>```

...looks like this in JSON -- where it becomes more apparent:

```<code>{
  "provider": {
    "name": "aws",
    "runtime": "nodejs12.x",
    "region": "us-east-1",
    "layers": [
      {
        "arn:us-east-1": "arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:10"
      }
    ]
  }
}
</code>```

Body:
I'm getting started trying to write a lambda function with node and puppeteer. I'm using the serverless framework

I've been trying to follow https://codissimo.sinumo.tech/2019/12/27/serverless-puppeteer-with-aws-lambda-layers-and-node-js/ to utilize the provisioned chrome at https://github.com/shelfio/chrome-aws-lambda-layer . My function is working as expected locally.

My Yaml file contains:

provider:
  name: aws
  runtime: nodejs12.x
  region: us-east-1
  # here we put the layers we want to use
  layers:
    # Google Chrome for AWS Lambda as a layer
    # Make sure you use the latest version depending on the region
    # https://github.com/shelfio/chrome-aws-lambda-layer
    - arn:us-east-1: arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:10

When I run:

$ serverless deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Installing dependencies for custom CloudFormation resources...
Serverless: Safeguards Processing...
Serverless: Safeguards Results:

Summary --------------------------------------------------

passed - no-secret-env-vars
passed - allowed-regions
passed - framework-version
warned - require-cfn-role
passed - no-unsafe-wildcard-iam-permissions
passed - allowed-stages
passed - allowed-runtimes

Details --------------------------------------------------

1) Warned - no cfnRole set
    details: http://slss.io/sg-require-cfn-role
    Require the cfnRole option, which specifies a particular role for CloudFormation to assume while deploying.

Serverless: Safeguards Summary: 6 passed, 1 warnings, 0 errors
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service thelandnow.zip file to S3 (43.66 MB)...
Serverless: Uploading custom CloudFormation resources...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
.......
Serverless: Operation failed!
Serverless: View the full error output: https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stack/detail?stackId=arn%3Aaws%3Acloudformation%3Aus-east-1%3A155754363046%3Astack%2Fsellthelandnow-dev%2F943f00e0-9d21-11ea-a8a3-12498e67507f
Serverless: Publishing service to the Serverless Dashboard...
Serverless: Successfully published your service to the Serverless Dashboard: https://dashboard.serverless.com/tenants/myaccount/applications/seller/services/thelandnow/stage/dev/region/us-east-1

Serverless Error ---------------------------------------

An error occurred: MainLambdaFunction - Value of property Layers must be of type List of String.

Get Support --------------------------------------------
    Docs:          docs.serverless.com
    Bugs:          github.com/serverless/serverless/issues
    Issues:        forum.serverless.com

Your Environment Information ---------------------------
    Operating System:          win32
    Node Version:              11.5.0
    Framework Version:         1.70.1
    Plugin Version:            3.6.11
    SDK Version:               2.3.0
    Components Version:        2.30.10

How can I fix this?

Edit:

Now getting:

So I guess in future I'll use a tool like https://www.convertjson.com/yaml-to-json.htm. Thank you. I changed to :

layers:
  - arn:us-east-1:arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:10

Now I'm seeing:

 An error occurred: MainLambdaFunction - 1 validation error detected: Value '[arn:us-east-1:arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:10]' at 'layers' failed to satisfy constraint: Member must satisfy constraint: [Member must have length less than or equal to 140, Member must have length greater than or equal to 1, Member must satisfy regular expression pattern: (arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+)|(arn:[a-zA-Z0-9-]+:lambda:::awslayer:[a-zA-Z0-9-_]+)] (Service: AWSLambdaInternal; Status Code: 400; Error Code: ValidationException; Request ID: a5fae73b-67b5-4910-8020-c283673e55f2).

Any ideas?

Body:
There is a space in your layer ARN.

Your config in YAML:

provider:
  name: aws
  runtime: nodejs12.x
  region: us-east-1
  # here we put the layers we want to use
  layers:
    # Google Chrome for AWS Lambda as a layer
    # Make sure you use the latest version depending on the region
    # https://github.com/shelfio/chrome-aws-lambda-layer
    - arn:us-east-1: arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:10

...looks like this in JSON -- where it becomes more apparent:

{
  "provider": {
    "name": "aws",
    "runtime": "nodejs12.x",
    "region": "us-east-1",
    "layers": [
      {
        "arn:us-east-1": "arn:aws:lambda:us-east-1:764866452798:layer:chrome-aws-lambda:10"
      }
    ]
  }
}


来源: stackexchange

问:
Java: Can (new Random()).nextInt(5) always return the same number?
Sometimes this piece of code always returns the same number (and sometimes it works fine):

```<code>(new Random()).nextInt(5)
</code>```

I have suspicions where the problem is - it probably always creates a new Random with the same seed. So what would be the best solution:

create a static var for Random() and
use it instead.

use Math.random() * 5
(looks like it uses a static var
internally)

or something else? I don't need anything fancy just something that looks random.

Also it would be helpful if someone can explain why the original code sometimes works and sometimes it doesn't.

Thanks.

答: The best way to approximate uniform distribution is to use the static method Random.nextInt(n) to produce integers in the range [0, n-1] (Yes, n is excluded). In your particular example, if you want integers in the range 0 to 5, inclusive, you would call Random.nextInt(6).</p>

ContentLicense: CC BY-SA 2.5

Body:
Sometimes this piece of code always returns the same number (and sometimes it works fine):

(new Random()).nextInt(5)

I have suspicions where the problem is - it probably always creates a new Random with the same seed. So what would be the best solution:

create a static var for Random() and
use it instead.

use Math.random() * 5
(looks like it uses a static var
internally)

or something else? I don't need anything fancy just something that looks random.

Also it would be helpful if someone can explain why the original code sometimes works and sometimes it doesn't.

Thanks.

ContentLicense: CC BY-SA 3.0


问:
How to construct a nested box plot in Seaborn from three dataframes
I have three datasets, and I am now making 3 different box plots. Right now I am using:

```<code>chart1 = sns.catplot(x="Provider", y="Appearances", kind="box", data=mlt_sample1k)
chart2 = sns.catplot(x="Provider", y="Appearances", kind="box", data=mlt_sample10k)
chart3 = sns.catplot(x="Provider", y="Appearances", kind="box", data=mlt_sample100k)
</code>```

where mlt_sample1k, mlt_sample10k and mlt_sample100k are my three dataframes.

I want to combine these into a single boxplot, with 3 parallel boxes per provider, as in the example from the docs. Something like:

but with 3 boxes, and the Thu, Fri, etc would be my "provider" categories. I see that in the docs they simply use:

```<code>ax = sns.boxplot(x="day", y="total_bill", hue="smoker",

                 data=tips, palette="Set3")
</code>```

However this does not work for me, as I have to specify three datasets, one for each box. How can I do this?

EDIT:  The structure of my dataframes is always the same:

```<code>item  |  provider  | appearances

'dog'    'prov1'      0.001
'cat'    'prov2'      0.02
'pig'    'prov1'      0.03
...
</code>```

The box plots represent the statistics of the items, according to the appearances column, per each provider (6 in total) per each dataframe.

The three dataframes are NOT the same length.

答:
IIUC, you could concat the three dataframes and assign a column to be used as the hue like:

```<code>sns.catplot(x="Provider", y="Appearances",
            kind="box", hue='h',
            data=pd.concat([mlt_sample1k.assign(h='1k'),
                            mlt_sample10k.assign(h='10k'),
                            mlt_sample100k.assign(h='100k')])
           )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have three datasets, and I am now making 3 different box plots. Right now I am using:

chart1 = sns.catplot(x="Provider", y="Appearances", kind="box", data=mlt_sample1k)
chart2 = sns.catplot(x="Provider", y="Appearances", kind="box", data=mlt_sample10k)
chart3 = sns.catplot(x="Provider", y="Appearances", kind="box", data=mlt_sample100k)

where mlt_sample1k, mlt_sample10k and mlt_sample100k are my three dataframes.

I want to combine these into a single boxplot, with 3 parallel boxes per provider, as in the example from the docs. Something like:

but with 3 boxes, and the Thu, Fri, etc would be my "provider" categories. I see that in the docs they simply use:

ax = sns.boxplot(x="day", y="total_bill", hue="smoker",

                 data=tips, palette="Set3")

However this does not work for me, as I have to specify three datasets, one for each box. How can I do this?

EDIT:  The structure of my dataframes is always the same:

item  |  provider  | appearances

'dog'    'prov1'      0.001
'cat'    'prov2'      0.02
'pig'    'prov1'      0.03
...

The box plots represent the statistics of the items, according to the appearances column, per each provider (6 in total) per each dataframe.

The three dataframes are NOT the same length.

Body:
IIUC, you could concat the three dataframes and assign a column to be used as the hue like:

sns.catplot(x="Provider", y="Appearances",
            kind="box", hue='h',
            data=pd.concat([mlt_sample1k.assign(h='1k'),
                            mlt_sample10k.assign(h='10k'),
                            mlt_sample100k.assign(h='100k')])
           )


问:
Access Amazon QLDB in Spring boot application
is there a way to access Amazon QLDB as a repository in spring boot applications like MongoDB?</p>

答:
I started to look at building exactly what you suggest, I even contacted the lead of spring data to look at adding this (I haven’t raised the ticket yet), however the CrudRepository interface provided enough integration for the demo applications that we have built with Spring Boot. One of the issues that i had when trying to create the Repository was the mapping of fields from the java objects into the partiql fields without explicit knowledge of what was changing.

QLDB does not have a jdbc driver anymore so it is now a proprietary driver which also uses partiql over sql, there could be some further issues getting this to work as a full blown repository in spring boot due to the inner reliance on sql in spring data .


问:
Running two v4l2loopback devices with their individual properties
Working with v4l2loopback devices I can run these two virtual devices:

a) running the preview image from a Canon DSLR via USB through v4l2loopback into OBS:

```<code>modprobe v4l2loopback
gphoto2 --stdout --capture-movie | gst-launch-1.0 fdsrc fd=0 ! decodebin name=dec ! queue ! videoconvert ! tee ! v4l2sink device=/dev/video0
</code>```

Found here, and it works.

b) Streaming the output of OBS into a browser based conferencing system, like this:

```<code>modprobe v4l2loopback devices=1 video_nr=10 card_label="OBS Cam" exclusive_caps=1
</code>```

Found here, this also works.

However, I need to run both a) and b) at the same time, which isn't working as expected. They are interfering, it seems they are using the same buffer the video flips back and forth between the two producers.

What I learned and tried:
A kernel module can only be loaded once. The v4l2loopback module can be unloaded using the command modprobe -r v4l2loopback. I don't know if loading it a second time will be ignored or unload the previous one.

I've tried to load the module with devices=2 as an option as well as different video devices, but I can't find the right syntax.

答:
from your description ("the video flips back and forth between the two producers") it seems that both producers are writing to the same video-device.

to fix this, you need to do two things:

create 2 video-devices

tell each producer to use their own video device

creating multiple video-devices

as documented this can be accomplished by specifying devices=2 when loading the module.

taking your invocation of modprobe, this would mean:

```<code>modprobe v4l2loopback devices=2 video_nr=10 card_label="OBS Cam" exclusive_caps=1
</code>```

this will create two new devices, the first one will be /dev/video10 (since you specified video_nr), the 2nd one will take the first free video-device.
on my system (that has a webcam, which occupies both /dev/video and /dev/video1) this is /dev/video2

telling each producer to use their own device

well, tell one producer to use /dev/video10 and the other to use /dev/video2 (or whatever video-devices you got)

e.g.

```<code>gphoto2 --stdout --capture-movie | gst-launch-1.0 \
       fdsrc fd=0  \
       ! decodebin name=dec  \
       ! queue  \
       ! videoconvert  \
       ! tee  \
       ! v4l2sink device=/dev/video10
</code>```

and configure obs to use /dev/video2.

or the other way round.

just don't use the same video-device for both producers.
(also make sure that your consumers use the correct video-device)

Body:
Working with v4l2loopback devices I can run these two virtual devices:

a) running the preview image from a Canon DSLR via USB through v4l2loopback into OBS:

modprobe v4l2loopback
gphoto2 --stdout --capture-movie | gst-launch-1.0 fdsrc fd=0 ! decodebin name=dec ! queue ! videoconvert ! tee ! v4l2sink device=/dev/video0

Found here, and it works.

b) Streaming the output of OBS into a browser based conferencing system, like this:

modprobe v4l2loopback devices=1 video_nr=10 card_label="OBS Cam" exclusive_caps=1

Found here, this also works.

However, I need to run both a) and b) at the same time, which isn't working as expected. They are interfering, it seems they are using the same buffer the video flips back and forth between the two producers.

What I learned and tried:
A kernel module can only be loaded once. The v4l2loopback module can be unloaded using the command modprobe -r v4l2loopback. I don't know if loading it a second time will be ignored or unload the previous one.

I've tried to load the module with devices=2 as an option as well as different video devices, but I can't find the right syntax.

Body:
from your description ("the video flips back and forth between the two producers") it seems that both producers are writing to the same video-device.

to fix this, you need to do two things:

create 2 video-devices

tell each producer to use their own video device

creating multiple video-devices

as documented this can be accomplished by specifying devices=2 when loading the module.

taking your invocation of modprobe, this would mean:

modprobe v4l2loopback devices=2 video_nr=10 card_label="OBS Cam" exclusive_caps=1

this will create two new devices, the first one will be /dev/video10 (since you specified video_nr), the 2nd one will take the first free video-device.
on my system (that has a webcam, which occupies both /dev/video and /dev/video1) this is /dev/video2

telling each producer to use their own device

well, tell one producer to use /dev/video10 and the other to use /dev/video2 (or whatever video-devices you got)

e.g.

gphoto2 --stdout --capture-movie | gst-launch-1.0 \
       fdsrc fd=0  \
       ! decodebin name=dec  \
       ! queue  \
       ! videoconvert  \
       ! tee  \
       ! v4l2sink device=/dev/video10

and configure obs to use /dev/video2.

or the other way round.

just don't use the same video-device for both producers.
(also make sure that your consumers use the correct video-device)


问:
Props (style) aren't be passed to children
I have this component

And i'm trying to apply background:

Someone know why background isn't appearing?

答:
Please change your BorderLayout to below format.

```<code> return (
    <View style={[styles.parent,props.style]}>
       /* remaining code */
    </View>
)
</code>```

You don't need to use flatten as View takes an array of styles as input. By following approach, BorderLayout default styles can be overridden by using style prop.

Changes made:
moved props.style to the end of the array so that it'll override default styles (in your case backgroundColor).

Body:
Please change your BorderLayout to below format.

 return (
    <View style={[styles.parent,props.style]}>
       /* remaining code */
    </View>
)

You don't need to use flatten as View takes an array of styles as input. By following approach, BorderLayout default styles can be overridden by using style prop.

Changes made:
moved props.style to the end of the array so that it'll override default styles (in your case backgroundColor).


问:
Using Optional.map() instead of Optional.ifPresent() to execute code that may throw an exception and returning any exceptions as the return value
I'm trying to get a feel for the proper way to use the java.util.Optional class.  Given the following example code:

```<code>public void doSomething(File destDir, String classifier) throws IOException {
    URL resourceRoot = introspectionService.getResourceRoot(pattern);

    if (resourceRoot != null) {
        JarFile jarFile = (JarFile) resourceRoot.getContent(); //this can throw IOException
        ... snipped for brevity ...
    }
}
</code>```

I would like to convert this method to use an Optional<URL> value from the introspectionService.

```<code>public void doSomething(File destDir, String classifier) throws IOException {
    Optional<URL> resourceRoot = introspectionService.getResourceRoot(pattern);

    resourceRoot.ifPresent(rootUrl-> {
        JarFile jarFile = (JarFile) rootUrl.getContent(); //this can throw IOException
        ... snipped for brevity ...
    });
}
</code>```

This obviously fails to compile because the signature of ifPresent() takes a Consumer which does not allow exceptions to be thrown from the accept() method.

I came up with the following work-around and was wondering if there is a better way:

```<code>public void doSomething(File destDir, String classifier) throws IOException {
    Optional<URL> resourceRoot = introspectionService.getResourceRoot(pattern);

    Optional<IOException> ioException =
    resourceRoot.map(rootUrl-> {
        try {
            JarFile jarFile = (JarFile) rootUrl.getContent(); //this can throw IOException
        ... snipped for brevity ...
            return null;
        }
        catch(IOException e) {
            return e;
        }
    });
    if (ioException.isPresent()) {
        throw ioException.get();
    }
}
</code>```

Is there a better alternative?

答:
EDIT: As MC Emperor suggested, you can catch the IOException and then throw an UncheckedIOException.

Here's a more generic way to do it by making the compiler think a checked exception is really unchecked.

```<code>resourceRoot.map(rootUrl-> {
    try {
        JarFile jarFile = (JarFile) rootUrl.getContent(); //this can throw IOException
    ... snipped for brevity ...
        return null;
    }
    catch(IOException e) {
        sneakyThrow(e);
    }
});
</code>```

You can define sneakyThrow as given below (I got it from this article). Because of type erasure and type inference (T is inferred to either RuntimeException or Error), it compiles without errors but still runs as if you actually said throw e.

```<code>public static <T extends Throwable> void sneakyThrow(Throwable t) throws T {
    throw (T) t;
}
</code>```

Lombok has a SneakyThrows annotation that helps you do this.

This way, you don't have to wrap it in a RuntimeException or anything - the exception is simply an IOException at runtime too.

Body:
I'm trying to get a feel for the proper way to use the java.util.Optional class.  Given the following example code:

public void doSomething(File destDir, String classifier) throws IOException {
    URL resourceRoot = introspectionService.getResourceRoot(pattern);

    if (resourceRoot != null) {
        JarFile jarFile = (JarFile) resourceRoot.getContent(); //this can throw IOException
        ... snipped for brevity ...
    }
}

I would like to convert this method to use an Optional<URL> value from the introspectionService.

public void doSomething(File destDir, String classifier) throws IOException {
    Optional<URL> resourceRoot = introspectionService.getResourceRoot(pattern);

    resourceRoot.ifPresent(rootUrl-> {
        JarFile jarFile = (JarFile) rootUrl.getContent(); //this can throw IOException
        ... snipped for brevity ...
    });
}

This obviously fails to compile because the signature of ifPresent() takes a Consumer which does not allow exceptions to be thrown from the accept() method.

I came up with the following work-around and was wondering if there is a better way:

public void doSomething(File destDir, String classifier) throws IOException {
    Optional<URL> resourceRoot = introspectionService.getResourceRoot(pattern);

    Optional<IOException> ioException =
    resourceRoot.map(rootUrl-> {
        try {
            JarFile jarFile = (JarFile) rootUrl.getContent(); //this can throw IOException
        ... snipped for brevity ...
            return null;
        }
        catch(IOException e) {
            return e;
        }
    });
    if (ioException.isPresent()) {
        throw ioException.get();
    }
}

Is there a better alternative?

Body:
EDIT: As MC Emperor suggested, you can catch the IOException and then throw an UncheckedIOException.

Here's a more generic way to do it by making the compiler think a checked exception is really unchecked.

resourceRoot.map(rootUrl-> {
    try {
        JarFile jarFile = (JarFile) rootUrl.getContent(); //this can throw IOException
    ... snipped for brevity ...
        return null;
    }
    catch(IOException e) {
        sneakyThrow(e);
    }
});

You can define sneakyThrow as given below (I got it from this article). Because of type erasure and type inference (T is inferred to either RuntimeException or Error), it compiles without errors but still runs as if you actually said throw e.

public static <T extends Throwable> void sneakyThrow(Throwable t) throws T {
    throw (T) t;
}

Lombok has a SneakyThrows annotation that helps you do this.

This way, you don't have to wrap it in a RuntimeException or anything - the exception is simply an IOException at runtime too.


问:
Mysql query max function for each row of a new column
I want to create a new column with the max value of another column in each row but when I use MAX() function it return only one row.

I would like to have the same value in each row. From the first code without MAX function i get 533 rows, then when i use MAX() I only get one row.

```<code>SELECT
    ap.id,
    ap.name,
    apc.closing_prob_c
FROM a_assigned_prospect ap
LEFT JOIN a_assigned_prospect_cstm apc ON apc.id_c=ap.id
</code>```

```<code>SELECT
    ap.id,
    ap.name,
    apc.closing_prob_c,
    MAX(apc.closing_prob_c)
FROM a_assigned_prospect ap
LEFT JOIN a_assigned_prospect_cstm apc ON apc.id_c=ap.id
</code>```

答:
I understand that you want the new column to have the max value of apc.closing_prob_c over the whole resultset, while still returning the original 533 rows.

If you are running MySQL 8.0, that's straight forward with a window max:

```<code>select
    ap.id,
    ap.name,
    apc.closing_prob_c,
    max(apc.closing_prob_c) over() max_closing_prob_c
from a_assigned_prospect ap
left join a_assigned_prospect_cstm apc on apc.id_c = ap.id
</code>```

In earlier versions, you would typically use a subquery:

```<code>select
    ap.id,
    ap.name,
    apc.closing_prob_c,
    (
        select max(apc1.closing_prob_c)
        from a_assigned_prospect_cstm apc1
        where exists (
            select 1 from a_assigned_prospect ap1 where ap1.id = apc1.id_c
        )
    ) max_closing_prob_c
from a_assigned_prospect ap
left join a_assigned_prospect_cstm apc on apc.id_c=ap.id
</code>```

Body:
I want to create a new column with the max value of another column in each row but when I use MAX() function it return only one row.

I would like to have the same value in each row. From the first code without MAX function i get 533 rows, then when i use MAX() I only get one row.

SELECT
    ap.id,
    ap.name,
    apc.closing_prob_c
FROM a_assigned_prospect ap
LEFT JOIN a_assigned_prospect_cstm apc ON apc.id_c=ap.id

SELECT
    ap.id,
    ap.name,
    apc.closing_prob_c,
    MAX(apc.closing_prob_c)
FROM a_assigned_prospect ap
LEFT JOIN a_assigned_prospect_cstm apc ON apc.id_c=ap.id

Body:
I understand that you want the new column to have the max value of apc.closing_prob_c over the whole resultset, while still returning the original 533 rows.

If you are running MySQL 8.0, that's straight forward with a window max:

select
    ap.id,
    ap.name,
    apc.closing_prob_c,
    max(apc.closing_prob_c) over() max_closing_prob_c
from a_assigned_prospect ap
left join a_assigned_prospect_cstm apc on apc.id_c = ap.id

In earlier versions, you would typically use a subquery:

select
    ap.id,
    ap.name,
    apc.closing_prob_c,
    (
        select max(apc1.closing_prob_c)
        from a_assigned_prospect_cstm apc1
        where exists (
            select 1 from a_assigned_prospect ap1 where ap1.id = apc1.id_c
        )
    ) max_closing_prob_c
from a_assigned_prospect ap
left join a_assigned_prospect_cstm apc on apc.id_c=ap.id


问:
When are Backticks ' ' used compared to Double Quotes " "?
What I know so far ...

1) Backticks are used when creating tibbles with non-syntactic variable/column names that contain numbers, spaces, or other symbols (because normally you can only name columns with letters right?)

```<code> tb <- tibble(
               ': ) ' = "smile, ' ' = "space",
               '2000' = "number", "double_quotes" = "normal_text")
</code>```

However, when I use double quotes here the tibble still forms with the nonsyntactic symbols/numbers.

2) Double quotes are used to subset column names when using double brackets.

```<code>  tb[["double_quotes"]]
</code>```

And here, when I use single quotes to subset, it still works as well.

3) When subsetting using $, to select for nonsyntactic names, I must use single quotes, but here again, if I subset using double quotes, it works as well

Again, tb$": )" works just as well as tb$': )'

So are they effectively interchangeable?

Interestingly, when I plot a graph

```<code>annoying <- tibble(
  `1` = 1:10,
  `2` = `1` * 2 + rnorm(length(`1`))
)

ggplot(annoying, aes(x = `1`, y = `2`)) +
  geom_point()
</code>```

Single quotes must be used when referring to the nonsyntactic variables because otherwise, it looks like ggplot treats X and Y as single points of 1 and 2 respectively. Are there any other cases like this?

答:
It's important to distinguish between single quotes (') and backticks (or "back-single-quotes") (`).

Most of what you want to know is in ?Quotes:

Single (') and double (") quotes delimit character constants.  They can be
       used interchangeably but double quotes are preferred (and
       character constants are printed using double quotes), so single
       quotes are normally only used to delimit character constants
       containing double quotes.

Almost always, other [i.e., non-syntactically valid] names can be used
       provided they are quoted.  The preferred quote is the backtick
       (‘`’) ... under many
       circumstances single or double quotes can be used (as a character
       constant will often be converted to a name).  One place where
       backticks may be essential is to delimit variable names in
       formulae: see ‘formula’.

For example, if you want to define a variable name containing a space, you need back-ticks:

```<code>`a b` <- 1
</code>```

Double quotes also work here (to my surprise!)

```<code>"a b" <- 1
</code>```

but if you want to use the resulting variable in an expression you'll need to use back-ticks. "a b" + 1 gives an error (" non-numeric argument to binary operator") but `a b`+1 works.

As @r2evans points out, the same rules apply in tidyverse expressions. You can use double- or single-quotes (if you want) to define new variables: mtcars %>% mutate("my stuff"=4), but if you want to subsequently use that variable (or any other non-syntactic variable) in an expression, you have to backtick-protect it: mtcars %>% mutate("my stuff"=4, new=`my stuff` + 5).

It's probably best practice/least confusing to just use backticks for all non-syntactic variable reference and single quotes for character constants.

Body:
What I know so far ...

1) Backticks are used when creating tibbles with non-syntactic variable/column names that contain numbers, spaces, or other symbols (because normally you can only name columns with letters right?)

 tb <- tibble(
               ': ) ' = "smile, ' ' = "space",
               '2000' = "number", "double_quotes" = "normal_text")

However, when I use double quotes here the tibble still forms with the nonsyntactic symbols/numbers.

2) Double quotes are used to subset column names when using double brackets.

  tb[["double_quotes"]]

And here, when I use single quotes to subset, it still works as well.

3) When subsetting using $, to select for nonsyntactic names, I must use single quotes, but here again, if I subset using double quotes, it works as well

Again, tb$": )" works just as well as tb$': )'

So are they effectively interchangeable?

Interestingly, when I plot a graph

annoying <- tibble(
  `1` = 1:10,
  `2` = `1` * 2 + rnorm(length(`1`))
)

ggplot(annoying, aes(x = `1`, y = `2`)) +
  geom_point()

Single quotes must be used when referring to the nonsyntactic variables because otherwise, it looks like ggplot treats X and Y as single points of 1 and 2 respectively. Are there any other cases like this?

Body:
It's important to distinguish between single quotes (') and backticks (or "back-single-quotes") (`).

Most of what you want to know is in ?Quotes:

Single (') and double (") quotes delimit character constants.  They can be
       used interchangeably but double quotes are preferred (and
       character constants are printed using double quotes), so single
       quotes are normally only used to delimit character constants
       containing double quotes.

Almost always, other [i.e., non-syntactically valid] names can be used
       provided they are quoted.  The preferred quote is the backtick
       (‘`’) ... under many
       circumstances single or double quotes can be used (as a character
       constant will often be converted to a name).  One place where
       backticks may be essential is to delimit variable names in
       formulae: see ‘formula’.

For example, if you want to define a variable name containing a space, you need back-ticks:

`a b` <- 1

Double quotes also work here (to my surprise!)

"a b" <- 1

but if you want to use the resulting variable in an expression you'll need to use back-ticks. "a b" + 1 gives an error (" non-numeric argument to binary operator") but `a b`+1 works.

As @r2evans points out, the same rules apply in tidyverse expressions. You can use double- or single-quotes (if you want) to define new variables: mtcars %>% mutate("my stuff"=4), but if you want to subsequently use that variable (or any other non-syntactic variable) in an expression, you have to backtick-protect it: mtcars %>% mutate("my stuff"=4, new=`my stuff` + 5).

It's probably best practice/least confusing to just use backticks for all non-syntactic variable reference and single quotes for character constants.


问:
How to use NavigationLink to detect name of click NavigationView item
How can the destination of a NavigationLink can modified to detect which item within a list was clicked? An if statement of some sort would be very helpful but all items currently do the same thing.

```<code>import SwiftUI

let textTitle = NSLocalizedString("PageTitle", comment: "")
let textItemA = NSLocalizedString("ItemA", comment: "")
let textItemB = NSLocalizedString("ItemB", comment: "")
let textItemC = NSLocalizedString("ItemC", comment: "")

struct ItemMain: Identifiable {
    var id = UUID()
    var name: String
}

let myItems: [MyItem] = [
    MyItem(name: textItemA),
    MyItem(name: textItemB),
    MyItem(name: textItemC)]

struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {
        NavigationView{
            List(myItems) { myItem in
                NavigationLink(destination: MyDetailView(myItem: myItem)) {
                    Text(myItem.name)
                }
            }

            .navigationBarTitle(textTitle)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct MyDetailView: View {
    var myItem: MyItem

    var body: some View {
        Text(myIem.name)
    }
}
</code>```

答:
You can use if statement inside the ForEach to specify special cases:

```<code>List(myItems) { myItem in
    if (myItem.name == "ItemA") //<<< Here goes your if
    {
        NavigationLink(destination: MyDetailView(myItem: myItem)) {
            Text(myItem.name)
        }
     }
     else
     {
         //show your alert here
</code>```

Body:
How can the destination of a NavigationLink can modified to detect which item within a list was clicked? An if statement of some sort would be very helpful but all items currently do the same thing.

import SwiftUI

let textTitle = NSLocalizedString("PageTitle", comment: "")
let textItemA = NSLocalizedString("ItemA", comment: "")
let textItemB = NSLocalizedString("ItemB", comment: "")
let textItemC = NSLocalizedString("ItemC", comment: "")

struct ItemMain: Identifiable {
    var id = UUID()
    var name: String
}

let myItems: [MyItem] = [
    MyItem(name: textItemA),
    MyItem(name: textItemB),
    MyItem(name: textItemC)]

struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {
        NavigationView{
            List(myItems) { myItem in
                NavigationLink(destination: MyDetailView(myItem: myItem)) {
                    Text(myItem.name)
                }
            }

            .navigationBarTitle(textTitle)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct MyDetailView: View {
    var myItem: MyItem

    var body: some View {
        Text(myIem.name)
    }
}

Body:
You can use if statement inside the ForEach to specify special cases:

List(myItems) { myItem in
    if (myItem.name == "ItemA") //<<< Here goes your if
    {
        NavigationLink(destination: MyDetailView(myItem: myItem)) {
            Text(myItem.name)
        }
     }
     else
     {
         //show your alert here


问:
C# WinForm KeyPress Enter key not fire after link clicked
Here is simple code in windowsForm

```<code>    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
       MessageBox.Show("LOLOLO");
       if (e.KeyChar == 13)
       {
         panel3.Visible = true;
       }
    }
</code>```

And i have Panel control with link which close this panel

```<code>private void linkLabel2_Click(object sender, EventArgs e)
{
   panel3.Visible = false;
}
</code>```

I'ts work When i press any key it show me MessageBox but when i press ENTER my Panel is open.
Problem is when i mouse clicked linkLabel2 to close Panel, any keys fire keyPress event, except ENTER key. When i press ENTER nothing to do, keyPress event not fire

How to fix it?

答:
Your code not work, I've added this.ActiveControl = null; inside linkLabel2_Click event and now works perfectlly!</p>

```<code>private void linkLabel2_Click(object sender, EventArgs e)
{
   this.ActiveControl = null;
   panel3.Visible = false;
}
</code>```

Body:
Here is simple code in windowsForm

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
       MessageBox.Show("LOLOLO");
       if (e.KeyChar == 13)
       {
         panel3.Visible = true;
       }
    }

And i have Panel control with link which close this panel

private void linkLabel2_Click(object sender, EventArgs e)
{
   panel3.Visible = false;
}

I'ts work When i press any key it show me MessageBox but when i press ENTER my Panel is open.
Problem is when i mouse clicked linkLabel2 to close Panel, any keys fire keyPress event, except ENTER key. When i press ENTER nothing to do, keyPress event not fire

How to fix it?

Body:
Your code not work, I've added this.ActiveControl = null; inside linkLabel2_Click event and now works perfectlly!

private void linkLabel2_Click(object sender, EventArgs e)
{
   this.ActiveControl = null;
   panel3.Visible = false;
}


问:
is it possible to install scapy on openWRT
I want to install scapy and wireshrk for python 2.7(already present in openWRT) in an ARM system having openWRT? Is there a package easy to install scapy in openWRT?  </p>

答:
As of today, scapy is available on the repositories:

```<code># opkg update
# opkg install scapy
</code>```

Body:
As of today, scapy is available on the repositories:

# opkg update
# opkg install scapy


问:
Optimizing Airflow Task that transfers data from BigQuery into MongoDB
I need to improve the performance of an Airflow task that transfers data from BigQuery to MongoDB. The relevant task in my DAG uses a PythonOperator, and simply calls the following python function to transfer a single table/collection:

```<code>def transfer_full_table(table_name):
    start_time = time.time()

    # (1) Connect to BigQuery + Mongo DB
    bq = bigquery.Client()
    cluster = MongoClient(MONGO_URI)
    db = cluster["dbname"]
    print(f'(1) Connected to BQ + Mongo: {round(time.time() - start_time, 5)}')

    # (2)-(3) Run the BQ Queries
    full_query = f"select * from `gcpprojectid.models.{table_name}`"
    results1 = bq.query(full_query)
    print(f'(2) Queried BigQuery: {round(time.time() - start_time, 5)}')
    results = results1.to_dataframe()
    print(f'(3) Converted to Pandas DF: {round(time.time() - start_time, 5)}')

    # (4) Handle Missing DateTimes   # Can we refactor this into its own function?
    datetime_cols = [key for key in dict(results.dtypes) if is_datetime(results[key])]
    for col in datetime_cols:
        results[[col]] = results[[col]].astype(object).where(results[[col]].notnull(), None)
    print(f'(4) Resolved Datetime Issue: {round(time.time() - start_time, 5)}')

    # (5) And Insert Properly Into Mongo
    db[table_name].drop()
    db[table_name].insert_many(results.to_dict('records'))
    print(f'(5) Wrote to Mongo: {round(time.time() - start_time, 5)}')
</code>```

The DAG is setup to transfer many tables from BigQuery to MongoDB (one transfer for each task), and this particular transfer_full_table function is meant to transfer an entire singular table, so it simply:

queries entire BQ table

converts to pandas, fixes type issue

drop previous MongoDB collection and reinsert

I am attempting to use this function on a table that is 60MB in size, and here is the performance of the various parts of the task:

```<code>(1) Connected to BQ + Mongo: 0.0786
(2) Queried BigQuery: 0.80595
(3) Converted to Pandas DF: 87.2797
(4) Resolved Datetime Issue: 88.33461
(5) Wrote to Mongo: 213.92398
</code>```

Steps 3 and 5 are taking all of the time. The task very quickly connects to BQ and Mongo (1), and BQ can very quickly query this table at 60MB (2). However, when I convert to a pandas dataframe (3) (needed for (4) to handle a type issue I was having), this step takes ~86.5 seconds. Resolving the date-time issue is then very fast (4), however at the end, dropping the previous MongoDB collection and re-inserting the new pandas dataframe into MongoDB (5) then takes (213.9 - 88.3) = ~125 seconds.

I am seeking any tips, either on the Pandas or on the MongoDB end, as to how I can optimize for these two bottlenecks.

答:
The short answer is that asynchronous operations are muddying your profiling.

The docs on bq.query state that the resulting google.cloud.bigquery.job.QueryJob object is an asyncronous query job. This means that, after the query is submitted, the python interpreter does not block until you try to use the results of the query with one of the syncronous QueryJob methods, to_dataframe(). A significant share of the 87 seconds you're seeing is likely just spent waiting for the query to return.

You could wait for the query to be complete by calling QueryJob.done iteratively until it returns true, then call your 2nd profiling print statement.

This isn't quite an optimization of your code, but hopefully helps move in the right direction. It's possible some tuning of the pandas roundtrip could help, but I think it's likely that most of your time is being spent waiting for read/write from your databases, and that writing more efficient or a larger number of smaller queries is going to be your only option for cutting down the total time.

Body:
I need to improve the performance of an Airflow task that transfers data from BigQuery to MongoDB. The relevant task in my DAG uses a PythonOperator, and simply calls the following python function to transfer a single table/collection:

def transfer_full_table(table_name):
    start_time = time.time()

    # (1) Connect to BigQuery + Mongo DB
    bq = bigquery.Client()
    cluster = MongoClient(MONGO_URI)
    db = cluster["dbname"]
    print(f'(1) Connected to BQ + Mongo: {round(time.time() - start_time, 5)}')

    # (2)-(3) Run the BQ Queries
    full_query = f"select * from `gcpprojectid.models.{table_name}`"
    results1 = bq.query(full_query)
    print(f'(2) Queried BigQuery: {round(time.time() - start_time, 5)}')
    results = results1.to_dataframe()
    print(f'(3) Converted to Pandas DF: {round(time.time() - start_time, 5)}')

    # (4) Handle Missing DateTimes   # Can we refactor this into its own function?
    datetime_cols = [key for key in dict(results.dtypes) if is_datetime(results[key])]
    for col in datetime_cols:
        results[[col]] = results[[col]].astype(object).where(results[[col]].notnull(), None)
    print(f'(4) Resolved Datetime Issue: {round(time.time() - start_time, 5)}')

    # (5) And Insert Properly Into Mongo
    db[table_name].drop()
    db[table_name].insert_many(results.to_dict('records'))
    print(f'(5) Wrote to Mongo: {round(time.time() - start_time, 5)}')

The DAG is setup to transfer many tables from BigQuery to MongoDB (one transfer for each task), and this particular transfer_full_table function is meant to transfer an entire singular table, so it simply:

queries entire BQ table

converts to pandas, fixes type issue

drop previous MongoDB collection and reinsert

I am attempting to use this function on a table that is 60MB in size, and here is the performance of the various parts of the task:

(1) Connected to BQ + Mongo: 0.0786
(2) Queried BigQuery: 0.80595
(3) Converted to Pandas DF: 87.2797
(4) Resolved Datetime Issue: 88.33461
(5) Wrote to Mongo: 213.92398

Steps 3 and 5 are taking all of the time. The task very quickly connects to BQ and Mongo (1), and BQ can very quickly query this table at 60MB (2). However, when I convert to a pandas dataframe (3) (needed for (4) to handle a type issue I was having), this step takes ~86.5 seconds. Resolving the date-time issue is then very fast (4), however at the end, dropping the previous MongoDB collection and re-inserting the new pandas dataframe into MongoDB (5) then takes (213.9 - 88.3) = ~125 seconds.

I am seeking any tips, either on the Pandas or on the MongoDB end, as to how I can optimize for these two bottlenecks.


问:
Adding more commits to a Branch in Git
Apologies in advance. I'm sure this is a very simple question with a very simple answer but I'm a beginner at Git and I'm a bit lost. I have a master branch. I made some changes yesterday and performed git add ., git commit, made a new branch by doing git branch part-one, then I pushed the commits to that new branch by doing git push origin part-one. I see that my commits got pushed into that branch on github. Now, I did some more work on the same files. I added and staged the changes just as before. Now when I go to push the commits by doing git push origin part-one it says Everything up-to-date. I don't see the most recent commits in my history on github.

Why is it not pushing the most recent commit to my part-one branch?

Possible cause: If I wanted to push these commits to my branch. Was I supposed to be do git checkout part-one, then do git add and git commit? I did those commands while I was on the master.

答:
In case anyone comes across this in the future: here's the solution that worked for me.

The problem was I had commits on my master that I actually wanted on my branch. What I did was this. I merged my branch with my master meaning that the branch will get all the commits from master, and the master will get all the commits from branch. From here, depending on what you need; you can use git reset --keep HEAD~X where X is how many commits you want to delete. You can then push the commits to your Github.

For reference: this was it Move the most recent commit(s) to a new branch with Git

Title: Adding more commits to a Branch in Git


问:
Change the Sender in Outlook using Redemption, but not with an account in the profile
I'm attempting to create Outlook emails that should be sent "from" someone other than the person actually sending the email. The idea is to prefill the email, display it in Outlook, allowing the end user to modify before sending. As a part of that process, I would like to use a different email address, which is a true email address, but is not an account in the end user's profile.

If this were SMTP, I could use the Net.Mail classes, which will accept any smtp address as the sender. Like this:

string from = "mytest@myorg.com";
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(from, to);

My question then, is it possible to do this using Redemption? All the examples that I've been able to find talk about either accessing the "Sender" property, or the "SendUsingAccount" property. From what I can tell, these both require an Account in the user profile.

答: If you are sending using Exchange (as well as most SMTP servers), it will not let you spoof the sender. The user must actually have the right to send as that user.</p>


问:
render function is not rendering items
I'm trying to render across an array object in react.js using this:

```<code>const myservice = getAllServices(uid).then(service => {
      renderallServices(service);
      return service;
  });
</code>```

where renderallServices(service) is

```<code>const renderallServices = (services) => (
  <>
  {services.map(service => (
          <Row className="justify-content-md-center">
          <ServiceCard service={service}>
          </ServiceCard>
          {console.log(service)}
          </Row>
        ))

    }
  </>

  );
</code>```

Note: the reason my renderallServices function is being called inside of .then() is because without that it returns a promise instead of the actual array object I want.
I know renderallServices is being called because the {console.log(service)} is returning each element in the array like I would expect. However, none of the JSX is being rendered.

答: What contains service ? Is it some jsx ? Because you are calling renderAllServices() which return jsx, but are returning service in your .then.

Title: render function is not rendering items

Body:
I'm trying to render across an array object in react.js using this:

const myservice = getAllServices(uid).then(service => {
      renderallServices(service);
      return service;
  });

where renderallServices(service) is

const renderallServices = (services) => (
  <>
  {services.map(service => (
          <Row className="justify-content-md-center">
          <ServiceCard service={service}>
          </ServiceCard>
          {console.log(service)}
          </Row>
        ))

    }
  </>

  );

Note: the reason my renderallServices function is being called inside of .then() is because without that it returns a promise instead of the actual array object I want.
I know renderallServices is being called because the {console.log(service)} is returning each element in the array like I would expect. However, none of the JSX is being rendered.


问:
How would I get the text of a JLabel (with an icon) explaining what the label is by hovering over the label?
I want to see the text of JLabel when I hover over the label. The text explains what the label does in detail.</p>

答:
If you want to retrieve the Tooltip then you should use something like this:

```<code>JLabel label;
...//initialize label, etc
String text = label.getToolTipText();
</code>```

In case you are asking how to set the Tooltip then you should do the opposite:

```<code>JLabel label;
...//initialize label, etc
label.setToolTipText("this is the description of the label");
</code>```

Body:
If you want to retrieve the Tooltip then you should use something like this:

JLabel label;
...//initialize label, etc
String text = label.getToolTipText();

In case you are asking how to set the Tooltip then you should do the opposite:

JLabel label;
...//initialize label, etc
label.setToolTipText("this is the description of the label");


问:
Issue in getting facebook ad campaign details using curl and python code
Please help me in fixing curl command and python code. I am putting the secret key, but unable to get the CAMPAIGN_ID. I have created an ad for my facebook page, but couldn't find CAMPAIGN_ID, I have tried to use Ad id, but that also didn't work.

```<code>curl -G \
     -d "level=ad" \
     -d "fields=impressions,ad_id" \
     -d "access_token=<ACCESS_TOKEN>" \
     "https://graph.facebook.com/<API_VERSION>/<CAMPAIGN_ID>/insights"
</code>```

I also used the python code below, but got a few errors.

```<code>from facebook_business.objects import AdCampaign
    campaign = AdCampaign('<AD_CAMPAIGN_ID>')
    params = {
                    'date_preset': AdCampaign.Preset.last_7_days,
    }
    insights = campaign.get_insights(params=params)
    print insights
</code>```

Below is the error:

traceback (most recent call last):
File "fbAds2.py", line 1, in <module>
from facebook_business.objects import AdCampaign
ModuleNotFoundError: No module named 'facebook_business.objects'```
</code>```

答:
I get the same error so I changed the code a bit and got results</p>

```<code>from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.campaign import Campaign
from facebook_business.api import FacebookAdsApi

app_id = 'zzzzzzzz'
app_secret = 'yyyyyyyy'
access_token = 'xxxxxxxxxxxxx'

campaign = Campaign('xxxxxxxx')

insights = campaign.get_insights()
print(insights)
</code>```

Body:
Please help me in fixing curl command and python code. I am putting the secret key, but unable to get the CAMPAIGN_ID. I have created an ad for my facebook page, but couldn't find CAMPAIGN_ID, I have tried to use Ad id, but that also didn't work.

curl -G \
     -d "level=ad" \
     -d "fields=impressions,ad_id" \
     -d "access_token=<ACCESS_TOKEN>" \
     "https://graph.facebook.com/<API_VERSION>/<CAMPAIGN_ID>/insights"

I also used the python code below, but got a few errors.

from facebook_business.objects import AdCampaign
    campaign = AdCampaign('<AD_CAMPAIGN_ID>')
    params = {
                    'date_preset': AdCampaign.Preset.last_7_days,
    }
    insights = campaign.get_insights(params=params)
    print insights

Below is the error:

traceback (most recent call last):
File "fbAds2.py", line 1, in <module>
from facebook_business.objects import AdCampaign
ModuleNotFoundError: No module named 'facebook_business.objects'```

Body:
I get the same error so I changed the code a bit and got results

from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.campaign import Campaign
from facebook_business.api import FacebookAdsApi

app_id = 'zzzzzzzz'
app_secret = 'yyyyyyyy'
access_token = 'xxxxxxxxxxxxx'

campaign = Campaign('xxxxxxxx')

insights = campaign.get_insights()
print(insights)


问:
Change text of a specific tkinter Label using function with arguments
I'm trying to reference a specific tkinter Label in a function based on an argument input. I've tried many things, and found some topics on exec and eval and variable variables, but I want to steer away from bad practices (I don't know how to achieve it through those methods anyway). I feel like I'm missing something extremely basic, but I can't wrap my head around it.

Below is a simplified code of my function:

```<code>    def myFunction(input_num):
        while ArbitraryVariableName == False:
            # Do stuff in while loop

        if input_num== "1":
            self.lbl1["text"] = "New Value 1"
        elif input_num == "2":
            self.lbl2["text"] = "New Value 2"
        elif input_num== "3":
            self.lbl3["text"] = "New Value 3"
        elif input_num== "4":
            self.lbl4["text"] = "New Value 4"
        elif input_num== "5":
            self.lbl5["text"] = "New Value 5"

        # And so forth for 20+ more elif statements
</code>```

You will notice that the input_num directly relates to the specific tkinter Label name of "lbl + input_num". If it helps, below is the code for one of two of the labels (they all follow a similar pattern):

```<code>    self.lbl1 = Label(topframe, text="Old Value Test 1")
    self.lbl1 .grid(column=1, row=1)

    self.lbl2 = Label(topframe, text="Old Value Test 2")
    self.lbl2 .grid(column=1, row=2)

    # And so forth
</code>```

Is there a cleaner and less-repetitive way to do this?

答:
You say that you don't want to have to use the eval function, so you could instead use a label list, which makes your code rather a lot shorter:

import tkinter as tk

class example:
    def __init__(self, master):
        self.master = master

        self.lbl1 = tk.Label(self.master, text="Old Value Test 1")
        self.lbl1.grid(column=0, row=0)

        self.lbl2 = tk.Label(self.master, text="Old Value Test 2")
        self.lbl2.grid(column=0, row=1)

        self.lbls = [self.lbl1, self.lbl2]

        self.myfunction(1)
        self.myfunction(2)

    def myfunction(self, input_num):
        self.lbls[input_num - 1]["text"] = f"New Value {input_num}"

def main():
    root = tk.Tk()
    example_win = example(root)
    root.mainloop()

if __name__ == '__main__':
    main()
```

With this code I did assume you had an integer from the input_num variable, instead of the string you showed in your example.

If you aren't using Python 3 you can't take advantage of the f-string.

Hope this helps,

James

Body:
I'm trying to reference a specific tkinter Label in a function based on an argument input. I've tried many things, and found some topics on exec and eval and variable variables, but I want to steer away from bad practices (I don't know how to achieve it through those methods anyway). I feel like I'm missing something extremely basic, but I can't wrap my head around it.

Below is a simplified code of my function:

    def myFunction(input_num):
        while ArbitraryVariableName == False:
            # Do stuff in while loop

        if input_num== "1":
            self.lbl1["text"] = "New Value 1"
        elif input_num == "2":
            self.lbl2["text"] = "New Value 2"
        elif input_num== "3":
            self.lbl3["text"] = "New Value 3"
        elif input_num== "4":
            self.lbl4["text"] = "New Value 4"
        elif input_num== "5":
            self.lbl5["text"] = "New Value 5"

        # And so forth for 20+ more elif statements

You will notice that the input_num directly relates to the specific tkinter Label name of "lbl + input_num". If it helps, below is the code for one of two of the labels (they all follow a similar pattern):

    self.lbl1 = Label(topframe, text="Old Value Test 1")
    self.lbl1 .grid(column=1, row=1)

    self.lbl2 = Label(topframe, text="Old Value Test 2")
    self.lbl2 .grid(column=1, row=2)

    # And so forth

Is there a cleaner and less-repetitive way to do this?

Body:
You say that you don't want to have to use the eval function, so you could instead use a label list, which makes your code rather a lot shorter:

import tkinter as tk

class example:
    def __init__(self, master):
        self.master = master

        self.lbl1 = tk.Label(self.master, text="Old Value Test 1")
        self.lbl1.grid(column=0, row=0)

        self.lbl2 = tk.Label(self.master, text="Old Value Test 2")
        self.lbl2.grid(column=0, row=1)

        self.lbls = [self.lbl1, self.lbl2]

        self.myfunction(1)
        self.myfunction(2)

    def myfunction(self, input_num):
        self.lbls[input_num - 1]["text"] = f"New Value {input_num}"

def main():
    root = tk.Tk()
    example_win = example(root)
    root.mainloop()

if __name__ == '__main__':
    main()

With this code I did assume you had an integer from the input_num variable, instead of the string you showed in your example.

If you aren't using Python 3 you can't take advantage of the f-string.

Hope this helps,

James


问:
aws (pip) returns invalid syntax
I am trying to install Amazon Web Services in pip, with

```<code>pip3 install awscli
</code>```

but I am getting an error when I try to run aws or aws configure in that case:

```<code>Traceback (most recent call last):
  File "/usr/local/bin/aws", line 7, in <module>
    from aws.main import main
  File "/usr/local/lib/python3.6/site-packages/aws/main.py", line 23
    print '%(name)s: %(endpoint)s' % {
</code>```

any clues?

答:
I found going into my python directory and removing the aws.exe fixed this error for me.

Go to this location
C:\Users\user.name\AppData\Roaming\Python\Python37\Scripts\

and delete this file aws.exe

Title: aws (pip) returns invalid syntax

Body:
I am trying to install Amazon Web Services in pip, with

pip3 install awscli

but I am getting an error when I try to run aws or aws configure in that case:

Traceback (most recent call last):
  File "/usr/local/bin/aws", line 7, in <module>
    from aws.main import main
  File "/usr/local/lib/python3.6/site-packages/aws/main.py", line 23
    print '%(name)s: %(endpoint)s' % {

any clues?


问:
Python not running a new window until closing another window
Why is Python waiting for you to close one window in order to open another?
Is it impossible to simultaneously open both?
Or why calling a Window in an infinite loop stops this loop until you close the window?</p>

```<code>    while True:
        webview.create_window('Hello world 1', 'https://gog.com/')
        webview.start()
        #loop waiting until wv is close
</code>```

答:
You can use multiprocessing to accomplish this:

from multiprocessing import Process
processes = []

    while True:
        webview.create_window('Hello world 1', 'https://gog.com/')
        window_process = Proces(target=webview.start, args=())
        window_process.start()
        processes.append(window_process) #So we can quit it later
```

<p>Then at the end of your code, put this to quit the processes neatly:</p>

<pre class="lang-py prettyprint-override"><code>for process in processes:
    try:
        process.terminate()
        process.join()
    except:
        pass
</code>```

Body:
Why is Python waiting for you to close one window in order to open another?
Is it impossible to simultaneously open both?
Or why calling a Window in an infinite loop stops this loop until you close the window?

    while True:
        webview.create_window('Hello world 1', 'https://gog.com/')
        webview.start()
        #loop waiting until wv is close

Body:
You can use multiprocessing to accomplish this:

from multiprocessing import Process
processes = []

    while True:
        webview.create_window('Hello world 1', 'https://gog.com/')
        window_process = Proces(target=webview.start, args=())
        window_process.start()
        processes.append(window_process) #So we can quit it later

Then at the end of your code, put this to quit the processes neatly:

for process in processes:
    try:
        process.terminate()
        process.join()
    except:
        pass


问:
test the existence of property in a deep object structure
In javascript, lets say I want to access a property deep in an object, for example:

entry.mediaGroup[0].contents[0].url

At any point along that structure, a property may be undefined (so mediaGroup may not be set).

What is a simple way to say:

```<code>if( entry.mediaGroup[0].contents[0].url ){
   console.log( entry.mediaGroup[0].contents[0].url )
}
</code>```

without generating an error? This way will generate an undefined error if any point along the way is undefined.

My solution

```<code>if(entry) && (entry.mediaGroup) && (entry.MediaGroup[0]) ...snip...){
   console.log(entry.mediaGroup[0].contents[0].url)
}
</code>```

which is pretty lengthy. I am guessing there must be something more elegant.

答:
Your current solution is probably as good as you can get, as mVChr says, try..catch is just lazy here. It's probably far less effient and has nothing to recommend it other than perhaps being easier to type (but not significantly so) and it'll be harder to debug as it silently hides errors.

The real issue is the very long "reference worm" created by attempting such access. An alternative to the original that at least reduces the number of property lookups is:

```<code>var o;
if ( (o = entry       ) &&
     (o = o.mediaGroup) &&
     (o = o[0]        ) &&
     (o = o.contents  ) &&
     (o = o[0]        )) {
  alert(o.url);
}
</code>```

But I expect you won't like that.

If you have many such deep access paths, you might like to create a function to do the access and return the last object on success or some other vaule on failure. For failure, you could also have it return the last non-falsey object on the path.

```<code>// Create test object
var entry = {};
entry.mediaGroup = [{
  contents: [{url: 'url'}]
}];

// Check that it "works"
// alert(entry.mediaGroup[0].contents[0].url);

// Deep property access function, returns last object
// or false
function deepAccess(obj) {

  var path = arguments;
  var i = 0, iLen = path.length;
  var o = path[i++];  // o is first arg
  var p = path[i++];  // p is second arg

  // Go along path until o[p] is falsey
  while (o[p]) {
    o = o[p];
    p = path[i++];
  }

  // Return false if didn't get all the way along
  // the path or the last non-falsey value referenced
  return (--i == iLen) && o;
}

// Test it
var x = deepAccess(entry, 'mediaGroup','0','contents','0');
alert(x && x.url);  // url

var x = deepAccess(entry, 'mediaGroup','1','contents','0');
alert(x && x.url);  // false
</code>```

Body:
In javascript, lets say I want to access a property deep in an object, for example:

entry.mediaGroup[0].contents[0].url

At any point along that structure, a property may be undefined (so mediaGroup may not be set).

What is a simple way to say:

if( entry.mediaGroup[0].contents[0].url ){
   console.log( entry.mediaGroup[0].contents[0].url )
}

without generating an error? This way will generate an undefined error if any point along the way is undefined.

My solution

if(entry) && (entry.mediaGroup) && (entry.MediaGroup[0]) ...snip...){
   console.log(entry.mediaGroup[0].contents[0].url)
}

which is pretty lengthy. I am guessing there must be something more elegant.

Body:
Your current solution is probably as good as you can get, as mVChr says, try..catch is just lazy here. It's probably far less effient and has nothing to recommend it other than perhaps being easier to type (but not significantly so) and it'll be harder to debug as it silently hides errors.

The real issue is the very long "reference worm" created by attempting such access. An alternative to the original that at least reduces the number of property lookups is:

var o;
if ( (o = entry       ) &&
     (o = o.mediaGroup) &&
     (o = o[0]        ) &&
     (o = o.contents  ) &&
     (o = o[0]        )) {
  alert(o.url);
}

But I expect you won't like that.

If you have many such deep access paths, you might like to create a function to do the access and return the last object on success or some other vaule on failure. For failure, you could also have it return the last non-falsey object on the path.

// Create test object
var entry = {};
entry.mediaGroup = [{
  contents: [{url: 'url'}]
}];

// Check that it "works"
// alert(entry.mediaGroup[0].contents[0].url);

// Deep property access function, returns last object
// or false
function deepAccess(obj) {

  var path = arguments;
  var i = 0, iLen = path.length;
  var o = path[i++];  // o is first arg
  var p = path[i++];  // p is second arg

  // Go along path until o[p] is falsey
  while (o[p]) {
    o = o[p];
    p = path[i++];
  }

  // Return false if didn't get all the way along
  // the path or the last non-falsey value referenced
  return (--i == iLen) && o;
}

// Test it
var x = deepAccess(entry, 'mediaGroup','0','contents','0');
alert(x && x.url);  // url

var x = deepAccess(entry, 'mediaGroup','1','contents','0');
alert(x && x.url);  // false


问:
How to properly use a binding in C#
I want to bind the background of a WPF Rectangle to the Brush property of another element.

The initialization looks like this:

```<code>MazeElement nextElement = new MazeElement();
nextElement.Position = new Point(xIndex, yIndex);
nextElement.BackgroundColor = Brushes.Aqua;
MazeElements.Add(nextElement);

Binding bg = new Binding {Source = MazeElements[Index(xIndex, yIndex)]};

Rectangle nextRect = new Rectangle();
nextRect.Height = MazeGridSize;
nextRect.Width = MazeGridSize;
nextRect.Fill = Brushes.White;
nextRect.Stroke = Brushes.Gray;
nextRect.StrokeThickness = 2;

nextRect.SetBinding(Shape.FillProperty, bg);

temp.Children.Add(nextRect);
Canvas.SetLeft(nextRect, xIndex * MazeGridSize);
Canvas.SetTop(nextRect, yIndex * MazeGridSize);
</code>```

Where is my mistake? I don't understand how to use the Binding from the C# side.

答:
First, you are not providing us with enough information. We cannot see the full nature of the type MazeElement. But I assume that the BackgroundColor is a Property on the MazeElement class

Second, the binding has a Source, an object in your case nextElement, and the a PropertyPath, in your case the BackgroundColor. Therefore your binding object should be:

```<code>Binding bg = new Binding {Source = nextElement, Path = new PropertyPath("BackgroundColor") };
</code>```

In your case the source property is of the same type as the target dependency property, so the above will do what you want. If it was not the case, you can set a converter on the binding - Look that up, if you need that in another situation

Title: How to properly use a binding in C#

Body:
I want to bind the background of a WPF Rectangle to the Brush property of another element.

The initialization looks like this:

MazeElement nextElement = new MazeElement();
nextElement.Position = new Point(xIndex, yIndex);
nextElement.BackgroundColor = Brushes.Aqua;
MazeElements.Add(nextElement);

Binding bg = new Binding {Source = MazeElements[Index(xIndex, yIndex)]};

Rectangle nextRect = new Rectangle();
nextRect.Height = MazeGridSize;
nextRect.Width = MazeGridSize;
nextRect.Fill = Brushes.White;
nextRect.Stroke = Brushes.Gray;
nextRect.StrokeThickness = 2;

nextRect.SetBinding(Shape.FillProperty, bg);

temp.Children.Add(nextRect);
Canvas.SetLeft(nextRect, xIndex * MazeGridSize);
Canvas.SetTop(nextRect, yIndex * MazeGridSize);

Where is my mistake? I don't understand how to use the Binding from the C# side.

Body:
First, you are not providing us with enough information. We cannot see the full nature of the type MazeElement. But I assume that the BackgroundColor is a Property on the MazeElement class

Second, the binding has a Source, an object in your case nextElement, and the a PropertyPath, in your case the BackgroundColor. Therefore your binding object should be:

Binding bg = new Binding {Source = nextElement, Path = new PropertyPath("BackgroundColor") };

In your case the source property is of the same type as the target dependency property, so the above will do what you want. If it was not the case, you can set a converter on the binding - Look that up, if you need that in another situation


问:
keep connected on multiple pages
I'm having trouble leaving a user account connected on multiple pages, what I want to do is that when the user authenticates, he is redirected to another page with the data loaded, but I can't do that, the data they are not uploaded to other pages.

data is not loaded:

my code js:

```<code>var authEmailPassButton = document.getElementById('authEmailPassButton')
var logOutButton = document.getElementById('logOutButton')
var emailInput = document.getElementById('emailInput')
var passwordInput = document.getElementById('passwordInput')

authEmailPassButton.addEventListener('click', function(){
    firebase
    .auth()
    .signInWithEmailAndPassword(emailInput.value, passwordInput.value)
    .then(function(result){
        console.log(result)
        alert('Welcome')
    })
.catch(function (error){
    console.error(error.code)
    console.error(erro.message)
    alert('Failed to authenticate, check the console for the error!')
})
})

firebase.auth().onAuthStateChanged(function(user){
if (user) {

    var user = firebase.auth().currentUser;

     if (user != null) {
        var email = user.email;
        var emailVerified = user.emailVerified;
        var uid = user.uid
        displayName.innerText = 'Welcome, ' + email
        window.location = 'home.html'
    }

} else {
    console.log('Not connected')
}
})

 logOutButton.addEventListener('click', function(){
firebase
.auth().signOut()
.then(function (){
        alert('You disconnected')
}, function(error){
        console.error(error)
    })
})
</code>```

my code html:

    <title>Firebase</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta http-equiv="Content-Type" content="text/html"; charset="utf-8">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="/css/style.css">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

        Home
        News
        profile setting
        Form

You are not authenticated

```

I don't know why this is happening!

答:
Browser don't maintain any state between pages they display. Firebase however will try to restore the user's authentication state when it loads a new page from the same domain.

If you want each page in a multi-page application to know about the signed in user, you will need to add an onAuthStateChanged listener to each page.

The listener you have looks like it should work fine on other pages too, although I'd simplify it a bit to:

```<code>firebase.auth().onAuthStateChanged(function(user){
  if (user) {
    var email = user.email;
    displayName.innerText = 'Welcome, ' + email
    ...
  } else {
    console.log('Not signed in')
  }
})
</code>```

Title: keep connected on multiple pages

Body:
I'm having trouble leaving a user account connected on multiple pages, what I want to do is that when the user authenticates, he is redirected to another page with the data loaded, but I can't do that, the data they are not uploaded to other pages.

data is not loaded:

my code js:

var authEmailPassButton = document.getElementById('authEmailPassButton')
var logOutButton = document.getElementById('logOutButton')
var emailInput = document.getElementById('emailInput')
var passwordInput = document.getElementById('passwordInput')

authEmailPassButton.addEventListener('click', function(){
    firebase
    .auth()
    .signInWithEmailAndPassword(emailInput.value, passwordInput.value)
    .then(function(result){
        console.log(result)
        alert('Welcome')
    })
.catch(function (error){
    console.error(error.code)
    console.error(erro.message)
    alert('Failed to authenticate, check the console for the error!')
})
})

firebase.auth().onAuthStateChanged(function(user){
if (user) {

    var user = firebase.auth().currentUser;

     if (user != null) {
        var email = user.email;
        var emailVerified = user.emailVerified;
        var uid = user.uid
        displayName.innerText = 'Welcome, ' + email
        window.location = 'home.html'
    }

} else {
    console.log('Not connected')
}
})

 logOutButton.addEventListener('click', function(){
firebase
.auth().signOut()
.then(function (){
        alert('You disconnected')
}, function(error){
        console.error(error)
    })
})

my code html:

    <title>Firebase</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta http-equiv="Content-Type" content="text/html"; charset="utf-8">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="/css/style.css">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

        Home
        News
        profile setting
        Form

You are not authenticated

I don't know why this is happening!

Body:
Browser don't maintain any state between pages they display. Firebase however will try to restore the user's authentication state when it loads a new page from the same domain.

If you want each page in a multi-page application to know about the signed in user, you will need to add an onAuthStateChanged listener to each page.

The listener you have looks like it should work fine on other pages too, although I'd simplify it a bit to:

firebase.auth().onAuthStateChanged(function(user){
  if (user) {
    var email = user.email;
    displayName.innerText = 'Welcome, ' + email
    ...
  } else {
    console.log('Not signed in')
  }
})


问:
How can I get the content of a Windows 10 ?Notification in a UWP/C#?
I'm trying to get the text inside user notifications, and the action that occurs if you click the notification. I get the user's permission to read them (using UserNotificationListener.RequestAccessAsync()), and then I iterate over them, and add them to a ListView:

```<code>private async void getNotificationsAsync()
{
    UserNotificationListener listener = UserNotificationListener.Current;
    IReadOnlyList<UserNotification> notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast);
    NotificationsList.Items.Clear();
    foreach (UserNotification notif in notifs)
    {
        //Console.WriteLine(notif.AppInfo.DisplayInfo.DisplayName);
        NotificationsList.Items.Add(notif.AppInfo.DisplayInfo.DisplayName);
    }
}
</code>```

But all I can get from the UserNotification class is the initiating application's name (and the time the notification occured). I can't find any way to access the content of the notification in the UserNotification class.

Is what I'm trying possible? Am I using the right class?

答:
Found it! (always happens after I ask the question ). For posterity's sake, here's the answer:

```<code>NotificationBinding toastBinding = notif.Notification.Visual.GetBinding(KnownNotificationBindings.ToastGeneric);

if (toastBinding != null)
{
    // And then get the text elements from the toast binding
    IReadOnlyList<AdaptiveNotificationText> textElements = toastBinding.GetTextElements();

    // Treat the first text element as the title text
    string titleText = textElements.FirstOrDefault()?.Text;

    // We'll treat all subsequent text elements as body text,
    // joining them together via newlines.
    string bodyText = string.Join("\n", textElements.Skip(1).Select(t => t.Text));
}
</code>```

Body:
I'm trying to get the text inside user notifications, and the action that occurs if you click the notification. I get the user's permission to read them (using UserNotificationListener.RequestAccessAsync()), and then I iterate over them, and add them to a ListView:

private async void getNotificationsAsync()
{
    UserNotificationListener listener = UserNotificationListener.Current;
    IReadOnlyList<UserNotification> notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast);
    NotificationsList.Items.Clear();
    foreach (UserNotification notif in notifs)
    {
        //Console.WriteLine(notif.AppInfo.DisplayInfo.DisplayName);
        NotificationsList.Items.Add(notif.AppInfo.DisplayInfo.DisplayName);
    }
}

But all I can get from the UserNotification class is the initiating application's name (and the time the notification occured). I can't find any way to access the content of the notification in the UserNotification class.

Is what I'm trying possible? Am I using the right class?

Body:
Found it! (always happens after I ask the question ). For posterity's sake, here's the answer:

NotificationBinding toastBinding = notif.Notification.Visual.GetBinding(KnownNotificationBindings.ToastGeneric);

if (toastBinding != null)
{
    // And then get the text elements from the toast binding
    IReadOnlyList<AdaptiveNotificationText> textElements = toastBinding.GetTextElements();

    // Treat the first text element as the title text
    string titleText = textElements.FirstOrDefault()?.Text;

    // We'll treat all subsequent text elements as body text,
    // joining them together via newlines.
    string bodyText = string.Join("\n", textElements.Skip(1).Select(t => t.Text));
}


问:
Flyway not finding my sql migrations in db/migration
The error:
[ERROR] com.googlecode.flyway.core.api.FlywayException: Unable to determine URL for classpath location: db/migration (ClassLoader: ClassRealm[plugin>com.googlecode.flyway:flyway-maven-plugin:2.1.1, parent: sun.misc.Launcher$AppClassLoader@43be2d65])

I followed the quickstart, so I'm not really doing anything complex yet.

pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.cpt.migrations</groupId>
  <artifactId>cpt_migrations</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>cpt_migrations</name>
  <url>http://maven.apache.org</url>

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

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.24</version>
    </dependency>
  </dependencies>
  <build>
      <plugins>
          <plugin>
              <groupId>com.googlecode.flyway</groupId>
              <artifactId>flyway-maven-plugin</artifactId>
              <version>2.1.1</version>
              <configuration>
                  <user>root</user>
                  <password></password>
                  <driver>com.mysql.jdbc.Driver</driver>
                  <url>jdbc:mysql://localhost:3306/cpt</url>
              </configuration>
          </plugin>
      </plugins>
  </build>
</project>
</code>```

And my folder structure is the prescribed PROJECT_ROOT/src/main/resources/db/migration/V1__Base_version.sql:

I get the error when, from the PROJECT_ROOT, I execute:
mvn flyway:migrate

答:
in my case this error was caused as package with name db.migration was created
instead of db -> migration

Body:
The error:
[ERROR] com.googlecode.flyway.core.api.FlywayException: Unable to determine URL for classpath location: db/migration (ClassLoader: ClassRealm[plugin>com.googlecode.flyway:flyway-maven-plugin:2.1.1, parent: sun.misc.Launcher$AppClassLoader@43be2d65])

I followed the quickstart, so I'm not really doing anything complex yet.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.cpt.migrations</groupId>
  <artifactId>cpt_migrations</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>cpt_migrations</name>
  <url>http://maven.apache.org</url>

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

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.24</version>
    </dependency>
  </dependencies>
  <build>
      <plugins>
          <plugin>
              <groupId>com.googlecode.flyway</groupId>
              <artifactId>flyway-maven-plugin</artifactId>
              <version>2.1.1</version>
              <configuration>
                  <user>root</user>
                  <password></password>
                  <driver>com.mysql.jdbc.Driver</driver>
                  <url>jdbc:mysql://localhost:3306/cpt</url>
              </configuration>
          </plugin>
      </plugins>
  </build>
</project>

And my folder structure is the prescribed PROJECT_ROOT/src/main/resources/db/migration/V1__Base_version.sql:

I get the error when, from the PROJECT_ROOT, I execute:
mvn flyway:migrate


问:
what is the difference between 'transform' and 'fit_transform' in sklearn
In the sklearn-python toolbox, there are two functions transform and fit_transform about sklearn.decomposition.RandomizedPCA. The description of two functions are as follows

But what is the difference between them ?

答:
In layman's terms, fit_transform means to do some calculation and then do transformation (say calculating the means of columns from some data and then replacing the missing values). So for training set, you need to both calculate and do transformation.

But for testing set, Machine learning applies prediction based on what was learned during the training set and so it doesn't need to calculate, it just performs the transformation.


问:
JavascriptException: Message: javascript error: arguments[0].click is not a function error using arguments[0].click through Selenium and Python
I have been webscraping some websites to grab there locations for webscraping practice. This code gets me down to individual city levels of a hotel brand, but whenever I use driver.execute_script("arguments[0].click();", button) in my code (as seen in the second to last line) I get this error:

```<code>JavascriptException: Message: javascript error: arguments[0].click is not a function
</code>```

Below is a sample of the code that I have written thus far.

```<code>for state in state_links:
driver = Chrome(path_to_chrome_driver)
link = 'https://www.ihg.com/destinations/us/en/united-states/' + state.lower().replace(' ', '-')
driver.get(link)
city_links = driver.find_elements_by_xpath('//div[@class="countryListingContainer col-xs-12"]//ul//div//li//a//span')
city_links = [thing.text for thing in city_links]
driver.close()
for city in city_links:
    driver = Chrome(path_to_chrome_driver)
    link2 = 'https://www.ihg.com/destinations/us/en/united-states/' + state.lower().replace(' hotels', '').replace(' ', '-') + '/' + city.lower().replace(' ', '-')
    driver.get(link2)
    hotel_links = driver.find_elements_by_xpath('//div[@class="hotelList-detailsContainer"]//div//div//p//a')
    hotel_links = [elem.text for elem in hotel_links]
    driver.close()
    for hotel in hotel_links:
        driver = Chrome(path_to_chrome_driver)
        driver.get(link2)
        driver.implicitly_wait(15)
        driver.execute_script("arguments[0].click();", hotel)
        driver.implicitly_wait(10)
</code>```

答:
This error message...

```<code>JavascriptException: Message: javascript error: arguments[0].click is not a function
</code>```

...implies that invoking click() on arguments[0] using execute_script() failed.

A bit of more information about the steps would have helped us to construct a canonical answer. However, presumably as you are collecting the hotel_links just after:

```<code>driver.get(link2)
hotel_links = driver.find_elements_by_xpath('//div[@class="hotelList-detailsContainer"]//div//div//p//a')
</code>```

So initially, hotel_links contains the WebElements. But in the next line you are overwriting the List hotel_links with the elem.text as follows:

```<code>hotel_links = [elem.text for elem in hotel_links]
</code>```

So, hotel_links now contains elements of type text.

As text element doesn't support click(), hence moving forward when you try to invoke click() on the text elements through execute_script(), you see the said error.

Solution

If you need the text of the hotel links, store them in a seperate List asfollows:

```<code>hotel_links_text = [elem.text for elem in hotel_links]
</code>```

Reference

You can find a couple of relevant discussions in:

What does arguments[0] and arguments[1] mean when using executeScript method from JavascriptExecutor interface through Selenium WebDriver?

Body:
I have been webscraping some websites to grab there locations for webscraping practice. This code gets me down to individual city levels of a hotel brand, but whenever I use driver.execute_script("arguments[0].click();", button) in my code (as seen in the second to last line) I get this error:

JavascriptException: Message: javascript error: arguments[0].click is not a function

Below is a sample of the code that I have written thus far.

for state in state_links:
driver = Chrome(path_to_chrome_driver)
link = 'https://www.ihg.com/destinations/us/en/united-states/' + state.lower().replace(' ', '-')
driver.get(link)
city_links = driver.find_elements_by_xpath('//div[@class="countryListingContainer col-xs-12"]//ul//div//li//a//span')
city_links = [thing.text for thing in city_links]
driver.close()
for city in city_links:
    driver = Chrome(path_to_chrome_driver)
    link2 = 'https://www.ihg.com/destinations/us/en/united-states/' + state.lower().replace(' hotels', '').replace(' ', '-') + '/' + city.lower().replace(' ', '-')
    driver.get(link2)
    hotel_links = driver.find_elements_by_xpath('//div[@class="hotelList-detailsContainer"]//div//div//p//a')
    hotel_links = [elem.text for elem in hotel_links]
    driver.close()
    for hotel in hotel_links:
        driver = Chrome(path_to_chrome_driver)
        driver.get(link2)
        driver.implicitly_wait(15)
        driver.execute_script("arguments[0].click();", hotel)
        driver.implicitly_wait(10)

Body:
This error message...

JavascriptException: Message: javascript error: arguments[0].click is not a function

...implies that invoking click() on arguments[0] using execute_script() failed.

A bit of more information about the steps would have helped us to construct a canonical answer. However, presumably as you are collecting the hotel_links just after:

driver.get(link2)
hotel_links = driver.find_elements_by_xpath('//div[@class="hotelList-detailsContainer"]//div//div//p//a')

So initially, hotel_links contains the WebElements. But in the next line you are overwriting the List hotel_links with the elem.text as follows:

hotel_links = [elem.text for elem in hotel_links]

So, hotel_links now contains elements of type text.

As text element doesn't support click(), hence moving forward when you try to invoke click() on the text elements through execute_script(), you see the said error.

Solution

If you need the text of the hotel links, store them in a seperate List asfollows:

hotel_links_text = [elem.text for elem in hotel_links]

Reference

You can find a couple of relevant discussions in:

What does arguments[0] and arguments[1] mean when using executeScript method from JavascriptExecutor interface through Selenium WebDriver?


问:
Using a primary key within a form view (Django)
I have a form that is associated with a model, and want to specify the form data using the model's PK to log the response.

However, when I do this, I get the error: QuestionRecordSubmitView() got an unexpected keyword argument 'pk'

urls.py

```<code>    path('survey/<int:pk>/record_submit_question/', views.QuestionRecordSubmitView, name='survey-question-submit-record')
</code>```

views.py

```<code>def QuestionRecordSubmitView(request):
model = Question

if request.method == 'POST':
    form = PostAudio(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse('survey-share', kwargs={"pk": form.question}))
else:
    form = PostAudio()
return render(request, 'survey/question_audio_submit.html')
</code>```

models.py

```<code>class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    response_file = models.FileField(blank=True, upload_to='audio_responses')

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
</code>```

forms.py

```<code>class PostAudio(forms.ModelForm):
    class Meta:
        model = Choice
        fields = ('response_file',)
</code>```

答:
The view should accept a pk parameter, the primary key that is captured from the path. Furthermore, you should specify the question_id of the instance:

```<code>from django.shortcuts import redirect

def QuestionRecordSubmitView(request<b>, pk</b>):
    if request.method == 'POST':
        form = PostAudio(request.POST, request.FILES)
        if form.is_valid():
            <b>form.instance.question_id = pk</b>
            form.save()
            return redirect('survey-share', pk=pk)
    else:
        form = PostAudio()
    return render(request, 'survey/question_audio_submit.html')</code>```

Body:
I have a form that is associated with a model, and want to specify the form data using the model's PK to log the response.

However, when I do this, I get the error: QuestionRecordSubmitView() got an unexpected keyword argument 'pk'

urls.py

    path('survey/<int:pk>/record_submit_question/', views.QuestionRecordSubmitView, name='survey-question-submit-record')

views.py

def QuestionRecordSubmitView(request):
model = Question

if request.method == 'POST':
    form = PostAudio(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse('survey-share', kwargs={"pk": form.question}))
else:
    form = PostAudio()
return render(request, 'survey/question_audio_submit.html')

models.py

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    response_file = models.FileField(blank=True, upload_to='audio_responses')

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

forms.py

class PostAudio(forms.ModelForm):
    class Meta:
        model = Choice
        fields = ('response_file',)

Body:
The view should accept a pk parameter, the primary key that is captured from the path. Furthermore, you should specify the question_id of the instance:

from django.shortcuts import redirect

def QuestionRecordSubmitView(request, pk):
    if request.method == 'POST':
        form = PostAudio(request.POST, request.FILES)
        if form.is_valid():
            form.instance.question_id = pk
            form.save()
            return redirect('survey-share', pk=pk)
    else:
        form = PostAudio()
    return render(request, 'survey/question_audio_submit.html')


问:
How to use a UICollectionViewCell in a UITableView?
I have a cell originally created as a UICollectionViewCell but I want to be able to reuse it in a UITableView. Would I simply have to reimplement it in the form of a UITableView or is there any alternative?

The UITableView needs to present the exact same cell as well, but it can't because of the lack of cross-compatibility. My original cell is declared as such and uses a NIB file for the UI layout:

```<code>class originalCollectionViewCell: UICollectionViewCell {
    //parent view that nests several other views
    @IBOutlet weak var viewBackground: UIView!

    override func awakeFromNib() {
        ...
    }
}
</code>```

答: If I'm understanding the question correctly, I'd recommend creating a subclass of UIView and move the subviews that are currently in your collection view cell into this subclass. Then use this subview as the contentView of both your collection view cell and table view cell.

Body:
I have a cell originally created as a UICollectionViewCell but I want to be able to reuse it in a UITableView. Would I simply have to reimplement it in the form of a UITableView or is there any alternative?

The UITableView needs to present the exact same cell as well, but it can't because of the lack of cross-compatibility. My original cell is declared as such and uses a NIB file for the UI layout:

class originalCollectionViewCell: UICollectionViewCell {
    //parent view that nests several other views
    @IBOutlet weak var viewBackground: UIView!

    override func awakeFromNib() {
        ...
    }
}