问:
How to copy files between S3 buckets in 2 different accounts using boto3
I'm trying to files from a vendors S3 bucket to my S3 bucket using boto3. I'm using the sts service to assume a role to access the vendor s3 bucket. I'm able to connect to the vendor bucket and get a listing of the bucket. I run into CopyObject operation: Access Denied error when copying to my bucket. Here is my script

```<code>session = boto3.session.Session(profile_name="s3_transfer")
sts_client = session.client("sts", verify=False)
assumed_role_object = sts_client.assume_role(
    RoleArn="arn:aws:iam::<accountid>:role/assumedrole",
    RoleSessionName="transfer_session",
    ExternalId="<ID>",
    DurationSeconds=18000,
)

creds = assumed_role_object["Credentials"]
src_s3 = boto3.client(
    "s3",
    aws_access_key_id=creds["AccessKeyId"],
    aws_secret_access_key=creds["SecretAccessKey"],
    aws_session_token=creds["SessionToken"],
    verify=False,
)
paginator =src_s3.get_paginator("list_objects_v2")
# testing with just 2 items.
# TODO: Remove MaxItems once script works.
pages = paginator.paginate(
    Bucket="ven_bucket", Prefix="client", PaginationConfig={"MaxItems": 2, "PageSize": 1000}
)
dest_s3 = session.client("s3", verify=False)
for page in pages:
    for obj in page["Contents"]:
        src_key = obj["Key"]
        des_key = dest_prefix + src_key[len(src_prefix) :]
        src = {"Bucket": "ven_bucket", "Key": src_key}
        print(src)
        print(des_key)
        dest_s3.copy(src, "my-bucket", des_key, SourceClient=src_s3)
</code>```

The line dest_s3.copy... is where I get the error. I have the following policy of my aws user to allow copy to my bucket

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

I get the following error when running the above script.

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

答:
The CopyObject() command can be used to copy objects between buckets without having to upload/download. Basically, the two S3 buckets communicate with each other and transfer the data.

This command can also be used to copy between buckets that in different regions and different AWS accounts.

If you wish to copy between buckets that belong to different AWS accounts, then you will need to use a single set of credentials that have:

GetObject permission on the source bucket

PutObject permission on the destination bucket

Also, please note that the CopyObject() command is sent to the destination account. The destination bucket effectively pulls the objects from the source bucket.

From your description, your code is assuming a role from the other account to gain read permission on the source bucket. Unfortunately, this is not sufficient for the CopyObject() command because the command must be sent to the destination bucket. (Yes, it is a little hard to discern this from the documentation. That is why the source bucket is specifically named, rather than the destination bucket.)

Therefore, in your situation, to be able to copy the objects, you will need to use a set of credentials from Account-B (the destination) that also has permission to read from Bucket-A (the source). This will require the vendor to modify the Bucket Policy associated with Bucket-A.

If they do not wish to do this, then your only option is to download the objects using the assumed role and then separately upload the files to your own bucket using credentials from your own Account-B.

Body:
I'm trying to files from a vendors S3 bucket to my S3 bucket using boto3. I'm using the sts service to assume a role to access the vendor s3 bucket. I'm able to connect to the vendor bucket and get a listing of the bucket. I run into CopyObject operation: Access Denied error when copying to my bucket. Here is my script

session = boto3.session.Session(profile_name="s3_transfer")
sts_client = session.client("sts", verify=False)
assumed_role_object = sts_client.assume_role(
    RoleArn="arn:aws:iam::<accountid>:role/assumedrole",
    RoleSessionName="transfer_session",
    ExternalId="<ID>",
    DurationSeconds=18000,
)

creds = assumed_role_object["Credentials"]
src_s3 = boto3.client(
    "s3",
    aws_access_key_id=creds["AccessKeyId"],
    aws_secret_access_key=creds["SecretAccessKey"],
    aws_session_token=creds["SessionToken"],
    verify=False,
)
paginator =src_s3.get_paginator("list_objects_v2")
# testing with just 2 items.
# TODO: Remove MaxItems once script works.
pages = paginator.paginate(
    Bucket="ven_bucket", Prefix="client", PaginationConfig={"MaxItems": 2, "PageSize": 1000}
)
dest_s3 = session.client("s3", verify=False)
for page in pages:
    for obj in page["Contents"]:
        src_key = obj["Key"]
        des_key = dest_prefix + src_key[len(src_prefix) :]
        src = {"Bucket": "ven_bucket", "Key": src_key}
        print(src)
        print(des_key)
        dest_s3.copy(src, "my-bucket", des_key, SourceClient=src_s3)

The line dest_s3.copy... is where I get the error. I have the following policy of my aws user to allow copy to my bucket

{
    "Version": "2012-10-17",
   "Statement": [
    {
        "Sid": "VisualEditor1",
        "Effect": "Allow",
        "Action": [
            "s3:*"
        ],
        "Resource": [
            "arn:aws:s3:::my-bucket/*",
            "arn:aws:s3:::my-bucket/"
        ]
    }
    ]
}

I get the following error when running the above script.

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


来源: stackexchange

问:
Problem with gcc -c parameter and set an outfile
I've a question about GCC and objects file..

In few words when I try to do this command:

```<code>gcc -Wall -o obj/config.o -c global.h config/config.c
</code>```

It's simply returns this fatal error:

```<code>gcc: fatal error: cannot specify -o with -c, -S or -E with multiple files
</code>```

I've tried to search on Google, but I've not found anything about it.
Maybe I used wrong keywords...
Anyone can help?

答:
.h header files don't get directly compiled, only .c source files. Get rid of global.h.

```<code>gcc -Wall -o obj/config.o -c config/config.c
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've a question about GCC and objects file..

In few words when I try to do this command:

gcc -Wall -o obj/config.o -c global.h config/config.c

It's simply returns this fatal error:

gcc: fatal error: cannot specify -o with -c, -S or -E with multiple files

I've tried to search on Google, but I've not found anything about it.
Maybe I used wrong keywords...
Anyone can help?

Body:
.h header files don't get directly compiled, only .c source files. Get rid of global.h.

gcc -Wall -o obj/config.o -c config/config.c


问:
"Bidirectional" type projection / variance in Kotlin?
Let's say we have a class hierarchy like Pug : Dog : Mammal : Animal.

I want a function that accepts a Bag<T> (where Bag is invariant in T) argument of things that are sub OR superclasses of Dog: fun work(things: Bag<in/out Dog) Such that Bag<Animal>, Bag<Dog>, Bag<Pug> is OK, but Bag<Cat> is NOT accepted.

Honestly, I'm not even sure what that type of projection is called. Any pointers?

答:
Honestly, I'm not even sure what that type of projection is called. Any pointers?

Sounds to me that what you need is to use Interfaces, by creating an Interface where you define your work method. This is good, as it adheres to the Composition over Inheritance principle.

After that, have the classes you want to use it implement the interface (say, class Dog : Mammal(), WorkInterface), and don't implement it in the ones you don't want/need to use work.

Also, have them override the work method. That way you will be able to call the work method on the instances of your objects when you want it. For example, your code should look something like this:

The WorkInterface interface:

```<code>interface WorkInterface{
    fun work(foo:String)    //add the parameters you need
}
</code>```

Using the interface on a class like Dog:

```<code>//implementing and extending are done the same way in Kotlin, after the colon
class Dog : Mammal(), WorkInterface{
    //define your attributes, methods etc..

    //override all the methods defined in the interface
    override fun work(foo: String){
        //implement the specific code you want this to do
    }
}
</code>```

After which you can use on your Dog instance like myDog.work("whatever").

Body:
Honestly, I'm not even sure what that type of projection is called. Any pointers?

Sounds to me that what you need is to use Interfaces, by creating an Interface where you define your work method. This is good, as it adheres to the Composition over Inheritance principle.

After that, have the classes you want to use it implement the interface (say, class Dog : Mammal(), WorkInterface), and don't implement it in the ones you don't want/need to use work.

Also, have them override the work method. That way you will be able to call the work method on the instances of your objects when you want it. For example, your code should look something like this:

The WorkInterface interface:

interface WorkInterface{
    fun work(foo:String)    //add the parameters you need
}

Using the interface on a class like Dog:

//implementing and extending are done the same way in Kotlin, after the colon
class Dog : Mammal(), WorkInterface{
    //define your attributes, methods etc..

    //override all the methods defined in the interface
    override fun work(foo: String){
        //implement the specific code you want this to do
    }
}

After which you can use on your Dog instance like myDog.work("whatever").


问:
Accessing "file" structure from user space
In reference to linux kernel, I would like to access the "file" structure information like current file offset in a user space C program. How do I do it?

Thanks in advance

答: You cannot access kernel structures in userspace.</p>

ContentLicense: CC BY-SA 3.0


问:
Invalid argument supplied for foreach() in WooCommerce
I have a small problem, I am modifying the tab structure of My Account in WooCommerce and I want to link 'Addresses' with 'Account details' and the problem occurs with 'Addresses' when I try to print the fields of that tab in 'Account Details' occurs:

```<code>Warning: Invalid argument supplied for foreach () in C: \ xampp \ htdocs \ wp-content \ plugins \ woocommerce \ templates \ myaccount \ form-edit-address.php on line 34
</code>```

And this is the error code:

```<code><?php
foreach ($address as $key => $field) { // **line 34**
woocommerce_form_field ($key, $field, wc_get_post_data_by_key ($key, $field ['value']));
}
?>
</code>```

Do a var_dump where it throws NULL. Seeing all this, I tried to modify the function in class-wc-shortcode-my-account.php where I do not achieve my goal. I have thought that there is some limitation so that the array is only available in that template; I do not know if I'm right and what I found in wc-template-functions.php was:

```<code>function woocommerce_account_edit_address( $type ) {
        $type = wc_edit_address_i18n( sanitize_title( $type ), true );

        WC_Shortcode_My_Account::edit_address( $type );
    }
}
</code>```

How can I print the array $address in a custom tab? Thanks!

UPGRADE:

One of my attempts is to include the file form-edit-address.php in form-edit-account.php

```<code><?php
include("form-edit-address.php");
?>
</code>```

Another attempt was to copy the contents of the form-edit-address.php file into the form-edit-account. Also try to place the global $ address and $ load-address variables without any effect:

```<code>public static function edit_address( $load_address = 'billing' ) {
        $current_user = wp_get_current_user();
        global $load_address;
        $load_address = sanitize_key( $load_address );
        $country      = get_user_meta( get_current_user_id(), $load_address . '_country', true );

        if ( ! $country ) {
            $country = WC()->countries->get_base_country();
        }

        if ( 'billing' === $load_address ) {
            $allowed_countries = WC()->countries->get_allowed_countries();

            if ( ! array_key_exists( $country, $allowed_countries ) ) {
                $country = current( array_keys( $allowed_countries ) );
            }
        }

        if ( 'shipping' === $load_address ) {
            $allowed_countries = WC()->countries->get_shipping_countries();

            if ( ! array_key_exists( $country, $allowed_countries ) ) {
                $country = current( array_keys( $allowed_countries ) );
            }
        }

        global $address;

        $address = WC()->countries->get_address_fields( $country, $load_address . '_' );

        // Enqueue scripts.
        wp_enqueue_script( 'wc-country-select' );
        wp_enqueue_script( 'wc-address-i18n' );

        // Prepare values.
        foreach ( $address as $key => $field ) {

            $value = get_user_meta( get_current_user_id(), $key, true );

            if ( ! $value ) {
                switch ( $key ) {
                    case 'billing_email':
                    case 'shipping_email':
                        $value = $current_user->user_email;
                        break;
                }
            }

            $address[ $key ]['value'] = apply_filters( 'woocommerce_my_account_edit_address_field_value', $value, $key, $load_address );
        }

        wc_get_template(
            'myaccount/form-edit-address.php',
            array(
                'load_address' => $load_address,
                'address'      => apply_filters( 'woocommerce_address_to_edit', $address, $load_address ),
            )
        );
    }
