问:
Average latency of atomics cmpxchg instructions on Intel Cpus

 I am looking for some reference on average latencies for lock cmpxchg instruction for various intel processors. I am not able to locate any good reference on the topic and any reference would greatly help.

Thanks.

答:
You can use AIDA64 software to check instruction latencies (but you cannot check which of the instructions to check, it has a hard-coded list of instructions). People are publishing the results at http://instlatx64.atw.hu/

From the lock instructions, AIDA64 verifies the lock add instructions and xchg [mem] (which is always locking even without an explicit lock prefix).

Here are some info. I will also give you, for comparison, latencies of the following instructions:

xchg reg1, reg2 which is not locking;

add to registers and memory.

As you see, the locking instructions are just 5 times slower on Haswell-DT and just ~2 times slower on Kaby Lake-S than non-locking memory stores.

Intel Core i5-4430, 3000 MHz (30 x 100) Haswell-DT

```<code>LOCK ADD [m8], r8         L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
LOCK ADD [m16], r16       L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
LOCK ADD [m32], r32       L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
LOCK ADD [m32 + 8], r32   L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
LOCK ADD [m64], r64       L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
LOCK ADD [m64 + 16], r64  L: 5.96ns= 17.8c  T: 7.21ns= 21.58c

XCHG r8, [m8]             L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
XCHG r16, [m16]           L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
XCHG r32, [m32]           L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
XCHG r64, [m64]           L: 5.96ns= 17.8c  T: 7.21ns= 21.58c

ADD r32, 0x04000          L: 0.22ns=  0.9c  T: 0.09ns=  0.36c
ADD r32, 0x08000          L: 0.22ns=  0.9c  T: 0.09ns=  0.36c
ADD r32, 0x10000          L: 0.22ns=  0.9c  T: 0.09ns=  0.36c
ADD r32, 0x20000          L: 0.22ns=  0.9c  T: 0.08ns=  0.34c
ADD r8, r8                L: 0.22ns=  0.9c  T: 0.05ns=  0.23c
ADD r16, r16              L: 0.22ns=  0.9c  T: 0.07ns=  0.29c
ADD r32, r32              L: 0.22ns=  0.9c  T: 0.05ns=  0.23c
ADD r64, r64              L: 0.22ns=  0.9c  T: 0.07ns=  0.29c
ADD r8, [m8]              L: 1.33ns=  5.6c  T: 0.11ns=  0.47c
ADD r16, [m16]            L: 1.33ns=  5.6c  T: 0.11ns=  0.47c
ADD r32, [m32]            L: 1.33ns=  5.6c  T: 0.11ns=  0.47c
ADD r64, [m64]            L: 1.33ns=  5.6c  T: 0.11ns=  0.47c
ADD [m8], r8              L: 1.19ns=  5.0c  T: 0.32ns=  1.33c
ADD [m16], r16            L: 1.19ns=  5.0c  T: 0.21ns=  0.88c
ADD [m32], r32            L: 1.19ns=  5.0c  T: 0.22ns=  0.92c
ADD [m32 + 8], r32        L: 1.19ns=  5.0c  T: 0.22ns=  0.92c
ADD [m64], r64            L: 1.19ns=  5.0c  T: 0.20ns=  0.85c
ADD [m64 + 16], r64       L: 1.19ns=  5.0c  T: 0.18ns=  0.73c
</code>```

Intel Core i7-7700K, 4700 MHz (47 x 100) Kaby Lake-S

```<code>LOCK ADD [m8], r8         L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
LOCK ADD [m16], r16       L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
LOCK ADD [m32], r32       L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
LOCK ADD [m32 + 8], r32   L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
LOCK ADD [m64], r64       L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
LOCK ADD [m64 + 16], r64  L: 4.01ns= 16.8c  T: 5.12ns= 21.50c

XCHG r8, [m8]             L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
XCHG r16, [m16]           L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
XCHG r32, [m32]           L: 4.01ns= 16.8c  T: 5.20ns= 21.83c
XCHG r64, [m64]           L: 4.01ns= 16.8c  T: 5.12ns= 21.50c

ADD r32, 0x04000          L: 0.33ns=  1.0c  T: 0.12ns=  0.36c
ADD r32, 0x08000          L: 0.31ns=  0.9c  T: 0.12ns=  0.37c
ADD r32, 0x10000          L: 0.31ns=  0.9c  T: 0.12ns=  0.36c
ADD r32, 0x20000          L: 0.31ns=  0.9c  T: 0.12ns=  0.36c
ADD r8, r8                L: 0.31ns=  0.9c  T: 0.11ns=  0.34c
ADD r16, r16              L: 0.31ns=  0.9c  T: 0.11ns=  0.32c
ADD r32, r32              L: 0.31ns=  0.9c  T: 0.11ns=  0.34c
ADD r64, r64              L: 0.31ns=  0.9c  T: 0.10ns=  0.31c
ADD r8, [m8]              L: 1.87ns=  5.6c  T: 0.16ns=  0.47c
ADD r16, [m16]            L: 1.87ns=  5.6c  T: 0.16ns=  0.47c
ADD r32, [m32]            L: 1.87ns=  5.6c  T: 0.16ns=  0.47c
ADD r64, [m64]            L: 1.87ns=  5.6c  T: 0.16ns=  0.47c
ADD [m8], r8              L: 1.89ns=  5.7c  T: 0.33ns=  1.00c
ADD [m16], r16            L: 1.87ns=  5.6c  T: 0.26ns=  0.78c
ADD [m32], r32            L: 1.87ns=  5.6c  T: 0.28ns=  0.84c
ADD [m32 + 8], r32        L: 1.89ns=  5.7c  T: 0.26ns=  0.78c
ADD [m64], r64            L: 1.89ns=  5.7c  T: 0.33ns=  1.00c
ADD [m64 + 16], r64       L: 1.89ns=  5.7c  T: 0.24ns=  0.73c
</code>```

Body:
You can use AIDA64 software to check instruction latencies (but you cannot check which of the instructions to check, it has a hard-coded list of instructions). People are publishing the results at http://instlatx64.atw.hu/

From the lock instructions, AIDA64 verifies the lock add instructions and xchg [mem] (which is always locking even without an explicit lock prefix).

Here are some info. I will also give you, for comparison, latencies of the following instructions:

xchg reg1, reg2 which is not locking;

add to registers and memory.

As you see, the locking instructions are just 5 times slower on Haswell-DT and just ~2 times slower on Kaby Lake-S than non-locking memory stores.

Intel Core i5-4430, 3000 MHz (30 x 100) Haswell-DT

LOCK ADD [m8], r8         L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
LOCK ADD [m16], r16       L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
LOCK ADD [m32], r32       L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
LOCK ADD [m32 + 8], r32   L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
LOCK ADD [m64], r64       L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
LOCK ADD [m64 + 16], r64  L: 5.96ns= 17.8c  T: 7.21ns= 21.58c

XCHG r8, [m8]             L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
XCHG r16, [m16]           L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
XCHG r32, [m32]           L: 5.96ns= 17.8c  T: 7.21ns= 21.58c
XCHG r64, [m64]           L: 5.96ns= 17.8c  T: 7.21ns= 21.58c

ADD r32, 0x04000          L: 0.22ns=  0.9c  T: 0.09ns=  0.36c
ADD r32, 0x08000          L: 0.22ns=  0.9c  T: 0.09ns=  0.36c
ADD r32, 0x10000          L: 0.22ns=  0.9c  T: 0.09ns=  0.36c
ADD r32, 0x20000          L: 0.22ns=  0.9c  T: 0.08ns=  0.34c
ADD r8, r8                L: 0.22ns=  0.9c  T: 0.05ns=  0.23c
ADD r16, r16              L: 0.22ns=  0.9c  T: 0.07ns=  0.29c
ADD r32, r32              L: 0.22ns=  0.9c  T: 0.05ns=  0.23c
ADD r64, r64              L: 0.22ns=  0.9c  T: 0.07ns=  0.29c
ADD r8, [m8]              L: 1.33ns=  5.6c  T: 0.11ns=  0.47c
ADD r16, [m16]            L: 1.33ns=  5.6c  T: 0.11ns=  0.47c
ADD r32, [m32]            L: 1.33ns=  5.6c  T: 0.11ns=  0.47c
ADD r64, [m64]            L: 1.33ns=  5.6c  T: 0.11ns=  0.47c
ADD [m8], r8              L: 1.19ns=  5.0c  T: 0.32ns=  1.33c
ADD [m16], r16            L: 1.19ns=  5.0c  T: 0.21ns=  0.88c
ADD [m32], r32            L: 1.19ns=  5.0c  T: 0.22ns=  0.92c
ADD [m32 + 8], r32        L: 1.19ns=  5.0c  T: 0.22ns=  0.92c
ADD [m64], r64            L: 1.19ns=  5.0c  T: 0.20ns=  0.85c
ADD [m64 + 16], r64       L: 1.19ns=  5.0c  T: 0.18ns=  0.73c

Intel Core i7-7700K, 4700 MHz (47 x 100) Kaby Lake-S

LOCK ADD [m8], r8         L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
LOCK ADD [m16], r16       L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
LOCK ADD [m32], r32       L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
LOCK ADD [m32 + 8], r32   L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
LOCK ADD [m64], r64       L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
LOCK ADD [m64 + 16], r64  L: 4.01ns= 16.8c  T: 5.12ns= 21.50c

XCHG r8, [m8]             L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
XCHG r16, [m16]           L: 4.01ns= 16.8c  T: 5.12ns= 21.50c
XCHG r32, [m32]           L: 4.01ns= 16.8c  T: 5.20ns= 21.83c
XCHG r64, [m64]           L: 4.01ns= 16.8c  T: 5.12ns= 21.50c

ADD r32, 0x04000          L: 0.33ns=  1.0c  T: 0.12ns=  0.36c
ADD r32, 0x08000          L: 0.31ns=  0.9c  T: 0.12ns=  0.37c
ADD r32, 0x10000          L: 0.31ns=  0.9c  T: 0.12ns=  0.36c
ADD r32, 0x20000          L: 0.31ns=  0.9c  T: 0.12ns=  0.36c
ADD r8, r8                L: 0.31ns=  0.9c  T: 0.11ns=  0.34c
ADD r16, r16              L: 0.31ns=  0.9c  T: 0.11ns=  0.32c
ADD r32, r32              L: 0.31ns=  0.9c  T: 0.11ns=  0.34c
ADD r64, r64              L: 0.31ns=  0.9c  T: 0.10ns=  0.31c
ADD r8, [m8]              L: 1.87ns=  5.6c  T: 0.16ns=  0.47c
ADD r16, [m16]            L: 1.87ns=  5.6c  T: 0.16ns=  0.47c
ADD r32, [m32]            L: 1.87ns=  5.6c  T: 0.16ns=  0.47c
ADD r64, [m64]            L: 1.87ns=  5.6c  T: 0.16ns=  0.47c
ADD [m8], r8              L: 1.89ns=  5.7c  T: 0.33ns=  1.00c
ADD [m16], r16            L: 1.87ns=  5.6c  T: 0.26ns=  0.78c
ADD [m32], r32            L: 1.87ns=  5.6c  T: 0.28ns=  0.84c
ADD [m32 + 8], r32        L: 1.89ns=  5.7c  T: 0.26ns=  0.78c
ADD [m64], r64            L: 1.89ns=  5.7c  T: 0.33ns=  1.00c
ADD [m64 + 16], r64       L: 1.89ns=  5.7c  T: 0.24ns=  0.73c


