问:
Bokeh Streaming Plot is Blank
My Bokeh Streaming Plot is a blank rectangle. I am able to create a simple line plot that does not update itself in real-time.
I have read the Bokeh documentation for the version of Bokeh I am using 0.12.10 and Python3.5.3. I have searched on-line extensively for a solution to the error message.

I am getting the error

```<code>Error thrown from periodic callback: ValueError('All streaming column updates must be the same length')
</code>```

I am using pyserial to retrieve data from a sensor. The example values are 73.40 for temperature and 12:30:42 for the time. I want to plot this data in real-time.

Here is the code:

```<code>import serial
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, output_file, show

ser = serial.Serial('/dev/ttyACM0', 9600)

source = ColumnDataSource(dict(time=[], sensor=[]))

p = figure(plot_height=400, plot_width=1200, title="Fahrenheit Plotting")

p.title.text = "Fahrenheit Plotter"
p.title.text_color = "blue"
p.title.text_font = "arial"
p.title.text_font_style = "bold"
p.yaxis.minor_tick_line_color = "yellow"
p.xaxis.axis_label = "Time"
p.yaxis.axis_label = "Fahrenheit"

p.line(x='time', y='sensor',line_width=3,color="blue",alpha=0.8,source=source)

def update():
    while True:
        arduinoString = ser.readline()
        data_array = str(arduinoString).split(',')
        time = data_array[1]
        sensor1 = data_array[2]
        print(sensor)
        print(time)
        new_data = dict(time=[], sensor1=[])
        new_data['time'] = data_array[1]
        new_data['sensor'] = data_array[2]
        source.stream(new_data, 20)

curdoc().add_root(p)
curdoc().add_periodic_callback(update, 100)
curdoc().title = "Device Temperatures"
</code>```

答:
The example code is not self-contained, so I can't run it to fix, and reply with an updated version. But the error message is telling you what is wrong. All columns in a ColumnDataSource data dictionary must always be the same length at all times. You new_data must look something analogous to this:

```<code>new_data = {
    'time'  : [1,2,3,4],
    'sensor : [100, 200]
}
</code>```

The columns for time and sensor (which happen the be lists here, but could be arrays, etc) do not have the same length. That is the problem. All columns of a CDS must always have the same length, at all times.

Title: Bokeh Streaming Plot is Blank

Body:
My Bokeh Streaming Plot is a blank rectangle. I am able to create a simple line plot that does not update itself in real-time.
I have read the Bokeh documentation for the version of Bokeh I am using 0.12.10 and Python3.5.3. I have searched on-line extensively for a solution to the error message.

I am getting the error

Error thrown from periodic callback: ValueError('All streaming column updates must be the same length')

I am using pyserial to retrieve data from a sensor. The example values are 73.40 for temperature and 12:30:42 for the time. I want to plot this data in real-time.

Here is the code:

import serial
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, output_file, show

ser = serial.Serial('/dev/ttyACM0', 9600)

source = ColumnDataSource(dict(time=[], sensor=[]))

p = figure(plot_height=400, plot_width=1200, title="Fahrenheit Plotting")

p.title.text = "Fahrenheit Plotter"
p.title.text_color = "blue"
p.title.text_font = "arial"
p.title.text_font_style = "bold"
p.yaxis.minor_tick_line_color = "yellow"
p.xaxis.axis_label = "Time"
p.yaxis.axis_label = "Fahrenheit"

p.line(x='time', y='sensor',line_width=3,color="blue",alpha=0.8,source=source)

def update():
    while True:
        arduinoString = ser.readline()
        data_array = str(arduinoString).split(',')
        time = data_array[1]
        sensor1 = data_array[2]
        print(sensor)
        print(time)
        new_data = dict(time=[], sensor1=[])
        new_data['time'] = data_array[1]
        new_data['sensor'] = data_array[2]
        source.stream(new_data, 20)

curdoc().add_root(p)
curdoc().add_periodic_callback(update, 100)
curdoc().title = "Device Temperatures"

Body:
The example code is not self-contained, so I can't run it to fix, and reply with an updated version. But the error message is telling you what is wrong. All columns in a ColumnDataSource data dictionary must always be the same length at all times. You new_data must look something analogous to this:

new_data = {
    'time'  : [1,2,3,4],
    'sensor : [100, 200]
}

The columns for time and sensor (which happen the be lists here, but could be arrays, etc) do not have the same length. That is the problem. All columns of a CDS must always have the same length, at all times.


来源: stackexchange

问:
Convert base 16 strings to base 2 strings in tsql
I am not particularly good at dealing with databases, but is there a way to represent binary data as a sort of base 2 strings? I use TSQL. Whatever I do I get binary values represented as base 16 strings at best. For example, I have, lets say, 500 in a cell and I want it to be displayed/treated as '0b111110100' rather than '0x01F4'. This

```<code> CONVERT(VARCHAR, cast(500 as binary(2)), 1)
</code>```

gives 0x01F4 whereas I would like to get 111110100 or the like.

I didn't find any suitable built-in functions. However, I came across one dreadful and quite complicated procedure to convert base 16 strings into base 2 strings. Also I could think about using nested replace() calls on the values to replace F with 1111 etc., but it doesn't feel right.

The whole purpose is to find values with at least 4 1s in a row in their binary representation. My approach: if I could make them look like '0b111110100', it would be as simple as LIKE %1111%. Or am I doing it wrong?

答:
Keeping in mind my initial goal:

The whole purpose is to find values with at least 4 1s in a row in their binary representation.

I took another route (without suggested functions) and could come up with this solution - first, I used recursion via Common Table Expressions to get the binary representation of needed values like this:

```<code>with cte as(
    select 1 code, 29/2 n, 29 - 2*(29/2) bit_val
    union all
    select code, n/2, n - 2*(n/2) from cte
    where n > 0
)
select  code, row_number() over(partition by code order by n desc)
bit_no, bit_val from cte
</code>```

which gave me the binary representation of 29 (for example):

```<code>-- code is an id of entity where the value I am trying to convert into binary belongs to
---------------------------
| code | bit_no | bit_val |
---------------------------
|  12  |   1    |    1    |
|  12  |   2    |    0    |
|  12  |   3    |    1    |
|  12  |   4    |    1    |
|  12  |   5    |    1    |
---------------------------
</code>```

Then I just used an aggregate function (SUM) within a 4-rows window:

```<code>select *, sum(bit_val) over(partition by code order by bit_no
rows between current row and 3 following) bits_in_a_row from cte1

-------------------------------------------
| code | bit_no | bit_val | bits_in_a_row |
-------------------------------------------
|  12  |   1    |    1    |       3       |
|  12  |   2    |    0    |       3       |
|  12  |   3    |    1    |       3       |
|  12  |   4    |    1    |       2       |
|  12  |   5    |    1    |       1       |
-------------------------------------------
</code>```

If the sum of cells in 4 consecutive rows is 4 - I got what I was looking for although it is not quite a conversion of base 16 strings to base 2 strings as I initially put it in the caption. The final answer can be achieved taking only identities where bits_in_a_row is equal to 4 (or whatever else).

ContentLicense: CC BY-SA 3.0

Body:
I am not particularly good at dealing with databases, but is there a way to represent binary data as a sort of base 2 strings? I use TSQL. Whatever I do I get binary values represented as base 16 strings at best. For example, I have, lets say, 500 in a cell and I want it to be displayed/treated as '0b111110100' rather than '0x01F4'. This

 CONVERT(VARCHAR, cast(500 as binary(2)), 1)

gives 0x01F4 whereas I would like to get 111110100 or the like.

I didn't find any suitable built-in functions. However, I came across one dreadful and quite complicated procedure to convert base 16 strings into base 2 strings. Also I could think about using nested replace() calls on the values to replace F with 1111 etc., but it doesn't feel right.

The whole purpose is to find values with at least 4 1s in a row in their binary representation. My approach: if I could make them look like '0b111110100', it would be as simple as LIKE %1111%. Or am I doing it wrong?

Body:
Keeping in mind my initial goal:

The whole purpose is to find values with at least 4 1s in a row in their binary representation.

I took another route (without suggested functions) and could come up with this solution - first, I used recursion via Common Table Expressions to get the binary representation of needed values like this:

with cte as(
    select 1 code, 29/2 n, 29 - 2*(29/2) bit_val
    union all
    select code, n/2, n - 2*(n/2) from cte
    where n > 0
)
select  code, row_number() over(partition by code order by n desc)
bit_no, bit_val from cte

which gave me the binary representation of 29 (for example):

-- code is an id of entity where the value I am trying to convert into binary belongs to
---------------------------
| code | bit_no | bit_val |
---------------------------
|  12  |   1    |    1    |
|  12  |   2    |    0    |
|  12  |   3    |    1    |
|  12  |   4    |    1    |
|  12  |   5    |    1    |
---------------------------

Then I just used an aggregate function (SUM) within a 4-rows window:

select *, sum(bit_val) over(partition by code order by bit_no
rows between current row and 3 following) bits_in_a_row from cte1

-------------------------------------------
| code | bit_no | bit_val | bits_in_a_row |
-------------------------------------------
|  12  |   1    |    1    |       3       |
|  12  |   2    |    0    |       3       |
|  12  |   3    |    1    |       3       |
|  12  |   4    |    1    |       2       |
|  12  |   5    |    1    |       1       |
-------------------------------------------

If the sum of cells in 4 consecutive rows is 4 - I got what I was looking for although it is not quite a conversion of base 16 strings to base 2 strings as I initially put it in the caption. The final answer can be achieved taking only identities where bits_in_a_row is equal to 4 (or whatever else).


问:
Convert XSLT 1.0 to 2.0
I need help converting an XSLT 1.0 file to 2.0 (so I can use the XSLT 2.0 replace() function call).

I've Googled, searched different books and SO with no success. I tried changing version="1.0" to 2.0 and changing html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" to simply html but this all just results in XSLTProcessor errors.

Any help is greatly appreciated. Thanks in advance.

Here is my XSLT:

```<code><?xml version="1.0" encoding="ISO-8859-1" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" indent="no"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" encoding="ISO-8859-1" />
<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<xsl:element name="meta">
<xsl:attribute name="name">description</xsl:attribute>
<xsl:attribute name="content"><xsl:value-of select="EventList/title"/></xsl:attribute>
</xsl:element>
<xsl:element name="link"><xsl:attribute name="rel">alternate</xsl:attribute><xsl:attribute name="type">application/rss+xml</xsl:attribute><xsl:attribute name="title">RSS</xsl:attribute><xsl:attribute name="href"><xsl:value-of select="EventList/rssURL"/></xsl:attribute></xsl:element>
</head>
<body>
 <xsl:apply-templates select="EventList" />
</body>
</html>
</xsl:template>
<xsl:template match="EventList">
 <xsl:choose>
  <xsl:when test="Event">
   <xsl:apply-templates select="Event"/>
  </xsl:when>
  <xsl:otherwise>
   <div class="eventItem">
    <div class="eventItemText">
     <p>There are currently no events posted for this category.</p>
    </div>
   </div>
  </xsl:otherwise>
 </xsl:choose>
</xsl:template>
<!-- List -->
<xsl:template match="Event">
 <li>
  <!-- Title -->
  <xsl:if test="eventStatus = 2"><xsl:value-of select="eventStatusString"/> - </xsl:if>
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/e/?d=<xsl:value-of select="replace(detailpath,'/events/','')"/></xsl:attribute><xsl:attribute name="id"><xsl:value-of select="eventID"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="title" disable-output-escaping="yes"/>
  </xsl:element>
  <!-- Date and time -->
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:choose>
    <xsl:when test="repeatRuleID > 0">
     Ongoing <xsl:value-of select="repeatRuleText"/> from <xsl:value-of select="beginDate"/> through <xsl:value-of select="repeatUntilDate"/>.
     <xsl:if test="repeatRuleID=99">See details for exact dates and times.</xsl:if>
    </xsl:when>
    <xsl:otherwise>
     <xsl:if test="string(beginDay)"><xsl:value-of select="beginDay"/>, </xsl:if>
     <xsl:value-of select="beginDate"/>.
    </xsl:otherwise>
   </xsl:choose>
   <xsl:if test="repeatRuleID!=99">
    <xsl:if test="string(beginTime)">
     <xsl:text disable-output-escaping="yes"></xsl:text><xsl:value-of select="beginTime"/>.
    </xsl:if>
   </xsl:if>
  </xsl:element>
  <!-- Location -->
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="locationText"/>
  </xsl:element>
 </li>
</xsl:template>
</xsl:stylesheet>
</code>```

答:
You should also check the non normative XSLT 2.0 Appendix J Changes from XSLT 1.0 .

This section lists all known cases
  where a stylesheet that was valid
  (produced no errors) under XSLT 1.0,
  and whose behavior was fully specified
  by XSLT 1.0, will produce different
  results under XSLT 2.0.

ContentLicense: CC BY-SA 2.5

Title: Convert XSLT 1.0 to 2.0

Body:
I need help converting an XSLT 1.0 file to 2.0 (so I can use the XSLT 2.0 replace() function call).

I've Googled, searched different books and SO with no success. I tried changing version="1.0" to 2.0 and changing html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" to simply html but this all just results in XSLTProcessor errors.

Any help is greatly appreciated. Thanks in advance.

Here is my XSLT:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" indent="no"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" encoding="ISO-8859-1" />
<xsl:template match="/">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<xsl:element name="meta">
<xsl:attribute name="name">description</xsl:attribute>
<xsl:attribute name="content"><xsl:value-of select="EventList/title"/></xsl:attribute>
</xsl:element>
<xsl:element name="link"><xsl:attribute name="rel">alternate</xsl:attribute><xsl:attribute name="type">application/rss+xml</xsl:attribute><xsl:attribute name="title">RSS</xsl:attribute><xsl:attribute name="href"><xsl:value-of select="EventList/rssURL"/></xsl:attribute></xsl:element>

 <xsl:apply-templates select="EventList" />

</xsl:template>
<xsl:template match="EventList">
 <xsl:choose>
  <xsl:when test="Event">
   <xsl:apply-templates select="Event"/>
  </xsl:when>
  <xsl:otherwise>

There are currently no events posted for this category.

  </xsl:otherwise>
 </xsl:choose>
</xsl:template>

<xsl:template match="Event">

  <xsl:if test="eventStatus = 2"><xsl:value-of select="eventStatusString"/> - </xsl:if>
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/e/?d=<xsl:value-of select="replace(detailpath,'/events/','')"/></xsl:attribute><xsl:attribute name="id"><xsl:value-of select="eventID"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="title" disable-output-escaping="yes"/>
  </xsl:element>

  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:choose>
    <xsl:when test="repeatRuleID > 0">
     Ongoing <xsl:value-of select="repeatRuleText"/> from <xsl:value-of select="beginDate"/> through <xsl:value-of select="repeatUntilDate"/>.
     <xsl:if test="repeatRuleID=99">See details for exact dates and times.</xsl:if>
    </xsl:when>
    <xsl:otherwise>
     <xsl:if test="string(beginDay)"><xsl:value-of select="beginDay"/>, </xsl:if>
     <xsl:value-of select="beginDate"/>.
    </xsl:otherwise>
   </xsl:choose>
   <xsl:if test="repeatRuleID!=99">
    <xsl:if test="string(beginTime)">
     <xsl:text disable-output-escaping="yes"></xsl:text><xsl:value-of select="beginTime"/>.
    </xsl:if>
   </xsl:if>
  </xsl:element>

  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="locationText"/>
  </xsl:element>

</xsl:template>
</xsl:stylesheet>


问:
Replace zeros with following nonzero value in MATLAB
I have a vector A, which contains values that are zeros. I would now like to replace all zeros with the following non-zero value. I found this solution by @Luis Mendo to replace zeros with the previous non-zero values.

```<code>A = [1 0 2 0 7 7 7 0 5 0 0 0 9];
t = cumsum(A~=0);
u = nonzeros(A);
B = u(t).';
</code>```

Is there a similar way to replace the zeros with the closest following non-zero value as well?

答:
You only need to apply the code to a flipped version of A and then flip the result:

```<code>A = [1 0 2 0 7 7 7 0 5 0 0 0 9];
t = cumsum(flip(A)~=0);
u = nonzeros(flip(A));
B = flip(u(t).');
</code>```

Or, as noted by @craigim, in recent Matlab versions you can use the 'reverse' flag in cumsum:

```<code>A = [1 0 2 0 7 7 7 0 5 0 0 0 9];
t = cumsum(A ~= 0, 'reverse');
u = nonzeros(flip(A));
B = u(t).';
</code>```

Body:
I have a vector A, which contains values that are zeros. I would now like to replace all zeros with the following non-zero value. I found this solution by @Luis Mendo to replace zeros with the previous non-zero values.

A = [1 0 2 0 7 7 7 0 5 0 0 0 9];
t = cumsum(A~=0);
u = nonzeros(A);
B = u(t).';

Is there a similar way to replace the zeros with the closest following non-zero value as well?

Body:
You only need to apply the code to a flipped version of A and then flip the result:

A = [1 0 2 0 7 7 7 0 5 0 0 0 9];
t = cumsum(flip(A)~=0);
u = nonzeros(flip(A));
B = flip(u(t).');

Or, as noted by @craigim, in recent Matlab versions you can use the 'reverse' flag in cumsum:

A = [1 0 2 0 7 7 7 0 5 0 0 0 9];
t = cumsum(A ~= 0, 'reverse');
u = nonzeros(flip(A));
B = u(t).';


问:
Woocommerce Related Products - show products in price interval
I'm trying to modify related.php in order to randomly show any 3 products from the shop that has a price in the range of plus/minus 100.

I'm using ACF fields and Woocommerce 3.2.
The problem is that although the products are selected correctly, their price is not displayed.  Instead, the price of the reference product is displayed for all 3 products.

Here is the code (price_obj is the ACF field for price):

```<code>global $product, $woocommerce_loop;

$product = new WC_Product(get_the_ID());

$price_product = get_field('price_obj',get_the_ID());

$args1=array(
    'post_type'         => 'product',
    'posts_per_page'    => -1,
    'post__not_in'      => array( $product->get_id() )
);

$products_in_range = array();

$my_query = new wp_query($args1);

if( $my_query->have_posts() ) {
    $val = count($my_query->get_posts());
    while ($my_query->have_posts()) {
        $my_query->the_post();
        $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large');

        $price = get_field('price_obj');
        $id = get_the_ID();

        if ((($price_product-100) <= $price) && ($price <= ($price_product+100))){
            array_push($products_in_range,$id);
        }
    }
}
wp_reset_query();

$rand_products = array_rand($products_in_range, 3);

?>

<?php if ($rand_products){ ?>
<div class="related products">

    <h2><?php _e( 'Related Products', 'woocommerce' ); ?></h2>

    <ul class="products">
        <?php
            foreach ($rand_products as $prod){
                $title = get_the_title($products_in_range[$prod]);
                $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($products_in_range[$prod]), 'large');
                $link = get_permalink($products_in_range[$prod]);
                $product_prod = new WC_Product($products_in_range[$prod]);
                $price = wc_price($product->get_price());
        ?>
        <li class="product type-product status-publish has-post-thumbnail first instock shipping-taxable purchasable product-type-simple">
            <a href="<?php echo $link; ?>" class="woocommerce-LoopProduct-link">
                <span class="et_shop_image">
                    <img width="400" height="400"
                        src="<?php echo $featured_image[0]; ?>"
                        class="attachment-shop_catalog size-shop_catalog wp-post-image"
                        alt=""
                        title="">
                    <span class="et_overlay"></span>
                </span>
                <h3><?php echo $title; ?></h3>
                <span class="price">
                    <span class="woocommerce-Price-amount amount">
                        <?php echo $price; ?>
                    </span>
                </span>
            </a>
        </li>
        <?php } ?>

    </ul>

</div>
</code>```

Many thanks for any help!

答:
get_field() can take three parameters. The first one is mandatory but the last 2 are optional.

```<code>get_field($selector, [$post_id], [$format_value]);
</code>```

Where the $selector is the name of the field.The $post_id is self explanatory, but is defaulted to the current post and the $format_value decides whether you want to apply formatting logic.

Because you are calling the function via get_field('price_obj') and omitting the ID of the post you want it is defaulting to the current post in this case the post of the main item.

This is wrong, because you were inside the WordPress loop the right object was being saved into $price.

As you mentioned below, when you went to access the object via

$price = wc_price($product->get_price());

You were accessing the $product object, which is the main item. But your sub-product were stored in $product_prod, so to access it's price you had to change your code to

```<code>$price = wc_price($product_prod->get_price());
</code>```

Body:
I'm trying to modify related.php in order to randomly show any 3 products from the shop that has a price in the range of plus/minus 100.

I'm using ACF fields and Woocommerce 3.2.
The problem is that although the products are selected correctly, their price is not displayed.  Instead, the price of the reference product is displayed for all 3 products.

Here is the code (price_obj is the ACF field for price):

global $product, $woocommerce_loop;

$product = new WC_Product(get_the_ID());

$price_product = get_field('price_obj',get_the_ID());

$args1=array(
    'post_type'         => 'product',
    'posts_per_page'    => -1,
    'post__not_in'      => array( $product->get_id() )
);

$products_in_range = array();

$my_query = new wp_query($args1);

if( $my_query->have_posts() ) {
    $val = count($my_query->get_posts());
    while ($my_query->have_posts()) {
        $my_query->the_post();
        $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large');

        $price = get_field('price_obj');
        $id = get_the_ID();

        if ((($price_product-100) <= $price) && ($price <= ($price_product+100))){
            array_push($products_in_range,$id);
        }
    }
}
wp_reset_query();

$rand_products = array_rand($products_in_range, 3);

?>

<?php if ($rand_products){ ?>

<?php _e( 'Related Products', 'woocommerce' ); ?>

        <?php
            foreach ($rand_products as $prod){
                $title = get_the_title($products_in_range[$prod]);
                $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($products_in_range[$prod]), 'large');
                $link = get_permalink($products_in_range[$prod]);
                $product_prod = new WC_Product($products_in_range[$prod]);
                $price = wc_price($product->get_price());
        ?>

            <a href="<?php echo $link; ?>" class="woocommerce-LoopProduct-link">

                    <img width="400" height="400"
                        src="<?php echo $featured_image[0]; ?>"
                        class="attachment-shop_catalog size-shop_catalog wp-post-image"
                        alt=""
                        title="">

<?php echo $title; ?>

                        <?php echo $price; ?>

        <?php } ?>

Many thanks for any help!

Body:
get_field() can take three parameters. The first one is mandatory but the last 2 are optional.

get_field($selector, [$post_id], [$format_value]);

Where the $selector is the name of the field.The $post_id is self explanatory, but is defaulted to the current post and the $format_value decides whether you want to apply formatting logic.

Because you are calling the function via get_field('price_obj') and omitting the ID of the post you want it is defaulting to the current post in this case the post of the main item.

This is wrong, because you were inside the WordPress loop the right object was being saved into $price.

As you mentioned below, when you went to access the object via

$price = wc_price($product->get_price());

You were accessing the $product object, which is the main item. But your sub-product were stored in $product_prod, so to access it's price you had to change your code to

$price = wc_price($product_prod->get_price());


问:
How to use OpenCV with IntelliJ IDEA 12
I'm trying to use IntelliJ IDEA 12 to develop OpenCV 2.4.5 applications in Java. I've followed the instructions for Eclipse from the website here.

The problem I am running into is that I can add the jar to my library but I don't know how to add the natives to my classpath.

答:
None of these answers helped me with my solution. I found this: https://github.com/ctodobom/OpenCV-3.1.0-Android and it is, by far, the easiest solution for android.
-edit-
To use this, you do have to have a Github repository that you want, but the steps are as follows.
1. Find the GitHub repo
2. Add maven { url 'https://jitpack.io' } to the project/build.gradle.
3. Then, inside of your app/build.gradle add compile 'com.github.ctodobom:OpenCV-3.1.0-Android:-SNAPSHOT' This has the github website along with the username, the repo, and the first of the repo. This will link it into your application.
-Edit- Additionally, if this method doesn't actually work for you as it did for me, then try using JavaCV. When I first implemented this method, it seemed like it worked because the IDE was reading that all of the functions were valid and I would get no errors. It was reading it but not importing so in some occasions, it would work as expected but it some occasions it would not. Therefore, it can work for you but I eventually went to JavaCV, which is far easier to work with in my opinion.

Title: How to use OpenCV with IntelliJ IDEA 12


问:
Make `git svn find-rev` search the whole repository
When I want to get a local hash of a commit based on SVN revision id, I usually run git svn find-rev. However, the one big inconvenience is that this command will only look for the commit in the current branch, or in the branch explicitly specified in the command after the revision.

Sometimes, I only know the revision id, and I want to find a local hash without knowing the branch name. Is there a way to do it with git svn find-rev? It would make sense, knowing that SVN revisions are unique.

EDIT:

Turns out, there is no good way to do it.
I accepted the answer, which provides a solution, but it takes too long to search a repository with huge number of branches, like mine. I ended up writing my own shell function and using a regular svn in combination with git svn, which works much faster:

```<code>gitrev()
{
  if [ -z "$1" ]; then
    echo "${FUNCNAME[0]} <revision> [git_args]"
    return 1
  fi
  local rev b
  rev="$1"
  shift
  b="$(svn log -v -c "$rev" "$SVN_BRANCHES_URL" | grep -m1 -Po '/branches/\K[^/]+')" &&
  git svn find-rev "r${rev#r}" "origin/$b" "$@"
}
</code>```

If you use it, you may need to replace grep -P part if you're not on GNU/Linux. Revision can be specified with or without "r" prefix.

答:
To search in all local branches you can e. g. do

```<code>git for-each-ref --format='%(refname)' refs/heads/ | xargs -l git svn find-rev r123456
</code>```

To have it more reliable but still fast, you can do it with a little bit more complex line that looks through all refs until a match is found and then aborts, e. g. like

```<code>while read ref; do result="$(git svn find-rev r123456 "$ref")"; [ -n "$result" ] && echo $result && break; done < <(git for-each-ref --format='%(refname)')
</code>```

Body:
When I want to get a local hash of a commit based on SVN revision id, I usually run git svn find-rev. However, the one big inconvenience is that this command will only look for the commit in the current branch, or in the branch explicitly specified in the command after the revision.

Sometimes, I only know the revision id, and I want to find a local hash without knowing the branch name. Is there a way to do it with git svn find-rev? It would make sense, knowing that SVN revisions are unique.

EDIT:

Turns out, there is no good way to do it.
I accepted the answer, which provides a solution, but it takes too long to search a repository with huge number of branches, like mine. I ended up writing my own shell function and using a regular svn in combination with git svn, which works much faster:

gitrev()
{
  if [ -z "$1" ]; then
    echo "${FUNCNAME[0]} <revision> [git_args]"
    return 1
  fi
  local rev b
  rev="$1"
  shift
  b="$(svn log -v -c "$rev" "$SVN_BRANCHES_URL" | grep -m1 -Po '/branches/\K[^/]+')" &&
  git svn find-rev "r${rev#r}" "origin/$b" "$@"
}

If you use it, you may need to replace grep -P part if you're not on GNU/Linux. Revision can be specified with or without "r" prefix.

Body:
To search in all local branches you can e. g. do

git for-each-ref --format='%(refname)' refs/heads/ | xargs -l git svn find-rev r123456

To have it more reliable but still fast, you can do it with a little bit more complex line that looks through all refs until a match is found and then aborts, e. g. like

while read ref; do result="$(git svn find-rev r123456 "$ref")"; [ -n "$result" ] && echo $result && break; done < <(git for-each-ref --format='%(refname)')


问:
How can I get CSS selector for text wrapped in a paragraph under
 tag
I am trying to capture an URL in a mail paragraph using a Xpath selector (Xpath: html/body/p[2]/text()[3]). I could not get a proper css selector but with Xpath, I'm getting an error as given below when executing the Selenium webdriver test.

```<code><body>
<p>Dear EmailTest user,</p>
<p>
Your profile on the Swwebsite has been successfully created.
<br/>
To begin, click on the link below. You will be prompted to create a password during the login process.
<br/>
https://test.website.com/one/portal/$swweb/?uri=emailuser-125633uu3d-452iekdkd
<br/>
After creating your password, you will be able to access your application with the below username:
<br/>
User Name emailuser_test
<br/>
</p>
</code>```

Getting the below error:

com.ibm.automation.wtf.driver.DriverException: TypeError: Argument 1 of Window.getComputedStyle does not implement interface Element.

  Build info: version: '3.5.2', revision: '10229a9', time: '2017-08-21T17:29:55.15Z'

On some search over internet it seemed a Firefox issue with CSS. Can somebody help me here in fixing the issue or getting a proper CSS selector for capturing URL in the mail

System info: host: 'IBM345-R902EWZ3', ip: '9.162.252.164', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'

  Driver info: org.openqa.selenium.firefox.FirefoxDriver

答:
First get whole mail body under
 tag using getText() method, then capturing the URL using Java String operation like split/substring/indexOf method.

Use cssSelector like below:

```<code>String mailBody = driver.findElement(By.cssSelector("body > p:nth-child(2)")).getText();
</code>```

Now parsing the string to capture the URL.

For example:

```<code>String[] temp = mailBody.split("\n");
String url = temp[2];
System.out.println(url);
</code>```

Or

```<code>int startIndex = mailBody.indexOf("https");
int endIndex = mailBody.indexOf("After creating your password");
String url = mailBody.substring(startIndex, endIndex - 1);
System.out.println(url);
</code>```

Or you can use any string operation(or regex) to search for the URL from mailBody string

Another try:

You can also get the whole mail body using xpath html/body/p[2] and then parse the string.

Title: How can I get CSS selector for text wrapped in a paragraph under<p> tag

Body:
I am trying to capture an URL in a mail paragraph using a Xpath selector (Xpath: html/body/p[2]/text()[3]). I could not get a proper css selector but with Xpath, I'm getting an error as given below when executing the Selenium webdriver test.

Dear EmailTest user,

Your profile on the Swwebsite has been successfully created.

To begin, click on the link below. You will be prompted to create a password during the login process.

https://test.website.com/one/portal/$swweb/?uri=emailuser-125633uu3d-452iekdkd

After creating your password, you will be able to access your application with the below username:

User Name emailuser_test

Getting the below error:

com.ibm.automation.wtf.driver.DriverException: TypeError: Argument 1 of Window.getComputedStyle does not implement interface Element.

  Build info: version: '3.5.2', revision: '10229a9', time: '2017-08-21T17:29:55.15Z'

On some search over internet it seemed a Firefox issue with CSS. Can somebody help me here in fixing the issue or getting a proper CSS selector for capturing URL in the mail

System info: host: 'IBM345-R902EWZ3', ip: '9.162.252.164', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'

  Driver info: org.openqa.selenium.firefox.FirefoxDriver

Body:
First get whole mail body under <p> tag using getText() method, then capturing the URL using Java String operation like split/substring/indexOf method.

Use cssSelector like below:

String mailBody = driver.findElement(By.cssSelector("body > p:nth-child(2)")).getText();

Now parsing the string to capture the URL.

For example:

String[] temp = mailBody.split("\n");
String url = temp[2];
System.out.println(url);

Or

int startIndex = mailBody.indexOf("https");
int endIndex = mailBody.indexOf("After creating your password");
String url = mailBody.substring(startIndex, endIndex - 1);
System.out.println(url);

Or you can use any string operation(or regex) to search for the URL from mailBody string

Another try:

You can also get the whole mail body using xpath html/body/p[2] and then parse the string.


问:
Oracle connection string for other user's tables
We have 2 servers with the same database schema, however due to the way our infrastructure is setup on one server we must prefix all table names with a username

ex:

```<code>select * from engmon.cmts
</code>```

However on the other server the query would need to look like this

```<code>select * from cmts
</code>```

This is because one server connects to a table in a different schema/username.  Is it possible to change something in the jdbc url to make both queries look like #2?  That way we do not need to dynamically change the sql depending on which server we are connecting to (dev or prod).

Any ideas?

答:
I don't believe you can do anything to the JDBC URL.  However, you could issue the SQL statement

```<code>ALTER SESSION SET current_schema = ENGMON
</code>```

immediately after connecting (you could also put this in a logon trigger in Oracle).  This would have the effect of instructing Oracle to resolve unqualified object names using the ENGMON schema rather than the current user's schema.  This has no impact on permissions-- your session still only has the privileges assigned to the current user, not to the ENGMON user.

Alternately, you could create synonyms for the various tables that you need to access.  Either local synonyms (visible just to you) or public synonyms (visible to all users).  So

```<code>CREATE [PUBLIC] SYNONYM cmts
   FOR engmon.cmts
</code>```

Synonyms would only need to be created once and would apply to all sessions no matter what application they come from.  Setting the CURRENT_SCHEMA would need to be done every time.

Body:
We have 2 servers with the same database schema, however due to the way our infrastructure is setup on one server we must prefix all table names with a username

ex:

select * from engmon.cmts

However on the other server the query would need to look like this

select * from cmts

This is because one server connects to a table in a different schema/username.  Is it possible to change something in the jdbc url to make both queries look like #2?  That way we do not need to dynamically change the sql depending on which server we are connecting to (dev or prod).

Any ideas?

Body:
I don't believe you can do anything to the JDBC URL.  However, you could issue the SQL statement

ALTER SESSION SET current_schema = ENGMON

immediately after connecting (you could also put this in a logon trigger in Oracle).  This would have the effect of instructing Oracle to resolve unqualified object names using the ENGMON schema rather than the current user's schema.  This has no impact on permissions-- your session still only has the privileges assigned to the current user, not to the ENGMON user.

Alternately, you could create synonyms for the various tables that you need to access.  Either local synonyms (visible just to you) or public synonyms (visible to all users).  So

CREATE [PUBLIC] SYNONYM cmts
   FOR engmon.cmts

Synonyms would only need to be created once and would apply to all sessions no matter what application they come from.  Setting the CURRENT_SCHEMA would need to be done every time.


问:
What is the difference between .ini and .properties files in relevance to Talend?
.properties file extension is used for loading context variables through a file in Talend. In tFileProperties, while selecting the file format for parameter file, we have a drop down of .properties and  .ini extension also. I want to know what is the difference between .ini and .properties file format in relevance to parameter file extensions in Talend. In which case we use .ini extension?

Documentation says that the only difference is that the .ini files are regrouped in sections, which are somewhat iterated, which I failed to understand. Can anyone elaborate with an example?

答:
Both file types allow you to declare key/value pairs like so:

```<code>key=value
</code>```

The difference between the two is that .ini uses sections. tFileInputProperties allows you to read a section by its name:

The big advantage of this over .properties file is that .ini file can have the same variable inside multiple sections. For instance, your sections can be your execution environments (DEV, PROD..etc) with your variable having a different value for each environment. You can then get the value by reading only the section corresponding to your execution environment (section can be a context variable).

This what I get by setting section to "DEV":

If you declare the same variable in .properties file multiple times, the last occurence of the variable is the one that will be returned. Suppose my file looks like this :

This is the result (notice how only 2 rows are read, and not the 4 present in the file)

Body:
Both file types allow you to declare key/value pairs like so:

key=value

The difference between the two is that .ini uses sections. tFileInputProperties allows you to read a section by its name:

The big advantage of this over .properties file is that .ini file can have the same variable inside multiple sections. For instance, your sections can be your execution environments (DEV, PROD..etc) with your variable having a different value for each environment. You can then get the value by reading only the section corresponding to your execution environment (section can be a context variable).

This what I get by setting section to "DEV":

If you declare the same variable in .properties file multiple times, the last occurence of the variable is the one that will be returned. Suppose my file looks like this :

This is the result (notice how only 2 rows are read, and not the 4 present in the file)


问:
javascript post request not seen by server
I am trying to do a simple post from javascript to php, and am not getting data to transfer.  I'm using Apache2 on Ubuntu.  If I run the php code in Mozilla, it does what I've asked, but when called from javascript php does not seem to get the info to php on the server side.  I've tried to simplify the code to focus on just the post function.  Here is the html code:

```<code><!doctype html>
<html>
<head>
<title>Post Test </title>
</head>
<body>

<p id="demo"></p>

<script>
    var http = new XMLHttpRequest();
    var url = "post_test.php";
    var file_data = "text string";
    http.open("POST", url, true);
    http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200){
          document.getElementById('demo').innerHTML=this.responseText
        };
    }
http.send(file_data);
</script>
</body>
</html>
</code>```

Here is the php:

```<code><?php
var_dump(isset($_POST['file_data']));
?>
</code>```

I get a bool(false) message on the screen.
I checked the file access.  Both files are set rwx for all.
I am trying to learn html,javascript, and php.  I'd like to hold off on jQuery until I can do more.

答:
You are sending PHP a string of plain text. You've made no mention of "file_data" in the string you are sending to the server, so where do you expect PHP to pick up on that name for the key in $_POST? PHP runs on the server, it can't see your JS variable names.

PHP will populate $_POST with data formatted according to the application/x-www-form-urlencoded and multipart/form-data data formats.

You can build application/x-www-form-urlencoded like so:

```<code>http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var data = "file_data=" + encodeURIComponent(file_data);
http.send(data);
</code>```

Body:
I am trying to do a simple post from javascript to php, and am not getting data to transfer.  I'm using Apache2 on Ubuntu.  If I run the php code in Mozilla, it does what I've asked, but when called from javascript php does not seem to get the info to php on the server side.  I've tried to simplify the code to focus on just the post function.  Here is the html code:

<!doctype html>

<title>Post Test </title>

Here is the php:

<?php
var_dump(isset($_POST['file_data']));
?>

I get a bool(false) message on the screen.
I checked the file access.  Both files are set rwx for all.
I am trying to learn html,javascript, and php.  I'd like to hold off on jQuery until I can do more.

Body:
You are sending PHP a string of plain text. You've made no mention of "file_data" in the string you are sending to the server, so where do you expect PHP to pick up on that name for the key in $_POST? PHP runs on the server, it can't see your JS variable names.

PHP will populate $_POST with data formatted according to the application/x-www-form-urlencoded and multipart/form-data data formats.

You can build application/x-www-form-urlencoded like so:

http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var data = "file_data=" + encodeURIComponent(file_data);
http.send(data);


问:
Closing multiple windows with CMD
I have been working on a batch-file program that opens multiple windows and then closes them all at the same time. I can use the TASKKILL command on Windows 10 to close them all simultaneously. I also want to use the program on Windows XP Home SP3 but it doesn't have the TASKKILL command. So my overall question is: Is there any way to close multiple windows on Windows XP through the Command Prompt without any 3rd party software? Also, here is the batch code I am using:</p>

```<code>@echo off
:init
cls
color 0f
title Test A1
start %RandomProgram%
ping localhost -n 10 >nul
start %RandomProgram%
ping localhost -n 10 >nul
start %RandomProgram%
ping localhost -n 10 >nul
start %RandomProgram%
ping localhost -n 10 >nul
start %RandomProgram%
ping localhost -n 15 >nul
::Close all the above windows here::
</code>```

答:
Squashman was right,

Windows XP has TSKILL

Title: Closing multiple windows with CMD

Body:
I have been working on a batch-file program that opens multiple windows and then closes them all at the same time. I can use the TASKKILL command on Windows 10 to close them all simultaneously. I also want to use the program on Windows XP Home SP3 but it doesn't have the TASKKILL command. So my overall question is: Is there any way to close multiple windows on Windows XP through the Command Prompt without any 3rd party software? Also, here is the batch code I am using:

@echo off
:init
cls
color 0f
title Test A1
start %RandomProgram%
ping localhost -n 10 >nul
start %RandomProgram%
ping localhost -n 10 >nul
start %RandomProgram%
ping localhost -n 10 >nul
start %RandomProgram%
ping localhost -n 10 >nul
start %RandomProgram%
ping localhost -n 15 >nul
::Close all the above windows here::


问:
wildcard, same field, sql
I'm getting zero results when I'm trying to query in the same field with one being a wild card. When I write it separate it works but I can't figure it out in the same table.</p>

```<code>Select *
from table
where table.field1 NOT IN ('UNK')
OR table.field1 NOT LIKE ('x01%')
</code>```

答:
Logic with NOT is tricky.  I think you want AND:

```<code>Select *
from table
where table.field1 NOT IN ('UNK') AND table.field1 NOT LIKE ('x01%')
</code>```

The problem with your statement is that 'UNK' is not like 'x01%'.  So, if the first evaluates to false, the the second will evaluate to true.  The AND fixes this problem.

Title: wildcard, same field, sql

Body:
I'm getting zero results when I'm trying to query in the same field with one being a wild card. When I write it separate it works but I can't figure it out in the same table.

Select *
from table
where table.field1 NOT IN ('UNK')
OR table.field1 NOT LIKE ('x01%')

Body:
Logic with NOT is tricky.  I think you want AND:

Select *
from table
where table.field1 NOT IN ('UNK') AND table.field1 NOT LIKE ('x01%')

The problem with your statement is that 'UNK' is not like 'x01%'.  So, if the first evaluates to false, the the second will evaluate to true.  The AND fixes this problem.


问:
Making John, john and JOHN mean the same variable in python lists?
My question is this.

How do I make it so users can not make a new user_name John if JOHN or john are already in use.

Can I make user_name.upper() = user_name.lower() or something like that.

These names are been iterated through a loop of current_users. I want the loop to detect current users and disallow the use of a name if it has already been used in its upper() or title() forms.

Edit: If possible could I get the most 'pythonic' way of doing this. Thanks.

答:
You can use a lambda (a small anonymous little function) and make all your whole list lower case, and then compare that the the lower new_name.  If it's new, add it, if not, don't.</p>

```<code>name_list = ["John", "Sam", "Joe"]
new_name = "jOhN"

if new_name.lower() in [x.lower() for x in name_list]:
    print("nope")
else:
    print("new name, add it!")
    name_list.append(new_name)

print (name_list)
</code>```

Body:
You can use a lambda (a small anonymous little function) and make all your whole list lower case, and then compare that the the lower new_name.  If it's new, add it, if not, don't.

name_list = ["John", "Sam", "Joe"]
new_name = "jOhN"

if new_name.lower() in [x.lower() for x in name_list]:
    print("nope")
else:
    print("new name, add it!")
    name_list.append(new_name)

print (name_list)


问:
Storing a list of functions
The code

```<code>for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, function( e:Event ):void
    {
        markers[i].openInfoWindow( infoWindows[i] );
    });
    map.addOverlay( markers[i] );
}
</code>```

I have a list of markers in markers array, and a list of associated InfoWindowOptions in the infoWindow array.

The Issue

By the time the marker is clicked and the anonymous function called, the for loop has already finished and i is now equal to markers.length. So I get an out of bounds error on markers[i] and infoWindows[i].

I would like to create a list of associated functions as well and store it in an array. So I can do something like this instead:

```<code>for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, markerListeners[i] );
}
</code>```

So what I need to know is either,

How can I can store a list of function references in an array?

Is there a better way of doing this?

答:
To avoid the bounds error, you need to get the value for i rather than the reference, which is being kept in your anonymous handler function.  I'm sure there is a more elegant way to accomplish that than the following, but this is what I got to do the trick:

```<code>    for ( var i:int = 0; i < markers.length; i++ )
    {
        markers[i].addEventListener( MapMouseEvent.CLICK, createMapMouseEventHandler(i));
        map.addOverlay( markers[i] );
    }
    ...
}

private function createMapMouseEventHandler(index:int):Function
{
    return function( e:Event ):void
        {
            markers[index].openInfoWindow( infoWindows[index] );
        }
}
</code>```

Note: If markers and/or infoWindows is outside the scope of the createMapMouseEventHandler you'll need to pass them as parameters.

Title: Storing a list of functions

Body:
The code

for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, function( e:Event ):void
    {
        markers[i].openInfoWindow( infoWindows[i] );
    });
    map.addOverlay( markers[i] );
}