</code>```

答:
I would need to look at your code closer but I am guessing that the issues it the way you are typing your variables.

Try $address instead of $ address

Body:
I have a small problem, I am modifying the tab structure of My Account in WooCommerce and I want to link 'Addresses' with 'Account details' and the problem occurs with 'Addresses' when I try to print the fields of that tab in 'Account Details' occurs:

Warning: Invalid argument supplied for foreach () in C: \ xampp \ htdocs \ wp-content \ plugins \ woocommerce \ templates \ myaccount \ form-edit-address.php on line 34

And this is the error code:

<?php
foreach ($address as $key => $field) { // **line 34**
woocommerce_form_field ($key, $field, wc_get_post_data_by_key ($key, $field ['value']));
}
?>

Do a var_dump where it throws NULL. Seeing all this, I tried to modify the function in class-wc-shortcode-my-account.php where I do not achieve my goal. I have thought that there is some limitation so that the array is only available in that template; I do not know if I'm right and what I found in wc-template-functions.php was:

function woocommerce_account_edit_address( $type ) {
        $type = wc_edit_address_i18n( sanitize_title( $type ), true );

        WC_Shortcode_My_Account::edit_address( $type );
    }
}

How can I print the array $address in a custom tab? Thanks!

UPGRADE:

One of my attempts is to include the file form-edit-address.php in form-edit-account.php

<?php
include("form-edit-address.php");
?>

Another attempt was to copy the contents of the form-edit-address.php file into the form-edit-account. Also try to place the global $ address and $ load-address variables without any effect:

public static function edit_address( $load_address = 'billing' ) {
        $current_user = wp_get_current_user();
        global $load_address;
        $load_address = sanitize_key( $load_address );
        $country      = get_user_meta( get_current_user_id(), $load_address . '_country', true );

        if ( ! $country ) {
            $country = WC()->countries->get_base_country();
        }

        if ( 'billing' === $load_address ) {
            $allowed_countries = WC()->countries->get_allowed_countries();

            if ( ! array_key_exists( $country, $allowed_countries ) ) {
                $country = current( array_keys( $allowed_countries ) );
            }
        }

        if ( 'shipping' === $load_address ) {
            $allowed_countries = WC()->countries->get_shipping_countries();

            if ( ! array_key_exists( $country, $allowed_countries ) ) {
                $country = current( array_keys( $allowed_countries ) );
            }
        }

        global $address;

        $address = WC()->countries->get_address_fields( $country, $load_address . '_' );

        // Enqueue scripts.
        wp_enqueue_script( 'wc-country-select' );
        wp_enqueue_script( 'wc-address-i18n' );

        // Prepare values.
        foreach ( $address as $key => $field ) {

            $value = get_user_meta( get_current_user_id(), $key, true );

            if ( ! $value ) {
                switch ( $key ) {
                    case 'billing_email':
                    case 'shipping_email':
                        $value = $current_user->user_email;
                        break;
                }
            }

            $address[ $key ]['value'] = apply_filters( 'woocommerce_my_account_edit_address_field_value', $value, $key, $load_address );
        }

        wc_get_template(
            'myaccount/form-edit-address.php',
            array(
                'load_address' => $load_address,
                'address'      => apply_filters( 'woocommerce_address_to_edit', $address, $load_address ),
            )
        );
    }


问:
is it posible to run asynchronous python script in a typescript style
At the moment I have a python script that makes an http request to a microservice. The request takes 3s on average.

This is my python script in a summarized way.

def main():
  response = request_to_MS(url)

  # This process does not need the response of the microservice.
  some_process()

  # This is where i actually need a response from the microservice
  do_something_with_response(response)

main()
```

<p>I would like my script to be able to continue with the code and wait for the request response later similar to typescript.</p>

<pre class="lang-js prettyprint-override"><code>/**
 * I'd like to write this kind of code in python.
 */
function get_data(): Promise<string>{
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('This is resolved');
    })
  })
}

async function main(){
  const data = get_data();
  console.log('Data variable stores my promise ', data);
  // Some process
  [1, 2, 3, 4, 5, 6 ,7 ,8].forEach((x: number) => console.log(x));
  // I need the promise value here
  console.log('En el await', (await data).length)
}

void main();
</code>```

Basically what I am looking for is that the time it takes to complete the execution of the process and the response time of the microservice overlap, allowing a better response time in total.

答:
Make request_to_MS(url) an async def co-routine, schedule it as a task with response = asyncio.create_task(request_to_MS(url)).

It will begin executing. Now you can continue to run some_process().  When you need response, simply do

do_something_with_response(await response)
```

<p>edit: The above will only work if main is also an <code>async def</code>, as you can only use <code>await</code>s in an async function. Instead of calling <code>main()</code>, call <code>asyncio.run(main())</code>.</p>

<p>Altogether:</p>

<pre class="lang-py prettyprint-override"><code>async def request_to_MS(url):
    await asyncio.sleep(3)
    return 'some internet data'

async def main():
    response = asyncio.create_task(request_to_MS(url))
    # response is now a Task

    some_process()

    # if response isn't done running yet, this line will block until it is
    do_something_with_response(await response)

asyncio.run(main())
</code>```

An important caveat, some_process doesn't have to be a coroutine, but if it is a blocking function (either by CPU or IO) it will never yield any cycles to let response run. If it blocks via IO, consider making it a coroutine as well. If there is no async support for whatever low-level IO operations it performs, or if it is CPU bound, consider using asyncio's run_in_executor.

Body:
At the moment I have a python script that makes an http request to a microservice. The request takes 3s on average.

This is my python script in a summarized way.

def main():
  response = request_to_MS(url)

  # This process does not need the response of the microservice.
  some_process()

  # This is where i actually need a response from the microservice
  do_something_with_response(response)

main()

I would like my script to be able to continue with the code and wait for the request response later similar to typescript.

/**
 * I'd like to write this kind of code in python.
 */
function get_data(): Promise<string>{
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('This is resolved');
    })
  })
}

async function main(){
  const data = get_data();
  console.log('Data variable stores my promise ', data);
  // Some process
  [1, 2, 3, 4, 5, 6 ,7 ,8].forEach((x: number) => console.log(x));
  // I need the promise value here
  console.log('En el await', (await data).length)
}

void main();

Basically what I am looking for is that the time it takes to complete the execution of the process and the response time of the microservice overlap, allowing a better response time in total.

Body:
Make request_to_MS(url) an async def co-routine, schedule it as a task with response = asyncio.create_task(request_to_MS(url)).

It will begin executing. Now you can continue to run some_process().  When you need response, simply do

do_something_with_response(await response)

edit: The above will only work if main is also an async def, as you can only use awaits in an async function. Instead of calling main(), call asyncio.run(main()).

Altogether:

async def request_to_MS(url):
    await asyncio.sleep(3)
    return 'some internet data'

async def main():
    response = asyncio.create_task(request_to_MS(url))
    # response is now a Task

    some_process()

    # if response isn't done running yet, this line will block until it is
    do_something_with_response(await response)

asyncio.run(main())

An important caveat, some_process doesn't have to be a coroutine, but if it is a blocking function (either by CPU or IO) it will never yield any cycles to let response run. If it blocks via IO, consider making it a coroutine as well. If there is no async support for whatever low-level IO operations it performs, or if it is CPU bound, consider using asyncio's run_in_executor.


问:
Change your "From Email" in Gmail
I receive forwarded emails from an email like info@companyname.com to my Gmail account; when I respond to these emails, I want they look as if they came from info@companyname.com instead of my Gmail account.

Is this possible?

答:
Not really a question for Stack Overflow, but have a look here:

http://gmailblog.blogspot.com/2009/07/send-mail-from-another-address-without.html

It's a post on the official GMAIL blog outlining how to send via an external SMTP host.

Title: Change your "From Email" in Gmail


问:
Linux $PATH is different for the same user, depending on how it is accessed
I have a php script running in a cronjob on the server.

However, I am unexpectedly getting different $PATH from the same user, depending on how I execute the command.

I log in as user ubuntu:

```<code>ubuntu@:$ echo $PATH
/home/ubuntu/bin:/home/ubuntu/.local/bin:/home/ubuntu/.nvm/versions/node/v12.3.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
</code>```

I then sudo su bitbucket:

```<code>bitbucket@:$ echo $PATH
/home/bitbucket/.nvm/versions/node/v12.3.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
</code>```

I execute a script from a cronjob running as bitbucket and output the following debug to a log file:

```<code>$ whoami
bitbucket
</code>```

The above proves the user is bitbucket, then:

```<code>$ echo $PATH
/usr/bin:/bin
</code>```

Please note I am not running as sudo. I am utilising sudo to switch user, but not using sudo to echo $PATH.

How is it that the same user has 2 different $PATH variables?

答:
You didn't say which shell you're using so I'm going to assume it's bash. The first, and perhaps most important, thing to note is that when you run sudo su bitbucket you're getting an interactive shell. Which means that ~/.bashrc will be sourced. Lots of people modify PATH in that script. Something that tends to cause problems. Why? Because non-interactive shells, such as the one launched by cron to run your command, won't read ~/.bashrc.

Your cron job gets a PATH equivalent to running this command: sudo su bitbucket -c 'echo $PATH'. Play around with that to get a better understanding of how this works. For example, instead of echo $PATH try env.

Body:
I have a php script running in a cronjob on the server.

However, I am unexpectedly getting different $PATH from the same user, depending on how I execute the command.

I log in as user ubuntu:

ubuntu@:$ echo $PATH
/home/ubuntu/bin:/home/ubuntu/.local/bin:/home/ubuntu/.nvm/versions/node/v12.3.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

I then sudo su bitbucket:

bitbucket@:$ echo $PATH
/home/bitbucket/.nvm/versions/node/v12.3.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

I execute a script from a cronjob running as bitbucket and output the following debug to a log file:

$ whoami
bitbucket

The above proves the user is bitbucket, then:

$ echo $PATH
/usr/bin:/bin

Please note I am not running as sudo. I am utilising sudo to switch user, but not using sudo to echo $PATH.

How is it that the same user has 2 different $PATH variables?


问:
Filter by all ids in an array
I have two models, both with a has_and_belongs_to_many relationship.

class Movie < ApplicationRecord
  has_and_belongs_to_many :genres
end
```

