问:
Parse through a JSON file and pick out certain properties
I have a JSON file containing over 8000 features. An example of one is below:

```<code>{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"uuid":"____","part2":"_____","length":"529","function":"______"},"geometry":{"type":"LineString","coordinates":[[-360909.60698310119,7600968.922204642,0.0],[-361357.344715965,7600811.951385159,0.0],[-361805.08159795138,7600654.939420643,0.0]]}}
</code>```

I am trying to use python to iterate through the features and print out certain aspects from the properties. At the minute I have the following code which is iterating through the features and printing the 1st feature and its properties 8420 times.

```<code>
import json

# Opening JSON file
f = open('file.json')

# returns JSON object as
# a dictionary
data = json.load(f)

# Iterating through the json
# list
for i in data['features']:
    print(data["features"][0]["properties"])
</code>```

How can I amend the above to show the features and properties for each of the 8420 features? I have tried

```<code>for i in data['features']:
    print(data["features"][i]["properties"])
</code>```

but I get the error TypeError: list indices must be integers or slices, not dict

答:
i is a dictionary, not an index.

```<code>for i in data['features']:
    print(i["properties"])
</code>```

If it was important to you to use an index, use enumerate or range:

```<code>for i, d in enumerate(data['features']):
    # data['features'][i] == d
</code>```
```<code>for i in range(len(data['features'])):
    # data['features'][i] ...
</code>```

Body:
I have a JSON file containing over 8000 features. An example of one is below:

{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"uuid":"____","part2":"_____","length":"529","function":"______"},"geometry":{"type":"LineString","coordinates":[[-360909.60698310119,7600968.922204642,0.0],[-361357.344715965,7600811.951385159,0.0],[-361805.08159795138,7600654.939420643,0.0]]}}

I am trying to use python to iterate through the features and print out certain aspects from the properties. At the minute I have the following code which is iterating through the features and printing the 1st feature and its properties 8420 times.

import json

# Opening JSON file
f = open('file.json')

# returns JSON object as
# a dictionary
data = json.load(f)

# Iterating through the json
# list
for i in data['features']:
    print(data["features"][0]["properties"])

How can I amend the above to show the features and properties for each of the 8420 features? I have tried

for i in data['features']:
    print(data["features"][i]["properties"])

but I get the error TypeError: list indices must be integers or slices, not dict

Body:
i is a dictionary, not an index.

for i in data['features']:
    print(i["properties"])

If it was important to you to use an index, use enumerate or range:

for i, d in enumerate(data['features']):
    # data['features'][i] == d

for i in range(len(data['features'])):
    # data['features'][i] ...


来源: stackexchange

问:
Merging too many small files into single large files in Datalake using Apache Spark
I Have Following Directory Structure In HDFS.

```<code>/user/hdfs/landing_zone/year=2021/month=11/day=01/part-1.txt
/user/hdfs/landing_zone/year=2021/month=11/day=01/part-2.txt
/user/hdfs/landing_zone/year=2021/month=11/day=01/part-3.txt
/user/hdfs/landing_zone/year=2021/month=11/day=02/part-1.txt
/user/hdfs/landing_zone/year=2021/month=11/day=02/part-2.txt
/user/hdfs/landing_zone/year=2021/month=11/day=02/part-3.txt
/user/hdfs/landing_zone/year=2021/month=11/day=03/part-1.txt
/user/hdfs/landing_zone/year=2021/month=11/day=03/part-2.txt
/user/hdfs/landing_zone/year=2021/month=11/day=03/part-3.txt
</code>```

I want to Merge the files DayWise.

```<code>/user/hdfs/landing_zone/year=2021/month=11/day=01/part-1.txt
/user/hdfs/landing_zone/year=2021/month=11/day=02/part-1.txt
/user/hdfs/landing_zone/year=2021/month=11/day=03/part-1.txt
</code>```

I have used below code.

```<code>val inputDir="/user/hdfs/landing_zone/year=2021/month=11/"
val hadoopConf = spark.sparkContext.hadoopConfiguration
val hdfsConf = new Configuration();
val fs: FileSystem = FileSystem.get(hdfsConf)
val sc = spark.sparkContext
val baseFolder = new Path(inputDir)
val files = baseFolder.getFileSystem(sc.hadoopConfiguration).listStatus(baseFolder).map(_.getPath.toString)
for (path <- files) {
var Folder_Path = fs.listStatus(new Path(path)).map(_.getPath).toList
for (eachfolder <- Folder_Path) {
var New_Folder_Path: String = eachfolder.toString
var Fs1 = FileSystem.get(spark.sparkContext.hadoopConfiguration)
var FilePath = Fs1.listStatus(new Path(s"${New_Folder_Path}")).filter(_.isFile).map(_.getPath).toList
var NewFiles = Fs1.listStatus(new Path(s"${New_Folder_Path}")).filter(_.isFile).map(_.getPath.getName).toList
</code>```

"FilePath" : Generating the List of Complete Path for all the files recursively.

```<code>List(/user/hdfs/landing_zone/year=2021/month=11/day=01/part-1.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=01/part-2.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=01/part-3.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=02/part-1.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=02/part-2.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=02/part-3.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=03/part-1.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=03/part-2.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=03/part-3.txt)
</code>```

"NewFiles" : - Generating the list of FileNames for all the files recursively

```<code>List(part-1.txt)
List(part-2.txt)
List(part-3.txt)
List(part-1.txt)
List(part-2.txt)
List(part-3.txt)
List(part-1.txt)
List(part-2.txt)
List(part-3.txt)
</code>```

Can Someone Suggest/Guide me How should I modify the code so that It can Generate the files DayWise and merge 3 file(1 day=3 files) into a single file (1 day = 1 file) recursively for all the days.

答:
They're are easier ways that getting into low level manipulations.I would suggest "picking the table up and putting it back down"

Literally, create a table based on the files, write it to a new table. This should concatenate the small files. (Without you having to manipulate it)

If you have created a hive table based on this you could use hive to do the work:

```<code>ALTER TABLE table_name [PARTITION (partition_key = 'partition_value' [, ...])] CONCATENATE;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I Have Following Directory Structure In HDFS.

/user/hdfs/landing_zone/year=2021/month=11/day=01/part-1.txt
/user/hdfs/landing_zone/year=2021/month=11/day=01/part-2.txt
/user/hdfs/landing_zone/year=2021/month=11/day=01/part-3.txt
/user/hdfs/landing_zone/year=2021/month=11/day=02/part-1.txt
/user/hdfs/landing_zone/year=2021/month=11/day=02/part-2.txt
/user/hdfs/landing_zone/year=2021/month=11/day=02/part-3.txt
/user/hdfs/landing_zone/year=2021/month=11/day=03/part-1.txt
/user/hdfs/landing_zone/year=2021/month=11/day=03/part-2.txt
/user/hdfs/landing_zone/year=2021/month=11/day=03/part-3.txt

I want to Merge the files DayWise.

/user/hdfs/landing_zone/year=2021/month=11/day=01/part-1.txt
/user/hdfs/landing_zone/year=2021/month=11/day=02/part-1.txt
/user/hdfs/landing_zone/year=2021/month=11/day=03/part-1.txt

I have used below code.

val inputDir="/user/hdfs/landing_zone/year=2021/month=11/"
val hadoopConf = spark.sparkContext.hadoopConfiguration
val hdfsConf = new Configuration();
val fs: FileSystem = FileSystem.get(hdfsConf)
val sc = spark.sparkContext
val baseFolder = new Path(inputDir)
val files = baseFolder.getFileSystem(sc.hadoopConfiguration).listStatus(baseFolder).map(_.getPath.toString)
for (path <- files) {
var Folder_Path = fs.listStatus(new Path(path)).map(_.getPath).toList
for (eachfolder <- Folder_Path) {
var New_Folder_Path: String = eachfolder.toString
var Fs1 = FileSystem.get(spark.sparkContext.hadoopConfiguration)
var FilePath = Fs1.listStatus(new Path(s"${New_Folder_Path}")).filter(_.isFile).map(_.getPath).toList
var NewFiles = Fs1.listStatus(new Path(s"${New_Folder_Path}")).filter(_.isFile).map(_.getPath.getName).toList

"FilePath" : Generating the List of Complete Path for all the files recursively.

List(/user/hdfs/landing_zone/year=2021/month=11/day=01/part-1.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=01/part-2.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=01/part-3.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=02/part-1.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=02/part-2.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=02/part-3.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=03/part-1.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=03/part-2.txt)
List(/user/hdfs/landing_zone/year=2021/month=11/day=03/part-3.txt)

"NewFiles" : - Generating the list of FileNames for all the files recursively

List(part-1.txt)
List(part-2.txt)
List(part-3.txt)
List(part-1.txt)
List(part-2.txt)
List(part-3.txt)
List(part-1.txt)
List(part-2.txt)
List(part-3.txt)

Can Someone Suggest/Guide me How should I modify the code so that It can Generate the files DayWise and merge 3 file(1 day=3 files) into a single file (1 day = 1 file) recursively for all the days.

Body:
They're are easier ways that getting into low level manipulations.I would suggest "picking the table up and putting it back down"

Literally, create a table based on the files, write it to a new table. This should concatenate the small files. (Without you having to manipulate it)

If you have created a hive table based on this you could use hive to do the work:

ALTER TABLE table_name [PARTITION (partition_key = 'partition_value' [, ...])] CONCATENATE;


问:
ActionBarDrawerToggle doesn't accept String as parameter
the Red line is under "Open navigation drawer" and "Close navigation drawer"

```<code>import androidx.appcompat.app.ActionBarDrawerToggle;
setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Menu");
    setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toogle = new ActionBarDrawerToggle(this,
                drawer,
                toolbar ,
                "Open navigation drawer",
                "Close navigation drawer"

                );
        drawer.setDrawerListener(toogle);
        toogle.syncState();
</code>```

This picture shows the problem

答:
According to Android official docs openDrawerContentDescRes and closeDrawerContentDescRes are of int datatype.

```<code>ActionBarDrawerToggle (Activity activity,
            DrawerLayout drawerLayout,
            int openDrawerContentDescRes,
            int closeDrawerContentDescRes)
