问:
Printing list of class objects inside
How can i print a list with all class objects inside that list?

```<code> List<Reader> MyObjectList = new List<Reader>();

 private void button2_Click(object sender, EventArgs e)
    {
        Reader reader = new Reader();

        reader._surname = Convert.ToString(textBox1.Text);
        reader._id = Convert.ToInt32(textBox2.Text);
        MyObjectList.Add(reader);

        MessageBox.Show("new reader");
    }
</code>```

I want to print all _surname and _id i add, with button click.

```<code>private void button3_Click(object sender, EventArgs e)
    {
        listBox1.DataSource = MyObjectList;
    }
</code>```

If i do it like this, my result says: OBJ6.MyObjectList.

PS. OBJ6 - my project name. How can i print all objects inside that class using button click?

答:
You have to set ItemTemplate in your ListBox.

```<code><ListBox>
                        <ListBox.ItemTemplate>
                                <DataTemplate>
                                        <WrapPanel>
                                                <TextBlock Text="Surname: " />
                                                <TextBlock Text="{Binding _surname}" FontWeight="Bold" />
                                                <TextBlock Text=", " />
                                                <TextBlock Text="Id: " />
                                                <TextBlock Text="{Binding _id}" FontWeight="Bold" />
                                        </WrapPanel>
                                </DataTemplate>
                        </ListBox.ItemTemplate>
                </ListBox>
</code>```

Also, read about binding ObservableLists as items source, so that you don't need a button to refresh the list.

Title: Printing list of class objects inside

Body:
How can i print a list with all class objects inside that list?

 List<Reader> MyObjectList = new List<Reader>();

 private void button2_Click(object sender, EventArgs e)
    {
        Reader reader = new Reader();

        reader._surname = Convert.ToString(textBox1.Text);
        reader._id = Convert.ToInt32(textBox2.Text);
        MyObjectList.Add(reader);

        MessageBox.Show("new reader");
    }

I want to print all _surname and _id i add, with button click.

private void button3_Click(object sender, EventArgs e)
    {
        listBox1.DataSource = MyObjectList;
    }

If i do it like this, my result says: OBJ6.MyObjectList.

PS. OBJ6 - my project name. How can i print all objects inside that class using button click?

Body:
You have to set ItemTemplate in your ListBox.

<ListBox>
                        <ListBox.ItemTemplate>
                                <DataTemplate>
                                        <WrapPanel>
                                                <TextBlock Text="Surname: " />
                                                <TextBlock Text="{Binding _surname}" FontWeight="Bold" />
                                                <TextBlock Text=", " />
                                                <TextBlock Text="Id: " />
                                                <TextBlock Text="{Binding _id}" FontWeight="Bold" />
                                        </WrapPanel>
                                </DataTemplate>
                        </ListBox.ItemTemplate>
                </ListBox>

Also, read about binding ObservableLists as items source, so that you don't need a button to refresh the list.


来源: stackexchange

问:
Removing Price from Woocommerce Emails
I have been searching and searching for literally 4 days now, how to remove the price from the emails that are being sent to both the customer and to the admin. I was able to remove the Subtotal and Total sections, and the heading for the price per product, but I cannot remove the physical Price cell in the table.

Below is the code I have adjusted, along with a screenshot of what the email looks like.

email_order_details.php

<?php
if ( ! defined( 'ABSPATH' ) ) {
 exit;
}

$text_align = is_rtl() ? 'right' : 'left';

do_action( 'woocommerce_email_before_order_table', $order, $sent_to_admin, $plain_text, $email ); ?>

<?php if ( ! $sent_to_admin ) : ?>

<?php printf( __( 'Order #%s', 'woocommerce' ), $order->get_order_number() ); ?> (<?php printf( '<time datetime="%s">%s</time>', $order->get_date_created()->format( 'c' ), wc_format_datetime( $order->get_date_created() ) ); ?>)

<?php else : ?>

get_id() . '&action=edit' ) ); ?>"><?php printf( __( 'Order #%s', 'woocommerce' ), $order->get_order_number() ); ?> (<?php printf( '<time datetime="%s">%s</time>', $order->get_date_created()->format( 'c' ), wc_format_datetime( $order->get_date_created() ) ); ?>)

<?php endif; ?>

    <th class="td" scope="col" style="text-align:<?php echo $text_align; ?>;"><?php _e( 'Product', 'woocommerce' ); ?>
    <th class="td" scope="col" style="text-align:<?php echo $text_align; ?>;"><?php _e( 'Quantity', 'woocommerce' ); ?>

   <?php echo wc_get_email_order_items( $order, array(
    'show_sku'      => $sent_to_admin,
    'show_image'    => false,
    'image_size'    => array( 32, 32 ),
    'plain_text'    => $plain_text,
    'sent_to_admin' => $sent_to_admin,
   ) ); ?>

   <?php
    if ( $order->get_customer_note() ) {
     ?>

      <th class="td" scope="row" colspan="2" style="text-align:<?php echo $text_align; ?>;"><?php _e( 'Note:', 'woocommerce' ); ?>
      <td class="td" style="text-align:<?php echo $text_align; ?>;"><?php echo wptexturize( $order->get_customer_note() ); ?>

<?php
    }
   ?>

<?php do_action( 'woocommerce_email_after_order_table', $order, $sent_to_admin, $plain_text, $email ); ?>```
</div>
</div>
</p>

<p><strong>email_order_items.php</strong></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-html lang-html prettyprint-override"><code><?php
if ( ! defined( 'ABSPATH' ) ) {
 exit;
}

$text_align = is_rtl() ? 'right' : 'left';

foreach ( $items as $item_id => $item ) :
 $product = $item->get_product();
 if ( apply_filters( 'woocommerce_order_item_visible', true, $item ) ) {
  ?>
  <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_order_item_class', 'order_item', $item, $order ) ); ?>">
   <td class="td" style="text-align:<?php echo $text_align; ?>; vertical-align:middle; border: 1px solid #eee; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif; word-wrap:break-word;"><?php

    // Show title/image etc
    if ( $show_image ) {
     echo apply_filters( 'woocommerce_order_item_thumbnail', '<div style="margin-bottom: 5px"><img src="' . ( $product->get_image_id() ? current( wp_get_attachment_image_src( $product->get_image_id(), 'thumbnail' ) ) : wc_placeholder_img_src() ) . '" alt="' . esc_attr__( 'Product image', 'woocommerce' ) . '" height="' . esc_attr( $image_size[1] ) . '" width="' . esc_attr( $image_size[0] ) . '" style="vertical-align:middle; margin-' . ( is_rtl() ? 'left' : 'right' ) . ': 10px;" /></div>', $item );
    }

    // Product name
    echo apply_filters( 'woocommerce_order_item_name', $item->get_name(), $item, false );

    // SKU
    if ( $show_sku && is_object( $product ) && $product->get_sku() ) {
     echo ' (#' . $product->get_sku() . ')';
    }

    // allow other plugins to add additional product information here
    do_action( 'woocommerce_order_item_meta_start', $item_id, $item, $order, $plain_text );

    wc_display_item_meta( $item );

    // allow other plugins to add additional product information here
    do_action( 'woocommerce_order_item_meta_end', $item_id, $item, $order, $plain_text );

   ?></td>
   <td class="td" style="text-align:<?php echo $text_align; ?>; vertical-align:middle; border: 1px solid #eee; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;"><?php echo apply_filters( 'woocommerce_email_order_item_quantity', $item->get_quantity(), $item ); ?></td>
  </tr>
  <?php
 }

 if ( $show_purchase_note && is_object( $product ) && ( $purchase_note = $product->get_purchase_note() ) ) : ?>
  <tr>
   <td colspan="3" style="text-align:<?php echo $text_align; ?>; vertical-align:middle; border: 1px solid #eee; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;"><?php echo wpautop( do_shortcode( wp_kses_post( $purchase_note ) ) ); ?></td>
  </tr>
 <?php endif; ?>

<?php endforeach; ?></code>```

Screenshot

Thank you.

答:
Modify this template \order\order-details-item.php to remove the item price.

Comment out the following code to remove the price from showing.

