问:
WooCommerce Storefront theme: How to show order details on order-received endpoint?
After the last WooCommerce update, the order details no longer displayed on the Thank You page. Since then, I have developed a child theme using the WooCommerce Storefront theme. No matter what I have tried, All I see is the 'thank you' message on the thank you page.

What I have tried so far:

Troubleshooting the entire process to find anything that might be wrong.
This included the following:

Checked for wc template function that calls the order-details template and it related action hook (both exist)

Making sure my child-theme's WooCommerce directory was correctly structured. Everything else works correctly, including my custom template fragments and their hooks.

Paying careful attention to syntax errors, including those that might silently fail.

Copied the WooCommerce directory from the plugin into the child theme. This yielded the same exact result--no order details on thank you page.

Eliminated WordPress Thank You page and used the default WooCommerce endpoint ('order-received'). NOTE: Due to the way this affected layout and display, I reverted back to my original WooCommerce directory structure, which is identical to the WooCommerce template directory, minus some of the sub-directories. (UPDATE: I actually am still using the copied WooCommerce directory)

Wrote a custom function with action hook in child theme's functions.php file, with no change in output.

In thankyou.php, created an action hook and wrote a function that used wc_get_template to call order-details, but it didn't work (silent fail)

Updated WordPress from 4.5 to 4.6.1, Updated the Storefront theme, and updated any outdated WooCommerce template files in my child theme.

```<code>Code:
**storefront-child/woocommerce/wc-template-functions.php**

if ( ! function_exists( 'woocommerce_order_details_table' ) ) {

    /**
     * Displays order details in a table.
     *
     * @param mixed $order_id
     * @subpackage  Orders
     */
    function woocommerce_order_details_table( $order_id ) {
        if ( ! $order_id ) return;

        wc_get_template( 'order/order-details.php', array(
            'order_id' => $order_id
        ) );
    }
}

**storefront-child/woocommerce/wc-template-hooks.php

/**
 * Order details.
 *
 * @see woocommerce_order_details_table()
 * @see woocommerce_order_again_button()
 */
 add_action( 'woocommerce_view_order', 'woocommerce_order_details_table', 10 );
 add_action( 'woocommerce_thankyou', 'woocommerce_order_details_table', 10 );
 add_action( 'woocommerce_order_details_after_order_table', 'woocommerce_order_again_button' );

**storefront-child/woocommerce/checkout/thankyou.php**

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( $order ) : ?>

    <?php if ( $order->has_status( 'failed' ) ) : ?>

    <p class="woocommerce-thankyou-order-failed"><?php _e( 'Unfortunately your order cannot be processed as the originating bank/merchant has declined your transaction. Please attempt your purchase again.', 'woocommerce' ); ?></p>

    <p class="woocommerce-thankyou-order-failed-actions">
        <a href="<?php echo esc_url( $order->get_checkout_payment_url() ); ?>" class="button pay"><?php _e( 'Pay', 'woocommerce' ) ?></a>
        <?php if ( is_user_logged_in() ) : ?>
            <a href="<?php echo esc_url( wc_get_page_permalink( 'myaccount' ) ); ?>" class="button pay"><?php _e( 'My Account', 'woocommerce' ); ?></a>
        <?php endif; ?>
    </p>

<?php else : ?>

    <p class="woocommerce-thankyou-order-received"><?php echo apply_filters( 'woocommerce_thankyou_order_received_text', __( 'Thank you. Your order has been received.', 'woocommerce' ), $order ); ?></p>

    <ul class="woocommerce-thankyou-order-details order_details">
        <li class="order">
            <?php _e( 'Order Number:', 'woocommerce' ); ?>
            <strong><?php echo $order->get_order_number(); ?></strong>
        </li>
        <li class="date">
            <?php _e( 'Date:', 'woocommerce' ); ?>
            <strong><?php echo date_i18n( get_option( 'date_format' ), strtotime( $order->order_date ) ); ?></strong>
        </li>
        <li class="total">
            <?php _e( 'Total:', 'woocommerce' ); ?>
            <strong><?php echo $order->get_formatted_order_total(); ?></strong>
        </li>
        <?php if ( $order->payment_method_title ) : ?>
        <li class="method">
            <?php _e( 'Payment Method:', 'woocommerce' ); ?>
            <strong><?php echo $order->payment_method_title; ?></strong>
        </li>
        <?php endif; ?>
    </ul>
    <div class="clear"></div>

<?php endif; ?>

<?php do_action( 'woocommerce_thankyou_' . $order->payment_method, $order->id ); ?>
<?php do_action( 'woocommerce_thankyou', $order->id ); ?>
</code>```

```<code><p class="woocommerce-thankyou-order-received"><?php echo apply_filters( 'woocommerce_thankyou_order_received_text', __( 'Thank you. Your order has been received.', 'woocommerce' ), null ); ?></p>

<?php endif;

?>

**storefront-child/woocommerce/order/order-details.php**

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$order = wc_get_order( $order_id );

$show_purchase_note    = $order->has_status( apply_filters( 'woocommerce_purchase_note_order_statuses', array( 'completed', 'processing' ) ) );
$show_customer_details = is_user_logged_in() && $order->get_user_id() === get_current_user_id();
?>
<h2><?php _e( 'Order Details', 'woocommerce' ); ?></h2>
<table class="shop_table order_details">
    <thead>
        <tr>
            <th class="product-name"><?php _e( 'Product', 'woocommerce' ); ?></th>
            <th class="product-total"><?php _e( 'Total', 'woocommerce' ); ?></th>
        </tr>
    </thead>
    <tbody>
    <?php
        foreach( $order->get_items() as $item_id => $item ) {
            $product = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item );

            wc_get_template( 'order/order-details-item.php', array(
                'order'              => $order,
                'item_id'            => $item_id,
                'item'               => $item,
                'show_purchase_note' => $show_purchase_note,
                'purchase_note'      => $product ? get_post_meta( $product->id, '_purchase_note', true ) : '',
                'product'            => $product,
            ) );
        }
    ?>
    <?php do_action( 'woocommerce_order_items_table', $order ); ?>
</tbody>
<tfoot>
    <?php
        foreach ( $order->get_order_item_totals() as $key => $total ) {
            ?>
            <tr>
                <th scope="row"><?php echo $total['label']; ?></th>
                <td><?php echo $total['value']; ?></td>
            </tr>
            <?php
        }
    ?>
</tfoot>
</code>```

```<code><?php if ( $show_customer_details ) : ?>
    <?php wc_get_template( 'order/order-details-customer.php',    array( 'order' =>  $order ) ); ?>
<?php endif; ?>

**Rendered HTML**
<div class="entry-content">
    <div class="mailmunch-forms-before-post" style="display: none !important;"></div>
<div class="woocommerce">
    <p class="woocommerce-thankyou-order-received">Thank you. Your order has been received.</p>
</div>

<!-- This is where the order details should be -->

<p> </p>

<div class="mailmunch-forms-in-post-middle" style="display: none !important;"></div>
<div class="mailmunch-forms-after-post" style="display: none !important;"></div>

</div>
</code>```

Am I missing something here, or is there something going on with WooCommerce? Any help would be greatly appreciated:)

UPDATE: Found that I have two versions of jQuery running: v1.11.3, and v1.12.4. There are also two different versions of jQueryUI loading: v1.10.4, and v1.11.4. Currently disabling WordPress plugins and noting what jquery versions are loading in the browser.

UPDATE: Found one plugin using jQueryUI v1.10.4. Still looking for the others.

UPDATE: Finished toubleshooting all the plugins, except WooCommerce (WSOD). MailChimp MailMunch  plugin was making the google api call to the older jquery version (v1.11.3), while the Spider Player was calling the older version of jQueryUI. De-activated both plugins, and STILL the same result.
It's as if WooCommerce is simply ignoring the order details in the middle of the thankyou.php template.

Any thoughts or ideas? I am really at a loss now. I can fix the jquery issues in the disabled plugins, but that won't fix my pressing issue with the Thank You page.

Any help would be greatly appreciated:)

UPDATE: After a lot more work, I have determined that WooCommerce IS using the child theme thankyou.php. Further troubleshooting also revealed that $order is false. This is why I am not seeing order details on the thank you page. Next: Figure why $order is false (It is an instance of WC_Order).

```<code>UPDATE: I did a stacktrace:

#0 /home/onyour6test/www/wp-content/plugins/woocommerce/includes/wc-core-functions.php(203): include()

#1 /home/onyour6test/www/wp-content/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php(212): wc_get_template('checkout/thanky...', Array)

#2 /home/onyour6test/www/wp-content/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php(59): WC_Shortcode_Checkout::order_received(NULL)

#3 /home/onyour6test/www/wp-content/plugins/woocommerce/includes/class-wc-shortcodes.php(71): WC_Shortcode_Checkout::output('')

#4 /home/onyour6test/www/wp-content/plugins/woocommerce/includes/class-wc-shortcodes.php(138): WC_Shortcodes::shortcode_wrapper(Array, '')

#5 /home/onyour6test/www/wp-includes/shortcodes.php(326): WC_Shortcodes::checkout('', '', 'woocommerce_che...')

#6 [internal function]: do_shortcode_tag(Arr in /home/onyour6test/www/wp-content/themes/storefront-child/woocommerce/checkout/thankyou.php on line 77
</code>```

I think the culprit may be in stacktrace #2: ...WC_Shortcode_Checkout::order_received(NULL).

Stacktrace #6 seems to confirm this, with do_shortcode_tag. Line 77 refers to where the call to $order fails, specifically here:

```<code><strong><? php _e( 'Order Number:', 'woocommerce' ); ?></strong>
</code>```

I managed to get this particular line of code to display, but it showed only "Order" in "Order Number", followed by a 500 internal server error. None of the rest of the remaining HTML or order-detail variables rendered on the page.

UPDATE: This appears to be something with the WooCommerce code itself. $order_id is empty, causing $order to return NULL. This prevents the order details from being displayed. This should display by default, with an option to turn it off in WooCommerce settings.

答:
The problem is $show_customer_details in order/order-details.php is set to false if the customer is not logged in.

I modified the customer check in my theme copy of order-details.php to also check if the order key (post password) matches the key that's provided as a URL parameter. This is the same check that WooCommerce performs when working out if it's okay to show the order info on the thank you page:

```<code>$order_key             = apply_filters( 'woocommerce_thankyou_order_key', empty( $_GET['key'] ) ? '' : wc_clean( $_GET['key'] ) );
$show_customer_details = $order_key == $order->get_order_key() || (is_user_logged_in() && $order->get_user_id() === get_current_user_id());
</code>```

