问:
Serializing Cart content without loosing data in WooCommerce 3
I have a client who wants to re-route all the carts from his various WooCommerce stores to one cart. For example the carts from stores A, B, C, and D will be passed to store F's payment gateway.

I figured out a way to do this by taking the contents of a cart from any of the stores and passing that to the function that makes the order in WooCommerce, but I have a problem here because if I var_dump WC()->cart->get_cart() it returns this array:

```<code>array(1) {
  ["98f13708210194c475687be6106a3b84"]=>
  array(10) {
    ["product_id"]=>
    int(20)
    ["variation_id"]=>
    int(0)
    ["variation"]=>
    array(0) {
    }
    ["quantity"]=>
    int(2)
    ["line_total"]=>
    float(3001.98)
    ["line_subtotal"]=>
    float(3001.98)
    ["line_tax"]=>
    float(0)
    ["line_subtotal_tax"]=>
    float(0)
    ["line_tax_data"]=>
    array(2) {
      ["total"]=>
      array(0) {
      }
      ["subtotal"]=>
      array(0) {
      }
    }
    ["data"]=>
    object(WC_Product_Simple)#8809 (12) {
      ["object_type":protected]=>
      string(7) "product"
      ["post_type":protected]=>
      string(7) "product"
      ["cache_group":protected]=>
      string(8) "products"
      ["data":protected]=>
      array(48) {
        ["name"]=>
        string(7) "Jet sky"
        ["slug"]=>
        string(7) "jet-sky"
        ["date_created"]=>
        object(WC_DateTime)#8801 (4) {
          ["utc_offset":protected]=>
          int(0)
          ["date"]=>
          string(26) "2017-06-23 15:25:27.000000"
          ["timezone_type"]=>
          int(1)
          ["timezone"]=>
          string(6) "+00:00"
        }
        ["date_modified"]=>
        object(WC_DateTime)#8804 (4) {
          ["utc_offset":protected]=>
          int(0)
          ["date"]=>
          string(26) "2017-06-23 15:25:27.000000"
          ["timezone_type"]=>
          int(1)
          ["timezone"]=>
          string(6) "+00:00"
        }
        ["status"]=>
        string(7) "publish"
        ["featured"]=>
        bool(false)
        ["catalog_visibility"]=>
        string(7) "visible"
        ["description"]=>
        string(278) "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo."
        ["short_description"]=>
        string(93) "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas."
        ["sku"]=>
        string(0) ""
        ["price"]=>
        string(7) "1500.99"
        ["regular_price"]=>
        string(7) "1500.99"
        ["sale_price"]=>
        string(0) ""
        ["date_on_sale_from"]=>
        NULL
        ["date_on_sale_to"]=>
        NULL
        ["total_sales"]=>
        int(0)
        ["tax_status"]=>
        string(7) "taxable"
        ["tax_class"]=>
        string(0) ""
        ["manage_stock"]=>
        bool(false)
        ["stock_quantity"]=>
        NULL
        ["stock_status"]=>
        string(7) "instock"
        ["backorders"]=>
        string(2) "no"
        ["sold_individually"]=>
        bool(false)
        ["weight"]=>
        string(0) ""
        ["length"]=>
        string(0) ""
        ["width"]=>
        string(0) ""
        ["height"]=>
        string(0) ""
        ["upsell_ids"]=>
        array(0) {
        }
        ["cross_sell_ids"]=>
        array(0) {
        }
        ["parent_id"]=>
        int(0)
        ["reviews_allowed"]=>
        bool(true)
        ["purchase_note"]=>
        string(0) ""
        ["attributes"]=>
        array(0) {
        }
        ["default_attributes"]=>
        array(0) {
        }
        ["menu_order"]=>
        int(0)
        ["virtual"]=>
        bool(false)
        ["downloadable"]=>
        bool(false)
        ["category_ids"]=>
        array(0) {
        }
        ["tag_ids"]=>
        array(0) {
        }
        ["shipping_class_id"]=>
        int(0)
        ["downloads"]=>
        array(0) {
        }
        ["image_id"]=>
        string(2) "18"
        ["gallery_image_ids"]=>
        array(1) {
          [0]=>
          int(19)
        }
        ["download_limit"]=>
        int(-1)
        ["download_expiry"]=>
        int(-1)
        ["rating_counts"]=>
        array(0) {
        }
        ["average_rating"]=>
        string(1) "0"
        ["review_count"]=>
        int(0)
      }
      ["supports":protected]=>
      array(1) {
        [0]=>
        string(16) "ajax_add_to_cart"
      }
      ["id":protected]=>
      int(20)
      ["changes":protected]=>
      array(0) {
      }
      ["object_read":protected]=>
      bool(true)
      ["extra_data":protected]=>
      array(0) {
      }
      ["default_data":protected]=>
      array(48) {
        ["name"]=>
        string(0) ""
        ["slug"]=>
        string(0) ""
        ["date_created"]=>
        NULL
        ["date_modified"]=>
        NULL
        ["status"]=>
        bool(false)
        ["featured"]=>
        bool(false)
        ["catalog_visibility"]=>
        string(7) "visible"
        ["description"]=>
        string(0) ""
        ["short_description"]=>
        string(0) ""
        ["sku"]=>
        string(0) ""
        ["price"]=>
        string(0) ""
        ["regular_price"]=>
        string(0) ""
        ["sale_price"]=>
        string(0) ""
        ["date_on_sale_from"]=>
        NULL
        ["date_on_sale_to"]=>
        NULL
        ["total_sales"]=>
        string(1) "0"
        ["tax_status"]=>
        string(7) "taxable"
        ["tax_class"]=>
        string(0) ""
        ["manage_stock"]=>
        bool(false)
        ["stock_quantity"]=>
        NULL
        ["stock_status"]=>
        string(7) "instock"
        ["backorders"]=>
        string(2) "no"
        ["sold_individually"]=>
        bool(false)
        ["weight"]=>
        string(0) ""
        ["length"]=>
        string(0) ""
        ["width"]=>
        string(0) ""
        ["height"]=>
        string(0) ""
        ["upsell_ids"]=>
        array(0) {
        }
        ["cross_sell_ids"]=>
        array(0) {
        }
        ["parent_id"]=>
        int(0)
        ["reviews_allowed"]=>
        bool(true)
        ["purchase_note"]=>
        string(0) ""
        ["attributes"]=>
        array(0) {
        }
        ["default_attributes"]=>
        array(0) {
        }
        ["menu_order"]=>
        int(0)
        ["virtual"]=>
        bool(false)
        ["downloadable"]=>
        bool(false)
        ["category_ids"]=>
        array(0) {
        }
        ["tag_ids"]=>
        array(0) {
        }
        ["shipping_class_id"]=>
        int(0)
        ["downloads"]=>
        array(0) {
        }
        ["image_id"]=>
        string(0) ""
        ["gallery_image_ids"]=>
        array(0) {
        }
        ["download_limit"]=>
        int(-1)
        ["download_expiry"]=>
        int(-1)
        ["rating_counts"]=>
        array(0) {
        }
        ["average_rating"]=>
        int(0)
        ["review_count"]=>
        int(0)
      }
      ["data_store":protected]=>
      object(WC_Data_Store)#8807 (4) {
        ["instance":"WC_Data_Store":private]=>
        object(WC_Product_Data_Store_CPT)#8806 (5) {
          ["internal_meta_keys":protected]=>
          array(39) {
            [0]=>
            string(11) "_visibility"
            [1]=>
            string(4) "_sku"
            [2]=>
            string(6) "_price"
            [3]=>
            string(14) "_regular_price"
            [4]=>
            string(11) "_sale_price"
            [5]=>
            string(22) "_sale_price_dates_from"
            [6]=>
            string(20) "_sale_price_dates_to"
            [7]=>
            string(11) "total_sales"
            [8]=>
            string(11) "_tax_status"
            [9]=>
            string(10) "_tax_class"
            [10]=>
            string(13) "_manage_stock"
            [11]=>
            string(6) "_stock"
            [12]=>
            string(13) "_stock_status"
            [13]=>
            string(11) "_backorders"
            [14]=>
            string(18) "_sold_individually"
            [15]=>
            string(7) "_weight"
            [16]=>
            string(7) "_length"
            [17]=>
            string(6) "_width"
            [18]=>
            string(7) "_height"
            [19]=>
            string(11) "_upsell_ids"
            [20]=>
            string(14) "_crosssell_ids"
            [21]=>
            string(14) "_purchase_note"
            [22]=>
            string(19) "_default_attributes"
            [23]=>
            string(19) "_product_attributes"
            [24]=>
            string(8) "_virtual"
            [25]=>
            string(13) "_downloadable"
            [26]=>
            string(9) "_featured"
            [27]=>
            string(19) "_downloadable_files"
            [28]=>
            string(16) "_wc_rating_count"
            [29]=>
            string(18) "_wc_average_rating"
            [30]=>
            string(16) "_wc_review_count"
            [31]=>
            string(22) "_variation_description"
            [32]=>
            string(13) "_thumbnail_id"
            [33]=>
            string(11) "_file_paths"
            [34]=>
            string(22) "_product_image_gallery"
            [35]=>
            string(16) "_product_version"
            [36]=>
            string(12) "_wp_old_slug"
            [37]=>
            string(10) "_edit_last"
            [38]=>
            string(10) "_edit_lock"
          }
          ["extra_data_saved":protected]=>
          bool(false)
          ["updated_props":protected]=>
          array(0) {
          }
          ["meta_type":protected]=>
          string(4) "post"
          ["object_id_field_for_meta":protected]=>
          string(0) ""
        }
        ["stores":"WC_Data_Store":private]=>
        array(18) {
          ["coupon"]=>
          string(24) "WC_Coupon_Data_Store_CPT"
          ["customer"]=>
          string(22) "WC_Customer_Data_Store"
          ["customer-download"]=>
          string(31) "WC_Customer_Download_Data_Store"
          ["customer-session"]=>
          string(30) "WC_Customer_Data_Store_Session"
          ["order"]=>
          string(23) "WC_Order_Data_Store_CPT"
          ["order-refund"]=>
          string(30) "WC_Order_Refund_Data_Store_CPT"
          ["order-item…
</code>```

When I try to loop through it and store the serialized or encoded values, this is what I get:

```<code>{ ["98f13708210194c475687be6106a3b84"]=> array(10)
{ ["product_id"]=> int(20)
["variation_id"]=> int(0)
["variation"]=> array(0) { }
["quantity"]=> int(2)
["line_total"]=> float(3001.98)
["line_subtotal"]=> float(3001.98)
["line_tax"]=> int(0)
["line_subtotal_tax"]=> int(0)
["line_tax_data"]=> array(2) {
 ["total"]=> array(0) { }
["subtotal"]=> array(0) { } }
["data"]=> array(0) { } } }`
</code>```

My questions:

What could be happening?

Why do I lose so much data?

How to get the missing data?

答:
You are loosing the ["data"] because as you can see it's a WC_product object and you can access the data directly since woocommerce 3+.

All other data after is protected so you can't get it too.

So you need to use a foreach loop this way:

```<code>// iterating through each cart items
foreach ( WC()->cart->get_cart() as $item_key => $item_values ){

    // We set the cart item data in an array
    $wc_get_cart[$item_key] = $item_values;

    // We remove the WC_Product object from this array
    unset($wc_get_cart[$item_key]['data']);

    // We set the data with WC_Data get_data() method in a variable (array)
    $product_data = $item_values['data']->get_data();

    // We set back this data
    $wc_get_cart[$item_key]['data'] = $product_data;

}
</code>```

Now you can serialize $wc_get_cart multi dimensional array and you will see that you have all the needed data

So you can use WC_Data get_data() method to convert WooCommerce objects like Orders or Products in an array and then to access properties without using the classes methods.

Body:
I have a client who wants to re-route all the carts from his various WooCommerce stores to one cart. For example the carts from stores A, B, C, and D will be passed to store F's payment gateway.

I figured out a way to do this by taking the contents of a cart from any of the stores and passing that to the function that makes the order in WooCommerce, but I have a problem here because if I var_dump WC()->cart->get_cart() it returns this array:

array(1) {
  ["98f13708210194c475687be6106a3b84"]=>
  array(10) {
    ["product_id"]=>
    int(20)
    ["variation_id"]=>
    int(0)
    ["variation"]=>
    array(0) {
    }
    ["quantity"]=>
    int(2)
    ["line_total"]=>
    float(3001.98)
    ["line_subtotal"]=>
    float(3001.98)
    ["line_tax"]=>
    float(0)
    ["line_subtotal_tax"]=>
    float(0)
    ["line_tax_data"]=>
    array(2) {
      ["total"]=>
      array(0) {
      }
      ["subtotal"]=>
      array(0) {
      }
    }
    ["data"]=>
    object(WC_Product_Simple)#8809 (12) {
      ["object_type":protected]=>
      string(7) "product"
      ["post_type":protected]=>
      string(7) "product"
      ["cache_group":protected]=>
      string(8) "products"
      ["data":protected]=>
      array(48) {
        ["name"]=>
        string(7) "Jet sky"
        ["slug"]=>
        string(7) "jet-sky"
        ["date_created"]=>
        object(WC_DateTime)#8801 (4) {
          ["utc_offset":protected]=>
          int(0)
          ["date"]=>
          string(26) "2017-06-23 15:25:27.000000"
          ["timezone_type"]=>
          int(1)
          ["timezone"]=>
          string(6) "+00:00"
        }
        ["date_modified"]=>
        object(WC_DateTime)#8804 (4) {
          ["utc_offset":protected]=>
          int(0)
          ["date"]=>
          string(26) "2017-06-23 15:25:27.000000"
          ["timezone_type"]=>
          int(1)
          ["timezone"]=>
          string(6) "+00:00"
        }
        ["status"]=>
        string(7) "publish"
        ["featured"]=>
        bool(false)
        ["catalog_visibility"]=>
        string(7) "visible"
        ["description"]=>
        string(278) "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo."
        ["short_description"]=>
        string(93) "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas."
        ["sku"]=>
        string(0) ""
        ["price"]=>
        string(7) "1500.99"
        ["regular_price"]=>
        string(7) "1500.99"
        ["sale_price"]=>
        string(0) ""
        ["date_on_sale_from"]=>
        NULL
        ["date_on_sale_to"]=>
        NULL
        ["total_sales"]=>
        int(0)
        ["tax_status"]=>
        string(7) "taxable"
        ["tax_class"]=>
        string(0) ""
        ["manage_stock"]=>
        bool(false)
        ["stock_quantity"]=>
        NULL
        ["stock_status"]=>
        string(7) "instock"
        ["backorders"]=>
        string(2) "no"
        ["sold_individually"]=>
        bool(false)
        ["weight"]=>
        string(0) ""
        ["length"]=>
        string(0) ""
        ["width"]=>
        string(0) ""
        ["height"]=>
        string(0) ""
        ["upsell_ids"]=>
        array(0) {
        }
        ["cross_sell_ids"]=>
        array(0) {
        }
        ["parent_id"]=>
        int(0)
        ["reviews_allowed"]=>
        bool(true)
        ["purchase_note"]=>
        string(0) ""
        ["attributes"]=>
        array(0) {
        }
        ["default_attributes"]=>
        array(0) {
        }
        ["menu_order"]=>
        int(0)
        ["virtual"]=>
        bool(false)
        ["downloadable"]=>
        bool(false)
        ["category_ids"]=>
        array(0) {
        }
        ["tag_ids"]=>
        array(0) {
        }
        ["shipping_class_id"]=>
        int(0)
        ["downloads"]=>
        array(0) {
        }
        ["image_id"]=>
        string(2) "18"
        ["gallery_image_ids"]=>
        array(1) {
          [0]=>
          int(19)
        }
        ["download_limit"]=>
        int(-1)
        ["download_expiry"]=>
        int(-1)
        ["rating_counts"]=>
        array(0) {
        }
        ["average_rating"]=>
        string(1) "0"
        ["review_count"]=>
        int(0)
      }
      ["supports":protected]=>
      array(1) {
        [0]=>
        string(16) "ajax_add_to_cart"
      }
      ["id":protected]=>
      int(20)
      ["changes":protected]=>
      array(0) {
      }
      ["object_read":protected]=>
      bool(true)
      ["extra_data":protected]=>
      array(0) {
      }
      ["default_data":protected]=>
      array(48) {
        ["name"]=>
        string(0) ""
        ["slug"]=>
        string(0) ""
        ["date_created"]=>
        NULL
        ["date_modified"]=>
        NULL
        ["status"]=>
        bool(false)
        ["featured"]=>
        bool(false)
        ["catalog_visibility"]=>
        string(7) "visible"
        ["description"]=>
        string(0) ""
        ["short_description"]=>
        string(0) ""
        ["sku"]=>
        string(0) ""
        ["price"]=>
        string(0) ""
        ["regular_price"]=>
        string(0) ""
        ["sale_price"]=>
        string(0) ""
        ["date_on_sale_from"]=>
        NULL
        ["date_on_sale_to"]=>
        NULL
        ["total_sales"]=>
        string(1) "0"
        ["tax_status"]=>
        string(7) "taxable"
        ["tax_class"]=>
        string(0) ""
        ["manage_stock"]=>
        bool(false)
        ["stock_quantity"]=>
        NULL
        ["stock_status"]=>
        string(7) "instock"
        ["backorders"]=>
        string(2) "no"
        ["sold_individually"]=>
        bool(false)
        ["weight"]=>
        string(0) ""
        ["length"]=>
        string(0) ""
        ["width"]=>
        string(0) ""
        ["height"]=>
        string(0) ""
        ["upsell_ids"]=>
        array(0) {
        }
        ["cross_sell_ids"]=>
        array(0) {
        }
        ["parent_id"]=>
        int(0)
        ["reviews_allowed"]=>
        bool(true)
        ["purchase_note"]=>
        string(0) ""
        ["attributes"]=>
        array(0) {
        }
        ["default_attributes"]=>
        array(0) {
        }
        ["menu_order"]=>
        int(0)
        ["virtual"]=>
        bool(false)
        ["downloadable"]=>
        bool(false)
        ["category_ids"]=>
        array(0) {
        }
        ["tag_ids"]=>
        array(0) {
        }
        ["shipping_class_id"]=>
        int(0)
        ["downloads"]=>
        array(0) {
        }
        ["image_id"]=>
        string(0) ""
        ["gallery_image_ids"]=>
        array(0) {
        }
        ["download_limit"]=>
        int(-1)
        ["download_expiry"]=>
        int(-1)
        ["rating_counts"]=>
        array(0) {
        }
        ["average_rating"]=>
        int(0)
        ["review_count"]=>
        int(0)
      }
      ["data_store":protected]=>
      object(WC_Data_Store)#8807 (4) {
        ["instance":"WC_Data_Store":private]=>
        object(WC_Product_Data_Store_CPT)#8806 (5) {
          ["internal_meta_keys":protected]=>
          array(39) {
            [0]=>
            string(11) "_visibility"
            [1]=>
            string(4) "_sku"
            [2]=>
            string(6) "_price"
            [3]=>
            string(14) "_regular_price"
            [4]=>
            string(11) "_sale_price"
            [5]=>
            string(22) "_sale_price_dates_from"
            [6]=>
            string(20) "_sale_price_dates_to"
            [7]=>
            string(11) "total_sales"
            [8]=>
            string(11) "_tax_status"
            [9]=>
            string(10) "_tax_class"
            [10]=>
            string(13) "_manage_stock"
            [11]=>
            string(6) "_stock"
            [12]=>
            string(13) "_stock_status"
            [13]=>
            string(11) "_backorders"
            [14]=>
            string(18) "_sold_individually"
            [15]=>
            string(7) "_weight"
            [16]=>
            string(7) "_length"
            [17]=>
            string(6) "_width"
            [18]=>
            string(7) "_height"
            [19]=>
            string(11) "_upsell_ids"
            [20]=>
            string(14) "_crosssell_ids"
            [21]=>
            string(14) "_purchase_note"
            [22]=>
            string(19) "_default_attributes"
            [23]=>
            string(19) "_product_attributes"
            [24]=>
            string(8) "_virtual"
            [25]=>
            string(13) "_downloadable"
            [26]=>
            string(9) "_featured"
            [27]=>
            string(19) "_downloadable_files"
            [28]=>
            string(16) "_wc_rating_count"
            [29]=>
            string(18) "_wc_average_rating"
            [30]=>
            string(16) "_wc_review_count"
            [31]=>
            string(22) "_variation_description"
            [32]=>
            string(13) "_thumbnail_id"
            [33]=>
            string(11) "_file_paths"
            [34]=>
            string(22) "_product_image_gallery"
            [35]=>
            string(16) "_product_version"
            [36]=>
            string(12) "_wp_old_slug"
            [37]=>
            string(10) "_edit_last"
            [38]=>
            string(10) "_edit_lock"
          }
          ["extra_data_saved":protected]=>
          bool(false)
          ["updated_props":protected]=>
          array(0) {
          }
          ["meta_type":protected]=>
          string(4) "post"
          ["object_id_field_for_meta":protected]=>
          string(0) ""
        }
        ["stores":"WC_Data_Store":private]=>
        array(18) {
          ["coupon"]=>
          string(24) "WC_Coupon_Data_Store_CPT"
          ["customer"]=>
          string(22) "WC_Customer_Data_Store"
          ["customer-download"]=>
          string(31) "WC_Customer_Download_Data_Store"
          ["customer-session"]=>
          string(30) "WC_Customer_Data_Store_Session"
          ["order"]=>
          string(23) "WC_Order_Data_Store_CPT"
          ["order-refund"]=>
          string(30) "WC_Order_Refund_Data_Store_CPT"
          ["order-item…

When I try to loop through it and store the serialized or encoded values, this is what I get:

{ ["98f13708210194c475687be6106a3b84"]=> array(10)
{ ["product_id"]=> int(20)
["variation_id"]=> int(0)
["variation"]=> array(0) { }
["quantity"]=> int(2)
["line_total"]=> float(3001.98)
["line_subtotal"]=> float(3001.98)
["line_tax"]=> int(0)
["line_subtotal_tax"]=> int(0)
["line_tax_data"]=> array(2) {
 ["total"]=> array(0) { }
["subtotal"]=> array(0) { } }
["data"]=> array(0) { } } }`