</code>```

So you need to change your string to string resource id ( R.string.YOUR_STRING) to describe the "open drawer" and "close drawer" action for accessibility.

Body:
the Red line is under "Open navigation drawer" and "Close navigation drawer"

import androidx.appcompat.app.ActionBarDrawerToggle;
setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Menu");
    setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toogle = new ActionBarDrawerToggle(this,
                drawer,
                toolbar ,
                "Open navigation drawer",
                "Close navigation drawer"

                );
        drawer.setDrawerListener(toogle);
        toogle.syncState();

This picture shows the problem

Body:
According to Android official docs openDrawerContentDescRes and closeDrawerContentDescRes are of int datatype.

ActionBarDrawerToggle (Activity activity,
            DrawerLayout drawerLayout,
            int openDrawerContentDescRes,
            int closeDrawerContentDescRes)

So you need to change your string to string resource id ( R.string.YOUR_STRING) to describe the "open drawer" and "close drawer" action for accessibility.


问:
Hide checkout fields when selecting multiple delivery methods in WooCommerce
I use code that hides the checkout fields if the Local Pickup shipping method is selected:

```<code>    // Conditional Show hide checkout fields based on chosen shipping methods
add_action( 'wp_footer', 'custom_checkout_field_script' );
function custom_checkout_field_script() {

    // HERE your shipping methods rate IDs
    $local_pickup = 'local_pickup:3';
    $pickpoint = 'wc_custom_shipping_pickpoint';

    $required_text = esc_attr__( 'required', 'woocommerce' );
    $required_html = '<abbr class="required" title="' . $required_text . '">*</abbr>';
    ?>
    <script>
        jQuery(function($){
            var ism = 'input[name^="shipping_method"]',         ismc = ism+':checked',
                csa = 'input#ship-to-different-address-checkbox',
                rq = '-required',       vr = 'validate'+rq,     w = 'woocommerce',      wv = w+'-validated',
                iv = '-invalid',        fi = '-field',          wir = w+iv+' '+w+iv+rq+fi,
                b = '#billing_',        s = '#shipping_',       f = '_field',
                a1 = 'country',     a2 = 'address_1',   a3 = 'address_2',   a4 = 'postcode',    a5 = 'state',   a6 = 'city',
                b1 = b+a1+f,        b2 = b+a2+f,        b3 = b+a3+f,        b4 = b+a4+f,        b5 = b+a5+f,    b6 = b+a6+f,
                s1 = s+a1+f,        s2 = s+a2+f,        s3 = s+a3+f,        s4 = s+a4+f,        s5 = s+a5+f,    s6 = s+a6+f,
                pickPoint = '<?php echo $pickpoint; ?>',        localPickup = '<?php echo $local_pickup; ?>';

            // Utility function to shows or hide checkout fields
            function showHide( action='show', selector='' ){
                if( action == 'show' )
                    $(selector).show(function(){
                        $(this).addClass(vr);
                        $(this).removeClass(wv);
                        $(this).removeClass(wir);
                        if( $(selector+' > label > abbr').html() == undefined )
                            $(selector+' label').append('<?php echo $required_html; ?>');
                    });
                else
                    $(selector).hide(function(){
                        $(this).removeClass(vr);
                        $(this).removeClass(wv);
                        $(this).removeClass(wir);
                        if( $(selector+' > label > abbr').html() != undefined )
                            $(selector+' label > .required').remove();
                    });
            }

            // Initializing at start after checkout init (Based on the chosen shipping method)
            setTimeout(function(){
                if( $(ismc).val() == pickPoint ) // Chosen "Pick point" (Hiding "Delivery")
                {
                    showHide('hide',b1 ); // Country
                    showHide('hide',b2 ); // Address 1
                    showHide('hide',b3 ); // Address 2
                    showHide('hide',b4 ); // Postcode
                    showHide('hide',b5 ); // State
                    showHide('hide',b6 ); // City
                }
                else if( $(ismc).val() == localPickup ) // Choosen "Local pickup" (Hidding "Take away")
                {
                    showHide('hide',b1);
                    showHide('hide',b2);
                    showHide('hide',b3);
                    showHide('hide',b4);
                    showHide('hide',b5);
                    showHide('hide',b6);
                }
                else
                {
                    showHide('hide',b1);
                    showHide('show',b2);
                    showHide('show',b3);
                    showHide('show',b4);
                    showHide('show',b5);
                    showHide('show',b6);
                }
            }, 100);

            // When shipping method is changed (Live event)
            $( 'form.checkout' ).on( 'change', ism, function() {
                if( $(ismc).val() == pickPoint )
                {
                    showHide('hide',b1);
                    showHide('hide',b2);
                    showHide('hide',b3);
                    showHide('hide',b4);
                    showHide('hide',b5);
                    showHide('hide',b6);

                    if( $(csa).prop('checked') ) {
                        showHide('hide',s1);
                        showHide('hide',s2);
                        showHide('hide',s3);
                        showHide('hide',s4);
                        showHide('hide',s5);
                        showHide('hide',s6);
                    }
                }
                else if( $(ismc).val() == localPickup )
                {
                    showHide('hide',b1);
                    showHide('hide',b2);
                    showHide('hide',b3);
                    showHide('hide',b4);
                    showHide('hide',b5);
                    showHide('hide',b6);

                    if( $(csa).prop('checked') ) {
                        showHide('hide',s1);
                        showHide('hide',s2);
                        showHide('hide',s3);
                        showHide('hide',s4);
                        showHide('hide',s5);
                        showHide('hide',s6);
                    }
                }
                else
                {
                    showHide('hide',b1);
                    showHide('show',b2);
                    showHide('show',b3);
                    showHide('show',b4);
                    showHide('show',b5);
                    showHide('show',b6);

                    if( $(csa).prop('checked') ) {
                        showHide('hide',s1);
                        showHide('show',s2);
                        showHide('show',s3);
                        showHide('show',s4);
                        showHide('show',s5);
                        showHide('hide',s6);
                    }
                }
            });

            // When "shipping to different address" is changed (Live event)
            $(csa).click( function() {
                if( $(ismc).val() == pickPoint && $(this).prop('checked') )
                {
                    showHide('hide',b1);
                    showHide('hide',b2);
                    showHide('hide',b3);
                    showHide('hide',b4);
                    showHide('hide',b4);
                    showHide('hide',b6);

                    showHide('hide',s1);
                    showHide('hide',s2);
                    showHide('hide',s3);
                    showHide('hide',s4);
                    showHide('hide',s5);
                    showHide('hide',s6);
                }
                else if( $(ismc).val() == localPickup && $(this).prop('checked') )
                {
                    showHide('hide',b1);
                    showHide('hide',b2);
                    showHide('hide',b3);
                    showHide('hide',b4);
                    showHide('hide',b4);
                    showHide('hide',b6);

                    showHide('hide',s1);
                    showHide('hide',s2);
                    showHide('hide',s3);
                    showHide('hide',s4);
                    showHide('hide',s5);
                    showHide('hide',s6);
                }
                else
                {
                    showHide('hide',b1);
                    showHide('show',b2);
                    showHide('show',b3);
                    showHide('show',b4);
                    showHide('show',b4);
                    showHide('show',b6);

                    showHide('hide',s1);
                    showHide('show',s2);
                    showHide('show',s3);
                    showHide('show',s4);
                    showHide('show',s5);
                    showHide('show',s6);
                }
            });
        });
    </script>
    <?php
}
</code>```

The problem is that I can't do this for multiple delivery methods. I need to specify local_pickup:3, local_pickup:6 and local_pickup:9. Hiding fields only works correctly with one specified delivery method.

Please help me to solve this problem. Thank you!

答:
The above code does not make fileds not required. Only solution I've found to work around is fill up hidden fields with placeholder value.</p>
```<code>// Conditional Show hide checkout fields based on chosen shipping methods
add_action( 'wp_footer', 'custom_checkout_field_script' );
function custom_checkout_field_script() {

    // HERE your shipping methods rate IDs
    $local_pickup  = array('inpost_paczkomaty:15');
    $required_text = esc_attr__( 'required', 'woocommerce' );
    $required_html = '<abbr class="required" title="' . $required_text . '">*</abbr>';
    ?>
    <script>
        jQuery(function($){
            var ism = 'input[name^="shipping_method"]',
                ismc = ism+':checked',
                csa = 'input#ship-to-different-address-checkbox',
                rq = '-required',
                vr = 'validate'+rq,
                w = 'woocommerce',
                wv = w+'-validated',
                iv = '-invalid',
                fi = '-field',
                wir = w+iv+' '+w+iv+rq+fi,
                b = '#billing_',
                s = '#shipping_',
                f = '_field',
                a1 = 'country', a2 = 'address_1', a3 = 'address_2', a4 = 'postcode', a5 = 'state', a6 = 'city',
                b1 = b+a1+f, b2 = b+a2+f, b3 = b+a3+f, b4 = b+a4+f, b5 = b+a5+f, b6 = b+a6+f,
                s1 = s+a1+f, s2 = s+a2+f, s3 = s+a3+f, s4 = s+a4+f, s5 = s+a5+f, s6 = s+a6+f,
                localPickup = '<?php echo json_encode($local_pickup); ?>';

            // Utility function to shows or hide checkout fields
            function showHide( action='show', selector='' ){
                if( action == 'show' ){
                    $(selector).show(function(){
                        $(this).addClass(vr);
                        $(this).removeClass(wv);
                        $(this).removeClass(wir);
                        if( $(selector+' > label > abbr').html() == undefined )
                            $(selector+' label').append('<?php echo $required_html; ?>');
                    });
                } else {
                    $(selector).hide(function(){
                        $(this).removeClass(vr);
                        $(this).removeClass(wv);
                        $(this).removeClass(wir);
                        $(this).find("[type='text']").val('00-000');
                        if( $(selector+' > label > abbr').html() != undefined ){
                            $(selector+' label > .required').remove();
                        }
                    });
                }
            }

            // Initializing at start after checkout init (Based on the chosen shipping method)
            setTimeout(function(){
                if( localPickup.includes( $(ismc).val() ) ){ // Choosen "Local pickup" (Hidding "Take away")
                    showHide('hide',b1); //Country
                    showHide('hide',b2); //Address line 1
                    showHide('hide',b3); //Address line 2
                    showHide('hide',b4); //Postcode
                    showHide('hide',b5); //State
                    showHide('hide',b6); //City
                }else{
                    showHide('hide',b1); //Country
                    showHide('show',b2); //Address line 1
                    showHide('hide',b3); //Address line 2
                    showHide('show',b4); //Postcode
                    showHide('hide',b5); //State
                    showHide('show',b6); //City
                }
            }, 100);

            // When shipping method is changed (Live event)
            $( 'form.checkout' ).on( 'change', ism, function() {
                if( localPickup.includes( $(ismc).val() ) ){
                    showHide('hide',b1); //Country
                    showHide('hide',b2); //Address line 1
                    showHide('hide',b3); //Address line 2
                    showHide('hide',b4); //Postcode
                    showHide('hide',b5); //State
                    showHide('hide',b6); //City

                    if( $(csa).prop('checked') ) {
                        showHide('hide',s1);
                        showHide('hide',s2);
                        showHide('hide',s3);
                        showHide('hide',s4);
                        showHide('hide',s5);
                        showHide('hide',s6);
                    }
                }else{
                    showHide('hide',b1); //Country
                    showHide('show',b2); //Address line 1
                    showHide('hide',b3); //Address line 2
                    showHide('show',b4); //Postcode
                    showHide('hide',b5); //State
                    showHide('show',b6); //City

                    if( $(csa).prop('checked') ) {
                        showHide('hide',s1);
                        showHide('hide',s2);
                        showHide('hide',s3);
                        showHide('hide',s4);
                        showHide('hide',s5);
                        showHide('hide',s6);
                    }
                }
            });

            // When "shipping to different address" is changed (Live event)
            $(csa).click( function() {
                if( localPickup.includes( $(ismc).val() ) && $(this).prop('checked') ){
                    showHide('hide',b1);
                    showHide('hide',b2);
                    showHide('hide',b3);
                    showHide('hide',b4);
                    showHide('hide',b4);
                    showHide('hide',b6);

                    showHide('hide',s1);
                    showHide('hide',s2);
                    showHide('hide',s3);
                    showHide('hide',s4);
                    showHide('hide',s5);
                    showHide('hide',s6);
                }else{
                    showHide('hide',b1);
                    showHide('hide',b2);
                    showHide('hide',b3);
                    showHide('hide',b4);
                    showHide('hide',b4);
                    showHide('hide',b6);

                    showHide('hide',s1);
                    showHide('show',s2);
                    showHide('hide',s3);
                    showHide('show',s4);
                    showHide('hide',s5);
                    showHide('show',s6);
                }
            });
        });
    </script>
    <?php
}
</code>```

Body:
I use code that hides the checkout fields if the Local Pickup shipping method is selected:

    // Conditional Show hide checkout fields based on chosen shipping methods
add_action( 'wp_footer', 'custom_checkout_field_script' );
function custom_checkout_field_script() {

    // HERE your shipping methods rate IDs
    $local_pickup = 'local_pickup:3';
    $pickpoint = 'wc_custom_shipping_pickpoint';

    $required_text = esc_attr__( 'required', 'woocommerce' );
    $required_html = '*';
    ?>

    <?php
}

The problem is that I can't do this for multiple delivery methods. I need to specify local_pickup:3, local_pickup:6 and local_pickup:9. Hiding fields only works correctly with one specified delivery method.

Please help me to solve this problem. Thank you!

Body:
The above code does not make fileds not required. Only solution I've found to work around is fill up hidden fields with placeholder value.

// Conditional Show hide checkout fields based on chosen shipping methods
add_action( 'wp_footer', 'custom_checkout_field_script' );
function custom_checkout_field_script() {

    // HERE your shipping methods rate IDs
    $local_pickup  = array('inpost_paczkomaty:15');
    $required_text = esc_attr__( 'required', 'woocommerce' );
    $required_html = '<abbr class="required" title="' . $required_text . '">*</abbr>';
    ?>
    <script>
        jQuery(function($){
            var ism = 'input[name^="shipping_method"]',
                ismc = ism+':checked',
                csa = 'input#ship-to-different-address-checkbox',
                rq = '-required',
                vr = 'validate'+rq,
                w = 'woocommerce',
                wv = w+'-validated',
                iv = '-invalid',
                fi = '-field',
                wir = w+iv+' '+w+iv+rq+fi,
                b = '#billing_',
                s = '#shipping_',
                f = '_field',
                a1 = 'country', a2 = 'address_1', a3 = 'address_2', a4 = 'postcode', a5 = 'state', a6 = 'city',
                b1 = b+a1+f, b2 = b+a2+f, b3 = b+a3+f, b4 = b+a4+f, b5 = b+a5+f, b6 = b+a6+f,
                s1 = s+a1+f, s2 = s+a2+f, s3 = s+a3+f, s4 = s+a4+f, s5 = s+a5+f, s6 = s+a6+f,
                localPickup = '<?php echo json_encode($local_pickup); ?>';

            // Utility function to shows or hide checkout fields
            function showHide( action='show', selector='' ){
                if( action == 'show' ){
                    $(selector).show(function(){
                        $(this).addClass(vr);
                        $(this).removeClass(wv);
                        $(this).removeClass(wir);
                        if( $(selector+' > label > abbr').html() == undefined )
                            $(selector+' label').append('<?php echo $required_html; ?>');
                    });
                } else {
                    $(selector).hide(function(){
                        $(this).removeClass(vr);
                        $(this).removeClass(wv);
                        $(this).removeClass(wir);
                        $(this).find("[type='text']").val('00-000');
                        if( $(selector+' > label > abbr').html() != undefined ){
                            $(selector+' label > .required').remove();
                        }
                    });
                }
            }

            // Initializing at start after checkout init (Based on the chosen shipping method)
            setTimeout(function(){
                if( localPickup.includes( $(ismc).val() ) ){ // Choosen "Local pickup" (Hidding "Take away")
                    showHide('hide',b1); //Country
                    showHide('hide',b2); //Address line 1
                    showHide('hide',b3); //Address line 2
                    showHide('hide',b4); //Postcode
                    showHide('hide',b5); //State
                    showHide('hide',b6); //City
                }else{
                    showHide('hide',b1); //Country
                    showHide('show',b2); //Address line 1
                    showHide('hide',b3); //Address line 2
                    showHide('show',b4); //Postcode
                    showHide('hide',b5); //State
                    showHide('show',b6); //City
                }
            }, 100);

            // When shipping method is changed (Live event)
            $( 'form.checkout' ).on( 'change', ism, function() {
                if( localPickup.includes( $(ismc).val() ) ){
                    showHide('hide',b1); //Country
                    showHide('hide',b2); //Address line 1
                    showHide('hide',b3); //Address line 2
                    showHide('hide',b4); //Postcode
                    showHide('hide',b5); //State
                    showHide('hide',b6); //City

                    if( $(csa).prop('checked') ) {
                        showHide('hide',s1);
                        showHide('hide',s2);
                        showHide('hide',s3);
                        showHide('hide',s4);
                        showHide('hide',s5);
                        showHide('hide',s6);
                    }
                }else{
                    showHide('hide',b1); //Country
                    showHide('show',b2); //Address line 1
                    showHide('hide',b3); //Address line 2
                    showHide('show',b4); //Postcode
                    showHide('hide',b5); //State
                    showHide('show',b6); //City

                    if( $(csa).prop('checked') ) {
                        showHide('hide',s1);
                        showHide('hide',s2);
                        showHide('hide',s3);
                        showHide('hide',s4);
                        showHide('hide',s5);
                        showHide('hide',s6);
                    }
                }
            });

            // When "shipping to different address" is changed (Live event)
            $(csa).click( function() {
                if( localPickup.includes( $(ismc).val() ) && $(this).prop('checked') ){
                    showHide('hide',b1);
                    showHide('hide',b2);
                    showHide('hide',b3);
                    showHide('hide',b4);
                    showHide('hide',b4);
                    showHide('hide',b6);

                    showHide('hide',s1);
                    showHide('hide',s2);
                    showHide('hide',s3);
                    showHide('hide',s4);
                    showHide('hide',s5);
                    showHide('hide',s6);
                }else{
                    showHide('hide',b1);
                    showHide('hide',b2);
                    showHide('hide',b3);
                    showHide('hide',b4);
                    showHide('hide',b4);
                    showHide('hide',b6);

                    showHide('hide',s1);
                    showHide('show',s2);
                    showHide('hide',s3);
                    showHide('show',s4);
                    showHide('hide',s5);
                    showHide('show',s6);
                }
            });
        });
    </script>
    <?php
}


问:
Gitlab ci automatically trigger another pipeline in another project
Let's assume that i have a project (firstProject) with it's pipeline (which is a test pipeline)

And another project (secondProject) with it's pipeline (build, test, build publish ...)

What i want to do :

After the secondProject pipeline finishes, automatically trigger the firstProject pipeline

I did that and it's working fine with :

```<code>Android:
  stage : Trigger-cross-projects
  trigger: repo/project