It's not pretty but it works.

Body:
After the last WooCommerce update, the order details no longer displayed on the Thank You page. Since then, I have developed a child theme using the WooCommerce Storefront theme. No matter what I have tried, All I see is the 'thank you' message on the thank you page.

What I have tried so far:

Troubleshooting the entire process to find anything that might be wrong.
This included the following:

Checked for wc template function that calls the order-details template and it related action hook (both exist)

Making sure my child-theme's WooCommerce directory was correctly structured. Everything else works correctly, including my custom template fragments and their hooks.

Paying careful attention to syntax errors, including those that might silently fail.

Copied the WooCommerce directory from the plugin into the child theme. This yielded the same exact result--no order details on thank you page.

Eliminated WordPress Thank You page and used the default WooCommerce endpoint ('order-received'). NOTE: Due to the way this affected layout and display, I reverted back to my original WooCommerce directory structure, which is identical to the WooCommerce template directory, minus some of the sub-directories. (UPDATE: I actually am still using the copied WooCommerce directory)

Wrote a custom function with action hook in child theme's functions.php file, with no change in output.

In thankyou.php, created an action hook and wrote a function that used wc_get_template to call order-details, but it didn't work (silent fail)

Updated WordPress from 4.5 to 4.6.1, Updated the Storefront theme, and updated any outdated WooCommerce template files in my child theme.

Code:
**storefront-child/woocommerce/wc-template-functions.php**

if ( ! function_exists( 'woocommerce_order_details_table' ) ) {

    /**
     * Displays order details in a table.
     *
     * @param mixed $order_id
     * @subpackage  Orders
     */
    function woocommerce_order_details_table( $order_id ) {
        if ( ! $order_id ) return;

        wc_get_template( 'order/order-details.php', array(
            'order_id' => $order_id
        ) );
    }
}

**storefront-child/woocommerce/wc-template-hooks.php

/**
 * Order details.
 *
 * @see woocommerce_order_details_table()
 * @see woocommerce_order_again_button()
 */
 add_action( 'woocommerce_view_order', 'woocommerce_order_details_table', 10 );
 add_action( 'woocommerce_thankyou', 'woocommerce_order_details_table', 10 );
 add_action( 'woocommerce_order_details_after_order_table', 'woocommerce_order_again_button' );

**storefront-child/woocommerce/checkout/thankyou.php**

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( $order ) : ?>

    <?php if ( $order->has_status( 'failed' ) ) : ?>

<?php _e( 'Unfortunately your order cannot be processed as the originating bank/merchant has declined your transaction. Please attempt your purchase again.', 'woocommerce' ); ?>

        <a href="<?php echo esc_url( $order->get_checkout_payment_url() ); ?>" class="button pay"><?php _e( 'Pay', 'woocommerce' ) ?>
        <?php if ( is_user_logged_in() ) : ?>
            <a href="<?php echo esc_url( wc_get_page_permalink( 'myaccount' ) ); ?>" class="button pay"><?php _e( 'My Account', 'woocommerce' ); ?>
        <?php endif; ?>

<?php else : ?>

<?php echo apply_filters( 'woocommerce_thankyou_order_received_text', __( 'Thank you. Your order has been received.', 'woocommerce' ), $order ); ?>

            <?php _e( 'Order Number:', 'woocommerce' ); ?>
            <?php echo $order->get_order_number(); ?>

            <?php _e( 'Date:', 'woocommerce' ); ?>
            <?php echo date_i18n( get_option( 'date_format' ), strtotime( $order->order_date ) ); ?>

            <?php _e( 'Total:', 'woocommerce' ); ?>
            <?php echo $order->get_formatted_order_total(); ?>

        <?php if ( $order->payment_method_title ) : ?>

            <?php _e( 'Payment Method:', 'woocommerce' ); ?>
            <?php echo $order->payment_method_title; ?>

        <?php endif; ?>

<?php endif; ?>

<?php do_action( 'woocommerce_thankyou_' . $order->payment_method, $order->id ); ?>
<?php do_action( 'woocommerce_thankyou', $order->id ); ?>

<?php echo apply_filters( 'woocommerce_thankyou_order_received_text', __( 'Thank you. Your order has been received.', 'woocommerce' ), null ); ?>

<?php endif;

?>

**storefront-child/woocommerce/order/order-details.php**

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$order = wc_get_order( $order_id );

$show_purchase_note    = $order->has_status( apply_filters( 'woocommerce_purchase_note_order_statuses', array( 'completed', 'processing' ) ) );
$show_customer_details = is_user_logged_in() && $order->get_user_id() === get_current_user_id();
?>

<?php _e( 'Order Details', 'woocommerce' ); ?>

            <?php _e( 'Product', 'woocommerce' ); ?>
            <?php _e( 'Total', 'woocommerce' ); ?>

    <?php
        foreach( $order->get_items() as $item_id => $item ) {
            $product = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item );

            wc_get_template( 'order/order-details-item.php', array(
                'order'              => $order,
                'item_id'            => $item_id,
                'item'               => $item,
                'show_purchase_note' => $show_purchase_note,
                'purchase_note'      => $product ? get_post_meta( $product->id, '_purchase_note', true ) : '',
                'product'            => $product,
            ) );
        }
    ?>
    <?php do_action( 'woocommerce_order_items_table', $order ); ?>

    <?php
        foreach ( $order->get_order_item_totals() as $key => $total ) {
            ?>

                <?php echo $total['label']; ?>
                <?php echo $total['value']; ?>

            <?php
        }
    ?>

<?php if ( $show_customer_details ) : ?>
    <?php wc_get_template( 'order/order-details-customer.php',    array( 'order' =>  $order ) ); ?>
<?php endif; ?>

**Rendered HTML**

Thank you. Your order has been received.

Am I missing something here, or is there something going on with WooCommerce? Any help would be greatly appreciated:)

UPDATE: Found that I have two versions of jQuery running: v1.11.3, and v1.12.4. There are also two different versions of jQueryUI loading: v1.10.4, and v1.11.4. Currently disabling WordPress plugins and noting what jquery versions are loading in the browser.

UPDATE: Found one plugin using jQueryUI v1.10.4. Still looking for the others.

UPDATE: Finished toubleshooting all the plugins, except WooCommerce (WSOD). MailChimp MailMunch  plugin was making the google api call to the older jquery version (v1.11.3), while the Spider Player was calling the older version of jQueryUI. De-activated both plugins, and STILL the same result.
It's as if WooCommerce is simply ignoring the order details in the middle of the thankyou.php template.

Any thoughts or ideas? I am really at a loss now. I can fix the jquery issues in the disabled plugins, but that won't fix my pressing issue with the Thank You page.

Any help would be greatly appreciated:)

UPDATE: After a lot more work, I have determined that WooCommerce IS using the child theme thankyou.php. Further troubleshooting also revealed that $order is false. This is why I am not seeing order details on the thank you page. Next: Figure why $order is false (It is an instance of WC_Order).

UPDATE: I did a stacktrace:

#0 /home/onyour6test/www/wp-content/plugins/woocommerce/includes/wc-core-functions.php(203): include()

#1 /home/onyour6test/www/wp-content/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php(212): wc_get_template('checkout/thanky...', Array)

#2 /home/onyour6test/www/wp-content/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php(59): WC_Shortcode_Checkout::order_received(NULL)

#3 /home/onyour6test/www/wp-content/plugins/woocommerce/includes/class-wc-shortcodes.php(71): WC_Shortcode_Checkout::output('')

#4 /home/onyour6test/www/wp-content/plugins/woocommerce/includes/class-wc-shortcodes.php(138): WC_Shortcodes::shortcode_wrapper(Array, '')

#5 /home/onyour6test/www/wp-includes/shortcodes.php(326): WC_Shortcodes::checkout('', '', 'woocommerce_che...')

#6 [internal function]: do_shortcode_tag(Arr in /home/onyour6test/www/wp-content/themes/storefront-child/woocommerce/checkout/thankyou.php on line 77

I think the culprit may be in stacktrace #2: ...WC_Shortcode_Checkout::order_received(NULL).

Stacktrace #6 seems to confirm this, with do_shortcode_tag. Line 77 refers to where the call to $order fails, specifically here:

<? php _e( 'Order Number:', 'woocommerce' ); ?>

I managed to get this particular line of code to display, but it showed only "Order" in "Order Number", followed by a 500 internal server error. None of the rest of the remaining HTML or order-detail variables rendered on the page.

UPDATE: This appears to be something with the WooCommerce code itself. $order_id is empty, causing $order to return NULL. This prevents the order details from being displayed. This should display by default, with an option to turn it off in WooCommerce settings.

Body:
The problem is $show_customer_details in order/order-details.php is set to false if the customer is not logged in.

I modified the customer check in my theme copy of order-details.php to also check if the order key (post password) matches the key that's provided as a URL parameter. This is the same check that WooCommerce performs when working out if it's okay to show the order info on the thank you page:

$order_key             = apply_filters( 'woocommerce_thankyou_order_key', empty( $_GET['key'] ) ? '' : wc_clean( $_GET['key'] ) );
$show_customer_details = $order_key == $order->get_order_key() || (is_user_logged_in() && $order->get_user_id() === get_current_user_id());

It's not pretty but it works.


来源: stackexchange

问:
errors not showing upon editing/updating an article - following rails guide v5.1.4
This problem is specific to the example tutorials mentioned in the Getting Started guide of Rails 5.1.4

Upon following Section 5.11 [Updating Articles] from the rails getting started guide, it is expected that the line containing <% if @article.errors.any? %> in the app/views/articles/edit.html.erb file will get invoked if an article with empty title or empty text are tried to be saved. Meaning, the error messages should show up.

However, the article is prevented from getting updated (as expected) but the error messages do not show up (as not expected).

Is anyone familiar with this problem from the getting started tutorials explained in Rails Guide 5.1.4 ?

EDIT::: Following are the controller file and the view file. I have added some puts statements to print to the console

The articles_controller,rb file:

```<code>def edit
  @article = Article.find(params[:id])
end

def update
  @article = Article.find(params[:id])
  if @article.update(valid_article_params)
    puts 'article successfully updated...'
    redirect_to @article
  else
    puts 'article could not be updated...'
    render 'edit'
  end
end

private
  def valid_article_params
    params.require(:article).permit(:title, :text)
  end
</code>```

The edit.html.erb file:

```<code><h1>Edit article</h1>
<%= form_with(model: @article) do |form| %>

  <% if @article.errors.any? %>
    <% puts 'there are some errors here in edit.html.erb' %>
    <div id="error_explanation">
      <h3>
        <%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:
      </h3>
      <ul>
        <% @article.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
    <% puts 'errors shown from edit.html.erb' %>
  <% end %>

  <p>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </p>

  <p>
    <%= form.label :text %><br>
    <%= form.text_area :text %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>

<%= link_to 'Back', articles_path %>
</code>```