<pre class="lang-rb prettyprint-override"><code>class Genre < ApplicationRecord
  has_and_belongs_to_many :movies
end
</code>```

So for example on the Movie index page, I want to be able to filter by Genre. For the filter form, I have a multi-select box of genres that when submitted sends an array of ids.

How would I find Movies that match ALL of those ids in the array instead of just any of the ids using Active Record? If a user selects for example, horror and comedy, it should filter down to movies that are both horror and comedy, not just any horror or any comedy.

ids = params[:genres]
Movie.includes(:genres).where(genres: {id: ids})
```

The above example finds any movie that is either horror or comedy.

答:
Figured it out by using joins with group and having.

ids = params[:genres]

Movie.joins(:genres)
  .where(genres: {id: ids})
  .group(:id)
  .having("count(*) = #{ids.count}")
```

This will basically filter down the duplicate matches, and return only the movies that have the same amount of results as the original array count. Meaning if the array count is 3, only movies that have 3 results from the original joins query will match.

Title: Filter by all ids in an array

Body:
I have two models, both with a has_and_belongs_to_many relationship.

class Movie < ApplicationRecord
  has_and_belongs_to_many :genres
end

class Genre < ApplicationRecord
  has_and_belongs_to_many :movies
end

So for example on the Movie index page, I want to be able to filter by Genre. For the filter form, I have a multi-select box of genres that when submitted sends an array of ids.

How would I find Movies that match ALL of those ids in the array instead of just any of the ids using Active Record? If a user selects for example, horror and comedy, it should filter down to movies that are both horror and comedy, not just any horror or any comedy.

ids = params[:genres]
Movie.includes(:genres).where(genres: {id: ids})

The above example finds any movie that is either horror or comedy.

Body:
Figured it out by using joins with group and having.

ids = params[:genres]

Movie.joins(:genres)
  .where(genres: {id: ids})
  .group(:id)
  .having("count(*) = #{ids.count}")

This will basically filter down the duplicate matches, and return only the movies that have the same amount of results as the original array count. Meaning if the array count is 3, only movies that have 3 results from the original joins query will match.


问:
Can we insert a row in a table with default values in each column using SSIS?
I am not sure if my question will find any solution and after searching I could not find a workaround.

SCENARIO:
I am developing a batch solution using SSIS. Which reads a query in data flow task. The query produces some row as result and I simply need to insert that result into destination table (in MS SQL Server database).

CHALLENGE

The challenge I see here is even if the SQL query does not produce any row, the destination table should be filled with default row. But with CTE produced in below query and in SSIS it doesn't seem to be that easy.

SQL Query plugged in SSIS OLE DB SOURCE EDITOR.

```<code>DECLARE @date DATE
SET @date = GETDATE();