My questions:

What could be happening?

Why do I lose so much data?

How to get the missing data?

Body:
You are loosing the ["data"] because as you can see it's a WC_product object and you can access the data directly since woocommerce 3+.

All other data after is protected so you can't get it too.

So you need to use a foreach loop this way:

// iterating through each cart items
foreach ( WC()->cart->get_cart() as $item_key => $item_values ){

    // We set the cart item data in an array
    $wc_get_cart[$item_key] = $item_values;

    // We remove the WC_Product object from this array
    unset($wc_get_cart[$item_key]['data']);

    // We set the data with WC_Data get_data() method in a variable (array)
    $product_data = $item_values['data']->get_data();

    // We set back this data
    $wc_get_cart[$item_key]['data'] = $product_data;

}

Now you can serialize $wc_get_cart multi dimensional array and you will see that you have all the needed data

So you can use WC_Data get_data() method to convert WooCommerce objects like Orders or Products in an array and then to access properties without using the classes methods.


来源: stackexchange

问:
Cannot Remove Attribute Javascript
If I try the code below on the console in Chrome, it is working. But the code is not working in my Javascript extension in Chrome.

```<code>var region = document.getElementById("physicalDeliveryOfficeName");
region.removeAttribute("onchange");
</code>```

Any thoughts what am I doing wrong? Tried to add this line in my function and on the top of my script but it is not working.

答:
It works in console because the dom has loaded. Wrap your code in an event handler.

```<code>document.addEventListener("DOMContentLoaded", function(event) {
  var region = document.getElementById("physicalDeliveryOfficeName");
  region.removeAttribute("onchange");
});
</code>```

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

ContentLicense: CC BY-SA 3.0

Title: Cannot Remove Attribute Javascript

Body:
If I try the code below on the console in Chrome, it is working. But the code is not working in my Javascript extension in Chrome.

var region = document.getElementById("physicalDeliveryOfficeName");
region.removeAttribute("onchange");

Any thoughts what am I doing wrong? Tried to add this line in my function and on the top of my script but it is not working.

Body:
It works in console because the dom has loaded. Wrap your code in an event handler.

document.addEventListener("DOMContentLoaded", function(event) {
  var region = document.getElementById("physicalDeliveryOfficeName");
  region.removeAttribute("onchange");
});

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded


问:
Visual Studio Community - disabled target platform "iOS"
I have just installed Visual Studio Community Edition and as I try to create new xamarin project, I noticed one of the target platforms, "iOS" is disabled.

What should I do to see it enabled?

答: Seems like the second attempt at installing Visual Studio fixed everything ... I can't imagine that I didn't have the iOS checkbox checked on first attempt ... #strange


问:
Alternatives to awkward Pandas/Python Dataframe Indexing: df_REPEATED[df_REPEATED['var']]>0?
In Pandas/Python, I have to write the dataframe name twice when conditioning on its own variable:

```<code>df_REPEATED[df_REPEATED['var']>0]
</code>```

This happens so many times it seems unreasonable. 90-99% of users would be happy 95% of the time with something like:

```<code>df_REPEATED[['var']>0]
</code>```

This syntax is also necessary using .loc[]. Is there any alternative or shortcut to writing this?

On the other hand, is there some use case I don't understand and actually my education in python has been woefully insufficient?

答:
df_REPEATED['var'] > 0 is a boolean array. Other than its length, it has no connection to the DataFrame. It could have been the result of another expression, say another_df['another_var'] > some_other_value, as long as the lengths match. So it offers flexibility. If the syntax was like the one you suggested, we couldn't do this. However, there are alternatives to what you are asking. For example,

```<code>df_REPEATED.query('var > 0')
</code>```

query can be very fast if the DataFrame is large and it is less verbose but it lacks the advantages of boolean indexing and you start having troubles if the expression gets complicated.

Body:
In Pandas/Python, I have to write the dataframe name twice when conditioning on its own variable:

df_REPEATED[df_REPEATED['var']>0]

This happens so many times it seems unreasonable. 90-99% of users would be happy 95% of the time with something like:

df_REPEATED[['var']>0]

This syntax is also necessary using .loc[]. Is there any alternative or shortcut to writing this?

On the other hand, is there some use case I don't understand and actually my education in python has been woefully insufficient?

Body:
df_REPEATED['var'] > 0 is a boolean array. Other than its length, it has no connection to the DataFrame. It could have been the result of another expression, say another_df['another_var'] > some_other_value, as long as the lengths match. So it offers flexibility. If the syntax was like the one you suggested, we couldn't do this. However, there are alternatives to what you are asking. For example,

df_REPEATED.query('var > 0')

query can be very fast if the DataFrame is large and it is less verbose but it lacks the advantages of boolean indexing and you start having troubles if the expression gets complicated.


问:
How to find records ONLY having multiple rows in SQL Server 2014?
Customers have accounts with us for their vehicles. Some accounts have multiple vehicles.

I would like to create a report of accounts ONLY with multiple vehicles (i.e. Multiple AccountIDs and Licence Plate numbers.)

Table Account A

Table Plate P

A.AccountId = P.AccountId

```<code>SELECT A.AccountNumber
      ,A.AccountId
      ,P.LicPlateNo

FROM Account A
INNER JOIN Plate P ON A.AccountId = P.AccountId

WHERE A.RegDate > '2017-01-01'
  AND (Select Count(P.LicPlateNo) GROUP BY A.AccountNumber) > 1
   -- HAVING Count(P.LicPlateNo) > 1 ????

ORDER BY A.AccountNumber
</code>```

答:
You got it almost .. need to use group by and having condition like

```<code>SELECT A.AccountNumber
      ,A.AccountId
      ,P.LicPlateNo

FROM Account A
INNER JOIN (
SELECT LicPlateNo, AccountId
FROM Plate
GROUP BY AccountId
HAVING Count(LicPlateNo) > 1 ) P
ON A.AccountId = P.AccountId
WHERE A.RegDate > '2017-01-01'
ORDER BY A.AccountNumber
</code>```

Body:
Customers have accounts with us for their vehicles. Some accounts have multiple vehicles.

I would like to create a report of accounts ONLY with multiple vehicles (i.e. Multiple AccountIDs and Licence Plate numbers.)

Table Account A

Table Plate P

A.AccountId = P.AccountId

SELECT A.AccountNumber
      ,A.AccountId
      ,P.LicPlateNo

FROM Account A
INNER JOIN Plate P ON A.AccountId = P.AccountId

WHERE A.RegDate > '2017-01-01'
  AND (Select Count(P.LicPlateNo) GROUP BY A.AccountNumber) > 1
   -- HAVING Count(P.LicPlateNo) > 1 ????

ORDER BY A.AccountNumber

Body:
You got it almost .. need to use group by and having condition like

SELECT A.AccountNumber
      ,A.AccountId
      ,P.LicPlateNo

FROM Account A
INNER JOIN (
SELECT LicPlateNo, AccountId
FROM Plate
GROUP BY AccountId
HAVING Count(LicPlateNo) > 1 ) P
ON A.AccountId = P.AccountId
WHERE A.RegDate > '2017-01-01'
ORDER BY A.AccountNumber


问:
App Script sends 405 response when trying to send a POST request
I have published an app script publicly (Anyone, even anonymous) with a doPost method as follow,

```<code> function doPost(e){
    var sheet = SpreadsheetApp.getActiveSheet();
    var length = e.contentLength;
    var body = e.postData.contents;
    var jsonString = e.postData.getDataAsString();
    var jsonData = JSON.parse(jsonString);
    sheet.appendRow([jsonData.title, length]);
    var MyResponse = "works";
    return ContentService.createTextOutput(MyResponse).setMimeType(ContentService.MimeType.JAVASCRIPT);
}
</code>```

When I sent a Post request with a JSON object with Advanced Rest Client it all works and return a 200 OK response. But when I try to send a post request with the react axios from a locally hosted react app it sends a 405 Response.

```<code>XMLHttpRequest cannot load https://script.google.com/macros/s/AKfycbzyc2CG9xLM-igL3zuslSmNY2GewL5seTWpMpDIQr_5eCod7_U/exec. Response for preflight has invalid HTTP status code 405
</code>```

I have enabled cross origin resource sharing in the  browser as well. The function that sends the POST request is as follow,

```<code>axios({
          method:'post',
          url:'https://script.google.com/macros/s/AKfycbzyc2CG9xLM-igL3zuslSmNY2GewL5seTWpMpDIQr_5eCod7_U/exec',
          data: {
            "title": 'Fred',
            "lastName": 'Flintstone'
          }
        }).then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
</code>```

答:
I think you need to return JSON data. It is possible that you need to return JSONP to a request from a browser, but here is what I think you need to do:

```<code>return ContentService.createTextOutput(JSON.stringify({message: MyResponse})).setMimeType(ContentService.MimeType.JSON);
</code>```

If that doesn't work, it is probably that you need to return JSONP to run in the browser. Here is some documentation to help you out: https://developers.google.com/apps-script/guides/content#serving_jsonp_in_web_pages

ContentLicense: CC BY-SA 4.0

Body:
I have published an app script publicly (Anyone, even anonymous) with a doPost method as follow,

 function doPost(e){
    var sheet = SpreadsheetApp.getActiveSheet();
    var length = e.contentLength;
    var body = e.postData.contents;
    var jsonString = e.postData.getDataAsString();
    var jsonData = JSON.parse(jsonString);
    sheet.appendRow([jsonData.title, length]);
    var MyResponse = "works";
    return ContentService.createTextOutput(MyResponse).setMimeType(ContentService.MimeType.JAVASCRIPT);
}

When I sent a Post request with a JSON object with Advanced Rest Client it all works and return a 200 OK response. But when I try to send a post request with the react axios from a locally hosted react app it sends a 405 Response.

XMLHttpRequest cannot load https://script.google.com/macros/s/AKfycbzyc2CG9xLM-igL3zuslSmNY2GewL5seTWpMpDIQr_5eCod7_U/exec. Response for preflight has invalid HTTP status code 405