答:
The problem is you forgot to add local: true. By default, all request when using form_with is ajax. So you need to turn it off

```<code>form_with(model: @article, local: true)
</code>```

Read more about form_with here link1 and link2

ContentLicense: CC BY-SA 3.0

Body:
This problem is specific to the example tutorials mentioned in the Getting Started guide of Rails 5.1.4

Upon following Section 5.11 [Updating Articles] from the rails getting started guide, it is expected that the line containing <% if @article.errors.any? %> in the app/views/articles/edit.html.erb file will get invoked if an article with empty title or empty text are tried to be saved. Meaning, the error messages should show up.

However, the article is prevented from getting updated (as expected) but the error messages do not show up (as not expected).

Is anyone familiar with this problem from the getting started tutorials explained in Rails Guide 5.1.4 ?

EDIT::: Following are the controller file and the view file. I have added some puts statements to print to the console

The articles_controller,rb file:

def edit
  @article = Article.find(params[:id])
end

def update
  @article = Article.find(params[:id])
  if @article.update(valid_article_params)
    puts 'article successfully updated...'
    redirect_to @article
  else
    puts 'article could not be updated...'
    render 'edit'
  end
end

private
  def valid_article_params
    params.require(:article).permit(:title, :text)
  end

The edit.html.erb file:

Edit article

<%= form_with(model: @article) do |form| %>

  <% if @article.errors.any? %>
    <% puts 'there are some errors here in edit.html.erb' %>

        <%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:

        <% @article.errors.full_messages.each do |msg| %>

<%= msg %>

        <% end %>

    <% puts 'errors shown from edit.html.erb' %>
  <% end %>

    <%= form.label :title %>

    <%= form.text_field :title %>

    <%= form.label :text %>

    <%= form.text_area :text %>

    <%= form.submit %>

<% end %>

<%= link_to 'Back', articles_path %>

Body:
The problem is you forgot to add local: true. By default, all request when using form_with is ajax. So you need to turn it off

form_with(model: @article, local: true)

Read more about form_with here link1 and link2


问:
Automapper Interface Mapping
I have PagedList implementation and I am trying to use AutoMapper in order to map entity PagedList to DTO PagedList.

Here is my interface:

```<code>public interface IPagedList<T> : IList<T>
{
    PagingInformation Paging { get; set; }
}
</code>```

Here is My Class Implementation:

```<code>public class PagedList<T> : List<T>, IPagedList<T> //, IList<T>
{
    public PagingInformation Paging { get; set; }

    public PagedList()
    {
    }

    public PagedList(IEnumerable<T> collection) : base(collection)
    {
    }

    public PagedList(IEnumerable<T> collection, PagingInformation paging) : base(collection)
    {
        Paging = paging;
    }

    public PagedList(int capacity) : base(capacity)
    {
    }

    PagingInformation IPagedList<T>.Paging
    {
        get => Paging;
        set => Paging = value;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

}
</code>```

I am using Automapper like

```<code>public async Task<DomainResult<IPagedList<PositionDto>>> GetPagedListAsync(int pageIndex = 0, int pageSize = 20)
{
    return DomainResult<IPagedList<PositionDto>>.Success(_mapper.Map<IPagedList<PositionDto>>(await _positionRepository.GetPagedListAsync(pageIndex, pageSize)));
}
</code>```

Without Mapper Configuration:
   I am getting following Error:

Error mapping types.

Mapping types: PagedList1 -> IPagedList1
  WestCore.Shared.Collections.Pagination.PagedList1[[WestCore.Domain.Entities.Position,
  WestCore.Domain, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null]] ->
  WestCore.Shared.Collections.Pagination.IPagedList1[[WestCore.AppCore.Models.PositionDto,
  WestCore.AppCore, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null]]

When I Add CreateMap(typeof(PagedList<>), typeof(IPagedList<>)) into Mapper Pofile, I am getting following Error:

Method 'get_Item' in type
  'Proxy  WestCore.Shared.Collections.Pagination.IPagedList`1[[WestCore.AppCore.Models.PositionDto_WestCore.AppCore_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null]]_WestCore.Shared_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null' from assembly 'AutoMapper.Proxies, Version=0.0.0.0, Culture=neutral,
  PublicKeyToken=be96cd2c38ef1005' does not have an implementation.

When I add CreateMap(typeof(PagedList<>),typeof(IPagedList<>)).As(typeof(PagedList<>)); into Mapper Profile, I am not getting error however PagedList returns empty result set

I am not sure whether I have missing implementation in PagedList method or it is a configuration issue.

Edit:

PagingInformation added below:

```<code>    public class PagingInformation
{
    /// <summary>
    /// Gets the index start value.
    /// </summary>
    /// <value>The index start value.</value>
    public int IndexFrom { get; }

    /// <summary>
    /// Gets the page index (current).
    /// </summary>
    public int PageIndex { get; }

    /// <summary>
    /// Gets the page size.
    /// </summary>
    public int PageSize { get; }

    /// <summary>
    /// Gets the total count of the list of type <typeparamref name="TEntity"/>
    /// </summary>
    public int TotalCount { get; }

    /// <summary>
    /// Gets the total pages.
    /// </summary>
    public int TotalPages { get; }

    /// <summary>
    /// Gets the has previous page.
    /// </summary>
    /// <value>The has previous page.</value>
    public bool HasPreviousPage => PageIndex - IndexFrom > 0;

    /// <summary>
    /// Gets the has next page.
    /// </summary>
    /// <value>The has next page.</value>
    public bool HasNextPage => PageIndex - IndexFrom + 1 < TotalPages;

    public PagingInformation(int pageIndex, int pageSize, int indexFrom, int count)
    {
        if (indexFrom > pageIndex)
        {
            throw new ArgumentException($"indexFrom: {indexFrom} > pageIndex: {pageIndex}, must indexFrom <= pageIndex");
        }

        PageIndex = pageIndex;
        PageSize = pageSize;
        IndexFrom = indexFrom;
        TotalCount = count;
        TotalPages = (int) Math.Ceiling(TotalCount / (double) PageSize);

    }
}
</code>```

Thank you

答:
You can not use interface as a result of the mapping because mapper have no idea how to create this.

You can use ConstructUsing to create IPagedList. Like this:

```<code>AutoMapper.Mapper.CreateMap<DtoParent, ICoreParent>()
            .ConstructUsing(parentDto => new CoreParent())
            .ForMember(dest => dest.Other, opt => opt.MapFrom(src => AutoMapper.Mapper.Map<DtoChild, ICoreChild>(src.Other)));
</code>```

EDIT:

Work this way:

```<code>class Example
{
    static void Main()
    {
        AutoMapper.Mapper.Initialize(config =>
        {
            config.CreateMap(typeof(PagedList<>), typeof(IPagedList<>))
                 .ConvertUsing(typeof(Converter<,>));

            config.CreateMap<Entity, DTO>();

        });

        var entityList = new PagedList<Entity>(new [] { new Entity(), }, new PagingInformation() { Total =  2, PageNumber =  1, PageSize = 10});

        var mapped = Mapper.Map<IPagedList<DTO>>(entityList);
    }
}

class Converter<TSource, TDest> : ITypeConverter<IPagedList<TSource> , IPagedList<TDest>>
{
    public IPagedList<TDest> Convert(IPagedList<TSource> source, IPagedList<TDest> destination, ResolutionContext context) =>  new PagedList<TDest>(context.Mapper.Map<IEnumerable<TDest>>(source.AsEnumerable()), source.Paging);
}

class Entity
{
    public Guid Id { get; set; } = Guid.NewGuid();
}

class DTO
{
    public Guid Id { get; set; } = Guid.NewGuid();
}

public interface IPagedList<T> : IList<T>
{
    PagingInformation Paging { get; set; }
}

public class PagingInformation
{
    public int Total { get; set; }

    public int PageSize { get; set; }

    public int PageNumber { get; set; }
}

public class PagedList<T> : List<T>, IPagedList<T>
{
    public PagingInformation Paging { get; set; }

    public PagedList() { }
    public PagedList(IEnumerable<T> collection) : base(collection) { }

    public PagedList(IEnumerable<T> collection, PagingInformation paging) : base(collection) { Paging = paging; }
}
</code>```

Also probably this require to map PagingInformation in some other way as in my example both paged lists are referencing to one PagingInformation object after map, that I think is ok until PagingInformation is immutable.

Title: Automapper Interface Mapping

Body:
I have PagedList implementation and I am trying to use AutoMapper in order to map entity PagedList to DTO PagedList.

Here is my interface:

public interface IPagedList<T> : IList<T>
{
    PagingInformation Paging { get; set; }
}

Here is My Class Implementation:

public class PagedList<T> : List<T>, IPagedList<T> //, IList<T>
{
    public PagingInformation Paging { get; set; }

    public PagedList()
    {
    }

    public PagedList(IEnumerable<T> collection) : base(collection)
    {
    }

    public PagedList(IEnumerable<T> collection, PagingInformation paging) : base(collection)
    {
        Paging = paging;
    }

    public PagedList(int capacity) : base(capacity)
    {
    }

    PagingInformation IPagedList<T>.Paging
    {
        get => Paging;
        set => Paging = value;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

}

I am using Automapper like

public async Task<DomainResult<IPagedList<PositionDto>>> GetPagedListAsync(int pageIndex = 0, int pageSize = 20)
{
    return DomainResult<IPagedList<PositionDto>>.Success(_mapper.Map<IPagedList<PositionDto>>(await _positionRepository.GetPagedListAsync(pageIndex, pageSize)));
}

Without Mapper Configuration:
   I am getting following Error:

Error mapping types.

Mapping types: PagedList1 -> IPagedList1
  WestCore.Shared.Collections.Pagination.PagedList1[[WestCore.Domain.Entities.Position,
  WestCore.Domain, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null]] ->
  WestCore.Shared.Collections.Pagination.IPagedList1[[WestCore.AppCore.Models.PositionDto,
  WestCore.AppCore, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null]]

When I Add CreateMap(typeof(PagedList<>), typeof(IPagedList<>)) into Mapper Pofile, I am getting following Error:

Method 'get_Item' in type
  'Proxy  WestCore.Shared.Collections.Pagination.IPagedList`1[[WestCore.AppCore.Models.PositionDto_WestCore.AppCore_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null]]_WestCore.Shared_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null' from assembly 'AutoMapper.Proxies, Version=0.0.0.0, Culture=neutral,
  PublicKeyToken=be96cd2c38ef1005' does not have an implementation.

When I add CreateMap(typeof(PagedList<>),typeof(IPagedList<>)).As(typeof(PagedList<>)); into Mapper Profile, I am not getting error however PagedList returns empty result set

I am not sure whether I have missing implementation in PagedList method or it is a configuration issue.

Edit:

PagingInformation added below:

    public class PagingInformation
{
    ///
    /// Gets the index start value.
    ///
    /// <value>The index start value.</value>
    public int IndexFrom { get; }

    ///
    /// Gets the page index (current).
    ///
    public int PageIndex { get; }

    ///
    /// Gets the page size.
    ///
    public int PageSize { get; }

    ///
    /// Gets the total count of the list of type <typeparamref name="TEntity"/>
    ///
    public int TotalCount { get; }

    ///
    /// Gets the total pages.
    ///
    public int TotalPages { get; }

    ///
    /// Gets the has previous page.
    ///
    /// <value>The has previous page.</value>
    public bool HasPreviousPage => PageIndex - IndexFrom > 0;

    ///
    /// Gets the has next page.
    ///
    /// <value>The has next page.</value>
    public bool HasNextPage => PageIndex - IndexFrom + 1 < TotalPages;

    public PagingInformation(int pageIndex, int pageSize, int indexFrom, int count)
    {
        if (indexFrom > pageIndex)
        {
            throw new ArgumentException($"indexFrom: {indexFrom} > pageIndex: {pageIndex}, must indexFrom <= pageIndex");
        }

        PageIndex = pageIndex;
        PageSize = pageSize;
        IndexFrom = indexFrom;
        TotalCount = count;
        TotalPages = (int) Math.Ceiling(TotalCount / (double) PageSize);

    }
}

Thank you

Body:
You can not use interface as a result of the mapping because mapper have no idea how to create this.

You can use ConstructUsing to create IPagedList. Like this:

AutoMapper.Mapper.CreateMap<DtoParent, ICoreParent>()
            .ConstructUsing(parentDto => new CoreParent())
            .ForMember(dest => dest.Other, opt => opt.MapFrom(src => AutoMapper.Mapper.Map<DtoChild, ICoreChild>(src.Other)));

EDIT:

Work this way:

class Example
{
    static void Main()
    {
        AutoMapper.Mapper.Initialize(config =>
        {
            config.CreateMap(typeof(PagedList<>), typeof(IPagedList<>))
                 .ConvertUsing(typeof(Converter<,>));

            config.CreateMap<Entity, DTO>();

        });

        var entityList = new PagedList<Entity>(new [] { new Entity(), }, new PagingInformation() { Total =  2, PageNumber =  1, PageSize = 10});

        var mapped = Mapper.Map<IPagedList<DTO>>(entityList);
    }
}

class Converter<TSource, TDest> : ITypeConverter<IPagedList<TSource> , IPagedList<TDest>>
{
    public IPagedList<TDest> Convert(IPagedList<TSource> source, IPagedList<TDest> destination, ResolutionContext context) =>  new PagedList<TDest>(context.Mapper.Map<IEnumerable<TDest>>(source.AsEnumerable()), source.Paging);
}

class Entity
{
    public Guid Id { get; set; } = Guid.NewGuid();
}

class DTO
{
    public Guid Id { get; set; } = Guid.NewGuid();
}

public interface IPagedList<T> : IList<T>
{
    PagingInformation Paging { get; set; }
}

public class PagingInformation
{
    public int Total { get; set; }

    public int PageSize { get; set; }

    public int PageNumber { get; set; }
}

public class PagedList<T> : List<T>, IPagedList<T>
{
    public PagingInformation Paging { get; set; }

    public PagedList() { }
    public PagedList(IEnumerable<T> collection) : base(collection) { }