来源: stackexchange

问:
Check if there are out of stock items in cart - WooCommerce
I need to display a section in my checkout order review ONLY IF there is an out of stock item in the cart (b/c our products are available on backorder). Here is the code that displays the section...

Functions.php:

```<code>function notes_in_cart() {
    global $woocommerce;
       if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }
    if ( WC()->cart->needs_shipping() ){
        //if cart has items out of stock
        //if (cart has out of stock product) {
        ?>
            <tr class="ceckoutStockMeta">
                <th>Item Shipments</th>

                <td>
                    <p style="color: red;">*You have one or more items in your cart that are currently out of stock. Please select a custom shipping option for your order.</p><br>
                    <form>

                        <input type="radio" name="stockOp" id="stockOption1" value="ship" />
                        <label for="stockOption1">Ship what is available now</label><br>

                        <input type="radio" name="stockOp" id="stockOption2" value="hold" />
                        <label for="stockOption2">Wait and ship together</label>
                    </form>
                </td>
            </tr>

        <?php

        //}
    }
}
add_action( 'woocommerce_cart_totals_after_order_total', 'notes_in_cart' );
add_action( 'woocommerce_review_order_after_order_total', 'notes_in_cart' );
</code>```

Right now the section shows all the time. I know I will probably need to call the cart items and loop through with a foreach to determine if one is out of stock, but not sure how.

答:
You can do it like this to check against the "Stock quantity" and the "Allow Backorders?" properties of the products:

```<code>function notes_in_cart() {
     global $woocommerce;

    if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }

    if ( WC()->cart->needs_shipping() ){

        // set $out_of_stock_exists to false by default
        $out_of_stock_exists = false;
        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
            if($values['data']->backorders_allowed()){ //check if backorders are allowed on this product
                // get the stock quantity - returns the available amount number
                $stock_info = $values['data']->get_stock_quantity();

                if($stock_info < $values['quantity']){ //thanks to LoicTheAztec for pointing it out in his answer
                    // set $out_of_stock_exists to true and stop foreach execution
                    $out_of_stock_exists = true;
                    break;
                }
            }

        }

        //if cart has items out of stock
        if ($out_of_stock_exists) {
            ?>
            <tr class="ceckoutStockMeta">
                <th>Item Shipments</th>
                <td>
                    <p style="color: red;">*You have one or more items in your cart that are currently out of stock. Please select a custom shipping option for your order.</p><br>
                    <form>

                        <input type="radio" name="stockOp" id="stockOption1" value="ship" />
                        <label for="stockOption1">Ship what is available now</label><br>

                        <input type="radio" name="stockOp" id="stockOption2" value="hold" />
                        <label for="stockOption2">Wait and ship together</label>
                    </form>
                </td>
            </tr>

            <?php

        }
    }
}
add_action( 'woocommerce_cart_totals_after_order_total', 'notes_in_cart' );
add_action( 'woocommerce_review_order_after_order_total', 'notes_in_cart' );
</code>```

It can also be done using the get_stock_status() or is_in_stock() methods that returns the value of "Stock status" - 'instock' or 'outofstock' - but that will not allow the checkout using backorders: https://github.com/woocommerce/woocommerce/issues/11187 or https://github.com/woocommerce/woocommerce/issues/10834

EDIT: More details on why is_in_stock() does not work:
The is_in_stock() method is this one:

```<code>public function is_in_stock() {
    return apply_filters( 'woocommerce_product_is_in_stock', 'instock' === $this->get_stock_status(), $this );
}
</code>```

That means it checks for "Stock Status" and it returns true if "in stock" and false if "out of stock".

Now, if you read here: https://conschneider.de/manage-stock-backorders-woocommerce/

You will find that:

Backorders only are possible for as long as the stock status is “in
  stock”. Setting the product to out of stock will again block purchases
  and display “out of stock”.

ContentLicense: CC BY-SA 3.0

Body:
I need to display a section in my checkout order review ONLY IF there is an out of stock item in the cart (b/c our products are available on backorder). Here is the code that displays the section...

Functions.php:

function notes_in_cart() {
    global $woocommerce;
       if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }
    if ( WC()->cart->needs_shipping() ){
        //if cart has items out of stock
        //if (cart has out of stock product) {
        ?>

                Item Shipments

*You have one or more items in your cart that are currently out of stock. Please select a custom shipping option for your order.

                    <form>

                        <input type="radio" name="stockOp" id="stockOption1" value="ship" />
                        Ship what is available now

                        <input type="radio" name="stockOp" id="stockOption2" value="hold" />
                        Wait and ship together
                    </form>

        <?php

        //}
    }
}
add_action( 'woocommerce_cart_totals_after_order_total', 'notes_in_cart' );
add_action( 'woocommerce_review_order_after_order_total', 'notes_in_cart' );

Right now the section shows all the time. I know I will probably need to call the cart items and loop through with a foreach to determine if one is out of stock, but not sure how.

Body:
You can do it like this to check against the "Stock quantity" and the "Allow Backorders?" properties of the products:

function notes_in_cart() {
     global $woocommerce;

    if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }

    if ( WC()->cart->needs_shipping() ){

        // set $out_of_stock_exists to false by default
        $out_of_stock_exists = false;
        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
            if($values['data']->backorders_allowed()){ //check if backorders are allowed on this product
                // get the stock quantity - returns the available amount number
                $stock_info = $values['data']->get_stock_quantity();

                if($stock_info < $values['quantity']){ //thanks to LoicTheAztec for pointing it out in his answer
                    // set $out_of_stock_exists to true and stop foreach execution
                    $out_of_stock_exists = true;
                    break;
                }
            }

        }

        //if cart has items out of stock
        if ($out_of_stock_exists) {
            ?>
            <tr class="ceckoutStockMeta">
                <th>Item Shipments</th>
                <td>
                    <p style="color: red;">*You have one or more items in your cart that are currently out of stock. Please select a custom shipping option for your order.</p><br>
                    <form>

                        <input type="radio" name="stockOp" id="stockOption1" value="ship" />
                        <label for="stockOption1">Ship what is available now</label><br>

                        <input type="radio" name="stockOp" id="stockOption2" value="hold" />
                        <label for="stockOption2">Wait and ship together</label>
                    </form>
                </td>
            </tr>

            <?php

        }
    }
}
add_action( 'woocommerce_cart_totals_after_order_total', 'notes_in_cart' );
add_action( 'woocommerce_review_order_after_order_total', 'notes_in_cart' );

It can also be done using the get_stock_status() or is_in_stock() methods that returns the value of "Stock status" - 'instock' or 'outofstock' - but that will not allow the checkout using backorders: https://github.com/woocommerce/woocommerce/issues/11187 or https://github.com/woocommerce/woocommerce/issues/10834

EDIT: More details on why is_in_stock() does not work:
The is_in_stock() method is this one:

public function is_in_stock() {
    return apply_filters( 'woocommerce_product_is_in_stock', 'instock' === $this->get_stock_status(), $this );
}

That means it checks for "Stock Status" and it returns true if "in stock" and false if "out of stock".

Now, if you read here: https://conschneider.de/manage-stock-backorders-woocommerce/

You will find that:

Backorders only are possible for as long as the stock status is “in
  stock”. Setting the product to out of stock will again block purchases
  and display “out of stock”.


问:
Error when trying to check for pressed key
I am trying to use a simple event listener.

This is what I have so far:

```<code>import keyboard
while True:
    if keyboard.is_pressed('p'):
        print('You pressed P')
</code>```

I get the error:

AttributeError: module 'keyboard' has no attribute 'is_pressed'

When I check the documentation, I see that is_pressed exists.

Is there something wrong with the library or am I doing something wrong?

答:
I'll add it as a formal answer anyways. You mentioned that you git clone the repository. I guess this is confusing since the README says you can either do pip install or git clone to install the package.

When you do import, it tells Python to go through it's package manager to find the module and these need to be installed on your end. pip is the package management system that Python uses

If you want to install a package that you have as a local folder (i.e. if you wanted to test a local module) you can do so see here

Body:
I am trying to use a simple event listener.

This is what I have so far:

import keyboard
while True:
    if keyboard.is_pressed('p'):
        print('You pressed P')

I get the error:

AttributeError: module 'keyboard' has no attribute 'is_pressed'

When I check the documentation, I see that is_pressed exists.

Is there something wrong with the library or am I doing something wrong?


问:
Converting Varchar 3 to int
When entering the very last join in my code below I get an error message that states "Conversion failed when converting the varchar value '3' to data type int." (MSG 245, Level 16, State 1, Line 1) Can someone please help me with this? In the one table it does have weird characters in front of the number that I am trying to join with the other number in the other table. </p>

```<code>SELECT ca.fdorgunit AS Facility
, pt.fdmedrecnum AS Account
, ca.fddos AS DOS
, ad.fdaddr1 AS [Address]
, pe.fdssn AS SSN
FROM OPENQUERY (VISION, 'SELECT * FROM ci.tbcase') AS ca
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbpatient') AS pt
ON pt.id = ca.fdpatient
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbperson') AS pe
ON pt.fdperson = pe.fdid
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbaddress') AS ad
ON ad.id = pe.fdaddress
WHERE ca.fdcasestatus = 'Performed'
GROUP BY ca.fdorgunit, ca.fddos, pt.fdmedrecnum, pe.fdssn, ad.fdaddr1
</code>```

答:
I think one of your records propabaly in pe.fdaddress is not numeric
to avoid this you better convert the integer to char
something like this </p>

```<code>SELECT ca.fdorgunit AS Facility
, pt.fdmedrecnum AS Account
, ca.fddos AS DOS
, ad.fdaddr1 AS [Address]
, pe.fdssn AS SSN
FROM OPENQUERY (VISION, 'SELECT * FROM ci.tbcase') AS ca
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbpatient') AS pt
ON pt.id = ca.fdpatient
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbperson') AS pe
ON pt.fdperson = pe.fdid
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbaddress') AS ad
ON CAST(ad.id AS varchar(10)) =  CAST(pe.fdaddress AS varchar(10))
WHERE ca.fdcasestatus = 'Performed'
GROUP BY ca.fdorgunit, ca.fddos, pt.fdmedrecnum, pe.fdssn, ad.fdaddr1
</code>```

Title: Converting Varchar 3 to int

Body:
When entering the very last join in my code below I get an error message that states "Conversion failed when converting the varchar value '3' to data type int." (MSG 245, Level 16, State 1, Line 1) Can someone please help me with this? In the one table it does have weird characters in front of the number that I am trying to join with the other number in the other table.

SELECT ca.fdorgunit AS Facility
, pt.fdmedrecnum AS Account
, ca.fddos AS DOS
, ad.fdaddr1 AS [Address]
, pe.fdssn AS SSN
FROM OPENQUERY (VISION, 'SELECT * FROM ci.tbcase') AS ca
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbpatient') AS pt
ON pt.id = ca.fdpatient
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbperson') AS pe
ON pt.fdperson = pe.fdid
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbaddress') AS ad
ON ad.id = pe.fdaddress
WHERE ca.fdcasestatus = 'Performed'
GROUP BY ca.fdorgunit, ca.fddos, pt.fdmedrecnum, pe.fdssn, ad.fdaddr1