I have enabled cross origin resource sharing in the  browser as well. The function that sends the POST request is as follow,

axios({
          method:'post',
          url:'https://script.google.com/macros/s/AKfycbzyc2CG9xLM-igL3zuslSmNY2GewL5seTWpMpDIQr_5eCod7_U/exec',
          data: {
            "title": 'Fred',
            "lastName": 'Flintstone'
          }
        }).then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });

Body:
I think you need to return JSON data. It is possible that you need to return JSONP to a request from a browser, but here is what I think you need to do:

return ContentService.createTextOutput(JSON.stringify({message: MyResponse})).setMimeType(ContentService.MimeType.JSON);

If that doesn't work, it is probably that you need to return JSONP to run in the browser. Here is some documentation to help you out: https://developers.google.com/apps-script/guides/content#serving_jsonp_in_web_pages


问:
Joining Oracle Table Data with MongoDB Collection
I have a reporting framework to build and generate reports (tabular format reports). As of now I used to write SQL query and it used to fetch data from Oracle. Now I have got an interesting challenge where half of data will come from Oracle and remaining data come from MongoDB based on output from Oracle data. Fetched tabular format data from Oracle will have one additional column which will contain key to fetch data from MongoDB. With this I will have two data set in tabular format one from Oracle data and one from MongoDB. Based on one common column I need to merge both table data and produce one data set to produce report.

I can write logic in java code to merge two tables (say data in 2D array format). But instead of doing this from my own, I am thinking to utilize some RDBMS in-memory data concept. For example, H2 database, where I can create two tables in memory on the fly and execute H2 queries to merge two tables. Or, I believe, there could be something in Oracle too like global temp table etc. Could someone please suggest the better approach to join oracle table data with MongoDB collection.

答: I think you can try and use Kafka and Spark Streaming to solve this problem. Assuming your data is transactional, you can create a Kafka broker and create a topic. Then make change to the existing services where you are saving to Oracle and MongoDB. Create 2 Kafka producers (one for Oracle and another for Mongo) to write the data as streams to the Kafka topic. Then create a consumer group to receive streams from Kafka. You may then aggregate the real time streams using a Spark cluster(You can look at Spark Streaming API for Kafka 1) and save the results back to MongoDB (using Spark Connector from MongoDB 2) or any other distributed database. Then you can do data visualizations/reporting on those results stored in MongoDB. </p>


问:
Is there a way to nest an enum within a data class in Kotlin?
Is there a way to nest an enum within a data class in Kotlin?

```<code>data class D(val a:Any) {
    enum class E {F,G}
    ...
}
</code>```

Or to declare it inline within a function?

```<code>fun foo() {
    enum class E {F,G}
    doSomething()
}
</code>```

I can't find documentation on the rules for where enums are allowed to be declared.

答:
There is no kotlin specification for the syntax at present. if you want to find the specification  you can see JLS, because Kotlin is based on Java, so some specifications also appropriate in Kotlin.

A nested enum type is implicitly static. It is permitted for the declaration of a nested enum type to redundantly specify the static modifier.

This implies that it is impossible to declare an enum type in the body of an inner class (§8.1.3), because an inner class cannot have static members except for constant variables.

and, all local classes are inner classes.

So the enum class can be declared anywhere except the local function scope and inner classes.

If you don't sure where can define a type you can try to prompt the scope in turn: local > class > top, then the kotlin compiler will give you the correct compiler error message to you. for example:

IF you define a const val in the local function, the compiler report the error as below:

```<code>fun local() {
    const val foo="bar"
    // ^--- the modifier `const` is not applicable to `local variable`
}
</code>```

IF you define a const val in the common class/interface, the compiler will report the error as below:

```<code>interface Foo {
  const val foo = "bar"
  //^--- `const val` only allowed on top-level or objects.
}
</code>```

Body:
Is there a way to nest an enum within a data class in Kotlin?

data class D(val a:Any) {
    enum class E {F,G}
    ...
}

Or to declare it inline within a function?

fun foo() {
    enum class E {F,G}
    doSomething()
}

I can't find documentation on the rules for where enums are allowed to be declared.

Body:
There is no kotlin specification for the syntax at present. if you want to find the specification  you can see JLS, because Kotlin is based on Java, so some specifications also appropriate in Kotlin.

A nested enum type is implicitly static. It is permitted for the declaration of a nested enum type to redundantly specify the static modifier.

This implies that it is impossible to declare an enum type in the body of an inner class (§8.1.3), because an inner class cannot have static members except for constant variables.

and, all local classes are inner classes.

So the enum class can be declared anywhere except the local function scope and inner classes.

If you don't sure where can define a type you can try to prompt the scope in turn: local > class > top, then the kotlin compiler will give you the correct compiler error message to you. for example:

IF you define a const val in the local function, the compiler report the error as below:

fun local() {
    const val foo="bar"
    // ^--- the modifier `const` is not applicable to `local variable`
}

IF you define a const val in the common class/interface, the compiler will report the error as below:

interface Foo {
  const val foo = "bar"
  //^--- `const val` only allowed on top-level or objects.
}


问:
Is there any way to rename a Cargo project?
I created a project using: cargo new projectname --bin.
How do I change projectname to some other name?

I checked the man page and the Cargo documentation. I also ran:

cargo help

cargo --list

man cargo

In the metadata files (Cargo.toml, Cargo.lock, ...), there is "name" and "path". I suppose I could change them manually, but I don't know if that would break anything.

What would be the best way to do this?

答:
I think that you should change it manually. Not so difficult, really.

I run this code:

$ cargo new smurf --bin
     Created binary (application) `smurf` project
$ cd smurf/
smurf$ cargo build
     ....
smurf$ grep -rl smurf .
./target/debug/smurf.d
./target/debug/smurf
./target/debug/.fingerprint/smurf-35f069edf7faaa12/bin-smurf-35f069edf7faaa12.json
./target/debug/.fingerprint/smurf-35f069edf7faaa12/dep-bin-smurf-35f069edf7faaa12
./target/debug/deps/smurf-35f069edf7faaa12
./Cargo.lock
./Cargo.toml
```

From all these files, the whole target may be just deleted. The .lock file can also be deleted. And the Cargo.toml... well you can just edit it.

I tried changing only the Cargo.toml and all just works. However you end up with useless files in target so I recommend deleting those anyway.

Body:
I think that you should change it manually. Not so difficult, really.

I run this code:

$ cargo new smurf --bin
     Created binary (application) `smurf` project
$ cd smurf/
smurf$ cargo build
     ....
smurf$ grep -rl smurf .
./target/debug/smurf.d
./target/debug/smurf
./target/debug/.fingerprint/smurf-35f069edf7faaa12/bin-smurf-35f069edf7faaa12.json
./target/debug/.fingerprint/smurf-35f069edf7faaa12/dep-bin-smurf-35f069edf7faaa12
./target/debug/deps/smurf-35f069edf7faaa12
./Cargo.lock
./Cargo.toml

From all these files, the whole target may be just deleted. The .lock file can also be deleted. And the Cargo.toml... well you can just edit it.

I tried changing only the Cargo.toml and all just works. However you end up with useless files in target so I recommend deleting those anyway.


问:
TextField returning null
Every time I type some text in the textField and click the button, to trigger the save () method the text field returns null. What could be causing this?

```<code>@FXM
private TextField nome = new TextField();

public void save() {
    Model model = new Model();
    model.setNome(nome.getText());
    model.setStatus(status.getSelectedToggle().isSelected());
}

public void initialize(URL location, ResourceBundle resources) {

    ModelController modelController = new ModelController();
    btnSalvar.setOnAction(event -> modelController.save());
    border.setCenter(modelController.onScreen());
}
</code>```

答:
The problem is with this line:

```<code>@FXM
private TextField nome = new TextField();
</code>```

When you do that you are replacing the reference to the object displayed on screen, to a new one you created. If you want to reference an object created through FXML simply use:

```<code>@FXML
private TextField nome;
</code>```

the TextField in the FXML file should have an fx:id matching the name of your variable:

```<code><TextField fx:id="nome" />
</code>```

Title: TextField returning null

Body:
Every time I type some text in the textField and click the button, to trigger the save () method the text field returns null. What could be causing this?

@FXM
private TextField nome = new TextField();

public void save() {
    Model model = new Model();
    model.setNome(nome.getText());
    model.setStatus(status.getSelectedToggle().isSelected());
}

public void initialize(URL location, ResourceBundle resources) {

    ModelController modelController = new ModelController();
    btnSalvar.setOnAction(event -> modelController.save());
    border.setCenter(modelController.onScreen());
}

Body:
The problem is with this line:

@FXM
private TextField nome = new TextField();

When you do that you are replacing the reference to the object displayed on screen, to a new one you created. If you want to reference an object created through FXML simply use:

@FXML
private TextField nome;

the TextField in the FXML file should have an fx:id matching the name of your variable:

<TextField fx:id="nome" />


问:
Best way to dynamically get column names from oracle tables
We are using an extractor application that will export data from the database to csv files. Based on some condition variable it extracts data from different tables, and for some conditions we have to use UNION ALL as the data has to be extracted from more than one table. So to satisfy the UNION ALL condition we are using nulls to match the number of columns.

Right now all the queries in the system are pre-built based on the condition variable. The problem is whenever there is change in the table projection (i.e new column added, existing column modified, column dropped) we have to manually change the code in the application.

Can you please give some suggestions how to extract the column names dynamically so that any changes in the table structure do not require change in the code?

My concern is the condition that decides which table to query. The variable condition is
like

if the condition is A, then load from TableX

if the condition is B  then load from TableA and TableY.

We must know from which table we need to get data.  Once we know the table it is  straightforward to query the column names from the data dictionary.  But there is one more condition, which is that some columns need to be excluded, and these columns are different for each table.

I am trying to solve the problem only for dynamically generating the list columns. But my manager told me to make solution on the conceptual level rather than just fixing. This is a very big system with providers and consumers constantly loading and consuming data. So he wanted solution that can be general.

So what is the best way for storing condition, tablename, excluded columns?  One way is storing in database.   Are there any other ways? If yes what is the best?  As I have to give at least a couple of ideas before finalizing.

Thanks,

答:
MNC,

How about creating a dictionary of all the known tables involved in the application process up front (irrespective of the combinations - just a dictionary of the tables) which is keyed on tablename. the members of this dictionary would be a IList<string> of the column names. This would allow you to compare two tables on both the number of columns present dicTable[myVarTableName].Count as well as iterating round the dicTable[myVarTableName].value to pull out the column names.

At the end of the piece, you could do a little linq function to determine the table with the greatest number of columns and create the structure with nulls accordingly.

Hope this gives food for thought..

ContentLicense: CC BY-SA 2.5


问:
Setting scrolling on a specific portion of the webpage
https://plnkr.co/edit/FvCTLHHfQA9KNAlfVYAP?p=preview

```<code><clr-main-container>
 <div class="content-container">
  <div class="content-area">
   <div class="row">
    <div class="col-xs-9" style="height:100%; border-right: 1px solid rgb(204, 204, 204); padding-right:0; overflow-y: auto;">
      <div class="container">
        left column
        <clr-tabs (clrTabsCurrentTabLinkChanged)="onTabSelected($event)" (clrTabsCurrentTabIndexChanged)="onTabIndexChanged($event)" (clrTabsCurrentTabContentChanged)="onTabContentActivated($event)">
          <clr-tab-link [clrTabLinkActive]="true">Tab 1</clr-tab-link>
            <clr-tab-content [clrTabContentActive]="true" style="overflow-y: auto;">
              SOME VERY LONG CONTENT THAT EXCEEDS 100vh in height;
            </clr-tab-content>
          <clr-tabs>
        </div>
    </div>
    <div class="col-xs">
      right column
    </div>
   </div>
  </div>
 </div>