with cte as
(
select
   T.mot_fleettypedescription AS 'FleetType'
   ,(CASE WHEN F.mot_averagefleetsize = 0 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_0'
   ,(CASE WHEN F.mot_averagefleetsize = 1 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_1'
   ,(CASE WHEN F.mot_averagefleetsize BETWEEN 2 AND 4 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_2-4'
   ,(CASE WHEN F.mot_averagefleetsize BETWEEN 5 AND 10 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_5-10'
   ,CONVERT(DATE, C.mot_monthenddate) AS 'MED'
from Filteredmot_carrierfleettypes F
left outer join Filteredmot_carrierfleettype T on F.mot_fleettype = T.mot_carrierfleettypeid
left outer join Filteredmot_fleetcount C on F.mot_carriernumber = C.mot_carriernumber
where F.statecode = 0 AND C.mot_monthenddate = CONVERT(DATE, DATEADD(D,-(DAY(@date)), @date))
group by F.mot_averagefleetsize, T.mot_fleettypedescription, C.mot_monthenddate
)

select
    CONVERT(NVARCHAR(50), 'by Weight') AS 'Caption', cte.MED AS 'Date', CONVERT(NVARCHAR(10), cte.FleetType) AS 'FleetType',
    CONVERT(NVARCHAR(25), 'ALL') AS 'OperatingStatus',
    SUM(cte.Fleet_Range_0) As 'Fleet_Range_0', SUM(cte.Fleet_Range_1) As 'Fleet_Range_1', SUM(cte.[Fleet_Range_2-4]) 'Fleet_Range_2-4',
    SUM(cte.[Fleet_Range_5-10]) 'Fleet_Range_5-10',
    (SUM(cte.Fleet_Range_0) + SUM(cte.Fleet_Range_1) + SUM(cte.[Fleet_Range_2-4]) + SUM(cte.[Fleet_Range_5-10])) 'TOTAL'
from cte
where cte.FleetType = 'Bus'
group by cte.FleetType, cte.MED
</code>```

RESEARCH
If it was pure SQL server environment, I would have checked for number of rows returned using COUNT(*) or @@ROWCOUNT with below query segment. But I am not sure how to blend this part with above actual query in SSIS.

```<code>DECLARE @CntOfRow INT;
select @CntOfRow = @@ROWCOUNT
--select @CntOfRow as 'Numrow'
if(@CntOfRow = 0)
begin
    if object_id ('tempdb..#Bus') is not null
    begin
        drop table #Bus
    end
    if object_id ('tempdb..#Bus') is null
    begin
        create table #Bus(
            Caption varchar(20), [Date] date, FleetType varchar(10), OperatingStatus varchar(25),
            Fleet_Range_0 int null, Fleet_Range_1 int null, [Fleet_Range_2-4] int null, [Fleet_Range_5-10] int null, TOTAL int null
        )
        insert into #Bus(Caption,[Date],FleetType,OperatingStatus, Fleet_Range_0,Fleet_Range_1,[Fleet_Range_2-4],[Fleet_Range_5-10],TOTAL)
        values('by Weight', CONVERT(DATE, DATEADD(D,-(DAY(@date)), @date)), 'Bus', 'ALL',0,0,0,0,0)
    end
    select * from #Bus
end
</code>```

INVESTIGATION

I looked into SSIS components like Row Count and Conditional Split in a way to first get the count of row following source query and then apply conditional split to further insert the retrieved result in destination table. But after conditional split I am not sure how to generate a temporary table and insert a row with default values to further insert it to destination table.

I am also exploring the Execute SQL Task in control flow to see if I can shift logic to generate default row there and pass that row in DFT to insert into destination table.

Any insight to this scenario is very much appreciated.

SNAPSHOT OF RESOLUTION

答:
You can use a complex SQL command in the OLEDB Source, try inserting data into a temp table, then check if the temp table doesn't contains rows insert default values. At the end select all rows from the temp table.

DECLARE @date DATE
SET @date = GETDATE();

with cte as
(
select
   T.mot_fleettypedescription AS 'FleetType'
   ,(CASE WHEN F.mot_averagefleetsize = 0 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_0'
   ,(CASE WHEN F.mot_averagefleetsize = 1 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_1'
   ,(CASE WHEN F.mot_averagefleetsize BETWEEN 2 AND 4 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_2-4'
   ,(CASE WHEN F.mot_averagefleetsize BETWEEN 5 AND 10 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_5-10'
   ,CONVERT(DATE, C.mot_monthenddate) AS 'MED'
from Filteredmot_carrierfleettypes F
left outer join Filteredmot_carrierfleettype T on F.mot_fleettype = T.mot_carrierfleettypeid
left outer join Filteredmot_fleetcount C on F.mot_carriernumber = C.mot_carriernumber
where F.statecode = 0 AND C.mot_monthenddate = CONVERT(DATE, DATEADD(D,-(DAY(@date)), @date))
group by F.mot_averagefleetsize, T.mot_fleettypedescription, C.mot_monthenddate
)
insert into #Bus(Caption,[Date],FleetType,OperatingStatus, Fleet_Range_0,Fleet_Range_1,[Fleet_Range_2-4],[Fleet_Range_5-10],TOTAL)
select
    CONVERT(NVARCHAR(50), 'by Weight') AS 'Caption', cte.MED AS 'Date', CONVERT(NVARCHAR(10), cte.FleetType) AS 'FleetType',
    CONVERT(NVARCHAR(25), 'ALL') AS 'OperatingStatus',
    SUM(cte.Fleet_Range_0) As 'Fleet_Range_0', SUM(cte.Fleet_Range_1) As 'Fleet_Range_1', SUM(cte.[Fleet_Range_2-4]) 'Fleet_Range_2-4',
    SUM(cte.[Fleet_Range_5-10]) 'Fleet_Range_5-10',
    (SUM(cte.Fleet_Range_0) + SUM(cte.Fleet_Range_1) + SUM(cte.[Fleet_Range_2-4]) + SUM(cte.[Fleet_Range_5-10])) 'TOTAL'
from cte
where cte.FleetType = 'Bus'
group by cte.FleetType, cte.MED

DECLARE @Count INT
SELECT @Count = Count(*) FROM #Bus

If @Count = 0
insert into #Bus(Caption,[Date],FleetType,OperatingStatus, Fleet_Range_0,Fleet_Range_1,[Fleet_Range_2-4],[Fleet_Range_5-10],TOTAL)
values('by Weight', CONVERT(DATE, DATEADD(D,-(DAY(@date)), @date)), 'Bus', 'ALL',0,0,0,0,0)

SELECT * FROM #Bus
```

If it doesn't works, try implementing this within a stored procedure

Body:
I am not sure if my question will find any solution and after searching I could not find a workaround.

SCENARIO:
I am developing a batch solution using SSIS. Which reads a query in data flow task. The query produces some row as result and I simply need to insert that result into destination table (in MS SQL Server database).

CHALLENGE

The challenge I see here is even if the SQL query does not produce any row, the destination table should be filled with default row. But with CTE produced in below query and in SSIS it doesn't seem to be that easy.

SQL Query plugged in SSIS OLE DB SOURCE EDITOR.

DECLARE @date DATE
SET @date = GETDATE();

with cte as
(
select
   T.mot_fleettypedescription AS 'FleetType'
   ,(CASE WHEN F.mot_averagefleetsize = 0 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_0'
   ,(CASE WHEN F.mot_averagefleetsize = 1 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_1'
   ,(CASE WHEN F.mot_averagefleetsize BETWEEN 2 AND 4 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_2-4'
   ,(CASE WHEN F.mot_averagefleetsize BETWEEN 5 AND 10 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_5-10'
   ,CONVERT(DATE, C.mot_monthenddate) AS 'MED'
from Filteredmot_carrierfleettypes F
left outer join Filteredmot_carrierfleettype T on F.mot_fleettype = T.mot_carrierfleettypeid
left outer join Filteredmot_fleetcount C on F.mot_carriernumber = C.mot_carriernumber
where F.statecode = 0 AND C.mot_monthenddate = CONVERT(DATE, DATEADD(D,-(DAY(@date)), @date))
group by F.mot_averagefleetsize, T.mot_fleettypedescription, C.mot_monthenddate
)

select
    CONVERT(NVARCHAR(50), 'by Weight') AS 'Caption', cte.MED AS 'Date', CONVERT(NVARCHAR(10), cte.FleetType) AS 'FleetType',
    CONVERT(NVARCHAR(25), 'ALL') AS 'OperatingStatus',
    SUM(cte.Fleet_Range_0) As 'Fleet_Range_0', SUM(cte.Fleet_Range_1) As 'Fleet_Range_1', SUM(cte.[Fleet_Range_2-4]) 'Fleet_Range_2-4',
    SUM(cte.[Fleet_Range_5-10]) 'Fleet_Range_5-10',
    (SUM(cte.Fleet_Range_0) + SUM(cte.Fleet_Range_1) + SUM(cte.[Fleet_Range_2-4]) + SUM(cte.[Fleet_Range_5-10])) 'TOTAL'
from cte
where cte.FleetType = 'Bus'
group by cte.FleetType, cte.MED

RESEARCH
If it was pure SQL server environment, I would have checked for number of rows returned using COUNT(*) or @@ROWCOUNT with below query segment. But I am not sure how to blend this part with above actual query in SSIS.

DECLARE @CntOfRow INT;
select @CntOfRow = @@ROWCOUNT
--select @CntOfRow as 'Numrow'
if(@CntOfRow = 0)
begin
    if object_id ('tempdb..#Bus') is not null
    begin
        drop table #Bus
    end
    if object_id ('tempdb..#Bus') is null
    begin
        create table #Bus(
            Caption varchar(20), [Date] date, FleetType varchar(10), OperatingStatus varchar(25),
            Fleet_Range_0 int null, Fleet_Range_1 int null, [Fleet_Range_2-4] int null, [Fleet_Range_5-10] int null, TOTAL int null
        )
        insert into #Bus(Caption,[Date],FleetType,OperatingStatus, Fleet_Range_0,Fleet_Range_1,[Fleet_Range_2-4],[Fleet_Range_5-10],TOTAL)
        values('by Weight', CONVERT(DATE, DATEADD(D,-(DAY(@date)), @date)), 'Bus', 'ALL',0,0,0,0,0)
    end
    select * from #Bus
end

INVESTIGATION

I looked into SSIS components like Row Count and Conditional Split in a way to first get the count of row following source query and then apply conditional split to further insert the retrieved result in destination table. But after conditional split I am not sure how to generate a temporary table and insert a row with default values to further insert it to destination table.

I am also exploring the Execute SQL Task in control flow to see if I can shift logic to generate default row there and pass that row in DFT to insert into destination table.

Any insight to this scenario is very much appreciated.

SNAPSHOT OF RESOLUTION

Body:
You can use a complex SQL command in the OLEDB Source, try inserting data into a temp table, then check if the temp table doesn't contains rows insert default values. At the end select all rows from the temp table.

DECLARE @date DATE
SET @date = GETDATE();

with cte as
(
select
   T.mot_fleettypedescription AS 'FleetType'
   ,(CASE WHEN F.mot_averagefleetsize = 0 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_0'
   ,(CASE WHEN F.mot_averagefleetsize = 1 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_1'
   ,(CASE WHEN F.mot_averagefleetsize BETWEEN 2 AND 4 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_2-4'
   ,(CASE WHEN F.mot_averagefleetsize BETWEEN 5 AND 10 THEN COUNT(C.mot_nscweight) ELSE 0 END) AS 'Fleet_Range_5-10'
   ,CONVERT(DATE, C.mot_monthenddate) AS 'MED'
from Filteredmot_carrierfleettypes F
left outer join Filteredmot_carrierfleettype T on F.mot_fleettype = T.mot_carrierfleettypeid
left outer join Filteredmot_fleetcount C on F.mot_carriernumber = C.mot_carriernumber
where F.statecode = 0 AND C.mot_monthenddate = CONVERT(DATE, DATEADD(D,-(DAY(@date)), @date))
group by F.mot_averagefleetsize, T.mot_fleettypedescription, C.mot_monthenddate
)
insert into #Bus(Caption,[Date],FleetType,OperatingStatus, Fleet_Range_0,Fleet_Range_1,[Fleet_Range_2-4],[Fleet_Range_5-10],TOTAL)
select
    CONVERT(NVARCHAR(50), 'by Weight') AS 'Caption', cte.MED AS 'Date', CONVERT(NVARCHAR(10), cte.FleetType) AS 'FleetType',
    CONVERT(NVARCHAR(25), 'ALL') AS 'OperatingStatus',
    SUM(cte.Fleet_Range_0) As 'Fleet_Range_0', SUM(cte.Fleet_Range_1) As 'Fleet_Range_1', SUM(cte.[Fleet_Range_2-4]) 'Fleet_Range_2-4',
    SUM(cte.[Fleet_Range_5-10]) 'Fleet_Range_5-10',
    (SUM(cte.Fleet_Range_0) + SUM(cte.Fleet_Range_1) + SUM(cte.[Fleet_Range_2-4]) + SUM(cte.[Fleet_Range_5-10])) 'TOTAL'
from cte
where cte.FleetType = 'Bus'
group by cte.FleetType, cte.MED

DECLARE @Count INT
SELECT @Count = Count(*) FROM #Bus

If @Count = 0
insert into #Bus(Caption,[Date],FleetType,OperatingStatus, Fleet_Range_0,Fleet_Range_1,[Fleet_Range_2-4],[Fleet_Range_5-10],TOTAL)
values('by Weight', CONVERT(DATE, DATEADD(D,-(DAY(@date)), @date)), 'Bus', 'ALL',0,0,0,0,0)

SELECT * FROM #Bus

If it doesn't works, try implementing this within a stored procedure


问:
Resize rectangular image to square, keeping ratio and fill background with black
I'm trying to resize a batch of grayscale images that are 256 x N pixels (N varies, but is always ≤256).

My intention is to downscale the images.

The resize would have to output a square (1:1) image, with:

resized image centered vertically

aspect ratio maintained

remaining pixels rendered black

Visually this would be the desired result:

I have tried creating a numpy zeroes matrix with the target size (e.g. 200 x 200) but have not been able to paste the resized image into its vertical center.

Any suggestions using cv2, PIL or numpy are welcome.

答:
Here is a code that solve your question with OPENCV module (using NUMPY module too)</p>

```<code>#Importing modules opencv + numpy
import cv2
import numpy as np

#Reading an image (you can use PNG or JPG)
img = cv2.imread("image.png")

#Getting the bigger side of the image
s = max(img.shape[0:2])

#Creating a dark square with NUMPY
f = np.zeros((s,s,3),np.uint8)

#Getting the centering position
ax,ay = (s - img.shape[1])//2,(s - img.shape[0])//2

#Pasting the 'image' in a centering position
f[ay:img.shape[0]+ay,ax:ax+img.shape[1]] = img

#Showing results (just in case)
cv2.imshow("IMG",f)
#A pause, waiting for any press in keyboard
cv2.waitKey(0)

#Saving the image
cv2.imwrite("img2square.png",f)
cv2.destroyAllWindows()
</code>```

Body:
Here is a code that solve your question with OPENCV module (using NUMPY module too)

#Importing modules opencv + numpy
import cv2
import numpy as np

#Reading an image (you can use PNG or JPG)
img = cv2.imread("image.png")

#Getting the bigger side of the image
s = max(img.shape[0:2])

#Creating a dark square with NUMPY
f = np.zeros((s,s,3),np.uint8)

#Getting the centering position
ax,ay = (s - img.shape[1])//2,(s - img.shape[0])//2

#Pasting the 'image' in a centering position
f[ay:img.shape[0]+ay,ax:ax+img.shape[1]] = img

#Showing results (just in case)
cv2.imshow("IMG",f)
#A pause, waiting for any press in keyboard
cv2.waitKey(0)

#Saving the image
cv2.imwrite("img2square.png",f)
cv2.destroyAllWindows()


问:
How to handle logical OR operation from cucumber step in java
I have a Cucumber step which I want to perform depending on the statement passed in Cucumber step

```<code>verify word does exists in log
clear the logs
</code>```

or I may pass

```<code>verify word does not exists in log
not clear the logs
</code>```

and Gherkin for this would be

```<code>("^verify word does(not|) exists in log$")
("^(|not )clear the logs$")
</code>```

Can I handle this in Java?

I want to perform action depending up on the key I pass

答:
Here is the solution in Ruby, it might give you an idea how to Updat your step and step def.

Step:

```<code>And verify word does exist in log
And verify word does not exist in log
</code>```

Step Def:

```<code>And(/^verify word does( not)? exist in log$/) do |negative|
    if negative
        # negative logic
    else
        # positive logic
    end
end
</code>```

Body:
I have a Cucumber step which I want to perform depending on the statement passed in Cucumber step

verify word does exists in log
clear the logs

or I may pass

verify word does not exists in log
not clear the logs

and Gherkin for this would be

("^verify word does(not|) exists in log$")
("^(|not )clear the logs$")

Can I handle this in Java?

I want to perform action depending up on the key I pass

Body:
Here is the solution in Ruby, it might give you an idea how to Updat your step and step def.

Step:

And verify word does exist in log
And verify word does not exist in log

Step Def:

And(/^verify word does( not)? exist in log$/) do |negative|
    if negative
        # negative logic
    else
        # positive logic
    end
end


问:
What's the best way of parsing strings?
We've got a scenario that requires us to parse lots of e-mail (plain text), each e-mail 'type' is the result of a script being run against various platforms. Some are tab delimited, some are space delimited, some we simply don't know yet.

We'll need to support more 'formats' in the future too.

Do we go for a solution using:

Regex

Simply string searching (using string.IndexOf etc)

Lex/ Yacc

Other

The overall solution will be developed in C# 2.0 (hopefully 3.5)

答:
The three solutions you stated each cover very different needs.

Manual parsing (simple text search) is the most flexible and the most adaptable, however, it very quickly becomes a real pain in the ass as the parsing required is more complicated.

Regex are a middle ground, and probably your best bet here. They are powerful, yet flexible as you can yourself add more logic from the code that call the different regex. The main drawback would be speed here.

Lex/Yacc is really only adapted to very complicated, predictable syntaxes and lacks a lot of post compile flexibility. You can't easily change parser in mid parsing, well actually you can but it's just too heavy and you'd be better using regex instead.

I know this is a cliché answer, it all really comes down to what your exact needs are, but from what you said, I would personally probably go with a bag of regex.

As an alternative, as Vaibhav poionted out, if you have several different situations that can arise and that you cna easily detect which one is coming, you could make a plugin system that chooses the right algorithm, and those algorithms could all be very different, one using Lex/Yacc in pointy cases and the other using IndexOf and regex for simpler cases.

ContentLicense: CC BY-SA 2.5

Title: What's the best way of parsing strings?

LastEditorDisplayName: Torsten Marek

OwnerDisplayName: Coincoin


问:
Attempting to create a query that will return all records has me stumped
I have a database with three tables.  "Roster", "Training Courses", and "Course Enrollment"
Roster and Course Enrollment are connected by "ETID" (employee training ID).  Course Enrollment and Training Courses are connected by "Course ID".

I am trying to create a query that will return ALL employees, and a YES/NO value for all courses.
I've written the following to look at specific employees, but I cant seem to find the right way to return all employees. Any help would be appreciated.

```<code>SELECT [TRAINING COURSES].[course id]
     , [TRAINING COURSES].[course name]
     , "YES" AS Completed
     , [COURSE ENROLLMENT].[training date]
FROM [TRAINING COURSES]
INNER JOIN [COURSE ENROLLMENT]
            ON [COURSE ENROLLMENT].[course id]=[TRAINING COURSES].[course id]
WHERE [COURSE ENROLLMENT].[ETID]=[ENTER ETID]

UNION ALL

SELECT [TRAINING COURSES].[course id]
     , [TRAINING COURSES].[course name]
     , "No" AS Completed
     , NULL
FROM [TRAINING COURSES]
WHERE NOT EXISTS
(
    SELECT *
    FROM [COURSE ENROLLMENT]
    WHERE [COURSE ENROLLMENT].[course id]=[TRAINING COURSES].[course id]
    AND [COURSE ENROLLMENT].[ETID]=[ENTER ETID:]
)
ORDER BY [TRAINING COURSES].[course name];
</code>```

答: Drop WHERE [COURSE ENROLLMENT].[ETID]=[ENTER ETID] from both sub-queries.

Body:
I have a database with three tables.  "Roster", "Training Courses", and "Course Enrollment"
Roster and Course Enrollment are connected by "ETID" (employee training ID).  Course Enrollment and Training Courses are connected by "Course ID".

I am trying to create a query that will return ALL employees, and a YES/NO value for all courses.
I've written the following to look at specific employees, but I cant seem to find the right way to return all employees. Any help would be appreciated.

SELECT [TRAINING COURSES].[course id]
     , [TRAINING COURSES].[course name]
     , "YES" AS Completed
     , [COURSE ENROLLMENT].[training date]
FROM [TRAINING COURSES]
INNER JOIN [COURSE ENROLLMENT]
            ON [COURSE ENROLLMENT].[course id]=[TRAINING COURSES].[course id]
WHERE [COURSE ENROLLMENT].[ETID]=[ENTER ETID]

UNION ALL

SELECT [TRAINING COURSES].[course id]
     , [TRAINING COURSES].[course name]
     , "No" AS Completed
     , NULL
FROM [TRAINING COURSES]
WHERE NOT EXISTS
(
    SELECT *
    FROM [COURSE ENROLLMENT]
    WHERE [COURSE ENROLLMENT].[course id]=[TRAINING COURSES].[course id]
    AND [COURSE ENROLLMENT].[ETID]=[ENTER ETID:]
)
ORDER BY [TRAINING COURSES].[course name];


问:
Why is my program only printing one grade?
Write a program to calculate students average test scores and their grades. You may
assume the following data:

```<code>Johnson 85 83 77 91 76
Aniston 80 90 95 93 48
Cooper 78 81 11 90 73
Gupta 92 83 30 69 87
Blair 23 45 96 38 59
Clark 60 85 45 39 67
Kennedy 77 31 52 74 83
Bronson 93 94 89 77 97
Sunny 79 85 28 93 82
Smith 85 72 49 75 63
</code>```

Use three arrays: a one-dimensional array to store the student names, a (parallel) twodimensional
array to store the test score, and a parallel one-dimensional array to store
grades. Your program must contain at least the following methods: a method to read
and store data into two arrays, a method to calculate the average test score and grade.

```<code>import java.util.Scanner;
public class Assignment2Ques2 {
</code>```

答:
You calculate grades in AvgCal.  Your loop structure appears to be

```<code>for each of the 10 students
    for each of the 5 marks per student
       calculate the student's average
    end of average calculation
    set one grade for the student based on his average
end of student grade calculation
</code>```

So you get one grade per student because that's all you calculate. And in fact that's all you can store in your program as written: you declare char Grades[10], i.e., you have only one character to hod the grade for each student.

Your indentation is a bit funky so it's harder to see than it should be. Note the layout of my pseudocode; your Java should be similarly indented.

I think you've actually done what the assignment asked for - each student gets one grade based on their average score. Why do you think he/she should get 5 grades?

By the way, this statement

```<code> System.out.println(Studt_Names[i] +":  " +Grades);
</code>```

will print out some cybercrud like "[C@139a55" (identically) for each student, not the content of the Grades array and certainly not a single entry in the array. Grades[i] would make sense. Did you transcribe it correctly?

Body:
Write a program to calculate students average test scores and their grades. You may
assume the following data:

Johnson 85 83 77 91 76
Aniston 80 90 95 93 48
Cooper 78 81 11 90 73
Gupta 92 83 30 69 87
Blair 23 45 96 38 59
Clark 60 85 45 39 67
Kennedy 77 31 52 74 83
Bronson 93 94 89 77 97
Sunny 79 85 28 93 82
Smith 85 72 49 75 63

Use three arrays: a one-dimensional array to store the student names, a (parallel) twodimensional
array to store the test score, and a parallel one-dimensional array to store
grades. Your program must contain at least the following methods: a method to read
and store data into two arrays, a method to calculate the average test score and grade.

import java.util.Scanner;
public class Assignment2Ques2 {

Body:
You calculate grades in AvgCal.  Your loop structure appears to be

for each of the 10 students
    for each of the 5 marks per student
       calculate the student's average
    end of average calculation
    set one grade for the student based on his average
end of student grade calculation

So you get one grade per student because that's all you calculate. And in fact that's all you can store in your program as written: you declare char Grades[10], i.e., you have only one character to hod the grade for each student.

Your indentation is a bit funky so it's harder to see than it should be. Note the layout of my pseudocode; your Java should be similarly indented.

I think you've actually done what the assignment asked for - each student gets one grade based on their average score. Why do you think he/she should get 5 grades?

By the way, this statement

 System.out.println(Studt_Names[i] +":  " +Grades);

will print out some cybercrud like "[C@139a55" (identically) for each student, not the content of the Grades array and certainly not a single entry in the array. Grades[i] would make sense. Did you transcribe it correctly?


问:
Get the amount of days between two given days of the week
I want to find out how many days there are between two given days of the week.

This looks to be a case for a well executed slice method; but I just can't get my head around it.

```<code>const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'

console.log(`${remaining} Days until the next dispatch`)
</code>```

Monday to Thursday is easy enough :

```<code>let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1
</code>```

But Thursday to Monday (for example) needs some logic that I can't figure out.

答:
You don't have to use slice function, here's a way of achieving your goal:

const getRemaining = (arr, start, end) => {
  let startIndex = arr.indexOf(start);
  let endIndex = days.indexOf(end);
  if (startIndex > endIndex) {
    // We should go to beginning
    endIndex += arr.length;
  }
  return endIndex - startIndex;
};

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

console.log('Thursday to Monday: ', getRemaining(days, 'Thursday', 'Monday'));
console.log('Monday to Thursday: ', getRemaining(days, 'Monday', 'Thursday'));```

Body:
I want to find out how many days there are between two given days of the week.

This looks to be a case for a well executed slice method; but I just can't get my head around it.

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'

console.log(`${remaining} Days until the next dispatch`)

Monday to Thursday is easy enough :

let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1

But Thursday to Monday (for example) needs some logic that I can't figure out.


问:
sqldatasource update() not working
I am using sqldatasource to perform an update.

I have a Transactions table which stores individual items that the user selects for purchase (item name, item price, orderID, etc)

I have an Orders table which stores values for the Order (account name, order total, etc)

Here is my SqlDataSource as defined in the .aspx page:

```<code>        <asp:SqlDataSource ID="SqlDataSource2" runat="server"
        ConnectionString="<%$ ConnectionStrings:NH_SWAGConnectionString %>"

        InsertCommand="INSERT INTO [tblOrders] ([OrderDate], [OrderTotal], [OrderAccount], [OrderCostCentre]) VALUES (@OrderDate, @OrderTotal, @OrderAccount, @OrderCostCentre); SELECT @OrderNewID = SCOPE_IDENTITY()"
        SelectCommand="SELECT * FROM [tblOrders]"
        UpdateCommand="UPDATE [tblOrders] SET [OrderDate] = @OrderDate, [OrderTotal] = @OrderTotal, [OrderAccount] = @OrderAccount, [OrderCostCentre] = @OrderCostCentre WHERE [OrderID] = @original_OrderID AND [OrderDate] = @original_OrderDate AND [OrderTotal] = @original_OrderTotal AND [OrderAccount] = @original_OrderAccount AND [OrderCostCentre] = @original_OrderCostCentre"
        OldValuesParameterFormatString="original_{0}"

        oninserting="SqlDataSource2_Inserting"
        oninserted="SqlDataSource2_Inserted" onupdated="SqlDataSource2_Updated"
        onupdating="SqlDataSource2_Updating">

        <InsertParameters>
            <asp:Parameter Direction="Output" Name="OrderNewId" Type="Int32" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="OrderDate" Type="DateTime" />
            <asp:Parameter Name="OrderAccount" Type="String" />
            <asp:Parameter Name="OrderCostCentre" Type="String" />
            <asp:Parameter Name="original_OrderID" Type="Int32" />
            <asp:Parameter Name="original_OrderDate" Type="DateTime" />
            <asp:Parameter Name="original_OrderTotal" Type="Decimal" />
            <asp:Parameter Name="original_OrderAccount" Type="String" />
            <asp:Parameter Name="original_OrderCostCentre" Type="String" />
            <%--<asp:ControlParameter ControlID="lblOrderTotal" Name="OrderTotal"
                PropertyName="Text" />--%>
        </UpdateParameters>
    </asp:SqlDataSource>
</code>```

You can see I blocked out the code that attaches the OrderID to a Textbox.  I did this because that portion wasn't working.  I then tried to modify the Parameter in Code-Behind:

```<code>        //Update Order Table with Total of Order
    //SqlDataSource2.UpdateParameters["OrderTotal"].DefaultValue = (string)OrderTotal.ToString();
    SqlDataSource2.UpdateParameters.Add("OrderTotal", (string)OrderTotal.ToString());
    SqlDataSource2.Update();
</code>```

The page doesn't error out, but the Update to OrderTotal in the Orders Db doesn't update.  It stays at '0'.  Can anyone shed some light on this for me?  I've been trying for 2 days now.  And yes, this is the last time I will be using SqlDataSource - It seems everyone recommends a different approach (DAC?) - Next project I will follow everyone's suggestion :)

Thanks all

答:
Add the OrderTotal to the list of parameters, and then do in code before the update:

```<code>SqlDataSource2.UpdateParameters["OrderTotal"].DefaultValue = OrderTotal.ToString();
SqlDataSource2.Update();
</code>```

Using the DefaultValue property passes this value to the query.

Or, tap into the Updating event, and add the new value to the event argument collection of values.  This gets passed to the backend.

HTH.

Title: sqldatasource update() not working

Body:
I am using sqldatasource to perform an update.

I have a Transactions table which stores individual items that the user selects for purchase (item name, item price, orderID, etc)

I have an Orders table which stores values for the Order (account name, order total, etc)

Here is my SqlDataSource as defined in the .aspx page:

        <asp:SqlDataSource ID="SqlDataSource2" runat="server"
        ConnectionString="<%$ ConnectionStrings:NH_SWAGConnectionString %>"

        InsertCommand="INSERT INTO [tblOrders] ([OrderDate], [OrderTotal], [OrderAccount], [OrderCostCentre]) VALUES (@OrderDate, @OrderTotal, @OrderAccount, @OrderCostCentre); SELECT @OrderNewID = SCOPE_IDENTITY()"
        SelectCommand="SELECT * FROM [tblOrders]"
        UpdateCommand="UPDATE [tblOrders] SET [OrderDate] = @OrderDate, [OrderTotal] = @OrderTotal, [OrderAccount] = @OrderAccount, [OrderCostCentre] = @OrderCostCentre WHERE [OrderID] = @original_OrderID AND [OrderDate] = @original_OrderDate AND [OrderTotal] = @original_OrderTotal AND [OrderAccount] = @original_OrderAccount AND [OrderCostCentre] = @original_OrderCostCentre"
        OldValuesParameterFormatString="original_{0}"

        oninserting="SqlDataSource2_Inserting"
        oninserted="SqlDataSource2_Inserted" onupdated="SqlDataSource2_Updated"
        onupdating="SqlDataSource2_Updating">

        <InsertParameters>
            <asp:Parameter Direction="Output" Name="OrderNewId" Type="Int32" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="OrderDate" Type="DateTime" />
            <asp:Parameter Name="OrderAccount" Type="String" />
            <asp:Parameter Name="OrderCostCentre" Type="String" />
            <asp:Parameter Name="original_OrderID" Type="Int32" />
            <asp:Parameter Name="original_OrderDate" Type="DateTime" />
            <asp:Parameter Name="original_OrderTotal" Type="Decimal" />
            <asp:Parameter Name="original_OrderAccount" Type="String" />
            <asp:Parameter Name="original_OrderCostCentre" Type="String" />
            <%--<asp:ControlParameter ControlID="lblOrderTotal" Name="OrderTotal"
                PropertyName="Text" />--%>
        </UpdateParameters>
    </asp:SqlDataSource>

You can see I blocked out the code that attaches the OrderID to a Textbox.  I did this because that portion wasn't working.  I then tried to modify the Parameter in Code-Behind:

        //Update Order Table with Total of Order
    //SqlDataSource2.UpdateParameters["OrderTotal"].DefaultValue = (string)OrderTotal.ToString();
    SqlDataSource2.UpdateParameters.Add("OrderTotal", (string)OrderTotal.ToString());
    SqlDataSource2.Update();

The page doesn't error out, but the Update to OrderTotal in the Orders Db doesn't update.  It stays at '0'.  Can anyone shed some light on this for me?  I've been trying for 2 days now.  And yes, this is the last time I will be using SqlDataSource - It seems everyone recommends a different approach (DAC?) - Next project I will follow everyone's suggestion :)

Thanks all

Body:
Add the OrderTotal to the list of parameters, and then do in code before the update:

SqlDataSource2.UpdateParameters["OrderTotal"].DefaultValue = OrderTotal.ToString();
SqlDataSource2.Update();

Using the DefaultValue property passes this value to the query.

Or, tap into the Updating event, and add the new value to the event argument collection of values.  This gets passed to the backend.

HTH.


问:
Nginx configuration leads to endless redirect loop
So I've looked at every sample configuration I could find and yet every time I try and view a page that requires ssl, I end up in an redirect loop. I'm running nginx/0.8.53 and passenger 3.0.2.

Here's the ssl config

```<code>server  {
  listen 443 default ssl;
  server_name <redacted>.com www.<redacted>.com;
  root /home/app/<redacted>/public;
  passenger_enabled on;
  rails_env production;
  ssl_certificate      /home/app/ssl/<redacted>.com.pem;
  ssl_certificate_key  /home/app/ssl/<redacted>.key;

  proxy_set_header  X-Real-IP  $remote_addr;
  proxy_set_header  X_FORWARDED_PROTO https;
  proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header  Host $http_host;
  proxy_set_header  X-Url-Scheme $scheme;
  proxy_redirect    off;
  proxy_max_temp_file_size 0;

  location /blog {
    rewrite ^/blog(/.*)?$ http://blog.<redacted>.com/$1 permanent;
  }

  location ~* \.(js|css|jpg|jpeg|gif|png)$ {
    if (-f $request_filename) {
      expires      max;
      break;
    }
  }

  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   html;
  }
}
</code>```

Here's the non-ssl config

```<code>server  {
  listen 80;
  server_name <redacted>.com www.<redacted>.com;
  root /home/app/<redacted>/public;
  passenger_enabled on;
  rails_env production;

  location /blog {
    rewrite ^/blog(/.*)?$ http://blog.<redacted>.com/$1 permanent;
  }

  location ~* \.(js|css|jpg|jpeg|gif|png)$ {
    if (-f $request_filename) {
      expires      max;
      break;
    }
  }

  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   html;
  }
}
</code>```

Let me know if there's any additional info I can give to help diagnose the issue.

答: I've toyed around with a bunch of these answers but nothing worked for me. Then I realized since I use Cloudflare the problem may not be in the server but with Cloudflare. Lo and behold when I set my SSL to Full (Strict) everything works as it should!

Body:
So I've looked at every sample configuration I could find and yet every time I try and view a page that requires ssl, I end up in an redirect loop. I'm running nginx/0.8.53 and passenger 3.0.2.

Here's the ssl config

server  {
  listen 443 default ssl;
  server_name <redacted>.com www.<redacted>.com;
  root /home/app/<redacted>/public;
  passenger_enabled on;
  rails_env production;
  ssl_certificate      /home/app/ssl/<redacted>.com.pem;
  ssl_certificate_key  /home/app/ssl/<redacted>.key;

  proxy_set_header  X-Real-IP  $remote_addr;
  proxy_set_header  X_FORWARDED_PROTO https;
  proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header  Host $http_host;
  proxy_set_header  X-Url-Scheme $scheme;
  proxy_redirect    off;
  proxy_max_temp_file_size 0;

  location /blog {
    rewrite ^/blog(/.*)?$ http://blog.<redacted>.com/$1 permanent;
  }

  location ~* \.(js|css|jpg|jpeg|gif|png)$ {
    if (-f $request_filename) {
      expires      max;
      break;
    }
  }

  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   html;
  }
}

Here's the non-ssl config

server  {
  listen 80;
  server_name <redacted>.com www.<redacted>.com;
  root /home/app/<redacted>/public;
  passenger_enabled on;
  rails_env production;

  location /blog {
    rewrite ^/blog(/.*)?$ http://blog.<redacted>.com/$1 permanent;
  }

  location ~* \.(js|css|jpg|jpeg|gif|png)$ {
    if (-f $request_filename) {
      expires      max;
      break;
    }
  }

  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   html;
  }
}

Let me know if there's any additional info I can give to help diagnose the issue.


问:
python tox: how to use a different python envlist in environment
Here is my tox.ini:

```<code>[tox]
envlist = py27,py35

[testenv]
deps =
    Flask
    connexion
    pytest
    coverage
    pytest-cov
    requests
    six
commands=pytest --junitxml xunit-reports/xunit-result-XXX.xml --cov {envsitepackagesdir} --cov-report=xml

[testenv:local]
#HOW DO I SPECIFY A NEW LIST OF PYENV LIKE 31,36 IN HERE????
commands=
    pytest --cov {envsitepackagesdir}/XXX  --cov-report html
</code>```

When I run tox it runs in py27 and py35. I want tox -e local to run in a different set of multiple python environments. I can't figure out how to do this. How do I do this? Right now it does not even respect the intial envlist and only runs on Python 2.7.

答:
A possible solution to what you are attempting to do is to use tox -l to list all the environments, filter the ones you want, and then feed them back into tox -e.

For example, to run all environments that have "local" in the name (using bash):

tox -e $(tox -l | grep local | paste -sd "," -)

Step-by-step explanation:

tox -l lists all the environments, one on each line

grep local filters only the lines of the input which contain the word "local"

paste -sd "," - joins the lines of the input with commas

Body:
Here is my tox.ini:

[tox]
envlist = py27,py35

[testenv]
deps =
    Flask
    connexion
    pytest
    coverage
    pytest-cov
    requests
    six
commands=pytest --junitxml xunit-reports/xunit-result-XXX.xml --cov {envsitepackagesdir} --cov-report=xml

[testenv:local]
#HOW DO I SPECIFY A NEW LIST OF PYENV LIKE 31,36 IN HERE????
commands=
    pytest --cov {envsitepackagesdir}/XXX  --cov-report html

When I run tox it runs in py27 and py35. I want tox -e local to run in a different set of multiple python environments. I can't figure out how to do this. How do I do this? Right now it does not even respect the intial envlist and only runs on Python 2.7.


问:
iOS JavascriptCore exception detailed stacktrace info
It seems the exception stacktrace in iOS only contains the method name or there is a bug. Below is my code of handling exceptions in JSContext.

```<code>context.exceptionHandler = { (ctx: JSContext!, value: JSValue!) in
    // type of String
    let stacktrace = value.objectForKeyedSubscript("stack").toString()
    // type of Number
    let lineNumber = value.objectForKeyedSubscript("line")
    // type of Number
    let column = value.objectForKeyedSubscript("column")
    let moreInfo = "in method \(stacktrace)Line number in file: \(lineNumber), column: \(column)"
    Logger.error("JS ERROR: \(value) \(moreInfo)")
}
</code>```

And I got logs like below

```<code>ERROR : JSContextRenderer.swift:308 : setupContext : JS ERROR: Error in method clearBackground
Line number in file: 162, column: 12"
</code>```

Note there is a new line right after the "clearBackground" name, I think there probably more information there.

Can anybody having similar experience confirm? Any help is appreciated. Thanks.

答: Long ago, @igrek asked where the keys in value come from. They're part of the Error object that was thrown by the JavaScript engine, and that now appears as value in the native error handler callback. What exactly Error includes depends on the implementation, but typically includes message, fileName, and lineNumber. It appears that stack is also supported. More details on the MDN page for Error .

Body:
It seems the exception stacktrace in iOS only contains the method name or there is a bug. Below is my code of handling exceptions in JSContext.

context.exceptionHandler = { (ctx: JSContext!, value: JSValue!) in
    // type of String
    let stacktrace = value.objectForKeyedSubscript("stack").toString()
    // type of Number
    let lineNumber = value.objectForKeyedSubscript("line")
    // type of Number
    let column = value.objectForKeyedSubscript("column")
    let moreInfo = "in method \(stacktrace)Line number in file: \(lineNumber), column: \(column)"
    Logger.error("JS ERROR: \(value) \(moreInfo)")
}

And I got logs like below

ERROR : JSContextRenderer.swift:308 : setupContext : JS ERROR: Error in method clearBackground
Line number in file: 162, column: 12"

Note there is a new line right after the "clearBackground" name, I think there probably more information there.

Can anybody having similar experience confirm? Any help is appreciated. Thanks.


问:
Bottom Navigation View setup with fragment navigation component not working
I tried implementing the bottom navigation view to set up with fragment transition using navigation components by referring Navigation Codelab.

The fragments are not changing when clicking on the bottom navigation view.

Note:

I am trying to implement the bottom navigation view inside another fragment. (Not an activity like in the codelab example)

MainActivity.kt:

```<code>class MainActivity : AppCompatActivity() {

    // Data binding
    private lateinit var mainActivityBinding: MainActivityBinding

    // On activity creation starting
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Set activity layout
        mainActivityBinding = DataBindingUtil.setContentView(this, R.layout.main_activity)
    }
}
</code>```

main_activity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activity.MainActivity">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/main_activity_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <fragment
            android:id="@+id/main_activity_nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/activity_navigation" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>
</code>```

activity_navigation.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_navigation"
    app:startDestination="@id/mainFragment">

    <fragment
        android:id="@+id/mainFragment"
        android:name="com.appz.abhi.moneytracker.view.main.MainFragment"
        android:label="main_fragment"
        tools:layout="@layout/main_fragment" />

</navigation>
</code>```

MainFragment.kt:

```<code>class MainFragment : Fragment() {

    // Data binding
    private var mainFragmentBinding: MainFragmentBinding? = null

    // On fragment view creation starting
    override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {

        // Inflate the fragment layout
        mainFragmentBinding = DataBindingUtil
                .inflate(inflater, R.layout.main_fragment, container, false)

        // Return root view
        return mainFragmentBinding!!.root
    }

    // On fragment view creation completion
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // Initialize UI
        initUI()
    }

    // Initialize UI
    private fun initUI() {

        // Setup action bar
        (activity as AppCompatActivity).setSupportActionBar(mainFragmentBinding?.mainFragmentToolbar)

        // Setup bottom navigation view
        setUpBottomNavigationView()
    }

    // Setup bottom navigation view
    private fun setUpBottomNavigationView() {

        // Nav host fragment
        val host: NavHostFragment = activity?.supportFragmentManager
                ?.findFragmentById(R.id.main_fragment_nav_host_fragment) as NavHostFragment?
                ?: return

        // Set up Action Bar
        val navController = host.navController

        // Setup bottom navigation view
        mainFragmentBinding?.mainFragmentBottomNavigationView?.setupWithNavController(navController)
    }
}
</code>```

main_fragment.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".view.main.MainFragment">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/main_fragment_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/main_fragment_app_bar_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/main_fragment_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@drawable/toolbar_background"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                tools:title="Money Tracker" />

        </com.google.android.material.appbar.AppBarLayout>

        <fragment
            android:id="@+id/main_fragment_nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/main_fragment_app_bar_layout"
            app:navGraph="@navigation/bottom_navigation_view_navigation" />

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/main_fragment_bottom_navigation_view"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@color/white"
            app:itemIconTint="@color/bottom_navigation"
            app:itemTextColor="@color/bottom_navigation"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:menu="@menu/bottom_navigation_view_menu"/>

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>
</code>```

bottom_navigation_view_navigation.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/bottom_navigation_view_navigation"
    app:startDestination="@id/settingsFragment">

    <fragment
        android:id="@+id/homeFragment"
        android:name="com.appz.abhi.moneytracker.view.home.HomeFragment"
        android:label="Home"
        tools:layout="@layout/home_fragment" />

    <fragment
        android:id="@+id/settingsFragment"
        android:name="com.appz.abhi.moneytracker.view.settings.SettingsFragment"
        android:label="Settings"
        tools:layout="@layout/settings_fragment" />

</navigation>
</code>```

bottom_navigation_view_menu:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@id/homeFragment"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/home"
        app:showAsAction="ifRoom" />

    <item
        android:id="@id/settingsFragment"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="@string/settings"
        app:showAsAction="ifRoom" />

</menu>
</code>```

HomeFragment.kt:

```<code>class HomeFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.home_fragment, container, false)
    }
}
</code>```

SettingsFragment.kt:

```<code>class SettingsFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.settings_fragment, container, false)
    }
}
</code>```

答:
It doesn't seem like you ever get to the setupWithNavController line. You use findFragmentById(R.id.main_fragment_nav_host_fragment) with the activity's FragmentManager, but the NavHostFragment in the activity is under the id main_activity_nav_host_fragment. You should be using childFragmentManager if you want to get the nested NavHostFragment in your MainFragment's layout:

```<code>// Nav host fragment
val host: NavHostFragment = childFragmentManager
        .findFragmentById(R.id.main_fragment_nav_host_fragment) as NavHostFragment?
        ?: return
</code>```

Note that there are very few cases where you actually want or need a nested NavHostFragment like this. As per the Listen for navigation events documentation, generally if you want global navigation such as a BottomNavigationView to only appear on some screens, you'd add an OnDestinationChangedListener and change its visibility there.

Body:
I tried implementing the bottom navigation view to set up with fragment transition using navigation components by referring Navigation Codelab.

The fragments are not changing when clicking on the bottom navigation view.

Note:

I am trying to implement the bottom navigation view inside another fragment. (Not an activity like in the codelab example)

MainActivity.kt:

class MainActivity : AppCompatActivity() {

    // Data binding
    private lateinit var mainActivityBinding: MainActivityBinding

    // On activity creation starting
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Set activity layout
        mainActivityBinding = DataBindingUtil.setContentView(this, R.layout.main_activity)
    }
}

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activity.MainActivity">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/main_activity_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <fragment
            android:id="@+id/main_activity_nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/activity_navigation" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

activity_navigation.xml:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_navigation"
    app:startDestination="@id/mainFragment">

    <fragment
        android:id="@+id/mainFragment"
        android:name="com.appz.abhi.moneytracker.view.main.MainFragment"
        android:label="main_fragment"
        tools:layout="@layout/main_fragment" />

</navigation>

MainFragment.kt:

class MainFragment : Fragment() {

    // Data binding
    private var mainFragmentBinding: MainFragmentBinding? = null

    // On fragment view creation starting
    override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {

        // Inflate the fragment layout
        mainFragmentBinding = DataBindingUtil
                .inflate(inflater, R.layout.main_fragment, container, false)

        // Return root view
        return mainFragmentBinding!!.root
    }

    // On fragment view creation completion
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // Initialize UI
        initUI()
    }

    // Initialize UI
    private fun initUI() {

        // Setup action bar
        (activity as AppCompatActivity).setSupportActionBar(mainFragmentBinding?.mainFragmentToolbar)

        // Setup bottom navigation view
        setUpBottomNavigationView()
    }

    // Setup bottom navigation view
    private fun setUpBottomNavigationView() {

        // Nav host fragment
        val host: NavHostFragment = activity?.supportFragmentManager
                ?.findFragmentById(R.id.main_fragment_nav_host_fragment) as NavHostFragment?
                ?: return

        // Set up Action Bar
        val navController = host.navController

        // Setup bottom navigation view
        mainFragmentBinding?.mainFragmentBottomNavigationView?.setupWithNavController(navController)
    }
}

main_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".view.main.MainFragment">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/main_fragment_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/main_fragment_app_bar_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/main_fragment_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@drawable/toolbar_background"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                tools:title="Money Tracker" />

        </com.google.android.material.appbar.AppBarLayout>

        <fragment
            android:id="@+id/main_fragment_nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/main_fragment_app_bar_layout"
            app:navGraph="@navigation/bottom_navigation_view_navigation" />

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/main_fragment_bottom_navigation_view"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@color/white"
            app:itemIconTint="@color/bottom_navigation"
            app:itemTextColor="@color/bottom_navigation"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:menu="@menu/bottom_navigation_view_menu"/>

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

bottom_navigation_view_navigation.xml:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/bottom_navigation_view_navigation"
    app:startDestination="@id/settingsFragment">

    <fragment
        android:id="@+id/homeFragment"
        android:name="com.appz.abhi.moneytracker.view.home.HomeFragment"
        android:label="Home"
        tools:layout="@layout/home_fragment" />

    <fragment
        android:id="@+id/settingsFragment"
        android:name="com.appz.abhi.moneytracker.view.settings.SettingsFragment"
        android:label="Settings"
        tools:layout="@layout/settings_fragment" />

</navigation>

bottom_navigation_view_menu:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@id/homeFragment"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/home"
        app:showAsAction="ifRoom" />

    <item
        android:id="@id/settingsFragment"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="@string/settings"
        app:showAsAction="ifRoom" />

</menu>

HomeFragment.kt:

class HomeFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.home_fragment, container, false)
    }
}

SettingsFragment.kt:

class SettingsFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.settings_fragment, container, false)
    }
}

