问:
Displaying rows dynamically
i want to show all the records which are in ms access database,but it displays only one record...
I have the following code

```<code>private void Form1_Load(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
        con.Open();
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        string sql = "SELECT * From tblCompany";

        da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
        da.Fill(ds);
        DataRow dr = ds.Tables[0].Rows[0];
        int cnt = ds.Tables[0].Rows.Count;
        textBox1.Text = cnt.ToString();
        for (int i = 0; i < cnt; i++)
        {
            dataGridView1.Rows[i].Cells[0].Value = dr.ItemArray.GetValue(1).ToString();
            dataGridView1.Rows[i].Cells[1].Value = dr.ItemArray.GetValue(2).ToString();
        }

    }
</code>```

how can i display all the records from the ms access database,in my DataGridView?

答:
If you want to access rows and columns in the gridview directly, you have to create them

```<code> dataGridView1.Columns.Add("c1", "c1");
 dataGridView1.Columns.Add("c2", "c2");
 dataGridView1.Rows.Add(10);
</code>```

will add 10 empty rows with 2 columns in the grid, then you can fill them in with values.

Alternativly you can bind your dataset to the control

```<code> dataGridView1.DataSource = ds.Tables[0]
</code>```

will display your table with autogenerated columns , without having to setup the gridview.

Title: Displaying rows dynamically

Body:
i want to show all the records which are in ms access database,but it displays only one record...
I have the following code

private void Form1_Load(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
        con.Open();
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        string sql = "SELECT * From tblCompany";

        da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
        da.Fill(ds);
        DataRow dr = ds.Tables[0].Rows[0];
        int cnt = ds.Tables[0].Rows.Count;
        textBox1.Text = cnt.ToString();
        for (int i = 0; i < cnt; i++)
        {
            dataGridView1.Rows[i].Cells[0].Value = dr.ItemArray.GetValue(1).ToString();
            dataGridView1.Rows[i].Cells[1].Value = dr.ItemArray.GetValue(2).ToString();
        }

    }

how can i display all the records from the ms access database,in my DataGridView?

Body:
If you want to access rows and columns in the gridview directly, you have to create them

 dataGridView1.Columns.Add("c1", "c1");
 dataGridView1.Columns.Add("c2", "c2");
 dataGridView1.Rows.Add(10);

will add 10 empty rows with 2 columns in the grid, then you can fill them in with values.

Alternativly you can bind your dataset to the control

 dataGridView1.DataSource = ds.Tables[0]

will display your table with autogenerated columns , without having to setup the gridview.


来源: stackexchange

问:
PHP - Output array value that contains a specific text marker
I'm using a function to output a collection of products in Shopify, onto a WordPress page.

I've got most of the data displaying correctly, except a custom value that is entered as a tag in Shopify. Using the api, I'm then trying to get this specific tag for the product subtitle which is formatted with att:Subtitle: before each product custom value/text.