</clr-main-container>
</code>```

I am trying to implement a layout such that the height of my html document is always 100vh, and if the content of a particular tab exceeds that height, then it should scroll instead of overshoot the length. However, in my implementation, the scroll behavior is getting applied to the entire page, instead of just the tab content.

What are some better ways of doing this? I have been able to identify that setting a height value to my content manually correctly sets the scroll behavior, however, I do not think that setting a height manually is the most optimum way of designing this layout. If my content div knew the height of the parent and stretched itself all the way to the bottom, maybe that might solve my problem. I am not too sure though.

答:
https://github.com/jamesflorentino/nanoScrollerJS

https://jamesflorentino.github.io/nanoScrollerJS/

There are many scroll plugins but You must test it for mobiles.

Body:
https://plnkr.co/edit/FvCTLHHfQA9KNAlfVYAP?p=preview

<clr-main-container>

        left column
        <clr-tabs (clrTabsCurrentTabLinkChanged)="onTabSelected($event)" (clrTabsCurrentTabIndexChanged)="onTabIndexChanged($event)" (clrTabsCurrentTabContentChanged)="onTabContentActivated($event)">
          <clr-tab-link [clrTabLinkActive]="true">Tab 1</clr-tab-link>
            <clr-tab-content [clrTabContentActive]="true" style="overflow-y: auto;">
              SOME VERY LONG CONTENT THAT EXCEEDS 100vh in height;
            </clr-tab-content>
          <clr-tabs>

      right column

</clr-main-container>

I am trying to implement a layout such that the height of my html document is always 100vh, and if the content of a particular tab exceeds that height, then it should scroll instead of overshoot the length. However, in my implementation, the scroll behavior is getting applied to the entire page, instead of just the tab content.

What are some better ways of doing this? I have been able to identify that setting a height value to my content manually correctly sets the scroll behavior, however, I do not think that setting a height manually is the most optimum way of designing this layout. If my content div knew the height of the parent and stretched itself all the way to the bottom, maybe that might solve my problem. I am not too sure though.


问:
Rails Stripe Retrieve ID Error "No such plan"
So my Plan says Stripe::InvalidRequestError at /orders/26/payments

No such plan: The title of my plan.

This code should check if the the plan already exists and if not create it and subscribe the user to it. I thought this worked because it was working for the case where I already had a plan with the same ID and it said "Plan already exists". How can I prevent this Error from happening?

This is my code:

```<code>class PaymentsController < ApplicationController
  before_action :set_order

  def new
  end

  def create
   @user = current_user

   customer = Stripe::Customer.create(
   source: params[:stripeToken],
   email:  params[:stripeEmail],
   )

# Storing the customer.id in the customer_id field of user
  @user.customer_id = customer.id

   @plan = Stripe::Plan.retrieve(@order.service.title)
    unless @plan
     plan = Stripe::Plan.create(
      :name => @order.service.title,
      :id => @order.service.title,
      :interval => "month",
      :currency => @order.amount.currency,
      :amount => @order.amount_pennies,
      )
    else
     subscription = Stripe::Subscription.create(
       :customer => @user.customer_id,
       :plan => @order.service.title
      )
    end

  @order.update(payment: plan.to_json, state: 'paid')
  redirect_to order_path(@order)

  rescue Stripe::CardError => e
  flash[:error] = e.message
  redirect_to new_order_payment_path(@order)

  end

  private

  def set_order
    @order = Order.where(state: 'pending').find(params[:order_id])
  end

end
</code>```

答:
The documentation says that if you try to retrieve a plan that does not exist, it will raise an error. So you just need to catch the error:</p>

```<code>begin
  @plan = Stripe::Plan.retrieve(@order.service.title)
rescue
  @plan = Stripe::Plan.create(...)
end
</code>```

Body:
So my Plan says Stripe::InvalidRequestError at /orders/26/payments

No such plan: The title of my plan.

This code should check if the the plan already exists and if not create it and subscribe the user to it. I thought this worked because it was working for the case where I already had a plan with the same ID and it said "Plan already exists". How can I prevent this Error from happening?

This is my code:

class PaymentsController < ApplicationController
  before_action :set_order

  def new
  end

  def create
   @user = current_user

   customer = Stripe::Customer.create(
   source: params[:stripeToken],
   email:  params[:stripeEmail],
   )

# Storing the customer.id in the customer_id field of user
  @user.customer_id = customer.id

   @plan = Stripe::Plan.retrieve(@order.service.title)
    unless @plan
     plan = Stripe::Plan.create(
      :name => @order.service.title,
      :id => @order.service.title,
      :interval => "month",
      :currency => @order.amount.currency,
      :amount => @order.amount_pennies,
      )
    else
     subscription = Stripe::Subscription.create(
       :customer => @user.customer_id,
       :plan => @order.service.title
      )
    end

  @order.update(payment: plan.to_json, state: 'paid')
  redirect_to order_path(@order)

  rescue Stripe::CardError => e
  flash[:error] = e.message
  redirect_to new_order_payment_path(@order)

  end

  private

  def set_order
    @order = Order.where(state: 'pending').find(params[:order_id])
  end

end

Body:
The documentation says that if you try to retrieve a plan that does not exist, it will raise an error. So you just need to catch the error:

begin
  @plan = Stripe::Plan.retrieve(@order.service.title)
rescue
  @plan = Stripe::Plan.create(...)
end


问:
Prestashop cash on delivery fee
I am a bit new in prestashop and I have following question.

I am using prestashop 1.6 and I would like to add fee when costumer wants to pay with Cash on delivery. I tried to use some of free modules, but they didn't add fee to final price, so prices listed in back office were without fee.

Thanks for help in advance.

答:
you can use following paid and free module that will allow you to add charges on cash on delivery
https://www.prestashop.com/forums/topic/75458-module-cash-on-delivery-cod-v05-with-fixed-and-percentage-fees/page-11

https://addons.prestashop.com/en/collect-on-delivery-cod/6337-cash-on-delivery-with-fee-surcharge-plus-cod.html

Title: Prestashop cash on delivery fee


问:
how validation works in mongoose
I was reading documentation of mongoose: http://mongoosejs.com/docs/guide.html

It is said that validation occurs before saving document in the database.

And to turn this feature off we have to set option: validateBeforeSave to false.

However I have another decent Node.js tutorial example where they just use .validate as follows:

```<code>      var course = new Course({});

      course.validate(function(err) {
        assert.ok(err);
        assert.equal(err.errors['title'].kind, 'required');

        course.title = 'Introduction to Computer Science';
        assert.equal(course.title, 'Introduction to Computer Science');

        var s = '0123456789';
        course.title = '';
        while (course.title.length < 150) {
          course.title += s;
        }

        course.validate(function(err) {
          assert.ok(err);
          assert.equal(err.errors['title'].kind, 'maxlength');

          ++succeeded;
          done();
        });
      });
