问:
Excel VBA Macro to search a column and display rows in pop up message based on column value
Im looking for some help creating an Excel macro that will seach Column A for cells that are not blank and column B for blanks on the same row then display a pop up message box when the workbook is opened showing the information for the rows that contain a name in Column A but do not have any information in the column B to remind people to complete items on the sheet.

Is this possible at all? IF so can someone please help with the code to make this work.

Many Thanks

答:
Based on what you've told me, this is what I can provide. Running it will find the first occurrence where Column A is not blank and Column B is missing text. You can then have your user fill it in, run it again to check for more.

```<code>Sub checkcolumns()
Dim i As Long

'100 is the last row you want to check. Change accordingly

For i = 1 To 100
    'Change Sheet1 to your worksheet name
    If ActiveWorkbook.Worksheets("Sheet1").Range("A" & i).Value <> "" And ActiveWorkbook.Worksheets("Sheet1").Range("B" & i).Value = "" Then
        MsgBox "Row " & i & " is missing a value in column B!", vbExclamation, "Missing value!"
        Exit Sub
    End If
Next i

MsgBox "Search complete, all values are in place!", vbInformation, "Success!"
End Sub
</code>```

To display all in one message:

```<code>Sub checkcolumns()
Dim i As Long
Dim message As String

For i = 1 To 100
    If ActiveWorkbook.Worksheets("Sheet1").Range("A" & i).Value <> "" And ActiveWorkbook.Worksheets("Sheet1").Range("B" & i).Value = "" Then
        message = message + "Row " & i & " is missing a value in Column B! "
    End If
Next i

MsgBox message, vbInformation, "Success!"
End Sub
</code>```

Body:
Based on what you've told me, this is what I can provide. Running it will find the first occurrence where Column A is not blank and Column B is missing text. You can then have your user fill it in, run it again to check for more.

Sub checkcolumns()
Dim i As Long

'100 is the last row you want to check. Change accordingly

For i = 1 To 100
    'Change Sheet1 to your worksheet name
    If ActiveWorkbook.Worksheets("Sheet1").Range("A" & i).Value <> "" And ActiveWorkbook.Worksheets("Sheet1").Range("B" & i).Value = "" Then
        MsgBox "Row " & i & " is missing a value in column B!", vbExclamation, "Missing value!"
        Exit Sub
    End If
Next i

MsgBox "Search complete, all values are in place!", vbInformation, "Success!"
End Sub

To display all in one message:

Sub checkcolumns()
Dim i As Long
Dim message As String

For i = 1 To 100
    If ActiveWorkbook.Worksheets("Sheet1").Range("A" & i).Value <> "" And ActiveWorkbook.Worksheets("Sheet1").Range("B" & i).Value = "" Then
        message = message + "Row " & i & " is missing a value in Column B! "
    End If
Next i

MsgBox message, vbInformation, "Success!"
End Sub


来源: stackexchange

问:
Angular2/cli code not running in IE
I have my angular2 code that is built using angular-cli which runs absolutely fine in Chrome. The same application doesn't run on IE. My tsconfig.json is as below. Are there any other things that I need to take care of.</p>

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "target": "es5",
    "experimentalDecorators": true,
    "lib": [
      "es2015"
    ]
  }
}
</code>```

答:
Try running polyfill.ts file that has scripts for old browsers.</p>

```<code>/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import 'classlist.js';  // Run `npm install --save classlist.js`.

/** IE10 and IE11 requires the following to support `@angular/animation`. */
 import 'web-animations-js';  // Run `npm install --save web-animations-js`.

/** Evergreen browsers require these. **/
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
</code>```

ContentLicense: CC BY-SA 3.0

Title: Angular2/cli code not running in IE

Body:
I have my angular2 code that is built using angular-cli which runs absolutely fine in Chrome. The same application doesn't run on IE. My tsconfig.json is as below. Are there any other things that I need to take care of.

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "target": "es5",
    "experimentalDecorators": true,
    "lib": [
      "es2015"
    ]
  }
}

Body:
Try running polyfill.ts file that has scripts for old browsers.

/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import 'classlist.js';  // Run `npm install --save classlist.js`.

/** IE10 and IE11 requires the following to support `@angular/animation`. */
 import 'web-animations-js';  // Run `npm install --save web-animations-js`.

/** Evergreen browsers require these. **/
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';


问:
React Native update style of Component
I'm trying to update the style of my TouchableOpacity Component when props change. I call a function, which is responsible for returning the style. Within that function I log the value of area.included. It returns the correct value, however the styles do not update appropriately.</p>

```<code><TouchableOpacity style={this.getRowStyle(area)} onPress={() => this.navToArea(area)}>
  <Text>Some Random Text</Text>
</TouchableOpacity>

getRowStyle(area) {
  console.log('area included', area.included)
  if (area.included) {
    return styles.swipeContainer
  } else {
    return styles.swipeContainerOpacity
  }
}

const styles = StyleSheet.create({
  swipeContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
  },
  swipeContainerOpacity: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
    opacity: 0.2,
  },
})
</code>```

答:
I ended up solving this by adding the conditions inline. I still think what I was doing should have worked. Potentially a react bug?</p>

```<code>{area.included &&
<TouchableOpacity style={styles.swipeContainer} onPress={() => this.navToArea(area)}>
  <Text>Some Random Text</Text>
</TouchableOpacity>
}
{!area.included &&
<TouchableOpacity style={styles.swipeContainerOpacity} onPress={() => this.navToArea(area)}>
  <Text>Some Random Text</Text>
</TouchableOpacity>
}
</code>```

Title: React Native update style of Component

Body:
I'm trying to update the style of my TouchableOpacity Component when props change. I call a function, which is responsible for returning the style. Within that function I log the value of area.included. It returns the correct value, however the styles do not update appropriately.

<TouchableOpacity style={this.getRowStyle(area)} onPress={() => this.navToArea(area)}>
  <Text>Some Random Text</Text>
</TouchableOpacity>

getRowStyle(area) {
  console.log('area included', area.included)
  if (area.included) {
    return styles.swipeContainer
  } else {
    return styles.swipeContainerOpacity
  }
}

const styles = StyleSheet.create({
  swipeContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
  },
  swipeContainerOpacity: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
    opacity: 0.2,
  },
})

Body:
I ended up solving this by adding the conditions inline. I still think what I was doing should have worked. Potentially a react bug?

{area.included &&
<TouchableOpacity style={styles.swipeContainer} onPress={() => this.navToArea(area)}>
  <Text>Some Random Text</Text>
</TouchableOpacity>
}
{!area.included &&
<TouchableOpacity style={styles.swipeContainerOpacity} onPress={() => this.navToArea(area)}>
  <Text>Some Random Text</Text>
</TouchableOpacity>
}


问:
Combining two python codes for raspberry pi with a servo and ldr sensor
I have Python code running on my raspberry pi 2b and a light sensor, which measures the amount of time it takes for the capacitor of the light sensor to charge and send the pin high:

```<code>import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)

pin_to_circuit = 7

def rc_time (pin_to_circuit):
    count = 0

    #Output on the pin for
    GPIO.setup(pin_to_circuit, GPIO.OUT)
    GPIO.output(pin_to_circuit, GPIO.LOW)
    time.sleep(0.1)

    #Change the pin back to input
    GPIO.setup(pin_to_circuit, GPIO.IN)

    #Count until the pin goes high
    while (GPIO.input(pin_to_circuit) == GPIO.LOW):
        count += 1

    if count > 1000000:
        return True
    else:
        return count

#Catch when script is interrupted, cleanup correctly
try:
# Main loop
while True:
    print rc_time(pin_to_circuit)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()
</code>```

I want when the count goes higher than 1000000, a MG90S, that I have also connected to the pi and a 4AA battery pack, moves about 90 degrees.
The code I was trying to integrate to move the servo:

```<code>import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

p.ChangeDutyCycle(7.5)  # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
GPIO.cleanup()
</code>```

I want to combine these two Python codes. I tried for a bit, but I have almost no Python experience.

答:
I've made a mistake in the code. I changed the order of the function call inside of the

```<code>if count > 1000000:
    return True
    move_90_degrees()
else:
    return count
</code>```

block to :

```<code>if count > 1000000:
    move_90_degrees()
    return True
else:
    return count