I have a list of markers in markers array, and a list of associated InfoWindowOptions in the infoWindow array.

The Issue

By the time the marker is clicked and the anonymous function called, the for loop has already finished and i is now equal to markers.length. So I get an out of bounds error on markers[i] and infoWindows[i].

I would like to create a list of associated functions as well and store it in an array. So I can do something like this instead:

for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, markerListeners[i] );
}

So what I need to know is either,

How can I can store a list of function references in an array?

Is there a better way of doing this?

Body:
To avoid the bounds error, you need to get the value for i rather than the reference, which is being kept in your anonymous handler function.  I'm sure there is a more elegant way to accomplish that than the following, but this is what I got to do the trick:

    for ( var i:int = 0; i < markers.length; i++ )
    {
        markers[i].addEventListener( MapMouseEvent.CLICK, createMapMouseEventHandler(i));
        map.addOverlay( markers[i] );
    }
    ...
}

private function createMapMouseEventHandler(index:int):Function
{
    return function( e:Event ):void
        {
            markers[index].openInfoWindow( infoWindows[index] );
        }
}

Note: If markers and/or infoWindows is outside the scope of the createMapMouseEventHandler you'll need to pass them as parameters.


问:
Can Tarray constructor be aborted to not add new record?
I am trying to control, limit how many new records are being added into array. Here is a simplified example:

I am trying to have variable LimitToUSA that will only let Developers from Country = US to be created in array:

```<code>type
  TDevelopers = record
    FName: string;
    LName: string;
    Country: string;
    constructor New(const aFName, aLName, aCountry: string);
  end;

var
  Developers:TArray<TDevelopers>;
  LimitToUSA: boolean; // <-- Controlling variable

constructor TDevelopers.New(const aFName, aLName, aCountry: string);
begin
  if LimitToUSA And (aCountry <> 'US') then
   Exit; // <-- Cancel adding new record here

  FName := aFName;
  LName := aLName;
  Country := aCountry;
end;

procedure TForm2.Button1Click(Sender: TObject);
begin
  LimitToUSA := True;

  Developers := TArray<TDevelopers>.Create(
    TDevelopers.New('John','Smith', 'US'),
    TDevelopers.New('Leo','Hazen', 'CA'),
    TDevelopers.New('Bob','Tilson','UK'),
    TDevelopers.New('Jennifer','Wolken','US'),
    TDevelopers.New('John','Willer','US'));
end;
</code>```

The problem is that it adds empty records for non-US Developers:

This solution is ugly when you 50 developers and it become annoying to maintain:

```<code>  if LimitToUSA then
  begin
    Developers := TArray<TDevelopers>.Create(
      TDevelopers.New('John','Smith', 'US'),
      TDevelopers.New('Jennifer','Wolken','US'),
      TDevelopers.New('John','Willer','US'));
  end
  else
  begin
    Developers := TArray<TDevelopers>.Create(
      TDevelopers.New('John','Smith', 'US'),
      TDevelopers.New('Leo','Hazen', 'CA'),
      TDevelopers.New('Bob','Tilson','UK'),
      TDevelopers.New('Jennifer','Wolken','US'),
      TDevelopers.New('John','Willer','US'));
  end;
</code>```

Is it possible to somehow cancel adding new record based on condition with constructor?

答:
No, you can't do that. What you can do is use a TList<TDevelopers> and only add valid class instances:

```<code>type
  TDevelopers = record
    LName: string;
    FName: string;
    Country: string;
    constructor New(const aFName, aLName, aCountry: string);
  end;

const
  NumDevelopers = 5; // or whatever the real number is.
  ConstDevelopers: array[0..NumDevelopers - 1] of TDevelopers =
  (
    (LName: 'Smith'; FName: 'John'; Country: 'US'),
    (LName: 'Wolken'; FName: 'Jennifer'; Country: 'US'),
    (LName: 'Hazen'; FName: 'Leo'; Country: 'CA'),
    (LName: 'Tilson'; FName: 'Bob'; Country: 'UK'),
    (LName: 'Willer'; FName: 'John'; Country: 'US')
  );

...

var
  Developers: TList<TDevelopers>;
  I: Integer;
begin
  Developers := TList<TDevelopers>.Create;
  for I := 0 to High(ConstDevelopers) do
  begin
    if not LimitToUSA or (ConstDevelopers[I].Country = 'US') then
      Developers.Add(ConstDevelopers[I]);
  end;
</code>```

Now, if you really need an array, you can use ToArray.

Note that I can't test this code right now (at the moment, I can only start this Mac in Safe Mode and then I can't start Parallels with the Windows VM). But it should give you a hint at what you can do.

Alternative

Alternatively, you keep your code and simply remove all records that are empty (check for Country = ''). In the latest Delphi versions (including Berlin), you can delete from dynamic arrays, using Delete, like Delete for strings. But go about it backwards, otherwise you'll get in trouble with your index:

```<code>for I := High(Developers) downto 0 do
  if Developers[I].Country = '' then
    Delete(Developers, I, 1);
</code>```

Alternative 2

To avoid having to repeat yourself, you can do:

```<code>  Developers := TArray<TDevelopers>.Create(
    TDevelopers.New('John','Smith', 'US'),
    TDevelopers.New('Jennifer','Wolken','US'),
    TDevelopers.New('John','Willer','US'));
  if not LimitToUSA then
  begin
    ForeignDevelopers := TArray<TDevelopers>.Create(
      TDevelopers.New('Leo','Hazen', 'CA'),
      TDevelopers.New('Bob','Tilson','UK'));
    Developers := Developers + ForeignDevelopers;
  end;
</code>```

Body:
I am trying to control, limit how many new records are being added into array. Here is a simplified example:

I am trying to have variable LimitToUSA that will only let Developers from Country = US to be created in array:

type
  TDevelopers = record
    FName: string;
    LName: string;
    Country: string;
    constructor New(const aFName, aLName, aCountry: string);
  end;

var
  Developers:TArray<TDevelopers>;
  LimitToUSA: boolean; // <-- Controlling variable

constructor TDevelopers.New(const aFName, aLName, aCountry: string);
begin
  if LimitToUSA And (aCountry <> 'US') then
   Exit; // <-- Cancel adding new record here

  FName := aFName;
  LName := aLName;
  Country := aCountry;
end;

procedure TForm2.Button1Click(Sender: TObject);
begin
  LimitToUSA := True;

  Developers := TArray<TDevelopers>.Create(
    TDevelopers.New('John','Smith', 'US'),
    TDevelopers.New('Leo','Hazen', 'CA'),
    TDevelopers.New('Bob','Tilson','UK'),
    TDevelopers.New('Jennifer','Wolken','US'),
    TDevelopers.New('John','Willer','US'));
end;

The problem is that it adds empty records for non-US Developers:

This solution is ugly when you 50 developers and it become annoying to maintain:

  if LimitToUSA then
  begin
    Developers := TArray<TDevelopers>.Create(
      TDevelopers.New('John','Smith', 'US'),
      TDevelopers.New('Jennifer','Wolken','US'),
      TDevelopers.New('John','Willer','US'));
  end
  else
  begin
    Developers := TArray<TDevelopers>.Create(
      TDevelopers.New('John','Smith', 'US'),
      TDevelopers.New('Leo','Hazen', 'CA'),
      TDevelopers.New('Bob','Tilson','UK'),
      TDevelopers.New('Jennifer','Wolken','US'),
      TDevelopers.New('John','Willer','US'));
  end;

Is it possible to somehow cancel adding new record based on condition with constructor?

Body:
No, you can't do that. What you can do is use a TList<TDevelopers> and only add valid class instances:

type
  TDevelopers = record
    LName: string;
    FName: string;
    Country: string;
    constructor New(const aFName, aLName, aCountry: string);
  end;

const
  NumDevelopers = 5; // or whatever the real number is.
  ConstDevelopers: array[0..NumDevelopers - 1] of TDevelopers =
  (
    (LName: 'Smith'; FName: 'John'; Country: 'US'),
    (LName: 'Wolken'; FName: 'Jennifer'; Country: 'US'),
    (LName: 'Hazen'; FName: 'Leo'; Country: 'CA'),
    (LName: 'Tilson'; FName: 'Bob'; Country: 'UK'),
    (LName: 'Willer'; FName: 'John'; Country: 'US')
  );

...