</code>```

I can't understand the underlying reason for using validate without setting validateBeforeSave option to false? Could someone please clarify how the provided code above works?

答:
As you said mongoose is fireing up validation before save operation, but there are some cases when you want to validate document schema without save. For this you can use validate method directly.
Your example from tutorial show us piece of code representing unit tests. So for example we can check methods which generate some model to save without saving him.
Also validate method could help when you have complicated action flow with many saves and dependencies. For example you want to save user dashboard model with proper structure but firstly you saving user profile. With validate method and for instance wrong dashboard structure you can check request and throw exception before saving user profile.</p>

Title: how validation works in mongoose

Body:
I was reading documentation of mongoose: http://mongoosejs.com/docs/guide.html

It is said that validation occurs before saving document in the database.

And to turn this feature off we have to set option: validateBeforeSave to false.

However I have another decent Node.js tutorial example where they just use .validate as follows:

      var course = new Course({});

      course.validate(function(err) {
        assert.ok(err);
        assert.equal(err.errors['title'].kind, 'required');

        course.title = 'Introduction to Computer Science';
        assert.equal(course.title, 'Introduction to Computer Science');

        var s = '0123456789';
        course.title = '';
        while (course.title.length < 150) {
          course.title += s;
        }

        course.validate(function(err) {
          assert.ok(err);
          assert.equal(err.errors['title'].kind, 'maxlength');

          ++succeeded;
          done();
        });
      });

I can't understand the underlying reason for using validate without setting validateBeforeSave option to false? Could someone please clarify how the provided code above works?


问:
How to push child arrays into items in an array to local React state, via a Firebase snapshot
The state in this little app is set by looping over the items in a Firebase snapshot (array). I can't figure out how to output a nested (child) array in this way. My gut says it's a regular JS function that I'm not thinking of like map and that I'm confused based on learning the syntax for state. I'd love some help in figuring out how to push the sessions arrays into state with each exercise.

Screenshot of the data structure in Firebase: [http://i.imgur.com/FlS054T.png]

```<code>componentDidMount () {
const exercisesRef = firebase.database().ref('exercises')
exercisesRef.on('value', snapshot => {
  let exercises = snapshot.val()
  let newState = []
  for (let exercise in exercises) {
    newState.push({
      id: exercise,
      title: exercises[exercise].title,
      setting: exercises[exercise].setting,
      settingType: exercises[exercise].settingType,
      reps: exercises[exercise].reps,
      raiseAfter: exercises[exercise].raiseAfter,
      raiseBy: exercises[exercise].raiseBy
    })
  }
  this.setState({
    exercises: newState
  })
})
</code>```

}

Thank you in advance for any help you can give!

答:
Based on the JSON formatting that you provided, it seems like

```<code>let exercise in exercises
</code>```

is providing you with each exercise as an object.

If that's the case, you should be able to just push exercise into newState directly, which would give you access to the sessions object within the exercise object.

Body:
The state in this little app is set by looping over the items in a Firebase snapshot (array). I can't figure out how to output a nested (child) array in this way. My gut says it's a regular JS function that I'm not thinking of like map and that I'm confused based on learning the syntax for state. I'd love some help in figuring out how to push the sessions arrays into state with each exercise.

Screenshot of the data structure in Firebase: [http://i.imgur.com/FlS054T.png]

componentDidMount () {
const exercisesRef = firebase.database().ref('exercises')
exercisesRef.on('value', snapshot => {
  let exercises = snapshot.val()
  let newState = []
  for (let exercise in exercises) {
    newState.push({
      id: exercise,
      title: exercises[exercise].title,
      setting: exercises[exercise].setting,
      settingType: exercises[exercise].settingType,
      reps: exercises[exercise].reps,
      raiseAfter: exercises[exercise].raiseAfter,
      raiseBy: exercises[exercise].raiseBy
    })
  }
  this.setState({
    exercises: newState
  })
})

}

Thank you in advance for any help you can give!

Body:
Based on the JSON formatting that you provided, it seems like

let exercise in exercises

is providing you with each exercise as an object.

If that's the case, you should be able to just push exercise into newState directly, which would give you access to the sessions object within the exercise object.


问:
ListView inside a ListItem displays only one entry
Inside my original Activity, I initialize an Adapter to populate a ListView and that goes smoothly. ArrayList populated with all the data gets passed as an argument to the Adapter and everything goes well.

Now inside that Adapter, or that ListView that gets populated, there's another ListView and another Adapter for it.

Again, I follow the same procedure and populate the Adapter with an ArrayList, but it seems as though only the first entry gets displayed in the nested ListView. I assume this is is because the parent ListView gets populated and the data for the child ListView only populates for one parents entry.

Anyway, here's the adapter initialization and the Adapter class:

```<code>    PlayerSeasonsStatsAdapter pssAdapter = new PlayerSeasonsStatsAdapter(getContext(), alPlayerSeasonsStats);
            vh.lvPlayerSeasonsStats.setAdapter(pssAdapter);
</code>```

alPlayerSeasonsStats is an ArrayList containing data to populate the child ListView.

Here's the child Adapter:

```<code>public class PlayerSeasonsStatsAdapter extends ArrayAdapter{
    private ArrayList<PlayerStatsTeamModelSeasons> playerSeasons = new ArrayList<PlayerStatsTeamModelSeasons>();
    private LayoutInflater mInflater;

    public PlayerSeasonsStatsAdapter(Context context, ArrayList<PlayerStatsTeamModelSeasons> playerSeasons) {
        super(context, 0, playerSeasons);
        this.playerSeasons = playerSeasons;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public PlayerStatsTeamModelSeasons getItem(int position) {
        return playerSeasons.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.player_seasons_stats_row, parent, false);
            vh = new ViewHolder();
            vh.tvPSSRCompetition = (TextView) convertView.findViewById(R.id.tvPSSRCompetition);
            vh.tvPSSRMatchesPlayed = (TextView) convertView.findViewById(R.id.tvPSSRMatchesPlayed);
            vh.tvPSSRGoalsScored = (TextView) convertView.findViewById(R.id.tvPSSRGoalsScored);
            vh.tvPSSRAssists = (TextView) convertView.findViewById(R.id.tvPSSRAssists);
            vh.tvPSSRYellowCards = (TextView) convertView.findViewById(R.id.tvPSSRYellowCards);
            vh.tvPSSRRedCards = (TextView) convertView.findViewById(R.id.tvPSSRRedCards);
            vh.ivPSSRCompetitionLogo = (ImageView) convertView.findViewById(R.id.ivPSSRCompetitionLogo);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();

        }
        PlayerStatsTeamModelSeasons pstmsModel = getItem(position);

        vh.tvPSSRCompetition.setText(pstmsModel.pstmSeasonModel.name);
        vh.tvPSSRMatchesPlayed.setText(pstmsModel.pstmsModel.matchesPlayed);
        vh.tvPSSRGoalsScored.setText(pstmsModel.pstmsModel.goalsScored);
        vh.tvPSSRAssists.setText(pstmsModel.pstmsModel.assists);
        vh.tvPSSRYellowCards.setText(pstmsModel.pstmsModel.yellowCards);
        int totalRedCards = Integer.parseInt(pstmsModel.pstmsModel.yellowRedCards) + Integer.parseInt(pstmsModel.pstmsModel.redCards);
        vh.tvPSSRRedCards.setText(totalRedCards + "");
        //loadLogoToView(vh.ivPSSRCompetitionLogo, pstmsModel.pstmSeasonModel.id, true);
        return convertView;
    }

    public static void loadLogoToView(ImageView iv, String teamId, boolean transform) {
        String image = Constant.IMAGES_ROOT +
                Constant.LOGO_PATH +
                teamId +
                Constant.LOGO_EXTENSION;
        RequestCreator img = Picasso.with(iv.getContext())
                .load(image);
        if (transform) img.transform(new RoundedCornersTransform(2));
        img.into(iv);
    }

    static class ViewHolder {
        ImageView ivPSSRCompetitionLogo;
        TextView tvPSSRCompetition;
        TextView tvPSSRMatchesPlayed;
        TextView tvPSSRGoalsScored;
        TextView tvPSSRAssists;
        TextView tvPSSRYellowCards;
        TextView tvPSSRRedCards;
    }
</code>```

What are my options here?

答:
Your Adapter should be look like

```<code>public class PlayerSeasonsStatsAdapter extends ArrayAdapter<PlayerStatsTeamModelSeasons> {

private  class ViewHolder {
    TextView tvPSSRCompetition;
}

public PlayerSeasonsStatsAdapter(Context context, List<PlayerStatsTeamModelSeasons> balanceModels) {

    super(context, R.layout.row_account_balance, balanceModels);

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

    PlayerStatsTeamModelSeasons model = getItem(position);

    PlayerSeasonsStatsAdapter.ViewHolder viewHolder;
    if (convertView == null) {

        viewHolder = new PlayerSeasonsStatsAdapter.ViewHolder();

        LayoutInflater inflater = LayoutInflater.from(getContext());

        convertView = inflater.inflate(R.layout.row_account_balance, parent, false);

        viewHolder.tvPSSRCompetition = (TextView) convertView.findViewById(R.id.tvPSSRCompetition);
        convertView.setTag(viewHolder);

    } else {

        viewHolder = (PlayerSeasonsStatsAdapter.ViewHolder) convertView.getTag();
    }
    viewHolder.tvPSSRCompetition.setText(model.getPSSRCompetition());

    if (position%2== 0) {
        convertView.setBackgroundColor(Color.parseColor("#F5EEE5"));
    }else{

        convertView.setBackgroundColor(Color.parseColor("#FFFFFF"));
    }

    return convertView;

   }

  }
</code>```

Just Call below like

```<code>   PlayerSeasonsStatsAdapter adapter = new PlayerSeasonsStatsAdapter(MainActivity.this, balanceList);
   listView.setAdapter(adapter);
</code>```

Listview Look like bellow

```<code>        <ListView
         android:id="@+id/listView"
          android:layout_width="match_parent"
           android:layout_height="match_parent" />
        </LinearLayout>
</code>```

here is row_account_balance layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"  >

    <TextView
        android:id="@+id/tvPSSRCompetition"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center|center_vertical|center_horizontal"
        android:text="@string/agent_statement_sl"
        android:textStyle="bold"
        android:paddingLeft="2dp"
        android:textSize="16sp"
        android:paddingBottom="5dp"
        android:paddingTop="5dp"/>
</LinearLayout>
</code>```

Body:
Inside my original Activity, I initialize an Adapter to populate a ListView and that goes smoothly. ArrayList populated with all the data gets passed as an argument to the Adapter and everything goes well.

Now inside that Adapter, or that ListView that gets populated, there's another ListView and another Adapter for it.

Again, I follow the same procedure and populate the Adapter with an ArrayList, but it seems as though only the first entry gets displayed in the nested ListView. I assume this is is because the parent ListView gets populated and the data for the child ListView only populates for one parents entry.

Anyway, here's the adapter initialization and the Adapter class:

    PlayerSeasonsStatsAdapter pssAdapter = new PlayerSeasonsStatsAdapter(getContext(), alPlayerSeasonsStats);
            vh.lvPlayerSeasonsStats.setAdapter(pssAdapter);

alPlayerSeasonsStats is an ArrayList containing data to populate the child ListView.

Here's the child Adapter:

public class PlayerSeasonsStatsAdapter extends ArrayAdapter{
    private ArrayList<PlayerStatsTeamModelSeasons> playerSeasons = new ArrayList<PlayerStatsTeamModelSeasons>();
    private LayoutInflater mInflater;

    public PlayerSeasonsStatsAdapter(Context context, ArrayList<PlayerStatsTeamModelSeasons> playerSeasons) {
        super(context, 0, playerSeasons);
        this.playerSeasons = playerSeasons;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public PlayerStatsTeamModelSeasons getItem(int position) {
        return playerSeasons.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.player_seasons_stats_row, parent, false);
            vh = new ViewHolder();
            vh.tvPSSRCompetition = (TextView) convertView.findViewById(R.id.tvPSSRCompetition);
            vh.tvPSSRMatchesPlayed = (TextView) convertView.findViewById(R.id.tvPSSRMatchesPlayed);
            vh.tvPSSRGoalsScored = (TextView) convertView.findViewById(R.id.tvPSSRGoalsScored);
            vh.tvPSSRAssists = (TextView) convertView.findViewById(R.id.tvPSSRAssists);
            vh.tvPSSRYellowCards = (TextView) convertView.findViewById(R.id.tvPSSRYellowCards);
            vh.tvPSSRRedCards = (TextView) convertView.findViewById(R.id.tvPSSRRedCards);
            vh.ivPSSRCompetitionLogo = (ImageView) convertView.findViewById(R.id.ivPSSRCompetitionLogo);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();

        }
        PlayerStatsTeamModelSeasons pstmsModel = getItem(position);

        vh.tvPSSRCompetition.setText(pstmsModel.pstmSeasonModel.name);
        vh.tvPSSRMatchesPlayed.setText(pstmsModel.pstmsModel.matchesPlayed);
        vh.tvPSSRGoalsScored.setText(pstmsModel.pstmsModel.goalsScored);
        vh.tvPSSRAssists.setText(pstmsModel.pstmsModel.assists);
        vh.tvPSSRYellowCards.setText(pstmsModel.pstmsModel.yellowCards);
        int totalRedCards = Integer.parseInt(pstmsModel.pstmsModel.yellowRedCards) + Integer.parseInt(pstmsModel.pstmsModel.redCards);
        vh.tvPSSRRedCards.setText(totalRedCards + "");
        //loadLogoToView(vh.ivPSSRCompetitionLogo, pstmsModel.pstmSeasonModel.id, true);
        return convertView;
    }

    public static void loadLogoToView(ImageView iv, String teamId, boolean transform) {
        String image = Constant.IMAGES_ROOT +
                Constant.LOGO_PATH +
                teamId +
                Constant.LOGO_EXTENSION;
        RequestCreator img = Picasso.with(iv.getContext())
                .load(image);
        if (transform) img.transform(new RoundedCornersTransform(2));
        img.into(iv);
    }

    static class ViewHolder {
        ImageView ivPSSRCompetitionLogo;
        TextView tvPSSRCompetition;
        TextView tvPSSRMatchesPlayed;
        TextView tvPSSRGoalsScored;
        TextView tvPSSRAssists;
        TextView tvPSSRYellowCards;
        TextView tvPSSRRedCards;
    }

What are my options here?

Body:
Your Adapter should be look like

public class PlayerSeasonsStatsAdapter extends ArrayAdapter<PlayerStatsTeamModelSeasons> {

private  class ViewHolder {
    TextView tvPSSRCompetition;
}

public PlayerSeasonsStatsAdapter(Context context, List<PlayerStatsTeamModelSeasons> balanceModels) {

    super(context, R.layout.row_account_balance, balanceModels);

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

    PlayerStatsTeamModelSeasons model = getItem(position);

    PlayerSeasonsStatsAdapter.ViewHolder viewHolder;
    if (convertView == null) {

        viewHolder = new PlayerSeasonsStatsAdapter.ViewHolder();

        LayoutInflater inflater = LayoutInflater.from(getContext());

        convertView = inflater.inflate(R.layout.row_account_balance, parent, false);

        viewHolder.tvPSSRCompetition = (TextView) convertView.findViewById(R.id.tvPSSRCompetition);
        convertView.setTag(viewHolder);

    } else {

        viewHolder = (PlayerSeasonsStatsAdapter.ViewHolder) convertView.getTag();
    }
    viewHolder.tvPSSRCompetition.setText(model.getPSSRCompetition());

    if (position%2== 0) {
        convertView.setBackgroundColor(Color.parseColor("#F5EEE5"));
    }else{

        convertView.setBackgroundColor(Color.parseColor("#FFFFFF"));
    }

    return convertView;

   }

  }

Just Call below like

   PlayerSeasonsStatsAdapter adapter = new PlayerSeasonsStatsAdapter(MainActivity.this, balanceList);
   listView.setAdapter(adapter);

Listview Look like bellow

        <ListView
         android:id="@+id/listView"
          android:layout_width="match_parent"
           android:layout_height="match_parent" />
        </LinearLayout>

here is row_account_balance layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"  >

    <TextView
        android:id="@+id/tvPSSRCompetition"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center|center_vertical|center_horizontal"
        android:text="@string/agent_statement_sl"
        android:textStyle="bold"
        android:paddingLeft="2dp"
        android:textSize="16sp"
        android:paddingBottom="5dp"
        android:paddingTop="5dp"/>
</LinearLayout>


问:
How to display date and time value in JSF's data table?
Data table in JSF displays the value of time stamp data type in MON dd,YYYY. But I also want to include hh:mm:ss. Please help.</p>

答:
You can display date and time in datatable similar to following example:</p>

```<code><p:column id="activityDate" headerText="#{msg.date}">
    <h:outputText value="#{res.activityDate}">
        <f:convertDateTime timeZone="#{referenceData.timezone}"
            pattern="MMM dd, yyyy HH:mm:ss" />
    </h:outputText>
</p:column>
</code>```

Body:
You can display date and time in datatable similar to following example:

<p:column id="activityDate" headerText="#{msg.date}">
    <h:outputText value="#{res.activityDate}">
        <f:convertDateTime timeZone="#{referenceData.timezone}"
            pattern="MMM dd, yyyy HH:mm:ss" />
    </h:outputText>
</p:column>


问:
How to diff a commit with its parent
Aside from writing an alias or script, is there a shorter command for getting the diff for a particular commit?

```<code>git diff 15dc8^..15dc8
</code>```

If you only give the single commit id git diff 15dc8, it diffs that commit against HEAD.

答:
Use:

```<code>git diff 15dc8^!
</code>```

as described in the following fragment of git-rev-parse(1) man page (or in modern Git gitrevisions(7) man page):

Two other shorthands for naming a set that is formed by a commit and its
parent commits exist. The r1^@ notation means all  parents of r1.  r1^!
includes commit r1 but excludes all of its parents.

This means that you can use 15dc8^! as a shorthand for 15dc8^..15dc8 anywhere in Git where revisions are needed.  For the diff command, the git diff 15dc8^..15dc8 is understood as git diff 15dc8^ 15dc8, which means the difference between parent of commit (15dc8^) and commit (15dc8).

Note: the description in git-rev-parse(1) man page talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^! is "r1 --not r1^@" i.e. "r1 ^r1^1 ^r1^2 ..."

Also, you can use git show COMMIT to get the commit description and diff for a commit. If you want only the diff, you can use git diff-tree -p COMMIT.

OwnerDisplayName: Brian Lindauer

Title: How to diff a commit with its parent

Body:
Aside from writing an alias or script, is there a shorter command for getting the diff for a particular commit?

git diff 15dc8^..15dc8

If you only give the single commit id git diff 15dc8, it diffs that commit against HEAD.

Body:
Use:

git diff 15dc8^!

as described in the following fragment of git-rev-parse(1) man page (or in modern Git gitrevisions(7) man page):

Two other shorthands for naming a set that is formed by a commit and its
parent commits exist. The r1^@ notation means all  parents of r1.  r1^!
includes commit r1 but excludes all of its parents.

This means that you can use 15dc8^! as a shorthand for 15dc8^..15dc8 anywhere in Git where revisions are needed.  For the diff command, the git diff 15dc8^..15dc8 is understood as git diff 15dc8^ 15dc8, which means the difference between parent of commit (15dc8^) and commit (15dc8).

Note: the description in git-rev-parse(1) man page talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^! is "r1 --not r1^@" i.e. "r1 ^r1^1 ^r1^2 ..."

Also, you can use git show COMMIT to get the commit description and diff for a commit. If you want only the diff, you can use git diff-tree -p COMMIT.

OwnerDisplayName: Jakub Narębski


问:
XPath to return default value if node not present
Say I have a pair of XML documents

```<code><Foo>
    <Bar/>
    <Baz>mystring</Baz>
</Foo>
</code>```

and

```<code><Foo>
    <Bar/>
</Foo>
</code>```

I want an XPath (Version 1.0 only) that returns "mystring" for the first document and "not-found" for the second. I tried

```<code>(string('not-found') | //Baz)[last()]
</code>```

but the left hand side of the union isn't a node-set

答:
@Alejandro provided the best XPath 1.0 answer, which has been known for years, since first used by Jeni Tennison almost ten years ago.

The only problem with this expression is its shiny elegance, which makes it difficult to understand by not only novice programmers.

In a hosted XPath 1.0 (and every XPath is hosted!) one can use more understandable expressions:

```<code>string((/Foo/Baz | $vDefaults[not(/Foo/Baz/text())]/Foo/Baz)[last())
</code>```

Here the variable $vDefaults is a separate document that has the same structure as the primary XML document, and whose text nodes contain default values.

Or, if XSLT is the hosting language, one can use the document() function:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my">
 <xsl:output  method="text"/>

 <my:defaults>
    <Foo>
        <Bar/>
        <Baz>not-found</Baz>
  </Foo>
 </my:defaults>

 <xsl:template match="/">
     <xsl:value-of select=
     "concat(/Foo/Baz,
           document('')[not(current()/Foo/Baz/text())]
                                        /*/my:defaults/Foo/Baz
           )"/>
 </xsl:template>
</xsl:stylesheet>
</code>```

Or, not using concat():

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my">
 <xsl:output  method="text"/>

 <my:defaults>
    <Foo>
        <Bar/>
        <Baz>not-found</Baz>
  </Foo>
 </my:defaults>

 <xsl:variable name="vDefaults" select="document('')/*/my:defaults"/>

 <xsl:template match="/">
     <xsl:value-of select=
     "(/Foo/Baz
       | $vDefaults/Foo/Baz[not(current()/Foo/Baz/text())]
       )
        [last()]"/>
 </xsl:template>