</code>```

But the secondProject doesn't wait for the result of the firstProject pipeline, and that's what I want to do, do you have any idea how to make the secondProject wait for the result of the firstProject ?

答:
You can try to use

```<code>      strategy: depend
</code>```

For more information: https://docs.gitlab.com/ee/ci/pipelines/multi_project_pipelines.html

Body:
Let's assume that i have a project (firstProject) with it's pipeline (which is a test pipeline)

And another project (secondProject) with it's pipeline (build, test, build publish ...)

What i want to do :

After the secondProject pipeline finishes, automatically trigger the firstProject pipeline

I did that and it's working fine with :

Android:
  stage : Trigger-cross-projects
  trigger: repo/project

But the secondProject doesn't wait for the result of the firstProject pipeline, and that's what I want to do, do you have any idea how to make the secondProject wait for the result of the firstProject ?

Body:
You can try to use

      strategy: depend

For more information: https://docs.gitlab.com/ee/ci/pipelines/multi_project_pipelines.html


问:
ListBox ObservableCollection duplicating
I have a WPF application which has a listbox bound to an ObservableCollection which retrieves it's data from a Database.  I am attempting to have the ListBox data refreshed every minute through the use of a DispatcherTimer.

```<code>Dim dispatcherTimer As DispatcherTimer = New System.Windows.Threading.DispatcherTimer
AddHandler dispatcherTimer.Tick, AddressOf getRoomMeetingDetails
dispatcherTimer.Interval = New TimeSpan(0, 2, 0)
dispatcherTimer.Start()
</code>```

Which calls the getRoomMeetingDetails method as follows.

```<code>Public Sub getRoomMeetingDetails()
  If Not My.Settings.rbConn = Nothing And _
     Not gl_rmName = Nothing Then
       Dim sqlConn As New SqlConnection(My.Settings.rbConn)
       Dim sqlquery As String = "SELECT  *" & _
                                        "FROM table " & _
       Dim sqlCmd As New SqlCommand(sqlquery, sqlConn)
       sqlConn.Open()
       Dim dr As SqlDataReader
       dr = sqlCmd.ExecuteReader
       While dr.Read
         roomMeetingList.Add(New meetingDetails() With {.eMeetingId = dr.Item("dId")})
       End While
  End If