Body:
It doesn't seem like you ever get to the setupWithNavController line. You use findFragmentById(R.id.main_fragment_nav_host_fragment) with the activity's FragmentManager, but the NavHostFragment in the activity is under the id main_activity_nav_host_fragment. You should be using childFragmentManager if you want to get the nested NavHostFragment in your MainFragment's layout:

// Nav host fragment
val host: NavHostFragment = childFragmentManager
        .findFragmentById(R.id.main_fragment_nav_host_fragment) as NavHostFragment?
        ?: return

Note that there are very few cases where you actually want or need a nested NavHostFragment like this. As per the Listen for navigation events documentation, generally if you want global navigation such as a BottomNavigationView to only appear on some screens, you'd add an OnDestinationChangedListener and change its visibility there.


问:
How to apply pull to refresh feature like chrome in web-view android studio?
I am trying to set up a pull to refresh feature like chrome (swipe refresh layout). The loading bar disappears after pull.
How can i fix this?

I've tried various code samples from stack overflow... but none of them seem to work.
Swipe to refresh works but disappears right after pull.

Swipe refresh in main activity java

```<code>mySwipeRefreshLayout = this.findViewById(R.id.swipeContainer);

        mySwipeRefreshLayout.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        browser.reload();
                        mySwipeRefreshLayout.setRefreshing(false);
                    }
                }
        );
</code>```