</code>```

otherwise, the code returns before the function call is executed. Is it working now?

Body:
I have Python code running on my raspberry pi 2b and a light sensor, which measures the amount of time it takes for the capacitor of the light sensor to charge and send the pin high:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)

pin_to_circuit = 7

def rc_time (pin_to_circuit):
    count = 0

    #Output on the pin for
    GPIO.setup(pin_to_circuit, GPIO.OUT)
    GPIO.output(pin_to_circuit, GPIO.LOW)
    time.sleep(0.1)

    #Change the pin back to input
    GPIO.setup(pin_to_circuit, GPIO.IN)

    #Count until the pin goes high
    while (GPIO.input(pin_to_circuit) == GPIO.LOW):
        count += 1

    if count > 1000000:
        return True
    else:
        return count

#Catch when script is interrupted, cleanup correctly
try:
# Main loop
while True:
    print rc_time(pin_to_circuit)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()

I want when the count goes higher than 1000000, a MG90S, that I have also connected to the pi and a 4AA battery pack, moves about 90 degrees.
The code I was trying to integrate to move the servo:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

p.ChangeDutyCycle(7.5)  # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
GPIO.cleanup()

I want to combine these two Python codes. I tried for a bit, but I have almost no Python experience.

Body:
I've made a mistake in the code. I changed the order of the function call inside of the

if count > 1000000:
    return True
    move_90_degrees()
else:
    return count

block to :

if count > 1000000:
    move_90_degrees()
    return True
else:
    return count

otherwise, the code returns before the function call is executed. Is it working now?


问:
How to get information from an unknown format file
I have this file which is simply called "KEY", no extension. It is used by a software that runs on MS-DOS, a very old one. I suspect this program uses that to store data, like the login password and other information.

My problem is that its an ancient software, there is no way to find its creator and there is a parameter from that file that I need to change (if it indeed holds that information). But when I open it with a notepad I see this:

ÜxÀYíÆÄÁÌsÎEÚ

¤gÄ[÷Á×

·

¤d×Q¤åÓÒÜs

Äeè

¤|ÀRëÖÒÁÌ

¾•

¤ ö[ðÐ    Å€ÌyœHæ Õ_èÔÄÁ

¿

É

¶

¤c÷o

³

¤ àNöÚ

³

¤c×]¤„F›žˆsÚB§ …¶•Kˆ€Çr

¶

¤ æKíÁ

µ•´‚V€—œ(

ÜzÄM÷Â    ÄÄõ

ïEÂ_

äCÀLöÐ

äEËJöÚ

ÜgÀP÷ÔÓÓõ

ÃOÕ_öÁÛÅÆhÓ

ÎDÂLáÆ–ÓÝ<ÿHæ\À

*iÉ_òÐFÓÒÚ¾ÒAæ

ÉXÊàÐFÄÅÏuÏPõKÁQöÔ

ÂLÀ]ðÜÙŽ’

ÓK×TáÁÅŽ’

ÄBÀOñÐ˜Ž’

ÄX'ZíÁ    ˜Ž’

3 ìPâÚÛÁËuÓJ§é

¤•

3 ñQðÔ ÓÓˆß

3 ëKáÃ    –ÖÉpÓV§é

§ …úú

§Tñ_æÙÅ

§Tæ_êÖÚÁ

§TñLåÛÛÉÜuÎ

¶•

±•

Û]ÌPàÚÅüËsÑIæDÁbéÓ…Ê2Ù\â

How can I decrypt this to get the information this file has?

Any help is appreciated.

Thank you!

答:
You can try TrIDNet, it will try to identify the file type based on known types.

http://mark0.net/soft-tridnet-e.html


问:
Conditionally enable/disable button control?
I've looked through the docs at https://dev.office.com/reference/add-ins/manifest/control but can't find anything.

I want to disable a button on the ribbon unless a certain condition is met. The condition would be the presence of a custom property on the selected mail item.

Can it be done?

答:
IMPORTANT UPDATE:

Enabling and Disabling Add-in Commands is now available in Preview for Excel. As part of AddinCommands 1.1, this feature supposed to be available for all Office products in the future.

THE OLD ANSWER:

Can it be done?

Nope.

Add-in commands for Outlook doesn't support dynamic enabling/disabling ribbon items. Activation rules are for context type of Outlook add-ins, which is currently not recommended way to write add-ins and they are not accepted by Office store.

Add-in commands for Excel, Word, and PowerPoint doesn't support dynamic enabling/disabling ribbon items either.

According to documentation on Control element of the Manifest none of the available controls have "enable/disable" attribute or tag.

If this is something you would like to see in upcoming releases, you may post/upvote your suggestion at https://officespdev.uservoice.com/

ContentLicense: CC BY-SA 4.0


问:
Woocommerce override Product Price with custom value on cart and checkout
i was wondering if someone had some experience with the following scenario.

I'm using WooCommerce to have my products listed, ready for sale. Some products (about 20) have a massive amount of variations, so i decided to have the product data in separated tables, and via SKU (simple query to get the data) to load them into woocommerce. So far, everything works great. These products are working fine. Their variations are showing up, and the user can select them, to add them to cart.

Thing is, i have setup these 20 products as single products, and gave them a price of $1, just to show the add to cart button (.single_add_to_cart_button), but when im selecting my variations (from the outside table/tables) the product gets added fine into the cart, but it shows for every product in that case, a price of $1, with all the custom fields included (which is nice). As far as i know, these custom fields are from the sessions). Below is all my code that im using in my functions.php (not mine, found on the net, fixed it to work with my case)

```
// Step 1: Add Data in a Custom Session, on ‘Add to Cart’ Button Click

add_action('wp_ajax_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
add_action('wp_ajax_nopriv_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');

function wdm_add_user_custom_data_options_callback()
{

    $product_id = $_POST['id'];
    $product_category = $_POST['product_category'];

    $custom_data_1 = $_POST['custom_data_1'];
    $custom_data_2 = $_POST['custom_data_2'];
    $custom_data_3 = $_POST['custom_data_3'];
    $custom_data_4 = $_POST['custom_data_4'];
    $custom_data_5 = $_POST['custom_data_5'];
    session_start();

    $_SESSION['custom_data_1'] = $custom_data_1;
    $_SESSION['custom_data_2'] = $custom_data_2;
    $_SESSION['custom_data_3'] = $custom_data_3;
    $_SESSION['custom_data_4'] = $custom_data_4;
    $_SESSION['custom_data_5'] = $custom_data_5;

    die();
}

// Step 2: Add Custom Data in WooCommerce Session

add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,2);

if(!function_exists('wdm_add_item_data'))
{

    function wdm_add_item_data($cart_item_data,$product_id)

    {
        global $woocommerce;
        session_start();
        $new_value = array();
        if (isset($_SESSION['custom_data_1'])) {
            $option1 = $_SESSION['custom_data_1'];
            $new_value['custom_data_1'] =  $option1;
        }
        if (isset($_SESSION['custom_data_2'])) {
            $option2 = $_SESSION['custom_data_2'];
            $new_value['custom_data_2'] =  $option2;
        }
        if (isset($_SESSION['custom_data_3'])) {
            $option3 = $_SESSION['custom_data_3'];
            $new_value['custom_data_3'] =  $option3;
        }
        if (isset($_SESSION['custom_data_4'])) {
            $option4 = $_SESSION['custom_data_4'];
            $new_value['custom_data_4'] =  $option4;
        }
        if (isset($_SESSION['custom_data_5'])) {
            $option5 = $_SESSION['custom_data_5'];
            $new_value['custom_data_5'] =  $option5;
        }

        if( empty($option1) && empty($option2) && empty($option3) && empty($option4) && empty($option5)  )
            return $cart_item_data;
        else
        {
            if(empty($cart_item_data))
                return $new_value;
            else
                return array_merge($cart_item_data,$new_value);
        }

        unset($_SESSION['custom_data_1']);
        unset($_SESSION['custom_data_2']);
        unset($_SESSION['custom_data_3']);
        unset($_SESSION['custom_data_4']);
        unset($_SESSION['custom_data_5']);

    }
}

// Step 3: Extract Custom Data from WooCommerce Session and Insert it into Cart Object

add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
if(!function_exists('wdm_get_cart_items_from_session'))
{
    function wdm_get_cart_items_from_session($item,$values,$key)
    {
        if (array_key_exists( 'custom_data_1', $values ) )
        {
            $item['custom_data_1'] = $values['custom_data_1'];
        }
        if (array_key_exists( 'custom_data_2', $values ) )
        {
            $item['custom_data_2'] = $values['custom_data_2'];
        }
        if (array_key_exists( 'custom_data_3', $values ) )
        {
            $item['custom_data_3'] = $values['custom_data_3'];
        }
        if (array_key_exists( 'custom_data_4', $values ) )
        {
            $item['custom_data_4'] = $values['custom_data_4'];
        }
        if (array_key_exists( 'custom_data_5', $values ) )
        {
            $item['custom_data_5'] = $values['custom_data_5'];
        }

        return $item;
    }
}

// Step 4: Display User Custom Data on Cart and Checkout page

add_filter('woocommerce_checkout_cart_item_quantity','wdm_add_user_custom_option_from_session_into_cart',1,3);
add_filter('woocommerce_cart_item_price','wdm_add_user_custom_option_from_session_into_cart',1,3);

if(!function_exists('wdm_add_user_custom_option_from_session_into_cart'))
{

    function wdm_add_user_custom_option_from_session_into_cart($product_name, $values, $cart_item_key )
    {

                        if(count($values['custom_data_1']) > 0)
                        {

                            $return_string = $product_name . "";
                            $return_string .= "";
                            $return_string .= "SKU : <b>" . $values['custom_data_1'] . "</b></p>";
                            //$return_string .= "Code : <b>" . $values['custom_data_2'] . "</b></p>";
                            $return_string .= "Width : <b>" . $values['custom_data_3'] . "</b> cm</p>";
                            $return_string .= "Height : <b>" . $values['custom_data_4'] . "</b> cm</p>";
                            $return_string .= "Price : <b>€ " . $values['custom_data_5'] . "</b></p>";
                            $return_string .= "";

                            return $return_string;
                        }
                        else
                        {
                            return $product_name;
                        }
    }

}

// Step 5: Add Custom Data as Metadata to the Order Items

add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
if(!function_exists('wdm_add_values_to_order_item_meta'))
{
    function wdm_add_values_to_order_item_meta($item_id, $values)
    {
        global $woocommerce,$wpdb;
        $user_custom_values = $values['wdm_user_custom_data_value'];
        if(!empty($user_custom_values))
        {
            wc_add_order_item_meta($item_id,'wdm_user_custom_data',$user_custom_values);
        }

        $custom_data_1 = $values['custom_data_1'];
        if(!empty($custom_data_1))
        {
            wc_add_order_item_meta($item_id,'custom_data_1',$custom_data_1);
        }
        $custom_data_2 = $values['custom_data_2'];
        if(!empty($custom_data_2))
        {
            wc_add_order_item_meta($item_id,'custom_data_2',$custom_data_2);
        }
        $custom_data_3 = $values['custom_data_3'];
        if(!empty($custom_data_3))
        {
            wc_add_order_item_meta($item_id,'custom_data_3',$custom_data_3);
        }
        $custom_data_4 = $values['custom_data_4'];
        if(!empty($custom_data_4))
        {
            wc_add_order_item_meta($item_id,'custom_data_4',$custom_data_4);
        }
        $custom_data_5 = $values['custom_data_5'];
        if(!empty($custom_data_5))
        {
            wc_add_order_item_meta($item_id,'custom_data_5',$custom_data_5);
        }
    }
}

// Step 6: Remove User Custom Data, if Product is Removed from Cart

add_action('woocommerce_before_cart_item_quantity_zero','wdm_remove_user_custom_data_options_from_cart',1,1);
if(!function_exists('wdm_remove_user_custom_data_options_from_cart'))
{
    function wdm_remove_user_custom_data_options_from_cart($cart_item_key)
    {
        global $woocommerce;
        // Get cart
        $cart = $woocommerce->cart->get_cart();
        // For each item in cart, if item is upsell of deleted product, delete it
        foreach( $cart as $key => $values)
        {
            if ( $values['wdm_user_custom_data_value'] == $cart_item_key )
                unset( $woocommerce->cart->cart_contents[ $key ] );
        }
    }
}
```

i tried to include the following code

```
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

    function add_custom_price( $cart_object ) {
        $custom_price = 999; // This is the custom price
        foreach ( $cart_object->cart_contents as $key => $value ) {
            $value['data']->price = $custom_price;
        }
    }
```

it changes the price to 999, since its fixed, but in my case, i am not able to include the value

```
$custom_data_5 = $_POST['custom_data_5']; // thats my unit price which needs to replace the $1 value of the simple product value from the product
```

any help would be appreciated on my side, since I'm running out of options right now, and this solution seems to be to correct one for me.

Jan

答:
all right, i think i got it done, searching and searching on stackoverflow.com of course ....

this i what i did :

```
 function ipe_add_to_cart_link() {

        global $product;
        $custom_price = 30;

        echo sprintf( '%s',
                esc_url( $product->add_to_cart_url() ),
                esc_attr( isset( $quantity ) ? $quantity : 1 ),
                $myCustomPrice, // Thats the value im getting from my add_to_cart_button - hidden
                esc_attr( $product->id ),
                esc_attr( $product->get_sku() ),
                esc_attr( isset( $class ) ? $class : 'button' ),
                esc_html( $product->add_to_cart_text() )
        );
}