```<code><td class="woocommerce-table__product-total product-total">
    <?php echo $order->get_formatted_line_subtotal( $item ); ?>
</td>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Removing Price from Woocommerce Emails

Body:
I have been searching and searching for literally 4 days now, how to remove the price from the emails that are being sent to both the customer and to the admin. I was able to remove the Subtotal and Total sections, and the heading for the price per product, but I cannot remove the physical Price cell in the table.

Below is the code I have adjusted, along with a screenshot of what the email looks like.

email_order_details.php

<?php
if ( ! defined( 'ABSPATH' ) ) {
 exit;
}

$text_align = is_rtl() ? 'right' : 'left';

do_action( 'woocommerce_email_before_order_table', $order, $sent_to_admin, $plain_text, $email ); ?>

<?php if ( ! $sent_to_admin ) : ?>

<?php printf( __( 'Order #%s', 'woocommerce' ), $order->get_order_number() ); ?> (<?php printf( '<time datetime="%s">%s</time>', $order->get_date_created()->format( 'c' ), wc_format_datetime( $order->get_date_created() ) ); ?>)

<?php else : ?>

<a class="link" href="<?php echo esc_url( admin_url( 'post.php?post=' . $order->get_id() . '&action=edit' ) ); ?>"><?php printf( __( 'Order #%s', 'woocommerce' ), $order->get_order_number() ); ?> (<?php printf( '<time datetime="%s">%s</time>', $order->get_date_created()->format( 'c' ), wc_format_datetime( $order->get_date_created() ) ); ?>)

<?php endif; ?>

    <th class="td" scope="col" style="text-align:<?php echo $text_align; ?>;"><?php _e( 'Product', 'woocommerce' ); ?>
    <th class="td" scope="col" style="text-align:<?php echo $text_align; ?>;"><?php _e( 'Quantity', 'woocommerce' ); ?>

   <?php echo wc_get_email_order_items( $order, array(
    'show_sku'      => $sent_to_admin,
    'show_image'    => false,
    'image_size'    => array( 32, 32 ),
    'plain_text'    => $plain_text,
    'sent_to_admin' => $sent_to_admin,
   ) ); ?>

   <?php
    if ( $order->get_customer_note() ) {
     ?>

      <th class="td" scope="row" colspan="2" style="text-align:<?php echo $text_align; ?>;"><?php _e( 'Note:', 'woocommerce' ); ?>
      <td class="td" style="text-align:<?php echo $text_align; ?>;"><?php echo wptexturize( $order->get_customer_note() ); ?>

<?php
    }
   ?>

<?php do_action( 'woocommerce_email_after_order_table', $order, $sent_to_admin, $plain_text, $email ); ?>

email_order_items.php

<?php
if ( ! defined( 'ABSPATH' ) ) {
 exit;
}

$text_align = is_rtl() ? 'right' : 'left';

foreach ( $items as $item_id => $item ) :
 $product = $item->get_product();
 if ( apply_filters( 'woocommerce_order_item_visible', true, $item ) ) {
  ?>
  <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_order_item_class', 'order_item', $item, $order ) ); ?>">
   <td class="td" style="text-align:<?php echo $text_align; ?>; vertical-align:middle; border: 1px solid #eee; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif; word-wrap:break-word;"><?php

    // Show title/image etc
    if ( $show_image ) {
     echo apply_filters( 'woocommerce_order_item_thumbnail', '
get_image_id() ? current( wp_get_attachment_image_src( $product->get_image_id(), 'thumbnail' ) ) : wc_placeholder_img_src() ) . '" alt="' . esc_attr__( 'Product image', 'woocommerce' ) . '" height="' . esc_attr( $image_size[1] ) . '" width="' . esc_attr( $image_size[0] ) . '" style="vertical-align:middle; margin-' . ( is_rtl() ? 'left' : 'right' ) . ': 10px;" />
', $item );
    }

    // Product name
    echo apply_filters( 'woocommerce_order_item_name', $item->get_name(), $item, false );

    // SKU
    if ( $show_sku && is_object( $product ) && $product->get_sku() ) {
     echo ' (#' . $product->get_sku() . ')';
    }

    // allow other plugins to add additional product information here
    do_action( 'woocommerce_order_item_meta_start', $item_id, $item, $order, $plain_text );

    wc_display_item_meta( $item );

    // allow other plugins to add additional product information here
    do_action( 'woocommerce_order_item_meta_end', $item_id, $item, $order, $plain_text );

   ?>
   <td class="td" style="text-align:<?php echo $text_align; ?>; vertical-align:middle; border: 1px solid #eee; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;"><?php echo apply_filters( 'woocommerce_email_order_item_quantity', $item->get_quantity(), $item ); ?>

  <?php
 }

 if ( $show_purchase_note && is_object( $product ) && ( $purchase_note = $product->get_purchase_note() ) ) : ?>

   <td colspan="3" style="text-align:<?php echo $text_align; ?>; vertical-align:middle; border: 1px solid #eee; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;"><?php echo wpautop( do_shortcode( wp_kses_post( $purchase_note ) ) ); ?>

 <?php endif; ?>

<?php endforeach; ?>

Screenshot

Thank you.

Body:
Modify this template \order\order-details-item.php to remove the item price.

Comment out the following code to remove the price from showing.

<td class="woocommerce-table__product-total product-total">
    <?php echo $order->get_formatted_line_subtotal( $item ); ?>
</td>


问:
How to make vscode's emmet allow expanding all custom tags
Previously when typing something in vscode like :-

asd[TAB]
dada[TAB]
sasa[TAB]

would expand into

<asd></asd>
<dada></dada>
<sasa></sasa>

but currently with the implementation of Emmet 2.0 this has changed.
Now it allows expanding html related tags only like ul, li, div, span, etc.

Please tell me if there's a way to obtain the functionality that I need.

答:
You probably have

// When enabled, Emmet abbreviations are expanded when pressing TAB.

```<code>"emmet.triggerExpansionOnTab": false,
</code>```

in your settings.  That is the default, change it to true and it works for me for whatever tags I create.

Body:
You probably have

// When enabled, Emmet abbreviations are expanded when pressing TAB.

"emmet.triggerExpansionOnTab": false,

in your settings.  That is the default, change it to true and it works for me for whatever tags I create.


问:
Spring Boot Testing @WebMvcTest for a Controller appears to load other controllers in the context
Here's my test case for a Spring Controller

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(value = MyController.class)
public class MyControllerTest {

    @MockBean
    private MyService myService;
}
</code>```

So this is a unit test specifically for the methods in MyController. But when I run the test, Spring appears to begin instantiating OtherController and all of it's dependencies.