Body:
I think one of your records propabaly in pe.fdaddress is not numeric
to avoid this you better convert the integer to char
something like this

SELECT ca.fdorgunit AS Facility
, pt.fdmedrecnum AS Account
, ca.fddos AS DOS
, ad.fdaddr1 AS [Address]
, pe.fdssn AS SSN
FROM OPENQUERY (VISION, 'SELECT * FROM ci.tbcase') AS ca
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbpatient') AS pt
ON pt.id = ca.fdpatient
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbperson') AS pe
ON pt.fdperson = pe.fdid
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbaddress') AS ad
ON CAST(ad.id AS varchar(10)) =  CAST(pe.fdaddress AS varchar(10))
WHERE ca.fdcasestatus = 'Performed'
GROUP BY ca.fdorgunit, ca.fddos, pt.fdmedrecnum, pe.fdssn, ad.fdaddr1


问:
Python Multi Process has missing process and completes a join when it shouldn't have
I am facing a pretty odd issue. I have multi process python code that processes some data in parallel. I split the data in to 8 and work on each split individually using a Process Class, I then do a join on each Process.

I just noticed that when I process a large amount of data, one of the threads.... disappears. As in it doesn't error out or raise an exception and it just goes missing. What is even more interesting is that it seems to successfully complete the join() on the process when I know for a fact it did not finish.

```<code>tn1_processes = []
for i in range(8):
        tn1_processes.append(
            MyCustomProcess(logger=self.logger, i=i,
                                    shared_queue=shared_queue))
        tn1_processes[-1].start()

for tn1_processor in tn1_processes:
    tn1_processor.join()
print('Done')
</code>```

What do I know for sure:
All Processes are starting and are processing data and reach about half way, I know this because I have logs that show all the Processes doing their work.
Then Process 1 disappears from the logs towards the end of it's job, while all the other ones keep working fine and completing. Then My code moves on after thinking all the Processes are complete after the joins (I demonstrate this with a print) however I know for a fact that one of the processes did not complete, it did not error out and for some strange reason it passed the join()?

The only thing I can think of is that the Process runs out of memory but I would feel it would error out or throw an exception if this happened. Actually it has happened to me before using the same code and I saw the exception in my logs and the code was able to handle and see that the Process failed. But this, no error or anything is strange.

Can anyone shed some light?

Using Python3.4

答:
If I remember correctly when a process abruptly terminates it wouldn't throw an error, you need to have another queue for storing the thrown exceptions and handle them elsewhere.

When a process ends however, an exit code is given: https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Process.exitcode

A rudimentary check would be making sure all of them safely exited (probably with 0 as exit code, while negative indicates termination signal and None as running).

Body:
I am facing a pretty odd issue. I have multi process python code that processes some data in parallel. I split the data in to 8 and work on each split individually using a Process Class, I then do a join on each Process.

I just noticed that when I process a large amount of data, one of the threads.... disappears. As in it doesn't error out or raise an exception and it just goes missing. What is even more interesting is that it seems to successfully complete the join() on the process when I know for a fact it did not finish.

tn1_processes = []
for i in range(8):
        tn1_processes.append(
            MyCustomProcess(logger=self.logger, i=i,
                                    shared_queue=shared_queue))
        tn1_processes[-1].start()

for tn1_processor in tn1_processes:
    tn1_processor.join()
print('Done')

What do I know for sure:
All Processes are starting and are processing data and reach about half way, I know this because I have logs that show all the Processes doing their work.
Then Process 1 disappears from the logs towards the end of it's job, while all the other ones keep working fine and completing. Then My code moves on after thinking all the Processes are complete after the joins (I demonstrate this with a print) however I know for a fact that one of the processes did not complete, it did not error out and for some strange reason it passed the join()?

The only thing I can think of is that the Process runs out of memory but I would feel it would error out or throw an exception if this happened. Actually it has happened to me before using the same code and I saw the exception in my logs and the code was able to handle and see that the Process failed. But this, no error or anything is strange.

Can anyone shed some light?

Using Python3.4


问:
PHP Arrays. Get value from array with arrays
I have array in PHP:

```<code>Array
(
  [1] => Array
    (
        [DeviceName] => Device1
        [DeviceId] => 0x0000001530A1B380
        [state] => 0
        ...
         )
  [2] => Array
    (
        [DeviceName] => Device2
        [DeviceId] => 0x0000001530A10C80
        [state] => 1
        ...
    )
  [3] => Array
    (
        [DeviceName] => Device3
        [DeviceId] => 0x0000001531471600
        [state] => 0
        ...
    )
  ...
)
</code>```

How I can get values of state and DeviceId keys only from the array where DeviceName = Device2?

I have tried this, but it returns deviceID from another array:

```<code>foreach ($values as $B) {
    $B = preg_replace('~[\r\n]+~', '', $B);
    if ($B['DeviceName'] == $Device) {
        print "Device ID: ".$B['DeviceId']."\n";
    }
}
</code>```

答:
There are a few ways to do this. I'd probably use a function to return an array of search results. If you expect to find multiple instance of Device2, you will need to loop through the array and look for matching results.

```<code>function findDevice2(array $devices) : array
{
    $results = [];
    foreach ($devices as $device) {
        if ($device['DeviceName'] == 'Device2') {
            $format = [
                'DeviceId' => $device['DeviceId'],
                'state' => $device['state']
            ];
            array_push($results, $format);
        }
    }
    return $results;
}

$foundSet = findDevice2($array);

var_dump($foundSet);
</code>```

This function accepts the incoming array, loops through each record looking for the DeviceName to be Device2. Once found, it pushes the DeviceId and State into a results array to be returned. This way you end up with an array with only the results you desire.

```<code>array(1) {
  [0] =>
  array(2) {
    'DeviceId' =>
    string(18) "0x0000001531471600"
    'state' =>
    int(0)
  }
}
</code>```

If you aren't using PHP 7.0+, just remove the type declarations from the function.

Body:
I have array in PHP:

Array
(
  [1] => Array
    (
        [DeviceName] => Device1
        [DeviceId] => 0x0000001530A1B380
        [state] => 0
        ...
         )
  [2] => Array
    (
        [DeviceName] => Device2
        [DeviceId] => 0x0000001530A10C80
        [state] => 1
        ...
    )
  [3] => Array
    (
        [DeviceName] => Device3
        [DeviceId] => 0x0000001531471600
        [state] => 0
        ...
    )
  ...
)

How I can get values of state and DeviceId keys only from the array where DeviceName = Device2?

I have tried this, but it returns deviceID from another array:

foreach ($values as $B) {
    $B = preg_replace('~[\r\n]+~', '', $B);
    if ($B['DeviceName'] == $Device) {
        print "Device ID: ".$B['DeviceId']."\n";
    }
}

Body:
There are a few ways to do this. I'd probably use a function to return an array of search results. If you expect to find multiple instance of Device2, you will need to loop through the array and look for matching results.

function findDevice2(array $devices) : array
{
    $results = [];
    foreach ($devices as $device) {
        if ($device['DeviceName'] == 'Device2') {
            $format = [
                'DeviceId' => $device['DeviceId'],
                'state' => $device['state']
            ];
            array_push($results, $format);
        }
    }
    return $results;
}

$foundSet = findDevice2($array);

var_dump($foundSet);

This function accepts the incoming array, loops through each record looking for the DeviceName to be Device2. Once found, it pushes the DeviceId and State into a results array to be returned. This way you end up with an array with only the results you desire.

array(1) {
  [0] =>
  array(2) {
    'DeviceId' =>
    string(18) "0x0000001531471600"
    'state' =>
    int(0)
  }
}

If you aren't using PHP 7.0+, just remove the type declarations from the function.


问:
DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER error
My package consists of dynamic db connections. When i run my package it is throwing error like  DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.The AcquireConnection method call to the connection manager "conn" failed with error code 0xC0202009.

I tried setting delay validation property to true at package level.

I tried to change Package Protection Level property to EncryptSensitiveWithpassword. Still am facing with same error.

Am able to run the package manually.

How to get rid of this.

答: I had this error keep reappearing because I forgot my connection string was created on the fly using variables and an expression (see image).  Once I edited the connection string there then this error went away.


问:
Ionic 3/Angular 2 - Renderer2.setValue() doesn't update the value of my input field
I'm trying to update the value of an input that isn't bound to a <form> in my component, and my research has lead me to use the Renderer2 service that Angular provides.

So I have my input that looks like this:

```<code><input type="text" #zipEl placeholder="Enter zip">
<button type="button" (click)="getLocation()">
   <span>Use current location</span>
</button>
</code>```

And in my component, I'm trying to just set the value simply like this:

```<code>@ViewChild('zipEl') zipEl:ElementRef;

constructor(private renderer: Renderer2) {

}

getLocation() {
    this.renderer.setValue(this.zipEl, '94085');
}
</code>```

Though nothing is happening. When I click the button to run the function, the input box never gets its value updated with 94085. Does anyone know what I'm doing wrong here?

Thanks in advance!

答:
Using Angular v4.0.2, I ended up using the .setAttribute() function shown here:

```<code>getLocation() {
    this.renderer.setAttribute(this.zipEl, 'value', '94085');
}
</code>```

Body:
I'm trying to update the value of an input that isn't bound to a <form> in my component, and my research has lead me to use the Renderer2 service that Angular provides.

So I have my input that looks like this:

<input type="text" #zipEl placeholder="Enter zip">
<button type="button" (click)="getLocation()">
   Use current location
</button>

And in my component, I'm trying to just set the value simply like this:

@ViewChild('zipEl') zipEl:ElementRef;

constructor(private renderer: Renderer2) {

}

getLocation() {
    this.renderer.setValue(this.zipEl, '94085');
}

Though nothing is happening. When I click the button to run the function, the input box never gets its value updated with 94085. Does anyone know what I'm doing wrong here?

Thanks in advance!

Body:
Using Angular v4.0.2, I ended up using the .setAttribute() function shown here:

getLocation() {
    this.renderer.setAttribute(this.zipEl, 'value', '94085');
}


问:
How to represent nested @Relation with Android Room?
Here is my POJO in kotlin:

```<code>data class Pass(var uuid: String,
                var activationRestrictions:List<ActivationRestriction>)

data class ActivationRestriction(var uuid: String,
                                 var activationRestrictionExceptions:List<ActivationRestrictionException>)

data class ActivationRestrictionException(var uuid: String)
</code>```

How can I represent this nested relation with Room? Here is one of the solution, but it does not contain a nested relation. I am specifically looking for solving a nested relationship with Room.

答:
You can use @Relation annotation for POJO classes.

A convenience annotation which can be used in a Pojo to automatically
  fetch relation entities. When the Pojo is returned from a query, all
  of its relations are also fetched by Room.

Here is the documentation.

Also, this answer has more details: Android Persistence room: "Cannot figure out how to read this field from a cursor"

Body:
Here is my POJO in kotlin:

data class Pass(var uuid: String,
                var activationRestrictions:List<ActivationRestriction>)