End Sub
</code>```

I then have my two classes for the Collection as follows (I am very new to ObservableCollections and have tried my best to model my code off the MSDN examples, so if this isn't the best method to use to achieve what I am trying to achieve, or can be done easier, please let me know)

```<code>Public Class MeetingList
  Inherits ObservableCollection(Of meetingDetails)
  Private Shared list As New MeetingList

  Public Shared Function getList() As MeetingList
    Return list
  End Function

  Private Sub New()
    AddItems()
  End Sub

  Public Shared Sub reset(ByVal rmName As String)
    list.ClearItems()
    list.AddItems()
  End Sub

  Private Sub AddItems()
  End Sub
End Class

Public Class meetingDetails
  Implements INotifyPropertyChanged

  Public Sub New()
  End Sub
  Public Property eID() As String
    Get
      Return _eID
    End Get
    Set(ByVal value As String)
       _eID = value
       OnPropertyChanged("eID")
    End Set
  End Property
  Private _eID As String

  Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged
End Class
</code>```

What is happening is when the DispatcherTimer is called every minute, the ListBox data is duplicated which I believe is because the getRoomMeetingDetails method is adding all of the SQL results on every tick.  How can I refresh the ListBox with only new data or data changes from the table?

I am really struggling to work out where I am going wrong and what needs to be added/removed for this to work.

If there is any details I am missing please let me know.

Matt

答:
Either you clear all the data in the listbox before adding them again or you do a check on the collection. I assume your eID is the primary key? the do something like this:

```<code>if ( roomMeetingList.Where ( entry => entry.eID == dbID ).Count () == 0 ) {
    // add
}
</code>```

C# code, but it shows the idea

developerFusion's convert made this VB:

```<code>If roomMeetingList.Where(Function(entry) entry.eID = dbID).Count() = 0 Then
     ' Add
End If
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a WPF application which has a listbox bound to an ObservableCollection which retrieves it's data from a Database.  I am attempting to have the ListBox data refreshed every minute through the use of a DispatcherTimer.

Dim dispatcherTimer As DispatcherTimer = New System.Windows.Threading.DispatcherTimer
AddHandler dispatcherTimer.Tick, AddressOf getRoomMeetingDetails
dispatcherTimer.Interval = New TimeSpan(0, 2, 0)
dispatcherTimer.Start()

Which calls the getRoomMeetingDetails method as follows.

Public Sub getRoomMeetingDetails()
  If Not My.Settings.rbConn = Nothing And _
     Not gl_rmName = Nothing Then
       Dim sqlConn As New SqlConnection(My.Settings.rbConn)
       Dim sqlquery As String = "SELECT  *" & _
                                        "FROM table " & _
       Dim sqlCmd As New SqlCommand(sqlquery, sqlConn)
       sqlConn.Open()
       Dim dr As SqlDataReader
       dr = sqlCmd.ExecuteReader
       While dr.Read
         roomMeetingList.Add(New meetingDetails() With {.eMeetingId = dr.Item("dId")})
       End While
  End If
End Sub