I have tried updating the above as

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(value = MyController.class, excludeFilters = @ComponentScan.Filter(value= OtherController.class, type = FilterType.ANNOTATION))

   public class MyControllerTest {

...
}
</code>```

But spring still appears to wire it. Here's the error thrown by Spring as it tries to instantiate OtherController when I run the above test specifically.

```<code>2017-01-06 12:09:46.207  WARN 18092 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'otherController' defined in file [C:\..OtherController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getOtherService' defined in com.my.myApplication: Unsatisfied dependency expressed through method 'getOtherService' parameter 0org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getOtherService' defined in com.myOrg.MyServiceApplication: Unsatisfied dependency expressed through method 'getPositionService' parameter 0
</code>```

What could be causing this?

答:
Chances are that you are triggering the bean scanning by accident via a @Componentscan or the likes.

For instance, as explained in this answer, Spring may be detecting your "production" @SpringBootApplication Application class, with all the component scans it brings about. If so make sure you "overwrite" your "production" Application class with your "test" one putting...

```<code>@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

...in a location that would override the "Production" Application.

For instance, if your IDE doesn't get messed by class name clashes:

```<code>"production" -> src/main/java/com/mycompany/Application.java
             -> src/main/java/com/mycompany/controllers/MyController.java
"test"       -> src/test/java/com/mycompany/Application.java
             -> src/test/java/com/mycompany/controllers/MyControllerTest.java
</code>```

As an alternative I also have found that in my case this works as well (i.e. placing the Application in the test controllers folder)

```<code>"production" -> src/main/java/com/mycompany/Application.java
             -> src/main/java/com/mycompany/controllers/MyController.java
"test"       -> src/test/java/com/mycompany/controllers/Application.java
             -> src/test/java/com/mycompany/controllers/MyControllerTest.java
</code>```

Body:
Here's my test case for a Spring Controller

@RunWith(SpringRunner.class)
@WebMvcTest(value = MyController.class)
public class MyControllerTest {

    @MockBean
    private MyService myService;
}

So this is a unit test specifically for the methods in MyController. But when I run the test, Spring appears to begin instantiating OtherController and all of it's dependencies.

I have tried updating the above as

@RunWith(SpringRunner.class)
@WebMvcTest(value = MyController.class, excludeFilters = @ComponentScan.Filter(value= OtherController.class, type = FilterType.ANNOTATION))

   public class MyControllerTest {

...
}

But spring still appears to wire it. Here's the error thrown by Spring as it tries to instantiate OtherController when I run the above test specifically.

2017-01-06 12:09:46.207  WARN 18092 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'otherController' defined in file [C:\..OtherController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getOtherService' defined in com.my.myApplication: Unsatisfied dependency expressed through method 'getOtherService' parameter 0org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getOtherService' defined in com.myOrg.MyServiceApplication: Unsatisfied dependency expressed through method 'getPositionService' parameter 0

What could be causing this?

Body:
Chances are that you are triggering the bean scanning by accident via a @Componentscan or the likes.

For instance, as explained in this answer, Spring may be detecting your "production" @SpringBootApplication Application class, with all the component scans it brings about. If so make sure you "overwrite" your "production" Application class with your "test" one putting...

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

...in a location that would override the "Production" Application.

For instance, if your IDE doesn't get messed by class name clashes:

"production" -> src/main/java/com/mycompany/Application.java
             -> src/main/java/com/mycompany/controllers/MyController.java
"test"       -> src/test/java/com/mycompany/Application.java
             -> src/test/java/com/mycompany/controllers/MyControllerTest.java

As an alternative I also have found that in my case this works as well (i.e. placing the Application in the test controllers folder)

"production" -> src/main/java/com/mycompany/Application.java
             -> src/main/java/com/mycompany/controllers/MyController.java
"test"       -> src/test/java/com/mycompany/controllers/Application.java
             -> src/test/java/com/mycompany/controllers/MyControllerTest.java


问:
How to align image to center of table cell (SWT Table)
I develop Eclipse RCP application and got a problem with a Table. We have some data in database in boolean format and users wants to see that field using checkbox.

I tried to implement it using Button(SWT.CHECK) as Table-Editor, but it worked too slow :(

I tried to use 2 images - checked and unchecked check-boxes, it works, but I can't align them to center, they are aligned to left automatically.

I even found how to catch SWT.MeasureItem and SWT.PaintItem events and process them manually by change event.x field, but I got a problem - I can't get what column measuring or painting at the moment, because Event doesn't provides me that information.

Is it the only way to align images to center by modify event data on redrawing, or may be there is other ways to represent boolean data via check-boxes? I don't need to edit them now, so read-only mode should be enough.

答:
Sorceror's solution came in handy. I've adapted it to a custom IStyledLabelProvider to be used within a DelegatingStyledCellLabelProvider:

```<code>public class MutedLabelProvider extends LabelProvider implements IStyledLabelProvider {

  public MutedLabelProvider(Tree containerTree, int columnIndex) {
    registerIconListener(containerTree, columnIndex);
  }

  @Override
  public StyledString getStyledText(Object element) {
    return new StyledString();
  }

  private void registerIconListener(Tree containerTree, int columnIndex) {
    containerTree.addListener(SWT.PaintItem, new Listener() {
      @Override
      public void handleEvent(Event event) {
        if (event.index == columnIndex) {
          TreeItem treeItem = (TreeItem) event.item;
          Object data = treeItem.getData();
          Image tmpImage = getImageFromData(data);
          if (tmpImage != null) {
            int tmpWidth = 0;
            int tmpHeight = 0;
            int tmpX = 0;
            int tmpY = 0;
            tmpWidth = containerTree.getColumn(event.index).getWidth();
            tmpHeight = treeItem.getBounds().height;
            tmpX = tmpImage.getBounds().width;
            tmpX = (tmpWidth / 2 - tmpX / 2);
            tmpY = tmpImage.getBounds().height;
            tmpY = (tmpHeight / 2 - tmpY / 2);
            if (tmpX <= 0) tmpX = event.x;
            else tmpX += event.x;
            if (tmpY <= 0) tmpY = event.y;
            else tmpY += event.y;
            event.gc.drawImage(tmpImage, tmpX, tmpY);
          }
        }
      }
    });
  }

  private Image getImageFromData(Object element) {
    if (element != null && element instanceof IMarker) {
      IMarker marker = (IMarker) element;
      boolean isItTrue = marker.getAttribute("MyBooleanAttr", false);
      if (isItTrue) {
        // TODO return here the image you want for true state
        return JFaceResources.getImageRegistry().get("MyImageForTrue");
      } else {
        // TODO return here the image you want for false state
        // Alternatively, you can return null for no image
        return null;
      }
    } else {
      return null;
    }
  }

}
</code>```

Note that I'm using IMarker as data for elements, and a TreeViewer (so I'm receiving TreeItems), but your data might differ, and your viewer might be a TableViewer; you just have to make your own adjustments.

Body:
Sorceror's solution came in handy. I've adapted it to a custom IStyledLabelProvider to be used within a DelegatingStyledCellLabelProvider:

public class MutedLabelProvider extends LabelProvider implements IStyledLabelProvider {

  public MutedLabelProvider(Tree containerTree, int columnIndex) {
    registerIconListener(containerTree, columnIndex);
  }

  @Override
  public StyledString getStyledText(Object element) {
    return new StyledString();
  }

  private void registerIconListener(Tree containerTree, int columnIndex) {
    containerTree.addListener(SWT.PaintItem, new Listener() {
      @Override
      public void handleEvent(Event event) {
        if (event.index == columnIndex) {
          TreeItem treeItem = (TreeItem) event.item;
          Object data = treeItem.getData();
          Image tmpImage = getImageFromData(data);
          if (tmpImage != null) {
            int tmpWidth = 0;
            int tmpHeight = 0;
            int tmpX = 0;
            int tmpY = 0;
            tmpWidth = containerTree.getColumn(event.index).getWidth();
            tmpHeight = treeItem.getBounds().height;
            tmpX = tmpImage.getBounds().width;
            tmpX = (tmpWidth / 2 - tmpX / 2);
            tmpY = tmpImage.getBounds().height;
            tmpY = (tmpHeight / 2 - tmpY / 2);
            if (tmpX <= 0) tmpX = event.x;
            else tmpX += event.x;
            if (tmpY <= 0) tmpY = event.y;
            else tmpY += event.y;
            event.gc.drawImage(tmpImage, tmpX, tmpY);
          }
        }
      }
    });
  }

  private Image getImageFromData(Object element) {
    if (element != null && element instanceof IMarker) {
      IMarker marker = (IMarker) element;
      boolean isItTrue = marker.getAttribute("MyBooleanAttr", false);
      if (isItTrue) {
        // TODO return here the image you want for true state
        return JFaceResources.getImageRegistry().get("MyImageForTrue");
      } else {
        // TODO return here the image you want for false state
        // Alternatively, you can return null for no image
        return null;
      }
    } else {
      return null;
    }
  }

}

Note that I'm using IMarker as data for elements, and a TreeViewer (so I'm receiving TreeItems), but your data might differ, and your viewer might be a TableViewer; you just have to make your own adjustments.


问:
How to scroll to text input on focus when there is an input accessory with React Native
I'm working on a React Native app and many screens has forms with text input fields.

When I press the text input, the keyboard opens. I created a floating InputAccessory component which appears at the top of the keyboard to dismiss it, with the button "Done" on it.

However now that I have this accessory, when I click an input field or press the "Next" button on the keyboard to go to the next field, the ScrollView scrolls to align the bottom of the text input with the top of the keyboard. With this floating accessory it poses problems as you can see below you can't see the content of the text input because of this accessory, and I'd like to have the scrollview scrolling a bit more to display the entire text input.

I could probably do the calculation for this and run the .scrollTo() method from the ScrollView component but this pattern is very common to my entire app and I'm looking for an elegant solution that could be generic enough every single time I import a text input and focus on it.

Do you have any suggestion?

Thanks

答:
I got the same issue before and i have 2 different solutions , Both of them worked for me.

1- Using react-native-keyboard-aware-scroll-view , Note that this library will already contain scrollView so you remove your own scroll view and use

```<code><KeyboardAwareScrollView>
  <View>
    <TextInput />
  </View>
</KeyboardAwareScrollView>
</code>```

You can also check documentation for more info.

This solution is easier as you don't need to handle anything by yourself, but i think you will have some issues if you want to include scrollView inside it.

2- I once created a component AvoidKeyboard that actually does something similar to your solution, but it used to translate top the whole view with the keyboard height value, this solution worked perfectly also for me.

Implementation

```<code>import React, { Component } from 'react';
import { Animated, Easing, Keyboard } from 'react-native';
import PropTypes from 'prop-types';

class AvoidKeyboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      animatedViewHeight: new Animated.Value(0),
      viewHeight: 0,
    };

    this.setViewHeightOnce = this.setViewHeightOnce.bind(this);
    this.keyboardWillShow = this.keyboardWillShow.bind(this);
    this.keyboardWillHide = this.keyboardWillHide.bind(this);
    this.keyboardDidShowListener = Keyboard.addListener('keyboardWillShow', this.keyboardWillShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardWillHide', this.keyboardWillHide);
  }

  componentWillUnmount() {
    this.keyboardDidShowListener && this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener && this.keyboardDidHideListener.remove();
  }

  setViewHeightOnce(event) {
    const { height } = event.nativeEvent.layout;
    if (this.state.viewHeight === 0) {
      const avoidPaddingBottom = 15;
      this.setState({
        viewHeight: height + avoidPaddingBottom,
        animatedViewHeight: new Animated.Value(height + avoidPaddingBottom),
      });
    }
  }

  keyboardWillShow(e) {
    const { viewHeight } = this.state;
    if (viewHeight) {
      requestAnimationFrame(() => { // eslint-disable-line no-undef
        Animated.timing(this.state.animatedViewHeight, {
          toValue: (viewHeight - e.endCoordinates.height),
          duration: 200,
          delay: 0,
          easing: Easing.inOut(Easing.ease),
        }).start();
      });
    }
  }

  keyboardWillHide() {
    requestAnimationFrame(() => { // eslint-disable-line no-undef
      Animated.timing(this.state.animatedViewHeight, {
        toValue: this.state.viewHeight,
        duration: 200,
        delay: 0,
        easing: Easing.inOut(Easing.ease),
      }).start();
    });
  }

  render() {
    let animatedHeight;
    const { viewHeight } = this.state;
    if (viewHeight > 0) {
      animatedHeight = { maxHeight: this.state.animatedViewHeight };
    }
    return (
      <Animated.View
        style={[{ flex: 1, justifyContent: 'flex-end' }, animatedHeight]}
        onLayout={this.setViewHeightOnce}
      >
        {this.props.children}
      </Animated.View>
    );
  }
}

AvoidKeyboard.propTypes = {
  children: PropTypes.node.isRequired,
};

export default AvoidKeyboard;
</code>```

Now you just need to wrap your component or screen inside AvoidKeyboard and your screen height will shrink once keyboard is open, and you will be able to scroll the screen

Body:
I got the same issue before and i have 2 different solutions , Both of them worked for me.

1- Using react-native-keyboard-aware-scroll-view , Note that this library will already contain scrollView so you remove your own scroll view and use

<KeyboardAwareScrollView>
  <View>
    <TextInput />
  </View>
</KeyboardAwareScrollView>

You can also check documentation for more info.

This solution is easier as you don't need to handle anything by yourself, but i think you will have some issues if you want to include scrollView inside it.

2- I once created a component AvoidKeyboard that actually does something similar to your solution, but it used to translate top the whole view with the keyboard height value, this solution worked perfectly also for me.

Implementation

import React, { Component } from 'react';
import { Animated, Easing, Keyboard } from 'react-native';
import PropTypes from 'prop-types';

class AvoidKeyboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      animatedViewHeight: new Animated.Value(0),
      viewHeight: 0,
    };

    this.setViewHeightOnce = this.setViewHeightOnce.bind(this);
    this.keyboardWillShow = this.keyboardWillShow.bind(this);
    this.keyboardWillHide = this.keyboardWillHide.bind(this);
    this.keyboardDidShowListener = Keyboard.addListener('keyboardWillShow', this.keyboardWillShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardWillHide', this.keyboardWillHide);
  }

  componentWillUnmount() {
    this.keyboardDidShowListener && this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener && this.keyboardDidHideListener.remove();
  }

  setViewHeightOnce(event) {
    const { height } = event.nativeEvent.layout;
    if (this.state.viewHeight === 0) {
      const avoidPaddingBottom = 15;
      this.setState({
        viewHeight: height + avoidPaddingBottom,
        animatedViewHeight: new Animated.Value(height + avoidPaddingBottom),
      });
    }
  }

  keyboardWillShow(e) {
    const { viewHeight } = this.state;
    if (viewHeight) {
      requestAnimationFrame(() => { // eslint-disable-line no-undef
        Animated.timing(this.state.animatedViewHeight, {
          toValue: (viewHeight - e.endCoordinates.height),
          duration: 200,
          delay: 0,
          easing: Easing.inOut(Easing.ease),
        }).start();
      });
    }
  }

  keyboardWillHide() {
    requestAnimationFrame(() => { // eslint-disable-line no-undef
      Animated.timing(this.state.animatedViewHeight, {
        toValue: this.state.viewHeight,
        duration: 200,
        delay: 0,
        easing: Easing.inOut(Easing.ease),
      }).start();
    });
  }

  render() {
    let animatedHeight;
    const { viewHeight } = this.state;
    if (viewHeight > 0) {
      animatedHeight = { maxHeight: this.state.animatedViewHeight };
    }
    return (
      <Animated.View
        style={[{ flex: 1, justifyContent: 'flex-end' }, animatedHeight]}
        onLayout={this.setViewHeightOnce}
      >
        {this.props.children}
      </Animated.View>
    );
  }
}

AvoidKeyboard.propTypes = {
  children: PropTypes.node.isRequired,
};

export default AvoidKeyboard;

Now you just need to wrap your component or screen inside AvoidKeyboard and your screen height will shrink once keyboard is open, and you will be able to scroll the screen

ContentLicense: CC BY-SA 4.0


问:
object oriented JavaScript
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

```<code>function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}
</code>```

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

```<code>function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

and

```<code>var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

答:
Before I comment your code, read a Tutorial: https://developer.mozilla.org/en/JavaScript/Guide

And now for entertaiment:

```<code>function Point()
{
    var x; // great a local variable!
    var y; // another one! they drop out of scope... (protip: use 'this')
}

var length = 1; // ???
var arrayindex; // better declare that in the for
var newpoint[0] =  new Point; // that works yes, but only the `new Point` part, 'newpoint[0]' what is that supposed to do?
newpoint[0].x = 10; // there's no x property on a `Point` here
newpoint[0].y = 10;
for(i=0 ; i<10; i ++) // i leaks into global scope
{
    newpoint[length].x = 10*i; // ??? Fails, newpoint is not an array
    newpoint[length++].y = 10*i; // Again, what's the point of this?
}

for(arrayindex in newpoint ) // great! a extremely slow for in to iterate over an array..
// pro tip, this will enumerate over all the _properties_ of the _object_
{
    // usual complain about the missing 'hasOwnProperty' call (TM)
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: object oriented JavaScript

Body:
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

and

var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

Body:
Before I comment your code, read a Tutorial: https://developer.mozilla.org/en/JavaScript/Guide

And now for entertaiment:

function Point()
{
    var x; // great a local variable!
    var y; // another one! they drop out of scope... (protip: use 'this')
}

var length = 1; // ???
var arrayindex; // better declare that in the for
var newpoint[0] =  new Point; // that works yes, but only the `new Point` part, 'newpoint[0]' what is that supposed to do?
newpoint[0].x = 10; // there's no x property on a `Point` here
newpoint[0].y = 10;
for(i=0 ; i<10; i ++) // i leaks into global scope
{
    newpoint[length].x = 10*i; // ??? Fails, newpoint is not an array
    newpoint[length++].y = 10*i; // Again, what's the point of this?
}

for(arrayindex in newpoint ) // great! a extremely slow for in to iterate over an array..
// pro tip, this will enumerate over all the _properties_ of the _object_
{
    // usual complain about the missing 'hasOwnProperty' call (TM)
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}


问:
Why does Python code runs slower if I use muliple processes
Hello I'm very depressed at the moment because of failing to speed up my Code:
I tried different stuff and now I used Multiprocessor Pools. To evaluate the speedup and effects of the Processornumbers I variate the number of processors I use. However, I lose speed if I increase the number of processors. I dont know why because in theory I compute 8 images parallel if i have 8 processes and 4 if I use 4 processes. Sure there is an overhead but this should not be such a big bottleneck. Does anyone spot the mistake here? Kind regards Max</p>

```<code>'''
Created on 17.11.2017

@author: Max
'''
#!/usr/bin/env python

import os, sys, errno
import re
import argparse
from time import time
import multiprocessing
import glob
import numpy as np
import matplotlib.pyplot as plt
import cv2
def computeFeatures(input, chunk_num):
    thresholded_chunk = []
    #print("Processing Chunk,",chunk_num)
    cv2.threshold(input,127,255,cv2.THRESH_BINARY_INV)
    cv2.threshold(input,127,255,cv2.THRESH_BINARY_INV)
    cv2.threshold(input,127,255,cv2.THRESH_BINARY_INV)
    cv2.threshold(input,127,255,cv2.THRESH_BINARY_INV)
    thresholded_chunk.append(cv2.threshold(input,127,255,cv2.THRESH_BINARY_INV))
    return (thresholded_chunk, chunk_num)

if __name__ == '__main__':
    num_Proc = 2
    max_Proc = 20
    while num_Proc != max_Proc:

        start = time()
        # Handle command line options
        numProcessors = num_Proc

        # Start my pool
        pool = multiprocessing.Pool(numProcessors)

        # Build task list
        path = "InputSimulation\*"
        tasks = []
        image_list= []
        img_idx = 0
        image_pathes = glob.glob(path+".jpg")
        results = []
        index_for_chunk = numProcessors
        while img_idx < len(image_pathes):
            #print("InsterImageNumber",img_idx)
            tasks.append( (cv2.imread(image_pathes[img_idx],0), img_idx, ) )
            if img_idx % numProcessors == 0:
                result = [pool.apply_async( computeFeatures, t ) for t in tasks]
                results.append(result)
                tasks = []
            img_idx +=1
        pool.close()
        pool.join()
            # Run tasks    #Flatten list before print

        end = time()
        print("DURATION FOR " +str(num_Proc) +" PROCESSES",end - start)
        num_Proc +=1
        # Process results
</code>```

答:
Since your not using any callback function with apply_async and always use the same function (computeFeatures) you are better of using Pool.map(). In your current use case apply_async will not preform any computations in parallel. On top of that it will add overhead for each computation.

Example:

```<code>from multiprocessing import Pool
from math import sqrt

p = Pool(8)
num_list = range(100000)

%%time
_ = p.map(sqrt, num_list)
</code>```

CPU times: user 19 ms, sys: 2.36 ms, total: 21.4 ms

Wall time: 27.7 ms

```<code>%%time
_ = [sqrt(num) for num in num_list]
</code>```

CPU times: user 33.7 ms, sys: 5.93 ms, total: 39.6 ms

Wall time: 37.5 ms

```<code>%%time
_ = [p.apply_async(sqrt, num) for num in num_list]
</code>```

CPU times: user 5.5 s, sys: 1.37 s, total: 6.87 s

Wall time: 5.95 s

As shown by this example. Simple computation is best done with Pool.map() Change your code into using map and you might see some improvement. Also its important to find the correct number of workers for your system and problem at hand.

```<code>result = pool.map(computeFeatures, tasks)
</code>```

Body:
Hello I'm very depressed at the moment because of failing to speed up my Code:
I tried different stuff and now I used Multiprocessor Pools. To evaluate the speedup and effects of the Processornumbers I variate the number of processors I use. However, I lose speed if I increase the number of processors. I dont know why because in theory I compute 8 images parallel if i have 8 processes and 4 if I use 4 processes. Sure there is an overhead but this should not be such a big bottleneck. Does anyone spot the mistake here? Kind regards Max

'''
Created on 17.11.2017

@author: Max
'''
#!/usr/bin/env python

import os, sys, errno
import re
import argparse
from time import time
import multiprocessing
import glob
import numpy as np
import matplotlib.pyplot as plt
import cv2
def computeFeatures(input, chunk_num):
    thresholded_chunk = []
    #print("Processing Chunk,",chunk_num)
    cv2.threshold(input,127,255,cv2.THRESH_BINARY_INV)
    cv2.threshold(input,127,255,cv2.THRESH_BINARY_INV)
    cv2.threshold(input,127,255,cv2.THRESH_BINARY_INV)
    cv2.threshold(input,127,255,cv2.THRESH_BINARY_INV)
    thresholded_chunk.append(cv2.threshold(input,127,255,cv2.THRESH_BINARY_INV))
    return (thresholded_chunk, chunk_num)

if __name__ == '__main__':
    num_Proc = 2
    max_Proc = 20
    while num_Proc != max_Proc:

        start = time()
        # Handle command line options
        numProcessors = num_Proc

        # Start my pool
        pool = multiprocessing.Pool(numProcessors)

        # Build task list
        path = "InputSimulation\*"
        tasks = []
        image_list= []
        img_idx = 0
        image_pathes = glob.glob(path+".jpg")
        results = []
        index_for_chunk = numProcessors
        while img_idx < len(image_pathes):
            #print("InsterImageNumber",img_idx)
            tasks.append( (cv2.imread(image_pathes[img_idx],0), img_idx, ) )
            if img_idx % numProcessors == 0:
                result = [pool.apply_async( computeFeatures, t ) for t in tasks]
                results.append(result)
                tasks = []
            img_idx +=1
        pool.close()
        pool.join()
            # Run tasks    #Flatten list before print

        end = time()
        print("DURATION FOR " +str(num_Proc) +" PROCESSES",end - start)
        num_Proc +=1
        # Process results

Body:
Since your not using any callback function with apply_async and always use the same function (computeFeatures) you are better of using Pool.map(). In your current use case apply_async will not preform any computations in parallel. On top of that it will add overhead for each computation.

Example:

from multiprocessing import Pool
from math import sqrt

p = Pool(8)
num_list = range(100000)

%%time
_ = p.map(sqrt, num_list)

CPU times: user 19 ms, sys: 2.36 ms, total: 21.4 ms

Wall time: 27.7 ms

%%time
_ = [sqrt(num) for num in num_list]

CPU times: user 33.7 ms, sys: 5.93 ms, total: 39.6 ms

Wall time: 37.5 ms

%%time
_ = [p.apply_async(sqrt, num) for num in num_list]

CPU times: user 5.5 s, sys: 1.37 s, total: 6.87 s

Wall time: 5.95 s

As shown by this example. Simple computation is best done with Pool.map() Change your code into using map and you might see some improvement. Also its important to find the correct number of workers for your system and problem at hand.

result = pool.map(computeFeatures, tasks)


问:
How to install ipython or flask and there dependences in virtualenv?
I have learned the dependences should be installed automatically, but it only install itself when I install flask in a virtualenv.

```<code>Installing collected packages: flask
Successfully installed flask-0.12.2