add_filter('woocommerce_loop_add_to_cart_link','ipe_add_to_cart_link');

function ipe_product_custom_price( $cart_item_data, $product_id ) {

     if( isset( $_POST['myCustomPrice'] ) && !empty($_POST['myCustomPrice'])) {

         $cart_item_data[ "myCustomPrice" ] = $_POST['myCustomPrice'];
     }
     return $cart_item_data;

 }

 add_filter( 'woocommerce_add_cart_item_data', 'ipe_product_custom_price', 99, 2 );

function ipe_apply_custom_price_to_cart_item( $cart_object ) {
    if( !WC()->session->__isset( "reload_checkout" )) {

        foreach ( $cart_object->cart_contents as $key => $value ) {
            if( isset( $value["myCustomPrice"] ) ) {
                $value['data']->price = $value["myCustomPrice"];
            }
        }
    }
}

add_action( 'woocommerce_before_calculate_totals', 'ipe_apply_custom_price_to_cart_item', 99 );
```

and placed everything in functions.php - worked like a charm. Hope that this solution is helping someone out there.

Jan

Body:
i was wondering if someone had some experience with the following scenario.

I'm using WooCommerce to have my products listed, ready for sale. Some products (about 20) have a massive amount of variations, so i decided to have the product data in separated tables, and via SKU (simple query to get the data) to load them into woocommerce. So far, everything works great. These products are working fine. Their variations are showing up, and the user can select them, to add them to cart.

Thing is, i have setup these 20 products as single products, and gave them a price of $1, just to show the add to cart button (.single_add_to_cart_button), but when im selecting my variations (from the outside table/tables) the product gets added fine into the cart, but it shows for every product in that case, a price of $1, with all the custom fields included (which is nice). As far as i know, these custom fields are from the sessions). Below is all my code that im using in my functions.php (not mine, found on the net, fixed it to work with my case)

// Step 1: Add Data in a Custom Session, on ‘Add to Cart’ Button Click

add_action('wp_ajax_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
add_action('wp_ajax_nopriv_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');

function wdm_add_user_custom_data_options_callback()
{

    $product_id = $_POST['id'];
    $product_category = $_POST['product_category'];

    $custom_data_1 = $_POST['custom_data_1'];
    $custom_data_2 = $_POST['custom_data_2'];
    $custom_data_3 = $_POST['custom_data_3'];
    $custom_data_4 = $_POST['custom_data_4'];
    $custom_data_5 = $_POST['custom_data_5'];
    session_start();

    $_SESSION['custom_data_1'] = $custom_data_1;
    $_SESSION['custom_data_2'] = $custom_data_2;
    $_SESSION['custom_data_3'] = $custom_data_3;
    $_SESSION['custom_data_4'] = $custom_data_4;
    $_SESSION['custom_data_5'] = $custom_data_5;

    die();
}

// Step 2: Add Custom Data in WooCommerce Session

add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,2);

if(!function_exists('wdm_add_item_data'))
{

    function wdm_add_item_data($cart_item_data,$product_id)

    {
        global $woocommerce;
        session_start();
        $new_value = array();
        if (isset($_SESSION['custom_data_1'])) {
            $option1 = $_SESSION['custom_data_1'];
            $new_value['custom_data_1'] =  $option1;
        }
        if (isset($_SESSION['custom_data_2'])) {
            $option2 = $_SESSION['custom_data_2'];
            $new_value['custom_data_2'] =  $option2;
        }
        if (isset($_SESSION['custom_data_3'])) {
            $option3 = $_SESSION['custom_data_3'];
            $new_value['custom_data_3'] =  $option3;
        }
        if (isset($_SESSION['custom_data_4'])) {
            $option4 = $_SESSION['custom_data_4'];
            $new_value['custom_data_4'] =  $option4;
        }
        if (isset($_SESSION['custom_data_5'])) {
            $option5 = $_SESSION['custom_data_5'];
            $new_value['custom_data_5'] =  $option5;
        }

        if( empty($option1) && empty($option2) && empty($option3) && empty($option4) && empty($option5)  )
            return $cart_item_data;
        else
        {
            if(empty($cart_item_data))
                return $new_value;
            else
                return array_merge($cart_item_data,$new_value);
        }

        unset($_SESSION['custom_data_1']);
        unset($_SESSION['custom_data_2']);
        unset($_SESSION['custom_data_3']);
        unset($_SESSION['custom_data_4']);
        unset($_SESSION['custom_data_5']);

    }
}

// Step 3: Extract Custom Data from WooCommerce Session and Insert it into Cart Object

add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
if(!function_exists('wdm_get_cart_items_from_session'))
{
    function wdm_get_cart_items_from_session($item,$values,$key)
    {
        if (array_key_exists( 'custom_data_1', $values ) )
        {
            $item['custom_data_1'] = $values['custom_data_1'];
        }
        if (array_key_exists( 'custom_data_2', $values ) )
        {
            $item['custom_data_2'] = $values['custom_data_2'];
        }
        if (array_key_exists( 'custom_data_3', $values ) )
        {
            $item['custom_data_3'] = $values['custom_data_3'];
        }
        if (array_key_exists( 'custom_data_4', $values ) )
        {
            $item['custom_data_4'] = $values['custom_data_4'];
        }
        if (array_key_exists( 'custom_data_5', $values ) )
        {
            $item['custom_data_5'] = $values['custom_data_5'];
        }

        return $item;
    }
}

// Step 4: Display User Custom Data on Cart and Checkout page

add_filter('woocommerce_checkout_cart_item_quantity','wdm_add_user_custom_option_from_session_into_cart',1,3);
add_filter('woocommerce_cart_item_price','wdm_add_user_custom_option_from_session_into_cart',1,3);

if(!function_exists('wdm_add_user_custom_option_from_session_into_cart'))
{

    function wdm_add_user_custom_option_from_session_into_cart($product_name, $values, $cart_item_key )
    {

                        if(count($values['custom_data_1']) > 0)
                        {

                            $return_string = $product_name . "";
                            $return_string .= "";
                            $return_string .= "SKU : " . $values['custom_data_1'] . "
";
                            //$return_string .= "Code : " . $values['custom_data_2'] . "
";
                            $return_string .= "Width : " . $values['custom_data_3'] . " cm
";
                            $return_string .= "Height : " . $values['custom_data_4'] . " cm
";
                            $return_string .= "Price : € " . $values['custom_data_5'] . "
";
                            $return_string .= "";

                            return $return_string;
                        }
                        else
                        {
                            return $product_name;
                        }
    }

}

// Step 5: Add Custom Data as Metadata to the Order Items

add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
if(!function_exists('wdm_add_values_to_order_item_meta'))
{
    function wdm_add_values_to_order_item_meta($item_id, $values)
    {
        global $woocommerce,$wpdb;
        $user_custom_values = $values['wdm_user_custom_data_value'];
        if(!empty($user_custom_values))
        {
            wc_add_order_item_meta($item_id,'wdm_user_custom_data',$user_custom_values);
        }

        $custom_data_1 = $values['custom_data_1'];
        if(!empty($custom_data_1))
        {
            wc_add_order_item_meta($item_id,'custom_data_1',$custom_data_1);
        }
        $custom_data_2 = $values['custom_data_2'];
        if(!empty($custom_data_2))
        {
            wc_add_order_item_meta($item_id,'custom_data_2',$custom_data_2);
        }
        $custom_data_3 = $values['custom_data_3'];
        if(!empty($custom_data_3))
        {
            wc_add_order_item_meta($item_id,'custom_data_3',$custom_data_3);
        }
        $custom_data_4 = $values['custom_data_4'];
        if(!empty($custom_data_4))
        {
            wc_add_order_item_meta($item_id,'custom_data_4',$custom_data_4);
        }
        $custom_data_5 = $values['custom_data_5'];
        if(!empty($custom_data_5))
        {
            wc_add_order_item_meta($item_id,'custom_data_5',$custom_data_5);
        }
    }
}

// Step 6: Remove User Custom Data, if Product is Removed from Cart

add_action('woocommerce_before_cart_item_quantity_zero','wdm_remove_user_custom_data_options_from_cart',1,1);
if(!function_exists('wdm_remove_user_custom_data_options_from_cart'))
{
    function wdm_remove_user_custom_data_options_from_cart($cart_item_key)
    {
        global $woocommerce;
        // Get cart
        $cart = $woocommerce->cart->get_cart();
        // For each item in cart, if item is upsell of deleted product, delete it
        foreach( $cart as $key => $values)
        {
            if ( $values['wdm_user_custom_data_value'] == $cart_item_key )
                unset( $woocommerce->cart->cart_contents[ $key ] );
        }
    }
}

i tried to include the following code

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

    function add_custom_price( $cart_object ) {
        $custom_price = 999; // This is the custom price
        foreach ( $cart_object->cart_contents as $key => $value ) {
            $value['data']->price = $custom_price;
        }
    }

it changes the price to 999, since its fixed, but in my case, i am not able to include the value

$custom_data_5 = $_POST['custom_data_5']; // thats my unit price which needs to replace the $1 value of the simple product value from the product

any help would be appreciated on my side, since I'm running out of options right now, and this solution seems to be to correct one for me.

Jan

Body:
all right, i think i got it done, searching and searching on stackoverflow.com of course ....

this i what i did :

 function ipe_add_to_cart_link() {

        global $product;
        $custom_price = 30;

        echo sprintf( '%s',
                esc_url( $product->add_to_cart_url() ),
                esc_attr( isset( $quantity ) ? $quantity : 1 ),
                $myCustomPrice, // Thats the value im getting from my add_to_cart_button - hidden
                esc_attr( $product->id ),
                esc_attr( $product->get_sku() ),
                esc_attr( isset( $class ) ? $class : 'button' ),
                esc_html( $product->add_to_cart_text() )
        );
}

add_filter('woocommerce_loop_add_to_cart_link','ipe_add_to_cart_link');

function ipe_product_custom_price( $cart_item_data, $product_id ) {

     if( isset( $_POST['myCustomPrice'] ) && !empty($_POST['myCustomPrice'])) {

         $cart_item_data[ "myCustomPrice" ] = $_POST['myCustomPrice'];
     }
     return $cart_item_data;

 }

 add_filter( 'woocommerce_add_cart_item_data', 'ipe_product_custom_price', 99, 2 );

function ipe_apply_custom_price_to_cart_item( $cart_object ) {
    if( !WC()->session->__isset( "reload_checkout" )) {

        foreach ( $cart_object->cart_contents as $key => $value ) {
            if( isset( $value["myCustomPrice"] ) ) {
                $value['data']->price = $value["myCustomPrice"];
            }
        }
    }
}

add_action( 'woocommerce_before_calculate_totals', 'ipe_apply_custom_price_to_cart_item', 99 );

and placed everything in functions.php - worked like a charm. Hope that this solution is helping someone out there.

Jan


问:
Paramiko exec_command not behaving as expected
I have a Python script to start a group of WebLogic server's node managers. The main call to do this is as follows:

stdin, stdout, stderr = client.exec_command('/app/oracle/Middleware/Oracle_Home/user_projects/domains/base_domain/bin/startNodeManager.sh')

This will start the processes on the servers but when I try to connect to Node Manager via WLST's nmConnect() I receive an error that Node Manager is not working. However one machine works...

I am running this from a script on a different machine. The script uses the third-party paramiko Python library to ssh into the remote machine and then call the above command. An interesting part of this problem is that the program is seen running in ps -ef | grep nodemanager. However when I try to issue nmConnect() I cannot connect as I normally can if I manually start node manager from the operating system myself.

答:
does the startNodeManager.sh by any chance output more than few lines of output? If so, my guess would be on process blocking during execution because you don't read out it's output...

For proper way to execute commands via paramiko, I'd recommend looking at this:  http://stackoverflow.com/a/32758464


问:
Callback functions in Java
Is there a way to pass a call back function in a Java method?

The behavior I'm trying to mimic is a .Net Delegate being passed to a function.

I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.

答:
A method is not (yet) a first-class object in Java; you can't pass a function pointer as a callback. Instead, create an object (which usually implements an interface) that contains the method you need and pass that.

Proposals for closures in Java—which would provide the behavior you are looking for—have been made, but none will be included in the upcoming Java 7 release.

OwnerDisplayName: Omar Kooheji

Title: Callback functions in Java

OwnerDisplayName: erickson

ContentLicense: CC BY-SA 2.5


问:
Difference between Select Unique and Select Distinct
I thought these were synonomous, but I wrote the following in Microsoft SQL:

```<code>Select Unique col from
     (select col from table1 union select col from table2) alias