I Just want the loading icon to load till the full page is refreshed like chrome.

答:
if you want to keep the loading till the page loaded you don't have to use                         mySwipeRefreshLayout.setRefreshing(false) inside your refresh listener , because your are disabling  it just after the refresh start.

instead you have to use it when your loading is done . let say as example you have a webview , so you should listen on the webview progress like this example :

```<code>mWebView.setWebViewClient(new WebViewClient() {
   public void onPageFinished(WebView view, String url) {
          mySwipeRefreshLayout.setRefreshing(false);
    }
});
</code>```

Body:
I am trying to set up a pull to refresh feature like chrome (swipe refresh layout). The loading bar disappears after pull.
How can i fix this?

I've tried various code samples from stack overflow... but none of them seem to work.
Swipe to refresh works but disappears right after pull.

Swipe refresh in main activity java

mySwipeRefreshLayout = this.findViewById(R.id.swipeContainer);

        mySwipeRefreshLayout.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        browser.reload();
                        mySwipeRefreshLayout.setRefreshing(false);
                    }
                }
        );

I Just want the loading icon to load till the full page is refreshed like chrome.

Body:
if you want to keep the loading till the page loaded you don't have to use                         mySwipeRefreshLayout.setRefreshing(false) inside your refresh listener , because your are disabling  it just after the refresh start.