This is the code I have got to (I've commented other unsuccessful attempts in the middle) - this is inside the overall code to show the 4 products in the Shopify collection:

```<code> // Using tags to output custom data from products
$tags = $current_product['tags'];

// $tags is a string, this turns the values into an array
$product_tags = explode(',', $tags);

// Evaluate if there is a string with att:Subtitle in the product tags
// https://tecadmin.net/check-string-contains-substring-in-php/
$subtitle_attribute_key = "att:Subtitle:";

if (strpos($tags, 'att:Subtitle:') !== false) {
    // Returns a numbered value corresponding to my subtitle attribute
    // $key = array_search($subtitle_attribute_key, $product_tags);
    $sub = strpos($tags, $subtitle_attribute_key);

    // Turns the numbered value into a text value
    // $numArray = explode(" ", $sub);
    // var_dump($numArray);
    $value = print_r($sub, true);
    // $value = array_search("att:Subtitle:",$product_tabs);
    // $value = array_search("att:Subtitle:", $tabs); // Warning: array_search() expects parameter 2 to be array, null given
    // $result = $product_tags['$value']; // my attempt to return the text

    // Remove att:Subtittle: in front of the subtitle value to output the clean final value
    $subtitle = ltrim($value, 'att:Subtitle:');
}
</code>```

So far it comes out as a number value where I'm displaying $subtitle... but I can't figure out how to display the custom text value instead.

Any ideas?

Thanks

EDIT: I am working with products that have multiple tags and I do not control these. Out of the tags I'm trying to find the one that starts with att:Subtitle: but only show the custom value after that marker.

When I echo $tags, the ist comes out something like this:

```<code>att:Benefit:balance, att:Perfect:Combination Skin, att:Size: 1.8 oz, att:Subtitle: Multi-Tasking Product, Key Ingredient 1, Key Ingredient 2, Essentials, meta-related-product-xyz, meta-related-product-brandname
</code>```

They will all have a different list of tags

答:
So for what I understand you're trying to get rid of 'att:Subtitle:' from the tags on your products descriptions? maybe you should try replacing that value on your tags array</p>

```<code>// Using tags to output custom data from products
$tags = $current_product['tags'];

// $tags is a string, this turns the values into an array
$product_tags = explode(',', $tags);

// Get rid of attribute on product tag
for($i = 0; $i < count($product_tags); $i++){
    $subtitle = str_replace(':att:Subtitle','',$product_tags[i]);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using a function to output a collection of products in Shopify, onto a WordPress page.

I've got most of the data displaying correctly, except a custom value that is entered as a tag in Shopify. Using the api, I'm then trying to get this specific tag for the product subtitle which is formatted with att:Subtitle: before each product custom value/text.

This is the code I have got to (I've commented other unsuccessful attempts in the middle) - this is inside the overall code to show the 4 products in the Shopify collection:

 // Using tags to output custom data from products
$tags = $current_product['tags'];

// $tags is a string, this turns the values into an array
$product_tags = explode(',', $tags);

// Evaluate if there is a string with att:Subtitle in the product tags
// https://tecadmin.net/check-string-contains-substring-in-php/
$subtitle_attribute_key = "att:Subtitle:";

if (strpos($tags, 'att:Subtitle:') !== false) {
    // Returns a numbered value corresponding to my subtitle attribute
    // $key = array_search($subtitle_attribute_key, $product_tags);
    $sub = strpos($tags, $subtitle_attribute_key);

    // Turns the numbered value into a text value
    // $numArray = explode(" ", $sub);
    // var_dump($numArray);
    $value = print_r($sub, true);
    // $value = array_search("att:Subtitle:",$product_tabs);
    // $value = array_search("att:Subtitle:", $tabs); // Warning: array_search() expects parameter 2 to be array, null given
    // $result = $product_tags['$value']; // my attempt to return the text

    // Remove att:Subtittle: in front of the subtitle value to output the clean final value
    $subtitle = ltrim($value, 'att:Subtitle:');
}

So far it comes out as a number value where I'm displaying $subtitle... but I can't figure out how to display the custom text value instead.

Any ideas?

Thanks

EDIT: I am working with products that have multiple tags and I do not control these. Out of the tags I'm trying to find the one that starts with att:Subtitle: but only show the custom value after that marker.

When I echo $tags, the ist comes out something like this:

att:Benefit:balance, att:Perfect:Combination Skin, att:Size: 1.8 oz, att:Subtitle: Multi-Tasking Product, Key Ingredient 1, Key Ingredient 2, Essentials, meta-related-product-xyz, meta-related-product-brandname

They will all have a different list of tags

Body:
So for what I understand you're trying to get rid of 'att:Subtitle:' from the tags on your products descriptions? maybe you should try replacing that value on your tags array

// Using tags to output custom data from products
$tags = $current_product['tags'];

// $tags is a string, this turns the values into an array
$product_tags = explode(',', $tags);

// Get rid of attribute on product tag
for($i = 0; $i < count($product_tags); $i++){
    $subtitle = str_replace(':att:Subtitle','',$product_tags[i]);
}


问:
mariabackup restoring a single database without affecting other tables
I'm currently using MariaDB 10.3.17 on CentOS 8 and I'm trying to restore a backup of a specific database. I made 2 dummy databases named test and test_restore. I updated test_restore then created an incremental backup with --databases="mysql test_restore"

I ran:

```<code># mariabackup --prepare --target-dir=<dir>/mariadb/backup/2020-02/18_10h_full/

# mariabackup --prepare --target-dir=<dir>/mariadb/backup/2020-02/18_10h_full/ --incremental-dir=<dir>/mariadb/backup/2020-02/18_10h10m_inc/

# mariabackup --copy-back --target-dir=<dir>/mariadb/backup/2020-02/18_10h_full/
</code>```

After that, I lost all data on my test db but kept my updated test_restore db

I can do a full backup and restore with the incremental back up of ALL databases altogether but thats gonna take a long time.

答: I might be wrong, but MariaDB's blog article How to Restore a Single Database from MariaDB Backup seems very suitable here. I'm linking it, because it doesn't make sense to me to simply copy all of the instructions and hints.</p>

Body:
I'm currently using MariaDB 10.3.17 on CentOS 8 and I'm trying to restore a backup of a specific database. I made 2 dummy databases named test and test_restore. I updated test_restore then created an incremental backup with --databases="mysql test_restore"

I ran:

# mariabackup --prepare --target-dir=<dir>/mariadb/backup/2020-02/18_10h_full/

# mariabackup --prepare --target-dir=<dir>/mariadb/backup/2020-02/18_10h_full/ --incremental-dir=<dir>/mariadb/backup/2020-02/18_10h10m_inc/

# mariabackup --copy-back --target-dir=<dir>/mariadb/backup/2020-02/18_10h_full/

After that, I lost all data on my test db but kept my updated test_restore db

I can do a full backup and restore with the incremental back up of ALL databases altogether but thats gonna take a long time.


答:
Of course it comes out as a number. You're getting a number from the strpos() and ultimate trying to run ltrim() on it.

If you're expecting the desired text to be in $tags immediately following 'att:Subtitle:' and have nothing else in that string, $subtitle = substr($tags, strpos('att:Subtitle:') + strlen('att:Subtitle:')); should give it to you. If you're expecting it to possibly be an element in the $product_tags array, need to loop (I'm assuming it shows up once, at most):

```<code>foreach ($product_tags as $product_tag) {
    if (strpos($product_tag, 'att:Subtitle:') !== false) {
        $subtitle = substr($product_tag, strpos($product_tag, 'att:Subtitle:') + strlen('att:Subtitle:'));
        break;
    }
}
</code>```

Title: PHP - Output array value that contains a specific text marker

Body:
Of course it comes out as a number. You're getting a number from the strpos() and ultimate trying to run ltrim() on it.

If you're expecting the desired text to be in $tags immediately following 'att:Subtitle:' and have nothing else in that string, $subtitle = substr($tags, strpos('att:Subtitle:') + strlen('att:Subtitle:')); should give it to you. If you're expecting it to possibly be an element in the $product_tags array, need to loop (I'm assuming it shows up once, at most):

foreach ($product_tags as $product_tag) {
    if (strpos($product_tag, 'att:Subtitle:') !== false) {
        $subtitle = substr($product_tag, strpos($product_tag, 'att:Subtitle:') + strlen('att:Subtitle:'));
        break;
    }
}


问:
AWS STS to list buckets gives access denied
I have a bucket with empty bucket policy, block public access turned ON (ACLs and Bucket) and trying to list buckets using IAM policy tied to user using STS AssumeRole with following attached policy.

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:GetObject",
                "s3:GetBucket*",
                "s3:ListBucket*",
                "s3:ListAllMyBuckets"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::my-test-bucket/*"
            ]
        }
    ]
}
</code>```

The assumed role credentials are used during the STS session in python (boto3)

s3c = boto3.client('s3',
  aws_access_key_id=credentials['AccessKeyId'],
  aws_secret_access_key=credentials['SecretAccessKey'],
  aws_session_token=credentials['SessionToken'])

s3c.list_buckets()
```

I get this exception:

botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied

When I tried to use IAM Policy simulator, it indicates "Implicitly denied". Im thinking if I need to access a bucket policy for this user? My understanding has been if both IAM and Bucket policy, it is an intersection. If either is not present, the other takes precedence.

答:
This is a pretty common issue because people tend to miss the difference between a "bucket" resource and an "object" resource. A bucket ends in the name of the bucket (arn:aws:s3:::my-test-bucket) whereas an object includes the bucket and key, and is often granted with a star after the initial slash. So, just change your policy to the following.

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:ListAllMyBuckets"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::my-test-bucket"
            ]
        },
        {
            "Action": [
                "s3:GetObject",
                "s3:GetBucket*",
                "s3:ListBucket*"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::my-test-bucket/*"
            ]
        }
    ]
}
</code>```

Body:
I have a bucket with empty bucket policy, block public access turned ON (ACLs and Bucket) and trying to list buckets using IAM policy tied to user using STS AssumeRole with following attached policy.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:GetObject",
                "s3:GetBucket*",
                "s3:ListBucket*",
                "s3:ListAllMyBuckets"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::my-test-bucket/*"
            ]
        }
    ]
}

The assumed role credentials are used during the STS session in python (boto3)

s3c = boto3.client('s3',
  aws_access_key_id=credentials['AccessKeyId'],
  aws_secret_access_key=credentials['SecretAccessKey'],
  aws_session_token=credentials['SessionToken'])

s3c.list_buckets()

I get this exception:

botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied

When I tried to use IAM Policy simulator, it indicates "Implicitly denied". Im thinking if I need to access a bucket policy for this user? My understanding has been if both IAM and Bucket policy, it is an intersection. If either is not present, the other takes precedence.

Body:
This is a pretty common issue because people tend to miss the difference between a "bucket" resource and an "object" resource. A bucket ends in the name of the bucket (arn:aws:s3:::my-test-bucket) whereas an object includes the bucket and key, and is often granted with a star after the initial slash. So, just change your policy to the following.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:ListAllMyBuckets"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::my-test-bucket"
            ]
        },
        {
            "Action": [
                "s3:GetObject",
                "s3:GetBucket*",
                "s3:ListBucket*"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::my-test-bucket/*"
            ]
        }
    ]
}


问:
Recursion function to count how many times a certain sequence appears
I am writing a recursive function that takes an integer as input and it will return the number of times 123 appears in the integer.

So for example:

print(onetwothree(123123999123))

Will print out 3 because the sequence 123 appears 3 times in the number I entered into the function.

Here is my code so far:

```<code>def onetwothree(x):
    count = 0
    while(x > 0):
        x = x//10
        count = count + 1
    if (count < 3):  #here i check if the digits is less than 3, it can't have the sequence 123 if it doesn't have 3 digits
        return 0
    if (x%10==1 and x//10%10 == 2 and x//10//10%10==3):
        counter += 1
    else:
        return(onetwothree(x//10))
</code>```

This keeps printing "0".

答:
I think you are overthinking recursion. A solution like so should work:

def onetwothree(n, count=0):
    if n <= 0:
        return count

    last_three_digits = n % 1000
    n_without_last_number = n // 10

    if last_three_digits == 123:
        return onetwothree(n_without_last_number, count + 1)
    else:
        return onetwothree(n_without_last_number, count)

print(onetwothree(123123999123))
```

<p>Outputs:</p>

```3
```

Body:
I am writing a recursive function that takes an integer as input and it will return the number of times 123 appears in the integer.

So for example:

print(onetwothree(123123999123))

Will print out 3 because the sequence 123 appears 3 times in the number I entered into the function.

Here is my code so far:

def onetwothree(x):
    count = 0
    while(x > 0):
        x = x//10
        count = count + 1
    if (count < 3):  #here i check if the digits is less than 3, it can't have the sequence 123 if it doesn't have 3 digits
        return 0
    if (x%10==1 and x//10%10 == 2 and x//10//10%10==3):
        counter += 1
    else:
        return(onetwothree(x//10))

This keeps printing "0".

Body:
I think you are overthinking recursion. A solution like so should work:

def onetwothree(n, count=0):
    if n <= 0:
        return count

    last_three_digits = n % 1000
    n_without_last_number = n // 10

    if last_three_digits == 123:
        return onetwothree(n_without_last_number, count + 1)
    else:
        return onetwothree(n_without_last_number, count)

print(onetwothree(123123999123))

Outputs:

3


问:
Redux: (Domain data and) App state vs. UI state
From the Redux docs on Basic State Shape:

Most applications deal with multiple types of data, which can be broadly divided into three categories:

Domain data: data that the application needs to show, use, or modify (such as "all of the Todos retrieved from the server")

App state: data that is specific to the application's behavior (such as "Todo #5 is currently selected", or "there is a request in progress to fetch Todos")

UI state: data that represents how the UI is currently displayed (such as "The EditTodo modal dialog is currently open")

The Domain data part is clear to me, but I can still vaguely distinguish between the App state and UI state. The examples given for the App state part: "Todo #5 is currently selected", or "there is a request in progress to fetch Todos", sound pretty much UI state-ish. How are they classified as App state, but not UI state?

答:
I wrote that Redux docs page.  (4 years ago!  wow.  time flies!)

I was trying to give some broad examples as a way to illustrate the concepts, not make strict categorizations.  You could probably make a legit argument that "which todo is selected" is more "UI"-ish than "App"-ish.  On the other hand, I'd say that "current selected todo" is more likely to relate to something else that the app can do, like "delete this todo", "mark this todo as completed", etc, while "the modal is open" is strictly about how the UI is being displayed.


问:
Why doesn't react output anything to the console when input is submited?
This is the react code I'm currently using:

import React, { Component } from 'react'

export class AddProduct extends Component {
    doSomething(){
        console.log('Hello')
    }
    render() {
        return (

Product name

                <input type="text" id="product"></input>

Product price

                <input type="text" id="price"></input>
                <input type="submit" id="submit" value="Submit" onSubmit={(e) => {this.doSomething();}}></input>

        )
    }
}

export default AddProduct
```

I'm expecting a 'Hello' output to the terminal when the submit button is pressed however it does not show up. Could anyone help me out?

答:
In order to handle a submit event, you must use a <form /> element.

Example:

```<code>import React, { Component } from 'react'

class AddProduct extends Component {
    doSomething() {
        console.log('Hello')
    }

    render() {
        return (
            <form onSubmit={(e) => this.doSomething()}>
                <h3>Product name</h3>
                <input type="text" id="product" />
                <h3>Product price</h3>
                <input type="text" id="price" />
                <input type="submit" id="submit" value="Submit" />
            </form>
        );
    }
}

export default AddProduct;
</code>```

See React Form Docs

Body:
This is the react code I'm currently using:

import React, { Component } from 'react'

export class AddProduct extends Component {
    doSomething(){
        console.log('Hello')
    }
    render() {
        return (

Product name

                <input type="text" id="product"></input>

Product price

                <input type="text" id="price"></input>
                <input type="submit" id="submit" value="Submit" onSubmit={(e) => {this.doSomething();}}></input>

        )
    }
}

export default AddProduct

I'm expecting a 'Hello' output to the terminal when the submit button is pressed however it does not show up. Could anyone help me out?

Body:
In order to handle a submit event, you must use a <form /> element.

Example:

import React, { Component } from 'react'

class AddProduct extends Component {
    doSomething() {
        console.log('Hello')
    }

    render() {
        return (
            <form onSubmit={(e) => this.doSomething()}>
                <h3>Product name</h3>
                <input type="text" id="product" />
                <h3>Product price</h3>
                <input type="text" id="price" />
                <input type="submit" id="submit" value="Submit" />
            </form>
        );
    }
}

export default AddProduct;

See React Form Docs


问:
Regular expression to retrieve a string from a multiline file text
I am searching for a way to extract the peer IP by looking for the secret of that peer.

Example:

```<code>peer 1.2.3.10 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordA
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}
peer 1.2.3.20 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordB
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}
peer 1.2.3.30 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordC
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}
</code>```

Provided I know SecrePasswordB, I would need to retrieve the peer IP which is 1.2.3.20, of empty if not found (or anything else easy to identify.

The text comes from a shell command into a variable (ie. TEXT=$(command_string)).

As I only have a basic shell and few tool available on the system that would need to be done with very basic linux tools. And here I am stuck not finding a solution...

答:
Assuming you have a variable TEXT assigned to the whole lines provided
as an example, would you please try:

```<code>secret="SecretPasswordB"        # or assign to your actual string
secret=$(printf %q "$secret")   # escape metacharacters just in case

pat='peer[[:blank:]]+(([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3})[[:blank:]]*\{[^{]+authentication[[:blank:]]*\{[^}]+pre-shared-secret[[:blank:]]+'"$secret"

if [[ $TEXT =~ $pat ]]; then
    echo "${BASH_REMATCH[1]}"
fi
</code>```

Output:

```<code>1.2.3.20
</code>```

Please note that the regex above is tested against the given example only and may not be robust enough for an arbitrary input.

Body:
I am searching for a way to extract the peer IP by looking for the secret of that peer.

Example:

peer 1.2.3.10 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordA
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}
peer 1.2.3.20 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordB
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}
peer 1.2.3.30 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordC
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}

Provided I know SecrePasswordB, I would need to retrieve the peer IP which is 1.2.3.20, of empty if not found (or anything else easy to identify.

The text comes from a shell command into a variable (ie. TEXT=$(command_string)).

As I only have a basic shell and few tool available on the system that would need to be done with very basic linux tools. And here I am stuck not finding a solution...

Body:
Assuming you have a variable TEXT assigned to the whole lines provided
as an example, would you please try:

secret="SecretPasswordB"        # or assign to your actual string
secret=$(printf %q "$secret")   # escape metacharacters just in case

pat='peer[[:blank:]]+(([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3})[[:blank:]]*\{[^{]+authentication[[:blank:]]*\{[^}]+pre-shared-secret[[:blank:]]+'"$secret"

if [[ $TEXT =~ $pat ]]; then
    echo "${BASH_REMATCH[1]}"
fi

Output:

1.2.3.20

Please note that the regex above is tested against the given example only and may not be robust enough for an arbitrary input.


问:
Rerender API's image every N second
Image rerender every N second (user determines value through Slider). Default value=3

Also i want to set initial state for imageUrl, before the component have rendered. How can i do this? And how to handle situation when user didn't connect to the Internet

```<code>const [value, setValue] = useState(3);
const [imgUrl, setImgUrl] = useState();

useEffect(() => {
  const valueCopy = value;
  const timer = setTimeout(() => {
            fetch('https://dog.ceo/api/breeds/image/random')
                .then(responce => responce.json())
                .then(data => {
                    setImgUrl(data.message);
                })
                .catch(err => console.warn(err));
        }, valueCopy * 1000);

   return () => clearTimeout(timer);
});

return (
   <Image style={styles.img} source={{ uri: `${imgUrl}` }} />
   <Text style={styles.valueText}>{value}</Text>
   <Slider value={value} onValueChange={(sliderValue) => setValue(sliderValue)} />

)

</code>```

答:
```<code>export default function App() {
  const [value, setValue] = useState(3);
  const [imgUrl, setImgUrl] = useState();

  const getImage = () =>
    fetch("https://dog.ceo/api/breeds/image/random")
      .then(response => response.json())
      .then(data => {
        setImgUrl(data.message);
      })
      .catch(console.warn);

  useEffect(() => {
    getImage();
  }, []);

  useEffect(() => {
    const timer = setInterval(getImage, value * 1000);
    return () => clearInterval(timer);
  }, [value]);

  return (
    <div>
      {imgUrl ? <img src={imgUrl} alt="dog" /> : <div>LOADING...</div>}

      <div>{value}</div>
      <input
        type="range"
        min={1}
        max={10}
        value={value}
        onChange={e => setValue(e.target.value)}
      />
    </div>
  );
}
</code>```

Title: Rerender API's image every N second

Body:
Image rerender every N second (user determines value through Slider). Default value=3

Also i want to set initial state for imageUrl, before the component have rendered. How can i do this? And how to handle situation when user didn't connect to the Internet

const [value, setValue] = useState(3);
const [imgUrl, setImgUrl] = useState();

useEffect(() => {
  const valueCopy = value;
  const timer = setTimeout(() => {
            fetch('https://dog.ceo/api/breeds/image/random')
                .then(responce => responce.json())
                .then(data => {
                    setImgUrl(data.message);
                })
                .catch(err => console.warn(err));
        }, valueCopy * 1000);

   return () => clearTimeout(timer);
});

return (
   <Image style={styles.img} source={{ uri: `${imgUrl}` }} />
   <Text style={styles.valueText}>{value}</Text>
   <Slider value={value} onValueChange={(sliderValue) => setValue(sliderValue)} />

)


问:
How to return the value of Data Reader(ASP.NET MVC)
```<code>public ActionResult Index()
{
    string sCurr = "";
    string myConString = "Driver={MySQL ODBC 5.3 Unicode Driver}; SERVER=localhost;Port=0000;DATABASE=ABC;UID=root;PASSWORD=123;OPTION=3;";

    OdbcConnection dbConnection = new OdbcConnection(myConString);
    dbConnection.Open();
    string sql = "SELECT * FROM USER";
    OdbcConnection conn = null;
    OdbcCommand comm = null;
    OdbcDataReader dr = null;
    conn = new OdbcConnection(myConString);
    conn.Open();
    comm = new OdbcCommand(sql, conn);
    dr = comm.ExecuteReader();
    if (dr != null)
    {
        while (dr.Read())
        {
            sCurr = (dr.GetValue(0).ToString());
        }
    }
    return View();
}
</code>```

I want to get value[2] and value[4] for checking purpose.

How to get the value ?

Please Help!

Thank you.

dr = comm.ExecuteReader(); have value like image below:

答:
Ensure your IDisposable objects are disposed-of before returning with a using() block. Otherwise you will potentially leak native resources and memory (e.g. you may prematurely exhaust your DbConnection pool).

Your code is defining empty Odbc... objects for no reason.

Use async for all IO where possible - as you're using ASP.NET this is supported (note that you cannot have concurrent async with ADO.NET objects whereas you can with filesystem IO on Windows).

```<code>public async Task<ActionResult> Index()
{
    const string connectionString = "Driver={MySQL ODBC 5.3 Unicode Driver}; SERVER=localhost;Port=0000;DATABASE=ABC;UID=root;PASSWORD=123;OPTION=3;";
    //const string sql = "SELECT * FROM USER"; // <-- don't do this. Always name your columns!
    const string sql = "SELECT UserId, Created, UserType, etc FROM `USER`":

    using( OdbcConnection c = new OdbcConnection( connectionString ))
    using( OdbcCommand cmd = c.CreateCommand() )
    {
        await c.OpenAsync();

        cmd.CommandText = sql;

        using( OdbcDataReader rdr = await cmd.ExecuteReaderAsync() )
        {
            while( await rdr.ReadAsync() )
            {
                Int32 userId = rdr.GetInt32( 0 );
                DateTime created = rdr.GetDateTime( 1 );
                String userType = rdr.GetString( 2 );
                // etc...
            }
        }
    }

    // etc...
}
</code>```

To return data to be rendered in the view, pass it using a View-Model:

```<code>class UserRow
{
    Int32    UserId  { get; set; }
    DateTime Created { get; set; }
    // etc...
}
</code>```

```<code>public async Task<ActionResult> Index()
{
    const string connectionString = "Driver={MySQL ODBC 5.3 Unicode Driver}; SERVER=localhost;Port=0000;DATABASE=ABC;UID=root;PASSWORD=123;OPTION=3;";
    //const string sql = "SELECT * FROM USER"; // <-- don't do this. Always name your columns!
    const string sql = "SELECT UserId, Created, UserType, etc FROM `USER`":

    using( OdbcConnection c = new OdbcConnection( connectionString ))
    using( OdbcCommand cmd = c.CreateCommand() )
    {
        await c.OpenAsync();

        cmd.CommandText = sql;

        using( OdbcDataReader rdr = await cmd.ExecuteReaderAsync() )
        {
            List<UserRow> list = new List<UserRow>();

            while( await rdr.ReadAsync() )
            {
                list.Add( new UserRow() {
                    UserId = rdr.GetInt32( 0 ),
                    Created = rdr.GetDateTime( 1 ),
                    // etc
                } );
            }

            return this.View( model: list );
        }
    }

    // etc...
}

</code>```

```<code>@model IReadOnlyList<UserRow>

<div>

<table>
    <thead>
        <tr>
            <th>UserID</th>
            <th>Created</th>
            etc
        </tr>
    </thead>
    <tbody>
@foreach( UserRow row in this.Model )
{
        <tr>
            <td>@row.UserId</td>
            <td>@row.Created</td>
            etc
        </tr>
}
    </tbody>
</table>

</div>
</code>```

Body:
public ActionResult Index()
{
    string sCurr = "";
    string myConString = "Driver={MySQL ODBC 5.3 Unicode Driver}; SERVER=localhost;Port=0000;DATABASE=ABC;UID=root;PASSWORD=123;OPTION=3;";

    OdbcConnection dbConnection = new OdbcConnection(myConString);
    dbConnection.Open();
    string sql = "SELECT * FROM USER";
    OdbcConnection conn = null;
    OdbcCommand comm = null;
    OdbcDataReader dr = null;
    conn = new OdbcConnection(myConString);
    conn.Open();
    comm = new OdbcCommand(sql, conn);
    dr = comm.ExecuteReader();
    if (dr != null)
    {
        while (dr.Read())
        {
            sCurr = (dr.GetValue(0).ToString());
        }
    }
    return View();
}

I want to get value[2] and value[4] for checking purpose.

How to get the value ?

Please Help!

Thank you.

dr = comm.ExecuteReader(); have value like image below:

Body:
Ensure your IDisposable objects are disposed-of before returning with a using() block. Otherwise you will potentially leak native resources and memory (e.g. you may prematurely exhaust your DbConnection pool).

Your code is defining empty Odbc... objects for no reason.

Use async for all IO where possible - as you're using ASP.NET this is supported (note that you cannot have concurrent async with ADO.NET objects whereas you can with filesystem IO on Windows).

public async Task<ActionResult> Index()
{
    const string connectionString = "Driver={MySQL ODBC 5.3 Unicode Driver}; SERVER=localhost;Port=0000;DATABASE=ABC;UID=root;PASSWORD=123;OPTION=3;";
    //const string sql = "SELECT * FROM USER"; // <-- don't do this. Always name your columns!
    const string sql = "SELECT UserId, Created, UserType, etc FROM `USER`":

    using( OdbcConnection c = new OdbcConnection( connectionString ))
    using( OdbcCommand cmd = c.CreateCommand() )
    {
        await c.OpenAsync();

        cmd.CommandText = sql;

        using( OdbcDataReader rdr = await cmd.ExecuteReaderAsync() )
        {
            while( await rdr.ReadAsync() )
            {
                Int32 userId = rdr.GetInt32( 0 );
                DateTime created = rdr.GetDateTime( 1 );
                String userType = rdr.GetString( 2 );
                // etc...
            }
        }
    }

    // etc...
}

To return data to be rendered in the view, pass it using a View-Model:

class UserRow
{
    Int32    UserId  { get; set; }
    DateTime Created { get; set; }
    // etc...
}

public async Task<ActionResult> Index()
{
    const string connectionString = "Driver={MySQL ODBC 5.3 Unicode Driver}; SERVER=localhost;Port=0000;DATABASE=ABC;UID=root;PASSWORD=123;OPTION=3;";
    //const string sql = "SELECT * FROM USER"; // <-- don't do this. Always name your columns!
    const string sql = "SELECT UserId, Created, UserType, etc FROM `USER`":

    using( OdbcConnection c = new OdbcConnection( connectionString ))
    using( OdbcCommand cmd = c.CreateCommand() )
    {
        await c.OpenAsync();

        cmd.CommandText = sql;

        using( OdbcDataReader rdr = await cmd.ExecuteReaderAsync() )
        {
            List<UserRow> list = new List<UserRow>();

            while( await rdr.ReadAsync() )
            {
                list.Add( new UserRow() {
                    UserId = rdr.GetInt32( 0 ),
                    Created = rdr.GetDateTime( 1 ),
                    // etc
                } );
            }

            return this.View( model: list );
        }
    }

    // etc...
}

@model IReadOnlyList<UserRow>

<div>

<table>
    <thead>
        <tr>
            <th>UserID</th>
            <th>Created</th>
            etc
        </tr>
    </thead>
    <tbody>
@foreach( UserRow row in this.Model )
{
        <tr>
            <td>@row.UserId</td>
            <td>@row.Created</td>
            etc
        </tr>
}
    </tbody>
</table>

</div>


问:
Android listview and VirtulaKeyboard
i have listview and editText ,i need to scroll the last item of the listview to top of the soft keyboard ,how can i done this.</p>

答:
Add these property in the listview.</p>

```<code>android:stackFromBottom="false"
android:transcriptMode="alwaysScroll"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android listview and VirtulaKeyboard

Body:
Add these property in the listview.

android:stackFromBottom="false"
android:transcriptMode="alwaysScroll"


问:
Malformed Node or String with Dynamodb Returned item
I have been experimenting with DynamoDB in AWS and have decided it's the wrong tool for me.  While working in AWS, I uploaded a large number of records to the system that I am now trying to retrieve using Python.  I admit, I'm completely new to Python and what I've cobbled together is from examples found around the internet.  I'm working with Office 365 Audit logs that have many fields and when I retrieve them from Dynamo, I found that decimal fields are coming back as decimal('1').

```<code>{
  'ItemType': 'File',
  'SourceFileName': 'xxx',
  'UserKey': 'xxx',
  'RecordType': Decimal('6'),
  'UserId': 'xxx',
  'ClientIP': 'xxx',
  'CorrelationId': 'xxx',
  'ObjectId': 'xxx',
  'Version': Decimal('1'),
  'Site': 'xxx',
  'WebId': 'xxx',
  'SourceFileExtension': 'js',
  'SiteUrl': 'xxx',
  'Workload': 'SharePoint',
  'SourceRelativeUrl': 'xxx',
  'EventSource': 'SharePoint',
  'ListId': 'xxx',
  'OrganizationId': 'xxx',
  'Operation': 'FileAccessed',
  'UserAgent': 'xxx',
  'ListItemUniqueId': 'xxx',
  'CreationTime': '2019-07-26T21:54:45',
  'UserType': Decimal('0'),
  'Id': 'xxx',
  'CustomUniqueId': False
}
</code>```

In troubleshooting, I found this handy function that converts Decimal('0') to an actual decimal

```<code>class DecimalEncoder(json.JSONEncoder):
    def default(self, o):

        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)
</code>```

and this function is called

```<code>response = table.scan(Limit=10)
for i in response['Items']:
    d = ast.literal_eval((json.dumps(i, cls=DecimalEncoder)))
</code>```

For the most part this works fine, unless i has a boolean field (like the example above). Then I get this error

```<code>malformed node or string: <_ast.Name object at 0x04B3F778>
</code>```

As far as I understand with Python, the boolean values of True and False are capitalized correctly.. I considered adding the the DecimalEncoder default method but this wouldn't do much since it's literally returning the same value

```<code>elif isinstance(o,bool):
    return True if o else False
</code>```

I did find by removing the key, I got no error

```<code>if 'CustomUniqueId' in i:
    del i['CustomUniqueId']
</code>```

However, don't want to lose this field. I'm at a loss as to how to resolve this.

答:
The problem is that you are converting your Python object to a JSON string (i.e. the json.dumps command) and then trying to interpret that string as Python dictionary (the ast.literal_eval takes a string and tries to run it as Python code).

A python dictionary looks very similar to a JSON object but they are not 100% compatible.  In JSON, boolean is presented as true and false and in Python it's represented as True and False.

I way to solve this would be to use json.loads which reads a JSON string and converts it into a Python equivalent:

```<code>d = json.loads((json.dumps(i, cls=DecimalEncoder)))
</code>```

That being said, this seems like a lot of hoops/processing to convert Decimal class to native floats and would recommend just using Decimal directly or converting to a float (i.e. float(d['RecordType'])) if you need to pass them to something that expects a float.

Body:
I have been experimenting with DynamoDB in AWS and have decided it's the wrong tool for me.  While working in AWS, I uploaded a large number of records to the system that I am now trying to retrieve using Python.  I admit, I'm completely new to Python and what I've cobbled together is from examples found around the internet.  I'm working with Office 365 Audit logs that have many fields and when I retrieve them from Dynamo, I found that decimal fields are coming back as decimal('1').

{
  'ItemType': 'File',
  'SourceFileName': 'xxx',
  'UserKey': 'xxx',
  'RecordType': Decimal('6'),
  'UserId': 'xxx',
  'ClientIP': 'xxx',
  'CorrelationId': 'xxx',
  'ObjectId': 'xxx',
  'Version': Decimal('1'),
  'Site': 'xxx',
  'WebId': 'xxx',
  'SourceFileExtension': 'js',
  'SiteUrl': 'xxx',
  'Workload': 'SharePoint',
  'SourceRelativeUrl': 'xxx',
  'EventSource': 'SharePoint',
  'ListId': 'xxx',
  'OrganizationId': 'xxx',
  'Operation': 'FileAccessed',
  'UserAgent': 'xxx',
  'ListItemUniqueId': 'xxx',
  'CreationTime': '2019-07-26T21:54:45',
  'UserType': Decimal('0'),
  'Id': 'xxx',
  'CustomUniqueId': False
}

In troubleshooting, I found this handy function that converts Decimal('0') to an actual decimal

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):

        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

and this function is called

response = table.scan(Limit=10)
for i in response['Items']:
    d = ast.literal_eval((json.dumps(i, cls=DecimalEncoder)))

For the most part this works fine, unless i has a boolean field (like the example above). Then I get this error

malformed node or string: <_ast.Name object at 0x04B3F778>

As far as I understand with Python, the boolean values of True and False are capitalized correctly.. I considered adding the the DecimalEncoder default method but this wouldn't do much since it's literally returning the same value

elif isinstance(o,bool):
    return True if o else False

I did find by removing the key, I got no error

if 'CustomUniqueId' in i:
    del i['CustomUniqueId']

However, don't want to lose this field. I'm at a loss as to how to resolve this.

Body:
The problem is that you are converting your Python object to a JSON string (i.e. the json.dumps command) and then trying to interpret that string as Python dictionary (the ast.literal_eval takes a string and tries to run it as Python code).

A python dictionary looks very similar to a JSON object but they are not 100% compatible.  In JSON, boolean is presented as true and false and in Python it's represented as True and False.

I way to solve this would be to use json.loads which reads a JSON string and converts it into a Python equivalent:

d = json.loads((json.dumps(i, cls=DecimalEncoder)))

That being said, this seems like a lot of hoops/processing to convert Decimal class to native floats and would recommend just using Decimal directly or converting to a float (i.e. float(d['RecordType'])) if you need to pass them to something that expects a float.


问:
Get current AUTO_INCREMENT value for any table
How do I get the current AUTO_INCREMENT value for a table in MySQL?</p>

答:
I was looking for the same and ended up by creating a static method inside a Helper class (in my case I named it App\Helpers\Database).

The method

```<code>/**
 * Method to get the autoincrement value from a database table
 *
 * @access public
 *
 * @param string $database The database name or configuration in the .env file
 * @param string $table    The table name
 *
 * @return mixed
 */
public static function getAutoIncrementValue($database, $table)
{
    $database ?? env('DB_DATABASE');

    return \DB::select("
        SELECT AUTO_INCREMENT
        FROM information_schema.TABLES
        WHERE TABLE_SCHEMA = '" . env('DB_DATABASE') . "'
        AND TABLE_NAME = '" . $table . "'"
    )[0]->AUTO_INCREMENT;
}
</code>```

To call the method and get the MySql AUTO_INCREMENT just use the following:

```<code>$auto_increment = \App\Helpers\Database::getAutoIncrementValue(env('DB_DATABASE'), 'your_table_name');
</code>```

Hope it helps.

Body:
I was looking for the same and ended up by creating a static method inside a Helper class (in my case I named it App\Helpers\Database).

The method

/**
 * Method to get the autoincrement value from a database table
 *
 * @access public
 *
 * @param string $database The database name or configuration in the .env file
 * @param string $table    The table name
 *
 * @return mixed
 */
public static function getAutoIncrementValue($database, $table)
{
    $database ?? env('DB_DATABASE');

    return \DB::select("
        SELECT AUTO_INCREMENT
        FROM information_schema.TABLES
        WHERE TABLE_SCHEMA = '" . env('DB_DATABASE') . "'
        AND TABLE_NAME = '" . $table . "'"
    )[0]->AUTO_INCREMENT;
}

To call the method and get the MySql AUTO_INCREMENT just use the following:

$auto_increment = \App\Helpers\Database::getAutoIncrementValue(env('DB_DATABASE'), 'your_table_name');

Hope it helps.


问:
pick image from photos/gallery using xctest
I am writing a test framework for an ios app that requires importing image from photos/gallery app for validation. I am using XCTest Framework for testing. I have looked over the Internet for some resources but couldn't find any. Can anyone help me how to approach the problem. Again, I have pick the image not from inside the app but from image but from Photos library. </p>

答:
```<code>let photosApp = XCUIApplication(bundleIdentifier: "com.apple.mobileslideshow")
photosApp.launch()

let continueButton = photosApp.buttons["Continue"]
if continueButton.waitForExistence(timeout: 2) {
  continueButton.tap()
}
photosApp.collectionViews["PhotosGridView"].cells.firstMatch.tap()
</code>```


问:
Convert 2D array to assigned key Object
```<code>array = [
    ["Work", 11.0],
    ["Eat", 2.0],
    ["Commute", 2.0],
    ["Watch Tv", 2.0],
    ["Sleep", 7.0]
];
</code>```

May I know how to convert the array to object:

```<code>var data = [{
        "Task": "Work",
        "Hour": 11.0
    },
    {
        "Task": "Eat",
        "Hour": 2.0
    }, {
        "Task": "Commute",
        "Hour": 2.0
    }, {
        "Task": "Watch Tv",
        "Hour": 2.0
    }, {
        "Task": "Sleep",
        "Hour": 7.0
    },
]
</code>```

答:
Array.prototype.map will create a new array based on a transformation of each element.  The transformation you should apply is to create an object where the Task property is element [0] of the array item and the Hour property is the element [1] of the array item.

array = [
  ["Work", 11.0],
  ["Eat", 2.0],
  ["Commute", 2.0],
  ["Watch Tv", 2.0],
  ["Sleep", 7.0]
];

result = array.map(e => ({ Task: e[0], Hour: e[1] }));

console.log(result);```

Title: Convert 2D array to assigned key Object

Body:
array = [
    ["Work", 11.0],
    ["Eat", 2.0],
    ["Commute", 2.0],
    ["Watch Tv", 2.0],
    ["Sleep", 7.0]
];

May I know how to convert the array to object:

var data = [{
        "Task": "Work",
        "Hour": 11.0
    },
    {
        "Task": "Eat",
        "Hour": 2.0
    }, {
        "Task": "Commute",
        "Hour": 2.0
    }, {
        "Task": "Watch Tv",
        "Hour": 2.0
    }, {
        "Task": "Sleep",
        "Hour": 7.0
    },
]


问:
Get last non-null value of a row and its column in pandas DataFrame
I want to get the last non-null value (rightmost) of row C in this DataFrame.
With that, I also want to get its Year (column name).

Here is my DataFrame :

```<code>df = pd.DataFrame(np.random.randint(0,100,size=(4, 5)),
                  columns=['2016', '2017', '2018', '2019', '2020'],
                  index=['A', 'B', 'C', 'D'])
df.iloc[2, 2:5] = np.NaN
print(df)
</code>```

```<code>    2016    2017    2018    2019    2020
A   41      69      63.0    85.0    16.0
B   12      99      88.0    87.0    13.0
C   80      15      NaN     NaN     NaN
D   42      27      3.0     76.0    6.0
</code>```

Result should look like {'year' : 2017, 'value' : 15}.
What's the best way of achieving that result ?

答:
Something like this should solve it

```<code>In [1]: import pandas as pd
   ...: import numpy as np
   ...: df = pd.DataFrame(np.random.randint(0,100,size=(4, 5)),
   ...:                   columns=['2016', '2017', '2018', '2019', '2020'],
   ...:                   index=['A', 'B', 'C', 'D'])
   ...: df.iloc[2, 2:5] = np.NaN
   ...: print(df)
   2016  2017  2018  2019  2020
A    13    78   9.0  13.0  98.0
B    35     3  32.0   6.0  42.0
C    26    24   NaN   NaN   NaN
D    77    91  96.0  60.0  94.0

In [2]: value = int(df.loc['C'][~df.loc['C'].isna()][-1])

In [3]: year = df.loc['C'][df.loc['C'] == value].index.values[0]

In [4]: result = {'year': year, 'value': value}

In [5]: result
Out[5]: {'year': '2017', 'value': 24}
</code>```

You can break the expressions above part by part to better understand how each functionality is getting used together here to yield the desired output.

Body:
I want to get the last non-null value (rightmost) of row C in this DataFrame.
With that, I also want to get its Year (column name).

Here is my DataFrame :

df = pd.DataFrame(np.random.randint(0,100,size=(4, 5)),
                  columns=['2016', '2017', '2018', '2019', '2020'],
                  index=['A', 'B', 'C', 'D'])
df.iloc[2, 2:5] = np.NaN
print(df)

    2016    2017    2018    2019    2020
A   41      69      63.0    85.0    16.0
B   12      99      88.0    87.0    13.0
C   80      15      NaN     NaN     NaN
D   42      27      3.0     76.0    6.0

Result should look like {'year' : 2017, 'value' : 15}.
What's the best way of achieving that result ?

Body:
Something like this should solve it

In [1]: import pandas as pd
   ...: import numpy as np
   ...: df = pd.DataFrame(np.random.randint(0,100,size=(4, 5)),
   ...:                   columns=['2016', '2017', '2018', '2019', '2020'],
   ...:                   index=['A', 'B', 'C', 'D'])
   ...: df.iloc[2, 2:5] = np.NaN
   ...: print(df)
   2016  2017  2018  2019  2020
A    13    78   9.0  13.0  98.0
B    35     3  32.0   6.0  42.0
C    26    24   NaN   NaN   NaN
D    77    91  96.0  60.0  94.0

In [2]: value = int(df.loc['C'][~df.loc['C'].isna()][-1])

In [3]: year = df.loc['C'][df.loc['C'] == value].index.values[0]

In [4]: result = {'year': year, 'value': value}

In [5]: result
Out[5]: {'year': '2017', 'value': 24}

You can break the expressions above part by part to better understand how each functionality is getting used together here to yield the desired output.


问:
PayPal webhook all events remain pending
When I complete a payment with PayPal using a sandbox account, webhook events are listed as "Pending" with an orange icon in the "Webhook events" section of the PayPal developer dashboard, and the log shows that the webhook has not been called. However, when using a different REST API app, the webhook call works perfectly!

I have tried:

Ensuring that currency is correctly configured

Changing the "Payment Review" setting to "Off" for each sandbox account

Making the app call the webhook for all events

Comparing settings with the other app I made, for which the webhook does get called

Checking that the webhook causes log output, so there is no error causing the lack of output

What other things could be causing this difference, making webhook calls work for one app but get stuck in "Pending" for another that I created more recently?

答:
Sandbox accounts and REST Apps are free and unlimited, so if one isn't working the way you need it to, the simple solution is to not use it anymore and use any number of new ones you create instead.

But if this remains an issue for you, it seems like you should direct the question to PayPal's support, since you've included no request/response log information to actually review for what might be different about the two apps or accounts' situations that causes one to be pending.


问:
WCF RIA Services simple question
I'm new to all this stuff, so a question is dumb. If I'll use WCF RIA Services in my app, does a user well need to install something special to launch my app?

Thank you in advance!

答: You can for example check this demo that uses RIA services and on the clients' end it will only require the Silverlight plugin.</p>

Title: WCF RIA Services simple question


问:
How to set a cluster creator in CloudFormation to re-use it in lambda?
I have a CloudFormation stack that creates an EKS cluster and then runs a kubectl command in a lambda.

The problem is that the cluster is created with the access only for the user who ran the cloudformation stack (e.g. a human user). And in this case, the role that runs a lambda with kubectl fails with You must be logged in to the server (Unauthorized) because it's not the role that triggered the cloudfromation cluster creation stack.

I checked alternative solutions like eksctl where I can specify the role that will run the CloudFormation stack that creates a cluster, but creating a cluster with eksctl takes longer than 15 minutes and I can't use it inside lambda.

Is there a way to create an EKS cluster and have access to it from a lambda in the same cloudformation stack?

答:
you should create a custom IAM Service role for Cloudformaction STACK and LAMBDA.
You must guarantee this role has the required permissions on EKS service and

in the Permissions section you can find how a stack can assume a role.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-add-tags.html

And here is how to create a role for a service,
https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html

By default EKS set as administrator the role assumed when it is created.


问:
In how many different ways can I call a function
In how many ways can I call this function, I found this question in one book and I was like 1 but I'm not sure, I think I can call it just once because, it has 3 integer parameters so that's the only way, I guess. The given answers wear (1, 2, 3 or 4) ways to call the Function.

```<code>int Volume (int x, int y=0, int z=3){ return x+y+z;}
</code>```

What's the correct answer?

Body:
In how many ways can I call this function, I found this question in one book and I was like 1 but I'm not sure, I think I can call it just once because, it has 3 integer parameters so that's the only way, I guess. The given answers wear (1, 2, 3 or 4) ways to call the Function.

int Volume (int x, int y=0, int z=3){ return x+y+z;}

What's the correct answer?

Body:
Three ways.

Example :

volume(3) //x = 3, y = 0, z = 3

volume(3,4) // x = 3, y = 4, z = 3

volume(3,4,5) // x = 3, y = 4, z = 5


问:
Flutter: json data is not displaying in future builder on http get request
I'm trying to display items from json http get request. But It displays nothing.

This is the request function

```<code>  Future<List<Products>> _getProducts() async{
    var data = await http.get("http://orangecitycafe.in/app_configs/products_display.php");
    var jsonData = json.decode(data.body);
    List<Products> products = [];

    for (var p in jsonData){
      Products product = Products(index: p["index"], id: p["product_id"], name: p["product_name"],
      price: p["product_price"],image: p["product_image"]);
      products.add(product);
    }
    print(products);
    return products;
  }
</code>```

NOTE: This is my custom created json file

This is my json file

And this is the php code for fetching data from database and creating a json format

```<code>$sql = "SELECT * FROM $products_table";
$result = mysqli_query($conn,$sql);
$db_data = array();

if(mysqli_num_rows($result)){
    while($row = mysqli_fetch_array($result)){
        $db_data[] = $row;
    }
    echo json_encode($db_data);
}
</code>```

And this is the UI for Future Builder

```<code>body:
      Container(
        child: FutureBuilder(
          future: _getProducts(),
          builder: (BuildContext context, AsyncSnapshot snapshot){

            if(snapshot.data == null){
              return Container(
                child: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            }
            else{
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index){
                return ListTile(
                  title: Text(snapshot.data[index].price),
                );
              },
            );
            }
          },
        ),
      )
</code>```

I don't know where actually the mistake is. Is it happens due to my custom json file or I might miss something.

答:
You can copy paste run full code below

You can see Products class in full code

code snippet to parse json string

```<code>Future<List<Products>> _getProducts() async {
  var data = await http
      .get("http://orangecitycafe.in/app_configs/products_display.php");
  var jsonData = json.decode(data.body);
  List<Products> products = [];
  products = productsFromJson(data.body);

  return products;
}
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
//     final products = productsFromJson(jsonString);

import 'dart:convert';

List<Products> productsFromJson(String str) =>
    List<Products>.from(json.decode(str).map((x) => Products.fromJson(x)));

String productsToJson(List<Products> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Products {
  String the0;
  String the1;
  String the2;
  String the3;
  String the4;
  DateTime the5;
  String productId;
  String categId;
  String productName;
  String productPrice;
  String productImage;
  DateTime addedDate;

  Products({
    this.the0,
    this.the1,
    this.the2,
    this.the3,
    this.the4,
    this.the5,
    this.productId,
    this.categId,
    this.productName,
    this.productPrice,
    this.productImage,
    this.addedDate,
  });

  factory Products.fromJson(Map<String, dynamic> json) => Products(
        the0: json["0"],
        the1: json["1"],
        the2: json["2"],
        the3: json["3"],
        the4: json["4"],
        the5: DateTime.parse(json["5"]),
        productId: json["product_id"],
        categId: json["categ_id"],
        productName: json["product_name"],
        productPrice: json["product_price"],
        productImage: json["product_image"],
        addedDate: DateTime.parse(json["added_date"]),
      );

  Map<String, dynamic> toJson() => {
        "0": the0,
        "1": the1,
        "2": the2,
        "3": the3,
        "4": the4,
        "5": the5.toIso8601String(),
        "product_id": productId,
        "categ_id": categId,
        "product_name": productName,
        "product_price": productPrice,
        "product_image": productImage,
        "added_date": addedDate.toIso8601String(),
      };
}

Future<List<Products>> _getProducts() async {
  var data = await http
      .get("http://orangecitycafe.in/app_configs/products_display.php");
  var jsonData = json.decode(data.body);
  List<Products> products = [];
  products = productsFromJson(data.body);

  /*for (var p in jsonData){
    Products product = Products(index: p["index"], id: p["product_id"], name: p["product_name"],
        price: p["product_price"],image: p["product_image"]);
    products.add(product);
  }
  print(products);*/
  return products;
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
              child: FutureBuilder(
                future: _getProducts(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.data == null) {
                    return Container(
                      child: Center(
                        child: CircularProgressIndicator(),
                      ),
                    );
                  } else {
                    return ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        return ListTile(
                          title: Text(snapshot.data[index].productName),
                        );
                      },
                    );
                  }
                },
              ),
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Body:
I'm trying to display items from json http get request. But It displays nothing.

This is the request function

  Future<List<Products>> _getProducts() async{
    var data = await http.get("http://orangecitycafe.in/app_configs/products_display.php");
    var jsonData = json.decode(data.body);
    List<Products> products = [];

    for (var p in jsonData){
      Products product = Products(index: p["index"], id: p["product_id"], name: p["product_name"],
      price: p["product_price"],image: p["product_image"]);
      products.add(product);
    }
    print(products);
    return products;
  }

NOTE: This is my custom created json file

This is my json file

And this is the php code for fetching data from database and creating a json format

$sql = "SELECT * FROM $products_table";
$result = mysqli_query($conn,$sql);
$db_data = array();

if(mysqli_num_rows($result)){
    while($row = mysqli_fetch_array($result)){
        $db_data[] = $row;
    }
    echo json_encode($db_data);
}

And this is the UI for Future Builder

body:
      Container(
        child: FutureBuilder(
          future: _getProducts(),
          builder: (BuildContext context, AsyncSnapshot snapshot){

            if(snapshot.data == null){
              return Container(
                child: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            }
            else{
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index){
                return ListTile(
                  title: Text(snapshot.data[index].price),
                );
              },
            );
            }
          },
        ),
      )

I don't know where actually the mistake is. Is it happens due to my custom json file or I might miss something.

Body:
You can copy paste run full code below

You can see Products class in full code

code snippet to parse json string

Future<List<Products>> _getProducts() async {
  var data = await http
      .get("http://orangecitycafe.in/app_configs/products_display.php");
  var jsonData = json.decode(data.body);
  List<Products> products = [];
  products = productsFromJson(data.body);

  return products;
}

working demo

full code

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
//     final products = productsFromJson(jsonString);

import 'dart:convert';

List<Products> productsFromJson(String str) =>
    List<Products>.from(json.decode(str).map((x) => Products.fromJson(x)));

String productsToJson(List<Products> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Products {
  String the0;
  String the1;
  String the2;
  String the3;
  String the4;
  DateTime the5;
  String productId;
  String categId;
  String productName;
  String productPrice;
  String productImage;
  DateTime addedDate;

  Products({
    this.the0,
    this.the1,
    this.the2,
    this.the3,
    this.the4,
    this.the5,
    this.productId,
    this.categId,
    this.productName,
    this.productPrice,
    this.productImage,
    this.addedDate,
  });

  factory Products.fromJson(Map<String, dynamic> json) => Products(
        the0: json["0"],
        the1: json["1"],
        the2: json["2"],
        the3: json["3"],
        the4: json["4"],
        the5: DateTime.parse(json["5"]),
        productId: json["product_id"],
        categId: json["categ_id"],
        productName: json["product_name"],
        productPrice: json["product_price"],
        productImage: json["product_image"],
        addedDate: DateTime.parse(json["added_date"]),
      );

  Map<String, dynamic> toJson() => {
        "0": the0,
        "1": the1,
        "2": the2,
        "3": the3,
        "4": the4,
        "5": the5.toIso8601String(),
        "product_id": productId,
        "categ_id": categId,
        "product_name": productName,
        "product_price": productPrice,
        "product_image": productImage,
        "added_date": addedDate.toIso8601String(),
      };
}

Future<List<Products>> _getProducts() async {
  var data = await http
      .get("http://orangecitycafe.in/app_configs/products_display.php");
  var jsonData = json.decode(data.body);
  List<Products> products = [];
  products = productsFromJson(data.body);

  /*for (var p in jsonData){
    Products product = Products(index: p["index"], id: p["product_id"], name: p["product_name"],
        price: p["product_price"],image: p["product_image"]);
    products.add(product);
  }
  print(products);*/
  return products;
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
              child: FutureBuilder(
                future: _getProducts(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.data == null) {
                    return Container(
                      child: Center(
                        child: CircularProgressIndicator(),
                      ),
                    );
                  } else {
                    return ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        return ListTile(
                          title: Text(snapshot.data[index].productName),
                        );
                      },
                    );
                  }
                },
              ),
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


问:
I can't edit config.inc.php file in xampp
I've tried to install nano and I did and I did a nano code(I can't remember what (it was 2 months ago)), which then made me ask for my password but I could not type so I terminated the terminal but then when I tried chmod, sudo or other code it told me it that file "config.inc.php does not exist".

Oh yeah the code was "sudo nano config.inc.php". please help I don't want a useless phpmyadmin. I also am trying to use mySQL(just for your information) and am using a Mac os Catalina 10.15.1

Please help.

答: sudo nano config.inc.php will ask for a password but won't give any local echo (as you type - on *nix shells anyways). Could that have lead to your problem? Sorry, I just wanted to add a comment but Stackoverflow wouldn't let me before I have 50 reputation points.


问:
chatbase: I need to recover the access to chatbase information (board) from my clients bots
I need to recover the access to chatbase information (board) from my clients bots, because the responsible person left my company. How can I recover the access?

Best regards
Fábio

答: Can you please email Chatbase-support@google.com with the name and api key of the bot as well as the email address of the former owner? </p>


问:
Updating member variable of object while using multprocessing pool
I have a class B which is composed of another class A.

In class B I am using multiprocessing pool to call a method from class A. This method updates a member variable of A (which is a dict).

When I print out this member variable it doesn't seem to have been updated. Here is the code describing the issue:

import multiprocessing as mp

class A():
    def __init__(self):
        self.aDict = {'key': 0}

    def set_lock(self, lock):
        self.lock = lock

    def do_work(self, item):
        print("Doing work for item: {}".format(item) )
        self.aDict['key'] += 1

        return [1,2,3] # return some list

class B():
    def __init__(self):
        self.objA = A()

    def run_with_mp(self):
        items=['item1', 'item2']
        with mp.Pool(processes=mp.cpu_count()) as pool:
            result = pool.map_async(self.objA.do_work, items)
            result.wait()
            pool.terminate()

        print(self.objA.aDict)

    def run(self):
        items=['item1', 'item2']
        for item in items:
            self.objA.do_work(item)

        print(self.objA.aDict)

if __name__ == "__main__":
    b = B()
    b.run_with_mp() # prints {'key': 0}
    b.run()         # prints {'key': 2}
```

b.run_with_mp() prints {'key': 0} whole b.run() prints {'key': 2}. I thought the multiprocessing pool version would also do the same since the object self.objA had scope for the full class of B where the multiprocessing pool runs.

I think each worker of the pool sees a different version of self.objA, which are different from the one in the main program flow. Is there a way to make all the workers update a common variable?

答:
You are close to the explanation, indeed, each spawned process holds its own area of memory, it means that they are independent. When you run the do_work each process updates its version of aDict because that variable it's not shared. If you want to share a variable, the easiest way is to use a Manager, for example:

import multiprocessing as mp

class A():
    def __init__(self):
        self.aDict = mp.Manager().dict({'key': 0})

    def set_lock(self, lock):
        self.lock = lock

    def do_work(self, item):
        print("Doing work for item: {}".format(item) )
        self.aDict['key'] += 1

        return [1,2,3] # return some list

class B():
    def __init__(self):
        self.objA = A()

    def run_with_mp(self):
        items=['item1', 'item2']
        with mp.Pool(processes=mp.cpu_count()) as pool:
            result = pool.map_async(self.objA.do_work, items)
            result.wait()
            pool.terminate()

        print(self.objA.aDict)

    def run(self):
        items=['item1', 'item2']
        for item in items:
            self.objA.do_work(item)

        print(self.objA.aDict)

if __name__ == "__main__":
    b = B()
    b.run_with_mp() # prints {'key': 2}
    b.run()         # prints {'key': 4}
```

I modified your example to share the aDict variable, so each process will update that property (run_with_mp and run methods). Consider reading more in docs.

Body:
I have a class B which is composed of another class A.

In class B I am using multiprocessing pool to call a method from class A. This method updates a member variable of A (which is a dict).

When I print out this member variable it doesn't seem to have been updated. Here is the code describing the issue:

import multiprocessing as mp

class A():
    def __init__(self):
        self.aDict = {'key': 0}

    def set_lock(self, lock):
        self.lock = lock

    def do_work(self, item):
        print("Doing work for item: {}".format(item) )
        self.aDict['key'] += 1

        return [1,2,3] # return some list

class B():
    def __init__(self):
        self.objA = A()

    def run_with_mp(self):
        items=['item1', 'item2']
        with mp.Pool(processes=mp.cpu_count()) as pool:
            result = pool.map_async(self.objA.do_work, items)
            result.wait()
            pool.terminate()

        print(self.objA.aDict)

    def run(self):
        items=['item1', 'item2']
        for item in items:
            self.objA.do_work(item)

        print(self.objA.aDict)

if __name__ == "__main__":
    b = B()
    b.run_with_mp() # prints {'key': 0}
    b.run()         # prints {'key': 2}

b.run_with_mp() prints {'key': 0} whole b.run() prints {'key': 2}. I thought the multiprocessing pool version would also do the same since the object self.objA had scope for the full class of B where the multiprocessing pool runs.

I think each worker of the pool sees a different version of self.objA, which are different from the one in the main program flow. Is there a way to make all the workers update a common variable?

Body:
You are close to the explanation, indeed, each spawned process holds its own area of memory, it means that they are independent. When you run the do_work each process updates its version of aDict because that variable it's not shared. If you want to share a variable, the easiest way is to use a Manager, for example:

import multiprocessing as mp

class A():
    def __init__(self):
        self.aDict = mp.Manager().dict({'key': 0})

    def set_lock(self, lock):
        self.lock = lock

    def do_work(self, item):
        print("Doing work for item: {}".format(item) )
        self.aDict['key'] += 1

        return [1,2,3] # return some list

class B():
    def __init__(self):
        self.objA = A()

    def run_with_mp(self):
        items=['item1', 'item2']
        with mp.Pool(processes=mp.cpu_count()) as pool:
            result = pool.map_async(self.objA.do_work, items)
            result.wait()
            pool.terminate()

        print(self.objA.aDict)

    def run(self):
        items=['item1', 'item2']
        for item in items:
            self.objA.do_work(item)

        print(self.objA.aDict)

if __name__ == "__main__":
    b = B()
    b.run_with_mp() # prints {'key': 2}
    b.run()         # prints {'key': 4}

I modified your example to share the aDict variable, so each process will update that property (run_with_mp and run methods). Consider reading more in docs.


问:
AWS STS to list buckets gives access denied
I have a bucket with empty bucket policy, block public access turned ON (ACLs and Bucket) and trying to list buckets using IAM policy tied to user using STS AssumeRole with following attached policy.

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:GetObject",
                "s3:GetBucket*",
                "s3:ListBucket*",
                "s3:ListAllMyBuckets"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::my-test-bucket/*"
            ]
        }
    ]
}
</code>```

The assumed role credentials are used during the STS session in python (boto3)

s3c = boto3.client('s3',
  aws_access_key_id=credentials['AccessKeyId'],
  aws_secret_access_key=credentials['SecretAccessKey'],
  aws_session_token=credentials['SessionToken'])

s3c.list_buckets()
```

I get this exception:

botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied

When I tried to use IAM Policy simulator, it indicates "Implicitly denied". Im thinking if I need to access a bucket policy for this user? My understanding has been if both IAM and Bucket policy, it is an intersection. If either is not present, the other takes precedence.

答:
Calling list_buckets() uses the s3:ListAllMyBuckets permission.

This permission cannot be restricted to a specific bucket. A user can either list all of the buckets in the account, or none of them.

Calling operations on a bucket (ListBucket, GetBucket*) requires permission for the bucket itself.

Operations on objects requires permission for the objects (or /* after the bucket name to permit actions on all objects).

Therefore, you can change your policy to:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:ListAllMyBuckets",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetBucket*"
            ],
            "Resource": "arn:aws:s3:::my-test-bucket"
        },
        {
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::my-test-bucket/*"
        }
    ]
}
</code>```

Body:
I have a bucket with empty bucket policy, block public access turned ON (ACLs and Bucket) and trying to list buckets using IAM policy tied to user using STS AssumeRole with following attached policy.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:GetObject",
                "s3:GetBucket*",
                "s3:ListBucket*",
                "s3:ListAllMyBuckets"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::my-test-bucket/*"
            ]
        }
    ]
}

The assumed role credentials are used during the STS session in python (boto3)

s3c = boto3.client('s3',
  aws_access_key_id=credentials['AccessKeyId'],
  aws_secret_access_key=credentials['SecretAccessKey'],
  aws_session_token=credentials['SessionToken'])

s3c.list_buckets()

I get this exception:

botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied

When I tried to use IAM Policy simulator, it indicates "Implicitly denied". Im thinking if I need to access a bucket policy for this user? My understanding has been if both IAM and Bucket policy, it is an intersection. If either is not present, the other takes precedence.

Body:
Calling list_buckets() uses the s3:ListAllMyBuckets permission.

This permission cannot be restricted to a specific bucket. A user can either list all of the buckets in the account, or none of them.

Calling operations on a bucket (ListBucket, GetBucket*) requires permission for the bucket itself.

Operations on objects requires permission for the objects (or /* after the bucket name to permit actions on all objects).

Therefore, you can change your policy to:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:ListAllMyBuckets",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetBucket*"
            ],
            "Resource": "arn:aws:s3:::my-test-bucket"
        },
        {
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::my-test-bucket/*"
        }
    ]
}


问:
WinSCP script works fine manually, but failes when executed by SQL Server Agent Job
I have a WinSCP script that SFTPs a file from a remote server to a local directory. The script works fine when I execute it from the command line, but when I try to execute it as a command step in a SQL Server Agent job, the job fails. All the history tells me is:

```<code>Executed as user: NT Service\SQLSERVERAGENT. The step did not generate any output. Process Exit Code 1. The step failed.
</code>```

which could mean anything. I've tried to break the problem down to its core by stripping everything out of the script except an exit statement. It still fails, so I know the issue is not in the script. Any thoughts?

答:
Posting in case anyone else runs into this problem. The WinSCP FAQ has a little section on these kinds of problems, but missed one ridiculously simple possibility: does the job have access to the script being executed?

Regardless of who created the script, the command will be executed by the SQLSERVERAGENT account. If you're like me, you keep your scripts under your user account's home directory, which SQLSERVERAGENT doesn't have access to. Move the script to a directory it can read and see if that fixes it for you. I used the Users\Public directory.

Body:
I have a WinSCP script that SFTPs a file from a remote server to a local directory. The script works fine when I execute it from the command line, but when I try to execute it as a command step in a SQL Server Agent job, the job fails. All the history tells me is:

Executed as user: NT Service\SQLSERVERAGENT. The step did not generate any output. Process Exit Code 1. The step failed.

which could mean anything. I've tried to break the problem down to its core by stripping everything out of the script except an exit statement. It still fails, so I know the issue is not in the script. Any thoughts?


问:
Added agentless job to our release pipeline but it fails
Added agent less job to our release pipeline but it fails , Please advice

error: 2020-02-11T19:31:58.7824352Z ##[error]Build with ID 321656 not found for build pipeline ID 241

failure

答:
When troubleshooting with @sudheer kumar, we found the build with ID 321656 can be retrieved via rest api and it is indeed exist for build pipeline 241.

We checked the option allowing scripts to acess OATH token for the agent job settings, and it turned out unchecking option allowing scripts to acess OATH token fixed above issue.


问:
Kotlin OkHttp3 Using 'of(Map<String, String>): Headers' is an error. function moved to extension
The code below gives the error : Using 'of(Map): Headers' is an error. function moved to extension.

```<code>val mapH = mapOf (Pair("Content-Disposition",
          "file; filename=\"$encodedFileName\""),
          Pair("Content-Transfer-Encoding",
          "binary"))

    val headers = Headers.of (mapH)
</code>```

Having read the documentation here https://square.github.io/okhttp/upgrading_to_okhttp_4/#extension-functions, I tried :

```<code>      val headers = headersOf(mapH)
and also
      val headers = mapH.toHeaders()
</code>```

and got the errors : Unresolved reference: for headersOf and toHeaders. Why ?

答:
Try this:</p>

```<code>import okhttp3.Headers.Companion.toHeaders
</code>```

Body:
The code below gives the error : Using 'of(Map): Headers' is an error. function moved to extension.

val mapH = mapOf (Pair("Content-Disposition",
          "file; filename=\"$encodedFileName\""),
          Pair("Content-Transfer-Encoding",
          "binary"))

    val headers = Headers.of (mapH)

Having read the documentation here https://square.github.io/okhttp/upgrading_to_okhttp_4/#extension-functions, I tried :

      val headers = headersOf(mapH)
and also
      val headers = mapH.toHeaders()

and got the errors : Unresolved reference: for headersOf and toHeaders. Why ?

Body:
Try this:

import okhttp3.Headers.Companion.toHeaders


答:
```<code>update mytable set newcol = 'yourvalhere' where somecol='somevalue';
</code>```

The Where clause is optional, if you want to add the same value to the entire table ignore it. For more info post an example of your schema and what you want the data to be.

See also

http://dev.mysql.com/doc/refman/5.0/en/update.html

Title: Mysql update data

Body:
UPDATE

+-----+------------------+-------------+
| id  | datenum          | F1_baro_20_ |
+-----+------------------+-------------+
|   1 | 734152.000000000 |     1005.21 |
|   2 | 734152.006944445 |     1005.26 |
+-----+------------------+-------------+

this is my table

And this is my new table

+-----+------------------+-------------+------------+
| id  | datenum          | F1_baro_20_ |new column  |
+-----+------------------+-------------+------------+
|   1 | 734152.000000000 |     1005.21 |            |
|   2 | 734152.006944445 |     1005.26 |            |
+-----+------------------+-------------+------------+

I want to insert data to the 'new_colum' where old_datenum=new_datenum but I don't wan to modify the existing data!

Body:
update mytable set newcol = 'yourvalhere' where somecol='somevalue';

The Where clause is optional, if you want to add the same value to the entire table ignore it. For more info post an example of your schema and what you want the data to be.

See also

http://dev.mysql.com/doc/refman/5.0/en/update.html


问:
Why does my RSA signing implementation work on some messages, but not on others?
I am trying to implement a simple RSA signature algorithm in C#, by only using BigInteger, and no built-in crypto tools. To sign a message, I encrypt it with the private key, and to verify it, I decrypt it with the public key. In the code below, I have noticed a very strange behavior. For some input strings, (e.g. "Test"), it successfully validates the signature, but for other strings (e.g. "Test1"), it fails.

What I've noticed is, that it only fails, when the m variable (the hash of the message) is a negative number, and this causes the decrypted ver variable to become an extremely large number and the code prints 'Wrong Signature'.

```<code>// Generating RSA keys
var random = new Random();
var p = new BigInteger(256, 100, random);
var q = new BigInteger(256, 100, random);

var n = p.Multiply(q);
var phi = p.Subtract(BigInteger.One).Multiply(q.Subtract(BigInteger.One));

var e = new BigInteger("65537");
var d = e.ModInverse(phi);

// Preparing the message
var messageHash = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("Test"));
var m = new BigInteger(messageHash);

// Signing the message
var signature = m.ModPow(d, n);

// Verifying the message
var ver = signature.ModPow(e, n);

Console.Out.WriteLine(m);
Console.Out.WriteLine(ver);

if(ver.Equals(m))
    Console.Out.WriteLine("Valid Signature");
else
    Console.Out.WriteLine("Wrong Signature");
</code>```

I'm using BouncyCastle for the BigInteger type.

Example output for the message "Test":

```<code>16928957987407306249184430693954511195
16928957987407306249184430693954511195
Valid Signature
</code>```

Example output for the message "Test1":

```<code>-40249184872970767997805928798048797124
10061048024793920770364189111057222210443355984675629704584018449091407182950576678391694061743052292040531884029654111183675927763342349593675935744009443
Wrong Signature
</code>```

I believe that the error is somewhere in the signing process, and not in the verification. Maybe I shouldn't try to encrypt negative numbers? What should I do if the hash is negative? How can I fix this code so it works reliably on any input string?

答:
@Topaco helped me solve my problem.

The RSA algorithm requires 0 <= m < n for a message m and modulus n, here . To prevent negative numbers, var m = new BigInteger(1, messageHash); could be used, which creates the corresponding unsigned value instead of the signed value

Body:
I am trying to implement a simple RSA signature algorithm in C#, by only using BigInteger, and no built-in crypto tools. To sign a message, I encrypt it with the private key, and to verify it, I decrypt it with the public key. In the code below, I have noticed a very strange behavior. For some input strings, (e.g. "Test"), it successfully validates the signature, but for other strings (e.g. "Test1"), it fails.

What I've noticed is, that it only fails, when the m variable (the hash of the message) is a negative number, and this causes the decrypted ver variable to become an extremely large number and the code prints 'Wrong Signature'.

// Generating RSA keys
var random = new Random();
var p = new BigInteger(256, 100, random);
var q = new BigInteger(256, 100, random);

var n = p.Multiply(q);
var phi = p.Subtract(BigInteger.One).Multiply(q.Subtract(BigInteger.One));

var e = new BigInteger("65537");
var d = e.ModInverse(phi);

// Preparing the message
var messageHash = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("Test"));
var m = new BigInteger(messageHash);

// Signing the message
var signature = m.ModPow(d, n);

// Verifying the message
var ver = signature.ModPow(e, n);

Console.Out.WriteLine(m);
Console.Out.WriteLine(ver);

if(ver.Equals(m))
    Console.Out.WriteLine("Valid Signature");
else
    Console.Out.WriteLine("Wrong Signature");

I'm using BouncyCastle for the BigInteger type.

Example output for the message "Test":

16928957987407306249184430693954511195
16928957987407306249184430693954511195
Valid Signature

Example output for the message "Test1":

-40249184872970767997805928798048797124
10061048024793920770364189111057222210443355984675629704584018449091407182950576678391694061743052292040531884029654111183675927763342349593675935744009443
Wrong Signature

I believe that the error is somewhere in the signing process, and not in the verification. Maybe I shouldn't try to encrypt negative numbers? What should I do if the hash is negative? How can I fix this code so it works reliably on any input string?


问:
How to be notified when a VisualElement gets actually visible?
Especially i’m working with a ScrollView.

I’d like to be notified when scrolling passed certain elements

答:
You could get the scrolled by handling the Scrolled event of the ScrollView

```<code><ScrollView  Scrolled="ScrollView_Scrolled" >

</ScrollView>
</code>```

```<code>    private double Position = 0;
    private void ScrollView_Scrolled(object sender, ScrolledEventArgs e)
    {
        var scrollView = sender as ScrollView;

        if (Position < e.ScrollY)
        {
            //scrolled down
            Position = e.ScrollY;

            //do something you want
        }
        else
        {
            //scrolled up

            if (Convert.ToInt16(e.ScrollY) == 0)
                Position = 0;

            //do something you want

        }
    }
</code>```

notifie when scrolling passed certain elements

I don't think we could implement it even in specific platforms . But as a workaround , we could use AbsoluteLayout and lisnten the e.ScrollY to judge if the ScrollView scroll to some specific elements .

Body:
You could get the scrolled by handling the Scrolled event of the ScrollView

<ScrollView  Scrolled="ScrollView_Scrolled" >

</ScrollView>

    private double Position = 0;
    private void ScrollView_Scrolled(object sender, ScrolledEventArgs e)
    {
        var scrollView = sender as ScrollView;

        if (Position < e.ScrollY)
        {
            //scrolled down
            Position = e.ScrollY;

            //do something you want
        }
        else
        {
            //scrolled up

            if (Convert.ToInt16(e.ScrollY) == 0)
                Position = 0;

            //do something you want

        }
    }

notifie when scrolling passed certain elements

I don't think we could implement it even in specific platforms . But as a workaround , we could use AbsoluteLayout and lisnten the e.ScrollY to judge if the ScrollView scroll to some specific elements .


问:
How to save stdout.read() in a csv file?
Guys I am struggling to figure out how to save output of a command I ran to a csv file. Here is the code i have written so far to get the output from a linux host using paramiko modue.

```<code>ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip,port=22,username=user_name,password=passwd)
stdin, stdout, stderr = ssh_client.exec_command("some random command")
output = (stdout.read().decode(encoding='ascii'))
print(output)
</code>```

This is the output I get:

```<code>Lun VV_WWN                           VVName                   HostName
1 600525465446418gsdhgdfhahf14488454 HOST-California_westcos domain123
9 600525465446418gsdhgdfhahf14488454 HOST-Texas_westcos      domain123
4 600525465446418gsdhgdfhahf14488454 HOST-Kasnsas_westcos    domain123
4 600525465446418gsdhgdfhahf14488454 HOST-Ohio_westcos       domain123
7 600525465446418gsdhgdfhahf14488454 HOST-Nevada_westcos     domain123
---------------------------------------------------------------------------
5                                                  total
</code>```

I need to remove header and footer and save this file as CSV. Any suggestion on how can i achieve this.
I would really appreciate the help.

答:
This worked for me</p>

```<code>import csv
split = output.split('\n')
keep = split[1:-3]
word_split = [k.split() for k in keep]
with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(word_split)
</code>```

Body:
Guys I am struggling to figure out how to save output of a command I ran to a csv file. Here is the code i have written so far to get the output from a linux host using paramiko modue.

ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip,port=22,username=user_name,password=passwd)
stdin, stdout, stderr = ssh_client.exec_command("some random command")
output = (stdout.read().decode(encoding='ascii'))
print(output)

This is the output I get:

Lun VV_WWN                           VVName                   HostName
1 600525465446418gsdhgdfhahf14488454 HOST-California_westcos domain123
9 600525465446418gsdhgdfhahf14488454 HOST-Texas_westcos      domain123
4 600525465446418gsdhgdfhahf14488454 HOST-Kasnsas_westcos    domain123
4 600525465446418gsdhgdfhahf14488454 HOST-Ohio_westcos       domain123
7 600525465446418gsdhgdfhahf14488454 HOST-Nevada_westcos     domain123
---------------------------------------------------------------------------
5                                                  total

I need to remove header and footer and save this file as CSV. Any suggestion on how can i achieve this.
I would really appreciate the help.

Body:
This worked for me

import csv
split = output.split('\n')
keep = split[1:-3]
word_split = [k.split() for k in keep]
with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(word_split)


问:
How to get a non-English Character in C++
I have a string like that "tỏa" and how to I get the character "ỏ" as a string?
When I print string[1], it displayed � not "ỏ".

Thank in advance. I hope you will help me to solve that problem.

答: Have a look at: http://www.cplusplus.com/forum/general/77234/ it nicely explains how to do it.</p>