</code>```

And it failed.  Changing it to

```<code>Select Distinct col from
     (select col from table1 union select col from table2) alias
</code>```

fixed it.  Can someone explain?

答:
Unique was the old syntax while Distinct is the new syntax,which is now the Standard sql.

Unique creates a constraint that all values to be inserted must be different from the others.
An error can be witnessed if one tries to enter a duplicate value.
Distinct results in the removal of the duplicate rows while retrieving data.

Example:
SELECT DISTINCT names FROM student ;

CREATE TABLE Persons (
Id varchar NOT NULL UNIQUE,
Name varchar(20) );

Body:
I thought these were synonomous, but I wrote the following in Microsoft SQL:

Select Unique col from
     (select col from table1 union select col from table2) alias

And it failed.  Changing it to

Select Distinct col from
     (select col from table1 union select col from table2) alias

fixed it.  Can someone explain?


问:
Visual Studio solution doesn't compile, but project does
When I build or rebuild my solution I get the error:

Error  CS2012  Cannot open 'C:\Users\myUserName\Documents\Visual Studio 2017\Projects\mySolutionFolder\myProjectFolder\obj\Debug\myExecutable.exe' for writing -- 'Access to the path 'C:\Users\myUserName\Documents\Visual Studio 2017\Projects\mySolutionFolder\myProjectFolder\obj\Debug\myExecutable.exe' is denied.'

However, when I build the project, it compiles fine. Once I build the project then a solution build doesn't throw any errors. I am running visual Studio 2017.

What I've tried (without success):

There is a second project in the solution, but I've unloaded it and it still errors.

I deleted the solution file and had visual studio create a new one.

Additional Info:
The error is somewhat random. Usually it errors out, but sometimes not. The odds of an error are reduced the longer I wait between a "Clean" and a rebuild. I have the same problem even when running in Administrator mode. I'm beginning to think it's a hard drive issue.

答:
The application is still running.

\Debug\myExecutable.exe' is denied.' is telling you that you cant replace that because its currently open.

Open task manager and make sure that you end that process, and it should work fine after that.

This is usually what happens to me when I get that error.

Hope this helps


问:
What the different between React$Element and ReactElement
I am trying to use flow with ReactJS. I need to add type to prop children. The article (Flow + React) does not say anything about it.

I'v found a lot of examples which use ReactElement (e.g). But flow says identifier ReactElement. Could not resolve name. I use React$Element<*> and it works.

The question. What the different between React$Element and ReactElement? And where can I find information about React$Element? Where does flow search type definitions.

答:
React$Element currently lives in the 'react.js' library file bundled with Flow:

```<code>/**
 * Type of a React element. React elements are commonly created using JSX
 * literals, which desugar to React.createElement calls (see below). The type
 * parameterization of React$Element mimics that of ReactClass (see above).
 */
declare class React$Element<Config> {
  type: ReactClass<Config>;
  props: $PropsOf<Config>;
  key: ?string;
  ref: any;
}
</code>```

It might eventually move to the new flowtype/flow-typed repo as the Flow team mentioned in their Introducing Flow Typed blog post. If you need definitions for libraries you install from NPM, 'flow-typed' is where to look.

Body:
React$Element currently lives in the 'react.js' library file bundled with Flow:

/**
 * Type of a React element. React elements are commonly created using JSX
 * literals, which desugar to React.createElement calls (see below). The type
 * parameterization of React$Element mimics that of ReactClass (see above).
 */
declare class React$Element<Config> {
  type: ReactClass<Config>;
  props: $PropsOf<Config>;
  key: ?string;
  ref: any;
}

It might eventually move to the new flowtype/flow-typed repo as the Flow team mentioned in their Introducing Flow Typed blog post. If you need definitions for libraries you install from NPM, 'flow-typed' is where to look.


问:
Convert all words from text file to UpperCase using cmd or vbsscript
I have a text file called C:\Test.txt. I would like to convert all words inside the text file to UpperCases using cmd. Could you please help me?

I tried with

```<code>@echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%a in (%1) do (
   set "line=%%a"
   for %%b in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
      set "line=!line:%%b=%%b!"
   )
   echo !line!
)
</code>```

but i do not see where to put the location of the test.txt file

答:
After loading text file as a variable, you could loop throught each char with
    foreach
 and check the Asci value (msgbox Asc("A")).
if asci code is between 97 and 122 ("a" and "z") , remove 32 ("A" is 65 and "a" is 97  ---->  "z" is 122 and "Z" is 90).</p>

Body:
I have a text file called C:\Test.txt. I would like to convert all words inside the text file to UpperCases using cmd. Could you please help me?

I tried with

@echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%a in (%1) do (
   set "line=%%a"
   for %%b in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
      set "line=!line:%%b=%%b!"
   )
   echo !line!
)

but i do not see where to put the location of the test.txt file


问:
QSerialPort with thread
I have been struggling a project that it communicates through the serial port in Qt for around two weeks. First I tried signal/slot method, it missed some data. Then I decided to use a thread for this, but I got the same result. While the application's window is being resized or maximized /minimized, even hold left mouse button on the window's bar, it missed some data. Please help me this condition.

The MainWindow Constructor:

```<code>SerialPort *serial= new SerialPort();
serial->moveToThread(&cThread);

connect(this , &MainWindow::finished, &cThread, &QThread::quit);
connect(this , &MainWindow::destroyed, this, &SerialPort::deleteLater);
connect(serial, &SerialPort::getData, this, &MainWindow::displayData);

cThread.start();
</code>```

The Serial Port read thread:

```<code>void SerialPort::newData()
{
     mutex.lock();
     bArray.insert(bArray.length(),serial->readAll());
     mutex.unlock();

     emit getData(&bArray,&mutex);
}
</code>```

The SerialPort Constructor:

```<code>serial = new QSerialPort();
connect(serial, &QSerialPort::readyRead, this,  &SerialPort::newData);

bArray.clear();

fill_serial_ports();
portName = find_stm32_port();

serial->setReadBufferSize(20*1024*1024); // it's a huge buffer.
bArray.reserve(20*1024*1024);  // it's a huge buffer.

open_serial_port();
</code>```

Also, I thought that this can be a bug what misses some data and wrote to the bug tracker. Assignee said that QSerialPort never loses data furthermore, my code is wrong. I'm very confused, I don't know where to make mistakes. Please, could you check my other solution? Where is the mistake?

My bug tracker report (Not accepted) : https://bugreports.qt.io/browse/QTBUG-61233

答:
Try to move your inner QSerialPort object serial to thread cThread too:

```<code>SerialPort *serial = new SerialPort();
serial->moveToThread(&cThread);
serial->serial.moveToThread(&cThread); // move you inner QSerialPort to cThread
</code>```

In the code above inner field serial->serial.moveToTheThread(...) does the magic.

Title: QSerialPort with thread

Body:
I have been struggling a project that it communicates through the serial port in Qt for around two weeks. First I tried signal/slot method, it missed some data. Then I decided to use a thread for this, but I got the same result. While the application's window is being resized or maximized /minimized, even hold left mouse button on the window's bar, it missed some data. Please help me this condition.

The MainWindow Constructor:

SerialPort *serial= new SerialPort();
serial->moveToThread(&cThread);

connect(this , &MainWindow::finished, &cThread, &QThread::quit);
connect(this , &MainWindow::destroyed, this, &SerialPort::deleteLater);
connect(serial, &SerialPort::getData, this, &MainWindow::displayData);

cThread.start();

The Serial Port read thread:

void SerialPort::newData()
{
     mutex.lock();
     bArray.insert(bArray.length(),serial->readAll());
     mutex.unlock();

     emit getData(&bArray,&mutex);
}

The SerialPort Constructor:

serial = new QSerialPort();
connect(serial, &QSerialPort::readyRead, this,  &SerialPort::newData);

bArray.clear();

fill_serial_ports();
portName = find_stm32_port();

serial->setReadBufferSize(20*1024*1024); // it's a huge buffer.
bArray.reserve(20*1024*1024);  // it's a huge buffer.

open_serial_port();

Also, I thought that this can be a bug what misses some data and wrote to the bug tracker. Assignee said that QSerialPort never loses data furthermore, my code is wrong. I'm very confused, I don't know where to make mistakes. Please, could you check my other solution? Where is the mistake?

My bug tracker report (Not accepted) : https://bugreports.qt.io/browse/QTBUG-61233

Body:
Try to move your inner QSerialPort object serial to thread cThread too:

SerialPort *serial = new SerialPort();
serial->moveToThread(&cThread);
serial->serial.moveToThread(&cThread); // move you inner QSerialPort to cThread

In the code above inner field serial->serial.moveToTheThread(...) does the magic.


问:
Split up Java code into Tokens
I need to be able to split Java code into individual tokens, where a token is a string of code which does not depend on spaces.

For instance, the following Java code:

```<code>if (method(a, b).equals("C, C++, Java"))
</code>```

would be split into:

```<code>['if', '(', 'method', '(', 'a', ',', 'b', ')', '.', 'equals', '(', '"C, C++, Java"', ')', ')']
</code>```

Basically, I need a list of tokens that can be (un)padded with spaces without changing the execution of the code. If I take the previous code example, I can add and remove spaces around the tokens to form something like:

```<code>if   (method    ( a,b)   . equals   ( "C, C++, Java")       )
</code>```

and I would still get the same result.

I'm guessing this is only possible through some external library, but I'm not aware of any.

答:
Parser generators like antlr or javacc have complete java grammars as examples. You could reuse the generated tokenizer to achieve your goal.

You could achieve some kind of tokenizing using regular expressions as well. But that would not 100 percent java tokens.

Title: Split up Java code into Tokens

Body:
I need to be able to split Java code into individual tokens, where a token is a string of code which does not depend on spaces.

For instance, the following Java code:

if (method(a, b).equals("C, C++, Java"))

would be split into:

['if', '(', 'method', '(', 'a', ',', 'b', ')', '.', 'equals', '(', '"C, C++, Java"', ')', ')']

Basically, I need a list of tokens that can be (un)padded with spaces without changing the execution of the code. If I take the previous code example, I can add and remove spaces around the tokens to form something like:

if   (method    ( a,b)   . equals   ( "C, C++, Java")       )

and I would still get the same result.

I'm guessing this is only possible through some external library, but I'm not aware of any.


问:
Check the status of last SQL statement that was executed in a stored procedure
How to check the status of the last SQL statement that was executed in a SQL Server stored procedure?

Code:

```<code>SET @SQLStmt = N'CREATE CLUSTERED COLUMNSTORE INDEX CCSI ON '+ @DBName +N'.dbo.' + @ResultTableName + N' WITH ( DROP_EXISTING = OFF )'