</xsl:stylesheet>
</code>```

Body:
Say I have a pair of XML documents

<Foo>
    <Bar/>
    <Baz>mystring</Baz>
</Foo>

and

<Foo>
    <Bar/>
</Foo>

I want an XPath (Version 1.0 only) that returns "mystring" for the first document and "not-found" for the second. I tried

(string('not-found') | //Baz)[last()]

but the left hand side of the union isn't a node-set

Body:
@Alejandro provided the best XPath 1.0 answer, which has been known for years, since first used by Jeni Tennison almost ten years ago.

The only problem with this expression is its shiny elegance, which makes it difficult to understand by not only novice programmers.

In a hosted XPath 1.0 (and every XPath is hosted!) one can use more understandable expressions:

string((/Foo/Baz | $vDefaults[not(/Foo/Baz/text())]/Foo/Baz)[last())

Here the variable $vDefaults is a separate document that has the same structure as the primary XML document, and whose text nodes contain default values.

Or, if XSLT is the hosting language, one can use the document() function:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my">
 <xsl:output  method="text"/>

 <my:defaults>
    <Foo>
        <Bar/>
        <Baz>not-found</Baz>
  </Foo>
 </my:defaults>

 <xsl:template match="/">
     <xsl:value-of select=
     "concat(/Foo/Baz,
           document('')[not(current()/Foo/Baz/text())]
                                        /*/my:defaults/Foo/Baz
           )"/>
 </xsl:template>
</xsl:stylesheet>

Or, not using concat():

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my">
 <xsl:output  method="text"/>

 <my:defaults>
    <Foo>
        <Bar/>
        <Baz>not-found</Baz>
  </Foo>
 </my:defaults>

 <xsl:variable name="vDefaults" select="document('')/*/my:defaults"/>

 <xsl:template match="/">
     <xsl:value-of select=
     "(/Foo/Baz
       | $vDefaults/Foo/Baz[not(current()/Foo/Baz/text())]
       )
        [last()]"/>
 </xsl:template>
</xsl:stylesheet>


问:
After installed Visual Studio 2010 Professional I am getting an error
I have installed VS 2010 Ultimate on Windows 7 Enterprise. It is not working. So I uninstalled that and re-install VS 2010 Professional.

But I am getting an error whenever I open Visual Studio 2010.

Error:

The 'Visual Studio Tools for Applications v3.0 Shell Integration Package' package did not load correctly.

The Problem may have been caused by a configuration change or by the installation of another extension. You can get more information by running the application together with the log parameter on the command line, and then examining the file

'C:\users\Name\AppData\Roaming\Microsoft\VisualStudio\10.0\ActivityLog.xml'.

How to fix this issue? Please help me.

答:
I ran Procmon from Sysinternals on devenv.exe with a filter set to capture file system events only, and only not equal 'success' results.

This brought up some results pointing at a directory where devenv.exe attempted to load Microsoft.VisualStudio.Tools.Applications.Package.dll from. None of those directories contained that file.

Searched for that file and found it under C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PrivateAssemblies\Microsoft.VisualStudio.Tools.Applications.Package.dll That location was not among the directories captured by Procmon.

Copied the file to the first location indicated by the error captured by Procmon and voila, problem solved.


问:
PHP & MYSQL -- how to dispaly "Already booked please select another date" message
I want to display this message "Already booked - please select another date" If two clients select the same product (pg_no)and date (Date). UNIQUE CONSTRAINT</p>

```<code><?php
//connecting string
include("dbconnect.php");