var
  Developers: TList<TDevelopers>;
  I: Integer;
begin
  Developers := TList<TDevelopers>.Create;
  for I := 0 to High(ConstDevelopers) do
  begin
    if not LimitToUSA or (ConstDevelopers[I].Country = 'US') then
      Developers.Add(ConstDevelopers[I]);
  end;

Now, if you really need an array, you can use ToArray.

Note that I can't test this code right now (at the moment, I can only start this Mac in Safe Mode and then I can't start Parallels with the Windows VM). But it should give you a hint at what you can do.

Alternative

Alternatively, you keep your code and simply remove all records that are empty (check for Country = ''). In the latest Delphi versions (including Berlin), you can delete from dynamic arrays, using Delete, like Delete for strings. But go about it backwards, otherwise you'll get in trouble with your index:

for I := High(Developers) downto 0 do
  if Developers[I].Country = '' then
    Delete(Developers, I, 1);

Alternative 2

To avoid having to repeat yourself, you can do:

  Developers := TArray<TDevelopers>.Create(
    TDevelopers.New('John','Smith', 'US'),
    TDevelopers.New('Jennifer','Wolken','US'),
    TDevelopers.New('John','Willer','US'));
  if not LimitToUSA then
  begin
    ForeignDevelopers := TArray<TDevelopers>.Create(
      TDevelopers.New('Leo','Hazen', 'CA'),
      TDevelopers.New('Bob','Tilson','UK'));
    Developers := Developers + ForeignDevelopers;
  end;


问:
Sorry, my bot code is having an issue... But it does not
I have developed a bot with the Microsoft Bot Framework (Builder v3.12.2.4, which is the latest version at this moment). I actually updated all libraries to the latest version, having AdaptiveCards as well, latest beta10.

So, I built the bot, deployed it, everything working great. But all of the sudden, all platforms give the response 'sorry, my bot code is having an issue'. So, at each input, the feedback is given (like hello, a card,...) but also this message.

I checked for double context.Wait() calls, which there are not.
I enabled Informational logging and put all kinds of logging, giving below results (no error to be seen in here, as my catch statements would log a row)

```<code>2017-12-04T16:45:40  PID[4812] Information Sentiment recognition ON: True
2017-12-04T16:45:41  PID[4812] Information Forwarded message to Luis Dialog: Hallo
2017-12-04T16:45:41  PID[4812] Information Detect Chat intent in Luis Dialog
</code>```

What I do see, but that was already the case before is:

```<code>2017-12-04T16:45:46  PID[4812] Warning     The Bot State API is being deprecated.
Please refer to https://aka.ms/yr235k for details on how to replace with your own storage.
</code>```

However, this seems to be something internal on the bot framework...
The Bot service says 'I'm fine, no issues found'. So I am running out of ideas.

Anyone encountered this and has a clue. BTW: I have setup adaptive cards for 1 platform (telegram) and using built in herocard on another (skype, web chat) and all are giving this behavior

Additional information. I forgot to put 1 exception logging, being in the API Controller method itself.
This one says:
    Operation returned an invalid status code 'Conflict'
However, I have no idea what it means. The default REST API explanations, found via https://learn.microsoft.com/en-us/rest/api/storageservices/common-rest-api-error-codes don't seem to make sense

答:
The error message:

The Bot State API is being deprecated

Means that your chatbot needs to use your own storage for managing state. The URL in the message goes to the Manage custom state data with Azure Cosmos DB for .NET page, which explains why.

Last July, the Bot Framework team blogged about this: Saving State data with BotBuilder-Azure in .NET. If you read a couple of the other blog posts after that, you'll learn how to use other data stores, like SQL Server, for state management.

Really, you want to use your own state management because the amount of storage they provide is very small, improved performance, reduced latency, and greater control over state.

Setting up state should be a normal task for all of your chatbots.

Body:
I have developed a bot with the Microsoft Bot Framework (Builder v3.12.2.4, which is the latest version at this moment). I actually updated all libraries to the latest version, having AdaptiveCards as well, latest beta10.

So, I built the bot, deployed it, everything working great. But all of the sudden, all platforms give the response 'sorry, my bot code is having an issue'. So, at each input, the feedback is given (like hello, a card,...) but also this message.

I checked for double context.Wait() calls, which there are not.
I enabled Informational logging and put all kinds of logging, giving below results (no error to be seen in here, as my catch statements would log a row)

2017-12-04T16:45:40  PID[4812] Information Sentiment recognition ON: True
2017-12-04T16:45:41  PID[4812] Information Forwarded message to Luis Dialog: Hallo
2017-12-04T16:45:41  PID[4812] Information Detect Chat intent in Luis Dialog

What I do see, but that was already the case before is:

2017-12-04T16:45:46  PID[4812] Warning     The Bot State API is being deprecated.
Please refer to https://aka.ms/yr235k for details on how to replace with your own storage.

However, this seems to be something internal on the bot framework...
The Bot service says 'I'm fine, no issues found'. So I am running out of ideas.

Anyone encountered this and has a clue. BTW: I have setup adaptive cards for 1 platform (telegram) and using built in herocard on another (skype, web chat) and all are giving this behavior

Additional information. I forgot to put 1 exception logging, being in the API Controller method itself.
This one says:
    Operation returned an invalid status code 'Conflict'
However, I have no idea what it means. The default REST API explanations, found via https://learn.microsoft.com/en-us/rest/api/storageservices/common-rest-api-error-codes don't seem to make sense


问:
Unable to add a source with url
[!] Unable to add a source with url git@github.com:CocoaPods/Specs.git named master-1. You can try adding it manually in ~/.cocoapods/repos or via pod repo add.   please any help

答:
This is often happening on initial pod install. I tried all and this steps helped me

Please follow these steps:

1] pod repo update

2] pod install

I hope that works for you. All the best

Title: Unable to add a source with url


问:
Couchbase: Is it possible to only invoke "SELECT" queries on the "master" node?
I am having several race conditions in my app where I was able to "SELECT" a document that was previously deleted by another thread 1-2 secs ago. I added ScanConsistency.REQUEST_PLUS to my "SELECTs" but it takes too long...

I am planning to add PersistTo.ONE param to the "DELETEs" however, I am not sure if the succeeding "SELECT" will still see the deleted document or not because I think that it might invoke "SELECT" on one of the non-master nodes which still has the deleted document in-memory.

Will it be possible to "SELECT" only on the master node?

I could use PersistTo.FOUR but I think that would also affect performance greatly.

答:
From what I could tell from reading the documentation on this feature (this is a fairly recent addition to Couchbase), the fact that the edit takes place on another thread is significant. Each thread is going to have to have its own session with the database, and the consistency level could in theory be pulled from that thread, but you would need to have that thread communicate with your thread (probably a non-starter).

Therefore, going back to basics, it's important to realize that the database itself is an eventually-consistent data store.  This means that, given the CAP-theorem, the data store sacrifices consistency for availability and partition tolerance. This is true in all cases, but the N1QL mechanism attempts to compensate a little bit for "your own writes." Being a software architect myself, I would not depend upon this except if I needed it as a temporary workaround, but rather keep the prevailing design principles in mind when designing the application data store.

Bottom line is that I believe this behavior is expected, and your design should be tolerant of it. If your application requires immediate consistency across sessions, then you should use a different data store.


问:
How to configure PageableHandlerMethodArgumentResolver in spring boot application
I have a spring boot application and I want to configure PageableHandlerMethodArgumentResolver, I try the following code, but doesn't not work:

```<code>@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    // .......

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
        resolver.setFallbackPageable(new PageRequest(0, 50));
        argumentResolvers.add(resolver);
        super.addArgumentResolvers(argumentResolvers);
    }
}
</code>```

Controller method:

```<code>@Override
@PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Page<Account>> query(@QuerydslPredicate Predicate predicate,
        @PageableDefault Pageable pageable) {
    return new ResponseEntity<>(accountRepo.findAll(predicate, pageable), HttpStatus.OK);
}
</code>```

And it is a simple Boot App, just playing with spring boot, with No Empty WebConfig Configuration class

```<code>@Configuration
public class WebConfig {

    @Bean
    public Filter html5ModeFilter() {
        return new Html5ModeFilter();
    }
}
</code>```

And here's a list of my config classes:

```<code>Html5ModeFilter.java
SecurityConfig.java
ServletInitializer.java
UserDetailsAdapter.java
WebConfig.java
</code>```

答:
Starting in spring-data-commons version 2.0, there is are 2 new classes that will make this kind of thing easier:

SortHandlerMethodArgumentResolverCustomizer

PageableHandlerMethodArgumentResolverCustomizer

Unfortunately that's not the version that ships with the current version of Spring Boot (1.5.9), so replace at your own risk.

```<code>@Bean
PageableHandlerMethodArgumentResolverCustomizer sortCustomizer() {
    // s is PageableHandlerMethodArgumentResolver
    return p -> p.setFallbackPageable(new PageRequest(0, 50));
}
</code>```

This is just an alternative way to now set your fallback. @Ali Dehghani's answer still applies that the Default was overriding the Fallback

Spring Data Web Support

Body:
I have a spring boot application and I want to configure PageableHandlerMethodArgumentResolver, I try the following code, but doesn't not work:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    // .......

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
        resolver.setFallbackPageable(new PageRequest(0, 50));
        argumentResolvers.add(resolver);
        super.addArgumentResolvers(argumentResolvers);
    }
}

Controller method:

@Override
@PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Page<Account>> query(@QuerydslPredicate Predicate predicate,
        @PageableDefault Pageable pageable) {
    return new ResponseEntity<>(accountRepo.findAll(predicate, pageable), HttpStatus.OK);
}

And it is a simple Boot App, just playing with spring boot, with No Empty WebConfig Configuration class

@Configuration
public class WebConfig {

    @Bean
    public Filter html5ModeFilter() {
        return new Html5ModeFilter();
    }
}

And here's a list of my config classes:

Html5ModeFilter.java
SecurityConfig.java
ServletInitializer.java
UserDetailsAdapter.java
WebConfig.java

Body:
Starting in spring-data-commons version 2.0, there is are 2 new classes that will make this kind of thing easier:

SortHandlerMethodArgumentResolverCustomizer

PageableHandlerMethodArgumentResolverCustomizer

Unfortunately that's not the version that ships with the current version of Spring Boot (1.5.9), so replace at your own risk.

@Bean
PageableHandlerMethodArgumentResolverCustomizer sortCustomizer() {
    // s is PageableHandlerMethodArgumentResolver
    return p -> p.setFallbackPageable(new PageRequest(0, 50));
}