EXEC dbo.pCOMMON_PrintVariable ': Create Clustered Columnstore Index: ', @SQLStmt
EXEC sp_executesql @SQLStmt
</code>```

Would like to check the status of the above statement and trigger some code after these statements.

答:
You can put the statement you want to check in a TRY..CATCH block.  If it fails, it will go to the CATCH block.   If it succeeds, it will go to the next statement after it.

Sample psuedo code:

```<code>BEGIN TRY
  SET @SQLStmt = N'CREATE CLUSTERED COLUMNSTORE INDEX CCSI ON '+ @DBName +N'.dbo.' + @ResultTableName + N' WITH ( DROP_EXISTING = OFF )'

  EXEC dbo.pCOMMON_PrintVariable ': Create Clustered Columnstore Index: ', @SQLStmt
  EXEC sp_executesql @SQLStmt

  --do whatever you want to do if the above statements succeed
END TRY

BEGIN CATCH
  --do whatever you want to do if the above statements fail
END CATCH
</code>```

Body:
How to check the status of the last SQL statement that was executed in a SQL Server stored procedure?

Code:

SET @SQLStmt = N'CREATE CLUSTERED COLUMNSTORE INDEX CCSI ON '+ @DBName +N'.dbo.' + @ResultTableName + N' WITH ( DROP_EXISTING = OFF )'

EXEC dbo.pCOMMON_PrintVariable ': Create Clustered Columnstore Index: ', @SQLStmt
EXEC sp_executesql @SQLStmt

Would like to check the status of the above statement and trigger some code after these statements.

Body:
You can put the statement you want to check in a TRY..CATCH block.  If it fails, it will go to the CATCH block.   If it succeeds, it will go to the next statement after it.

Sample psuedo code:

BEGIN TRY
  SET @SQLStmt = N'CREATE CLUSTERED COLUMNSTORE INDEX CCSI ON '+ @DBName +N'.dbo.' + @ResultTableName + N' WITH ( DROP_EXISTING = OFF )'

  EXEC dbo.pCOMMON_PrintVariable ': Create Clustered Columnstore Index: ', @SQLStmt
  EXEC sp_executesql @SQLStmt

  --do whatever you want to do if the above statements succeed
END TRY

BEGIN CATCH
  --do whatever you want to do if the above statements fail
END CATCH


答:
Thing is: in the end, any external library will be using standard Java libraries. So of course: you can sit down and write your own Java parser. From bottom to top.

But the real answer is: unless this is for a school project, simply don't re-invent the wheel. Of course building a parser and tokenizer is a very valuable lesson for programmers, it is also quite some work. And chances are that it will cost you days (probably weeks)  even when following the approach given in the other answer (relying on parts of existing technology).

So when you asking: how to do that efficiently, look out for existing Java parsers; for example JavaParser. You see, in the real world, requirements change and evolve quickly. Today you are asked to solve the simple problem outlined in the question. But it is likely that more and more ideas what the tool should do will evolve. And sooner or later, nothing else but a full fledged parser will do. So why not start with such a thing in the first place?

Title: Split up Java code into Tokens


问:
Instead of renaming my file just duplicating
I have a program that should process the files in the directory and if the file size is more than 50 bytes delete it. Otherwise, if the file size is less then 50 bytes program should rename the args[1] file to the allFilesContent.txt(same directory), and write all the files to this file, separated by "n" (110 ASCII code). But instead the program just creates another file and writes to the very first args[1] file. What's the problem? </p>

```<code>public class Solution
{
    public static void main(String [] args) throws IOException
    {
        File path = new File(args[0]);
        File resultFileAbsolutePath = new File(args[1]);
        ArrayList<File> allFiles = new ArrayList<>();
        boolean isRenamed = false;

        for(File file : path.listFiles())
        {
            if(file.length() > 50)
            {
                FileUtils.deleteFile(file);
            }

            else if(file.length() <= 50)
            {
                if(!isRenamed)
                {
                FileUtils.renameFile(resultFileAbsolutePath, new File(resultFileAbsolutePath.getParent()+"\\allFilesContent.txt"));
                isRenamed = true;
                }
                if(!file.getName().equals(resultFileAbsolutePath.getName()))
                {
                allFiles.add(file);
                }
            }
        }

        Collections.sort(allFiles, new Comparator<File>()
        {
            @Override
            public int compare(File o1, File o2)
            {
                return o1.getName().compareTo(o2.getName());
            }
        });

        FileOutputStream fileOutputStream = new FileOutputStream(resultFileAbsolutePath, true);

        for (File file : allFiles)
        {
            try(FileInputStream fileInputStream = new FileInputStream(file))
            {
                if(allFiles.indexOf(file) != 0) fileOutputStream.write(110);
                int data;
                while(fileInputStream.available() > 0)
                {
                    data = fileInputStream.read();
                    fileOutputStream.write(data);
                }
            }
        }

       fileOutputStream.close();
    }

    public static void deleteFile(File file)
    {
        if (!file.delete())
        {
            System.out.println("Can not delete file with name " + file.getName());
        }
    }
}
</code>```

<p>And FileUtils class </p>

```<code>import java.io.File;

public class FileUtils
{

    public static void deleteFile(File file)
    {
        if (!file.delete())
        {
            System.out.println("Can not delete file with name " + file.getName());
        }
    }

    public static void renameFile(File source, File destination)
    {
        if (!source.renameTo(destination))
        {
            System.out.println("Can not rename file with name " + source.getName());
        }
    }
}
</code>```

答:
You have following statement: "FileOutputStream fileOutputStream = new FileOutputStream(resultFileAbsolutePath, true);"

Instead of "true" put "false". It should work.

Body:
I have a program that should process the files in the directory and if the file size is more than 50 bytes delete it. Otherwise, if the file size is less then 50 bytes program should rename the args[1] file to the allFilesContent.txt(same directory), and write all the files to this file, separated by "n" (110 ASCII code). But instead the program just creates another file and writes to the very first args[1] file. What's the problem?

public class Solution
{
    public static void main(String [] args) throws IOException
    {
        File path = new File(args[0]);
        File resultFileAbsolutePath = new File(args[1]);
        ArrayList<File> allFiles = new ArrayList<>();
        boolean isRenamed = false;

        for(File file : path.listFiles())
        {
            if(file.length() > 50)
            {
                FileUtils.deleteFile(file);
            }

            else if(file.length() <= 50)
            {
                if(!isRenamed)
                {
                FileUtils.renameFile(resultFileAbsolutePath, new File(resultFileAbsolutePath.getParent()+"\\allFilesContent.txt"));
                isRenamed = true;
                }
                if(!file.getName().equals(resultFileAbsolutePath.getName()))
                {
                allFiles.add(file);
                }
            }
        }

        Collections.sort(allFiles, new Comparator<File>()
        {
            @Override
            public int compare(File o1, File o2)
            {
                return o1.getName().compareTo(o2.getName());
            }
        });

        FileOutputStream fileOutputStream = new FileOutputStream(resultFileAbsolutePath, true);

        for (File file : allFiles)
        {
            try(FileInputStream fileInputStream = new FileInputStream(file))
            {
                if(allFiles.indexOf(file) != 0) fileOutputStream.write(110);
                int data;
                while(fileInputStream.available() > 0)
                {
                    data = fileInputStream.read();
                    fileOutputStream.write(data);
                }
            }
        }

       fileOutputStream.close();
    }

    public static void deleteFile(File file)
    {
        if (!file.delete())
        {
            System.out.println("Can not delete file with name " + file.getName());
        }
    }
}

And FileUtils class

import java.io.File;

public class FileUtils
{

    public static void deleteFile(File file)
    {
        if (!file.delete())
        {
            System.out.println("Can not delete file with name " + file.getName());
        }
    }

    public static void renameFile(File source, File destination)
    {
        if (!source.renameTo(destination))
        {
            System.out.println("Can not rename file with name " + source.getName());
        }
    }
}


问:
Is there a way for a Chef recipe to continue after a reboot (Windows)?
I am trying to use Chef to automate installation/deployment of an older version of a Windows product (Sharepoint 2007, specifically), and I almost have it working, but, at one point during the installation, the installer encounters an "application compatibility" problem and pops up a window that asks whether to continue or not.  If I click to continue, the installation continues to the end, and it works properly.

I found a way to avoid the popup, by adding an "Appcompat" key in the windows registry, but if I use regedit to add the key during the Chef run, I have to get Chef to reboot the machine and then to continue with the rest of the installation afterwards.

I've tried a recipe with something like:

```<code>reboot 'Restart Computer' do
  action :nothing
end

powershell_script "install-Sharepoint2007-PREREQUISITES" do
code <<-EOH

regedit /s .\appcompat.reg

EOH

notifies :reboot_now, 'reboot[Restart Computer]', :immediately

end

powershell_script "install-Sharepoint2007" do
code <<-EOH

... the rest of the installation....

EOH

notifies :reboot_now, 'reboot[Restart Computer]', :immediately

