问:
How to create a unique string/key form JavaScript object?
I would like to create a unique string/ key/ identifier/ hash from object's values. For example:

```<code>let myObj =
{
  key1: 'val1',
  key2: 'val2',
  key3: 'val3',
  key4: 'val4'
};

function getObjectUniqueKey(obj) {
  return (`${ obj.key1 }|${ obj.key2 }|${ obj.key3 }|${ obj.key4 }`);
}
</code>```

The method getObjectUniqueKey() will work fine, however it isn't scale to bigger objects (my objects have more than 10 keys).

Is there any way in JavaScript to create a unique string that will represent an object? something similar to JSON.stringify() but isn't so robust?

(JSON.stringify will also stringify the keys, but all my objects have the same interface - same key's names - so stringifing them isn't needed).

{ key: 'val1' } and { key: 'val2' } should produce different results.

{ key1: 'val' } and { key2: 'val' } should produce different results.

{ a: 1, b: 2 } and { b: 2, a: 1 } should produce the same result.

答:
A sort is most likely needed if you want to produce the same hash regardless of key order. If you don't want to wind up with absurdly long keys for large objects you'll need some kind of lossy hashing to occur. Note that in order to fully hash an object, we need to be able to hash every type of value within the object. The logic below primarily hashes Arrays of Strings with lossyHashStrs. It can also convert an Object into an Array of Strings by collecting all keys and values into an Array. As mentioned, every value within the Object needs to be hashable. The below code handles String, Number, and Object values. It will choke if the Object includes an Array as a property, for example (but could be extended to handle this!)

Overall, hashes will be strings that appear like 12-digit decimal numbers, with leading zeros if necessary.

// A utility function for checking variable types
let isType = (v, type) => (v == null && type == null) || v.constructor === type;

let lossyHashStrs = strs => {

  // Convert an Array of Strings into a String that looks like a 12-digit number

  let max = 999999999999;
  let n1 = 129837378393;
  let n2 = 348973984723;
  for (let str of strs) { // Loop over all strings...
    for (let i = 0; i < str.length; i++) { // Loop over characters of the current string...
      // Some homebrewed hashing chaos, which factors in the current character
      n2 = (7 + n2 * n1 * str.charCodeAt(i)) % max;
      n1 = (11 + n1 * n2 + n2 * n2) % max;
    }
  }
  return `${n1}`.padStart(`${max}`.length, '0');
};

let lossyHashObj = obj => {

  // Convert an Object into an Array of Strings, then return the `lossyHashStrs` result

  let vals = [];
  let keys = Object.keys(obj).sort();
  for (let key of keys) {
    vals.push(key);
    let val = obj[key];

    // Ensure that `val` can be converted to a String:

    // If `val` is already a String, no dilemma!
    if (isType(val, String)) vals.push(val);

    // If `val` is a Number, simply use `toString`
    else if (isType(val, Number)) vals.push(val.toString());

    // If `val` is an Object recursively call `lossyHashObj` (yes - circular references will repeat infinitely)
    else if (isType(val, Object)) vals.push(lossyHashObj(val));

    // TODO:
    // else if (isType(val, Array)) /* ... */

    // Throw an Error for any other type of value
    else throw new Error(`Object contains a ${val.constructor.name}; don't know how to hash :(`);

  }
  return lossyHashStrs(vals);

};

let tests = [
  [ { a: 1 }, { a: 1 } ],
  [ { a: 1 }, { a: 2 } ],
  [ { a: 1, b: 1 }, { a: 1, b: 1 } ],
  [ { a: 1, b: 2 }, { a: 2, b: 1 } ],
  [ { a: 2, b: 3 }, { b: 3, c: 4 } ],
  [ { c: 3, b: 2, a: 1 }, { a: 1, b: 2, c: 3 } ]
]