This is just an alternative way to now set your fallback. @Ali Dehghani's answer still applies that the Default was overriding the Fallback

Spring Data Web Support


问:
Recursive CTE for parsing JSON file
I'm using SQL Server 2014 for parsing a JSON file and for that I think that a recursive CTE is convenient.

The JSON file is like this:

```<code>{
  "0": {
    "SalesOrderNumber": "CSVSO67695",
    "SalesOrderDetailID": 97971,
    "OrderDate": "2014-03-05 00:00:00.000",
    "ProductNumber": "WB-H098",
    "Quantity": 1,
    "LineTotal": 4.99,
    "CustomerType": "Individual",
    "TestData_1": "Sales extract OK!",
    "TestData_2": 255
  },
  "1": {
    "SalesOrderNumber": "CSVSO53485",
    "SalesOrderDetailID": 47747,
    "OrderDate": "2013-07-31 00:00:00.000",
    "ProductNumber": "SJ-0194-L",
    "Quantity": 10,
    "LineTotal": 323.94,
    "CustomerType": "Store",
    "TestData_1": "Sales extract OK!",
    "TestData_2": 255
  },
  "2": {
    "SalesOrderNumber": "CSVSO52248",
    "SalesOrderDetailID": 43809,
    "OrderDate": "2013-07-07 00:00:00.000",
    "ProductNumber": "TT-M928",
    "Quantity": 1,
    "LineTotal": 4.99,
    "CustomerType": "Individual",
    "TestData_1": "Sales extract OK!",
    "TestData_2": 255
  }
</code>```

}

Can anyone help me with this?

答:
You don't need recursion for this. Grab a copy of delimitedSplit8K and do this:

```<code>declare @json varchar(8000) =
'{
"0": {
"SalesOrderNumber": "CSVSO67695",
"SalesOrderDetailID": 97971,
"OrderDate": "2014-03-05 00:00:00.000",
"ProductNumber": "WB-H098",
"Quantity": 1,
"LineTotal": 4.99,
"CustomerType": "Individual",
"TestData_1": "Sales extract OK!",
"TestData_2": 255
},
"1": {
"SalesOrderNumber": "CSVSO53485",
"SalesOrderDetailID": 47747,
"OrderDate": "2013-07-31 00:00:00.000",
"ProductNumber": "SJ-0194-L",
"Quantity": 10,
"LineTotal": 323.94,
"CustomerType": "Store",
"TestData_1": "Sales extract OK!",
"TestData_2": 255
},
"2": {
"SalesOrderNumber": "CSVSO52248",
"SalesOrderDetailID": 43809,
"OrderDate": "2013-07-07 00:00:00.000",
"ProductNumber": "TT-M928",
"Quantity": 1,
"LineTotal": 4.99,
"CustomerType": "Individual",
"TestData_1": "Sales extract OK!",
"TestData_2": 255
  }
}';

select
  jsonItemId,
  item,
  attrib,
  attribValue
from
(
  select
    jsonItemId = sum(sign(jsonItemIdPrep)) over (order by itemnumber),
    ItemNumber,
    item,
    attrib      = ltrim(replace(substring(item, 1, sep.pos-1),'"','')),
    attribValue = replace(ltrim(replace(substring(item, sep.pos+1, len(item)),'"','')),',',''),
    jsonItemIdPrep
  from
  (
    select ItemNumber, item, jsonItemIdPrep =
      case
        when item like '%"[0-9]": {%'
          or item like '%"[0-9][0-9]": {%'
          or item like '%"[0-9][0-9][0-9]": {%' -- 1,2 or 3 digits
        then substring(item, v.ps, charindex('"', item, v.ps)- v.ps)
      end
    from dbo.DelimitedSplit8K(replace(@json,char(10),''), char(13))
    cross apply (values (charindex('"',item)+1)) v(ps)
    where ItemNumber > 1 and item not like '%}' and item not like '%},'
  ) x
  cross apply (values (charindex(':', item))) sep(pos)
  cross apply (values (replace(substring(item, 1, sep.pos-1),'"',''))) p(xxx)
) x
where jsonItemIdPrep is null;
</code>```

Results

```<code>jsonItemId  item                                                  attrib                        attribValue
----------- ----------------------------------------------------- ----------------------------- -----------------------------------
0           "SalesOrderNumber": "CSVSO67695",                 SalesOrderNumber              CSVSO67695
0           "SalesOrderDetailID": 97971,                      SalesOrderDetailID            97971
0           "OrderDate": "2014-03-05 00:00:00.000",           OrderDate                     2014-03-05 00:00:00.000
0           "ProductNumber": "WB-H098",                       ProductNumber                 WB-H098
0           "Quantity": 1,                                    Quantity                      1
0           "LineTotal": 4.99,                                LineTotal                     4.99
0           "CustomerType": "Individual",                     CustomerType                  Individual
0           "TestData_1": "Sales extract OK!",                TestData_1                    Sales extract OK!
0           "TestData_2": 255                                 TestData_2                    255
1           "SalesOrderNumber": "CSVSO53485",                 SalesOrderNumber              CSVSO53485
1           "SalesOrderDetailID": 47747,                      SalesOrderDetailID            47747
1           "OrderDate": "2013-07-31 00:00:00.000",           OrderDate                     2013-07-31 00:00:00.000
1           "ProductNumber": "SJ-0194-L",                     ProductNumber                 SJ-0194-L
1           "Quantity": 10,                                   Quantity                      10
1           "LineTotal": 323.94,                              LineTotal                     323.94
1           "CustomerType": "Store",                          CustomerType                  Store
1           "TestData_1": "Sales extract OK!",                TestData_1                    Sales extract OK!
1           "TestData_2": 255                                 TestData_2                    255
2           "SalesOrderNumber": "CSVSO52248",                 SalesOrderNumber              CSVSO52248
2           "SalesOrderDetailID": 43809,                      SalesOrderDetailID            43809
2           "OrderDate": "2013-07-07 00:00:00.000",           OrderDate                     2013-07-07 00:00:00.000
2           "ProductNumber": "TT-M928",                       ProductNumber                 TT-M928
2           "Quantity": 1,                                    Quantity                      1
2           "LineTotal": 4.99,                                LineTotal                     4.99
2           "CustomerType": "Individual",                     CustomerType                  Individual
2           "TestData_1": "Sales extract OK!",                TestData_1                    Sales extract OK!
2           "TestData_2": 255                                 TestData_2                    255
</code>```

Title: Recursive CTE for parsing JSON file

Body:
I'm using SQL Server 2014 for parsing a JSON file and for that I think that a recursive CTE is convenient.

The JSON file is like this:

{
  "0": {
    "SalesOrderNumber": "CSVSO67695",
    "SalesOrderDetailID": 97971,
    "OrderDate": "2014-03-05 00:00:00.000",
    "ProductNumber": "WB-H098",
    "Quantity": 1,
    "LineTotal": 4.99,
    "CustomerType": "Individual",
    "TestData_1": "Sales extract OK!",
    "TestData_2": 255
  },
  "1": {
    "SalesOrderNumber": "CSVSO53485",
    "SalesOrderDetailID": 47747,
    "OrderDate": "2013-07-31 00:00:00.000",
    "ProductNumber": "SJ-0194-L",
    "Quantity": 10,
    "LineTotal": 323.94,
    "CustomerType": "Store",
    "TestData_1": "Sales extract OK!",
    "TestData_2": 255
  },
  "2": {
    "SalesOrderNumber": "CSVSO52248",
    "SalesOrderDetailID": 43809,
    "OrderDate": "2013-07-07 00:00:00.000",
    "ProductNumber": "TT-M928",
    "Quantity": 1,
    "LineTotal": 4.99,
    "CustomerType": "Individual",
    "TestData_1": "Sales extract OK!",
    "TestData_2": 255
  }

}

Can anyone help me with this?

Body:
You don't need recursion for this. Grab a copy of delimitedSplit8K and do this:

declare @json varchar(8000) =
'{
"0": {
"SalesOrderNumber": "CSVSO67695",
"SalesOrderDetailID": 97971,
"OrderDate": "2014-03-05 00:00:00.000",
"ProductNumber": "WB-H098",
"Quantity": 1,
"LineTotal": 4.99,
"CustomerType": "Individual",
"TestData_1": "Sales extract OK!",
"TestData_2": 255
},
"1": {
"SalesOrderNumber": "CSVSO53485",
"SalesOrderDetailID": 47747,
"OrderDate": "2013-07-31 00:00:00.000",
"ProductNumber": "SJ-0194-L",
"Quantity": 10,
"LineTotal": 323.94,
"CustomerType": "Store",
"TestData_1": "Sales extract OK!",
"TestData_2": 255
},
"2": {
"SalesOrderNumber": "CSVSO52248",
"SalesOrderDetailID": 43809,
"OrderDate": "2013-07-07 00:00:00.000",
"ProductNumber": "TT-M928",
"Quantity": 1,
"LineTotal": 4.99,
"CustomerType": "Individual",
"TestData_1": "Sales extract OK!",
"TestData_2": 255
  }
}';

select
  jsonItemId,
  item,
  attrib,
  attribValue
from
(
  select
    jsonItemId = sum(sign(jsonItemIdPrep)) over (order by itemnumber),
    ItemNumber,
    item,
    attrib      = ltrim(replace(substring(item, 1, sep.pos-1),'"','')),
    attribValue = replace(ltrim(replace(substring(item, sep.pos+1, len(item)),'"','')),',',''),
    jsonItemIdPrep
  from
  (
    select ItemNumber, item, jsonItemIdPrep =
      case
        when item like '%"[0-9]": {%'
          or item like '%"[0-9][0-9]": {%'
          or item like '%"[0-9][0-9][0-9]": {%' -- 1,2 or 3 digits
        then substring(item, v.ps, charindex('"', item, v.ps)- v.ps)
      end
    from dbo.DelimitedSplit8K(replace(@json,char(10),''), char(13))
    cross apply (values (charindex('"',item)+1)) v(ps)
    where ItemNumber > 1 and item not like '%}' and item not like '%},'
  ) x
  cross apply (values (charindex(':', item))) sep(pos)
  cross apply (values (replace(substring(item, 1, sep.pos-1),'"',''))) p(xxx)
) x
where jsonItemIdPrep is null;

Results