    public PagedList(IEnumerable<T> collection, PagingInformation paging) : base(collection) { Paging = paging; }
}

Also probably this require to map PagingInformation in some other way as in my example both paged lists are referencing to one PagingInformation object after map, that I think is ok until PagingInformation is immutable.


问:
Trying to reduce memory impact in a for loop Swift (4)
I have a pdf document (approx 200 pages). I run a for loop to iterate all the pages in turn and scrape it for some strings and stores in an Array.

This however results in a crash

Message from debugger: Terminated due to memory issue.

Im trying to reduce the size of the memory by removing elements from the array but despite the array being shortened the data size remains the same how is this?

```<code>let document = PDFDocument(url: documentURL)
document?.delegate = self

let numberOfPages = CGFloat((document?.pageCount)!)

var pageText : String?

for page in 0...Int(numberOfPages) {

    if document?.page(at: page)?.string != nil {
        pageText = document?.page(at: page)?.string

        var parameters: [String]?
        parameters = pageText?.components(separatedBy: "Train From")

        pageText = nil //pageText now stored in parameters variable so set to nil

        if parameters!.count > 1 && parameters!.count < 3 {
            print(MemoryLayout.size(ofValue: parameters!), ">", parameters!.count)
            parameters!.removeLast() // we only need first item
            print(MemoryLayout.size(ofValue: parameters!), ">>", parameters!.count)
        }
    }
}
</code>```

the print out is

8 > 2

8 >> 1

so the array is removing an element yet its size remains 8?
How, why?

I need to free up memory in my for loop.

答:
When you use MemoryLayout.size you get the size of memory of that type. But a struct with a fixed size, so you see the size of that cell.

You should duplicate in the count of the cells:

```<code>print(MemoryLayout.size(ofValue: parameters!) * parameters!.count, ">", parameters!.count)
parameters!.removeLast() // we only need first item
print(MemoryLayout.size(ofValue: parameters!) * parameters!.count, ">>", parameters!.count)
</code>```

Body:
I have a pdf document (approx 200 pages). I run a for loop to iterate all the pages in turn and scrape it for some strings and stores in an Array.

This however results in a crash

Message from debugger: Terminated due to memory issue.

Im trying to reduce the size of the memory by removing elements from the array but despite the array being shortened the data size remains the same how is this?

let document = PDFDocument(url: documentURL)
document?.delegate = self

let numberOfPages = CGFloat((document?.pageCount)!)

var pageText : String?

for page in 0...Int(numberOfPages) {

    if document?.page(at: page)?.string != nil {
        pageText = document?.page(at: page)?.string

        var parameters: [String]?
        parameters = pageText?.components(separatedBy: "Train From")

        pageText = nil //pageText now stored in parameters variable so set to nil

        if parameters!.count > 1 && parameters!.count < 3 {
            print(MemoryLayout.size(ofValue: parameters!), ">", parameters!.count)
            parameters!.removeLast() // we only need first item
            print(MemoryLayout.size(ofValue: parameters!), ">>", parameters!.count)
        }
    }
}

the print out is

8 > 2

8 >> 1

so the array is removing an element yet its size remains 8?
How, why?

I need to free up memory in my for loop.

Body:
When you use MemoryLayout.size you get the size of memory of that type. But a struct with a fixed size, so you see the size of that cell.

You should duplicate in the count of the cells:

print(MemoryLayout.size(ofValue: parameters!) * parameters!.count, ">", parameters!.count)
parameters!.removeLast() // we only need first item
print(MemoryLayout.size(ofValue: parameters!) * parameters!.count, ">>", parameters!.count)


问:
How to implement thread pool that will automatically shutdown at end of execution?
I'm writing a Java client which could theoretically be used in a different environment: Java main(), in a servlet container, or via dependency injection.

The client implements internal connection thread pooling.

The problem with this approach is that users of the client that are unaware of the fact that an internal thread pool is implemented will see his or her application "hang" on shutdown.  My users need to know to send a shutdown() message to the library.

I'm wondering if any other alternative approach could be taken that would, on one hand, allow me to start a thread pool for my connections; and, on the other hand, catch some event, perhaps a JVM event, that indicates the JVM is going down, which will allow me to call my shutdown() implementation.

答: Runtime.getRuntime().addShutdownHook() would be the thing I would think of. http://blog.yohanliyanage.com/2010/10/know-the-jvm-2-shutdown-hooks/ has decent explanation. Does that help?

ContentLicense: CC BY-SA 2.5


问:
Chai assert.deepEqual throws error "TypeError: Right-hand side of 'instanceof' is not an object" when using atob
I'm using Chai and Mocha to run tests on my helper functions. I used JSDOM to include atob and btoa. This is my setup.js file:

const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('<!doctype html>');
const { window } = jsdom;

global.window = window;
global.document = window.document
global.btoa = window.btoa;
global.atob = window.atob;```
</div>
</div>
</p>

<p>When I try to run my tests, I get this error: </p>

<p><code>TypeError: Right-hand side of 'instanceof' is not an object.</code></p>

<p>My test function:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>describe('helpers', () => {
  const testObject = { id: 1 };
  const encodedObject = base64EncodeObject(testObject);
  const decodedObject = base64DecodeObject(encodedObject);

  describe('base64DecodeObject()', () => {
    it('decoded object should match original object', () => {
      assert.deepEqual(decodedObject, testObject);
    });
  });
});</code>```

Target function:

const base64DecodeObject = (base64String) => {
  let object = atob(base64String);
  object = JSON.parse(object);
  return object;
}```

答:
Your problem is caused by the fact that you're only going only part-way towards mimicking a DOM environment in Node. You set a few variables and stop there, and so you end up with something which is neither a stock Node environment, nor a DOM environment.

chai uses deep-eql to perform deep comparison, and deep-eql uses a package named type-detect to do some of its work. type-detect performs a test that indicates to it that it is running in a DOM environment and eventually it tries to do this:

```<code>if (obj instanceof globalObject.HTMLElement && obj.tagName === 'BLOCKQUOTE') {
</code>```

Since you did not copy HTMLElement from window to global, then it fails with the error you get. You can fix it by adding:

```<code>global.HTMLElement = window.HTMLElement;
</code>```

Body:
I'm using Chai and Mocha to run tests on my helper functions. I used JSDOM to include atob and btoa. This is my setup.js file:

const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('<!doctype html>');
const { window } = jsdom;

global.window = window;
global.document = window.document
global.btoa = window.btoa;
global.atob = window.atob;

When I try to run my tests, I get this error:

TypeError: Right-hand side of 'instanceof' is not an object.

My test function:

describe('helpers', () => {
  const testObject = { id: 1 };
  const encodedObject = base64EncodeObject(testObject);
  const decodedObject = base64DecodeObject(encodedObject);

  describe('base64DecodeObject()', () => {
    it('decoded object should match original object', () => {
      assert.deepEqual(decodedObject, testObject);
    });
  });
});

Target function:

const base64DecodeObject = (base64String) => {
  let object = atob(base64String);
  object = JSON.parse(object);
  return object;
}

Body:
Your problem is caused by the fact that you're only going only part-way towards mimicking a DOM environment in Node. You set a few variables and stop there, and so you end up with something which is neither a stock Node environment, nor a DOM environment.

chai uses deep-eql to perform deep comparison, and deep-eql uses a package named type-detect to do some of its work. type-detect performs a test that indicates to it that it is running in a DOM environment and eventually it tries to do this:

if (obj instanceof globalObject.HTMLElement && obj.tagName === 'BLOCKQUOTE') {

Since you did not copy HTMLElement from window to global, then it fails with the error you get. You can fix it by adding:

global.HTMLElement = window.HTMLElement;


问:
parse "strange" date format
Hi I have trouble have parse date in this format:

```<code>1295716379
</code>```

I don’t what kind of date format is it.

Human readable value of this string is:

```<code>22. 1. 2011, 18.12
</code>```

Also I don’t know that this format is some cowboy coder format or it is some "standard".

And if it is possible parse string on the top to human readable format, for examle in C#, Java, C++.

Thank

答:
That's a UNIX Epoch timestamp.

An example in C# to convert it to a DateTime:

```<code>DateTime ToDateTime(int seconds)
{
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return epoch.ToLocalTime().AddSeconds(seconds);
}
</code>```

This will convert it into local time.

Title: parse "strange" date format

Body:
Hi I have trouble have parse date in this format:

1295716379

I don’t what kind of date format is it.

Human readable value of this string is:

22. 1. 2011, 18.12

Also I don’t know that this format is some cowboy coder format or it is some "standard".

And if it is possible parse string on the top to human readable format, for examle in C#, Java, C++.

Thank

Body:
That's a UNIX Epoch timestamp.

An example in C# to convert it to a DateTime:

DateTime ToDateTime(int seconds)
{
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return epoch.ToLocalTime().AddSeconds(seconds);
}

This will convert it into local time.


问:
No need to cast the result of findViewById?
Recently I found that AndroidStudio reminds me to remove some class cast. I remember that in the old time, we have to cast the result of findViewById, but now it's not necessary.

The result of findViewById is still View, so i want to know why we don't need to cast the class?

I can't find any documents mentioned that, can anyone find any document?

答:
According to this article:

The following function relies on Java’s generics automatic type inference in order to eliminate a need for manual casting:

```<code>protected <T extends View> T findViewById(@IdRes int id) {
    return (T) getRootView().findViewById(id);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
According to this article:

The following function relies on Java’s generics automatic type inference in order to eliminate a need for manual casting:

protected <T extends View> T findViewById(@IdRes int id) {
    return (T) getRootView().findViewById(id);
}


答:
Add local: true to your form as follows:

```<code><%= form_with(model: @article) do |form| %>
</code>```

To:

```<code><%= form_with(model: @article, local: true) do |form| %>
</code>```

The reason is stated in the same guide:

by default form_with submits forms using Ajax thereby skipping full page redirects. To make this guide easier to get into we've disabled that with local: true for now.

I check and the Guide contains an error. The section 5.11 is missing local: true

Title: errors not showing upon editing/updating an article - following rails guide v5.1.4

Body:
Add local: true to your form as follows:

<%= form_with(model: @article) do |form| %>

To:

<%= form_with(model: @article, local: true) do |form| %>

The reason is stated in the same guide:

by default form_with submits forms using Ajax thereby skipping full page redirects. To make this guide easier to get into we've disabled that with local: true for now.

I check and the Guide contains an error. The section 5.11 is missing local: true


问:
Why do I have NUL line in my written file using fopen fclose c++ linux?
I have some C code running on a linux OS into a portable device. I'm using a VRmagic system, similar to BeagleBone etc...).

In this code, I'm using the following function to write results inside a txt file.

```<code>//globale definition
FILE *logfile;
const char *logpath = "/MY_DEVICE/log.txt";
const char *main_folder_result_path = "/MEASUREMENT_RESULTS/";
const char *all_measurement_results_file_name = "all_computation_data.txt";

void save_to_log_file(const char *logpath,const char *message){
    #ifdef savealllog
        logfile = fopen(logpath,"a");  //logpath = "/MY_DEVICE/log.txt";
        fprintf(logfile,"%s",message);
        fclose(logfile);
    #endif
    #ifdef printalloutput
        printf("%s",message);
    #endif
}

void append_all_measurement_file(){

    char buff[255];
    char filename[255];

    save_to_log_file(logpath,"     Appending all measurement file...");

    sprintf(filename,"%s%s",main_folder_result_path,all_measurement_results_file_name);

    //here after we create the header if the file does not exist already
    FILE *pFile_all_measurement_results = fopen(filename, "r"); //lets try to read the file
    if (pFile_all_measurement_results == NULL){ // if file does not exist
        pFile_all_measurement_results = fopen(filename, "w");
        fprintf(pFile_all_measurement_results,"date-time S_type Part_name batch count abs value_1 value_2 value_3 value_4\n");
        fclose(pFile_all_measurement_results);
    }
    else{
        fclose(pFile_all_measurement_results); //if file does exist then we have to close it here
    }

    //here after we are going to write results
    pFile_all_measurement_results = fopen(filename, "a"); //lets open the file in append mode

    fprintf(pFile_all_measurement_results,"%s %s %s %d %d %d ",dateandtimetps.dt,measurement_type_str,Name_Str, batch_number,count_number,absolute_measurement_number);
    fprintf(pFile_all_measurement_results,"%.03f ", value_1);
    fprintf(pFile_all_measurement_results,"%.03f ", value_2);
    fprintf(pFile_all_measurement_results,"%.03f ", value_3);
    fprintf(pFile_all_measurement_results,"%.03f\n", value_4); //(there are a bit more in reality.....)

    fclose(pFile_all_measurement_results); //we can now close the file

    save_to_log_file(logpath,"done.\n");
}
</code>```

99.9% of the time all is OK.
But, randomly, I do have some NUL character in my file, and this happen when I turn OFF my system.

Looks like the file has not been closed properly or something like that for some reason.....

When I get my txt file, and open it with notepad++ on my computer, it does look like the following:

I can confirm that the device has been turned OFF between line 172 and line 174.

Many thanks for help

答:
Just closing a file on Unix systems does not implicate the contents are instantly written to disk; usually buffering/caching is enabled.

To make sure the contents are written you can use sync() immediately after a write and/or close operation, which will minimize the risk of lost updates.

Additionally I recommend to use a journaling filesystem like ext4 (which may not be an option on external drives like USB pens, but is strongly recommend for all system and data partitions). This will not save you from data loss in case of a power failure or crash, but will avoid inconsistencies/partial writes like you are experiencing.

Body:
I have some C code running on a linux OS into a portable device. I'm using a VRmagic system, similar to BeagleBone etc...).

In this code, I'm using the following function to write results inside a txt file.

//globale definition
FILE *logfile;
const char *logpath = "/MY_DEVICE/log.txt";
const char *main_folder_result_path = "/MEASUREMENT_RESULTS/";
const char *all_measurement_results_file_name = "all_computation_data.txt";

void save_to_log_file(const char *logpath,const char *message){
    #ifdef savealllog
        logfile = fopen(logpath,"a");  //logpath = "/MY_DEVICE/log.txt";
        fprintf(logfile,"%s",message);
        fclose(logfile);
    #endif
    #ifdef printalloutput
        printf("%s",message);
    #endif
}

void append_all_measurement_file(){

    char buff[255];
    char filename[255];

    save_to_log_file(logpath,"     Appending all measurement file...");

    sprintf(filename,"%s%s",main_folder_result_path,all_measurement_results_file_name);

    //here after we create the header if the file does not exist already
    FILE *pFile_all_measurement_results = fopen(filename, "r"); //lets try to read the file
    if (pFile_all_measurement_results == NULL){ // if file does not exist
        pFile_all_measurement_results = fopen(filename, "w");
        fprintf(pFile_all_measurement_results,"date-time S_type Part_name batch count abs value_1 value_2 value_3 value_4\n");
        fclose(pFile_all_measurement_results);
    }
    else{
        fclose(pFile_all_measurement_results); //if file does exist then we have to close it here
    }

    //here after we are going to write results
    pFile_all_measurement_results = fopen(filename, "a"); //lets open the file in append mode

    fprintf(pFile_all_measurement_results,"%s %s %s %d %d %d ",dateandtimetps.dt,measurement_type_str,Name_Str, batch_number,count_number,absolute_measurement_number);
    fprintf(pFile_all_measurement_results,"%.03f ", value_1);
    fprintf(pFile_all_measurement_results,"%.03f ", value_2);
    fprintf(pFile_all_measurement_results,"%.03f ", value_3);
    fprintf(pFile_all_measurement_results,"%.03f\n", value_4); //(there are a bit more in reality.....)

    fclose(pFile_all_measurement_results); //we can now close the file

    save_to_log_file(logpath,"done.\n");
}

99.9% of the time all is OK.
But, randomly, I do have some NUL character in my file, and this happen when I turn OFF my system.

Looks like the file has not been closed properly or something like that for some reason.....

When I get my txt file, and open it with notepad++ on my computer, it does look like the following:

I can confirm that the device has been turned OFF between line 172 and line 174.

Many thanks for help


问:
RecyclerAdapter IndexOutOfBoundError on using CustomViewHolder
What i'm trying to do is that, I have an adapter which I'm using for many different activities each having their own ViewHolder. So I'm firstly making an abstract recycler adapter named DimRecyclerAbstractAdapter without a ViewHolder. Then for each different activity I'm making a static inner class named DimCustomAdapter which extends DimRecyclerAbstractAdapter having it's own ViewHolder. But I'm getting this error.

```<code>java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
                                                                                at java.util.ArrayList.get(ArrayList.java:411)
</code>```

This is the abstract adapter class  -

```<code>public abstract class DimRecyclerAbstractAdapter<VHA extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VHA> {

    private List<tbl_dim_1> mtbldimList1;

    public DimRecyclerAbstractAdapter(List<tbl_dim_1> tblDimList1) {
        this.mtbldimList1 = tblDimList1;
    }

    @Override
    public int getItemCount() {
            return mtbldimList1.size();
    }

    public void addItems(List<tbl_dim_1> tblDimList1) {

        this.mtbldimList1 = tblDimList1;
        notifyDataSetChanged();
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        mtbldimList1 = null;
        super.onDetachedFromRecyclerView(recyclerView);
    }

}
</code>```

This is the activity in which I've implemented custom ViewHolder -

```<code>public class DetailActivity1 extends LifecycleActivity{

    DimListViewModel dmvmodel;
    RecyclerView rcView;
    DimCustomAdapter rcAdapter;
    public static final String LOG_TAG = "In DetailActivity1 ";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recycler_view);

        Intent receivedIntent = getIntent();
        int rid_int = receivedIntent.getIntExtra("mRId",0);
        Log.v(LOG_TAG,"Rid value int == " + rid_int);

        rcView = (RecyclerView) findViewById(R.id.recyclerView);

        rcAdapter = new DimCustomAdapter(new ArrayList<tbl_dim_1>());
        rcView.setLayoutManager(new LinearLayoutManager(DetailActivity1.this));
        Log.v(LOG_TAG, "Layout manager set");
        rcView.setAdapter(rcAdapter);

        dmvmodel = ViewModelProviders.of(this).get(DimListViewModel.class);
        Log.v(LOG_TAG, "View model returned");

        dmvmodel.getDimList2con1(rid_int).observe(DetailActivity1.this, new Observer<List<tbl_dim_1>>() {

            @Override
            public void onChanged(@Nullable List<tbl_dim_1> changedItems) {
                Log.v(LOG_TAG, "onChanged called, items will be added");
                rcAdapter.addItems(changedItems);
            }
        });
    }

    @Override
    protected void onDestroy() {

        rcAdapter = null;
        rcView.setAdapter(null);
        rcView.setLayoutManager(null);
        rcView = null;
        dmvmodel = null;
        super.onDestroy();
        RefWatcher refWatcher = LeakCheckApplication.getRefWatcher(this);
        refWatcher.watch(this);
    }

    public static class DimCustomAdapter extends DimRecyclerAbstractAdapter<DimCustomAdapter.RecyclerViewHolder> {

        private static List<tbl_dim_1> mtbldimCustom;

        DimCustomAdapter(List<tbl_dim_1> tblDimListPassed) {
            super(mtbldimCustom);
            mtbldimCustom = tblDimListPassed;
        }

        @Override
        public DimCustomAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View vw = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.recycler_item, parent, false);

//          vw.setOnClickListener(vwOnClickListener);
            return new DimCustomAdapter.RecyclerViewHolder(vw);
        }

        @Override
        public void onBindViewHolder(final RecyclerViewHolder holder, int position) {
//          Log.v(LOG_TAG, "Inside onBindViewHolder - ");
            if (holder.dataTextView.getText() != null) {
                String LOG_TAG = "DimCustomAdapter:";
                Log.d(LOG_TAG, "holder is not null, i was right");
                holder.dataTextView.setText(null);
                holder.dataTextView.setOnClickListener(null);
            }

            final tbl_dim_1 dimAtPosition = mtbldimCustom.get(position);
            holder.dataTextView.setText(dimAtPosition.mCONTENT);
            holder.dataTextView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg) {

                    Intent dw = new Intent(arg.getContext(), DetailActivity2.class);
                    dw.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    dw.putExtra("mRId", dimAtPosition.mR_ID);
                    arg.getContext().startActivity(dw);
                }
            });
        }

        class RecyclerViewHolder extends RecyclerView.ViewHolder {
            private TextView dataTextView;

            RecyclerViewHolder(View view) {
                super(view);
                dataTextView = (TextView) view.findViewById(R.id.data_text_view);
            }
        }
    }
}
</code>```

And this is how I'm calling this inner class from outer class within same activity -

```<code>DimCustomAdapter rcAdapter = new DimCustomAdapter(new ArrayList<tbl_dim_1>());
</code>```

答:
Its because of empty list that you are passing while creating the adapter.
DimCustomAdapter rcAdapter = new DimCustomAdapter(new ArrayList<tbl_dim_1>());

Just add a null or empty check in onBindViewHolder method before calling

```<code>final tbl_dim_1 dimAtPosition = mtbldimCustom.get(position);
</code>```

Hope this will stop crashing your application.

You can try like below,

```<code>ArrayList<tbl_dim_1> list = new ArrayList<>()
rcAdapter = new DimCustomAdapter(list);
</code>```

then in observe method,

```<code>dmvmodel.getDimList2con1(rid_int).observe(DetailActivity1.this, new Observer<List<tbl_dim_1>>() {

            @Override
            public void onChanged(@Nullable List<tbl_dim_1> changedItems) {
                Log.v(LOG_TAG, "onChanged called, items will be added");
                list.addAll(changedItems);
                rcAdapter.notifyDataSetChanged()
            }
        });
</code>```

Body:
What i'm trying to do is that, I have an adapter which I'm using for many different activities each having their own ViewHolder. So I'm firstly making an abstract recycler adapter named DimRecyclerAbstractAdapter without a ViewHolder. Then for each different activity I'm making a static inner class named DimCustomAdapter which extends DimRecyclerAbstractAdapter having it's own ViewHolder. But I'm getting this error.

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
                                                                                at java.util.ArrayList.get(ArrayList.java:411)

This is the abstract adapter class  -

public abstract class DimRecyclerAbstractAdapter<VHA extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VHA> {

    private List<tbl_dim_1> mtbldimList1;

    public DimRecyclerAbstractAdapter(List<tbl_dim_1> tblDimList1) {
        this.mtbldimList1 = tblDimList1;
    }

    @Override
    public int getItemCount() {
            return mtbldimList1.size();
    }

    public void addItems(List<tbl_dim_1> tblDimList1) {

        this.mtbldimList1 = tblDimList1;
        notifyDataSetChanged();
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        mtbldimList1 = null;
        super.onDetachedFromRecyclerView(recyclerView);
    }

}

This is the activity in which I've implemented custom ViewHolder -

public class DetailActivity1 extends LifecycleActivity{

    DimListViewModel dmvmodel;
    RecyclerView rcView;
    DimCustomAdapter rcAdapter;
    public static final String LOG_TAG = "In DetailActivity1 ";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recycler_view);

        Intent receivedIntent = getIntent();
        int rid_int = receivedIntent.getIntExtra("mRId",0);
        Log.v(LOG_TAG,"Rid value int == " + rid_int);

        rcView = (RecyclerView) findViewById(R.id.recyclerView);

        rcAdapter = new DimCustomAdapter(new ArrayList<tbl_dim_1>());
        rcView.setLayoutManager(new LinearLayoutManager(DetailActivity1.this));
        Log.v(LOG_TAG, "Layout manager set");
        rcView.setAdapter(rcAdapter);

        dmvmodel = ViewModelProviders.of(this).get(DimListViewModel.class);
        Log.v(LOG_TAG, "View model returned");

        dmvmodel.getDimList2con1(rid_int).observe(DetailActivity1.this, new Observer<List<tbl_dim_1>>() {

            @Override
            public void onChanged(@Nullable List<tbl_dim_1> changedItems) {
                Log.v(LOG_TAG, "onChanged called, items will be added");
                rcAdapter.addItems(changedItems);
            }
        });
    }

    @Override
    protected void onDestroy() {

        rcAdapter = null;
        rcView.setAdapter(null);
        rcView.setLayoutManager(null);
        rcView = null;
        dmvmodel = null;
        super.onDestroy();
        RefWatcher refWatcher = LeakCheckApplication.getRefWatcher(this);
        refWatcher.watch(this);
    }

    public static class DimCustomAdapter extends DimRecyclerAbstractAdapter<DimCustomAdapter.RecyclerViewHolder> {

        private static List<tbl_dim_1> mtbldimCustom;

        DimCustomAdapter(List<tbl_dim_1> tblDimListPassed) {
            super(mtbldimCustom);
            mtbldimCustom = tblDimListPassed;
        }

        @Override
        public DimCustomAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View vw = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.recycler_item, parent, false);

//          vw.setOnClickListener(vwOnClickListener);
            return new DimCustomAdapter.RecyclerViewHolder(vw);
        }