//assigning
$name=$_REQUEST['Name'];
$tele=$_REQUEST['Tele'];
$city=$_REQUEST['City'];

// UNIQUE CONSTRAINT
$pg_no=$_REQUEST['pg_no']; //product
$date=$_REQUEST['Date'];       //date

//checking if pg_no and Date are same
$check = mysqli_query($db_connect,"SELECT * FROM lstclient WHERE pg_no='{$pg_no}', Date='{$date}'");

{
    echo "Already booked please select another date<br/>";
}
//if not the insert data
else
{
    $query = mysqli_query($db_connect,"INSERT  INTO  lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}

// link closing
mysqli_close($db_connect);

// messaging
if($query)
{
    header("location:index.php?note=failed");
}
else
{
    header("location:index.php?note=success");
}
?>
</code>```

答:
To view the message on your HTML page, based on the code you have provided, you just need to set a $_GET var:

```<code><?php
if (isset($_GET['note']))
{
    if($_GET['note'] == 'failed';)
    {
        $note = "Those dates have already been booked.";
    }
    else if($_GET['note'] == 'success')
    {
        $note = "You have been booked!";
    }
}
else
{
    $note = "";
}
?>

<div class="message">
    <p class="alert">
        <?php
            if ($note != "")
            {
                echo $note;
            }
        ?>
    </p>
</div>
</code>```

That would check for a note parameter in your url and set it to $note then output it in your HTML.

You don't need to add anything to the database, you can save the request and log it so you can view which dates are the most popular.

Body:
I want to display this message "Already booked - please select another date" If two clients select the same product (pg_no)and date (Date). UNIQUE CONSTRAINT

<?php
//connecting string
include("dbconnect.php");

//assigning
$name=$_REQUEST['Name'];
$tele=$_REQUEST['Tele'];
$city=$_REQUEST['City'];

// UNIQUE CONSTRAINT
$pg_no=$_REQUEST['pg_no']; //product
$date=$_REQUEST['Date'];       //date

//checking if pg_no and Date are same
$check = mysqli_query($db_connect,"SELECT * FROM lstclient WHERE pg_no='{$pg_no}', Date='{$date}'");

{
    echo "Already booked please select another date
";
}
//if not the insert data
else
{
    $query = mysqli_query($db_connect,"INSERT  INTO  lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}

// link closing
mysqli_close($db_connect);

// messaging
if($query)
{
    header("location:index.php?note=failed");
}
else
{
    header("location:index.php?note=success");
}
?>

Body:
To view the message on your HTML page, based on the code you have provided, you just need to set a $_GET var:

<?php
if (isset($_GET['note']))
{
    if($_GET['note'] == 'failed';)
    {
        $note = "Those dates have already been booked.";
    }
    else if($_GET['note'] == 'success')
    {
        $note = "You have been booked!";
    }
}
else
{
    $note = "";
}
?>

<div class="message">
    <p class="alert">
        <?php
            if ($note != "")
            {
                echo $note;
            }
        ?>
    </p>
</div>

That would check for a note parameter in your url and set it to $note then output it in your HTML.

You don't need to add anything to the database, you can save the request and log it so you can view which dates are the most popular.


问:
set chart name in Xlwings
When I plot a chart by xlwings, I can't change chart name. The chart name and legend name are still 'Series 1', but the upper left corner shows 'Feb sales' which is I want

```<code>import xlwings as xw

sht = xw.Book().sheets[0]
sht.range('A1').value = list(zip([1, 2, 3, 4]))
chart = sht.charts.add()
chart.set_source_data(sht.range('A1').expand())
chart.chart_type = 'line_markers'
chart.name='Feb sales'
#chart.api.ChartTitle.Text = 'Feb sales'
#chart.delete()
</code>```

created chart

Is this a known issue? How can I fix this?

答:
This should work:

```<code>import xlwings as xw

sht = xw.Book().sheets[0]
sht.range('A1').value = list(zip([1, 2, 3, 4]))
chart = sht.charts.add()
chart.set_source_data(sht.range('A1').expand())
chart.chart_type = 'line_markers'

chart.api[1].SetElement(2)  # Place chart title at the top
chart.api[1].ChartTitle.Text = 'Feb sales'  # Change text of the chart title
</code>```

The expression chart.api returns a tuple with two COM wrappers. I'm not really sure why there are two COM wrappers, but it seems that you need the second one to access the chart. Hence the use of chart.api[1] here.

With the attribute xlwings.Chart.name you can set an excel chart's Name property (as you did in your question's code), but this is not a property that is used for display. To achieve display of text in the chart you need to set the excel chart's ChartTitle property (as done in this answer's code).

Title: set chart name in Xlwings

Body:
When I plot a chart by xlwings, I can't change chart name. The chart name and legend name are still 'Series 1', but the upper left corner shows 'Feb sales' which is I want

import xlwings as xw

sht = xw.Book().sheets[0]
sht.range('A1').value = list(zip([1, 2, 3, 4]))
chart = sht.charts.add()
chart.set_source_data(sht.range('A1').expand())
chart.chart_type = 'line_markers'
chart.name='Feb sales'
#chart.api.ChartTitle.Text = 'Feb sales'
#chart.delete()

created chart

Is this a known issue? How can I fix this?

Body:
This should work:

import xlwings as xw

sht = xw.Book().sheets[0]
sht.range('A1').value = list(zip([1, 2, 3, 4]))
chart = sht.charts.add()
chart.set_source_data(sht.range('A1').expand())
chart.chart_type = 'line_markers'

chart.api[1].SetElement(2)  # Place chart title at the top
chart.api[1].ChartTitle.Text = 'Feb sales'  # Change text of the chart title

The expression chart.api returns a tuple with two COM wrappers. I'm not really sure why there are two COM wrappers, but it seems that you need the second one to access the chart. Hence the use of chart.api[1] here.

With the attribute xlwings.Chart.name you can set an excel chart's Name property (as you did in your question's code), but this is not a property that is used for display. To achieve display of text in the chart you need to set the excel chart's ChartTitle property (as done in this answer's code).


问:
BigQuery : Scalar Subquery produced more than one - Custom Dimensions
Im trying to get a custom dimension into my one of my unions, but im getting a issue with scalar sub query produced more than one element. I believe the issue lies within this code.  Im trying to migrate across to standard SQL so please give answer in standard SQL.

```<code>SELECT
      d.value
FROM
      UNNEST(hits) AS hits,
      UNNEST(hits.customDimensions) AS d
WHERE
      d.index = 65) AS viewID,
</code>```

Overall example of the query

```<code>#standardSQL
SELECT
  date,
  channelGrouping,
  viewID,
  SUM(Revenue) Revenue,
  SUM(Shipping) Shipping,
  SUM(bounces) bounces,
  SUM(transactions) transactions,
  COUNT(date) sessions
FROM (
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    (
    SELECT
      d.value
    FROM
      UNNEST(hits) AS hits,
      UNNEST(hits.customDimensions) AS d
    WHERE
      d.index = 65) AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703' )
GROUP BY
  date,
  channelGrouping,
  viewID
</code>```

答:
The problem is that some or all hits have a custom dimension with an index of 65. There are a few different ways to address this. You can use an ARRAY subquery to get all of the values with that index:

```<code>ARRAY(
  SELECT
    d.value
  FROM
    UNNEST(hits) AS hits,
    UNNEST(hits.customDimensions) AS d
  WHERE
    d.index = 65) AS viewIDs,
</code>```

This will give you all view IDs across hits, but you would need to use an array for viewID in the first query of the union as well. Another option is just to get the view ID from the first hit:

```<code>(
  SELECT
    d.value
  FROM
    UNNEST(hits[SAFE_OFFSET(0)].customDimensions) AS d
  WHERE
    d.index = 65) AS viewID
</code>```

Or, if you don't care which view ID you get, you could use a LIMIT to get an arbitrary ID:

```<code>(
  SELECT
    d.value
  FROM
    UNNEST(hits) AS hits,
    UNNEST(hits.customDimensions) AS d
  WHERE
    d.index = 65
  LIMIT 1) AS viewID,
</code>```

Body:
Im trying to get a custom dimension into my one of my unions, but im getting a issue with scalar sub query produced more than one element. I believe the issue lies within this code.  Im trying to migrate across to standard SQL so please give answer in standard SQL.

SELECT
      d.value
FROM
      UNNEST(hits) AS hits,
      UNNEST(hits.customDimensions) AS d
WHERE
      d.index = 65) AS viewID,

Overall example of the query

#standardSQL
SELECT
  date,
  channelGrouping,
  viewID,
  SUM(Revenue) Revenue,
  SUM(Shipping) Shipping,
  SUM(bounces) bounces,
  SUM(transactions) transactions,
  COUNT(date) sessions
FROM (
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    (
    SELECT
      d.value
    FROM
      UNNEST(hits) AS hits,
      UNNEST(hits.customDimensions) AS d
    WHERE
      d.index = 65) AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703' )
GROUP BY
  date,
  channelGrouping,
  viewID

Body:
The problem is that some or all hits have a custom dimension with an index of 65. There are a few different ways to address this. You can use an ARRAY subquery to get all of the values with that index:

ARRAY(
  SELECT
    d.value
  FROM
    UNNEST(hits) AS hits,
    UNNEST(hits.customDimensions) AS d
  WHERE
    d.index = 65) AS viewIDs,

This will give you all view IDs across hits, but you would need to use an array for viewID in the first query of the union as well. Another option is just to get the view ID from the first hit:

(
  SELECT
    d.value
  FROM
    UNNEST(hits[SAFE_OFFSET(0)].customDimensions) AS d
  WHERE
    d.index = 65) AS viewID

Or, if you don't care which view ID you get, you could use a LIMIT to get an arbitrary ID:

(
  SELECT
    d.value
  FROM
    UNNEST(hits) AS hits,
    UNNEST(hits.customDimensions) AS d
  WHERE
    d.index = 65
  LIMIT 1) AS viewID,