end
</code>```

but the processing basically stops, after the reboot after setting the registry key.

So I was wondering:  Is there a way to do this with Chef?

Thanks,
Jim

EDIT:

I find it hard to use just the comments because of lack of formatting so I'm adding information on what I have tried thus far here.

Basically, the only way I can get the chef-client to run in a scheduled task so far is to do a "ONCE" scheduled task, setting the time for the task to run (so far, I'm manually setting the time in my schtasks command, just to test).

When I do that, and set the "/RU" to SYSTEM, I can see the "chef-client -o" start to run and it actually seems to complete, but I see errors in the Sharepoint installer logs, and in particular, it appears that some of the steps in the psconfig (the Sharepoint command line configuration tool) are failing.

I think/guess that the reason for those failures is that the schtasks is running the "chef-client -o" as the wrong Windows user.

The thing is, if I run the "chef-client -o" on the 2nd part cookbook "manually", i.e., if I log into the Windows machine and type:

chef-client -o install-SHAREPOINT-PART2

Then, Sharepoint gets installed and configured correctly.

So, the thing I'm stuck on now is when I do that same "chef-client -o" command via schtasks, what should I use as the "/RU" and "/RP" for the schtasks command?

Thanks,
Jim

EDIT 2:  Sorry, I forgot to include the schtasks line in the first cookbook/recipe, which sets up the task for the second cookbook/recipe chef run:

```<code>schtasks /create /tn Task_Name /tr "chef-client -o install-SHAREPOINT2007FULL-PART2" /sc once /RU "SYSTEM" /SD 06/27/2015 /ST 12:30
</code>```

EDIT 3: The original reason that I was looking into this (having Chef work "through" a reboot) was that as part of installing Sharepoint, I had to set a Windows registry key, and I thought that I had to reboot to make that registry change effective for the rest of the install process.

However, I did some testing yesterday, and it appears that is not the case.  I can make the registry change, then do the rest of the installation, without having to reboot in between.

So, bottom line is that I didn't need to process after the reboot after all.

But anyway, hopefully some of the info here may help someone later.  The main thing I found was was I couldn't get it to work using ONSTART with the /Z /V1...  I had to use the ONCE and would have had to have code in my Chef recipe to figure out the date and time to fire the ONCE tasks.

答:
I have done it using FLAG file method, example given below.
Example of domain join-</p>

```<code>---------------------------Script Start------------------------

    powershell_script 'Domain_Join' do
    guard_interpreter :powershell_script
    code -domainJoin
    $currentTime = Get-Date
    $currentTimeString = $currentTime.ToString()

  $systemDomain = (Get-WmiObject Win32_ComputerSystem).Domain
  If (($systemDomain) -eq 'domainName')
  {
    Try {
  write-host "$env:computerName is DOMAIN MEMBER"
  Remove-Item C:\\DomainJoinFlag.txt -ErrorAction Stop
  Unregister-ScheduledTask -TaskName "Chef client schedule_DJ" -Confirm:$false
  } # end of Try
          Catch [System.Management.Automation.ItemNotFoundException]
            { write-host "Server is already domain member, Or Exception raised due to either missing FLAG file or Server startup schedule task configuration."
              eventcreate /t INFORMATION /ID 0909 /L APPLICATION /SO "ChefClient_$env:computerName" /D "Server is already domain member, Or Exception raised due to either missing FLAG file or Server startup schedule task configuration. Refer to the CHEF reciepie for DomainJoin or check Administrative credentials for creting schedule task"}
            }
    else { write-host "$env:computerName is NOT domain member, joining the server to the domain. Server will be rebooting in a while..."
            eventcreate /t INFORMATION /ID 0909 /L APPLICATION /SO "ChefClient_$env:computerName" /D "Joining the server : $env:ComputerName to the domain ININLAB.COM (Server Time): $currentTimeString"
            New-Item C:\\DomainJoinFlag.txt -type file -force
            write-host "$env:computerName DOMAIN JOIN INITIATED for the server"
            $cred = New-Object System.Management.Automation.PsCredential("domain\\domain_user", (ConvertTo-SecureString "Password" -AsPlainText -Force))
            Add-Computer -DomainName "domainName" -Credential $cred -OUPath "OU=HyperV,OU=Infrastructure,OU=Servers,DC=domain,DC=name"
            shutdown -r -t 120
            } #end_of_else
            domainJoin
  notifies :run, 'windows_task[Chef client schedule_DJ]', :immediately
end

windows_task 'Chef client schedule_DJ' do
  user 'SYSTEM'
  command 'chef-client -L C:\chef\chef-client_after_reboot_domainJoin.log'
  run_level :highest
  frequency :onstart
  frequency_modifier 30
  action :create
  only_if { ::File.exist?('C:\\DomainJoinFlag.txt') }
end

---------------------------Script Ends------------------------
</code>```

Body:
I am trying to use Chef to automate installation/deployment of an older version of a Windows product (Sharepoint 2007, specifically), and I almost have it working, but, at one point during the installation, the installer encounters an "application compatibility" problem and pops up a window that asks whether to continue or not.  If I click to continue, the installation continues to the end, and it works properly.

I found a way to avoid the popup, by adding an "Appcompat" key in the windows registry, but if I use regedit to add the key during the Chef run, I have to get Chef to reboot the machine and then to continue with the rest of the installation afterwards.

I've tried a recipe with something like:

reboot 'Restart Computer' do
  action :nothing
end

powershell_script "install-Sharepoint2007-PREREQUISITES" do
code <<-EOH

regedit /s .\appcompat.reg

EOH

notifies :reboot_now, 'reboot[Restart Computer]', :immediately

end

powershell_script "install-Sharepoint2007" do
code <<-EOH

... the rest of the installation....

EOH

notifies :reboot_now, 'reboot[Restart Computer]', :immediately

end

but the processing basically stops, after the reboot after setting the registry key.

So I was wondering:  Is there a way to do this with Chef?

Thanks,
Jim

EDIT:

I find it hard to use just the comments because of lack of formatting so I'm adding information on what I have tried thus far here.

Basically, the only way I can get the chef-client to run in a scheduled task so far is to do a "ONCE" scheduled task, setting the time for the task to run (so far, I'm manually setting the time in my schtasks command, just to test).

When I do that, and set the "/RU" to SYSTEM, I can see the "chef-client -o" start to run and it actually seems to complete, but I see errors in the Sharepoint installer logs, and in particular, it appears that some of the steps in the psconfig (the Sharepoint command line configuration tool) are failing.

I think/guess that the reason for those failures is that the schtasks is running the "chef-client -o" as the wrong Windows user.

The thing is, if I run the "chef-client -o" on the 2nd part cookbook "manually", i.e., if I log into the Windows machine and type:

chef-client -o install-SHAREPOINT-PART2

Then, Sharepoint gets installed and configured correctly.

So, the thing I'm stuck on now is when I do that same "chef-client -o" command via schtasks, what should I use as the "/RU" and "/RP" for the schtasks command?

Thanks,
Jim

EDIT 2:  Sorry, I forgot to include the schtasks line in the first cookbook/recipe, which sets up the task for the second cookbook/recipe chef run:

schtasks /create /tn Task_Name /tr "chef-client -o install-SHAREPOINT2007FULL-PART2" /sc once /RU "SYSTEM" /SD 06/27/2015 /ST 12:30

EDIT 3: The original reason that I was looking into this (having Chef work "through" a reboot) was that as part of installing Sharepoint, I had to set a Windows registry key, and I thought that I had to reboot to make that registry change effective for the rest of the install process.

However, I did some testing yesterday, and it appears that is not the case.  I can make the registry change, then do the rest of the installation, without having to reboot in between.

So, bottom line is that I didn't need to process after the reboot after all.

But anyway, hopefully some of the info here may help someone later.  The main thing I found was was I couldn't get it to work using ONSTART with the /Z /V1...  I had to use the ONCE and would have had to have code in my Chef recipe to figure out the date and time to fire the ONCE tasks.

Body:
I have done it using FLAG file method, example given below.
Example of domain join-

---------------------------Script Start------------------------

    powershell_script 'Domain_Join' do
    guard_interpreter :powershell_script
    code -domainJoin
    $currentTime = Get-Date
    $currentTimeString = $currentTime.ToString()

  $systemDomain = (Get-WmiObject Win32_ComputerSystem).Domain
  If (($systemDomain) -eq 'domainName')
  {
    Try {
  write-host "$env:computerName is DOMAIN MEMBER"
  Remove-Item C:\\DomainJoinFlag.txt -ErrorAction Stop
  Unregister-ScheduledTask -TaskName "Chef client schedule_DJ" -Confirm:$false
  } # end of Try
          Catch [System.Management.Automation.ItemNotFoundException]
            { write-host "Server is already domain member, Or Exception raised due to either missing FLAG file or Server startup schedule task configuration."
              eventcreate /t INFORMATION /ID 0909 /L APPLICATION /SO "ChefClient_$env:computerName" /D "Server is already domain member, Or Exception raised due to either missing FLAG file or Server startup schedule task configuration. Refer to the CHEF reciepie for DomainJoin or check Administrative credentials for creting schedule task"}
            }
    else { write-host "$env:computerName is NOT domain member, joining the server to the domain. Server will be rebooting in a while..."
            eventcreate /t INFORMATION /ID 0909 /L APPLICATION /SO "ChefClient_$env:computerName" /D "Joining the server : $env:ComputerName to the domain ININLAB.COM (Server Time): $currentTimeString"
            New-Item C:\\DomainJoinFlag.txt -type file -force
            write-host "$env:computerName DOMAIN JOIN INITIATED for the server"
            $cred = New-Object System.Management.Automation.PsCredential("domain\\domain_user", (ConvertTo-SecureString "Password" -AsPlainText -Force))
            Add-Computer -DomainName "domainName" -Credential $cred -OUPath "OU=HyperV,OU=Infrastructure,OU=Servers,DC=domain,DC=name"
            shutdown -r -t 120
            } #end_of_else
            domainJoin
  notifies :run, 'windows_task[Chef client schedule_DJ]', :immediately
end

windows_task 'Chef client schedule_DJ' do
  user 'SYSTEM'
  command 'chef-client -L C:\chef\chef-client_after_reboot_domainJoin.log'
  run_level :highest
  frequency :onstart
  frequency_modifier 30
  action :create
  only_if { ::File.exist?('C:\\DomainJoinFlag.txt') }
end

---------------------------Script Ends------------------------


问:
Filter out data from Spark dataframe by priority rules using Spark
I have a dataframe df, some sample records are mentioned below:

**customers**   **product**   **val_id**
     1               A            1
     2               C            r
     3               B            X
     4               D            X
     5               E            1
     6               F            9
```

<p>I have some n number of rules that I have to apply on this data, Some sample rules are:</p>

<p><strong>Name:Rule 1, ID:1</strong></p>

<pre class="lang-none prettyprint-override"><code>filter out customers who have product A and B, rule priority is 1
</code>```

Name:Rule 2, ID:2

filter out customers who have product A, B,C and F, rule priority is 3
```

<p><strong>Name:Rule 3, ID:3</strong></p>

<pre class="lang-none prettyprint-override"><code>filter out customers who have product C and E, rule priority is 2
</code>```

Requirement is that create a new dataframe and filter out those customers which are passed from these rules and also mention from which rule they passed, customers who passed from priority 1 rule, should not be processed by lower priority rules and customers who passed from priority 2 rule, should not be processed by low priority rules and so on.

So my final dataframe should be:

**customers**   **product**   **val_id**   **rule_name**   **rule_id**
     1               A            1              Rule1           1
     2               C            r              Rule3           3
     3               B            X              Rule1           1
     5               E            1              Rule3           3
     6               F            9              Rule2           2
```