        @Override
        public void onBindViewHolder(final RecyclerViewHolder holder, int position) {
//          Log.v(LOG_TAG, "Inside onBindViewHolder - ");
            if (holder.dataTextView.getText() != null) {
                String LOG_TAG = "DimCustomAdapter:";
                Log.d(LOG_TAG, "holder is not null, i was right");
                holder.dataTextView.setText(null);
                holder.dataTextView.setOnClickListener(null);
            }

            final tbl_dim_1 dimAtPosition = mtbldimCustom.get(position);
            holder.dataTextView.setText(dimAtPosition.mCONTENT);
            holder.dataTextView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg) {

                    Intent dw = new Intent(arg.getContext(), DetailActivity2.class);
                    dw.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    dw.putExtra("mRId", dimAtPosition.mR_ID);
                    arg.getContext().startActivity(dw);
                }
            });
        }

        class RecyclerViewHolder extends RecyclerView.ViewHolder {
            private TextView dataTextView;

            RecyclerViewHolder(View view) {
                super(view);
                dataTextView = (TextView) view.findViewById(R.id.data_text_view);
            }
        }
    }
}

And this is how I'm calling this inner class from outer class within same activity -

DimCustomAdapter rcAdapter = new DimCustomAdapter(new ArrayList<tbl_dim_1>());

Body:
Its because of empty list that you are passing while creating the adapter.
DimCustomAdapter rcAdapter = new DimCustomAdapter(new ArrayList<tbl_dim_1>());

Just add a null or empty check in onBindViewHolder method before calling

final tbl_dim_1 dimAtPosition = mtbldimCustom.get(position);

Hope this will stop crashing your application.

You can try like below,

ArrayList<tbl_dim_1> list = new ArrayList<>()
rcAdapter = new DimCustomAdapter(list);

then in observe method,

dmvmodel.getDimList2con1(rid_int).observe(DetailActivity1.this, new Observer<List<tbl_dim_1>>() {

            @Override
            public void onChanged(@Nullable List<tbl_dim_1> changedItems) {
                Log.v(LOG_TAG, "onChanged called, items will be added");
                list.addAll(changedItems);
                rcAdapter.notifyDataSetChanged()
            }
        });


问:
What's the best way to save a complete webpage on a linux server?
I need to archive complete pages including any linked images etc. on my linux server. Looking for the best solution. Is there a way to save all assets and then relink them all to work in the same directory?

I've thought about using curl, but I'm unsure of how to do all of this. Also, will I maybe need PHP-DOM?

Is there a way to use firefox on the server and copy the temp files after the address has been loaded or similar?

Any and all input welcome.

Edit:

It seems as though wget is 'not' going to work as the files need to be rendered. I have firefox installed on the server, is there a way to load the url in firefox and then grab the temp files and clear the temp files after?

答:
If all the content in the web page was static, you could get around this issue with something like wget:

```<code>$ wget -r -l 10 -p http://my.web.page.com/
</code>```

or some variation thereof.

Since you also have dynamic pages, you cannot in general archive such a web page using wget or any simple HTTP client. A proper archive needs to incorporate the contents of the backend database and any server-side scripts. That means that the only way to do this properly is to copy the backing server-side files. That includes at least the HTTP server document root and any database files.

EDIT:

As a work-around, you could modify your webpage so that a suitably priviledged user could download all the server-side files, as well as a text-mode dump of the backing database (e.g. an SQL dump). You should take extreme care to avoid opening any security holes through this archiving system.

If you are using a virtual hosting provider, most of them provide some kind of Web interface that allows backing-up the whole site. If you use an actual server, there is a large number of back-up solutions that you could install, including a few Web-based ones for hosted sites.

Body:
If all the content in the web page was static, you could get around this issue with something like wget:

$ wget -r -l 10 -p http://my.web.page.com/

or some variation thereof.

Since you also have dynamic pages, you cannot in general archive such a web page using wget or any simple HTTP client. A proper archive needs to incorporate the contents of the backend database and any server-side scripts. That means that the only way to do this properly is to copy the backing server-side files. That includes at least the HTTP server document root and any database files.

EDIT:

As a work-around, you could modify your webpage so that a suitably priviledged user could download all the server-side files, as well as a text-mode dump of the backing database (e.g. an SQL dump). You should take extreme care to avoid opening any security holes through this archiving system.

If you are using a virtual hosting provider, most of them provide some kind of Web interface that allows backing-up the whole site. If you use an actual server, there is a large number of back-up solutions that you could install, including a few Web-based ones for hosted sites.


问:
How to convert from string to number in Oracle using TO_NUMBER function with fixed decimal point char?
I need to convert in procedure from string to decimal with fixed decimal separator . independant on culture settings. Next, I know decimal number is limited just with 6 decimal places after . and there is no limitiation on number of digits before .. Using Oracle documentation and its examples for format strings I have now just this solution:

```<code>v_number := TO_NUMBER(v_string, '9999999999999999999999999999999999D999999', 'NLS_NUMERIC_CHARACTERS = ''. ''');
</code>```

Number of 9 chars before D is maximum number allowed. I find this format string as pretty awful. Is there any better format string for this general conversion or some way to omit second parameter of function? In general I just need to pass to function NLS parameter to tell it i just want to convert with decimal separator ., but second parameter is mandatory in that case as well.

答:
Handles both comma and period.</p>

```<code>FUNCTION to_number2(p_num_str VARCHAR2) RETURN NUMBER AS
BEGIN
  RETURN TO_NUMBER(REPLACE(p_num_str, ',', '.'), '999999999999D999999999999', 'NLS_NUMERIC_CHARACTERS=''.,''');
END;
</code>```

Body:
I need to convert in procedure from string to decimal with fixed decimal separator . independant on culture settings. Next, I know decimal number is limited just with 6 decimal places after . and there is no limitiation on number of digits before .. Using Oracle documentation and its examples for format strings I have now just this solution:

v_number := TO_NUMBER(v_string, '9999999999999999999999999999999999D999999', 'NLS_NUMERIC_CHARACTERS = ''. ''');

Number of 9 chars before D is maximum number allowed. I find this format string as pretty awful. Is there any better format string for this general conversion or some way to omit second parameter of function? In general I just need to pass to function NLS parameter to tell it i just want to convert with decimal separator ., but second parameter is mandatory in that case as well.

Body:
Handles both comma and period.

FUNCTION to_number2(p_num_str VARCHAR2) RETURN NUMBER AS
BEGIN
  RETURN TO_NUMBER(REPLACE(p_num_str, ',', '.'), '999999999999D999999999999', 'NLS_NUMERIC_CHARACTERS=''.,''');
END;


问:
MS Excel 2016, Power View, Image URL unable to increase size
GitHub Repository with photos.xlsx file and Photographs (link)

Software: MS Excel 2016 with Power View enabled

I created Power View report in photos.xlsx  that displays photograph and numbers next to it.

How do I increase size of photograph?

Increasing Font size doesn't increase photo size

I simply cannot select the corner and drag.

And I cannot find FORMAT option to increase size.

HELP!

答:
I think images added to the Power View are only static so they can,t be changed in size once in the Power View. </p>

<p>Check this link out: https://social.technet.microsoft.com/Forums/en-US/81202bdb-4892-45b8-a1ae-67f09058a53f/can-i-expand-image-size-in-power-views-table-?forum=powerview  </p>

Body:
I think images added to the Power View are only static so they can,t be changed in size once in the Power View.

Check this link out: https://social.technet.microsoft.com/Forums/en-US/81202bdb-4892-45b8-a1ae-67f09058a53f/can-i-expand-image-size-in-power-views-table-?forum=powerview


问:
Template Function to manipulate memory
I'm modifying the memory of a game, therefor i do something like this:

```<code>*(float*)0x89635637 = 10.0f;
</code>```

Now i want to turn this into a template function which allows me to read and set the memory with only writing the address once, i thought of something like this:

```<code>template <typename Variable> Variable GetSetAddress(Variable address, Variable value = NULL)
{
    if (value != NULL)
        *(Variable*)address = value;

    return *(Variable*)address;
}
</code>```

Now i tried calling it like this:

```<code>float value = GetSetAddress<float>(0x89635637, 10.0f);
</code>```

But it gave me this error:

error C2440: 'type cast' : cannot convert from 'float' to 'float *'

I'm pretty inexperienced with using templates, so i'd be thankful if one of you could point me in the right direction. Thanks in advance!

答:
It doesn't make sense to compare value to NULL, as value in this case is a float. Additionally, the address parameter shouldn't be a Variable, it should be an integral type which can store a pointer value, like std::uintptr_t

```<code>template <typename T> T GetSetAddress(std::uintptr_t address, T value)
{
    *(T*)address = value;
    return *(T*)address;
}
</code>```

It's generally best to avoid c-style casts as well. You could use a reinterpret_cast instead, and simplify the return statement:

```<code>template <typename T> T GetSetAddress(std::uintptr_t address, T value)
{
    *reinterpret_cast<T*>(address) = value;
    return value;
}
</code>```

Title: Template Function to manipulate memory

Body:
I'm modifying the memory of a game, therefor i do something like this:

*(float*)0x89635637 = 10.0f;

Now i want to turn this into a template function which allows me to read and set the memory with only writing the address once, i thought of something like this:

template <typename Variable> Variable GetSetAddress(Variable address, Variable value = NULL)
{
    if (value != NULL)
        *(Variable*)address = value;

    return *(Variable*)address;
}

Now i tried calling it like this:

float value = GetSetAddress<float>(0x89635637, 10.0f);

But it gave me this error:

error C2440: 'type cast' : cannot convert from 'float' to 'float *'

I'm pretty inexperienced with using templates, so i'd be thankful if one of you could point me in the right direction. Thanks in advance!

Body:
It doesn't make sense to compare value to NULL, as value in this case is a float. Additionally, the address parameter shouldn't be a Variable, it should be an integral type which can store a pointer value, like std::uintptr_t

template <typename T> T GetSetAddress(std::uintptr_t address, T value)
{
    *(T*)address = value;
    return *(T*)address;
}

It's generally best to avoid c-style casts as well. You could use a reinterpret_cast instead, and simplify the return statement:

template <typename T> T GetSetAddress(std::uintptr_t address, T value)
{
    *reinterpret_cast<T*>(address) = value;
    return value;
}


问:
Network adapter Disabled on windows azure virtual machine (how to reactivate)
I have a problem with my azure virtual machine (name : Davzen, resource group : Rs1). I made a bad manipulation accidentally : I desactivated the network adapter of the virtual machine , it has ejected me of the Remote Desktop and I didn’t manage to reconnect me since this moment. I tried : restart , réinitialise connection, change virtual machine plan ( 3,5go ram-> 7 go ram). But this setting persist and I didn’t manage to reactivite the network adapter and to connect me with Remote Desktop.
Can everybody help me ?

But it doesn’t work any at all

答:
You cannot add network interfaces to an existing VM using the Azure portal. To add network interfaces to an existing VM, you must use the CLI or PowerShell.
If a network interface has a private IPv6 address assigned to it, it cannot be added to an existing virtual machine. You can only add a network interface with an assigned private IPv6 address to a virtual machine when you create a virtual machine. See Network interface IP addresses to learn more about assigning IP addresses to network interfaces.
For reference you may go through these articles:
https://learn.microsoft.com/en-us/azure/virtual-machines/linux/multiple-nics?toc=%2fazure%2fvirtual-network%2ftoc.json#add-a-nic-to-a-vm  </p>

<p>https://learn.microsoft.com/en-us/azure/virtual-machines/windows/multiple-nics?toc=%2fazure%2fvirtual-network%2ftoc.json#add-a-nic-to-an-existing-vm </p>

Body:
You cannot add network interfaces to an existing VM using the Azure portal. To add network interfaces to an existing VM, you must use the CLI or PowerShell.
If a network interface has a private IPv6 address assigned to it, it cannot be added to an existing virtual machine. You can only add a network interface with an assigned private IPv6 address to a virtual machine when you create a virtual machine. See Network interface IP addresses to learn more about assigning IP addresses to network interfaces.
For reference you may go through these articles:
https://learn.microsoft.com/en-us/azure/virtual-machines/linux/multiple-nics?toc=%2fazure%2fvirtual-network%2ftoc.json#add-a-nic-to-a-vm

https://learn.microsoft.com/en-us/azure/virtual-machines/windows/multiple-nics?toc=%2fazure%2fvirtual-network%2ftoc.json#add-a-nic-to-an-existing-vm


问:
strncpy behaviour in different IDEs
I am wondering why in Eclipse with internal CDT builder I can do this

```<code>char *data = 0;
char data2[20] = "Hello";

strncpy(data, data2, 10);
</code>```

But in visual studio I have to do this

```<code>char *data = malloc(20);
char data2[20] = "Hello";

strncpy(data, data2, 10);
</code>```

As you can see I have to use malloc() in visual studio otherwise I get access violation to memory, but why don't I need it in eclipse?

答:
For most of the cases,

```<code>  char *data = 0;
</code>```

is the same as

```<code>  char *data = NULL;
</code>```

and then, you're using a NULL pointer (i.e., an invalid address you're not suppose to access) as a target for strncpy(). It is undefined behavior

Elaborated in C11, chapter §7.1.4, Use of library functions