I then have my two classes for the Collection as follows (I am very new to ObservableCollections and have tried my best to model my code off the MSDN examples, so if this isn't the best method to use to achieve what I am trying to achieve, or can be done easier, please let me know)

Public Class MeetingList
  Inherits ObservableCollection(Of meetingDetails)
  Private Shared list As New MeetingList

  Public Shared Function getList() As MeetingList
    Return list
  End Function

  Private Sub New()
    AddItems()
  End Sub

  Public Shared Sub reset(ByVal rmName As String)
    list.ClearItems()
    list.AddItems()
  End Sub

  Private Sub AddItems()
  End Sub
End Class

Public Class meetingDetails
  Implements INotifyPropertyChanged

  Public Sub New()
  End Sub
  Public Property eID() As String
    Get
      Return _eID
    End Get
    Set(ByVal value As String)
       _eID = value
       OnPropertyChanged("eID")
    End Set
  End Property
  Private _eID As String

  Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged
End Class

What is happening is when the DispatcherTimer is called every minute, the ListBox data is duplicated which I believe is because the getRoomMeetingDetails method is adding all of the SQL results on every tick.  How can I refresh the ListBox with only new data or data changes from the table?

I am really struggling to work out where I am going wrong and what needs to be added/removed for this to work.

If there is any details I am missing please let me know.

Matt

Body:
Either you clear all the data in the listbox before adding them again or you do a check on the collection. I assume your eID is the primary key? the do something like this:

if ( roomMeetingList.Where ( entry => entry.eID == dbID ).Count () == 0 ) {
    // add
}

C# code, but it shows the idea

developerFusion's convert made this VB:

If roomMeetingList.Where(Function(entry) entry.eID = dbID).Count() = 0 Then
     ' Add
End If


问:
excel formula to select column values based on two conditions
I want to select the values column values corresponding to 0% and Bravo, so I want the values 0.939958, 0,067266 etc. Could someone help me out to select the values? I have tried this:

```<code>=CHOOSE(MATCH((L2=B2:J2)*(L3=B3:J3);0);B4:B21;C4:C21;D4:D21;E4:E21;F4:F21;G4:G21;H4:H21;I4:I21;J4:J21)
</code>```

But this did not work..

Kind regards.

答:
Use INDEX and add two MATCHes together:

```<code>=INDEX($B$4:$J$21,0,MATCH(0%,$B$2:$J$2)+MATCH("Bravo",$B$3:$D$3,0)-1)
</code>```

This works because the Arizona,Bravo,Charlie are a repeating pattern.  So the first Match returns the first starting place 1,4,7 and then the second returns either 1,2,3.  We add them together and subtract one to return the correct column.

The 0 in the second criterion of the INDEX tells the INDEX to return the full column.  You can then decide what row you want by replacing that with the relative row number desired

You can then change the 0% and "Bravo" to whatever you want.

Your local settings may require the replacement of , with ;.

Body:
I want to select the values column values corresponding to 0% and Bravo, so I want the values 0.939958, 0,067266 etc. Could someone help me out to select the values? I have tried this:

=CHOOSE(MATCH((L2=B2:J2)*(L3=B3:J3);0);B4:B21;C4:C21;D4:D21;E4:E21;F4:F21;G4:G21;H4:H21;I4:I21;J4:J21)

But this did not work..

Kind regards.

Body:
Use INDEX and add two MATCHes together:

=INDEX($B$4:$J$21,0,MATCH(0%,$B$2:$J$2)+MATCH("Bravo",$B$3:$D$3,0)-1)

This works because the Arizona,Bravo,Charlie are a repeating pattern.  So the first Match returns the first starting place 1,4,7 and then the second returns either 1,2,3.  We add them together and subtract one to return the correct column.

The 0 in the second criterion of the INDEX tells the INDEX to return the full column.  You can then decide what row you want by replacing that with the relative row number desired

You can then change the 0% and "Bravo" to whatever you want.

Your local settings may require the replacement of , with ;.


问:
Group lines with similar slope and y-intercept
In python I am using hough lines to detect lines on an image. It is working pretty well to detect lines, but the source image is hand drawn producing many straight lines over each line segment.  I would like to combine lines with similar slope and y intercept to recreate the overall structure of image.
I know I can change the hough line parameters (threshold, min_length, max_gap,) to make longer straighter lines but I would like to keep the granular output of the hough line function and remake the structure with the outputted lines

Hough lines of the image looks like this

My current output is a dict with start/end points of lines, slope and y-intercept:

```<code>{'slope': -2.0, 'start': (438, 317), 'yintercept': 167.0, 'end': (457, 279)}
{'slope': -8.0, 'start': (580, 414), 'yintercept': 1442.0, 'end': (582, 398)}
{'slope': -5.333333333333333, 'start': (438, 375), 'yintercept':
{'slope': -1.5, 'start': (492, 215), 'yintercept': 142.5, 'end': (502, 200)}
{'slope': 0.0, 'start': (524, 316), 'yintercept': 152.0, 'end': (536, 316)}
{'slope': 3.0, 'start': (533, 238), 'yintercept': -232.0, 'end': (527, 220)}
{'slope': -1.9142857142857144, 'start': (450, 292), 'yintercept': 164.37142857142857, 'end': (485, 225)}
{'slope': 0.0, 'start': (467, 317), 'yintercept': 153.0, 'end': (523, 317)}
</code>```

There are 40 lines in the original output but I would like to combine into just 6 lines.

My questions:

What is the best method to groupby both slope and y-intercept?

How do I group by line that are similar and not exact?

I am able to group by exact slope:

```<code>grouper = itemgetter("slope")
    result = []
    for key, grp in groupby(sorted(line_dict, key = grouper), grouper):
        result.append(list(grp))
</code>```

Any help with this is appreciated.

答:
you can use  -

```<code>norm = np.linalg.norm(b, ord=2, axis=1)
#b = array of start and end of lines
# axis 1 = row
print(norm)
</code>```

and check if norm is in range or below certain threshold

Body:
In python I am using hough lines to detect lines on an image. It is working pretty well to detect lines, but the source image is hand drawn producing many straight lines over each line segment.  I would like to combine lines with similar slope and y intercept to recreate the overall structure of image.
I know I can change the hough line parameters (threshold, min_length, max_gap,) to make longer straighter lines but I would like to keep the granular output of the hough line function and remake the structure with the outputted lines

Hough lines of the image looks like this

My current output is a dict with start/end points of lines, slope and y-intercept:

{'slope': -2.0, 'start': (438, 317), 'yintercept': 167.0, 'end': (457, 279)}
{'slope': -8.0, 'start': (580, 414), 'yintercept': 1442.0, 'end': (582, 398)}
{'slope': -5.333333333333333, 'start': (438, 375), 'yintercept':
{'slope': -1.5, 'start': (492, 215), 'yintercept': 142.5, 'end': (502, 200)}
{'slope': 0.0, 'start': (524, 316), 'yintercept': 152.0, 'end': (536, 316)}
{'slope': 3.0, 'start': (533, 238), 'yintercept': -232.0, 'end': (527, 220)}
{'slope': -1.9142857142857144, 'start': (450, 292), 'yintercept': 164.37142857142857, 'end': (485, 225)}
{'slope': 0.0, 'start': (467, 317), 'yintercept': 153.0, 'end': (523, 317)}

There are 40 lines in the original output but I would like to combine into just 6 lines.

My questions:

What is the best method to groupby both slope and y-intercept?

How do I group by line that are similar and not exact?

I am able to group by exact slope:

grouper = itemgetter("slope")
    result = []
    for key, grp in groupby(sorted(line_dict, key = grouper), grouper):
        result.append(list(grp))

Any help with this is appreciated.

Body:
you can use  -

norm = np.linalg.norm(b, ord=2, axis=1)
#b = array of start and end of lines
# axis 1 = row
print(norm)

and check if norm is in range or below certain threshold


问:
Make Image Clickable on Slide Show
I'm using this code for slide show. I can't seem to get the image clickable without losing the name in the 'name' div.

What I'm after is to be able to click on a picture on the slide show and be able to go to the details page. Whenever I get the image clickable, the name does not display in the 'name' div; and if I remove the link, then the name will display.

I don't know how to solve this problem.

Here's the code I'm using.

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>JQuery Cycle Plugin - Pager Demo with Prev/Next Controls</title>
<link rel="stylesheet" type="text/css" media="screen" href="../jq.css" />
<link rel="stylesheet" type="text/css" media="screen" href="cycle.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/chili-1.7.pack.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.cycle.all.js"></script>

<style type="text/css">
#main { margin: 20px }
#nav { margin: 10px; position: relative }
#nav li { float: left; list-style: none}
#nav a { margin: 5px; padding: 3px 5px; border: 1px solid #ccc; background: #fc0; text-decoration: none }
#nav li.activeSlide a { background: #faa; color: black }
#nav a:focus { outline: none; }

</style>

<script type="text/javascript">
$(document).ready(function() {
     $('#slideshow').cycle({
          prev:    '.prev', // Setup prev links
          next:    '.next', // Setup next links
          pager:   '.nav',       // Setup pager navs
          before: function () {
          $("#name").text(this.alt);     }
     });
});
</script>

<style type="text/css">
#left, #slideshow, #right { float: left; width: 200px; }
</style>
</head>
<body>

<!-- left nav bar -->
<div id="left">
    <a href="#"><span class="prev">Prev</span></a>
    <a href="#"><span class="next">Next</span></a>

    <ul class="nav"></ul>
</div>

<!-- slideshow -->
<div id="slideshow">

 <?php
                 mysql_connect("localhost", "root", "")or die("cannot connect");
                 mysql_select_db($db_name)or die("cannot select DB");

                 $data = mysql_query("SELECT * FROM people") or die(mysql_error());
                 while($info = mysql_fetch_array( $data )){
    <!--HERE ON THIS LINE---- > echo "<a href=\"show.php?id=".$info['id']."\"><img src=\"http://localhost:8080/about/images/".$info['photo'] . "\" alt=\"".$info['name'] ."\"/>";
  }
?>

</div>

 <div id="name">

 </div>
 <!-- right nav bar -->
 <div id="right">
     <a href="#"><span class="prev">Prev</span></a>
     <a href="#"><span class="next">Next</span></a>
     <ul class="nav"></ul>
 </div>

 </div>

</body>
</html>
</code>```

Thanks for your assistance

答:
I'm not sure if this affects the jQuery code or not because I can't test it right now, but you don't have a closing A tag.

Should look like this:

```<code>echo "<a href=\"show.php?id=".$info['id']."\"><img src=\"http://localhost:8080/about/images/".$info['photo'] . "\" alt=\"".$info['name'] ."\"/></a>";
</code>```

Title: Make Image Clickable on Slide Show

Body:
I'm using this code for slide show. I can't seem to get the image clickable without losing the name in the 'name' div.

What I'm after is to be able to click on a picture on the slide show and be able to go to the details page. Whenever I get the image clickable, the name does not display in the 'name' div; and if I remove the link, then the name will display.

I don't know how to solve this problem.

Here's the code I'm using.

<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>JQuery Cycle Plugin - Pager Demo with Prev/Next Controls</title>
<link rel="stylesheet" type="text/css" media="screen" href="../jq.css" />
<link rel="stylesheet" type="text/css" media="screen" href="cycle.css" />

    Prev
    Next

 <?php
                 mysql_connect("localhost", "root", "")or die("cannot connect");
                 mysql_select_db($db_name)or die("cannot select DB");

                 $data = mysql_query("SELECT * FROM people") or die(mysql_error());
                 while($info = mysql_fetch_array( $data )){

     Prev
     Next

Thanks for your assistance

Body:
I'm not sure if this affects the jQuery code or not because I can't test it right now, but you don't have a closing A tag.

Should look like this:

echo "<a href=\"show.php?id=".$info['id']."\"><img src=\"http://localhost:8080/about/images/".$info['photo'] . "\" alt=\"".$info['name'] ."\"/></a>";


问:
Pagination not iterating over pages
Want to iterate all pages from this url ""url = "https://www.iata.org/en/about/members/airline-list/"" and dump the results in a .csv file.

How could implementing a piece of code to iterate through the pages be included in the current code below?

```<code>import requests
import pandas as pd
from bs4 import BeautifulSoup
from urllib.request import Request

url = 'https://www.iata.org/en/about/members/airline-list/'
req = Request(url , headers = {
                            'accept':'*/*',
                            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'})

data = []

while True:
    print(url)
    html = requests.get(url)
    soup = BeautifulSoup(html.text, 'html.parser')
    data.append(pd.read_html(soup.select_one('table.datatable').prettify())[0])

    if soup.select_one('span.pagination-link.is-active + div a[href]'):
        url = soup.select_one('span.pagination-link.is-active + div a')['href']
    else:
        break
df = pd.concat(data)
df.to_csv('airline-list.csv',encoding='utf-8-sig',index=False)
</code>```

答:
To get data dynamically, use:

```<code>import pandas as pd
import requests
import bs4

url = 'https://www.iata.org/en/about/members/airline-list/?page={page}&search=&ordering=Alphabetical'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'}

# Total number of pages
html = requests.get(url.format(page=1), headers=headers)
soup = bs4.BeautifulSoup(html.text)
pages = int(soup.find_all('a', {'class': 'pagination-link'})[-2].text)

data = []
for page in range(1, pages+1):
    html = requests.get(url.format(page=page, headers=headers))
    data.append(pd.read_html(html.text)[0])
df = pd.concat(data)
</code>```

Output:

```<code>>>> df
             Airline Name IATA Designator 3 digit code ICAO code           Country / Territory
0                 ABX Air              GB          832       ABX                 United States
1         Aegean Airlines              A3          390       AEE                        Greece
2              Aer Lingus              EI           53       EIN                       Ireland
3          Aero Republica              P5          845       RPB                      Colombia
4                Aeroflot              SU          555       AFL            Russian Federation
..                    ...             ...          ...       ...                           ...
3                 WestJet              WS          838       WJA                        Canada
4   White coloured by you              WI           97       WHT                      Portugal
5                 Wideroe              WF          701       WIF                        Norway
6         Xiamen Airlines              MF          731       CXA  China (People's Republic of)
7      YTO Cargo Airlines              YG          860       HYT  China (People's Republic of)

[288 rows x 5 columns]
</code>```

Title: Pagination not iterating over pages

Body:
Want to iterate all pages from this url ""url = "https://www.iata.org/en/about/members/airline-list/"" and dump the results in a .csv file.

How could implementing a piece of code to iterate through the pages be included in the current code below?

import requests
import pandas as pd
from bs4 import BeautifulSoup
from urllib.request import Request

url = 'https://www.iata.org/en/about/members/airline-list/'
req = Request(url , headers = {
                            'accept':'*/*',
                            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'})

data = []

while True:
    print(url)
    html = requests.get(url)
    soup = BeautifulSoup(html.text, 'html.parser')
    data.append(pd.read_html(soup.select_one('table.datatable').prettify())[0])

    if soup.select_one('span.pagination-link.is-active + div a[href]'):
        url = soup.select_one('span.pagination-link.is-active + div a')['href']
    else:
        break
df = pd.concat(data)
df.to_csv('airline-list.csv',encoding='utf-8-sig',index=False)

Body:
To get data dynamically, use:

import pandas as pd
import requests
import bs4

url = 'https://www.iata.org/en/about/members/airline-list/?page={page}&search=&ordering=Alphabetical'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'}

# Total number of pages
html = requests.get(url.format(page=1), headers=headers)
soup = bs4.BeautifulSoup(html.text)
pages = int(soup.find_all('a', {'class': 'pagination-link'})[-2].text)

data = []
for page in range(1, pages+1):
    html = requests.get(url.format(page=page, headers=headers))
    data.append(pd.read_html(html.text)[0])
df = pd.concat(data)

Output:

>>> df
             Airline Name IATA Designator 3 digit code ICAO code           Country / Territory
0                 ABX Air              GB          832       ABX                 United States
1         Aegean Airlines              A3          390       AEE                        Greece
2              Aer Lingus              EI           53       EIN                       Ireland
3          Aero Republica              P5          845       RPB                      Colombia
4                Aeroflot              SU          555       AFL            Russian Federation
..                    ...             ...          ...       ...                           ...
3                 WestJet              WS          838       WJA                        Canada
4   White coloured by you              WI           97       WHT                      Portugal
5                 Wideroe              WF          701       WIF                        Norway
6         Xiamen Airlines              MF          731       CXA  China (People's Republic of)
7      YTO Cargo Airlines              YG          860       HYT  China (People's Republic of)

[288 rows x 5 columns]


问:
Qt Creator : QML : How to rotate a live video
I'm trying to display a live video I'm getting from an external camera and rotate it (in live) according to an angle sent every second by an arduino card.

My problem, for now, is "just" to have a button that will rotate the live video by 45 degrees when clicked.

I've tried with a Qt Widget Application and C++ code, but I've seen that QML would be easier to deal with live video and camera.

So here is my QML code :

Main.cpp

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}
</code>```

Test.pro

```<code>TEMPLATE = app

QT += qml quick
CONFIG += c++11

SOURCES += main.cpp

RESOURCES += qml.qrc
</code>```

main.qml

```<code>import QtQuick 2.3
import QtQuick.Window 2.2
import QtMultimedia 5.9
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.2

Window {
    visible: true

    width: Screen.height/2
    height: Screen.width/2

    Camera {
        id: camera
        captureMode: Camera.CaptureStillImage
    }

    VideoOutput {
        anchors.fill: parent
        source: camera
        focus : visible

    }

    ColumnLayout {
        anchors.fill: content
        spacing: 10

        RowLayout {
            spacing: 10

            Button {
                id: btnTrasera
                text: "Rotation"
                onClicked: camera.rotation = 45
            }
        }

        Item {
            Layout.fillWidth: true
            Layout.fillHeight: true
        }

    }

}
</code>```

I can't find any function that allows me to rotate the camera or VideoOutput. I think I've to change the class of my video to be able to do it but I can't find how, probably because I'm a begginer in Qt creator.

If any of you have any idea to help, I would be glad to here it !

Koda

答:
Thanks to @JarMan I manage to do it, so I'm posting the code here :

main.qml

```<code>import QtQuick.Window 2.2
import QtMultimedia 5.9
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.2

Window {
    visible: true

    width: Screen.height/2
    height: Screen.width/2

    Camera {
        id: camera
        captureMode: Camera.CaptureStillImage
    }

    Item {
        id: itemVideo
        anchors.fill: parent
        VideoOutput {
            anchors.fill: parent
            source: camera
            focus : visible
         }

    }

    ColumnLayout {
        anchors.fill: parent
        spacing: 10

        RowLayout {
            spacing: 10

            Button {
                id: btnTrasera
                text: "Rotation"
                onClicked: itemVideo.rotation = itemVideo.rotation + 45
            }

        }

        Item {
            Layout.fillWidth: true
            Layout.fillHeight: true
        }

    }

}

</code>```

Thanks !

Body:
I'm trying to display a live video I'm getting from an external camera and rotate it (in live) according to an angle sent every second by an arduino card.

My problem, for now, is "just" to have a button that will rotate the live video by 45 degrees when clicked.

I've tried with a Qt Widget Application and C++ code, but I've seen that QML would be easier to deal with live video and camera.

So here is my QML code :

Main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

Test.pro

TEMPLATE = app

QT += qml quick
CONFIG += c++11

SOURCES += main.cpp

RESOURCES += qml.qrc

main.qml

import QtQuick 2.3
import QtQuick.Window 2.2
import QtMultimedia 5.9
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.2

Window {
    visible: true

    width: Screen.height/2
    height: Screen.width/2

    Camera {
        id: camera
        captureMode: Camera.CaptureStillImage
    }

    VideoOutput {
        anchors.fill: parent
        source: camera
        focus : visible

    }

    ColumnLayout {
        anchors.fill: content
        spacing: 10

        RowLayout {
            spacing: 10

            Button {
                id: btnTrasera
                text: "Rotation"
                onClicked: camera.rotation = 45
            }
        }

        Item {
            Layout.fillWidth: true
            Layout.fillHeight: true
        }

    }

}

I can't find any function that allows me to rotate the camera or VideoOutput. I think I've to change the class of my video to be able to do it but I can't find how, probably because I'm a begginer in Qt creator.

If any of you have any idea to help, I would be glad to here it !

Koda

Body:
Thanks to @JarMan I manage to do it, so I'm posting the code here :

main.qml

import QtQuick.Window 2.2
import QtMultimedia 5.9
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.2

Window {
    visible: true

    width: Screen.height/2
    height: Screen.width/2

    Camera {
        id: camera
        captureMode: Camera.CaptureStillImage
    }

    Item {
        id: itemVideo
        anchors.fill: parent
        VideoOutput {
            anchors.fill: parent
            source: camera
            focus : visible
         }

    }

    ColumnLayout {
        anchors.fill: parent
        spacing: 10

        RowLayout {
            spacing: 10

            Button {
                id: btnTrasera
                text: "Rotation"
                onClicked: itemVideo.rotation = itemVideo.rotation + 45
            }

        }

        Item {
            Layout.fillWidth: true
            Layout.fillHeight: true
        }

    }

}

Thanks !


问:
GPU underutilized in Actor Critic (A2C) Stable Baselines3 implementation
I am trying to use A2C of StablesBaselines3 for training an agent on my custom environment. My problem is that my GPU Utilization is very less (around 10 % only) while my CPU utilization has hit the ceiling. Because of this the training is very very slow. I have tried the following things as per this discussion thread addressed by @araffin
[https://github.com/hill-a/stable-baselines/issues/308]

Expanding the Actor and Critic architecture to a three layer neural
network having 256, 256 and 128 neurons respectively. The GPU
utilization did increase after that but it was only marginal
(increased from 10 % to 15 %) as in this suggestion

changed device argument of A2C method to 'cuda' from the default which is 'auto' -
No improvement

It is not entirely clear what worked for the user in the above mentioned discussion.
My A2C is intialized as follows:

```<code>import gym
from stable_baselines3 import A2C
policy_kwargs = dict(activation_fn=th.nn.ReLU,
                     net_arch=[dict(pi=[256, 256, 128], vf=[256, 256, 128])])
model = A2C("MlpPolicy", env, verbose=1,  learning_rate=linear_schedule(0.001),\
 n_steps=50, gamma=0.8, gae_lambda=1.0, ent_coef=0.2, vf_coef=0.2, \
tensorboard_log=logdir,  policy_kwargs=policy_kwargs, seed=50, device='cuda' )
model.learn(total_timesteps=50000)
</code>```

GPU configurations are:

Cuda version - 9.0

GPU - NVIDIA RTX 2080i

GPU mem - 11GB (out of that only about 1600MB is being used)

CPU configurations

Threads per Core - 2

Core per socket - 8

Intel i9 core 9900 K @ 3.6 Ghz

CPU Mem - 32GB
SW versions

Torch - 1.6.0

Tensorflow GPU - 2.4.1 (although I know SB3 implementation uses Torch)

Python 3.7 on anaconda environment

Any help will be appreciated!

答:
Stable baselines is using your gpu ... if you look task manager
on second tab click on your gpu and instead of 3D
select cuda and you will see the usage of cuda

I had some troubles with my env because my env uses pandas .. and pandas use cpu .. on windows is not possible easly to use cudf so my cpu was using 100%

I used pandas and numpy on my custom env ..
to improve it I should use cunumery and cudf instead, but to do it I need linux.

so for now, my cpu is using 100% gpu is using cuda 70% and gpu memory almost 1.7 gb

Body:
I am trying to use A2C of StablesBaselines3 for training an agent on my custom environment. My problem is that my GPU Utilization is very less (around 10 % only) while my CPU utilization has hit the ceiling. Because of this the training is very very slow. I have tried the following things as per this discussion thread addressed by @araffin
[https://github.com/hill-a/stable-baselines/issues/308]

Expanding the Actor and Critic architecture to a three layer neural
network having 256, 256 and 128 neurons respectively. The GPU
utilization did increase after that but it was only marginal
(increased from 10 % to 15 %) as in this suggestion

changed device argument of A2C method to 'cuda' from the default which is 'auto' -
No improvement

It is not entirely clear what worked for the user in the above mentioned discussion.
My A2C is intialized as follows:

import gym
from stable_baselines3 import A2C
policy_kwargs = dict(activation_fn=th.nn.ReLU,
                     net_arch=[dict(pi=[256, 256, 128], vf=[256, 256, 128])])
model = A2C("MlpPolicy", env, verbose=1,  learning_rate=linear_schedule(0.001),\
 n_steps=50, gamma=0.8, gae_lambda=1.0, ent_coef=0.2, vf_coef=0.2, \
tensorboard_log=logdir,  policy_kwargs=policy_kwargs, seed=50, device='cuda' )
model.learn(total_timesteps=50000)

GPU configurations are:

Cuda version - 9.0

GPU - NVIDIA RTX 2080i

GPU mem - 11GB (out of that only about 1600MB is being used)

CPU configurations

Threads per Core - 2

Core per socket - 8

Intel i9 core 9900 K @ 3.6 Ghz

CPU Mem - 32GB
SW versions

Torch - 1.6.0

Tensorflow GPU - 2.4.1 (although I know SB3 implementation uses Torch)

Python 3.7 on anaconda environment

Any help will be appreciated!


问:
Why are field initializers of a derived class are executed before base classes's initializers
constructors are executed in the order from top to bottom I.E. base's first followed by derived one. This arangement is based on an important OOP assurance that an object (base here) must always be initialized before it can be used (here in derived class's constructor).

I'm wondering why field-initializers do not follow this principle in C#? Am I missing something here?

I've come across a usefulness of this principle with field-initializers as well. I have a base class with a property returning Identity object. Every derived class has its own repository field which I have been initializing using field-initializer (using default constructor). Recently I've decided that the repository class must also be provided with Identity object so I introduced an extra argument in the repository constructor. But I'm stuck to find out:

```<code>public class ForumController : AppControllerBase
{
        ForumRepository repository = new ForumRepository(Identity);
    // Above won't compile since Identity is in the base class.

   // ... Action methods.
}
</code>```

Now I'm left with only one option that is to plump my every controller with a default constructor for only to do the job of initializing of repository object with Identity.

答:
Field initialisers are executed in the constructor, and as the constructor in the base class is called first, all field initialisers are also executed before the derived constructor executes.

Example:

```<code>public class Base {

  // field initialiser:
  private string _firstName = "Arthur";

  public string FirstName { get { return _firstName;}}
  public string LastName { get; private set; }

  // initialiser in base constructor:
  public Base() {
    LastName = "Dent";
  }

}

public class Derived : Base {

  public string FirstNameCopy { get; private set; }
  public string LastNameCopy { get; private set; }

  public Derived() {
    // get values from base class:
    FirstNameCopy = FirstName;
    LastNameCopy = LastName;
  }

}
</code>```

Test:

```<code>Derived x = new Derived();
Console.WriteLine(x.FirstNameCopy);
Console.WriteLine(x.LastNameCopy);
</code>```

Output:

```<code>Arthur
Dent
</code>```

Body:
constructors are executed in the order from top to bottom I.E. base's first followed by derived one. This arangement is based on an important OOP assurance that an object (base here) must always be initialized before it can be used (here in derived class's constructor).

I'm wondering why field-initializers do not follow this principle in C#? Am I missing something here?

I've come across a usefulness of this principle with field-initializers as well. I have a base class with a property returning Identity object. Every derived class has its own repository field which I have been initializing using field-initializer (using default constructor). Recently I've decided that the repository class must also be provided with Identity object so I introduced an extra argument in the repository constructor. But I'm stuck to find out:

public class ForumController : AppControllerBase
{
        ForumRepository repository = new ForumRepository(Identity);
    // Above won't compile since Identity is in the base class.

   // ... Action methods.
}

Now I'm left with only one option that is to plump my every controller with a default constructor for only to do the job of initializing of repository object with Identity.

Body:
Field initialisers are executed in the constructor, and as the constructor in the base class is called first, all field initialisers are also executed before the derived constructor executes.

Example:

public class Base {

  // field initialiser:
  private string _firstName = "Arthur";

  public string FirstName { get { return _firstName;}}
  public string LastName { get; private set; }

  // initialiser in base constructor:
  public Base() {
    LastName = "Dent";
  }

}

public class Derived : Base {

  public string FirstNameCopy { get; private set; }
  public string LastNameCopy { get; private set; }

  public Derived() {
    // get values from base class:
    FirstNameCopy = FirstName;
    LastNameCopy = LastName;
  }

}

Test:

Derived x = new Derived();
Console.WriteLine(x.FirstNameCopy);
Console.WriteLine(x.LastNameCopy);

Output:

Arthur
Dent


问:
Azure EventHub Premium Throughput Limit
What are the throughput limits of Azure Event Hub we have to calculate when using Event Hub Premium?

The documentation says there are no limits per PU when using the Premium tier but i don't understand what that means.

If there are no limits why should i ever then use more than 1 PU ?

We currently calculate with 15 MB / second ingress and activating capture which results in roughly €2000.

When i compare this to premium where capture and ingress is included, 1 PU only costs ~ € 900. So this would save us a lot of money but i'm just now sure if 1 PU can handle 15 MB / second ingress.

答:
You may want to take a look at Scaling with Event Hubs, which describes some of the considerations in more detail.

With respect to processing units, the docs say:

How much you can ingest and stream with a processing unit depends on various factors such as your producers, consumers, the rate at which you're ingesting and processing, and much more. One processing unit can approximately offer core capacity of ~5-10 MB/s ingress and 10-20 MB/s egress, given that we have sufficient partitions so that storage is not a throttling factor.

Based on that, it seems as though you'll need at least 2 PUs to handle your 15mbps ingress rate.

Title: Azure EventHub Premium Throughput Limit


问:
How to authenticate qliksense enterprise and connect from the browser
I'm building a qliksense mashup using React. I can authenticate and connect to the SaaS version of qliksense and would now like to connect to the Enterprise version of qliksense. How can I authenticate and connect from the browser. Would that be possible and how?</p>

答:
You can achieve this via redirect, here is an example in Angular (https://github.com/qlik-oss/enigma.js/blob/master/examples/complete/car-models/README.md). The authentication flow would be the same in React.

The framework I've built, Motor.js also supports this out of the box (https://motor.so/).

Thanks,
Luke


问:
Numeric UDL operator template
I'm trying to define what Pablo Halpern calls a numeric UDL operator template. I want it to return a lambda that would count how many characters at the beginning of a char array are from the given set.

Here's my test code:

```<code>template <char... c>
constexpr auto operator ""_cntany() {
  return [](const char* s){
    unsigned n = 0;
    while (((*s==c) || ...)) { ++n; ++s; }
    return n;
  };
}

int main(int argc, char** argv) {
  return ("test"_cntany)(argv[1]);
}
</code>```

But this doesn't compile with GCC 11.2 (https://godbolt.org/z/TdbKzTMW8).
Here's the error I'm getting:

```<code><source>: In function 'int main(int, char**)':
<source>:11:15: error: no matching function for call to 'operator""_cntany<"test">()'
  11 |       return ("test"_cntany)(argv[1]);
      |               ^~~~~~~~~~~~~
<source>:2:20: note: candidate: 'template<char ...c> constexpr auto operator""_cntany()'
    2 |     constexpr auto operator ""_cntany() {
      |                    ^~~~~~~~
<source>:2:20: note:   template argument deduction/substitution failed:
<source>:11:15: error: '"test"' is not a valid template argument for type 'char' because string literals can never be used in this context
  11 |       return ("test"_cntany)(argv[1]);
     |               ^~~~~~~~~~~~~
Compiler returned: 1
</code>```

What am I doing wrong?

答:
cppreference says

If the literal operator is a template, it must have an empty parameter list and can have only one template parameter, which must be a non-type template parameter pack with element type char (in which case it is known as a numeric literal operator template)

template <char...> double operator "" _x();
```

Also see [over.literal.5]

i.e. it's numeric-, and not a string literal.

It can be used like 123_cntany.

Note, there is a new C++20 string literal operator template: see this answer

Title: Numeric UDL operator template

Body:
I'm trying to define what Pablo Halpern calls a numeric UDL operator template. I want it to return a lambda that would count how many characters at the beginning of a char array are from the given set.

Here's my test code:

template <char... c>
constexpr auto operator ""_cntany() {
  return [](const char* s){
    unsigned n = 0;
    while (((*s==c) || ...)) { ++n; ++s; }
    return n;
  };
}

int main(int argc, char** argv) {
  return ("test"_cntany)(argv[1]);
}

But this doesn't compile with GCC 11.2 (https://godbolt.org/z/TdbKzTMW8).
Here's the error I'm getting:

<source>: In function 'int main(int, char**)':
<source>:11:15: error: no matching function for call to 'operator""_cntany<"test">()'
  11 |       return ("test"_cntany)(argv[1]);
      |               ^~~~~~~~~~~~~
<source>:2:20: note: candidate: 'template<char ...c> constexpr auto operator""_cntany()'
    2 |     constexpr auto operator ""_cntany() {
      |                    ^~~~~~~~
<source>:2:20: note:   template argument deduction/substitution failed:
<source>:11:15: error: '"test"' is not a valid template argument for type 'char' because string literals can never be used in this context
  11 |       return ("test"_cntany)(argv[1]);
     |               ^~~~~~~~~~~~~
Compiler returned: 1

What am I doing wrong?

Body:
cppreference says

If the literal operator is a template, it must have an empty parameter list and can have only one template parameter, which must be a non-type template parameter pack with element type char (in which case it is known as a numeric literal operator template)

template <char...> double operator "" _x();

Also see [over.literal.5]

i.e. it's numeric-, and not a string literal.

It can be used like 123_cntany.

Note, there is a new C++20 string literal operator template: see this answer


问:
SwitfUI ForEach Index
I want to display an ordered List, have this code:

```<code>List {
    var i = 1
    ForEach(definitions, id: \.self) { definition in
        Text("\(i). \(definition)")
        // a little bit ugly
        let _ = i += 1
    }
}
</code>```

Is there nicer option?

答:
```<code>List {
    ForEach(definitions.indices, id: \.self) { i in
        Text("\(i). \(definitions[i])")
    }
}
</code>```

Title: SwitfUI ForEach Index

Body:
I want to display an ordered List, have this code:

List {
    var i = 1
    ForEach(definitions, id: \.self) { definition in
        Text("\(i). \(definition)")
        // a little bit ugly
        let _ = i += 1
    }
}

Is there nicer option?


问:
How can I Compare 2 Audio Files Programmatically?
I want to compare 2 audio files programmatically.
For example: I have a sound file in my iPhone app, and then I record another one. I want to check if the existing sound matches the recorded sound or not ( - similar to voice recognition).

How can I accomplish this?

答:
I think as well you may try to select a few second sample from both audio track, mnormalise them in amplitude and reduce noise with a band pass filter and after try to use a correlator.

for instance you may take a 5 second sample of one of the thwo and made it slide over the second one computing a cross corelation for any time you shift. (be carefull that if you take a too small pachet you may have high correlation when not expeced and you will soffer the side effect due to the croping of the signal and the crosscorrelation).
After yo can collect an array with al the results of the cross correlation and get the index of the maximun.

You should then set experimentally up threshould o decide when yo assume the pachet to b the same. this will change depending on the quality of the audio track you are comparing.

I implemented a correator to receive and distinguish preamble in wireless communication. My script is actually done in matlab. if you are interested i can try to find the common part and send it to you.

It would be a too long code to be pasted hene in the forum. if you want just let me know and i will send it to ya asap.

cheers


问:
Make sure that data is loaded before the application startup | Spring webflux
I have a spring webflux application.

I am loading some list from database into bean. I have two ways of implementing the loading of this bean.

Approach 1: Reactive Way

```<code>@Bean
  public List<Item> getItemList() throws IOException {
     List<Item> itemList = new ArrayList<>();
     itemRespository.findAll().collectList().subscribe(itemList::addAll);
     return itemList;
  }
</code>```

Approach 2 : Blocking way

```<code>@Bean
public List<Item> getItemList() throws IOException {
     List<Item> itemList = itemRespository.findAll().collectList().block();
     return itemList;
 }
</code>```

Now as I want my application to be reactive, I don't want to use the blocking way.
But the endpoints which I am exposing through my controller depends on this bean's data.

```<code>@RestController
public class SomeController{

   @Autowired
   private List<items> getItemList;

   @GetMapping('/endpoint')
   public void process(){
     List list = getItemList; //this may not get initialzed as the bean loading is reactive

     //some more code
}
}
</code>```

So in case of reactive approach, it may happen that somebody may call my endpoint(as application has already started and ready to serve requests), while due to some reason it may happened that my list has yet not bean retrieved from database(may be any reason ex: slowness of database server etc.), producing inconsistent results for the users calling my endpoint(which in turns depend on this bean).

I am looking for a solution for this scenario.

EDIT :  More precise question is that should I load those beans reactively in my application, on which my exposed endpoints are dependent?

答:
The current application architecture solution presented is a typical example on a design that is inherently blocking.

If the first request made to the api needs the items to be in place, then we must sure that they are there before we can take on requests. And the only way to ensure that is to block until the items de facto have been fetched and stored.

Since the design is inherently blocking, we need to rethink our approach.

What we want is to make the service available for requests as quick as possible. We can solve this by using a cache, that will get filled when the first request is made.

Which means application starts up with an empty cache. This cache could for instance be a @Component as spring beans are singletons by default.

the steps would be:

service starts up, cache is empty

service receives its first request

checks if there is data in the cache

if data is stale, evict the cache

if cache is empty, fetch the data from our source

fill the cache with our fetched data

set a ttl (time to live) on the data placed in the cache

return the data to the calling client

Second request:

request comes in to the service

checks if there is data in the cache

checks if the data is stale

if not grab the data and return it to the calling subscriber

There are several cache solutions out there, spring has their @Cachable annotation, which by default is just a key value store, but can be paired with an external solution like redis etc.

Other solutions can be Google guava which has a very good read on their github.

This type of solution is called trading memory for cpu we gain startup time and fast requests (cpu), but the cost is we will spend some more memory to hold data in a cache.

Body:
I have a spring webflux application.

I am loading some list from database into bean. I have two ways of implementing the loading of this bean.

Approach 1: Reactive Way

@Bean
  public List<Item> getItemList() throws IOException {
     List<Item> itemList = new ArrayList<>();
     itemRespository.findAll().collectList().subscribe(itemList::addAll);
     return itemList;
  }

Approach 2 : Blocking way

@Bean
public List<Item> getItemList() throws IOException {
     List<Item> itemList = itemRespository.findAll().collectList().block();
     return itemList;
 }

Now as I want my application to be reactive, I don't want to use the blocking way.
But the endpoints which I am exposing through my controller depends on this bean's data.

@RestController
public class SomeController{

   @Autowired
   private List<items> getItemList;

   @GetMapping('/endpoint')
   public void process(){
     List list = getItemList; //this may not get initialzed as the bean loading is reactive

     //some more code
}
}

So in case of reactive approach, it may happen that somebody may call my endpoint(as application has already started and ready to serve requests), while due to some reason it may happened that my list has yet not bean retrieved from database(may be any reason ex: slowness of database server etc.), producing inconsistent results for the users calling my endpoint(which in turns depend on this bean).

I am looking for a solution for this scenario.

EDIT :  More precise question is that should I load those beans reactively in my application, on which my exposed endpoints are dependent?


问:
How to get background image to 100vh on smaller screens but 50vh on large screens?
Learning bootstrap, I am trying to make a hero section on my website where if you are on the large screen breakpoint, the background image on the hero section will be 50% of the web page, but on smaller screens it will change to 100% of the webpage.

I think the problem lies with me setting height:50vh, I just simply don't know what to write on the bootstrap portion where if the screen switches to small, the height becomes 100.

Thank you!

.bg-image {
  width: 100%;
  height: 50vh;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-image: linear-gradient(to bottom, rgba(118, 118, 121, 0.432), rgba(82, 76, 80, 0.73)), url('https://via.placeholder.com/800/ff0000');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<div class="bg-image p-5 text-light ">
  <div class="container text-center pt-5 h-100 ">
    <h1 class="m-5">I Need Help </h1>
    <button class="btn-primary rounded-pill">Book Us</button>
  </div>
</div></code>```

答:
Bootstrap's small (sm) breakpoint is at screen widths less than 768px. You can use a media query for this...

```<code>.bg-image {
    height: 100vh;
    background-color: red;
}

@media (min-width: 768px) {
    .bg-image {
        height: 50vh;
    }
}
</code>```

https://codeply.com/p/wvMY8zAx9H

Body:
Learning bootstrap, I am trying to make a hero section on my website where if you are on the large screen breakpoint, the background image on the hero section will be 50% of the web page, but on smaller screens it will change to 100% of the webpage.

I think the problem lies with me setting height:50vh, I just simply don't know what to write on the bootstrap portion where if the screen switches to small, the height becomes 100.

Thank you!

.bg-image {
  width: 100%;
  height: 50vh;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-image: linear-gradient(to bottom, rgba(118, 118, 121, 0.432), rgba(82, 76, 80, 0.73)), url('https://via.placeholder.com/800/ff0000');
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

I Need Help

    <button class="btn-primary rounded-pill">Book Us</button>

Body:
Bootstrap's small (sm) breakpoint is at screen widths less than 768px. You can use a media query for this...

.bg-image {
    height: 100vh;
    background-color: red;
}

@media (min-width: 768px) {
    .bg-image {
        height: 50vh;
    }
}

https://codeply.com/p/wvMY8zAx9H


问:
Unit Testing UNUserNotificationCenterDelegate Methods
I'd like to unit test some UNUserNotificationCenterDelegate methods, especially userNotificationCenter(_, willPresent:, withCompletionHandler:)

To do that, I'd have to create an instance of UNNotification, but that's not really possible because it only has an initWithCoder initializer. What to do?

This is an example of what I'd like to test:

```<code>func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
    completionHandler(.sound)
}
</code>```

答:
You can use class_createInstance(UNNotification.classForKeyedArchiver() ...)and cast the value as UNNotification

If you want to manipulate its content and date members you can subclass UNNotification and use this same formula «changing class name and cast» to create it, then you override those members- which are open- and return whatever you want

Body:
I'd like to unit test some UNUserNotificationCenterDelegate methods, especially userNotificationCenter(_, willPresent:, withCompletionHandler:)

To do that, I'd have to create an instance of UNNotification, but that's not really possible because it only has an initWithCoder initializer. What to do?

This is an example of what I'd like to test:

func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
    completionHandler(.sound)
}


答:
C++ doesn't have udl for string with that template format unfortunately.

gcc has an extension for that template <typename Char, Char... c>

so it would be

```<code>template <typename Char, Char... c>
constexpr auto operator ""_cntany() {
  return [](const char* s){
    unsigned n = 0;
    while (((*s==c) || ...)) { ++n; ++s; }
    return n;
  };
}
</code>```

but it is not portable as extension.

Title: Numeric UDL operator template

Body:
C++ doesn't have udl for string with that template format unfortunately.

gcc has an extension for that template <typename Char, Char... c>

so it would be

template <typename Char, Char... c>
constexpr auto operator ""_cntany() {
  return [](const char* s){
    unsigned n = 0;
    while (((*s==c) || ...)) { ++n; ++s; }
    return n;
  };
}

but it is not portable as extension.


问:
Time of system startup in python
I'm working on a Windows application  that will show time when my system was started. I tried to do something with WMI, I took SystemUpTime, but it gave me time since last startup. I am looking for first startup per day, so for example if user will turn on computer at 7:00 and later will do restart at 9:00 it should still show 7:00. Is there any library which can be helpful?</p>

答:
I'm not aware of a library that would do this.

One option would be to:

Make your program run on startup.

Save the boot time each time your program runs

Display the earliest boot time for the current day.

Save the boot times in sqlite3, its built in to Python these days.

Title: Time of system startup in python


问:
Mock UNNotificationResponse & UNNotification (and other iOS platform classes with init() marked as unavailable)
I need to mock UNNotificationResponse and UNNotification so that I can test my implementation of:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void)

However I can't usefully subclass these classes because init() is specifically marked as unavailable, resulting in compilation errors like this if I try:

/Path/to/PushClientTests.swift:38:5: Cannot override 'init' which has been marked unavailable

What alternate approaches can be taken here? I look into going down the Protocol Oriented Programming route, however since I do not control the API being called, I can't modify it to take the protocols I'd write.

答:
You can use class_createInstance(UNNotification.classForKeyedArchiver() ...)and cast the value as UNNotification

If you want to manipulate its content and date members you can subclass UNNotification and use this same formula «changing class name and cast to your subclass» to create it, then you override those members- which are open- and return whatever you want


问:
How to use css counters in nested lists without parent index while not using a separate counter for each level
My code example:

.list {
    counter-reset: section;
}

.item::before {
    counter-increment: section;
    content: counters(section, ".") '. ';
}

.list .list .item {
    margin-left: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='list'>
      <div class='item'>item</div>
      <div class='item'>item
        <div class='list'>
          <div class='item'>item</div>
          <div class='item'>item</div>
          <div class='item'>item </div>

        </div>
      </div>
      <div class='item'>item</div>
      <div class='item'>item</div>
    </div></code>```

The above code outputs：

```<code>1. item
2. item
   2.1. item
   2.2. item
   2.3. item
3. item
4. item
</code>```

I want the child items not to have a parent index, like the following:

```<code>1. item
2. item
   1. item
   2. item
   3. item
3. item
4. item
</code>```

I am aware that this can be achieved with a separate counter for each level, but then you need to write out the CSS for each counter. In my real use case, there are unpredictable levels and I don't control the HTML. There could be 50 levels and I can't possibly write out all the 50 sets of CSS rules. That's why I use the counters() function, which handles multiple levels automatically. The question is, the counters() function comes with the parent index. Is it possible at all to get rid of it?

If pure CSS can't do it, can we do it with the help of JS?

答:
Looks funny, but you might use counter() not counters():

.list {
  counter-reset: section;
}

.item::before {
  counter-increment: section;
  content: counter(section) '. ';
}

.list .list .item {
  margin-left: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='list'>
  <div class='item'>item</div>
  <div class='item'>item
    <div class='list'>
      <div class='item'>item</div>
      <div class='item'>item
        <div class='list'>
          <div class='item'>item</div>
          <div class='item'>item</div>
          <div class='item'>item </div>

        </div>
      </div>
      <div class='item'>item </div>

    </div>
  </div>
  <div class='item'>item</div>
  <div class='item'>item</div>
</div></code>```

BTW, it's weird to make lists with
s when
 and
 are available and intended exactly for that purpose.

Body:
My code example:

.list {
    counter-reset: section;
}

.item::before {
    counter-increment: section;
    content: counters(section, ".") '. ';
}

.list .list .item {
    margin-left: 30px;
}

item

item

item

item

item

item

item

The above code outputs：

1. item
2. item
   2.1. item
   2.2. item
   2.3. item
3. item
4. item

I want the child items not to have a parent index, like the following:

1. item
2. item
   1. item
   2. item
   3. item
3. item
4. item

I am aware that this can be achieved with a separate counter for each level, but then you need to write out the CSS for each counter. In my real use case, there are unpredictable levels and I don't control the HTML. There could be 50 levels and I can't possibly write out all the 50 sets of CSS rules. That's why I use the counters() function, which handles multiple levels automatically. The question is, the counters() function comes with the parent index. Is it possible at all to get rid of it?

If pure CSS can't do it, can we do it with the help of JS?

Body:
Looks funny, but you might use counter() not counters():

.list {
  counter-reset: section;
}

.item::before {
  counter-increment: section;
  content: counter(section) '. ';
}

.list .list .item {
  margin-left: 30px;
}

<div class='list'>
  <div class='item'>item</div>
  <div class='item'>item
    <div class='list'>
      <div class='item'>item</div>
      <div class='item'>item
        <div class='list'>
          <div class='item'>item</div>
          <div class='item'>item</div>
          <div class='item'>item </div>

        </div>
      </div>
      <div class='item'>item </div>

    </div>
  </div>
  <div class='item'>item</div>
  <div class='item'>item</div>
</div>

BTW, it's weird to make lists with <div>s when <ul> and <ol> are available and intended exactly for that purpose.