instead you have to use it when your loading is done . let say as example you have a webview , so you should listen on the webview progress like this example :

mWebView.setWebViewClient(new WebViewClient() {
   public void onPageFinished(WebView view, String url) {
          mySwipeRefreshLayout.setRefreshing(false);
    }
});


问:
Storing UserPreferences with a React Native App
I'm trying to run a few examples using react-native and was curious to see how to store User Preferences using NSUserDefaults with React Native.

Would we have to implement a module that exports the NSUserDefaults method as mentioned here

答:
React native has it own serves wrapped UserDefaults, official site link</p>

```<code>import {Setting} from from 'react-native';

const name = Settings.get("your_id_key_can_get_from_setting_bundle");
console.log(name);

Settings.watchKeys('your_id_key', () => {
  console.log(Settings.get("your_id_key"))
})
</code>```

Body:
React native has it own serves wrapped UserDefaults, official site link

import {Setting} from from 'react-native';

const name = Settings.get("your_id_key_can_get_from_setting_bundle");
console.log(name);

Settings.watchKeys('your_id_key', () => {
  console.log(Settings.get("your_id_key"))
})


问:
Get special max record
I have in my Table1 3 fields (IdFactory Type Numeric-IdSector Type Numeric-NameFactory Type Text).When i click on Button1 i get max record of (IdFactory) in TextBox1.My ComboBox1 is filled with several numbers from 1 to 100.I choose (IdSector) by ComboBox1 and the records in this field (IdSector) repeat only 5 times.How to automatically display max record of (IdSector) in combobox1 when i Click on Button1.this is my code to get max record on TextBox1</p>