[....] If an argument to a function has an invalid value (such as a value
  outside the domain of the function, or a pointer outside the address space of the program,
  or a null pointer, or a pointer to non-modifiable storage when the corresponding
  parameter is not const-qualified) or a type (after promotion) not expected by a function
  with variable number of arguments, the behavior is undefined. [...]

Title: strncpy behaviour in different IDEs

Body:
I am wondering why in Eclipse with internal CDT builder I can do this

char *data = 0;
char data2[20] = "Hello";

strncpy(data, data2, 10);

But in visual studio I have to do this

char *data = malloc(20);
char data2[20] = "Hello";

strncpy(data, data2, 10);

As you can see I have to use malloc() in visual studio otherwise I get access violation to memory, but why don't I need it in eclipse?

Body:
For most of the cases,

  char *data = 0;

is the same as

  char *data = NULL;

and then, you're using a NULL pointer (i.e., an invalid address you're not suppose to access) as a target for strncpy(). It is undefined behavior

Elaborated in C11, chapter §7.1.4, Use of library functions

[....] If an argument to a function has an invalid value (such as a value
  outside the domain of the function, or a pointer outside the address space of the program,
  or a null pointer, or a pointer to non-modifiable storage when the corresponding
  parameter is not const-qualified) or a type (after promotion) not expected by a function
  with variable number of arguments, the behavior is undefined. [...]


问:
using images from resources - image control is empty
I try use images from resources.

I add one png image to resources, name heart.png. It’s public property.

I expose resources with class as advice here:
http://houseofbilz.com/archives/2009/03/15/binding-to-resources-in-silverlightwpf/

Here is class:

namespace Spirit.Util
{
    using Properties;

```<code>public class PublicResources
{
    private readonly  static Resources Resources = new Resources();

    public Resources SpiritResources { get { return Resources; } }

}
</code>```

}

I add to app.xaml:

```<code><Util:PublicResources x:Key="SpiritResources"/>
</code>```

And try use on image control.

```<code>        <Image Style="{StaticResource InfoIcon}">
            <Image.Source>
                <!--<MultiBinding Converter="{StaticResource imageToGrayConverter}">-->
                    <Binding Path="SpiritResources.heart" Source="{StaticResource SpiritResources}"/>
                    <!--<Binding Path="Oponent.Info.IsFriend" Mode="OneWay" UpdateSourceTrigger="PropertyChanged"/>
                </MultiBinding>-->
            </Image.Source>
        </Image>
</code>```

Frist problem is that image control is empty, why?

My complete goal is bind image from resources on image control with multibinding and multiconverter.
If property Isfriend (Oponent.Info.IsFriend) is false I want convert image to grayscale.

Another problem is here. I use this converter class on conversion image to grayscale.

```<code> public class ImageToGrayConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            //string imageUri = values[0] as BimapImage;

            //value is type of System.Drawing.Image
            var image = values[0] as BitmapImage; //new BitmapImage(new Uri(imageUri, UriKind.Relative));

            string s = values[1].ToString();

            bool isLogged = System.Convert.ToBoolean(s);

            if (!isLogged)
            {
                try
                {
                    if (image != null)
                    {
                        var grayBitmapSource = new FormatConvertedBitmap();
                        grayBitmapSource.BeginInit();
                        grayBitmapSource.Source = image;
                        grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
                        grayBitmapSource.EndInit();
                        return grayBitmapSource;
                    }
                    return null;

                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return image;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
</code>```

Value is type of System.Drawing.BitmapImage, I think that I can convert Bitmap to BitmapImage class with this simple class:

http://dog-net.org/content/development/wpf/system-drawing-bitmap-to-bitmapimage/

But I must solve first problem on the beggining. Thank for advice.

答:
As your post is not taggeg as Silverlight, I've solved your problem in WPF application.

I just added existing PNG file to standart Resources. Then put Resources in XAML as static resource and binded PNG file's content to Image element:

```<code><Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:props="clr-namespace:WpfApplication1.Properties">
<Window.Resources>
    <self:ImageConverter x:Key="Conv"/>
    <props:Resources x:Key="Res"/>
</Window.Resources>
<StackPanel>
    <Image Source="{Binding Source={StaticResource Res}, Path=dossier_ardoise_images, Converter={StaticResource Conv}}"/>
</StackPanel>
</code>```

My converter method looks like this (it's standart IValueConverter, but it doesn't matter):

```<code>    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is Bitmap)
        {
            var stream = new MemoryStream();
            ((Bitmap)value).Save(stream, ImageFormat.Png);

            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = stream;
            bitmap.EndInit();

            return bitmap; // use when you need normal image

            var conv = new FormatConvertedBitmap();
            conv.BeginInit();
            conv.Source = bitmap;
            conv.DestinationFormat = PixelFormats.Gray32Float;
            conv.EndInit();

            return conv; // use when you need grayed image

        }
        return value;
    }
</code>```

EDITED

In order to get grayscaled bitmap with keeping transparency I would recommend you use next method (from this article):

```<code>    public static Bitmap MakeGrayscale(Bitmap original)
    {
        //create a blank bitmap the same size as original
        Bitmap newBitmap = new Bitmap(original.Width, original.Height);

        //get a graphics object from the new image
        Graphics g = Graphics.FromImage(newBitmap);

        //create the grayscale ColorMatrix
        ColorMatrix colorMatrix = new ColorMatrix(
           new float[][]
              {
                 new float[] {.3f, .3f, .3f, 0, 0},
                 new float[] {.59f, .59f, .59f, 0, 0},
                 new float[] {.11f, .11f, .11f, 0, 0},
                 new float[] {0, 0, 0, 1, 0},
                 new float[] {0, 0, 0, 0, 1}
              });

        //create some image attributes
        ImageAttributes attributes = new ImageAttributes();

        //set the color matrix attribute
        attributes.SetColorMatrix(colorMatrix);

        //draw the original image on the new image
        //using the grayscale color matrix
        g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
           0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

        //dispose the Graphics object
        g.Dispose();
        return newBitmap;
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is Bitmap)
        {
            var stream = new MemoryStream();
            MakeGrayscale((Bitmap)value).Save(stream, ImageFormat.Png);
            //((Bitmap)value).Save(stream, ImageFormat.Png);

            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            return bitmap;
        }
        return value;
    }
</code>```

Body:
I try use images from resources.

I add one png image to resources, name heart.png. It’s public property.

I expose resources with class as advice here:
http://houseofbilz.com/archives/2009/03/15/binding-to-resources-in-silverlightwpf/

Here is class:

namespace Spirit.Util
{
    using Properties;

public class PublicResources
{
    private readonly  static Resources Resources = new Resources();

    public Resources SpiritResources { get { return Resources; } }

}

}

I add to app.xaml:

<Util:PublicResources x:Key="SpiritResources"/>

And try use on image control.

        <Image Style="{StaticResource InfoIcon}">
            <Image.Source>

                    <Binding Path="SpiritResources.heart" Source="{StaticResource SpiritResources}"/>

            </Image.Source>
        </Image>

Frist problem is that image control is empty, why?

My complete goal is bind image from resources on image control with multibinding and multiconverter.
If property Isfriend (Oponent.Info.IsFriend) is false I want convert image to grayscale.

Another problem is here. I use this converter class on conversion image to grayscale.

 public class ImageToGrayConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            //string imageUri = values[0] as BimapImage;

            //value is type of System.Drawing.Image
            var image = values[0] as BitmapImage; //new BitmapImage(new Uri(imageUri, UriKind.Relative));

            string s = values[1].ToString();

            bool isLogged = System.Convert.ToBoolean(s);

            if (!isLogged)
            {
                try
                {
                    if (image != null)
                    {
                        var grayBitmapSource = new FormatConvertedBitmap();
                        grayBitmapSource.BeginInit();
                        grayBitmapSource.Source = image;
                        grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
                        grayBitmapSource.EndInit();
                        return grayBitmapSource;
                    }
                    return null;

                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return image;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

Value is type of System.Drawing.BitmapImage, I think that I can convert Bitmap to BitmapImage class with this simple class:

http://dog-net.org/content/development/wpf/system-drawing-bitmap-to-bitmapimage/

But I must solve first problem on the beggining. Thank for advice.

Body:
As your post is not taggeg as Silverlight, I've solved your problem in WPF application.

I just added existing PNG file to standart Resources. Then put Resources in XAML as static resource and binded PNG file's content to Image element:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:props="clr-namespace:WpfApplication1.Properties">
<Window.Resources>
    <self:ImageConverter x:Key="Conv"/>
    <props:Resources x:Key="Res"/>
</Window.Resources>
<StackPanel>
    <Image Source="{Binding Source={StaticResource Res}, Path=dossier_ardoise_images, Converter={StaticResource Conv}}"/>
</StackPanel>

My converter method looks like this (it's standart IValueConverter, but it doesn't matter):

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is Bitmap)
        {
            var stream = new MemoryStream();
            ((Bitmap)value).Save(stream, ImageFormat.Png);

            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = stream;
            bitmap.EndInit();

            return bitmap; // use when you need normal image

            var conv = new FormatConvertedBitmap();
            conv.BeginInit();
            conv.Source = bitmap;
            conv.DestinationFormat = PixelFormats.Gray32Float;
            conv.EndInit();

            return conv; // use when you need grayed image

        }
        return value;
    }

EDITED

In order to get grayscaled bitmap with keeping transparency I would recommend you use next method (from this article):

    public static Bitmap MakeGrayscale(Bitmap original)
    {
        //create a blank bitmap the same size as original
        Bitmap newBitmap = new Bitmap(original.Width, original.Height);

        //get a graphics object from the new image
        Graphics g = Graphics.FromImage(newBitmap);

        //create the grayscale ColorMatrix
        ColorMatrix colorMatrix = new ColorMatrix(
           new float[][]
              {
                 new float[] {.3f, .3f, .3f, 0, 0},
                 new float[] {.59f, .59f, .59f, 0, 0},
                 new float[] {.11f, .11f, .11f, 0, 0},
                 new float[] {0, 0, 0, 1, 0},
                 new float[] {0, 0, 0, 0, 1}
              });

        //create some image attributes
        ImageAttributes attributes = new ImageAttributes();

        //set the color matrix attribute
        attributes.SetColorMatrix(colorMatrix);

        //draw the original image on the new image
        //using the grayscale color matrix
        g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
           0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

        //dispose the Graphics object
        g.Dispose();
        return newBitmap;
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is Bitmap)
        {
            var stream = new MemoryStream();
            MakeGrayscale((Bitmap)value).Save(stream, ImageFormat.Png);
            //((Bitmap)value).Save(stream, ImageFormat.Png);

            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            return bitmap;
        }
        return value;
    }