data class ActivationRestriction(var uuid: String,
                                 var activationRestrictionExceptions:List<ActivationRestrictionException>)

data class ActivationRestrictionException(var uuid: String)

How can I represent this nested relation with Room? Here is one of the solution, but it does not contain a nested relation. I am specifically looking for solving a nested relationship with Room.


问:
How can I place color style and centered on my Multi-column headers?
If you could give me an example of it I would appreciate it!

enter image description here

Thanks in advance!

答:
You should use headerAttributes

Example:

```<code>columns:[{
            headerAttributes: {
              style: "text-align: center; background-color: red;"
            },
            title: "Header",
            columns: [{
                field: "FirstName",
                title: "First Name",
                width: "120px"
                },{
                field: "LastName",
                title: "Last Name",
                width: "120px"
                },{
                field: "Country",
                width: "120px"
                },{
                field: "City",
                width: "120px"
                },{
                field: "Title"
            }]
          }]
</code>```

Body:
You should use headerAttributes

Example:

columns:[{
            headerAttributes: {
              style: "text-align: center; background-color: red;"
            },
            title: "Header",
            columns: [{
                field: "FirstName",
                title: "First Name",
                width: "120px"
                },{
                field: "LastName",
                title: "Last Name",
                width: "120px"
                },{
                field: "Country",
                width: "120px"
                },{
                field: "City",
                width: "120px"
                },{
                field: "Title"
            }]
          }]


问:
Get the longest text in HTML document using Jquery or javascript
HTML:

```<code><div id="customdiv">
<p>AAAAAA AAAAA AAAAA AAAAA AAAAA AAAA</p>
<p>AAAAAA</p>
<p>AAAAAA</p>
</div>
</code>```

I need the output like this:

Largest value is:AAAAAA AAAAA AAAAA AAAAA AAAAA AAAA
Length:37

答:
Here is one way you could attempt to do it:

```<code>var longest = "";

$('p').each(function() {

  if ($(this).text().length > longest.length) {

    longest = $(this).text();

  }

});

console.log(longest);
</code>```

Here is a JSFiddle showing how it works: https://jsfiddle.net/2yne0qno/

Body:
HTML:

AAAAAA AAAAA AAAAA AAAAA AAAAA AAAA

AAAAAA

AAAAAA

I need the output like this:

Largest value is:AAAAAA AAAAA AAAAA AAAAA AAAAA AAAA
Length:37

Body:
Here is one way you could attempt to do it:

var longest = "";

$('p').each(function() {

  if ($(this).text().length > longest.length) {

    longest = $(this).text();

  }

});

console.log(longest);

Here is a JSFiddle showing how it works: https://jsfiddle.net/2yne0qno/


问:
TypeError: can't subtract offset-naive and offset-aware datetimes
So I am trying to subtract to datetime object. I got one from using dateutil.parser and the other was from datetime.now(). I keep getting a

TypeError: can't subtract offset-naive and offset-aware datetimes

I checked for solutions but they dont seem to work. Here is the code:

```<code>import json
from dateutil import parser
from datetime import *

with open(".log") as dataFile:
   dataFile.seek(0)
   data = []
   line=dataFile.readline()
   data=json.loads(line)
   data=ast.literal_eval(json.dumps(data))
   last=parser.parse(data["TIME"])
   print datetime.now()-last
</code>```

Here is the line of data it is reading:

```<code>{"TIME": "2017-06-29T15:17:27.663Z"}
</code>```

答:
Fixed it by changing the print to </p>

```<code>print datetime.utcnow().replace(tzinfo=pytz.UTC)-last
</code>```

Body:
So I am trying to subtract to datetime object. I got one from using dateutil.parser and the other was from datetime.now(). I keep getting a

TypeError: can't subtract offset-naive and offset-aware datetimes

I checked for solutions but they dont seem to work. Here is the code:

import json
from dateutil import parser
from datetime import *

with open(".log") as dataFile:
   dataFile.seek(0)
   data = []
   line=dataFile.readline()
   data=json.loads(line)
   data=ast.literal_eval(json.dumps(data))
   last=parser.parse(data["TIME"])
   print datetime.now()-last

Here is the line of data it is reading:

{"TIME": "2017-06-29T15:17:27.663Z"}

Body:
Fixed it by changing the print to

print datetime.utcnow().replace(tzinfo=pytz.UTC)-last


问:
"Outlook blocked access to the following potentially unsafe attachments"
Recently, we have some users which suddenly got this massege:
"Outlook blocked access to the following potentially unsafe attachments"
(outlook 2010 plus)

I had tried all of this: https://support.microsoft.com/en-us/help/829982/outlook-blocked-access-to-the-following-potentially-unsafe-attachment
but nothing had changed...

答:
The update blocks access to attachments with long filenames and/or file names with consecutive periods

Remove this update to fix :-
(might want to decline these updates in WSUS to prevent re-installation)

Outlook 2007: KB3191898
Outlook 2010: KB3203467
Outlook 2013: KB3191938
Outlook 2016: KB3191932

Replaced with :-

Outlook 2010  KB4011042
Outlook 2013  KB3191849
Outlook 2016  Fixed in build 1706 - run Office update (note not fixed in Deferred channel)
No fix for Outlook 2007

ContentLicense: CC BY-SA 4.0


问:
How to use the Search Method in java mail api
I am using the javamail api to make a Search option which Searches the Emails in the Gmail Folder on the Basis of a Keyword present in the Subject of the Messages
Here is the Code that i am Using

```<code>public class EGMail7 {
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    final String m10 = "abc@gmail.com";
    final String n10 = "12345";
    string host = "smtp.gmail.com";
    try
    {
    Properties pro1 = new Properties();
    pro1.put("mail.smtp.host", "smtp.gmail.com");
    pro1.put("mail.smtp.socketFactory.port", "465");
    pro1.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    pro1.put("mail.smtp.auth", "true");
    pro1.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(pro1,
        new javax.mail.Authenticator()
{
    protected PasswordAuthentication getPasswordAuthentication()
{
        return new PasswordAuthentication(m10,n10);
        }
    });
    Store store = session.getStore("imaps");
    store.connect(host, m10, n10);
    Folder folderbox = store.getFolder("INBOX");
    folderbox.open(Folder.READ_ONLY);
    SearchTerm search = new SearchTerm(){

        @Override
        public boolean match(Message message) {
            try
            {
                if(message.getSubject().contains([Keyword]))
                {
                    return true;
                }
            }
            catch(Exception e)
            {
                System.err.println(e.getMessage());
            }
            return false;
        }

    };

    Message[] found = folderbox.search(search);

    int length = found.length;
    for(int i = 0;i<found.length;i++)
    {
        Message mess1 = found[i];
        System.out.println("->Message Number > "+i);
        System.out.println("->Message Subject >"+mess1.getSubject());
    }
    folderbox.close(true);
    store.close();
}
    catch(Exception e)
    {
        System.err.println(e.getMessage());
    }
   }
  }
</code>```

I am using the Eclipse IDE and the problem i am facing is that whatever keyword I pass in the SearchTerm Method I always end up getting null Exception and an Message[] Found Array . I used Stack Trace to find out the Problem of this NullPointer Exception and it is at the line

```<code>Message[] found = folderbox.search(search);
</code>```

I cannot Seem to understand what is the Problem Here ?

Regards,
Thank you

PS - and if someone could also please post the corrected code it would be great
Thanks

Also When i Am Just Adding the Keyword Directly in the SearchTerm it give an Error like

```<code>SearchTerm searchCon = new SearchTerm([Keyword]);
</code>```

There are 2 Errors
1.Cannot Instantiate the SearchTerm
2.The Serializable class does not Declare a static final Serial Verison UID field of Type Long

So I Cannot Understand what is the Mistake here

答:
Your code is full of these common JavaMail mistakes, please correct them.

There's no need to create your own custom SearchTerm, just use SubjectTerm:

```<code>SearchTerm search = new SubjectTerm(keyword);
</code>```

Body:
I am using the javamail api to make a Search option which Searches the Emails in the Gmail Folder on the Basis of a Keyword present in the Subject of the Messages
Here is the Code that i am Using

public class EGMail7 {
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    final String m10 = "abc@gmail.com";
    final String n10 = "12345";
    string host = "smtp.gmail.com";
    try
    {
    Properties pro1 = new Properties();
    pro1.put("mail.smtp.host", "smtp.gmail.com");
    pro1.put("mail.smtp.socketFactory.port", "465");
    pro1.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    pro1.put("mail.smtp.auth", "true");
    pro1.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(pro1,
        new javax.mail.Authenticator()
{
    protected PasswordAuthentication getPasswordAuthentication()
{
        return new PasswordAuthentication(m10,n10);
        }
    });
    Store store = session.getStore("imaps");
    store.connect(host, m10, n10);
    Folder folderbox = store.getFolder("INBOX");
    folderbox.open(Folder.READ_ONLY);
    SearchTerm search = new SearchTerm(){

        @Override
        public boolean match(Message message) {
            try
            {
                if(message.getSubject().contains([Keyword]))
                {
                    return true;
                }
            }
            catch(Exception e)
            {
                System.err.println(e.getMessage());
            }
            return false;
        }

    };

    Message[] found = folderbox.search(search);

    int length = found.length;
    for(int i = 0;i<found.length;i++)
    {
        Message mess1 = found[i];
        System.out.println("->Message Number > "+i);
        System.out.println("->Message Subject >"+mess1.getSubject());
    }
    folderbox.close(true);
    store.close();
}
    catch(Exception e)
    {
        System.err.println(e.getMessage());
    }
   }
  }

I am using the Eclipse IDE and the problem i am facing is that whatever keyword I pass in the SearchTerm Method I always end up getting null Exception and an Message[] Found Array . I used Stack Trace to find out the Problem of this NullPointer Exception and it is at the line

Message[] found = folderbox.search(search);

I cannot Seem to understand what is the Problem Here ?

Regards,
Thank you

PS - and if someone could also please post the corrected code it would be great
Thanks

Also When i Am Just Adding the Keyword Directly in the SearchTerm it give an Error like

SearchTerm searchCon = new SearchTerm([Keyword]);

There are 2 Errors
1.Cannot Instantiate the SearchTerm
2.The Serializable class does not Declare a static final Serial Verison UID field of Type Long

So I Cannot Understand what is the Mistake here

Body:
Your code is full of these common JavaMail mistakes, please correct them.

There's no need to create your own custom SearchTerm, just use SubjectTerm:

SearchTerm search = new SubjectTerm(keyword);


问:
How to configure S3 bucket to allow POSTs to API Gateway without 405 error
I have a static website hosted on AWS S3. The website can be accessed from either:
https://s3.amazonaws.com/example-bucket-name-to-avoid-spam/index.html
Or
http://example-bucket-name-to-avoid-spam.s3-website-us-east-1.amazonaws.com/

When a user completes the form and the captcha on the page and presses submit the following JavaScript is triggered:

```
</div>
</div>
</p>

<p>This successfully sends a POST through to the AWS API Gateway which processes the request correctly and sends a text with Twilio to the desired phone number.</p>

<p>I've also confirmed in Postman that the API Gateway/Lambda response itself is correctly coming back:</p>

```{
    "statusCode": 200,
    "headers": {
        "Access-Control-Allow-Origin": "*"
    },
    "body": "{\"message\":\"Text message successfully sent!\",\"data\":{\"dateCreated\":\"2017-07-06T16:49:00.000Z\",\"dateUpdated\":\"2017-07-06T16:49:00.000Z\",\"from\":\"+13334445566\",\"body\":\"Sent from your Twilio trial account - test 5 with postman - looking at Lambda logs\"}}"
}
```

<p>The issue happens after that POST is (presumably) sent to API Gateway. The static site redirects to an error page with this message when on the non-https url above:</p>

```405 Method Not Allowed

Code: MethodNotAllowed
Message: The specified method is not allowed against this resource.
Method: POST
ResourceType: OBJECT
RequestId: IDSTRING123
HostId: Longhostidthing1237ygausdhasdgylh231ctidasd=
```

<p>And this for the https url:</p>

```<Error>
MethodNotAllowed
<Message>
The specified method is not allowed against this resource.
</Message>
<Method>POST</Method>
<ResourceType>OBJECT</ResourceType>
<RequestId>IDSTRING123</RequestId>
<HostId>
Longhostidthing1237ygausdhasdgylh231ctidasd=
</HostId>
</Error>
```

<p>Initially I thought this was a CORS issue, but I've checked and rechecked several times the CORS policy on the bucket is very permissive:</p>

```<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <MaxAgeSeconds>0</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>0</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
```

I've also fiddled around with this a few times to confirm I was being as permissive as possible.

Finally, I've tried this incognito in Chrome, with cookies and all browsing data cleared in a separate profile, and all of the above with a plugin that disables CORS from the browser-side. None of these attempts appear to resolve my issue.

Any ideas?

答:
Mark B was correct.

"It sounds like you are posting something via JavaScript to API Gateway, but then also posting the same thing to S3? My guess is you need to simply prevent the default form post action from occurring since you are handling it via javascript."

Edit:
The easiest fix for this is to change this line:

```<code>document.getElementById('send-text').addEventListener('click', function () {
</code>```

to this:

```<code>document.getElementById('send-text').addEventListener('click', function (event) {
</code>```

And call event.preventDefault() on the subsequent line to prevent the default code from running and firing a post request.

Body:
I have a static website hosted on AWS S3. The website can be accessed from either:
https://s3.amazonaws.com/example-bucket-name-to-avoid-spam/index.html
Or
http://example-bucket-name-to-avoid-spam.s3-website-us-east-1.amazonaws.com/

When a user completes the form and the captcha on the page and presses submit the following JavaScript is triggered:

This successfully sends a POST through to the AWS API Gateway which processes the request correctly and sends a text with Twilio to the desired phone number.

I've also confirmed in Postman that the API Gateway/Lambda response itself is correctly coming back:

{
    "statusCode": 200,
    "headers": {
        "Access-Control-Allow-Origin": "*"
    },
    "body": "{\"message\":\"Text message successfully sent!\",\"data\":{\"dateCreated\":\"2017-07-06T16:49:00.000Z\",\"dateUpdated\":\"2017-07-06T16:49:00.000Z\",\"from\":\"+13334445566\",\"body\":\"Sent from your Twilio trial account - test 5 with postman - looking at Lambda logs\"}}"
}

The issue happens after that POST is (presumably) sent to API Gateway. The static site redirects to an error page with this message when on the non-https url above:

405 Method Not Allowed

Code: MethodNotAllowed
Message: The specified method is not allowed against this resource.
Method: POST
ResourceType: OBJECT
RequestId: IDSTRING123
HostId: Longhostidthing1237ygausdhasdgylh231ctidasd=

And this for the https url:

<Error>
MethodNotAllowed
<Message>
The specified method is not allowed against this resource.
</Message>
<Method>POST</Method>
<ResourceType>OBJECT</ResourceType>
<RequestId>IDSTRING123</RequestId>
<HostId>
Longhostidthing1237ygausdhasdgylh231ctidasd=
</HostId>
</Error>

Initially I thought this was a CORS issue, but I've checked and rechecked several times the CORS policy on the bucket is very permissive:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <MaxAgeSeconds>0</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>0</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

I've also fiddled around with this a few times to confirm I was being as permissive as possible.

Finally, I've tried this incognito in Chrome, with cookies and all browsing data cleared in a separate profile, and all of the above with a plugin that disables CORS from the browser-side. None of these attempts appear to resolve my issue.

Any ideas?

Body:
Mark B was correct.

"It sounds like you are posting something via JavaScript to API Gateway, but then also posting the same thing to S3? My guess is you need to simply prevent the default form post action from occurring since you are handling it via javascript."

Edit:
The easiest fix for this is to change this line:

document.getElementById('send-text').addEventListener('click', function () {

to this:

document.getElementById('send-text').addEventListener('click', function (event) {

And call event.preventDefault() on the subsequent line to prevent the default code from running and firing a post request.


问:
How to find and replace a string with PowerShell - issue with Eastern European characters
I'm writing a PowerShell script to find and replace xml tags containing Eastern European characters and change them to English.

My source file is encoded in UTF-8.

My code:

```<code>$content = [System.IO.File]::ReadAllText("file.xml").Replace("<Číslo_zboží>","<Code>")
[System.IO.File]::WriteAllText("file.xml", $content)
</code>```

While I can successfully find and replace tags with standard English characters, those containing Eastern European characters are ignored by PowerShell. Many thanks for your advice.

答:
The [System.IO.File] class's methods default to (BOM-less) UTF-8, so assuming that file.xml is UTF-8-encoded (whether with BOM or not), reading and writing that file should work as expected, but note that writing will result in no BOM.

I suspect the problem is that your source file, despite being UTF-8-encoded, lacks a BOM, which Windows PowerShell (unfortunately) requires in order to recognize UTF-8 encoding.

In the absence of a BOM, Windows PowerShell interprets your source file as "ANSI"-encoded, which is the single-byte, extended-ASCII encoding implied by your system's legacy system locale.
So even if your script's actual encoding is UTF-8, the absence of a BOM means that Windows PowerShell will misinterpret the non-ASCII characters in the script, so that string operations based on string literals defined in the script  will not work as expected.

To be safe, always create UTF-8-encoded PowerShell scripts with a BOM.

Note that the upcoming cross-platform PowerShell Core will likely switch to (BOM-less) UTF-8 as the default, but it will continue to recognize BOMs, so saving UTF-8 scripts with a BOM should be a future-proof approach.

Body:
I'm writing a PowerShell script to find and replace xml tags containing Eastern European characters and change them to English.

My source file is encoded in UTF-8.

My code:

$content = [System.IO.File]::ReadAllText("file.xml").Replace("<Číslo_zboží>","")
[System.IO.File]::WriteAllText("file.xml", $content)

While I can successfully find and replace tags with standard English characters, those containing Eastern European characters are ignored by PowerShell. Many thanks for your advice.


问:
How to move a directory out of ./virualenvs and into my project in PYTHONANYWHERE
Just for the record - I feel so stupid asking this question.

I can not move a directory out of;
home/username/django18/lib/python35/site-packages
into my Django project here;
home/username/my_project

I did a;

```<code>pip install django-allauth
</code>```

to install AllAuth for my project, which in turn dropped it in the above directory, not my project. To be neat and organised... I would like my AllAuth diretory to sit in the main directory of my project..

I have tried using the bash terminal, but can not get to that directory from it.

答:
You should not even try moving the installed package, because it (probably) won't work. Python virtualenvs are not really relocatable.

Just create a new virtual environment in your project directory and install all pip packages there:

```<code>cd my_project
virtualenv .env
. .env/bin/activate
pip install -r requirements.txt    # if you have a list of pip requirements
pip install django-allauth
</code>```

Body:
Just for the record - I feel so stupid asking this question.

I can not move a directory out of;
home/username/django18/lib/python35/site-packages
into my Django project here;
home/username/my_project

I did a;

pip install django-allauth

to install AllAuth for my project, which in turn dropped it in the above directory, not my project. To be neat and organised... I would like my AllAuth diretory to sit in the main directory of my project..

I have tried using the bash terminal, but can not get to that directory from it.

Body:
You should not even try moving the installed package, because it (probably) won't work. Python virtualenvs are not really relocatable.

Just create a new virtual environment in your project directory and install all pip packages there:

cd my_project
virtualenv .env
. .env/bin/activate
pip install -r requirements.txt    # if you have a list of pip requirements
pip install django-allauth


问:
How to check if Vuex state object is empty
I have an initial empty object in Vuex state that gets updated from an API.

```<code>const state = {
  someObject: {}
}
</code>```

How do I check if the object is empty in my template?

```<code><template>
  <div v-if="someObject">
    This should not display when someObject is empty.
  </div>
</template>
</code>```

What is best practice for checking if a state object is set/empty or not?

Should i set someObject: null/undefined/false initially, even if it expects to be updated with a new object?

Does it make sense to do a check in getters?

```<code>export const someObject = state => Object.getOwnPropertyNames(state.someObject).length == 0 ? state.someObject : false
</code>```

答:
You could use the lodash method: _.isEmpty({someObject});

Or if you wanted to do a getter:

```<code>computed:{
  objectLength(state){
    return Object.keys(state.someObject).length
  }
</code>```

Body:
I have an initial empty object in Vuex state that gets updated from an API.

const state = {
  someObject: {}
}

How do I check if the object is empty in my template?

<template>

    This should not display when someObject is empty.

</template>

What is best practice for checking if a state object is set/empty or not?

Should i set someObject: null/undefined/false initially, even if it expects to be updated with a new object?

Does it make sense to do a check in getters?

export const someObject = state => Object.getOwnPropertyNames(state.someObject).length == 0 ? state.someObject : false

Body:
You could use the lodash method: _.isEmpty({someObject});

Or if you wanted to do a getter:

computed:{
  objectLength(state){
    return Object.keys(state.someObject).length
  }


问:
How to use restore_attributes in a Rails controller with nested attributes?
Example:
a Person model accepts_nested_attributes_for a Pets model as in the example found here. Submitting a form_for(@person) with a nested fields_for :pets hits the update method in the PeoplesController. If there was an unsuccessful save i.e due to the pet's name failing a presence: true validation, how can one restore the changes made to the pet instance using ActiveModel::Dirty, therefore restoring the changes made
in the form? I want to do this so that the nested form inputs will retain the pet's values they had pre-save and not be blank.

Example:

```<code>def update
  @person = Person.find(params[:id])
  respond_to do |format|
    if @person.update_attributes(person_params)
      format.html { redirect_to persons_path }
    else
      # @person.restore_attributes works for restoring the @person
      # input values. I would like to do something like
      # @person.pet.restore_attributes
      format.html { render :edit }
    end
  end
end
</code>```

答:
I figured out a way to get this done. When using a nested fields_for, you have access to the object within that form, therefore you can call restore_attributes, etc. on it.

A rough example :

```<code><%= form_for(@person) do |f| %>
  <%= f.fields_for :pets do |ff| %>
    <%
    if ff.object.errors
      ff.object.restore_attributes
    end
    %>
  <% end %>
<% end %>
</code>```

Body:
Example:
a Person model accepts_nested_attributes_for a Pets model as in the example found here. Submitting a form_for(@person) with a nested fields_for :pets hits the update method in the PeoplesController. If there was an unsuccessful save i.e due to the pet's name failing a presence: true validation, how can one restore the changes made to the pet instance using ActiveModel::Dirty, therefore restoring the changes made
in the form? I want to do this so that the nested form inputs will retain the pet's values they had pre-save and not be blank.

Example:

def update
  @person = Person.find(params[:id])
  respond_to do |format|
    if @person.update_attributes(person_params)
      format.html { redirect_to persons_path }
    else
      # @person.restore_attributes works for restoring the @person
      # input values. I would like to do something like
      # @person.pet.restore_attributes
      format.html { render :edit }
    end
  end
end

Body:
I figured out a way to get this done. When using a nested fields_for, you have access to the object within that form, therefore you can call restore_attributes, etc. on it.

A rough example :

<%= form_for(@person) do |f| %>
  <%= f.fields_for :pets do |ff| %>
    <%
    if ff.object.errors
      ff.object.restore_attributes
    end
    %>
  <% end %>
<% end %>


问:
PHP $_GET request inside class construct, not working
This code doesn't work.  The $_GET variables are set, but this code always returns $model, $manufacturer, etc, as being empty.  What am I doing wrong?

```<code><?php
class Tiles extends Phones {
    private $model;
    private $manufacturer;
    private $all;

    function __construct() {
        $this->model = $_GET['model'] ?? null;
        $this->manufacturer = $_GET['manufacturer'] ?? null;
        $this->all = $_GET;
    }

    function showEntry() {
        echo $model;
    }
}
?>
</code>```

This is my first time using the __construct method, so if i'm missing something obvious, please, point me in the right direction.

Edit: I should add, if I simply use $_GET['model'], etc in my showEntry() method, it works.

答: You should echo $this->model; instead of just echo $model; inside of showEntry().

Body:
This code doesn't work.  The $_GET variables are set, but this code always returns $model, $manufacturer, etc, as being empty.  What am I doing wrong?

<?php
class Tiles extends Phones {
    private $model;
    private $manufacturer;
    private $all;

    function __construct() {
        $this->model = $_GET['model'] ?? null;
        $this->manufacturer = $_GET['manufacturer'] ?? null;
        $this->all = $_GET;
    }

    function showEntry() {
        echo $model;
    }
}
?>

This is my first time using the __construct method, so if i'm missing something obvious, please, point me in the right direction.

Edit: I should add, if I simply use $_GET['model'], etc in my showEntry() method, it works.


问:
fetch all elements dom jquery
I have 2 classes and I want to fetch them all in the DOM of a page to compare their content text with jQuery. I believe that in JS it is something like:

function myFonction() {
  var item = document.getElementsByClassName("title")[0];
  if (item) {
    for (var i = 0; i < document.getElementsByClassName("title2").length; i++) {
      var content = document.getElementsByClassName("title2")[i].innerHTML.trim();
      if (content == item.innerHTML.trim()) {
        console.log("OK");
      }
    }
  }
}
myFonction();```

答: use .getElementsByClassName for each class. Iterate over the .get results and just do if groupA[i] == groupB[i] then do whatever. If you too lazy let me frikin do it for you for a "point". lol

Title: fetch all elements dom jquery


问:
What is this code asking to do?
```<code>case class TempData(year:Int,month:Int,Prec:Double,Maxtemp:Int,Meantemp:Int,Mintemp:Int)

def parseLine(line:String):TempData = {
  val p = line.split(",")
  TempData(p(1).toInt,p(4).toInt,p(5).toDouble,p(6).toInt,p(7).toInt,p(8).toInt)
}
</code>```

答:
It simply takes a line(which is CSV) splits it by , and creates TempData instance from those values.

see example,

```<code>scala> case class TempData(year:Int,month:Int,Prec:Double,Maxtemp:Int,Meantemp:Int,Mintemp:Int)
defined class TempData

scala> val p = "whatever,2017,whatever,whatever,10,5.0,1000,2000,3000".split(",")
p: Array[String] = Array(whatever, 2017, whatever, whatever, 10, 5.0, 1000, 2000, 3000)

scala> TempData(p(1).toInt,p(4).toInt,p(5).toDouble,p(6).toInt,p(7).toInt,p(8).toInt)
res1: TempData = TempData(2017,10,5.0,1000,2000,3000)
</code>```

which is equivalent to

```<code>scala> TempData(year=p(1).toInt, month=p(4).toInt, Prec=p(5).toDouble, Maxtemp=p(6).toInt, Meantemp=p(7).toInt, Mintemp=p(8).toInt)
res2: TempData = TempData(2017,10,5.0,1000,2000,3000)
</code>```

read about String#split and also case classes in scala.

Title: What is this code asking to do?

Body:
It simply takes a line(which is CSV) splits it by , and creates TempData instance from those values.

see example,

scala> case class TempData(year:Int,month:Int,Prec:Double,Maxtemp:Int,Meantemp:Int,Mintemp:Int)
defined class TempData

scala> val p = "whatever,2017,whatever,whatever,10,5.0,1000,2000,3000".split(",")
p: Array[String] = Array(whatever, 2017, whatever, whatever, 10, 5.0, 1000, 2000, 3000)

scala> TempData(p(1).toInt,p(4).toInt,p(5).toDouble,p(6).toInt,p(7).toInt,p(8).toInt)
res1: TempData = TempData(2017,10,5.0,1000,2000,3000)

which is equivalent to

scala> TempData(year=p(1).toInt, month=p(4).toInt, Prec=p(5).toDouble, Maxtemp=p(6).toInt, Meantemp=p(7).toInt, Mintemp=p(8).toInt)
res2: TempData = TempData(2017,10,5.0,1000,2000,3000)

read about String#split and also case classes in scala.


问:
Find the registry key that has a value of a certain name in PowerShell
I know I have a registry entry under HKEY_LOCAL_MACHINE/SOFTWARE/CLASSES that has a certain value.  However, I don't know the Key.  (This is a GUID that I am trying to look up.)  The following code works to get to this value, but it's slow and seems inelegant.  Is there a better way of doing it?</p>

```<code>$key = Get-ChildItem -Path "HKLM:\SOFTWARE\Classes" -Recurse | Get-ItemProperty -Name "FooBar" -ErrorAction @{}
$codeGuid = $key.PsChildName
</code>```

答:
The recurse is what kills you. To lighten the burden of recursively searching Classes, you can manually specify a Depth. If you KNOW how many steps your key is into the Registry Hierarchy, you can cut the speed significantly. For example:

```<code>$Timer = New-Object System.Diagnostics.Stopwatch

######NORMAL#######
#Completes in 70.2157527 Seconds on my system
$Timer.Start()
    Get-ChildItem -Path "HKLM:\Software\Classes" -Recurse | Get-ItemProperty -Name "AlwaysShowExt" -ErrorAction SilentlyContinue | Out-Null
$Timer.Stop()
$Timer.Elapsed
$Timer.Reset()

######DEPTH 1######
#Completes in 12.7461096 Seconds on my system
$Timer.Start()
    Get-ChildItem -Path "HKLM:\Software\Classes" -Recurse -Depth 1 | Get-ItemProperty -Name "AlwaysShowExt" -ErrorAction SilentlyContinue | Out-Null
$Timer.Stop()
$Timer.Elapsed
$Timer.Reset()

######DEPTH 2######
#Completes in 33.9162044 Seconds on my system
$Timer.Start()
    Get-ChildItem -Path "HKLM:\Software\Classes" -Recurse -Depth 2 | Get-ItemProperty -Name "AlwaysShowExt" -ErrorAction SilentlyContinue | Out-Null
$Timer.Stop()
$Timer.Elapsed
$Timer.Reset()
</code>```

Your best results are going to be with a Depth of 1, but Depths of 2 or 3 will still be faster than not specifying.

Body:
I know I have a registry entry under HKEY_LOCAL_MACHINE/SOFTWARE/CLASSES that has a certain value.  However, I don't know the Key.  (This is a GUID that I am trying to look up.)  The following code works to get to this value, but it's slow and seems inelegant.  Is there a better way of doing it?

$key = Get-ChildItem -Path "HKLM:\SOFTWARE\Classes" -Recurse | Get-ItemProperty -Name "FooBar" -ErrorAction @{}
$codeGuid = $key.PsChildName

Body:
The recurse is what kills you. To lighten the burden of recursively searching Classes, you can manually specify a Depth. If you KNOW how many steps your key is into the Registry Hierarchy, you can cut the speed significantly. For example:

$Timer = New-Object System.Diagnostics.Stopwatch

######NORMAL#######
#Completes in 70.2157527 Seconds on my system
$Timer.Start()
    Get-ChildItem -Path "HKLM:\Software\Classes" -Recurse | Get-ItemProperty -Name "AlwaysShowExt" -ErrorAction SilentlyContinue | Out-Null
$Timer.Stop()
$Timer.Elapsed
$Timer.Reset()

######DEPTH 1######
#Completes in 12.7461096 Seconds on my system
$Timer.Start()
    Get-ChildItem -Path "HKLM:\Software\Classes" -Recurse -Depth 1 | Get-ItemProperty -Name "AlwaysShowExt" -ErrorAction SilentlyContinue | Out-Null
$Timer.Stop()
$Timer.Elapsed
$Timer.Reset()

######DEPTH 2######
#Completes in 33.9162044 Seconds on my system
$Timer.Start()
    Get-ChildItem -Path "HKLM:\Software\Classes" -Recurse -Depth 2 | Get-ItemProperty -Name "AlwaysShowExt" -ErrorAction SilentlyContinue | Out-Null
$Timer.Stop()
$Timer.Elapsed
$Timer.Reset()

Your best results are going to be with a Depth of 1, but Depths of 2 or 3 will still be faster than not specifying.


问:
Deleting element in JavaScript or JQuery
I have two view pages. On both pages I have a list of items with a picture of a star next to it. On the 1st page, I can click the star and it will turn blue or gray. On the 2nd page, if the star is blue and I click on it I want to delete the parent div associated it. It does delete it when I reload the whole page but doesn't delete it immediately. How can I delete it from the page immediately and without clicking the reload button?

This is in my result.html.erb where I want to delete the parent div. To be clear, when I click on the star associated with the diamond div, I want to delete that whole div and leave the pearl div alone.

```<code><div id="result">
  <div class="diamond">
    <a target="_blank" href="www.website.com">diamond</a>
    <img class="star-pic" src="/assets/star-blue.png" alt="star pic">
  </div>
  <div class="pearl">
    <a target="_blank" href="www.website.com">pearl</a>
    <img class="star-pic" src="/assets/star-blue.png" alt="star pic">
  </div>
</div>
</code>```

This is in my application.js

```<code>var favoriteGems = JSON.parse(localStorage.getItem("gems")) || []

function changeStar(){
  if($(this).attr("src") == "/assets/star-gray.png"){
    $(this).attr("src", "/assets/star-blue.png")
    favoriteGems.push($(this).closest("div").first().text().replace(/\s+/g, ''))
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
  }
  else if ($(this).attr("src") == "/assets/star-blue.png"){
    $(this).attr("src", "/assets/star-gray.png")
    favoriteGems = favoriteGems.filter(item => item !== $(this).closest("div").first().text().replace(/\s+/g, ''))
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
    $("#result").remove("."+item)
    $("#result").show()
  }
}

$(".star-pic").on("click", changeStar)
</code>```

I've tried

```<code>$("#result").remove("."+item)
location.reload()
</code>```

and that doesn't work either.

Any guidance would be greatly appreciated.

答:
item in $("#result").remove("."+item) may not be the value you want. You can add var item = $(this).closest("div").first().text().replace(/\s+/g, '') before this line.

You can refactor changeStarfurther like this:

```<code>function changeStar() {
  var targetItem = $(this).closest("div").first().text().replace(/\s+/g, '');
  var favoriteGems = JSON.parse(localStorage.getItem("gems")) || [];
  if($(this).attr("src") === "/assets/star-gray.png"){
    $(this).attr("src", "/assets/star-blue.png")
    favoriteGems.push(targetItem)
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
  }
  else if ($(this).attr("src") === "/assets/star-blue.png"){
    $(this).attr("src", "/assets/star-gray.png")
    favoriteGems = favoriteGems.filter(item => item !== targetItem)
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
    $("#result").remove("." + targetItem)
    $("#result").show()
  }
}
</code>```

Body:
I have two view pages. On both pages I have a list of items with a picture of a star next to it. On the 1st page, I can click the star and it will turn blue or gray. On the 2nd page, if the star is blue and I click on it I want to delete the parent div associated it. It does delete it when I reload the whole page but doesn't delete it immediately. How can I delete it from the page immediately and without clicking the reload button?

This is in my result.html.erb where I want to delete the parent div. To be clear, when I click on the star associated with the diamond div, I want to delete that whole div and leave the pearl div alone.

    diamond

    pearl

This is in my application.js

var favoriteGems = JSON.parse(localStorage.getItem("gems")) || []

function changeStar(){
  if($(this).attr("src") == "/assets/star-gray.png"){
    $(this).attr("src", "/assets/star-blue.png")
    favoriteGems.push($(this).closest("div").first().text().replace(/\s+/g, ''))
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
  }
  else if ($(this).attr("src") == "/assets/star-blue.png"){
    $(this).attr("src", "/assets/star-gray.png")
    favoriteGems = favoriteGems.filter(item => item !== $(this).closest("div").first().text().replace(/\s+/g, ''))
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
    $("#result").remove("."+item)
    $("#result").show()
  }
}

$(".star-pic").on("click", changeStar)

I've tried

$("#result").remove("."+item)
location.reload()

and that doesn't work either.

Any guidance would be greatly appreciated.

Body:
item in $("#result").remove("."+item) may not be the value you want. You can add var item = $(this).closest("div").first().text().replace(/\s+/g, '') before this line.

You can refactor changeStarfurther like this:

function changeStar() {
  var targetItem = $(this).closest("div").first().text().replace(/\s+/g, '');
  var favoriteGems = JSON.parse(localStorage.getItem("gems")) || [];
  if($(this).attr("src") === "/assets/star-gray.png"){
    $(this).attr("src", "/assets/star-blue.png")
    favoriteGems.push(targetItem)
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
  }
  else if ($(this).attr("src") === "/assets/star-blue.png"){
    $(this).attr("src", "/assets/star-gray.png")
    favoriteGems = favoriteGems.filter(item => item !== targetItem)
    localStorage.setItem("gems", JSON.stringify(favoriteGems))
    $("#result").remove("." + targetItem)
    $("#result").show()
  }
}


问:
How to shorten many if statements
I'm fairly new to programming and not sure if there is any way to shorten this code. Basically, whatever value is entered for x determines the number of # after the '.' </p>

```<code>    String x = mSharedPreferences.getString("title", "3");
    if (x.equals("1")){
        df = new DecimalFormat("#.#");
    }
    else if(x.equals("2")){
        df = new DecimalFormat("#.##");
    }
    else if(x.equals("3")){
        df = new DecimalFormat("#.###");
    }
    else if(x.equals("4")){
        df = new DecimalFormat("#.####");
    }
</code>```

答:
A switch case will not provide the exact same functionality as a if,else if, else actually. It provides subtly different functionality.

The only way I have seen this shrank down is using an array, then doing an include check if the item being checked is in the array of possible answers.

Psuedo code is:

if ["1", "2", "3", "4"].include?(x)
end

Title: How to shorten many if statements

Body:
I'm fairly new to programming and not sure if there is any way to shorten this code. Basically, whatever value is entered for x determines the number of # after the '.'

    String x = mSharedPreferences.getString("title", "3");
    if (x.equals("1")){
        df = new DecimalFormat("#.#");
    }
    else if(x.equals("2")){
        df = new DecimalFormat("#.##");
    }
    else if(x.equals("3")){
        df = new DecimalFormat("#.###");
    }
    else if(x.equals("4")){
        df = new DecimalFormat("#.####");
    }


问:
using the FMU in fmu_sdk
I have a small code in C that I want to use to call the IMF functions of fmu_sdk in order to be able to export my model in FMU.

If you could tell me how the functions I need to use, here is my program:

best regards
Mary

答:
```<code>  #include <stdio.h>
  #include <stdlib.h>

 #define vrai 1
 #define faux 0
 typedef enum BOOLEAN {false, true} bool;
 bool function_ET(bool e1,bool e2);
 int main(){
   bool e1;
   bool e2;
   bool s;

printf("entrez les valeur de e1 et e2:");
scanf("%d%d",&e1 ,&e2);
   s = function_ET(e1,e2);
printf("s = %d",s);
}
bool function_ET(bool e1,bool e2){
   return(e1 & e2);
}
</code>```

Title: using the FMU in fmu_sdk


问:
Formatting a string with NSNumberFormatter
I have this app of mine where one text field must behave like a calculator display would. The number this text field shows is calculated by a function. If the number is, for example, "3.21" it should be displayed like this, with 2 decimal places. If the number has more decimal places, it should be displayed with the number of decimal places it has.

The textfield allows displaying 10 digits.

If the number is bigger than 9999999999 (10 nines) it should be displayed in scientific notation, like "4.767 E20" or something like that.

I suppose I have to use NSNumberFormatter for that matter but I see that I will have a series of ifs and a complicate sequence of NSNumberFormatters to do the job, specially for the number of decimal places.

My question is: is this the way to go or is there some kind of NSNumberFormatter that can do this automatically?

答:
You don't need to use a number formatter at all. You can use the %g format string, from either Swift or Objective-C. The Swift code would look like this:

```<code>import UIKit
var value = 0.0
for digits in 1...12 {
  value = value * 10 + 9
  print(String(format:"%.10g", value))
}
</code>```

That yields the result:

```<code>9
99
999
9999
99999
999999
9999999
99999999
999999999
9999999999
1e+11
1e+12
</code>```

In Objective-C, you'd use NSString's stringWithFormat method, and also use the format string @"%.10g"

My Objective-C is getting rusty, but the code would look something like this:

```<code>double value = 0;
for (int x = 0; x < 12; x++) {
  value = value * 10 + 9;
  NSString *result = [NSString stringWithFormat: @"%.10g", value];
  NSLog(@"value = %@", result);
}
</code>```

Body:
You don't need to use a number formatter at all. You can use the %g format string, from either Swift or Objective-C. The Swift code would look like this:

import UIKit
var value = 0.0
for digits in 1...12 {
  value = value * 10 + 9
  print(String(format:"%.10g", value))
}

That yields the result:

9
99
999
9999
99999
999999
9999999
99999999
999999999
9999999999
1e+11
1e+12

In Objective-C, you'd use NSString's stringWithFormat method, and also use the format string @"%.10g"

My Objective-C is getting rusty, but the code would look something like this:

double value = 0;
for (int x = 0; x < 12; x++) {
  value = value * 10 + 9;
  NSString *result = [NSString stringWithFormat: @"%.10g", value];
  NSLog(@"value = %@", result);
}


问:
Making golang Gorilla CORS handler work
I have fairly simple setup here as described in the code below. But I am not able to get the CORS to work. I keep getting this error:

XMLHttpRequest cannot load http://localhost:3000/signup. Response to
      preflight request doesn't pass access control check: No 'Access-
      Control-Allow-Origin' header is present on the requested resource.
      Origin 'http://localhost:8000' is therefore not allowed access. The
      response had HTTP status code 403.

I am sure I am missing something simple here.

Here is the code I have:

```<code>package main

import (
    "log"
    "net/http"

    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
    "myApp/src/controllers"
)

func main() {
    ac := new(controllers.AccountController)

    router := mux.NewRouter()
    router.HandleFunc("/signup", ac.SignUp).Methods("POST")
    router.HandleFunc("/signin", ac.SignIn).Methods("POST")

    log.Fatal(http.ListenAndServe(":3000", handlers.CORS()(router)))
}
</code>```

答:
You can get more details here: Why doesn’t Postman get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when my JavaScript code does? about this issue.

Also try this handler: Go Cors Handler  which should solve your issue. I find this much cleaner and easy to resolve the issue.

```<code>package main

import (
    "log"
    "net/http"
    "github.com/rs/cors"
    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
    "myApp/src/controllers"
)

func main() {
    ac := new(controllers.AccountController)

    router := mux.NewRouter()
    router.HandleFunc("/signup", ac.SignUp).Methods("POST")
    router.HandleFunc("/signin", ac.SignIn).Methods("POST")

    c := cors.New(cors.Options{
        AllowedOrigins: []string{"http://localhost:8000"},
        AllowCredentials: true,
    })

    handler := c.Handler(router)
    log.Fatal(http.ListenAndServe(":3000", handler)
}
</code>```

Title: Making golang Gorilla CORS handler work

Body:
I have fairly simple setup here as described in the code below. But I am not able to get the CORS to work. I keep getting this error:

XMLHttpRequest cannot load http://localhost:3000/signup. Response to
      preflight request doesn't pass access control check: No 'Access-
      Control-Allow-Origin' header is present on the requested resource.
      Origin 'http://localhost:8000' is therefore not allowed access. The
      response had HTTP status code 403.

I am sure I am missing something simple here.

Here is the code I have:

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
    "myApp/src/controllers"
)

func main() {
    ac := new(controllers.AccountController)

    router := mux.NewRouter()
    router.HandleFunc("/signup", ac.SignUp).Methods("POST")
    router.HandleFunc("/signin", ac.SignIn).Methods("POST")

    log.Fatal(http.ListenAndServe(":3000", handlers.CORS()(router)))
}

Body:
You can get more details here: Why doesn’t Postman get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when my JavaScript code does? about this issue.

Also try this handler: Go Cors Handler  which should solve your issue. I find this much cleaner and easy to resolve the issue.

package main

import (
    "log"
    "net/http"
    "github.com/rs/cors"
    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
    "myApp/src/controllers"
)

func main() {
    ac := new(controllers.AccountController)

    router := mux.NewRouter()
    router.HandleFunc("/signup", ac.SignUp).Methods("POST")
    router.HandleFunc("/signin", ac.SignIn).Methods("POST")

    c := cors.New(cors.Options{
        AllowedOrigins: []string{"http://localhost:8000"},
        AllowCredentials: true,
    })

    handler := c.Handler(router)
    log.Fatal(http.ListenAndServe(":3000", handler)
}


问:
How to select a specific range from first row with each id MSSQL
I have created a table in html to display first rows of each id and allow user to select specific range they want to see, but not sure how I can write it in query.

```<code>With results as
 (
   i.*,
   ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY I.ID DESC) AS [RN]
   FROM HolidayList AS I
   INNER JOIN (
      SELECT ID, MIN(CreateDate) FROM HolidayList GROUP BY ID
   )
   AS j ON i.ID = j.ID AND i.CreateDate = j.CreateDate
 )
 SELECT * FROM results WHERE [RN] = 1;
</code>```

UPDATED

I have tried to inject two ROW_NUMBER(), but what I received is row 10 and row 25 and they are first rows of some specific id.

```<code> With results as
     (
       i.*,
       ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY I.ID DESC) AS [RN],
       ROW_NUMBER() OVER (ORDER BY I.ID) AS [R]
       FROM HolidayList AS I
       INNER JOIN (
          SELECT ID, MIN(CreateDate) FROM HolidayList GROUP BY ID
       )
       AS j ON i.ID = j.ID AND i.CreateDate = j.CreateDate
     )
     SELECT * FROM results WHERE [RN] = 1 AND BETWEEN [R]>10 AND [R]<25
</code>```

What I am really looking for is select a specific range from all the first row for each id.

FINAL

Thank to McGlothlin, finally I solve it. What I need is a nested CTE.

```<code>With First_CTE as
         (
           i.*,
           ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY I.ID DESC) AS [RN]
           FROM HolidayList AS I
           INNER JOIN (
              SELECT ID, MIN(CreateDate) FROM HolidayList GROUP BY ID
           )
           AS j ON i.ID = j.ID AND i.CreateDate = j.CreateDate
         ),
         results AS
          (
            SELECT k.*,
            ROW_NUMBER() OVER (ORDER BY k.ID DESC) AS [R]
            FROM First_CTE AS k WHERE k.[RN] = 1
          )
          SELECT * FROM results WHERE [R]>10 AND [R]<25
</code>```

答:
The problem lies in this line:

```<code>ROW_NUMBER() OVER I.ID AS [R]
</code>```

I think what you meant was:

```<code>ROW_NUMBER() OVER (ORDER BY I.ID) AS [R]
</code>```

This is assuming you want to give it a row count over every row that is returned in the CTE. The ROW_NUMBER() function requires an ORDER BY to be specified, and the OVER clause would still require parentheses if you were using a function like SUM that could be used without an ORDER BY.

Edit: Based on your comment, it sounds like what you're looking for is an OFFSET. In that case you would remove the second ROW_NUMBER and include something like this:

```<code>ORDER BY ID OFFSET 10 ROWS FETCH FIRST 15 ROWS ONLY
</code>```

This returns rows 11 to 25, sorted by ID.

Since the OFFSET syntax doesn't work in SQL Server 2008, you should do something like this as your end result:

```<code>With results as
    (
      i.*,
      ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY I.ID DESC) AS [RN]
      ROW_NUMBER() OVER (ORDER BY I.ID) AS [R]
      FROM HolidayList AS I
      INNER JOIN (
         SELECT ID, MIN(CreateDate) FROM HolidayList GROUP BY ID
      )
      AS j ON i.ID = j.ID AND i.CreateDate = j.CreateDate
    )
    SELECT *
    FROM results
    WHERE [RN] = 1
        AND [R] BETWEEN 11 AND 25
</code>```

Body:
I have created a table in html to display first rows of each id and allow user to select specific range they want to see, but not sure how I can write it in query.

With results as
 (
   i.*,
   ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY I.ID DESC) AS [RN]
   FROM HolidayList AS I
   INNER JOIN (
      SELECT ID, MIN(CreateDate) FROM HolidayList GROUP BY ID
   )
   AS j ON i.ID = j.ID AND i.CreateDate = j.CreateDate
 )
 SELECT * FROM results WHERE [RN] = 1;

UPDATED

I have tried to inject two ROW_NUMBER(), but what I received is row 10 and row 25 and they are first rows of some specific id.

 With results as
     (
       i.*,
       ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY I.ID DESC) AS [RN],
       ROW_NUMBER() OVER (ORDER BY I.ID) AS [R]
       FROM HolidayList AS I
       INNER JOIN (
          SELECT ID, MIN(CreateDate) FROM HolidayList GROUP BY ID
       )
       AS j ON i.ID = j.ID AND i.CreateDate = j.CreateDate
     )
     SELECT * FROM results WHERE [RN] = 1 AND BETWEEN [R]>10 AND [R]<25

What I am really looking for is select a specific range from all the first row for each id.

FINAL

Thank to McGlothlin, finally I solve it. What I need is a nested CTE.

With First_CTE as
         (
           i.*,
           ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY I.ID DESC) AS [RN]
           FROM HolidayList AS I
           INNER JOIN (
              SELECT ID, MIN(CreateDate) FROM HolidayList GROUP BY ID
           )
           AS j ON i.ID = j.ID AND i.CreateDate = j.CreateDate
         ),
         results AS
          (
            SELECT k.*,
            ROW_NUMBER() OVER (ORDER BY k.ID DESC) AS [R]
            FROM First_CTE AS k WHERE k.[RN] = 1
          )
          SELECT * FROM results WHERE [R]>10 AND [R]<25

Body:
The problem lies in this line:

ROW_NUMBER() OVER I.ID AS [R]

I think what you meant was:

ROW_NUMBER() OVER (ORDER BY I.ID) AS [R]

This is assuming you want to give it a row count over every row that is returned in the CTE. The ROW_NUMBER() function requires an ORDER BY to be specified, and the OVER clause would still require parentheses if you were using a function like SUM that could be used without an ORDER BY.

Edit: Based on your comment, it sounds like what you're looking for is an OFFSET. In that case you would remove the second ROW_NUMBER and include something like this:

ORDER BY ID OFFSET 10 ROWS FETCH FIRST 15 ROWS ONLY

This returns rows 11 to 25, sorted by ID.

Since the OFFSET syntax doesn't work in SQL Server 2008, you should do something like this as your end result:

With results as
    (
      i.*,
      ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY I.ID DESC) AS [RN]
      ROW_NUMBER() OVER (ORDER BY I.ID) AS [R]
      FROM HolidayList AS I
      INNER JOIN (
         SELECT ID, MIN(CreateDate) FROM HolidayList GROUP BY ID
      )
      AS j ON i.ID = j.ID AND i.CreateDate = j.CreateDate
    )
    SELECT *
    FROM results
    WHERE [RN] = 1
        AND [R] BETWEEN 11 AND 25


问:
How can I insert some XAML snippet in to my window as child element?
I have some XAML (as string) like this:

```<code> <Grid>
        <TextBlock>some text</TextBlock>
</Grid>
</code>```

And I want to insert it into my window without generating it in code behind:

```<code> <Window  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="BookOnTheFly.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
 <insert xaml snippet here>
    </Grid>
</window>
</code>```

I mean something like jQuery append..

答:
In code you would add the element to the Children of the Grid. Something like this

XAML:

```<code><Grid Name="grid">
     <!-- Where your code will be inserted -->
</Grid>

<Grid Name="toBeInserted">
    <TextBlock>some Text</TextBlock>
</Grid>
</code>```

Code:

```<code>grid.Children.Add(toBeInserted);
</code>```

Note:
You will get an exception if the thing you're adding is already the child of another element. You must remove it from that element first before adding it to the new one.

```<code>oldContainer.Children.Remove(toBeInserted);
</code>```

Hope this helps!

Body:
I have some XAML (as string) like this:

 <Grid>
        <TextBlock>some text</TextBlock>
</Grid>

And I want to insert it into my window without generating it in code behind:

 <Window  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="BookOnTheFly.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
 <insert xaml snippet here>
    </Grid>
</window>

I mean something like jQuery append..

Body:
In code you would add the element to the Children of the Grid. Something like this

XAML:

<Grid Name="grid">
     <!-- Where your code will be inserted -->
</Grid>

<Grid Name="toBeInserted">
    <TextBlock>some Text</TextBlock>
</Grid>

Code:

grid.Children.Add(toBeInserted);

Note:
You will get an exception if the thing you're adding is already the child of another element. You must remove it from that element first before adding it to the new one.

oldContainer.Children.Remove(toBeInserted);

Hope this helps!


问:
How to check for conditional properties on the global window object in Typescript
I need to check the window global for an init_data object that may or may not be there. Trying to access it directly Typescript complained: Property 'init_data' does not exist on type 'Window'

I had a working workaround but it no longer works with Typescript 2.4.

The workaround was:

```<code>interface Window {
  init_data?: any
}

const isLoggedIn = function() {
  let win:Window = window
  return win.init_data ? true : false
}
</code>```

This now throws the error: error TS2559: Type 'Window' has no properties in common with type 'Window'.

答:
```<code>const isLoggedIn = () => !!window['init_data'];
</code>```

Body:
I need to check the window global for an init_data object that may or may not be there. Trying to access it directly Typescript complained: Property 'init_data' does not exist on type 'Window'

I had a working workaround but it no longer works with Typescript 2.4.

The workaround was:

interface Window {
  init_data?: any
}

const isLoggedIn = function() {
  let win:Window = window
  return win.init_data ? true : false
}

This now throws the error: error TS2559: Type 'Window' has no properties in common with type 'Window'.


问:
Trying to understand power function, C Programming Language, 2e, 27
I'm working my way through The C Programming Language, K&R, 2nd edition, page 26, about the power() function, and I'm confused by something:

```<code>int power(int base, int n)
{
    int p;

    for (p = 1; n > 0; --n)
        p = p * base;
    return p;
}
</code>```

How does p get incremented? If the for loop "runs backwards until it becomes zero", why is it n > 0 and not n = 0?

答:
p is incremented by the following line:

```<code>p = p * base;
</code>```

You might read this as "take value p, multiply it by base, and store it into p".

If the for loop "runs backwards until it becomes zero", why is it n > 0 and not n = 0?

The second argument in the for-loop is used to determine if the loop should run. Therefore n > 0 means "As long as n is greater than 0, run the loop", while n == 0 would mean "As long as n is equal to 0, run the loop".

The intended purpose here is to run the loop n times. You subtract 1 from n each time, and then stop the loop once it becomes 0. This will have multiplied p by base for n times.

Body:
I'm working my way through The C Programming Language, K&R, 2nd edition, page 26, about the power() function, and I'm confused by something:

int power(int base, int n)
{
    int p;

    for (p = 1; n > 0; --n)
        p = p * base;
    return p;
}

How does p get incremented? If the for loop "runs backwards until it becomes zero", why is it n > 0 and not n = 0?

Body:
p is incremented by the following line:

p = p * base;

You might read this as "take value p, multiply it by base, and store it into p".

If the for loop "runs backwards until it becomes zero", why is it n > 0 and not n = 0?

The second argument in the for-loop is used to determine if the loop should run. Therefore n > 0 means "As long as n is greater than 0, run the loop", while n == 0 would mean "As long as n is equal to 0, run the loop".

The intended purpose here is to run the loop n times. You subtract 1 from n each time, and then stop the loop once it becomes 0. This will have multiplied p by base for n times.