答:
Keep your data objects local so you can be sure they closed and disposed. The Using...End Using blocks do this for you even if there is an error.

What I think you are after is the IdSector for the highest IdFactory. Although you can't use an aggregate function in a where clause; you can use a sub-query with an aggregate.

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim result As Object
    Using Conne As New OleDbConnection("Your connection string")
        Using Cmd As New OleDbCommand("Select IdSector from Table1 Where IdFactory = (Select max(IdFactory) From Table1);", Conne)
            Conne.Open()
            result = Cmd.ExecuteScalar
        End Using
    End Using
    If result Is Nothing Then
        TextBox1.Text = "1"
        ComboBox1.Text = "1"
    Else
        TextBox1.Text = (CInt(result) + 1).ToString
        ComboBox1.Text = result.ToString
    End If
End Sub
</code>```

Title: Get special max record

Body:
Keep your data objects local so you can be sure they closed and disposed. The Using...End Using blocks do this for you even if there is an error.

What I think you are after is the IdSector for the highest IdFactory. Although you can't use an aggregate function in a where clause; you can use a sub-query with an aggregate.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim result As Object
    Using Conne As New OleDbConnection("Your connection string")
        Using Cmd As New OleDbCommand("Select IdSector from Table1 Where IdFactory = (Select max(IdFactory) From Table1);", Conne)
            Conne.Open()
            result = Cmd.ExecuteScalar
        End Using
    End Using
    If result Is Nothing Then
        TextBox1.Text = "1"
        ComboBox1.Text = "1"
    Else
        TextBox1.Text = (CInt(result) + 1).ToString
        ComboBox1.Text = result.ToString
    End If
End Sub


问:
How do I abort a query execution on a PrePersist function?
I'm currently working on a synfomy 4.2 project using sonata admin and Doctrine ORM.

I would like to abort a query execution when some condition is set to true, for example, if I would like to insert a new Product, but the Product for some reason laks of the parameter price then I would like to abort that query and set a flash message to make the user know that the Product could not be created because it laks of price.

I have done my research but I cant find anything that relates to my problem, I do know that this functionality must be applied in a PrePersist function on the Entity.

I have been breaking my head with something like this.

```<code>/**
* @ORM\PrePersist
*/
public function prePersist(LifecycleEventArgs $args)
{
    $em = $args->getEntityManager("App\Milenio\VersionsControlBundle\Entity\Plugins");
    $em->getConnection();
    $em->flush();
    $em->clear();
}
</code>```

But of course this does nothing, I'm still causing an obvious SQL exception.

I know there are ways to tell sonata admin to make an input required but in my particular case that wont make the trick.

答: Would it not make more sense to force the user to fill in the price, or to just make the price not nullable, and catch the error in the controller, and then message the user, these things are cleaner solutions and don't require listeners. Furthermore I don't think you can flush in a prepersist, maybe entitymanager->rollback, or entitymanager detach are what you are looking for</p>

Body:
I'm currently working on a synfomy 4.2 project using sonata admin and Doctrine ORM.

I would like to abort a query execution when some condition is set to true, for example, if I would like to insert a new Product, but the Product for some reason laks of the parameter price then I would like to abort that query and set a flash message to make the user know that the Product could not be created because it laks of price.

I have done my research but I cant find anything that relates to my problem, I do know that this functionality must be applied in a PrePersist function on the Entity.

I have been breaking my head with something like this.

/**
* @ORM\PrePersist
*/
public function prePersist(LifecycleEventArgs $args)
{
    $em = $args->getEntityManager("App\Milenio\VersionsControlBundle\Entity\Plugins");
    $em->getConnection();
    $em->flush();
    $em->clear();
}

But of course this does nothing, I'm still causing an obvious SQL exception.

I know there are ways to tell sonata admin to make an input required but in my particular case that wont make the trick.