Can some one help me out to resolve this problem, using Spark Scala. Any help will be appreciated.

答:
Try Out something like this:

```<code>val rule_name = when(col("product").isin("A","B"), "ABC").otherwise(when(col("product").isin("A","B","D"), "DEF").otherwise(""))
val rule_id = when(col("product").isin("A","B"), "123").otherwise(when(col("product").isin("A","B","D"), "456").otherwise(""))
val df1 = df_customers.withColumn("rule_name" , rule_name).withColumn("rule_id" , rule_id)
df1.show()
</code>```

This is an example and might not be an exact solution, but you will be able to tackle your problem.

Body:
I have a dataframe df, some sample records are mentioned below:

**customers**   **product**   **val_id**
     1               A            1
     2               C            r
     3               B            X
     4               D            X
     5               E            1
     6               F            9

I have some n number of rules that I have to apply on this data, Some sample rules are:

Name:Rule 1, ID:1

filter out customers who have product A and B, rule priority is 1

Name:Rule 2, ID:2

filter out customers who have product A, B,C and F, rule priority is 3

Name:Rule 3, ID:3

filter out customers who have product C and E, rule priority is 2

Requirement is that create a new dataframe and filter out those customers which are passed from these rules and also mention from which rule they passed, customers who passed from priority 1 rule, should not be processed by lower priority rules and customers who passed from priority 2 rule, should not be processed by low priority rules and so on.

So my final dataframe should be:

**customers**   **product**   **val_id**   **rule_name**   **rule_id**
     1               A            1              Rule1           1
     2               C            r              Rule3           3
     3               B            X              Rule1           1
     5               E            1              Rule3           3
     6               F            9              Rule2           2

Can some one help me out to resolve this problem, using Spark Scala. Any help will be appreciated.

Body:
Try Out something like this:

val rule_name = when(col("product").isin("A","B"), "ABC").otherwise(when(col("product").isin("A","B","D"), "DEF").otherwise(""))
val rule_id = when(col("product").isin("A","B"), "123").otherwise(when(col("product").isin("A","B","D"), "456").otherwise(""))
val df1 = df_customers.withColumn("rule_name" , rule_name).withColumn("rule_id" , rule_id)
df1.show()

This is an example and might not be an exact solution, but you will be able to tackle your problem.


问:
Is the Rails 2 ActionController::Base.session[:secret] redundant with Rails 3 Main::Application.config.secret_token?
Is the Rails 2 ActionController::Base.session[:secret] redundant with Rails 3 Main::Application.config.secret_token?

I'm using activerecord sessions -- I still need the secret for my session cookie, right?

Is the same secret used for form submission validations?

答:
You should not set the secret directly on ActionController::Base.session anymore. Use ApplicationName.config.secret_token.

If you intend to use Rails' unobtrusive Javascript functionality, read up on the new csrf_meta_tag view helper: http://apidock.com/rails/ActionView/Helpers/CsrfHelper/csrf_meta_tag


问:
How to capitalize words with brackets in sentence
I am using the following code to capitalize each word in a sentence, but I am unable to capitalize words with brackets attached.

PHP Code:

```<code>  <?php
     $str = "[this is the {command line (interface ";
     $output  = ucwords(strtolower($str));
     echo $output;
</code>```

Output:

[this Is The {command Line (interface

But my expected output should be:

[This Is The {Command Line (Interface

How can I handle words with brackets?
There may be multiple brackets.

For example:

[{this is the ({command line ({(interface

I want to find a general solution/function in PHP.

答:
```<code>$output = ucwords($str, ' [{(');
echo $output;
// output ->
// [This Is The {Command Line (Interface
</code>```

Update: general solution. Here a "bracket" - is any non-letter character. Any letter, following the "bracket" is converted to uppercase.

```<code>$string = "test is the {COMMAND line -STRET (interface 5more 9words #here";
$strlowercase = strtolower($string);

$result = preg_replace_callback('~(^|[^a-zA-Z])([a-z])~', function($matches)
{
    return $matches[1] . ucfirst($matches[2]);
}, $strlowercase);

var_dump($result);
// string(62) "Test Is The {Command Line -Stret (Interface 5More 9Words #Here"
</code>```

Live demo

Body:
I am using the following code to capitalize each word in a sentence, but I am unable to capitalize words with brackets attached.

PHP Code:

  <?php
     $str = "[this is the {command line (interface ";
     $output  = ucwords(strtolower($str));
     echo $output;

Output:

[this Is The {command Line (interface

But my expected output should be:

[This Is The {Command Line (Interface

How can I handle words with brackets?
There may be multiple brackets.

For example:

[{this is the ({command line ({(interface

I want to find a general solution/function in PHP.

Body:
$output = ucwords($str, ' [{(');
echo $output;
// output ->
// [This Is The {Command Line (Interface

Update: general solution. Here a "bracket" - is any non-letter character. Any letter, following the "bracket" is converted to uppercase.

$string = "test is the {COMMAND line -STRET (interface 5more 9words #here";
$strlowercase = strtolower($string);

$result = preg_replace_callback('~(^|[^a-zA-Z])([a-z])~', function($matches)
{
    return $matches[1] . ucfirst($matches[2]);
}, $strlowercase);

var_dump($result);
// string(62) "Test Is The {Command Line -Stret (Interface 5More 9Words #Here"

Live demo


问:
Update shrinkwrap.json after dependency is moved to devDependencies
By mistake i did npm i --save xxx and my shrinkwrap.json was (correctly) written.

As i wanted actually to did --saveDev i started to explore solutions

Now my first idea was to do npm uninstall --save xxx but to my surprise library was removed from package.json but shrinkwrap.json was not written

Is there a way to revert this ?

thx

答:
Apparently this is a problem with certain versions of npm - so you should try updating your local npm install.

If updating npm is not satisfactory, you could create a postuninstall script to automatically re-shrinkwrap every time a package is uninstalled:

```<code>"scripts": {
    "postuninstall": "npm shrinkwrap"
}
</code>```

Body:
Apparently this is a problem with certain versions of npm - so you should try updating your local npm install.

If updating npm is not satisfactory, you could create a postuninstall script to automatically re-shrinkwrap every time a package is uninstalled:

"scripts": {
    "postuninstall": "npm shrinkwrap"
}


问:
SpriteKit SKAction.animateWithTextures: Resize and Restore
Very easy question but would prefer to have someone tell me if I got it correct.
What are the restore and resize parameters for SKAction.animateWithTextures?

If I have an image that's 500x500, and my animation is 400x400, then resize:true will replace my 500x500 with the 400x400 animation? And restore:true would bring it back to the 500x500 after it's done playing the animation, whereas if that restore was was false it keep make my original 500x500 sprite stay at the smaller 400x400 size?

Thanks I just want to confirm this is the case!

答:
from apple documentation: https://developer.apple.com/documentation/spritekit/skaction/1417656-animate

@param resize If YES, the sprite is resized to match each new texture.
     If NO, the size of the sprite remains at a constant size.
     @param restore If YES, When the action completes, the sprite’s texture is restored
     to the texture it had before the action completed. (If the
     resize parameter is YES, the sprite is resized to match the
     size of the original texture.
     If NO, when the action completes the sprite’s texture remains
     set to the final texture in the array.


问:
Filter array of Any based on variable
I have an array of type Any in that array there are two different types, Person and SportsMan both these has a value called rank. I want to sort my array based on the rank. Here is how I have done it today and it works:

```<code>self.persons.sort {
    let a = ($0 as AnyObject) as? Person
    let b = ($0 as AnyObject) as? SportsMan
    let l = a?.rank ?? b?.rank

    let c = ($1 as AnyObject) as? Person
    let d = ($1 as AnyObject) as? SportsMan
    let r = c?.rank ?? d?.rank
    return l! < r!
}
</code>```

I´m feeling a bit unsure because of the ! in l! < r!. Is this a good way to solve this or is it any built in function to use for this?

答:
Make a protocol such as Rankable, and make Person and SportsMan conform to it.

```<code>protocol Rankable {
    var rank: Int { get }
}
</code>```

Then make your array into an [Rankable] (a.k.a. Array<Rankable>) rather than [Any], and sort it like so:

```<code>self.persons.sort{ $0.rank < $1.rank }
</code>```

Title: Filter array of Any based on variable

Body:
I have an array of type Any in that array there are two different types, Person and SportsMan both these has a value called rank. I want to sort my array based on the rank. Here is how I have done it today and it works:

self.persons.sort {
    let a = ($0 as AnyObject) as? Person
    let b = ($0 as AnyObject) as? SportsMan
    let l = a?.rank ?? b?.rank

    let c = ($1 as AnyObject) as? Person
    let d = ($1 as AnyObject) as? SportsMan
    let r = c?.rank ?? d?.rank
    return l! < r!
}

I´m feeling a bit unsure because of the ! in l! < r!. Is this a good way to solve this or is it any built in function to use for this?

Body:
Make a protocol such as Rankable, and make Person and SportsMan conform to it.

protocol Rankable {
    var rank: Int { get }
}

Then make your array into an [Rankable] (a.k.a. Array<Rankable>) rather than [Any], and sort it like so:

self.persons.sort{ $0.rank < $1.rank }


问:
How can I set the background of a GTKListStore/GTKComboBox in GTK2?
I'm using this code to create a combo box with colored background/text:

```<code>GtkListStore *liststore;
GtkWidget *combo;
GtkCellRenderer *column;
liststore = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
for(int i=0; i<10; i++) {
    gtk_list_store_insert_with_values(liststore, NULL, -1, 0, "Default", 1, "white", 2, "black", -1);
}
combo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(liststore));
g_object_unref(liststore);
column = gtk_cell_renderer_text_new();
gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combo), column, TRUE);
gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo), column, "text", 0, "foreground", 1, "background", 2, NULL);
</code>```

and it works. It looks like this:

My question is, how can I set the background of the liststore or the combo box so that there is no whitespace as seen in the picture?
Thanks!

答:
I'm using Numix theme, so the "border" is red. You can use css to override theme styles:

```<code>GtkCssProvider *provider;

provider = gtk_css_provider_new ();
gtk_css_provider_load_from_data (provider, "menuitem { background: #000; } menuitem:hover { background: #FFF; } .combo { background: #000; }", -1, NULL);
gtk_style_context_add_provider (
  GTK_STYLE_CONTEXT (gtk_widget_get_style_context (GTK_WIDGET (combo))),
  GTK_STYLE_PROVIDER (provider),
  GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

gtk_style_context_add_provider_for_screen (gtk_widget_get_screen (combo),
                                           GTK_STYLE_PROVIDER (provider),
                                           GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
g_object_unref (provider);
</code>```

Here's result:

And here is the full source code:
https://pastebin.com/wDeUpb8A

Also take a look at GtkInspector, it's a handy tool for such purposes.

Body:
I'm using this code to create a combo box with colored background/text:

GtkListStore *liststore;
GtkWidget *combo;
GtkCellRenderer *column;
liststore = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
for(int i=0; i<10; i++) {
    gtk_list_store_insert_with_values(liststore, NULL, -1, 0, "Default", 1, "white", 2, "black", -1);
}
combo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(liststore));
g_object_unref(liststore);
column = gtk_cell_renderer_text_new();
gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combo), column, TRUE);
gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo), column, "text", 0, "foreground", 1, "background", 2, NULL);

and it works. It looks like this:

My question is, how can I set the background of the liststore or the combo box so that there is no whitespace as seen in the picture?
Thanks!

Body:
I'm using Numix theme, so the "border" is red. You can use css to override theme styles:

GtkCssProvider *provider;

provider = gtk_css_provider_new ();
gtk_css_provider_load_from_data (provider, "menuitem { background: #000; } menuitem:hover { background: #FFF; } .combo { background: #000; }", -1, NULL);
gtk_style_context_add_provider (
  GTK_STYLE_CONTEXT (gtk_widget_get_style_context (GTK_WIDGET (combo))),
  GTK_STYLE_PROVIDER (provider),
  GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

gtk_style_context_add_provider_for_screen (gtk_widget_get_screen (combo),
                                           GTK_STYLE_PROVIDER (provider),
                                           GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
g_object_unref (provider);

Here's result:

And here is the full source code:
https://pastebin.com/wDeUpb8A

Also take a look at GtkInspector, it's a handy tool for such purposes.


问:
Display Timer on Screen in Assembly MASM 8086
I have to display the time passing on the screen, i've been looking online and found how to set up a time delay but i don't know how to display it on the screen
Here's what i got right now(I dont even know if this is the way to do it)</p>

```<code> delay proc

    mov ah, 00
    int 1Ah
    mov bx, dx
 jmp_delay:
    int 1Ah
    sub dx, bx
    cmp dl, delaytime
    jl jmp_delay
    ret
 delay endp
</code>```

答:
There could use several methods for this:

Use the DOS int 21h to display text (maybe function 9?).

Use the BIOS int 10h to display characters.

Or finally write directly to the screen at B800:0000

Personally I'd use the BIOS method.

Body:
I have to display the time passing on the screen, i've been looking online and found how to set up a time delay but i don't know how to display it on the screen
Here's what i got right now(I dont even know if this is the way to do it)

 delay proc

    mov ah, 00
    int 1Ah
    mov bx, dx
 jmp_delay:
    int 1Ah
    sub dx, bx
    cmp dl, delaytime
    jl jmp_delay
    ret
 delay endp


问:
Importing word vectors from tensorflow into gensim
I want to import word vecters created from tensorflow and utilize it at gensim.

there is a method gensim.models.KeyedVectors.load_word2vec_format

so I tried this method by following exactly the same way in Training wordvec in Tensorflow, importing to Gensim

Example:

2 3

word0 -0.000737 -0.002106 0.001851

word1 -0.000878 -0.002106 0.002834

Save the file and then load with kwarg binary=False:

```<code>model = Word2Vec.load_word2vec_format(filename, binary=False)
</code>```

but error like

```<code>Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    model=gensim.models.KeyedVectors.load_word2vec_format('test.w2v')
  File "C:\Users\cbj\Anaconda3\lib\site-packages\gensim\models\keyedvectors.py", line 243, in load_word2vec_format
    raise EOFError("unexpected end of input; is count incorrect or file otherwise damaged?")
EOFError: unexpected end of input; is count incorrect or file otherwise damaged?
</code>```

raised

how can I solve this problem?

答:
This error is raised when the number of vector data doesn't match the number you provided at the first line.

If the first line wrote 2 3, you should have exactly 2 lines below. Make sure that there's no empty line at the end of your file and of course some where in your file.

Body:
I want to import word vecters created from tensorflow and utilize it at gensim.

there is a method gensim.models.KeyedVectors.load_word2vec_format

so I tried this method by following exactly the same way in Training wordvec in Tensorflow, importing to Gensim

Example:

2 3

word0 -0.000737 -0.002106 0.001851

word1 -0.000878 -0.002106 0.002834

Save the file and then load with kwarg binary=False:

model = Word2Vec.load_word2vec_format(filename, binary=False)

but error like

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    model=gensim.models.KeyedVectors.load_word2vec_format('test.w2v')
  File "C:\Users\cbj\Anaconda3\lib\site-packages\gensim\models\keyedvectors.py", line 243, in load_word2vec_format
    raise EOFError("unexpected end of input; is count incorrect or file otherwise damaged?")
EOFError: unexpected end of input; is count incorrect or file otherwise damaged?

raised

how can I solve this problem?


问:
How can I add index number in the front of output when using grep?
I am studying a simulated chemical reaction and hope to track atom motion. This motion was written in a big file with different timestep. I want to get the atom ID(unique in each timestep) in each time step. However, the output of

```<code>`grep -ni " 6557 " filename`
</code>```

has different line number which is hard to associate with timestep.

1117:      O       6557    0.000000    0.000000

5189:      O       6557    0.000000    0.000000

21491:      Fe      6557    0.000000   0.000000

How can I add index number (NOT line number) in the front of output when using grep command? like below:

1     O       6557    0.000000    0.000000

2     O       6557    0.000000    0.000000

3    Fe      6557    0.000000    0.000000

Many thanks.

答:
GNU cat can do this:

```<code>grep " 6557 " filename | cat -n
</code>```

Alternatively you can do it manually with perl:

```<code>perl -ne 'print ++$c, " ", $_ if / 6557 /' filename
</code>```

Body:
I am studying a simulated chemical reaction and hope to track atom motion. This motion was written in a big file with different timestep. I want to get the atom ID(unique in each timestep) in each time step. However, the output of

`grep -ni " 6557 " filename`

has different line number which is hard to associate with timestep.

1117:      O       6557    0.000000    0.000000

5189:      O       6557    0.000000    0.000000

21491:      Fe      6557    0.000000   0.000000

How can I add index number (NOT line number) in the front of output when using grep command? like below:

1     O       6557    0.000000    0.000000

2     O       6557    0.000000    0.000000

3    Fe      6557    0.000000    0.000000

Many thanks.

Body:
GNU cat can do this:

grep " 6557 " filename | cat -n

Alternatively you can do it manually with perl:

perl -ne 'print ++$c, " ", $_ if / 6557 /' filename


问:
Preventing refresh upon AJAX request
I have a form in my code, and I would simply like to display the fields from that form on my webpage, using AJAX. I tried e.preventDefault() and return false but none of these seem to be working.

I trigger the submit through a button click event.

My Jquery code:

```<code>$("body").on('click', '#save', function (e) {//button which triggers submit
    $('form').submit();
    e.preventDefault();
});

$('#form').on('submit', function(e){
    e.preventDefault();
    e.stopPropagation();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: '/results',
        data: $('#form').serializeArray(),
        success: function (data) {
            //if no error from backend validation is thrown
            return false;
            $('#tabShow').html(data);
        },
        error: function () {
            alert('error');
        }
    });
</code>```

My form html is : <form class="form-horizontal" method="POST" action="/results" id="form">

In my web.php:

```<code>Route::post('/results', function() {
$m=Request::all();
var_dump($m);
});
</code>```

The problem with this code is that it refreshes the current page that I am on.
I have a save button, which should submit the form. I can't use a type submit because of my other functions.

Thank you for the help.

答:
Do the request in the Save button click event, eg.

HTML

```<code><form id="contact-form" class="form-horizontal" action="/echo/html/" method="post">
    <!-- many fields -->
    <button id="save" class="btn btn-primary btn-lg">Submit</button>
</form>
</code>```

JS

```<code>$("body").on('click', '#save', function (e) {//button which triggers
    var contactForm = $('#contact-form');

    e.preventDefault();
    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
        }
    });

    // Send a POST AJAX request to the URL of form's action
    $.ajax({
      type: "POST",
      url: contactForm.attr('action'),
      data: contactForm.serialize()
    })
    .done(function(response) {
      console.log(response);
    })
    .fail(function(response) {
      console.log(response);
    });
});
</code>```

Working demo

Title: Preventing refresh upon AJAX request

Body:
I have a form in my code, and I would simply like to display the fields from that form on my webpage, using AJAX. I tried e.preventDefault() and return false but none of these seem to be working.

I trigger the submit through a button click event.

My Jquery code:

$("body").on('click', '#save', function (e) {//button which triggers submit
    $('form').submit();
    e.preventDefault();
});

$('#form').on('submit', function(e){
    e.preventDefault();
    e.stopPropagation();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: '/results',
        data: $('#form').serializeArray(),
        success: function (data) {
            //if no error from backend validation is thrown
            return false;
            $('#tabShow').html(data);
        },
        error: function () {
            alert('error');
        }
    });

My form html is : <form class="form-horizontal" method="POST" action="/results" id="form">

In my web.php:

Route::post('/results', function() {
$m=Request::all();
var_dump($m);
});

The problem with this code is that it refreshes the current page that I am on.
I have a save button, which should submit the form. I can't use a type submit because of my other functions.

Thank you for the help.

Body:
Do the request in the Save button click event, eg.

HTML

<form id="contact-form" class="form-horizontal" action="/echo/html/" method="post">
    <!-- many fields -->
    <button id="save" class="btn btn-primary btn-lg">Submit</button>
</form>

JS

$("body").on('click', '#save', function (e) {//button which triggers
    var contactForm = $('#contact-form');

    e.preventDefault();
    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
        }
    });

    // Send a POST AJAX request to the URL of form's action
    $.ajax({
      type: "POST",
      url: contactForm.attr('action'),
      data: contactForm.serialize()
    })
    .done(function(response) {
      console.log(response);
    })
    .fail(function(response) {
      console.log(response);
    });
});

Working demo


问:
Transform SQL Table
We have a table that has the following format

```<code>RecordID FieldName FieldValue

1         Name      John
1         Age       30
2         Name      Alice
2         Age       40
</code>```

We would like to present this as:

```<code>John   30
Alice  40
</code>```

Anyone have a good solution for this?

答:
```<code>SELECT
  TN.FieldValue AS ValueName
, TV.FieldValue AS ValueAge
FROM dbo.Table1 TN
INNER JOIN dbo.Table1 TV ON TN.RecordID = TV.RecordID
  AND TN.FieldName = 'Name'
  AND TV.FieldName = 'Age'
</code>```

Title: Transform SQL Table

Body:
We have a table that has the following format

RecordID FieldName FieldValue

1         Name      John
1         Age       30
2         Name      Alice
2         Age       40

We would like to present this as:

John   30
Alice  40

Anyone have a good solution for this?