jsonItemId  item                                                  attrib                        attribValue
----------- ----------------------------------------------------- ----------------------------- -----------------------------------
0           "SalesOrderNumber": "CSVSO67695",                 SalesOrderNumber              CSVSO67695
0           "SalesOrderDetailID": 97971,                      SalesOrderDetailID            97971
0           "OrderDate": "2014-03-05 00:00:00.000",           OrderDate                     2014-03-05 00:00:00.000
0           "ProductNumber": "WB-H098",                       ProductNumber                 WB-H098
0           "Quantity": 1,                                    Quantity                      1
0           "LineTotal": 4.99,                                LineTotal                     4.99
0           "CustomerType": "Individual",                     CustomerType                  Individual
0           "TestData_1": "Sales extract OK!",                TestData_1                    Sales extract OK!
0           "TestData_2": 255                                 TestData_2                    255
1           "SalesOrderNumber": "CSVSO53485",                 SalesOrderNumber              CSVSO53485
1           "SalesOrderDetailID": 47747,                      SalesOrderDetailID            47747
1           "OrderDate": "2013-07-31 00:00:00.000",           OrderDate                     2013-07-31 00:00:00.000
1           "ProductNumber": "SJ-0194-L",                     ProductNumber                 SJ-0194-L
1           "Quantity": 10,                                   Quantity                      10
1           "LineTotal": 323.94,                              LineTotal                     323.94
1           "CustomerType": "Store",                          CustomerType                  Store
1           "TestData_1": "Sales extract OK!",                TestData_1                    Sales extract OK!
1           "TestData_2": 255                                 TestData_2                    255
2           "SalesOrderNumber": "CSVSO52248",                 SalesOrderNumber              CSVSO52248
2           "SalesOrderDetailID": 43809,                      SalesOrderDetailID            43809
2           "OrderDate": "2013-07-07 00:00:00.000",           OrderDate                     2013-07-07 00:00:00.000
2           "ProductNumber": "TT-M928",                       ProductNumber                 TT-M928
2           "Quantity": 1,                                    Quantity                      1
2           "LineTotal": 4.99,                                LineTotal                     4.99
2           "CustomerType": "Individual",                     CustomerType                  Individual
2           "TestData_1": "Sales extract OK!",                TestData_1                    Sales extract OK!
2           "TestData_2": 255                                 TestData_2                    255


问:
How to add a Send feedback option on an app crashing?
How can I add a Send feedback option on an Android app crashing? This option is seen in Google's own apps and here is an example from Starbucks.

There are a number of very old answers to this question that involve programmatically creating something like this. They seem overly involved to make this show.

I'm surprised there isn't a simple way to implement this without putting a try catch around the entire app. Can this be enabled simply e.g. by enabling an option on the Google Play store console or by by adding something to the manifest?

I have not been able to find data on how to do this in the Android or Play Store documentation.

Update: We are using Crashlytics/Fabric as our crash reporting library

This image shows the default behaviour on Android 6.0.

And 8.0:

答:
There are a bunch of libraries for doing this, but if you're like me and don't like the overhead of generic libraries for such a simple task, it's pretty easy to do yourself.

Here are a few steps to get you going:

1) Add a class that extends Application (if you don't have one already).

2) In it's onCreate use Thread.setDefaultUncaughtExceptionHandler to set a custom UncoughtExceptionHandler.

3) In the custom handler, start an activity using an intent with the Intent.FLAG_ACTIVITY_NEW_TASK flag. For this activity add the android:process=":crash" attribute in the manifest (crash can be whatever you want). This step will make sure the new activity will start on a different process (This is important because the old one has crashed and now in a stack rollback process beacuse of the exception).

4) In this activity, do whatever you need. (present the UI you wanted for the crash report, and/or send an e-mail to yourself). JavaMail is good for the silent E-mailing.

Note: In the UncaughtExceptionHandler, you get the Thread and the Exception of the crash. You can easily extract the stack trace by using:
final StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
and/or extract the Thread name if you need those, and send them to the activity using the intent's bundle.

Hope This Helps


答:
So, here's an idea:

groupBy, because you need to group data from each month together

slice, because you need to see which is the month of the date

collect, because you need to filter by month and map to value

sum, mmmm... I'm not sure where this one comes in. Any ideas?

Title: Complex multi-dimensional list operations in Scala

Body:
Given a list such as the following:

val dane = List(
    ("2011-01-04", -137.76),
    ("2011-01-04", 2376.45),
    ("2011-01-04", -1.70),
    ("2011-01-04", -1.70),
    ("2011-01-04", -1.00),
    // ... skip a few ...
    ("2011-12-22", -178.02),
    ("2011-12-29", 1800.82),
    ("2011-12-23", -83.97),
    ("2011-12-24", -200.00),
    ("2011-12-24", -30.55),
    ("2011-12-30", 728.00)
)

I'd like to sum the values (i.e. the second item of the inner lists) of a specific month (e.g. January, or 01), using the following operations in the specified order:

groupBy

slice

collect

sum


问:
change greater than ('>' ) selector into simple css class in ul li tag
I want to remove CSS selector greater than ('>') in menu into simple CSS class.
 Greater than ('>') this selector have a lot of confusion for me actually I'm a beginner in web programming so I does not understand how this selector work.

this CSS rule and html code grab from anywhere so I want to change into class selector.

```<code>    // css
     .menu>ul>li{
            float:left;
            font-size:13px;
            position:relative
        }

         .menu>ul>li:hover{
            background:#083b65;
        }
        .menu>ul>li>a{
            height:38px;
            padding:13px 1px 13px 6px
        }

        .mobmenu ul li:hover{
            background:#083b65;
        }
        .mobmenu ul li{
            border-bottom: 1px solid white;
        }

        .mobmenu ul li a{
            padding:8px;
            white-space:nowrap;
            display:block;
            width:100%
        }

// html code

  <nav class="menu" >
            <ul class="mobmenu">
                <li>
                    <a href="#">Beginner</a>
                    <ul>
                        <li><a href="">  Web Programming for beginner  </a></li>
                        <li><a href="">  java Programming for beginner   </a></li>
                         <li><a href="">C# Programming for beginner      </a></li>
                         <li><a href="">>.NET Programming for beginner   </a></li>
                         <li><a href=""> C++ Programming for beginner    </a></li>
                    </ul>
                </li>
                 <li>
                    <a href="#">intermediate</a>
                    <ul >
                       <li><a href="">  Web Programming for intermediate  </a></li>
                        <li><a href="">  java Programming for intermediate   </a></li>
                         <li><a href="">C# Programming for intermediate      </a></li>
                         <li><a href="">>.NET Programming for intermediate   </a></li>
                         <li><a href=""> C++ Programming for intermediate    </a></li>

                    </ul>
                </li>
                  <li>
                    <a href="#">Advance</a>
                    <ul >
                       <li><a href="">  Web Programming for Advance  </a></li>
                        <li><a href="">  java Programming for Advance   </a></li>
                         <li><a href="">C# Programming for Advance      </a></li>
                         <li><a href="">>.NET Programming for Advance   </a></li>
                         <li><a href=""> C++ Programming for Advance    </a></li>
                       <li><a href="">  Web Programming for Advance  </a></li>
                        <li><a href="">  java Programming for Advance   </a></li>
                         <li><a href="">C# Programming for Advance      </a></li>
                         <li><a href="">>.NET Programming for Advance   </a></li>
                         <li><a href=""> C++ Programming for Advance    </a></li>

                    </ul>
                </li>
            </ul>

        </nav>
</code>```

答:
They are parent-child relationships. In your first selector (on top), .menu is a direct parent of ul and ul is a direct parent of li.

So that whole selector will target all li that has a ul as a parent that also has a .menu class as a parent.

Hope that helps.

ContentLicense: CC BY-SA 4.0

Body:
I want to remove CSS selector greater than ('>') in menu into simple CSS class.
 Greater than ('>') this selector have a lot of confusion for me actually I'm a beginner in web programming so I does not understand how this selector work.

this CSS rule and html code grab from anywhere so I want to change into class selector.

    // css
     .menu>ul>li{
            float:left;
            font-size:13px;
            position:relative
        }

         .menu>ul>li:hover{
            background:#083b65;
        }
        .menu>ul>li>a{
            height:38px;
            padding:13px 1px 13px 6px
        }

        .mobmenu ul li:hover{
            background:#083b65;
        }
        .mobmenu ul li{
            border-bottom: 1px solid white;
        }

        .mobmenu ul li a{
            padding:8px;
            white-space:nowrap;
            display:block;
            width:100%
        }

// html code

                    Beginner

  Web Programming for beginner

  java Programming for beginner

C# Programming for beginner

>.NET Programming for beginner

 C++ Programming for beginner

                    intermediate

  Web Programming for intermediate

  java Programming for intermediate

C# Programming for intermediate

>.NET Programming for intermediate

 C++ Programming for intermediate

                    Advance

  Web Programming for Advance

  java Programming for Advance

C# Programming for Advance

>.NET Programming for Advance

 C++ Programming for Advance

  Web Programming for Advance

  java Programming for Advance

C# Programming for Advance

>.NET Programming for Advance

 C++ Programming for Advance


问:
Hive External Table - Drop Table / Partition and Delete Data
When a hive external table or partition is dropped, it only removes the metadata from hive metastore. The underlying data in HDFS/ Azure storage account are not deleted. What are the options for deleting the data while the table/ partition is dropped?</p>

答:
I have been doing some research and these are my findings

Option 1:
Drop the table/ partition & remove corresponding files in HDFS/ Azure Blob storage if using HDInsight.

Option 2:
Update hive metastore to make the table property as managed. drop the partition and change back to table property external as below.

```<code>ALTER TABLE poc_drop_partition SET TBLPROPERTIES('EXTERNAL'='FALSE') ;
ALTER TABLE poc_drop_partition DROP IF EXISTS PARTITION(partition_date <= '2017-10-11');
ALTER TABLE poc_drop_partition SET TBLPROPERTIES('EXTERNAL'='TRUE') ;
</code>```

Similarly DROP table statement will drop the table and the underlying data files.

Is there any better ways of doing this. I am aware that there is TRUNCATE functionality in JIRA to be worked on.

Body:
I have been doing some research and these are my findings

Option 1:
Drop the table/ partition & remove corresponding files in HDFS/ Azure Blob storage if using HDInsight.

Option 2:
Update hive metastore to make the table property as managed. drop the partition and change back to table property external as below.

ALTER TABLE poc_drop_partition SET TBLPROPERTIES('EXTERNAL'='FALSE') ;
ALTER TABLE poc_drop_partition DROP IF EXISTS PARTITION(partition_date <= '2017-10-11');
ALTER TABLE poc_drop_partition SET TBLPROPERTIES('EXTERNAL'='TRUE') ;

Similarly DROP table statement will drop the table and the underlying data files.

Is there any better ways of doing this. I am aware that there is TRUNCATE functionality in JIRA to be worked on.