➜  ~ python
Python 3.6.2 (default, Sep 15 2017, 07:44:18)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from flask import Flask
Trceback...
...
ModuleNotFoundError: No module named 'werkzeug'
</code>```

Then I have to install werkzeug and re-import Flask

but:

```<code>ModuleNotFoundError: No module named 'jinja2'
</code>```

After install jinja2, there still markupsafe, itsdangerous (etc) to install to run Flask.

Solved

I forgot when did I set 'no-dependences = True' in .pip/pip.conf.

Now it's okey after detele the line.

答:
My suspicion is that you've either

installed packages into virtualenv but receive these errors when the virtualenv is not activated i.e. when interpreter has no access to those packages

or

vice versa i.e. installed packages globally and then activated virtualenv, where by default the only pre-installed packages are pip, setuptools, and wheel.

I would suggest activating the virtualenv [from dir holding venv, run . <venvName>/bin/activate] and checking packages available [pip list]. Then, deactivate and check global packages available.

Body:
I have learned the dependences should be installed automatically, but it only install itself when I install flask in a virtualenv.

Installing collected packages: flask
Successfully installed flask-0.12.2

➜  ~ python
Python 3.6.2 (default, Sep 15 2017, 07:44:18)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from flask import Flask
Trceback...
...
ModuleNotFoundError: No module named 'werkzeug'

Then I have to install werkzeug and re-import Flask

but:

ModuleNotFoundError: No module named 'jinja2'

After install jinja2, there still markupsafe, itsdangerous (etc) to install to run Flask.

Solved

I forgot when did I set 'no-dependences = True' in .pip/pip.conf.

Now it's okey after detele the line.


问:
Catching input events
I have a form with TextBox, ComboBox and CheckBox that are filled from a function (with textbox.text = "newValue"; for example).

```<code>private void updateIdentite(Contact c, Dal dal)
{
    Identite id = dal.GetIdentite(c);
    if (id != null)
    {
        idCivilite.SelectedValue = id.type_civilite;//example of a ComboBox
        ...
        idNom.Text = id.pers_nom;//example of a TextBox
        ...
        idAi.IsChecked = (id.cont_drap_ai == "1");//example of a CheckBox
        ...
    }
}
</code>```

I need to catch an event when an item is edited manually by the user, but with TextChanged, SelectionChanged or Checked, these events are also fired when the form is filled with the previous function.

```<code>foreach (object item in identiteGrid.Children)
{
    TextBox tb = item as TextBox;
    if (tb != null)
    {
        tb.TextChanged += new TextChangedEventHandler(idTextBox_TextChanged);
        continue;
    }
    ComboBox droplist = item as ComboBox;
    if (droplist != null)
    {
        droplist.SelectionChanged += new SelectionChangedEventHandler(idCombobox_SelectionChanged);
        continue;
    }
    CheckBox cb = item as CheckBox;
    if (cb != null)
    {
        cb.Checked += new RoutedEventHandler(idCheckbox_Checked);
        continue;
    }
}
</code>```

Is there any way to catch an "onInput" event for those controls ?

Thanks

答:
Grabbing User Input

Consider using: Control.OnKeyDown Method.

in order to place input by the user he must be with focus on the control and hit some key.

Also , if you want to be fully covered you can also hook Control.MouseClick Event on the controls...

Read more on these events.

https://msdn.microsoft.com/en-us/library/system.windows.forms.control.onkeydown(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.windows.forms.control.mouseclick(v=vs.110).aspx

Title: Catching input events

Body:
I have a form with TextBox, ComboBox and CheckBox that are filled from a function (with textbox.text = "newValue"; for example).

private void updateIdentite(Contact c, Dal dal)
{
    Identite id = dal.GetIdentite(c);
    if (id != null)
    {
        idCivilite.SelectedValue = id.type_civilite;//example of a ComboBox
        ...
        idNom.Text = id.pers_nom;//example of a TextBox
        ...
        idAi.IsChecked = (id.cont_drap_ai == "1");//example of a CheckBox
        ...
    }
}

I need to catch an event when an item is edited manually by the user, but with TextChanged, SelectionChanged or Checked, these events are also fired when the form is filled with the previous function.

foreach (object item in identiteGrid.Children)
{
    TextBox tb = item as TextBox;
    if (tb != null)
    {
        tb.TextChanged += new TextChangedEventHandler(idTextBox_TextChanged);
        continue;
    }
    ComboBox droplist = item as ComboBox;
    if (droplist != null)
    {
        droplist.SelectionChanged += new SelectionChangedEventHandler(idCombobox_SelectionChanged);
        continue;
    }
    CheckBox cb = item as CheckBox;
    if (cb != null)
    {
        cb.Checked += new RoutedEventHandler(idCheckbox_Checked);
        continue;
    }
}

Is there any way to catch an "onInput" event for those controls ?

Thanks


问:
Xamarin : Change label text inside listview
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have a Label and 2 images inside listview-viewcell. I want to change the label text onclick of images. Increase the label text value by 1 if click like and decrease by 1 if click unlike. I use the label x:name, but it is not accessible in class. How can i fix this?

```<code>    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>
                        <Label
                            Text="{Binding likeCount}"
                            x:Name="likecount"/>
                         <Image Source="like.png">
                               <Image.GestureRecognizers>
                                    <TapGestureRecognizer
                                        Tapped="LikeOrUnlikeTweet"
                                        CommandParameter="{Binding .}"
                                        NumberOfTapsRequired="1" />
                                </Image.GestureRecognizers>
                            </Image
                            <Image Source="unlike.png">
                               <Image.GestureRecognizers>
                                    <TapGestureRecognizer
                                        Tapped="LikeOrUnlikeTweet"
                                        CommandParameter="{Binding .}"
                                        NumberOfTapsRequired="1" />
                                </Image.GestureRecognizers>
                            </Image
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>
</code>```

Anybody please suggest a solution with working code.
Thanks in advance

答:
I would take one of 2 paths for doing this:

Use an ObservableCollection as ItemsSource for your list, obvious when you change properties of an item they would be reflected in the list. What the list view would do is it would replace the old item with the new one modified with your new values. You can make a search about what an ObservableCollection collection is.

My actual way, as im fighting low performance of android with listviews, and this makes it: you can create a custom class for ViewCell, avoid low-speed bindings, set all properties inside your custom ViewCell by code. When the cell bindigcontext changes more likely the ItemsSource item is being assigned to your cell, so you can now take its value ans set it up.

```<code>protected override void OnBindingContextChanged()
{
    SetupCell(); //assign values to named controls manually
    base.OnBindingContextChanged();
}

    public void SetupCell()
    {
        var item = BindingContext as YouItemClass;
        if (item == null) return;

        txtTitle.Text = item.Name;
</code>```

//etc
...

Body:
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have a Label and 2 images inside listview-viewcell. I want to change the label text onclick of images. Increase the label text value by 1 if click like and decrease by 1 if click unlike. I use the label x:name, but it is not accessible in class. How can i fix this?

    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>

                         <Image Source="like.png">
                               <Image.GestureRecognizers>
                                    <TapGestureRecognizer
                                        Tapped="LikeOrUnlikeTweet"
                                        CommandParameter="{Binding .}"
                                        NumberOfTapsRequired="1" />
                                </Image.GestureRecognizers>
                            </Image
                            <Image Source="unlike.png">
                               <Image.GestureRecognizers>
                                    <TapGestureRecognizer
                                        Tapped="LikeOrUnlikeTweet"
                                        CommandParameter="{Binding .}"
                                        NumberOfTapsRequired="1" />
                                </Image.GestureRecognizers>
                            </Image
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>

Anybody please suggest a solution with working code.
Thanks in advance

Body:
I would take one of 2 paths for doing this:

Use an ObservableCollection as ItemsSource for your list, obvious when you change properties of an item they would be reflected in the list. What the list view would do is it would replace the old item with the new one modified with your new values. You can make a search about what an ObservableCollection collection is.

My actual way, as im fighting low performance of android with listviews, and this makes it: you can create a custom class for ViewCell, avoid low-speed bindings, set all properties inside your custom ViewCell by code. When the cell bindigcontext changes more likely the ItemsSource item is being assigned to your cell, so you can now take its value ans set it up.

protected override void OnBindingContextChanged()
{
    SetupCell(); //assign values to named controls manually
    base.OnBindingContextChanged();
}

    public void SetupCell()
    {
        var item = BindingContext as YouItemClass;
        if (item == null) return;

        txtTitle.Text = item.Name;

//etc
...


问:
Standalone Java Unit Test v/s Tomcat web app
We are testing the load on a web app, using jmeter. Now, with Jmeter, the server just gives up after some time, around 100 DB connections. The issue is that the standalone java unit test runs for more than 2000 invocations without any slow up or blocking and I see that a single DB connection is used for it. Why is there such a huge difference in the performance?</p>

答: The tests that I ran were direct connections to DB and kind of single DB calls, but whereas in tomcat, the workflows are longer and more random. With these points in mind, I have started modifying the tomcat web app code to minimize these transactions and use read-only queries wherever needed.</p>


问:
jQuery children selector
I have the following markup:

```<code><div class="form-fields">
  <div class="row">
    <span class="info">Info</span>
  </div>
</div>
</code>```

Using the children selector how can I select span.info? I have tried doing:

$('.form-fields').children('.row .info')

But this didn't work for me.

EDIT: Thanks for the answers everyone. If I assign the container DIV as follows:

var parentDiv = $('.form-fields')

Then using the var 'parentDiv' what is the best way to select span.info?

答:
Why do you need to use .children?

```<code>$('.form-fields span.info')
</code>```

Title: jQuery children selector

Body:
I have the following markup:

    Info

Using the children selector how can I select span.info? I have tried doing:

$('.form-fields').children('.row .info')

But this didn't work for me.

EDIT: Thanks for the answers everyone. If I assign the container DIV as follows:

var parentDiv = $('.form-fields')

Then using the var 'parentDiv' what is the best way to select span.info?

Body:
Why do you need to use .children?

$('.form-fields span.info')


问:
C - Null Terminating char doesnt stop printing
in this part of code:

```<code>char* data;
char num[10];

sprintf(num, "%d", 260);
strcat(data, num);
strcat(data, "\0");

sprintf(num, "%d", 130);
strcat(data, num);

sprintf(num, "%d", 128);
strcat(data, num);

printf("Data: %s", data);
</code>```

it's printing:

```<code>Data: 260130128
</code>```

Why does this happen? The null terminator character shouldnt terminate the printing?

Thank you

Edits:

The data has been initialized before, I am getting it from a function.

Why does not print only 260? How can I do it?

答:
No. strcat removes the trailing nul character before appending.

Reference http://www.cplusplus.com/reference/cstring/strcat/

Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.

Body:
in this part of code:

char* data;
char num[10];

sprintf(num, "%d", 260);
strcat(data, num);
strcat(data, "\0");

sprintf(num, "%d", 130);
strcat(data, num);

sprintf(num, "%d", 128);
strcat(data, num);

printf("Data: %s", data);

it's printing:

Data: 260130128

Why does this happen? The null terminator character shouldnt terminate the printing?

Thank you

Edits:

The data has been initialized before, I am getting it from a function.

Why does not print only 260? How can I do it?


问:
Can't push my changes to a branch
I hope someone can help me with this issue. I've been working on this specific project for a while now and only recently have I been getting this issue every time I try to push my changes to the remote branch.

It seems like it needs all other branches to be updated before I can push my latest changes on the current branch.

答: this means that on the other branches an update was committed. update your branches and merge if that is needed. when everything is up-to-date then you can post all your changes to the "remote" branch.</p>

Title: Can't push my changes to a branch


答:
Use find to get non-direct descendants:

```<code>$('.form-fields').find('.row .info')
</code>```

Title: jQuery children selector

Body:
Use find to get non-direct descendants:

$('.form-fields').find('.row .info')


问:
Rocket.Chat as Docker-Container using sub folder
I'm trying to run RocketChat as a docker container with reverse proxy in a sub folder (https://001docker2t/rocketchat).
My problem is that file upload is using the wrong url (https://001docker2t/ufs/...) and stay at 0%.

As in the documentation for sub folders (https://rocket.chat/docs/installation/manual-installation/running-in-a-sub-folder) i set the ROOT_URL to https://001docker2t/rocketchat/. In the application i set under Admin > General only the domain.

Do i have a wrong configuration or is there something wrong with uploads using subfolders?

Docker calls:

docker run --name rocketchatdb --restart unless-stopped -d -v /var/docker/rocketchat/db:/data/db mongo:3.0 --smallfiles

docker run --name rocketchat --restart unless-stopped -p 172.17.0.1:3000:3000 --link rocketchatdb --env ROOT_URL=https://001docker2t/rocketchat/ --env MONGO_URL=mongodb://rocketchatdb:27017/meteor -d rocket.chat

Versions:

NODE_VERSION    4.8.2

YARN_VERSION    0.22.0

RC_VERSION  0.54.2

答: Update to latest version (verified on 0.59.3), it was fixed already.</p>


问:
C++ Input Sentence
I have a problem with inputting sentences to char or string.

```<code>std::string STabPytania;
bool OK=true;

void pobieranie()
{
    cout << "Podaj ilosc pytan :";
    cin >> iloscP;

    for (pytanie = 1; pytanie <= iloscP; pytanie++)
    {
        cout << "__________________________________________________________";
        cout << "\n Napisz tresc pytania nr" << pytanie << " :";
        std::getline(cin, STabPytania);
        cout << "\n Podaj ilosc odpowiedzi dla: " << pytanie << " pytania:";
        cin >> iloscO;
        for (odpowiedzi = 1; odpowiedzi <= iloscO; odpowiedzi++)
        {
            cout << "\n Napisz tresc odpowiedzi nr" << odpowiedzi << " :";
            cin >> TabOdpowiedzi[pytanie][odpowiedzi];
        }
    }
}
</code>```

But when it comes to asking me for sentence program skips to next instruction without waiting for me input, why?

Debuging

Code

答:
cin some times create issues because of \n character in the buffer. So clean that each time with cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); like below:-

```<code>void pobieranie()
{
 cout << "Podaj ilosc pytan :";
 cin >> iloscP;
 cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
for (pytanie = 1; pytanie <= iloscP; pytanie++)
{
    cout << "__________________________________________________________";
    cout << "\n Napisz tresc pytania nr" << pytanie << " :";
    std::getline(cin, STabPytania);
    cout << "\n Podaj ilosc odpowiedzi dla: " << pytanie << " pytania:";
    cin >> iloscO;
    cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
    for (odpowiedzi = 1; odpowiedzi <= iloscO; odpowiedzi++)
    {
        cout << "\n Napisz tresc odpowiedzi nr" << odpowiedzi << " :";
        cin >> TabOdpowiedzi[pytanie][odpowiedzi];
        cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
    }
  }
}
</code>```

Title: C++ Input Sentence

Body:
I have a problem with inputting sentences to char or string.

std::string STabPytania;
bool OK=true;

void pobieranie()
{
    cout << "Podaj ilosc pytan :";
    cin >> iloscP;

    for (pytanie = 1; pytanie <= iloscP; pytanie++)
    {
        cout << "__________________________________________________________";
        cout << "\n Napisz tresc pytania nr" << pytanie << " :";
        std::getline(cin, STabPytania);
        cout << "\n Podaj ilosc odpowiedzi dla: " << pytanie << " pytania:";
        cin >> iloscO;
        for (odpowiedzi = 1; odpowiedzi <= iloscO; odpowiedzi++)
        {
            cout << "\n Napisz tresc odpowiedzi nr" << odpowiedzi << " :";
            cin >> TabOdpowiedzi[pytanie][odpowiedzi];
        }
    }
}

But when it comes to asking me for sentence program skips to next instruction without waiting for me input, why?

Debuging

Code

Body:
cin some times create issues because of \n character in the buffer. So clean that each time with cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); like below:-

void pobieranie()
{
 cout << "Podaj ilosc pytan :";
 cin >> iloscP;
 cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
for (pytanie = 1; pytanie <= iloscP; pytanie++)
{
    cout << "__________________________________________________________";
    cout << "\n Napisz tresc pytania nr" << pytanie << " :";
    std::getline(cin, STabPytania);
    cout << "\n Podaj ilosc odpowiedzi dla: " << pytanie << " pytania:";
    cin >> iloscO;
    cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
    for (odpowiedzi = 1; odpowiedzi <= iloscO; odpowiedzi++)
    {
        cout << "\n Napisz tresc odpowiedzi nr" << odpowiedzi << " :";
        cin >> TabOdpowiedzi[pytanie][odpowiedzi];
        cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
    }
  }
}


问:
Failed to download pdf file
I want to download this pdf file

```<code>https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf
</code>```

I am using this code to download pdf files, it works fine with many files but it failed on pdf file like above

```<code>    public void downloadFile(@NonNull String urlStr, @NonNull String fullFilePath,
                         @NonNull DownloadListener downloadListener) {
    cancelStatus = false;
    InputStream is = null;
    File ffPath = null;
    FileOutputStream fos = null;
    try {
        downloadListener.onProgress(0);
        URL url = new URL(urlStr);
        URLConnection conexion = url.openConnection();
        conexion.setReadTimeout(2000000);
        conexion.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5");
        System.setProperty("http.agent", "");
        conexion.connect();
        int lenghtOfFile = conexion.getContentLength();
        if (lenghtOfFile <= 0) lenghtOfFile = 1;
        is = url.openStream();
        ffPath = new File(fullFilePath);
        fos = new FileOutputStream(ffPath);
        int count = 0;
        long total = 0;
        int progress = 0;
        byte data[] = new byte[1024];
        while ((count = is.read(data)) != -1) {
            if (cancelStatus == true) {
                break;
            }
            total += count;
            int progress_temp = (int) total * 100 / lenghtOfFile;
            if (progress != progress_temp) {
                progress = progress_temp;
                downloadListener.onProgress(progress >= 0 && progress <= 100 ? progress : 0);
            }
            fos.write(data, 0, count);
            cancelStatus = downloadListener.onPacketDownloaded(total, lenghtOfFile);
        }
        if (is != null) is.close();
        if (fos != null) fos.close();

        if (lenghtOfFile <= 1) {
            downloadListener.onComplete();
        } else if (ffPath.length() < lenghtOfFile) {
            if (cancelStatus) {
                downloadListener.onCancel();
            } else {
                downloadListener.onError();
            }

        } else if (ffPath.length() >= lenghtOfFile) {
            downloadListener.onComplete();
        }
        if (cancelStatus == true) {
            if (ffPath != null) ffPath.delete();
        }
    } catch (MalformedURLException e) {
        try {
            if (is != null) is.close();
            if (fos != null) fos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (ffPath != null) ffPath.delete();
        downloadListener.onError();
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        try {
            if (is != null) is.close();
            if (fos != null) fos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (ffPath != null) ffPath.delete();
        downloadListener.onError();
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        try {
            if (is != null) is.close();
            if (fos != null) fos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (ffPath != null) ffPath.delete();
        downloadListener.onError();
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

the problem is count = is.read(data) return -1 and break from while loop after one loop, the file about 345 kb

please help

答:
/**
     * download file used too download the file and save into phone
     *
     * @param fileURL  contain file url
     * @param fileName contain file name
     */</p>

```<code>public void DownloadFile(String fileURL, String fileName) {
    try {
        String RootDir = Environment.getExternalStorageDirectory()
                + File.separator + "Cards List";
        File RootFile = new File(RootDir);
        RootFile.mkdir();
        // File root = Environment.getExternalStorageDirectory();
        java.net.URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();
        FileOutputStream f = new FileOutputStream(new File(RootFile,
                fileName + " abc " + ".pdf"));
        InputStream in = c.getInputStream();
        byte[] buffer = new byte[1024];
        int len1 = 0;

        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();

    } catch (Exception e) {

        Log.d("Error....", e.toString());
    }

} // used to download the file from server

class ProgressBack extends AsyncTask<String, Void, Void> {
    ProgressDialog PD;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        PD = ProgressDialog.show(MainActivity.this, null, "Please Wait ...", true);
        PD.setCancelable(true);
    }

    @Override
    protected Void doInBackground(String... params) {
        DownloadFile("https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf",
                "Cards List"); // calling DownloadFile
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        PD.dismiss();
        Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
    }
}
</code>```

Title: Failed to download pdf file

Body:
I want to download this pdf file

https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf

I am using this code to download pdf files, it works fine with many files but it failed on pdf file like above

    public void downloadFile(@NonNull String urlStr, @NonNull String fullFilePath,
                         @NonNull DownloadListener downloadListener) {
    cancelStatus = false;
    InputStream is = null;
    File ffPath = null;
    FileOutputStream fos = null;
    try {
        downloadListener.onProgress(0);
        URL url = new URL(urlStr);
        URLConnection conexion = url.openConnection();
        conexion.setReadTimeout(2000000);
        conexion.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5");
        System.setProperty("http.agent", "");
        conexion.connect();
        int lenghtOfFile = conexion.getContentLength();
        if (lenghtOfFile <= 0) lenghtOfFile = 1;
        is = url.openStream();
        ffPath = new File(fullFilePath);
        fos = new FileOutputStream(ffPath);
        int count = 0;
        long total = 0;
        int progress = 0;
        byte data[] = new byte[1024];
        while ((count = is.read(data)) != -1) {
            if (cancelStatus == true) {
                break;
            }
            total += count;
            int progress_temp = (int) total * 100 / lenghtOfFile;
            if (progress != progress_temp) {
                progress = progress_temp;
                downloadListener.onProgress(progress >= 0 && progress <= 100 ? progress : 0);
            }
            fos.write(data, 0, count);
            cancelStatus = downloadListener.onPacketDownloaded(total, lenghtOfFile);
        }
        if (is != null) is.close();
        if (fos != null) fos.close();

        if (lenghtOfFile <= 1) {
            downloadListener.onComplete();
        } else if (ffPath.length() < lenghtOfFile) {
            if (cancelStatus) {
                downloadListener.onCancel();
            } else {
                downloadListener.onError();
            }

        } else if (ffPath.length() >= lenghtOfFile) {
            downloadListener.onComplete();
        }
        if (cancelStatus == true) {
            if (ffPath != null) ffPath.delete();
        }
    } catch (MalformedURLException e) {
        try {
            if (is != null) is.close();
            if (fos != null) fos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (ffPath != null) ffPath.delete();
        downloadListener.onError();
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        try {
            if (is != null) is.close();
            if (fos != null) fos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (ffPath != null) ffPath.delete();
        downloadListener.onError();
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        try {
            if (is != null) is.close();
            if (fos != null) fos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (ffPath != null) ffPath.delete();
        downloadListener.onError();
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

the problem is count = is.read(data) return -1 and break from while loop after one loop, the file about 345 kb

please help

Body:
/**
     * download file used too download the file and save into phone
     *
     * @param fileURL  contain file url
     * @param fileName contain file name
     */

public void DownloadFile(String fileURL, String fileName) {
    try {
        String RootDir = Environment.getExternalStorageDirectory()
                + File.separator + "Cards List";
        File RootFile = new File(RootDir);
        RootFile.mkdir();
        // File root = Environment.getExternalStorageDirectory();
        java.net.URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();
        FileOutputStream f = new FileOutputStream(new File(RootFile,
                fileName + " abc " + ".pdf"));
        InputStream in = c.getInputStream();
        byte[] buffer = new byte[1024];
        int len1 = 0;

        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();

    } catch (Exception e) {

        Log.d("Error....", e.toString());
    }

} // used to download the file from server

class ProgressBack extends AsyncTask<String, Void, Void> {
    ProgressDialog PD;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        PD = ProgressDialog.show(MainActivity.this, null, "Please Wait ...", true);
        PD.setCancelable(true);
    }

    @Override
    protected Void doInBackground(String... params) {
        DownloadFile("https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf",
                "Cards List"); // calling DownloadFile
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        PD.dismiss();
        Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
    }
}


问:
Printing list of class objects inside
How can i print a list with all class objects inside that list?

```<code> List<Reader> MyObjectList = new List<Reader>();

 private void button2_Click(object sender, EventArgs e)
    {
        Reader reader = new Reader();

        reader._surname = Convert.ToString(textBox1.Text);
        reader._id = Convert.ToInt32(textBox2.Text);
        MyObjectList.Add(reader);

        MessageBox.Show("new reader");
    }
</code>```

I want to print all _surname and _id i add, with button click.

```<code>private void button3_Click(object sender, EventArgs e)
    {
        listBox1.DataSource = MyObjectList;
    }
</code>```

If i do it like this, my result says: OBJ6.MyObjectList.

PS. OBJ6 - my project name. How can i print all objects inside that class using button click?

答:
A List<T> has not overridden ToString, that's why you see it's type name OBJ6.MyObjectList as result instead of the desired "all surname and id's".

You can use this:

```<code>private void button3_Click(object sender, EventArgs e)
{
    string whatYouWant = String.Join(
        Environment.NewLine, // change this to the desired delimiter
        MyObjectList.Select(r => $"{r._surname} {r._id}")); // change format here
    // ...
}
</code>```

Title: Printing list of class objects inside

Body:
How can i print a list with all class objects inside that list?

 List<Reader> MyObjectList = new List<Reader>();

 private void button2_Click(object sender, EventArgs e)
    {
        Reader reader = new Reader();

        reader._surname = Convert.ToString(textBox1.Text);
        reader._id = Convert.ToInt32(textBox2.Text);
        MyObjectList.Add(reader);

        MessageBox.Show("new reader");
    }

I want to print all _surname and _id i add, with button click.

private void button3_Click(object sender, EventArgs e)
    {
        listBox1.DataSource = MyObjectList;
    }

If i do it like this, my result says: OBJ6.MyObjectList.

PS. OBJ6 - my project name. How can i print all objects inside that class using button click?

Body:
A List<T> has not overridden ToString, that's why you see it's type name OBJ6.MyObjectList as result instead of the desired "all surname and id's".

You can use this:

private void button3_Click(object sender, EventArgs e)
{
    string whatYouWant = String.Join(
        Environment.NewLine, // change this to the desired delimiter
        MyObjectList.Select(r => $"{r._surname} {r._id}")); // change format here
    // ...
}


问:
How can one slow down emissions form Flux.interval?
Would this need back pressure or is there a simpler way?

For example in the below code , I want the spin function to be called every 2 seconds. Sometimes 'spin' can take longer time to compute than 2 second interval, in which case I do not want any interval emissions to queue up. But in the below code they do queue up.

In the code below, the first 4 spin function calls take 10 seconds and the rest take 1 second. As a result the Flux.interval emissions 'catch up' once the function gets faster. However, I do not want any 'catch up' to happen

```<code>import reactor.core.publisher.Flux;

import java.time.Duration;
import java.util.Date;
import java.util.Iterator;

public class Test {
   public static void main(String[] args) {
        Iterator<Integer> secs = new Iterator<Integer>() {
            private int num = 0;
            @Override
            public boolean hasNext() {
                return true;
            }
            @Override
            public Integer next() {
                return num++ < 4 ? 10 : 1;
            }
        };

        Flux.interval(Duration.ofSeconds(5))
                .map(n -> {spin(secs.next()); return n;})
                .doOnNext(n -> log("Processed " + n))
                .blockLast();

    }

    private static void spin(int secs) {
        log("Current job will take " + secs + " secs");
        long sleepTime = secs*1000000000L; // convert to nanos
        long startTime = System.nanoTime();
        while ((System.nanoTime() - startTime) < sleepTime) {}
    }

    static void log(Object label) {
        System.out.println((new Date()).toString() + "\t| " +Thread.currentThread().getName()   + "\t| " + label);
    }
}
</code>```

Output:
Notice the "Processed" timestamp initially is spaced by 10 seconds, but from job 4 to job 8, there is a 'catch up' that I do not want to take place. I want to spin to executed no earlier than 2 seconds after the previous invocation

```<code>Thu Jun 01 17:16:23 EDT 2017    | parallel-1    | Current job will take 10 secs
Thu Jun 01 17:16:33 EDT 2017    | parallel-1    | Processed 0
Thu Jun 01 17:16:33 EDT 2017    | parallel-1    | Current job will take 10 secs
Thu Jun 01 17:16:43 EDT 2017    | parallel-1    | Processed 1
Thu Jun 01 17:16:43 EDT 2017    | parallel-1    | Current job will take 10 secs
Thu Jun 01 17:16:53 EDT 2017    | parallel-1    | Processed 2
Thu Jun 01 17:16:53 EDT 2017    | parallel-1    | Current job will take 10 secs
Thu Jun 01 17:17:03 EDT 2017    | parallel-1    | Processed 3
Thu Jun 01 17:17:03 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:04 EDT 2017    | parallel-1    | Processed 4
Thu Jun 01 17:17:04 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:05 EDT 2017    | parallel-1    | Processed 5
Thu Jun 01 17:17:05 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:06 EDT 2017    | parallel-1    | Processed 6
Thu Jun 01 17:17:06 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:07 EDT 2017    | parallel-1    | Processed 7
Thu Jun 01 17:17:07 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:08 EDT 2017    | parallel-1    | Processed 8
Thu Jun 01 17:17:08 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:09 EDT 2017    | parallel-1    | Processed 9
Thu Jun 01 17:17:13 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:14 EDT 2017    | parallel-1    | Processed 10
Thu Jun 01 17:17:18 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:19 EDT 2017    | parallel-1    | Processed 11
</code>```

答:
You can delay events with the delayElements(Duration delay) method. If you want more finegrained control you can use delayUntil(Function<? super T,? extends Publisher<?>> triggerProvider)

Depending on your exact requirements the result might look like this:

```<code> Flux.interval(Duration.ofSeconds(5))
     .map(n -> {spin(secs.next()); return n;})
     .doOnNext(n -> log("Processed " + n))
     .delayUntil(n -> Mono.just(1).delayElements(Duration.Seconds(Math.max(0, 2 - n)))
     .blockLast();
</code>```

Body:
Would this need back pressure or is there a simpler way?

For example in the below code , I want the spin function to be called every 2 seconds. Sometimes 'spin' can take longer time to compute than 2 second interval, in which case I do not want any interval emissions to queue up. But in the below code they do queue up.

In the code below, the first 4 spin function calls take 10 seconds and the rest take 1 second. As a result the Flux.interval emissions 'catch up' once the function gets faster. However, I do not want any 'catch up' to happen

import reactor.core.publisher.Flux;

import java.time.Duration;
import java.util.Date;
import java.util.Iterator;

public class Test {
   public static void main(String[] args) {
        Iterator<Integer> secs = new Iterator<Integer>() {
            private int num = 0;
            @Override
            public boolean hasNext() {
                return true;
            }
            @Override
            public Integer next() {
                return num++ < 4 ? 10 : 1;
            }
        };

        Flux.interval(Duration.ofSeconds(5))
                .map(n -> {spin(secs.next()); return n;})
                .doOnNext(n -> log("Processed " + n))
                .blockLast();

    }

    private static void spin(int secs) {
        log("Current job will take " + secs + " secs");
        long sleepTime = secs*1000000000L; // convert to nanos
        long startTime = System.nanoTime();
        while ((System.nanoTime() - startTime) < sleepTime) {}
    }

    static void log(Object label) {
        System.out.println((new Date()).toString() + "\t| " +Thread.currentThread().getName()   + "\t| " + label);
    }
}

Output:
Notice the "Processed" timestamp initially is spaced by 10 seconds, but from job 4 to job 8, there is a 'catch up' that I do not want to take place. I want to spin to executed no earlier than 2 seconds after the previous invocation

Thu Jun 01 17:16:23 EDT 2017    | parallel-1    | Current job will take 10 secs
Thu Jun 01 17:16:33 EDT 2017    | parallel-1    | Processed 0
Thu Jun 01 17:16:33 EDT 2017    | parallel-1    | Current job will take 10 secs
Thu Jun 01 17:16:43 EDT 2017    | parallel-1    | Processed 1
Thu Jun 01 17:16:43 EDT 2017    | parallel-1    | Current job will take 10 secs
Thu Jun 01 17:16:53 EDT 2017    | parallel-1    | Processed 2
Thu Jun 01 17:16:53 EDT 2017    | parallel-1    | Current job will take 10 secs
Thu Jun 01 17:17:03 EDT 2017    | parallel-1    | Processed 3
Thu Jun 01 17:17:03 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:04 EDT 2017    | parallel-1    | Processed 4
Thu Jun 01 17:17:04 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:05 EDT 2017    | parallel-1    | Processed 5
Thu Jun 01 17:17:05 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:06 EDT 2017    | parallel-1    | Processed 6
Thu Jun 01 17:17:06 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:07 EDT 2017    | parallel-1    | Processed 7
Thu Jun 01 17:17:07 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:08 EDT 2017    | parallel-1    | Processed 8
Thu Jun 01 17:17:08 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:09 EDT 2017    | parallel-1    | Processed 9
Thu Jun 01 17:17:13 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:14 EDT 2017    | parallel-1    | Processed 10
Thu Jun 01 17:17:18 EDT 2017    | parallel-1    | Current job will take 1 secs
Thu Jun 01 17:17:19 EDT 2017    | parallel-1    | Processed 11

Body:
You can delay events with the delayElements(Duration delay) method. If you want more finegrained control you can use delayUntil(Function<? super T,? extends Publisher<?>> triggerProvider)

Depending on your exact requirements the result might look like this:

 Flux.interval(Duration.ofSeconds(5))
     .map(n -> {spin(secs.next()); return n;})
     .doOnNext(n -> log("Processed " + n))
     .delayUntil(n -> Mono.just(1).delayElements(Duration.Seconds(Math.max(0, 2 - n)))
     .blockLast();


问:
jq: how to select elements with different structure
I'm sure this is very simple, but I do not know how to do it with jq.

I have a JSON like this one

```<code>[
  {
    "id": "109",
    "name": "aaa"
  },
  {
    "id": "1098",
    "name": [
      "bbb",
      "ccc"
    ]
  },
  {
    "id": "2000",
    "name": [
      "fff",
      "ddd"
    ]
  }
]
</code>```

And I would like to extract the .name. When name is an array, I would like to take always the first element.

Do I must create an if clause, or is there some more direct mode?

As output I would like to have "aaa" "bbb" "fff", but I have "aaa" "bbb" "fff" "bbb" "fff".

Here is what I have so far:

if .[].name|type == "array" then .[].name[0]?  else first(.[].name) end
```

<p>Output:</p>

```"aaa"
"bbb"
"fff"
"bbb"
"fff"
```

Interactive example https://jqplay.org/s/fOBuwdj6WS

答:
To extract all names, but only the first name in case the name is an array:

```<code>jq '.[].name | if type=="array" then first else . end' <file
</code>```

For your sample input, the output is:

```<code>"aaa"
"bbb"
"fff"
</code>```

Body:
I'm sure this is very simple, but I do not know how to do it with jq.

I have a JSON like this one

[
  {
    "id": "109",
    "name": "aaa"
  },
  {
    "id": "1098",
    "name": [
      "bbb",
      "ccc"
    ]
  },
  {
    "id": "2000",
    "name": [
      "fff",
      "ddd"
    ]
  }
]

And I would like to extract the .name. When name is an array, I would like to take always the first element.

Do I must create an if clause, or is there some more direct mode?

As output I would like to have "aaa" "bbb" "fff", but I have "aaa" "bbb" "fff" "bbb" "fff".

Here is what I have so far:

if .[].name|type == "array" then .[].name[0]?  else first(.[].name) end

Output:

"aaa"
"bbb"
"fff"
"bbb"
"fff"

Interactive example https://jqplay.org/s/fOBuwdj6WS

Body:
To extract all names, but only the first name in case the name is an array:

jq '.[].name | if type=="array" then first else . end' <file

For your sample input, the output is:

"aaa"
"bbb"
"fff"


问:
Why can I not dereference or add a generic type even though I'm passing in a type that can be dereferenced and added?
I have some problems with a generic implementation of a method:

```<code>use std::collections::BTreeMap;
use global::entity::EntityId;

struct simple_system<T> {
    list_sum: BTreeMap<EntityId, T>,
    list_com: BTreeMap<EntityId, Vec<T>>,
}

impl<T> simple_system<T> {
    pub fn new() -> simple_system<T> {
        simple_system {
            list_sum: BTreeMap::new(),
            list_com: BTreeMap::new(),
        }
    }

    pub fn addComponent(&mut self, id: EntityId, comp: T) {
        self.list_com.entry(id).or_insert_with(Vec::new).push(comp);
        match self.list_sum.get_mut(&id) {
            Some(v) => *v = *v + *comp,
            None => self.list_sum.insert(id, comp),
        }
    }
}
</code>```

with the following errors.

error[E0614]: type `T` cannot be dereferenced
  --> src/main.rs:20:34
   |
20 |             Some(v) => *v = *v + *comp,
   |                                  ^^^^^

error[E0369]: binary operation `+` cannot be applied to type `T`
  --> src/main.rs:20:29
   |
20 |             Some(v) => *v = *v + *comp,
   |                             ^^^^^^^^^^
   |
   = note: an implementation of `std::ops::Add` might be missing for `T`
```

I don't know what I have to change to get it to work. I use it with u32 type so it should have an + operator.

答:
The Rust generics systems doesn't work the way C++ templates do: in C++ the compiler doesn't check whether the code actually compiles with any type in advance.

Rust makes sure the function compiles with any type that fulfills the listed requirements (called trait bounds).  The compiler already told you what is missing: std::ops::Add might be missing for T, so ask for it:

```<code>impl<T: Add<Output = T>> simple_system<T> { /* … */ }
</code>```

This will not fix everything; your code has other issues as well.

Body:
I have some problems with a generic implementation of a method:

use std::collections::BTreeMap;
use global::entity::EntityId;

struct simple_system<T> {
    list_sum: BTreeMap<EntityId, T>,
    list_com: BTreeMap<EntityId, Vec<T>>,
}

impl<T> simple_system<T> {
    pub fn new() -> simple_system<T> {
        simple_system {
            list_sum: BTreeMap::new(),
            list_com: BTreeMap::new(),
        }
    }

    pub fn addComponent(&mut self, id: EntityId, comp: T) {
        self.list_com.entry(id).or_insert_with(Vec::new).push(comp);
        match self.list_sum.get_mut(&id) {
            Some(v) => *v = *v + *comp,
            None => self.list_sum.insert(id, comp),
        }
    }
}

with the following errors.

error[E0614]: type `T` cannot be dereferenced
  --> src/main.rs:20:34
   |
20 |             Some(v) => *v = *v + *comp,
   |                                  ^^^^^

error[E0369]: binary operation `+` cannot be applied to type `T`
  --> src/main.rs:20:29
   |
20 |             Some(v) => *v = *v + *comp,
   |                             ^^^^^^^^^^
   |
   = note: an implementation of `std::ops::Add` might be missing for `T`

I don't know what I have to change to get it to work. I use it with u32 type so it should have an + operator.

Body:
The Rust generics systems doesn't work the way C++ templates do: in C++ the compiler doesn't check whether the code actually compiles with any type in advance.

Rust makes sure the function compiles with any type that fulfills the listed requirements (called trait bounds).  The compiler already told you what is missing: std::ops::Add might be missing for T, so ask for it:

impl<T: Add<Output = T>> simple_system<T> { /* … */ }

This will not fix everything; your code has other issues as well.


问:
Error in on clause comparison - Big Query
The following big query code gives the following error.

```<code>select
   selected_date date,
   pp.name property,
   bb.bookings bb,
   av.available vailable,
from
(SELECT DATE(DATE_ADD(TIMESTAMP("2017-10-01"), pos - 1, "DAY")) AS selected_date
FROM (
     SELECT ROW_NUMBER() OVER() AS pos, *
     FROM (FLATTEN((
     SELECT SPLIT(RPAD('', 1 + DATEDIFF(TIMESTAMP(CURRENT_DATE()), TIMESTAMP("2017-10-01")), '.'),'') AS h
     FROM (SELECT NULL)),h
)))) v
   cross join
 (select p.name name from [roomsproperties.properties] p where p.name not like '%test%' group by name) as pp

 left join
 (select sum(b.rooms) bookings,
        p.name property,
        b.checkin checkin,
        b.checkout checkout
        from [bookings.bookings] b
        left join [roomsproperties.rooms] r on r.id = b.room_id
            left join [roomsproperties.properties] p on p.id = r.property_id
        where p.name not like '%test%'
        and b.status not in('Rejected', 'Cancelled - By customer', 'OTP Not Varified')
        group by property,checkin,checkout
        ) as bb on pp.name = bb.property and (v.selected_date between bb.checkin and bb.checkout)

left join
(select sum(r.quantity) available,
         p.name property,
         date(r.created_at) date
         from [roomsproperties.rooms] r
         left join [roomsproperties.properties] p on p.id = r.property_id
         group by property, date
         ) av on pp.name = av.property and v.selected_date >= av.date
</code>```

The error is,

Error: ON clause must be AND of = comparisons of one field name from each table, with all field names prefixed with table name. Consider using Standard SQL

Can any one help

答:
You should try:

```<code>(select ...) as bb on pp.name = bb.property
WHERE v.selected_date  between bb.checkin and bb.checkou
</code>```

and:

```<code>(select ...) as av on pp.name = av.property
WHERE v.selected_date >= av.date
</code>```

Body:
The following big query code gives the following error.

select
   selected_date date,
   pp.name property,
   bb.bookings bb,
   av.available vailable,
from
(SELECT DATE(DATE_ADD(TIMESTAMP("2017-10-01"), pos - 1, "DAY")) AS selected_date
FROM (
     SELECT ROW_NUMBER() OVER() AS pos, *
     FROM (FLATTEN((
     SELECT SPLIT(RPAD('', 1 + DATEDIFF(TIMESTAMP(CURRENT_DATE()), TIMESTAMP("2017-10-01")), '.'),'') AS h
     FROM (SELECT NULL)),h
)))) v
   cross join
 (select p.name name from [roomsproperties.properties] p where p.name not like '%test%' group by name) as pp

 left join
 (select sum(b.rooms) bookings,
        p.name property,
        b.checkin checkin,
        b.checkout checkout
        from [bookings.bookings] b
        left join [roomsproperties.rooms] r on r.id = b.room_id
            left join [roomsproperties.properties] p on p.id = r.property_id
        where p.name not like '%test%'
        and b.status not in('Rejected', 'Cancelled - By customer', 'OTP Not Varified')
        group by property,checkin,checkout
        ) as bb on pp.name = bb.property and (v.selected_date between bb.checkin and bb.checkout)

left join
(select sum(r.quantity) available,
         p.name property,
         date(r.created_at) date
         from [roomsproperties.rooms] r
         left join [roomsproperties.properties] p on p.id = r.property_id
         group by property, date
         ) av on pp.name = av.property and v.selected_date >= av.date

The error is,

Error: ON clause must be AND of = comparisons of one field name from each table, with all field names prefixed with table name. Consider using Standard SQL

Can any one help

Body:
You should try:

(select ...) as bb on pp.name = bb.property
WHERE v.selected_date  between bb.checkin and bb.checkou

and:

(select ...) as av on pp.name = av.property
WHERE v.selected_date >= av.date