for (let [ v1, v2 ] of tests) {

  let hash1 = lossyHashObj(v1);
  let hash2 = lossyHashObj(v2);
  console.log([
    `Compare:`,
    `  ${JSON.stringify(v1)} (hash: ${hash1})`,
    `  ${JSON.stringify(v2)} (hash: ${hash2})`,
    `Hashes match: ${(hash1 === hash2).toString().toUpperCase()}`
  ].join('\n'));

}```

Body:
I would like to create a unique string/ key/ identifier/ hash from object's values. For example:

let myObj =
{
  key1: 'val1',
  key2: 'val2',
  key3: 'val3',
  key4: 'val4'
};

function getObjectUniqueKey(obj) {
  return (`${ obj.key1 }|${ obj.key2 }|${ obj.key3 }|${ obj.key4 }`);
}

The method getObjectUniqueKey() will work fine, however it isn't scale to bigger objects (my objects have more than 10 keys).

Is there any way in JavaScript to create a unique string that will represent an object? something similar to JSON.stringify() but isn't so robust?

(JSON.stringify will also stringify the keys, but all my objects have the same interface - same key's names - so stringifing them isn't needed).

{ key: 'val1' } and { key: 'val2' } should produce different results.

{ key1: 'val' } and { key2: 'val' } should produce different results.

{ a: 1, b: 2 } and { b: 2, a: 1 } should produce the same result.


来源: stackexchange

问:
Unable to create new react app with npx create-react-app
I am trying to create new react app with npx create-react-app [name] command. But I get following error:

error Couldn't find package "@babel/plugin-transform-flow-strip-types@7.9.0" required by "babel-preset-react-app@^9.1.2" on the "npm" registry.

Each time it is saying some package could not be found on npm registry (not only @babel/plugin-transform-flow-strip-types@7.9.0 this package).

I have also updated my npm and npx, but no success.

答: You can try deleting the .npmrc file located in Users/you/.npmrc and run the command again, seems there is a bug with npm and this is a workaround

ContentLicense: CC BY-SA 4.0


问:
Why is there an error saying that the object is not found?
The following link displays an image of the coding that I have done:

答:
You need to reference the table you are using, so instead of </p>

```<code>hist(Age)
</code>```

<p>use </p>

```<code>hist(my_data$Age)
</code>```

Body:
You need to reference the table you are using, so instead of

hist(Age)

use

hist(my_data$Age)


问:
Show or hide checkout postcode field based on chosen city in WooCommerce
In Woocommerce, I am trying to hide the checkout postcode field if a specific city field is selected. I found a working code that hides the billing phone if company field is empty:

```<code>add_action( 'woocommerce_after_checkout_form', 'conditionally_hide_show_checkout_field', 9999 );
function conditionally_hide_show_checkout_field() {
wc_enqueue_js( "
  jQuery('#billing_company').keyup(function() {
     if (jQuery(this).val().length == 0) {
        jQuery('#billing_phone').hide();
     } else {
        jQuery('#billing_phone').show();
     }
  }).keyup();
");
}
</code>```

I don't know how to alter this code to make the required postcode field to be hidden when a specific billing city is selected. Any help is appreciated.

答:
It's a bit much more complicated and you will need to define the city in the last function.

The following code handles multiple necessary tasks to show / hide the postcode field based on a specific defined selected city:

```<code>// Make postcode field optional
add_filter( 'woocommerce_default_address_fields',  'customizing_checkout_fields' );
function customizing_checkout_fields( $fields ) {
    if( is_checkout() ) {
        $fields['postcode']['required'] = false;
    }
    return $fields;
}

// Replace "(optional)" text by required "*"
add_filter( 'woocommerce_form_field' , 'replace_checkout_optional_by_required', 10, 4 );
function replace_checkout_optional_by_required( $field, $key, $args, $value ) {
    // Only on checkout page for postcode field
    if( is_checkout() && ! is_wc_endpoint_url() && in_array($key, ['billing_postcode', 'shipping_postcode']) ) {
        $optional = '<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $required = '<abbr class="required" title="required">*</abbr>';
        $field = str_replace( $optional, $required, $field );
    }
    return $field;
}

// Hidden input fields for Postcode validation when it's visible
add_action( 'woocommerce_after_order_notes', 'checkout_hidden_field_for_validation', 10, 1 );
function checkout_hidden_field_for_validation( $checkout ) {
    // Hidden field for the phone number validation
    echo '<input type="hidden" name="billing_postcode_check" id="billing_postcode_check" value="">
          <input type="hidden" name="shipping_postcode_check" id="shipping_postcode_check" value="">';
}

// Postcode field validation when it's visible
add_action('woocommerce_checkout_process', 'wps_select_checkout_field_process');
function wps_select_checkout_field_process() {
    if( isset($_POST['billing_postcode_check']) && $_POST['billing_postcode_check'] === 'yes'
    && isset($_POST['billing_postcode']) && empty($_POST['billing_postcode']) ) {
        wc_add_notice( __("The billing postcode field is a required field.", "woocommerce"), 'error' );
    }

    if( isset($_POST['shipping_postcode_check']) && $_POST['shipping_postcode_check'] === 'yes'
    && isset($_POST['shipping_postcode']) && empty($_POST['shipping_postcode']) ) {
        wc_add_notice( __("The shipping postcode is a required field.", "woocommerce"), 'error' );
    }
}

// Conditional Show hide checkout fields based on chosen payment methods
add_action( 'wp_footer', 'conditionally_show_hide_billing_custom_field' );
function conditionally_show_hide_billing_custom_field(){
    // Only on checkout page
     if ( is_checkout() && ! is_wc_endpoint_url() ) :

     // HERE define the city that will hide postcode field
     $city = 'Paris';

     $required = ' <abbr class="required" title="required">*</abbr>';
    ?>
    <script>
        jQuery(function($){
            var bc   = '#billing_city_field input',
                sc   = '#shipping_city_field input',
                bp   = '#billing_postcode_field',
                sp   = '#shipping_postcode_field',
                bpc  = '#billing_postcode_check',
                spc  = '#shipping_postcode_check',
                city = '<?php echo $city; ?>',
                req  = '<?php echo $required; ?>';

            // On "update" checkout form event, replace "(optional)" by required "*"
            $(document.body).on('update_checkout', function(){
                $('#billing_postcode_field label > .optional').replaceWith(req);
            });

            // Function that shows or hide checkout fields
            function showHide( selector = '', action = 'show' ){
                var check = selector == bp ? $(bpc) : $(spc);
                if( action == 'show' )
                    $(selector).show( 200, function(){
                        $(this).addClass("validate-required");
                        check.val('yes');
                    });
                else
                    $(selector).hide( 200, function(){
                        $(this).removeClass("validate-required");
                        check.val('');
                    });
                $(selector).removeClass("woocommerce-validated");
                $(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
            }

            // 1. Initialising (on load): Show/hide based on customer city

            // Billing field
            if( $(bc).val() === city || $(bc).val() == '' )
                showHide( bp, 'hide' );
            else
                showHide( bp );

            // Shipping field
            if( $(sc).val() === city || $(sc).val() == '' )
                showHide( sp, 'hide' );
            else
                showHide( sp );

            // 2. Change live event:  Show/hide based on city change

            $( 'form.checkout' ).on( 'change input', bc, function() { // Billing field
                if( $(bc).val() === city )
                    showHide( bp, 'hide' );
                else
                    showHide( bp );
            });

            $( 'form.checkout' ).on( 'change input', sc, function() { // Shipping field
                if( $(sc).val() === city )
                    showHide( sp, 'hide' );
                else
                    showHide( sp );
            });
        });
    </script>
    <?php
    endif;
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Some related answers:

Show hide custom Woocommerce checkout field based on selected payment method

Remove "(optional)" text from checkout fields in Woocommerce 3.4+

Hidding billing and shipping postcode on load:

Replace:

```<code>            // 1. Initialising (on load): Show/hide based on customer city

            // Billing field
            if( $(bc).val() === city || $(bc).val() == '' )
                showHide( bp, 'hide' );
            else
                showHide( bp );

            // Shipping field
            if( $(sc).val() === city || $(sc).val() == '' )
                showHide( sp, 'hide' );
            else
                showHide( sp );
</code>```

by:

```<code>            // 1. Initialising (on load): Hide postcode

            showHide( bp, 'hide' ); // Billing field
            showHide( sp, 'hide' ); // Shipping field
</code>```

Body:
In Woocommerce, I am trying to hide the checkout postcode field if a specific city field is selected. I found a working code that hides the billing phone if company field is empty:

add_action( 'woocommerce_after_checkout_form', 'conditionally_hide_show_checkout_field', 9999 );
function conditionally_hide_show_checkout_field() {
wc_enqueue_js( "
  jQuery('#billing_company').keyup(function() {
     if (jQuery(this).val().length == 0) {
        jQuery('#billing_phone').hide();
     } else {
        jQuery('#billing_phone').show();
     }
  }).keyup();
");
}

I don't know how to alter this code to make the required postcode field to be hidden when a specific billing city is selected. Any help is appreciated.

Body:
It's a bit much more complicated and you will need to define the city in the last function.

The following code handles multiple necessary tasks to show / hide the postcode field based on a specific defined selected city:

// Make postcode field optional
add_filter( 'woocommerce_default_address_fields',  'customizing_checkout_fields' );
function customizing_checkout_fields( $fields ) {
    if( is_checkout() ) {
        $fields['postcode']['required'] = false;
    }
    return $fields;
}

// Replace "(optional)" text by required "*"
add_filter( 'woocommerce_form_field' , 'replace_checkout_optional_by_required', 10, 4 );
function replace_checkout_optional_by_required( $field, $key, $args, $value ) {
    // Only on checkout page for postcode field
    if( is_checkout() && ! is_wc_endpoint_url() && in_array($key, ['billing_postcode', 'shipping_postcode']) ) {
        $optional = '<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $required = '<abbr class="required" title="required">*</abbr>';
        $field = str_replace( $optional, $required, $field );
    }
    return $field;
}

// Hidden input fields for Postcode validation when it's visible
add_action( 'woocommerce_after_order_notes', 'checkout_hidden_field_for_validation', 10, 1 );
function checkout_hidden_field_for_validation( $checkout ) {
    // Hidden field for the phone number validation
    echo '<input type="hidden" name="billing_postcode_check" id="billing_postcode_check" value="">
          <input type="hidden" name="shipping_postcode_check" id="shipping_postcode_check" value="">';
}

// Postcode field validation when it's visible
add_action('woocommerce_checkout_process', 'wps_select_checkout_field_process');
function wps_select_checkout_field_process() {
    if( isset($_POST['billing_postcode_check']) && $_POST['billing_postcode_check'] === 'yes'
    && isset($_POST['billing_postcode']) && empty($_POST['billing_postcode']) ) {
        wc_add_notice( __("The billing postcode field is a required field.", "woocommerce"), 'error' );
    }

    if( isset($_POST['shipping_postcode_check']) && $_POST['shipping_postcode_check'] === 'yes'
    && isset($_POST['shipping_postcode']) && empty($_POST['shipping_postcode']) ) {
        wc_add_notice( __("The shipping postcode is a required field.", "woocommerce"), 'error' );
    }
}

// Conditional Show hide checkout fields based on chosen payment methods
add_action( 'wp_footer', 'conditionally_show_hide_billing_custom_field' );
function conditionally_show_hide_billing_custom_field(){
    // Only on checkout page
     if ( is_checkout() && ! is_wc_endpoint_url() ) :

     // HERE define the city that will hide postcode field
     $city = 'Paris';

     $required = '&nbsp;<abbr class="required" title="required">*</abbr>';
    ?>
    <script>
        jQuery(function($){
            var bc   = '#billing_city_field input',
                sc   = '#shipping_city_field input',
                bp   = '#billing_postcode_field',
                sp   = '#shipping_postcode_field',
                bpc  = '#billing_postcode_check',
                spc  = '#shipping_postcode_check',
                city = '<?php echo $city; ?>',
                req  = '<?php echo $required; ?>';

            // On "update" checkout form event, replace "(optional)" by required "*"
            $(document.body).on('update_checkout', function(){
                $('#billing_postcode_field label > .optional').replaceWith(req);
            });

            // Function that shows or hide checkout fields
            function showHide( selector = '', action = 'show' ){
                var check = selector == bp ? $(bpc) : $(spc);
                if( action == 'show' )
                    $(selector).show( 200, function(){
                        $(this).addClass("validate-required");
                        check.val('yes');
                    });
                else
                    $(selector).hide( 200, function(){
                        $(this).removeClass("validate-required");
                        check.val('');
                    });
                $(selector).removeClass("woocommerce-validated");
                $(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
            }

            // 1. Initialising (on load): Show/hide based on customer city

            // Billing field
            if( $(bc).val() === city || $(bc).val() == '' )
                showHide( bp, 'hide' );
            else
                showHide( bp );

            // Shipping field
            if( $(sc).val() === city || $(sc).val() == '' )
                showHide( sp, 'hide' );
            else
                showHide( sp );

            // 2. Change live event:  Show/hide based on city change

            $( 'form.checkout' ).on( 'change input', bc, function() { // Billing field
                if( $(bc).val() === city )
                    showHide( bp, 'hide' );
                else
                    showHide( bp );
            });

            $( 'form.checkout' ).on( 'change input', sc, function() { // Shipping field
                if( $(sc).val() === city )
                    showHide( sp, 'hide' );
                else
                    showHide( sp );
            });
        });
    </script>
    <?php
    endif;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Some related answers:

Show hide custom Woocommerce checkout field based on selected payment method

Remove "(optional)" text from checkout fields in Woocommerce 3.4+

Hidding billing and shipping postcode on load:

Replace:

            // 1. Initialising (on load): Show/hide based on customer city

            // Billing field
            if( $(bc).val() === city || $(bc).val() == '' )
                showHide( bp, 'hide' );
            else
                showHide( bp );

            // Shipping field
            if( $(sc).val() === city || $(sc).val() == '' )
                showHide( sp, 'hide' );
            else
                showHide( sp );

by:

            // 1. Initialising (on load): Hide postcode

            showHide( bp, 'hide' ); // Billing field
            showHide( sp, 'hide' ); // Shipping field


问:
How to switch off Auto Import with IntelliJ/Scala Plugin
Simple Problem: Ever since I switched to Idea 10.5, it has this auto import feature enabled. For a Java developer, this is surely nice, but every time I type thing like var x: Float it automatically adds import java.lang.Float on the beginning of the file. Very often, it even adds imports I did not even want, from unknown packages deep in my jar jungle, and prefers Java over Scala packages.

Played around with the switches in Code completion tab, but it keeps on doing this. How can I get rid of this?

答:
That is plugin bug. This should be fixed soon.
It's impossible to turn off in settings. Sorry for inconveniences.</p>

ContentLicense: CC BY-SA 3.0


问:
Discord.py on_member_join and on_member_leave not working
I started using discord.py (not discord.ext commands, only import discord). Recently, I made a channel, the name of which shows the member count in the guild, and it updates everytime someone joins or leaves. This is my code:

import discord

client = discord.Client()

@client.event
async def on_ready():
    print("Bot is ready")

@client.event
async def on_member_join(member):
    channel = client.get_channel('channel id here')
    await channel.edit(name = 'Member count: {}'.format(channel.guild.member_count()))

@client.event
async def on_member_leave(member):
    channel = client.get_channel('channel id here')
    await channel.edit(name = 'Member count: {}'.format(channel.guild.member_count()))

client.run('my token here')
```
<p>I also added <code>client.on_message</code> command so the bot would edit that name to whatever I typed in.</p>
<pre class="lang-py prettyprint-override"><code>@client.event
async def on_message(message)
     if message.content == 'rename channel':
            channel = client.get_channel('channel id here')
            await channel.edit(name = 'TEST')
</code>```

Now, after adding some print's for debugging, I found out that on_member_join() and on_member_leave() never get called, but the bot edits the channel's name when I type the command. That's a voice channel, which shows member count. There aren't any errors. Did I read the API wrong? Please help

答:
IDs of any kind in discord should be passed as an integer, not a string. Additionally, discord.Guild.member_count is an attribute, not a method, so use it without the parentheses. You should also be using on_member_remove() instead of on_member_leave().

import discord

client = discord.Client()

@client.event
async def on_ready():
    print("Bot is ready")

@client.event
async def on_member_join(member):
    channel = client.get_channel(ID)
    await channel.edit(name = 'Member count: {}'.format(channel.guild.member_count))

@client.event
async def on_member_remove(member):
    channel = client.get_channel(ID)
    await channel.edit(name = 'Member count: {}'.format(channel.guild.member_count))

client.run('my token here')
```

Body:
I started using discord.py (not discord.ext commands, only import discord). Recently, I made a channel, the name of which shows the member count in the guild, and it updates everytime someone joins or leaves. This is my code:

import discord

client = discord.Client()

@client.event
async def on_ready():
    print("Bot is ready")

@client.event
async def on_member_join(member):
    channel = client.get_channel('channel id here')
    await channel.edit(name = 'Member count: {}'.format(channel.guild.member_count()))

@client.event
async def on_member_leave(member):
    channel = client.get_channel('channel id here')
    await channel.edit(name = 'Member count: {}'.format(channel.guild.member_count()))

client.run('my token here')

I also added client.on_message command so the bot would edit that name to whatever I typed in.

@client.event
async def on_message(message)
     if message.content == 'rename channel':
            channel = client.get_channel('channel id here')
            await channel.edit(name = 'TEST')

Now, after adding some print's for debugging, I found out that on_member_join() and on_member_leave() never get called, but the bot edits the channel's name when I type the command. That's a voice channel, which shows member count. There aren't any errors. Did I read the API wrong? Please help


问:
Function to convert letter-number coordinates to 2D array indices
I'm trying to build a board game where my board is a 2D array of lists.

```<code>self._board = [["A", "B", "C"],
               ["D", "E", "F"],
               ["G", "H", "I"]]
</code>```

How can I write a function that can be used to access each piece by using letter-number coordinates.
So for example I can use the function to get "A" by using converter(A1) or "F" by using converter(B3). I would like to avoid importing any modules.

答:
Pick the first string-input as the row counter, lowercase it and translate it from lecter to number though the dictonary I have created below; pick the second string-input as the column counter, then use these counter to access the board.

 This should do the trick without importing extenal modules:

```<code>self._board = [["A", "B", "C"],
               ["D", "E", "F"],
               ["G", "H", "I"]]

lecter_to_number = {chr(i + 96): i for i in range(1, 27)}

def pick_element(input):

    row = lecter_to_number[input[0].lower()]
    col = int(input[1])

    return self._board[row - 1][col - 1]

pick_element('B3')
</code>```

Body:
I'm trying to build a board game where my board is a 2D array of lists.

self._board = [["A", "B", "C"],
               ["D", "E", "F"],
               ["G", "H", "I"]]

How can I write a function that can be used to access each piece by using letter-number coordinates.
So for example I can use the function to get "A" by using converter(A1) or "F" by using converter(B3). I would like to avoid importing any modules.

Body:
Pick the first string-input as the row counter, lowercase it and translate it from lecter to number though the dictonary I have created below; pick the second string-input as the column counter, then use these counter to access the board.

 This should do the trick without importing extenal modules:

self._board = [["A", "B", "C"],
               ["D", "E", "F"],
               ["G", "H", "I"]]

lecter_to_number = {chr(i + 96): i for i in range(1, 27)}

def pick_element(input):

    row = lecter_to_number[input[0].lower()]
    col = int(input[1])

    return self._board[row - 1][col - 1]

pick_element('B3')


问:
Javascript - flatMap method over array - (flatMap is not a function)
According to the Mozilla Developer Website:

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map followed by a flat of depth 1, but flatMap is often quite useful, as merging both into one method is slightly more efficient.

Example:

```<code>let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];

const flatMap = arr.flatMap(x => x);
console.log(flatMap);
</code>```

TypeError: arr.flatMap() is not a function

Why is this returning this error?

EDIT

I am running this through Atom text editor and have used HomeBrew to update it to the latest version using brew upgrade node and it is still giving me the same error.

I have also tried npm install n -g

答:
I was getting this when testing with jest, it's because flatmap is only part of node 11 and I was using node 10.

As a workaround, I added require('core-js/stable'); in my setupTests.ts.

I presume also there are some browsers that won't have this either. As such I will also put that require line in my application imports somewhere.

Body:
According to the Mozilla Developer Website:

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map followed by a flat of depth 1, but flatMap is often quite useful, as merging both into one method is slightly more efficient.

Example:

let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];

const flatMap = arr.flatMap(x => x);
console.log(flatMap);

TypeError: arr.flatMap() is not a function

Why is this returning this error?

EDIT

I am running this through Atom text editor and have used HomeBrew to update it to the latest version using brew upgrade node and it is still giving me the same error.

I have also tried npm install n -g


问:
Realisation of compose method
Help me please with understanding realisation own "compose" method for two function.
I have singnature
def compose[A, B, C](g: B => C, f: A => B): A => C = ???
And i want to write method "h" which is composition of two function (f and g) or g(f).

```<code>val res: Int = compose[Int, Int, Int]((b: Int) => b + 1, (a: Int) => a + 1)(1)
</code>```

答:
You need to return a function that receives an x of type A and returns a function g which returns C and is applied to a function f applied to x

def compose[A, B, C](g: B => C, f: A => B): A => C = x => g(f(x))
```

<p>Then you can define f and g </p>

<pre class="lang-scala prettyprint-override"><code>val f = (x:Int) => x * 2
val g = (x:Int) => x * 4
</code>```

And h will be the composition of those two functions

val h = compose(f, g)
val result = h(42)
```

Title: Realisation of compose method

Body:
Help me please with understanding realisation own "compose" method for two function.
I have singnature
def compose[A, B, C](g: B => C, f: A => B): A => C = ???
And i want to write method "h" which is composition of two function (f and g) or g(f).

val res: Int = compose[Int, Int, Int]((b: Int) => b + 1, (a: Int) => a + 1)(1)

Body:
You need to return a function that receives an x of type A and returns a function g which returns C and is applied to a function f applied to x

def compose[A, B, C](g: B => C, f: A => B): A => C = x => g(f(x))

Then you can define f and g

val f = (x:Int) => x * 2
val g = (x:Int) => x * 4

And h will be the composition of those two functions

val h = compose(f, g)
val result = h(42)


问:
How can I compare two time strings in the format HH:MM:SS?
I have two time strings in HH:MM:SS format. For example, str1 contains 10:20:45,  str2 contains 5:10:10.

How can I compare the above values?

答:
Try this code.</p>

```<code>var startTime = "05:01:20";
var endTime = "09:00:00";
var regExp = /(\d{1,2})\:(\d{1,2})\:(\d{1,2})/;
if(parseInt(endTime .replace(regExp, "$1$2$3")) > parseInt(startTime .replace(regExp, "$1$2$3"))){
alert("End time is greater");
}
</code>```

Body:
Try this code.

var startTime = "05:01:20";
var endTime = "09:00:00";
var regExp = /(\d{1,2})\:(\d{1,2})\:(\d{1,2})/;
if(parseInt(endTime .replace(regExp, "$1$2$3")) > parseInt(startTime .replace(regExp, "$1$2$3"))){
alert("End time is greater");
}


问:
how to use LevelDB in c++ on Mac, why I got "ld: symbol(s) not found for architecture x86_64"
I am new to C++, and now I want to learn LevelDB, but get some issues.

brew install leveldb --cc=gcc-4.8

my code:

```<code>#include <iostream>
#include "leveldb/db.h"
int main() {
    leveldb::Options options;
    leveldb::DB *db;
    options.create_if_missing = true;
    leveldb::Status status = leveldb::DB::Open(options, "./.db", &db);
    assert(status.ok())
    std::cout << "Hello, World!" << std::endl;
    return 0;
}
</code>```

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.6)
project(ldb)
set(CMAKE_CXX_STANDARD 14)

find_library(LevelDB_LIBRARY leveldb)

set(SOURCE_FILES main.cpp)
add_executable(ldb ${SOURCE_FILES})

target_link_libraries(ldb /usr/local/lib/libleveldb.a)

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
TARGET_LINK_LIBRARIES(ldb pthread)

set(CMAKE_VERBOSE_MAKEFILE TRUE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -v -stdlib=libstdc++")
</code>```

then, here is the errors:

```<code>    /Applications/CLion.app/Contents/bin/cmake/bin/cmake -E cmake_link_script CMakeFiles/ldb.dir/link.txt --verbose=1
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++    -v -stdlib=libstdc++ -g -Wl,-search_paths_first -Wl,-headerpad_max_install_names  CMakeFiles/ldb.dir/main.cpp.o  -o ldb /usr/local/lib/libleveldb.a -lpthread
    Apple LLVM version 8.1.0 (clang-802.0.41)
    Target: x86_64-apple-darwin16.5.0
    Thread model: posix
    InstalledDir:/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
    clang: warning: libstdc++ is deprecated; move to libc++ [-Wdeprecated]
    "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -lto_library /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/libLTO.dylib -dynamic -arch x86_64 -macosx_version_min 10.12.0 -o ldb -search_paths_first -headerpad_max_install_names CMakeFiles/ldb.dir/main.cpp.o /usr/local/lib/libleveldb.a -lpthread -lstdc++ -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.1.0/lib/darwin/libclang_rt.osx.a
    Undefined symbols for architecture x86_64:
      "snappy::RawCompress(char const*, unsigned long, char*, unsigned long*)", referenced from:
          leveldb::TableBuilder::WriteBlock(leveldb::BlockBuilder*, leveldb::BlockHandle*) in libleveldb.a(table_builder.o)
      "snappy::RawUncompress(char const*, unsigned long, char*)", referenced from:
          leveldb::ReadBlock(leveldb::RandomAccessFile*, leveldb::ReadOptions const&, leveldb::BlockHandle const&, leveldb::BlockContents*) in libleveldb.a(format.o)
      "snappy::MaxCompressedLength(unsigned long)", referenced from:
          leveldb::TableBuilder::WriteBlock(leveldb::BlockBuilder*, leveldb::BlockHandle*) in libleveldb.a(table_builder.o)
      "snappy::GetUncompressedLength(char const*, unsigned long, unsigned long*)", referenced from:
          leveldb::ReadBlock(leveldb::RandomAccessFile*, leveldb::ReadOptions const&, leveldb::BlockHandle const&, leveldb::BlockContents*) in libleveldb.a(format.o)
    ld: symbol(s) not found for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    make[2]: *** [ldb] Error 1
    make[1]: *** [CMakeFiles/ldb.dir/all] Error 2
    make: *** [all] Error 2
</code>```

it works on CentOS server，but not work on my Mac，what's the problem？

if I compile it by hand.gcc-4.8 main.cpp  -L. -I./Users/apple/CLionProjects/leveldb/include -lpthread -lleveldb -lstdc++ got a warning: section "__textcoal_nt" is deprecated, but if i replace gcc-4.8 with gcc-5, i got an error :

```<code>    Undefined symbols for architecture x86_64:
    "leveldb::DB::Open(leveldb::Options const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, leveldb::DB**)", referenced from:
          _main in ccWAzDAN.o
    ld: symbol(s) not found for architecture x86_64
    collect2: error: ld returned 1 exit status
</code>```

Why is it different?

答:
Usually find_package should be used. But levelDB is not detectable with find_package at the moment of this answer. Here is the info https://github.com/google/leveldb/issues/641

Consider using externalproject_add for he LevelDB: https://github.com/ohhmm/openmind/blob/f1459119e8d36d6cc6edc776b2f242edaf51fecf/CMakeLists.txt#L292

Alternatively just add leveldb to TARGET_LINK_LIBRARIES together with pthread. This works for posix but not for Windows though.

Body:
I am new to C++, and now I want to learn LevelDB, but get some issues.

brew install leveldb --cc=gcc-4.8

my code:

#include <iostream>
#include "leveldb/db.h"
int main() {
    leveldb::Options options;
    leveldb::DB *db;
    options.create_if_missing = true;
    leveldb::Status status = leveldb::DB::Open(options, "./.db", &db);
    assert(status.ok())
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.6)
project(ldb)
set(CMAKE_CXX_STANDARD 14)

find_library(LevelDB_LIBRARY leveldb)

set(SOURCE_FILES main.cpp)
add_executable(ldb ${SOURCE_FILES})

target_link_libraries(ldb /usr/local/lib/libleveldb.a)

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
TARGET_LINK_LIBRARIES(ldb pthread)

set(CMAKE_VERBOSE_MAKEFILE TRUE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -v -stdlib=libstdc++")

then, here is the errors:

    /Applications/CLion.app/Contents/bin/cmake/bin/cmake -E cmake_link_script CMakeFiles/ldb.dir/link.txt --verbose=1
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++    -v -stdlib=libstdc++ -g -Wl,-search_paths_first -Wl,-headerpad_max_install_names  CMakeFiles/ldb.dir/main.cpp.o  -o ldb /usr/local/lib/libleveldb.a -lpthread
    Apple LLVM version 8.1.0 (clang-802.0.41)
    Target: x86_64-apple-darwin16.5.0
    Thread model: posix
    InstalledDir:/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
    clang: warning: libstdc++ is deprecated; move to libc++ [-Wdeprecated]
    "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -lto_library /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/libLTO.dylib -dynamic -arch x86_64 -macosx_version_min 10.12.0 -o ldb -search_paths_first -headerpad_max_install_names CMakeFiles/ldb.dir/main.cpp.o /usr/local/lib/libleveldb.a -lpthread -lstdc++ -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.1.0/lib/darwin/libclang_rt.osx.a
    Undefined symbols for architecture x86_64:
      "snappy::RawCompress(char const*, unsigned long, char*, unsigned long*)", referenced from:
          leveldb::TableBuilder::WriteBlock(leveldb::BlockBuilder*, leveldb::BlockHandle*) in libleveldb.a(table_builder.o)
      "snappy::RawUncompress(char const*, unsigned long, char*)", referenced from:
          leveldb::ReadBlock(leveldb::RandomAccessFile*, leveldb::ReadOptions const&, leveldb::BlockHandle const&, leveldb::BlockContents*) in libleveldb.a(format.o)
      "snappy::MaxCompressedLength(unsigned long)", referenced from:
          leveldb::TableBuilder::WriteBlock(leveldb::BlockBuilder*, leveldb::BlockHandle*) in libleveldb.a(table_builder.o)
      "snappy::GetUncompressedLength(char const*, unsigned long, unsigned long*)", referenced from:
          leveldb::ReadBlock(leveldb::RandomAccessFile*, leveldb::ReadOptions const&, leveldb::BlockHandle const&, leveldb::BlockContents*) in libleveldb.a(format.o)
    ld: symbol(s) not found for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    make[2]: *** [ldb] Error 1
    make[1]: *** [CMakeFiles/ldb.dir/all] Error 2
    make: *** [all] Error 2

it works on CentOS server，but not work on my Mac，what's the problem？

if I compile it by hand.gcc-4.8 main.cpp  -L. -I./Users/apple/CLionProjects/leveldb/include -lpthread -lleveldb -lstdc++ got a warning: section "__textcoal_nt" is deprecated, but if i replace gcc-4.8 with gcc-5, i got an error :

    Undefined symbols for architecture x86_64:
    "leveldb::DB::Open(leveldb::Options const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, leveldb::DB**)", referenced from:
          _main in ccWAzDAN.o
    ld: symbol(s) not found for architecture x86_64
    collect2: error: ld returned 1 exit status

Why is it different?


问:
Rials Routing Error:Because of Controller name different from model name?
everyone! I am new to rails and working on Codecademy tutorials. But I wanted to see if I can run the same app on my mac using VS Code and got into some roadblocks. The application is basically to create a form that takes in messages and displays it (in the index view). I wanted to explore changing the names of controller and model to what I want and guess I messed up the internal routing. Following is the controller (messagec)

```<code>class MessagecController < ApplicationController

    def index
        @messages1 = MessagesMo1.all
    end

    def new
        @messages2 = MessagesMo1.new
    end

    def create
        @messages2 = MessagesMo1.new(message_params)
        if @messages2.save #tells if the object is saved successfully in db or not
           flash[:success] = "Great! Your post has been created!"
           redirect_to '/messages'
        else
          flash.now[:error] = "Fix your mistakes, please."
          render 'new'
        end
    end

    private
    def message_params
      params.require(:message).permit(:content)
    end
end
</code>```

THe following is the model (messagesmo1)

```<code>class CreateMessagesMo1s < ActiveRecord::Migration[6.0]
  def change
    create_table :messages_mo1s do |t|
      t.text :content
      t.timestamps
    end
  end
end
</code>```

The following is the routes.rb file

```<code>get '/messages' => 'messagec#index'
get '/messages/new' => 'messagec#new'
post 'messages' => 'messagec#create'
post 'messages_mo1s' => 'message_mo1s#create'
</code>```

The following is the code in create.html.erb file

```<code>    <%= form_for(@messages2) do |f| %>
    <div class = "field">
        <%= f.label :message %><br>
        <%= f.text_area :content %>
    </div>
    <div class = "actions">
    <%= f.submit "Create" %>
    </div>
    <% end %>
</code>```

I am able to see the message list and able to go to create new message page. But when I submit the form, I am getting the following Routing error:

uninitialized constant MessageMo1sController Did you mean? MessagecController MessagesMController

My first questions is:
1) What am I missing in the routes.rb file?
2) Is there any rule between naming the model similar to that of the controller?

答:
It finally worked. Following are the 2 changes:
1) Instead of <%= form_for(@messages2) do |f| %>, I used a URL parameter
  <%= form_for(@messages2, url:'/messages/') do |f| %>
2)As @cdadityang mentioned, I updated the params to params.require(:messages_mo1).permit(:content)

without the URL being given explicitly, I think the rails is assuming '/message_mo1' are the path. So the URL is basically taking it to 'messagec#create'

Body:
everyone! I am new to rails and working on Codecademy tutorials. But I wanted to see if I can run the same app on my mac using VS Code and got into some roadblocks. The application is basically to create a form that takes in messages and displays it (in the index view). I wanted to explore changing the names of controller and model to what I want and guess I messed up the internal routing. Following is the controller (messagec)

class MessagecController < ApplicationController

    def index
        @messages1 = MessagesMo1.all
    end

    def new
        @messages2 = MessagesMo1.new
    end

    def create
        @messages2 = MessagesMo1.new(message_params)
        if @messages2.save #tells if the object is saved successfully in db or not
           flash[:success] = "Great! Your post has been created!"
           redirect_to '/messages'
        else
          flash.now[:error] = "Fix your mistakes, please."
          render 'new'
        end
    end

    private
    def message_params
      params.require(:message).permit(:content)
    end
end

THe following is the model (messagesmo1)

class CreateMessagesMo1s < ActiveRecord::Migration[6.0]
  def change
    create_table :messages_mo1s do |t|
      t.text :content
      t.timestamps
    end
  end
end

The following is the routes.rb file

get '/messages' => 'messagec#index'
get '/messages/new' => 'messagec#new'
post 'messages' => 'messagec#create'
post 'messages_mo1s' => 'message_mo1s#create'

The following is the code in create.html.erb file

    <%= form_for(@messages2) do |f| %>

        <%= f.label :message %>

        <%= f.text_area :content %>

    <%= f.submit "Create" %>

    <% end %>

I am able to see the message list and able to go to create new message page. But when I submit the form, I am getting the following Routing error:

uninitialized constant MessageMo1sController Did you mean? MessagecController MessagesMController

My first questions is:
1) What am I missing in the routes.rb file?
2) Is there any rule between naming the model similar to that of the controller?


问:
Gotham Medium / black font definition in css
I was trying to define gotham font in css however it doesnt seem to work, do i need to download it and include a link to it or do something else for it to work?

my code:

```<code>.display-4{
    font-family: Gotham-Black;

}
</code>```

答:
Yes, you need to download it and add the path to the font's location.
More info can be found here: https://www.w3schools.com/cssref/css3_pr_font-face_rule.asp</p>

Body:
I was trying to define gotham font in css however it doesnt seem to work, do i need to download it and include a link to it or do something else for it to work?

my code:

.display-4{
    font-family: Gotham-Black;

}


问:
How to programmatically open ngbootstrap popover for a d3 element?
I want to open a popover onmouseover for a D3 element.

Essentially this means my component.html file is almost empty, containing only the popover template:

<ng-template #popContent let-greeting="greeting">{{greeting}}, {{name}}!</ng-template>

I can't use the usual

[ngbPopover]="popContent" popoverTitle="Greeting" #p="ngbPopover" triggers="manual"

attributes, since target D3 element doesn't exist yet

What I need is to be able to somehow call the popover's open function passing the popover contents and position.
something like this in my component:

```<code>public showPopover(node, text){ // node is the DOM element for which to show popover
 ... what should go here? ...
}
</code>```

答:
Hi it was useful thank you, but I have to add a thing you need to change the property ".elementRef" to public in the definition file popover.d.ts</p>

```<code>export declare class NgbPopover implements OnInit, OnDestroy, OnChanges {
public _elementRef;
</code>```

Body:
I want to open a popover onmouseover for a D3 element.

Essentially this means my component.html file is almost empty, containing only the popover template:

<ng-template #popContent let-greeting="greeting">{{greeting}}, {{name}}!</ng-template>

I can't use the usual

[ngbPopover]="popContent" popoverTitle="Greeting" #p="ngbPopover" triggers="manual"

attributes, since target D3 element doesn't exist yet

What I need is to be able to somehow call the popover's open function passing the popover contents and position.
something like this in my component:

public showPopover(node, text){ // node is the DOM element for which to show popover
 ... what should go here? ...
}

Body:
Hi it was useful thank you, but I have to add a thing you need to change the property ".elementRef" to public in the definition file popover.d.ts

export declare class NgbPopover implements OnInit, OnDestroy, OnChanges {
public _elementRef;


问:
Rotating label using rot = on grid.arrange not working
I am trying to rotate one of the labels on my grid.arrange panel figure to look like the axis of all three plots, but this is not working using the methods I am finding online.

When I use a textGrob for control of the font size (which I need to be 24), using this code, I get this figure. I am inserting the rot= 90 argument but it isn't doing anything to the figure.

```<code>grid.arrange(d.a.plot1, d.b.plot1, d.c.plot1, ncol = 1, left = textGrob("Probability of remaining availabile", gp=gpar(fontsize=24, rot = 90)), bottom = textGrob("Depth(cm)", gp=gpar(fontsize = 24)))
</code>```

When I use the standard grid.arrange code to add a rotated label using the code below, the position is fine, but then I can't adjust the font.

```<code>grid.arrange(d.a.plot1, d.b.plot1, d.c.plot1, ncol = 1, left = "Probability of remaining availabile", bottom = textGrob("Depth(cm)", gp=gpar(fontsize = 24)))
</code>```

答:
You just need to take rot = 90 out of gpar and pass it directly to textGrob:

# Simulate the plot grobs:
f <- function() cowplot::as_grob(~plot(rnorm(100), rnorm(100)))

grid.arrange(f(), f(), f(), ncol = 1,
            left = textGrob("Probability of remaining availabile", rot = 90,
                            gp = gpar(fontsize=24)),
            bottom = textGrob("Depth(cm)", gp=gpar(fontsize = 24)))
```

Body:
I am trying to rotate one of the labels on my grid.arrange panel figure to look like the axis of all three plots, but this is not working using the methods I am finding online.

When I use a textGrob for control of the font size (which I need to be 24), using this code, I get this figure. I am inserting the rot= 90 argument but it isn't doing anything to the figure.

grid.arrange(d.a.plot1, d.b.plot1, d.c.plot1, ncol = 1, left = textGrob("Probability of remaining availabile", gp=gpar(fontsize=24, rot = 90)), bottom = textGrob("Depth(cm)", gp=gpar(fontsize = 24)))

When I use the standard grid.arrange code to add a rotated label using the code below, the position is fine, but then I can't adjust the font.

grid.arrange(d.a.plot1, d.b.plot1, d.c.plot1, ncol = 1, left = "Probability of remaining availabile", bottom = textGrob("Depth(cm)", gp=gpar(fontsize = 24)))


问:
!== ' ' not allowing the intake of 0 in Javascript calculator
I've knocked up a simple calculator in vanilla JS. However when the user enters a 0 the calculation does nothing. I'd expect it to take 0 for example x it by 10 and give the answer 10. As an example. I'm guessing this line is stopping 0. Any ideas?</p>

```<code>const isValid = field => (field && field !== '' && !isNaN(field));
</code>```

答:
```<code>const isValid = field => (field === 0 || (!!field && !isNaN(field)));
</code>```

Since 0 is falsey, you can handle it separately.
true || false will return true.

!!field takes care of undefined, '', null, 0, etc. Basically it handles all falsey values. So you don't need to check for '' separately. Since !'' is true, so !!'' is false.

Body:
I've knocked up a simple calculator in vanilla JS. However when the user enters a 0 the calculation does nothing. I'd expect it to take 0 for example x it by 10 and give the answer 10. As an example. I'm guessing this line is stopping 0. Any ideas?

const isValid = field => (field && field !== '' && !isNaN(field));

Body:
const isValid = field => (field === 0 || (!!field && !isNaN(field)));

Since 0 is falsey, you can handle it separately.
true || false will return true.

!!field takes care of undefined, '', null, 0, etc. Basically it handles all falsey values. So you don't need to check for '' separately. Since !'' is true, so !!'' is false.


问:
I don't understand where the get method of the requests object supported by the requests package for Python gets its code
I have just installed the requests package. It works, meaning that I can run the first two instructions from the documentation without error, namely import requests and requests.get.

I don't understand the underlying source. I see a directory in site-packages named requests. It contains the necessary __init__.py so the system should accept it as a valid object for an import. However, I would expect to see a get.py in the directory to correspond to the get in the script. But no such thing exists. In fact the whole directory is amazingly small. Where is everything?

答:
Take a look at requests.__init__.py but specifically line 123:

from .api import request, get, head, post, patch, put, delete, options
```

<p>Then if you go into <code>requests.api.py</code> you'll find <code>get()</code>, which is the source implementation for that method:</p>

<pre class="lang-py prettyprint-override"><code>def get(url, params=None, **kwargs):
    r"""Sends a GET request.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)
</code>```

I'm pretty sure by importing get() into __init__.py that makes it available/invokable via the requests module you initially imported.

Body:
Take a look at requests.__init__.py but specifically line 123:

from .api import request, get, head, post, patch, put, delete, options

Then if you go into requests.api.py you'll find get(), which is the source implementation for that method:

def get(url, params=None, **kwargs):
    r"""Sends a GET request.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)

I'm pretty sure by importing get() into __init__.py that makes it available/invokable via the requests module you initially imported.


问:
Android NDK with Linux: "ndk-build" command not found
I'm new to Linux (Ubuntu) and I had a problem building the libraries in my project.
I added the android ndk to the PATH like this:

```<code>  export PATH=$PATH:/android-ndk-r9b
</code>```

and to Eclipse

but when I try to use the

```<code>ndk-build
</code>```

command, I get this output:

```<code>ndk-build: command not found
</code>```

Any help?

答:
Your PATH should include the root directory of your NDK:</p>

```<code>export PATH=$PATH:/home/.../android-ndk-xxx
</code>```

Body:
I'm new to Linux (Ubuntu) and I had a problem building the libraries in my project.
I added the android ndk to the PATH like this:

  export PATH=$PATH:/android-ndk-r9b

and to Eclipse

but when I try to use the

ndk-build

command, I get this output:

ndk-build: command not found

Any help?

Body:
Your PATH should include the root directory of your NDK:

export PATH=$PATH:/home/.../android-ndk-xxx


问:
How to implement better error messages for flex/bison
I need to have proper error messages for syntax errors for a grammar I'm writing. I've figured out that I can define a rule (? not sure about the terminology) for newlines in the flex file that increments a line-number counter, and I can use that in yyerror(const char*). However, I also need to know the exact position where the error occurred to have better error messages. This is what I would want the error messages to look like:

```<code>Syntax error on line X:
SOME ERRONEOUS TEXT ON LINE X
_______________^
Expected other text.
</code>```

How could I get the column information as well as the text on the erroneous line?

Thank you in advance.

答:
Output Unexpected and Expected Tokens

Just with using

```<code>#define YYERROR_VERBOSE 1
</code>```

yyerror outputs already something like

```<code>syntax error, unexpected '+', expecting NUM or '('
</code>```

Print Line Number

To print the current line number you can make use of yylineno. You need to declare it with

```<code>extern int yylineno;
</code>```

in the .y file.

In the .l flex file you need to add:

```<code>%option yylineno
</code>```

Print Column

To get column information, you must track the columns in the lexer file. So after you have read a token, you can simply add the length of the token (e.g. by using strlen(yytext)). For error reporting, you are interested in the column where the token starts, so you need a second variable that is set and remembers the column position before reading the token.

You could use a simple macro for it:

```<code>#define HANDLE_COLUMN column = next_column; next_column += strlen(yytext)
</code>```

Print Current Input Line

To print the current input line, you must track it yourself. You can read lines from yyin yourself and use this data in the lexer by defining the macro YY_INPUT accordingly. There is this nice answer https://stackoverflow.com/a/43303098 which explains how it works.

The author also shows an example of how the current column can be determined using the macro YY_USER_ACTION.

Simple Example

A simple, self-contained example of a calculator that can handle addition and subtraction could look like this

With an input 5+3+2+1 it gives as output:

```<code>5+3+2+1
=11
</code>```

A erroneous input such as '5+2++1' results as output:

```<code>error: syntax error, unexpected '+', expecting NUM or '(' in line 3, column 5
5+2++1
____^
</code>```

calc.l

```<code>%{
    #include "y.tab.h"
    extern int yylval;
    static int next_column = 1;
    int column = 1;

    #define HANDLE_COLUMN column = next_column; next_column += strlen(yytext)

    char *lineptr = NULL;
    size_t n = 0;
    size_t consumed = 0;
    size_t available = 0;

    size_t min(size_t a, size_t b);
    #define YY_INPUT(buf,result,max_size) {\
        if(available <= 0) {\
            consumed = 0;\
            available = getline(&lineptr, &n, yyin);\
            if (available < 0) {\
                if (ferror(yyin)) { perror("read error:"); }\
                    available = 0;\
                }\
        }\
        result = min(available, max_size);\
        strncpy(buf, lineptr + consumed, result);\
        consumed += result;\
        available -= result;\
    }
%}

%option noyywrap noinput nounput yylineno

%%

[\t ]+   { HANDLE_COLUMN; }
[0-9]+   { HANDLE_COLUMN; yylval = atoi(yytext);  return NUM; }
\n       { HANDLE_COLUMN; next_column = 1; return '\n'; }
.        { HANDLE_COLUMN; return yytext[0]; }

%%

size_t min(size_t a, size_t b) {
    return b < a ? b : a;
}
</code>```

calc.y

```<code>%{
    #include <stdio.h>
    int yylex(void);
    void yyerror(const char *s);
    extern int yylineno;
    extern int column;
    extern char *lineptr;
    #define YYERROR_VERBOSE 1
%}

%token NUM
%left '-' '+'
%left '(' ')'

%%
LINE:                   { $$ = 0; }
       | LINE EXPR '\n' { printf("%s=%d\n", lineptr, $2); }
       | LINE '\n'
       ;

EXPR:    NUM            { $$ = $1; }
     |   EXPR '-' EXPR  { $$ = $1 - $3; }
     |   EXPR '+' EXPR  { $$ = $1 + $3; }
     |   '(' EXPR ')'   { $$ = $2; }
     ;

%%

void yyerror(const char *str)
{
    fprintf(stderr,"error: %s in line %d, column %d\n", str, yylineno, column);
    fprintf(stderr,"%s", lineptr);
    for(int i = 0; i < column - 1; i++)
        fprintf(stderr,"_");
    fprintf(stderr,"^\n");
}

int main()
{
   yyparse();
   free(lineptr);
}
</code>```

Build Command

Depending on your system, a build command would look similar to the following:

```<code>flex calc.l
yacc -d calc.y
cc -Wextra -Wall lex.yy.c y.tab.c
</code>```

Body:
I need to have proper error messages for syntax errors for a grammar I'm writing. I've figured out that I can define a rule (? not sure about the terminology) for newlines in the flex file that increments a line-number counter, and I can use that in yyerror(const char*). However, I also need to know the exact position where the error occurred to have better error messages. This is what I would want the error messages to look like:

Syntax error on line X:
SOME ERRONEOUS TEXT ON LINE X
_______________^
Expected other text.

How could I get the column information as well as the text on the erroneous line?

Thank you in advance.

Body:
Output Unexpected and Expected Tokens

Just with using

#define YYERROR_VERBOSE 1

yyerror outputs already something like

syntax error, unexpected '+', expecting NUM or '('

Print Line Number

To print the current line number you can make use of yylineno. You need to declare it with

extern int yylineno;

in the .y file.

In the .l flex file you need to add:

%option yylineno

Print Column

To get column information, you must track the columns in the lexer file. So after you have read a token, you can simply add the length of the token (e.g. by using strlen(yytext)). For error reporting, you are interested in the column where the token starts, so you need a second variable that is set and remembers the column position before reading the token.

You could use a simple macro for it:

#define HANDLE_COLUMN column = next_column; next_column += strlen(yytext)

Print Current Input Line

To print the current input line, you must track it yourself. You can read lines from yyin yourself and use this data in the lexer by defining the macro YY_INPUT accordingly. There is this nice answer https://stackoverflow.com/a/43303098 which explains how it works.

The author also shows an example of how the current column can be determined using the macro YY_USER_ACTION.

Simple Example

A simple, self-contained example of a calculator that can handle addition and subtraction could look like this

With an input 5+3+2+1 it gives as output:

5+3+2+1
=11

A erroneous input such as '5+2++1' results as output:

error: syntax error, unexpected '+', expecting NUM or '(' in line 3, column 5
5+2++1
____^

calc.l

%{
    #include "y.tab.h"
    extern int yylval;
    static int next_column = 1;
    int column = 1;

    #define HANDLE_COLUMN column = next_column; next_column += strlen(yytext)

    char *lineptr = NULL;
    size_t n = 0;
    size_t consumed = 0;
    size_t available = 0;

    size_t min(size_t a, size_t b);
    #define YY_INPUT(buf,result,max_size) {\
        if(available <= 0) {\
            consumed = 0;\
            available = getline(&lineptr, &n, yyin);\
            if (available < 0) {\
                if (ferror(yyin)) { perror("read error:"); }\
                    available = 0;\
                }\
        }\
        result = min(available, max_size);\
        strncpy(buf, lineptr + consumed, result);\
        consumed += result;\
        available -= result;\
    }
%}

%option noyywrap noinput nounput yylineno

%%

[\t ]+   { HANDLE_COLUMN; }
[0-9]+   { HANDLE_COLUMN; yylval = atoi(yytext);  return NUM; }
\n       { HANDLE_COLUMN; next_column = 1; return '\n'; }
.        { HANDLE_COLUMN; return yytext[0]; }

%%

size_t min(size_t a, size_t b) {
    return b < a ? b : a;
}

calc.y

%{
    #include <stdio.h>
    int yylex(void);
    void yyerror(const char *s);
    extern int yylineno;
    extern int column;
    extern char *lineptr;
    #define YYERROR_VERBOSE 1
%}

%token NUM
%left '-' '+'
%left '(' ')'

%%
LINE:                   { $$ = 0; }
       | LINE EXPR '\n' { printf("%s=%d\n", lineptr, $2); }
       | LINE '\n'
       ;

EXPR:    NUM            { $$ = $1; }
     |   EXPR '-' EXPR  { $$ = $1 - $3; }
     |   EXPR '+' EXPR  { $$ = $1 + $3; }
     |   '(' EXPR ')'   { $$ = $2; }
     ;

%%

void yyerror(const char *str)
{
    fprintf(stderr,"error: %s in line %d, column %d\n", str, yylineno, column);
    fprintf(stderr,"%s", lineptr);
    for(int i = 0; i < column - 1; i++)
        fprintf(stderr,"_");
    fprintf(stderr,"^\n");
}

int main()
{
   yyparse();
   free(lineptr);
}

Build Command

Depending on your system, a build command would look similar to the following:

flex calc.l
yacc -d calc.y
cc -Wextra -Wall lex.yy.c y.tab.c


问:
Trying to make a timer which resets at the main Menu
I have a timer for a game in Unity and I have it carrying across to each new scene and working. The issue is I also want the timer to reset when the MainMenu scene has loaded and I can not for the life of me get this to work. Help would be appreciated, code's below -</p>

```<code>using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

using UnityEngine.SceneManagement;

public class Timer : MonoBehaviour

{

public Text TimerText;

public float StartTime = 0f;

     // Start is called before the first frame update
     void Start()
     {
         string Scene = SceneManager.GetActiveScene().name;
         if (Scene == "MainMenu")
         {
             Destroy(this.gameObject);
         }
         else
         {
             DontDestroyOnLoad(this.gameObject);
         }
     }
     void Update()
     {
         float t = Time.time - StartTime;
         string minutes = ((int)t / 60).ToString();
         string seconds = (t % 60).ToString("f2");
         TimerText.text = minutes + ":" + seconds;
     }

}
</code>```

答:
```<code>1    SceneManager.sceneLoaded += OnSceneLoaded;
2    public void OnSceneLoaded(Scene scene, LoadSceneMode mode)
3    {
4    }
</code>```

Then check the current scene, and reset the timer if the new scene is the menu

Body:
I have a timer for a game in Unity and I have it carrying across to each new scene and working. The issue is I also want the timer to reset when the MainMenu scene has loaded and I can not for the life of me get this to work. Help would be appreciated, code's below -

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

using UnityEngine.SceneManagement;

public class Timer : MonoBehaviour

{

public Text TimerText;

public float StartTime = 0f;

     // Start is called before the first frame update
     void Start()
     {
         string Scene = SceneManager.GetActiveScene().name;
         if (Scene == "MainMenu")
         {
             Destroy(this.gameObject);
         }
         else
         {
             DontDestroyOnLoad(this.gameObject);
         }
     }
     void Update()
     {
         float t = Time.time - StartTime;
         string minutes = ((int)t / 60).ToString();
         string seconds = (t % 60).ToString("f2");
         TimerText.text = minutes + ":" + seconds;
     }

}

Body:
1    SceneManager.sceneLoaded += OnSceneLoaded;
2    public void OnSceneLoaded(Scene scene, LoadSceneMode mode)
3    {
4    }

Then check the current scene, and reset the timer if the new scene is the menu


问:
Python/Regex - match all sentences matching another regex expression
I use the following regex to match any square brackets containing digits inside them and then ten words preceding and following those brackets
(?P<capture>(?:\w+\W+){,10}\[\d+\]\W+(?:\w+\W+){,10})

This would then return
appellant had pleaded guilty: see R v McReady and Hurd [1978] 1 WLR 1376. In those circumstances, the legal advice would

Now I decided that looking for whole sentences makes more sense, so I want it to find all sentences, however long, including \[\d+\]\W+ in them.

Any help as how I would do that? I tried different methods but must have made mistakes along the way

答:
My understanding of what you are looking for is, to find all the sentences that contain [number] in it. Try the below pattern with global and multiline match options on your text:

```<code>\s+[^.!?]*\[\d+\].*?[.!?]
</code>```

For the example text below you should get two matches which are in bold color:

Appellant had pleaded guilty: see R v McReady and Hurd [1978] 1 WLR 1376. In those circumstances, the legal advice would. Is there another case [123]?

Body:
My understanding of what you are looking for is, to find all the sentences that contain [number] in it. Try the below pattern with global and multiline match options on your text:

\s+[^.!?]*\[\d+\].*?[.!?]

For the example text below you should get two matches which are in bold color:

Appellant had pleaded guilty: see R v McReady and Hurd [1978] 1 WLR 1376. In those circumstances, the legal advice would. Is there another case [123]?


问:
AWS S3 Glacier upload-archive taking a long time to finish execution - ways to check status or speed upload?
I am trying to upload some .tar.gz files to AWS S3 Glacier using the upload-archive command (docs).

I ran the upload-archive command over one day ago on a 29 GB .tar.gz file like so:

aws glacier upload-archive --vault-name my-vault --account-id - --archive-description "my description" --body my-file.tar.gz
```

<p>I checked today, and found it still has yet to finish execution.</p>

<hr>

<p>My question is two parts:</p>

<ul>
<li>Is there some way to see that the command is still running?

<ul>
<li>A progress bar would be awesome</li>
</ul></li>
<li>Are there any ways (or alternate methods) to speed up the <code>upload-archive</code>?</li>
</ul>

<p>FYI, I am using <code>aws-cli==2.0.17</code>.  Thank you in advance for any help!</p>

<hr>

<p><strong>**Edit**</strong></p>

<p>After running for two days, the <code>upload-archive</code> command errored out with the below message:</p>

```An error occurred (InvalidParameterValueException) when calling the UploadArchive operation: Invalid Content-Length: 30957118
```

Which lead to aws-cli #3413.  The posts there are in agreement with all the answers below.

答:
In case you do not require to use Amazon S3 Glacier special features such as vault locks and vault policies, you may consider using Amazon S3 with storage class of glacier.

The class stores all your objects in the Amazon S3 Glacier backed, but provides easy and familiar interface of S3. Some benefits as compared to using Amazon S3 Glacier directly:

file names are preserved in S3. In Glacier your filenames get scrambled,

easy multi-part upload using aws s3 cli,

easy retrieval to the archived objects

s3 object lifecycles which can automatically transition your objects to S3 glacier storage, or from glacier to deep archive.

Body:
I am trying to upload some .tar.gz files to AWS S3 Glacier using the upload-archive command (docs).

I ran the upload-archive command over one day ago on a 29 GB .tar.gz file like so:

aws glacier upload-archive --vault-name my-vault --account-id - --archive-description "my description" --body my-file.tar.gz

I checked today, and found it still has yet to finish execution.

My question is two parts:

Is there some way to see that the command is still running?

A progress bar would be awesome

Are there any ways (or alternate methods) to speed up the upload-archive?

FYI, I am using aws-cli==2.0.17.  Thank you in advance for any help!

**Edit**

After running for two days, the upload-archive command errored out with the below message:

An error occurred (InvalidParameterValueException) when calling the UploadArchive operation: Invalid Content-Length: 30957118

Which lead to aws-cli #3413.  The posts there are in agreement with all the answers below.


问:
How to restrict edit script to run in specific column _google sheets
I am running a script in sheets to allow multiple selection. The script works but when i go to edit a cell somewhere else on the sheet the information disappears. I need to run this script only for column 5, so if something is documented elsewhere, it wont keep disappearing. </p>

```<code>function onEdit(e) {
    var oldValue;
    var newValue;
    var ss=SpreadsheetApp.getActiveSpreadsheet();
    var activeCell = ss.getActiveCell();
    if(activeCell.getColumn() == 5 && ss.getActiveSheet().getName()=="TRACKER- Relaunch")
        newValue=e.value;
    oldValue=e.oldValue;
    if(!e.value) {
        activeCell.setValue("");
    }
    else {
        if (!e.oldValue) {
            activeCell.setValue(newValue);
        }
        else {
            if(oldValue.indexOf(newValue) <0) {
                activeCell.setValue(oldValue+','+newValue);
            }
            else {
                activeCell.setValue(oldValue);
            }
        }
    }
}
</code>```

答:
Try this:</p>

```<code>function onEdit(e) {
  var sh=e.range.getSheet();
  if(e.range.columnStart==5 && sh.getName()=="TRACKER- Relaunch") {
    if(!e.value) {//this doesn't make much sense
      e.range.setValue("");
    }else if(!e.oldValue) {//nor does this
      e.range.setValue(e.value);
    }else if(e.oldValue.indexOf(e.value)==-1) {
      e.range.setValue(e.oldValue + ',' + e.value);
    }else{
      e.range.setValue(e.oldValue);
    }
  }
}
</code>```

Body:
I am running a script in sheets to allow multiple selection. The script works but when i go to edit a cell somewhere else on the sheet the information disappears. I need to run this script only for column 5, so if something is documented elsewhere, it wont keep disappearing.

function onEdit(e) {
    var oldValue;
    var newValue;
    var ss=SpreadsheetApp.getActiveSpreadsheet();
    var activeCell = ss.getActiveCell();
    if(activeCell.getColumn() == 5 && ss.getActiveSheet().getName()=="TRACKER- Relaunch")
        newValue=e.value;
    oldValue=e.oldValue;
    if(!e.value) {
        activeCell.setValue("");
    }
    else {
        if (!e.oldValue) {
            activeCell.setValue(newValue);
        }
        else {
            if(oldValue.indexOf(newValue) <0) {
                activeCell.setValue(oldValue+','+newValue);
            }
            else {
                activeCell.setValue(oldValue);
            }
        }
    }
}

Body:
Try this:

function onEdit(e) {
  var sh=e.range.getSheet();
  if(e.range.columnStart==5 && sh.getName()=="TRACKER- Relaunch") {
    if(!e.value) {//this doesn't make much sense
      e.range.setValue("");
    }else if(!e.oldValue) {//nor does this
      e.range.setValue(e.value);
    }else if(e.oldValue.indexOf(e.value)==-1) {
      e.range.setValue(e.oldValue + ',' + e.value);
    }else{
      e.range.setValue(e.oldValue);
    }
  }
}


问:
Trouble Printing iFrames
[Simplified version of this question:]

Why do iFrames sometimes refuse to print? For example, hit print preview on these two pages:

http://fiddle.jshell.net/gJDv4/1/show/

http://fiddle.jshell.net/gJDv4/2/show/

On print-preview, the iFrames are visible in the first example, but hidden in the second. The ONLY code difference between first and second iFrames is a CSS property (margin: 20px;) has been added to the iFrames in the second example.

[Long (original) version:]

I am building a preview/print page that assembles a bunch of independent HTML files referencing their own style-sheets and javascript files.

http://jsfiddle.net/GJKkm/16/

The idea is that all files are displayed in iFrames for preview, and then when printed, each iFrame (which likely will span multiple pages) prints out as if it were it's own document.

However, when I print (or print-preview) the iFrames either show no content, or they only print the first page, truncating the remaining pages of the iFrame.

http://fiddle.jshell.net/GJKkm/16/show/ (use this link to print-preview, not the one above)

The iFrames printed (and print-previewed) just fine before I made them multiple pages:

http://fiddle.jshell.net/GJKkm/7/show/

What is the reason for this behavior?

答:
I came up with a way to solve it.

The aim is to get the contents of all the iframes into the parent window by manipulating the DOM using javascript.

With this solution you even avoid the problem of the iframe being cut off if it exceeds one page.

Here is the code:

```<code><script>

 pages =[] // initiate an empty list here

function printPage() {

var frames = document.getElementsByTagName('iframe');
// get all the iframes and loop over them
// then push their innerHTML into the list
for (var i = 0; i < frames.length; i++){
   pages.push(frames[i].contentWindow.document.body.innerHTML);
;
}
if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the concatenated iframes innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the iframes
window.print();
}
else {
// do nothing
}

}
</script>
</code>```

With this you get only one print dialogue box to print all the iframes.

Remember that in your parent page HTML you will have the code below to call the printPage function.

```<code><input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />
</code>```

Title: Trouble Printing iFrames

Body:
I came up with a way to solve it.

The aim is to get the contents of all the iframes into the parent window by manipulating the DOM using javascript.

With this solution you even avoid the problem of the iframe being cut off if it exceeds one page.

Here is the code:

<script>

 pages =[] // initiate an empty list here

function printPage() {

var frames = document.getElementsByTagName('iframe');
// get all the iframes and loop over them
// then push their innerHTML into the list
for (var i = 0; i < frames.length; i++){
   pages.push(frames[i].contentWindow.document.body.innerHTML);
;
}
if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the concatenated iframes innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the iframes
window.print();
}
else {
// do nothing
}

}
</script>

With this you get only one print dialogue box to print all the iframes.

Remember that in your parent page HTML you will have the code below to call the printPage function.

<input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />


问:
How to publish website but prevent visitors?
I would like to publish my asp.net core to my own domain that is hosted on a shared hosting.
However, after publishing I would like to spend a few hours live testing it (yeah, I have yet to learn auto testing using selenium).

While doing so, I want to prevent visitors from knowing that the site is published so that they won't use it; some strangers know that I will be publishing some time soon and they may have set up auto monitoring.

How can that be achieved?

答: Best recommendation would be to use a different subdomain if your applications isn't affected by the domain it is accessed on, this will allow the older version to still be used by others. But if you don't mind if others are completely unable to access the system while you are testing, just whitelist only your IP on the domain.</p>


问:
Connecting VM Client To Server On My Computer C#
I'm having trouble with this network chat application code I found. It works fine when both applications are run on the same computer, but when trying to connect a VM client to my host app running on my real install, I get a timeout. Here is the code.</p>

```<code>static readonly object _lock = new object();
        static readonly Dictionary<int, TcpClient> list_clients = new Dictionary<int, TcpClient>();

        static void Main(string[] args) {
            int count = 1;

            TcpListener ServerSocket = new TcpListener(IPAddress.Parse("192.168.1.59"), 5000);
            ServerSocket.Start();

            while(true) {
                TcpClient client = ServerSocket.AcceptTcpClient();
                lock(_lock) list_clients.Add(count, client);
                Console.WriteLine("Someone connected!!");

                Thread t = new Thread(handle_clients);
                t.Start(count);
                count++;
            }
        }
    }

class Client {
        static void Main(string[] args) {
            IPAddress ip = IPAddress.Parse("192.168.1.59");
            int port = 5000;
            TcpClient client = new TcpClient();
            client.Connect(ip, port);
            Console.WriteLine("client connected!!");
            NetworkStream ns = client.GetStream();
            Thread thread = new Thread(o => ReceiveData((TcpClient)o));

            thread.Start(client);

            string s;
            while(!string.IsNullOrEmpty((s = Console.ReadLine()))) {
                byte[] buffer = Encoding.ASCII.GetBytes(s);
                ns.Write(buffer, 0, buffer.Length);
            }

            client.Client.Shutdown(SocketShutdown.Send);
            thread.Join();
            ns.Close();
            client.Close();
            Console.WriteLine("disconnect from server!!");
            Console.ReadKey();
        }
    }```
</code>```

答:
Your VM is probably running in a different network interface.

Try instead:

TcpListener ServerSocket = new TcpListener(IPAddress.Any, 5000);

This way you tell the server to listen on any network interface.

Addition: Also, the VM client should connect to the IP address your computer (with TCPListener program) has, within the VM network range. Not 192.168.1.59, but:

```<code>static void Main(string[] args) {
    IPAddress ip = IPAddress.Parse("172.17.xx.xx");
    ...
</code>```

Body:
I'm having trouble with this network chat application code I found. It works fine when both applications are run on the same computer, but when trying to connect a VM client to my host app running on my real install, I get a timeout. Here is the code.

static readonly object _lock = new object();
        static readonly Dictionary<int, TcpClient> list_clients = new Dictionary<int, TcpClient>();

        static void Main(string[] args) {
            int count = 1;

            TcpListener ServerSocket = new TcpListener(IPAddress.Parse("192.168.1.59"), 5000);
            ServerSocket.Start();

            while(true) {
                TcpClient client = ServerSocket.AcceptTcpClient();
                lock(_lock) list_clients.Add(count, client);
                Console.WriteLine("Someone connected!!");

                Thread t = new Thread(handle_clients);
                t.Start(count);
                count++;
            }
        }
    }

class Client {
        static void Main(string[] args) {
            IPAddress ip = IPAddress.Parse("192.168.1.59");
            int port = 5000;
            TcpClient client = new TcpClient();
            client.Connect(ip, port);
            Console.WriteLine("client connected!!");
            NetworkStream ns = client.GetStream();
            Thread thread = new Thread(o => ReceiveData((TcpClient)o));

            thread.Start(client);

            string s;
            while(!string.IsNullOrEmpty((s = Console.ReadLine()))) {
                byte[] buffer = Encoding.ASCII.GetBytes(s);
                ns.Write(buffer, 0, buffer.Length);
            }

            client.Client.Shutdown(SocketShutdown.Send);
            thread.Join();
            ns.Close();
            client.Close();
            Console.WriteLine("disconnect from server!!");
            Console.ReadKey();
        }
    }```

Body:
Your VM is probably running in a different network interface.

Try instead:

TcpListener ServerSocket = new TcpListener(IPAddress.Any, 5000);

This way you tell the server to listen on any network interface.

Addition: Also, the VM client should connect to the IP address your computer (with TCPListener program) has, within the VM network range. Not 192.168.1.59, but:

static void Main(string[] args) {
    IPAddress ip = IPAddress.Parse("172.17.xx.xx");
    ...


问:
set an environment variable when running test from run button in VSCODE
I am creating some tests in Flutter, but I need to set an environment variable before running the tests. Is there a way to set an environment variable when running the app from these "Run | Debug" buttons?

答:
With the new update to the Dart SDK it is possible:
https://dartcode.org/releases/v3-11/

[...] For example, to add CodeLens for a launch config that sets a RELEASE_MODE=true environment variable to tests in test/integration_tests:

```<code>{
    "name": "Current File (release mode)",
    "type": "dart",
    "request": "launch",
    "codeLens": {
        // Types of CodeLens to inject
        "for": [ "run-test", "run-test-file", "debug-test", "debug-test-file" ],
        // Restrict to certain folders
        "path": "test/integration_tests",
        // Text for CodeLens link (${debugType} will be replaced with "run" or "debug")
        "title": "${debugType} (release)"
    },
    "env": { "RELEASE_MODE": true }
}
</code>```

This will insert additional CodeLens links into tests, groups and main functions:

Body:
With the new update to the Dart SDK it is possible:
https://dartcode.org/releases/v3-11/

[...] For example, to add CodeLens for a launch config that sets a RELEASE_MODE=true environment variable to tests in test/integration_tests:

{
    "name": "Current File (release mode)",
    "type": "dart",
    "request": "launch",
    "codeLens": {
        // Types of CodeLens to inject
        "for": [ "run-test", "run-test-file", "debug-test", "debug-test-file" ],
        // Restrict to certain folders
        "path": "test/integration_tests",
        // Text for CodeLens link (${debugType} will be replaced with "run" or "debug")
        "title": "${debugType} (release)"
    },
    "env": { "RELEASE_MODE": true }
}

This will insert additional CodeLens links into tests, groups and main functions:


问:
How to generate MANIFEST.MF file during compile phase
Standard way - using maven-jar-plugin - generates manifest file only during package phase and directly into jar file.

What I need is to generate manifest during compile phase and to be available in <target>/classes/META-INF.

My goal is to be able to read this manifest file in project running in debug mode in IntelliJ Idea. (Idea resolves in-project jar dependencies from <target>/classes instead of from <target>/*.jar - for hot-swap purpose).

The only solution I know of so far is to actually create my own MANIFEST.MF in src/main/java/resources/META-INF and let it be filtered+copied during resources phase. But I want to avoid this solution, I want the manifest to be generated standard way using <archive> configuration in pom file.

答:
Many thanks for the excellent answer from @frekele. As I cannot add comments to existing answers, so adding this one to note that you need to tie to the compile phase instead of process-classes if you want to generate the manifest during the compile phase:

<plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <version>4.2.1</version>
    <executions>
        <execution>
        <id>bundle-manifest</id>
        <phase>compile</phase>

```

Body:
Many thanks for the excellent answer from @frekele. As I cannot add comments to existing answers, so adding this one to note that you need to tie to the compile phase instead of process-classes if you want to generate the manifest during the compile phase:

<plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <version>4.2.1</version>
    <executions>
        <execution>
        <id>bundle-manifest</id>
        <phase>compile</phase>
        <!-- ... -->


问:
How to create a multistage dockerfile for a python app?
Below is the directory structure and the dockerfile for my python application. In order to run the main.py, I need to create a data set by running generate_data.py, which is in the data directory. How can I create a multistage dockerfile in order to first create the data and then run the main.py file? I'm new to using docker and I feel overwhelmed.

```<code>FROM python:3.7.2-slim
WORKDIR /usr/src/app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . /usr/src/app
CMD ["python", "./src/main.py"]
</code>```

答:
You can create a shell script then use that for CMD

start.sh:

```<code>#!/bin/bash
python generate_data.py
python ./src/main.py
</code>```

Dockerfile:

```<code>FROM python:3.7.2-slim
WORKDIR /usr/src/app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . /usr/src/app
CMD ["sh", "start.sh"]
</code>```

Body:
Below is the directory structure and the dockerfile for my python application. In order to run the main.py, I need to create a data set by running generate_data.py, which is in the data directory. How can I create a multistage dockerfile in order to first create the data and then run the main.py file? I'm new to using docker and I feel overwhelmed.

FROM python:3.7.2-slim
WORKDIR /usr/src/app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . /usr/src/app
CMD ["python", "./src/main.py"]

Body:
You can create a shell script then use that for CMD

start.sh:

#!/bin/bash
python generate_data.py
python ./src/main.py

Dockerfile:

FROM python:3.7.2-slim
WORKDIR /usr/src/app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . /usr/src/app
CMD ["sh", "start.sh"]


问:
How to extract characters from an array in column-major order?
I am trying to have java read my array and output what is in the array by column.
Here is my code so far where I created the array and pulled a text file into that array:

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ArrayTryTwo {
    // Written by Nathan Hobson
    public static void main(String[] args) throws FileNotFoundException {
        String str = "";
        char[][] ar = new char[6][7];
        final int size = 42;
        int count = 0, len;

        File file = new File("/Users/nathanhobson/Desktop/Array.txt");
        Scanner sc = new Scanner(file);

        str = sc.nextLine();
        while (sc.hasNextLine()) {
            str = str + "\n" + sc.nextLine();
        }
        char[] charArray = str.toCharArray();
        len=charArray.length;
        for(int a=0; a<6; a++) {
            if(count>size) {
                break;
            }
            for(int b=0; b<7; b++) {
                if(count>size) {
                    break;
                }
                else if(len<size && count>=len) {
                    ar[a][b]='*';
                }
                else {
                    ar[a][b]=charArray[count];
                    count++;
                }
            }
        }
        System.out.println("The 2 dimensional array:");
        for(int a=0; a<6; a++) {
            for(int b=0; b<7; b++) {
                System.out.print(ar[a][b]+" ");
            }
            System.out.println();
        }
        sc.close();
    }
}
</code>```

The problem I am running into is how to code java to read the array by column(each column from top to bottom). I know it will just be a few lines of code but I cannot find an example in my book or online so I am asking now in stackoverflow. I hope that this was the right way to ask a question on this website.

答:
Right now you are storing the array of characters in a 1D array, charArray, then placing those values into a 2D character array, ar. I would recommend directly placing the characters into a 2D array like so.

```<code>char[][] charMatrix = new char[6][7];
Scanner charScanner = new Scanner(new File("/Users/nathanhobson/Desktop/Array.txt"));

//temp array for each line
char[] lineArr;

for(int i = 0; i < charMatrix.length; i++) {
    lineArr = charScanner.nextLine().toCharArray();
    charMatrix[i] = lineArr;
}
</code>```

In order to print out the columns of an array, you loop through each row index for every column index.

```<code>for(int col = 0; col < charMatrix[0].length; col++) {
    for(int row = 0; row < charMatrix.length; row++) {
        System.out.println(charMatrix[row][col] + " ");
    }
    System.out.print("\n");
}
</code>```

You can print the columns in what ever manner you would like, that's just one method how you would go about accessing the elements by column.

Hope this helps

Body:
I am trying to have java read my array and output what is in the array by column.
Here is my code so far where I created the array and pulled a text file into that array:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ArrayTryTwo {
    // Written by Nathan Hobson
    public static void main(String[] args) throws FileNotFoundException {
        String str = "";
        char[][] ar = new char[6][7];
        final int size = 42;
        int count = 0, len;

        File file = new File("/Users/nathanhobson/Desktop/Array.txt");
        Scanner sc = new Scanner(file);

        str = sc.nextLine();
        while (sc.hasNextLine()) {
            str = str + "\n" + sc.nextLine();
        }
        char[] charArray = str.toCharArray();
        len=charArray.length;
        for(int a=0; a<6; a++) {
            if(count>size) {
                break;
            }
            for(int b=0; b<7; b++) {
                if(count>size) {
                    break;
                }
                else if(len<size && count>=len) {
                    ar[a][b]='*';
                }
                else {
                    ar[a][b]=charArray[count];
                    count++;
                }
            }
        }
        System.out.println("The 2 dimensional array:");
        for(int a=0; a<6; a++) {
            for(int b=0; b<7; b++) {
                System.out.print(ar[a][b]+" ");
            }
            System.out.println();
        }
        sc.close();
    }
}

The problem I am running into is how to code java to read the array by column(each column from top to bottom). I know it will just be a few lines of code but I cannot find an example in my book or online so I am asking now in stackoverflow. I hope that this was the right way to ask a question on this website.

Body:
Right now you are storing the array of characters in a 1D array, charArray, then placing those values into a 2D character array, ar. I would recommend directly placing the characters into a 2D array like so.

char[][] charMatrix = new char[6][7];
Scanner charScanner = new Scanner(new File("/Users/nathanhobson/Desktop/Array.txt"));

//temp array for each line
char[] lineArr;

for(int i = 0; i < charMatrix.length; i++) {
    lineArr = charScanner.nextLine().toCharArray();
    charMatrix[i] = lineArr;
}

In order to print out the columns of an array, you loop through each row index for every column index.

for(int col = 0; col < charMatrix[0].length; col++) {
    for(int row = 0; row < charMatrix.length; row++) {
        System.out.println(charMatrix[row][col] + " ");
    }
    System.out.print("\n");
}

You can print the columns in what ever manner you would like, that's just one method how you would go about accessing the elements by column.

Hope this helps


问:
A way to backup data(databases, collections, documents) in mongodb
do you know any tool to backup data in mongodb? Like mysqldump in mongodb

thank you in advance!

答: Useful answer from "MongoDB backup plan" question.</p>