问:
Conditionally display Woocommerce checkout field
On a Wordpress website,I am currently trying to setup a Woocommerce and Learnpress plugins. I Use Woocommerce Checkout Add-ons commercial plugin which allows to create some additional checkout fields.

I would like to display conditionally some checkout fields only when certain Learnpress courses are present in the checkout cart.

The code present in the checkout plugin is as follows:

```<code><?php if ( $add_on_fields ) : ?>

<div id="wc_checkout_add_ons">
<?php
    foreach ( $add_on_fields as $key => $field ) :
        woocommerce_form_field( $key, $field, WC()->checkout()->get_value(
        $key ) );
    endforeach;
?>
</div>

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

So started going this route:

```<code><div id="wc_checkout_add_ons">
<?php
    $course_category = get_the_terms( $post->ID, 'course_category' );
    echo $course_category;
    if ($course_category == 'weekend-intensives') {
        foreach ( $add_on_fields as $key => $field ) :
            woocommerce_form_field( $key, $field, WC()->checkout()->get_value( $key ) );
        endforeach;
    } else {
        echo ('Proceed with checkout');
    }
?>
</div>
</code>```

Right now I don't even get that initial echo for $course_category so I know that I am already wrong there...

I need to figure out what the code would be for getting the learnpress course category of the course in the checkout/cart.

I know there is a lot more to it than this and I am likely way off, but I am willing to work through it with some assistance.

Any help would be greatly appreciated.

答:
You can use has_term() specific WordPress conditional function for custom taxonomies and custom taxonomies as "Product categories" or for your case "Course categories" that you can use easily.

1) You need to check cart items, to see if there is a cart item that remains to 'weekend-intensives' Course category and this has to be done at the beginning of the code. This way you can alter the existing condition if ( $add_on_fields ) :…

2) You need to be sure that the Course categories taxonomy are applicable to WooCommerce product custom post type. If not you will not be able to check for any Course categories cart items.

So the correct way to do it is:

```<code><?php
    ## ---- Custom code start here ---- ##
    $is_in_cart = false;

    // Checking cart items for specific "Course category"
    foreach( WC->cart->get_cart() as $cart_item ){
        // Here your Course category
        if( has_term( 'weekend-intensives', 'course_category', $cart_item['product_id'] ){
            $is_in_cart = true; // Found
            break; // Stop the loop
        }
    }
    // adding our condition in existing code if statement
    if ( $add_on_fields && $is_in_cart ) :

    ## ---- Custom code Ends here ---- ##

    // if ( $add_on_fields ) :
?>

<div id="wc_checkout_add_ons">
<?php
    foreach ( $add_on_fields as $key => $field ) :
        woocommerce_form_field( $key, $field, WC()->checkout()->get_value( $key ) );
    endforeach;
?>
</div>

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

This is untested, but it should work (if Course categories are applicable to WC products)

UPDATE

Check if a product ID works with "weekend-intensives" course category:

Code goes in function.php file of your active child theme (or theme).

Set inside it the correct product ID to check and save.

Go in archives pages or product pages to see the result (once saved).

The code:

```<code>// Checking for "weekend-intensives" course category in shop and product pages
add_action( 'woocommerce_before_main_content', function(){
    // Only for admin user role
    if( ! current_user_can('edit_products')) return;

    // ==> BELOW set your product ID to check
    $product_id = 43;

    // Output the raw cart object data
    if( has_term( 'weekend-intensives', 'course_category', $product_id ){
        echo '```YES! This product works with "weekend-intensives" course category```';
    } else {
        echo '```This product DOES NOT WORK with "weekend-intensives" course category```';
    }
}, 987 );
</code>```

Body:
On a Wordpress website,I am currently trying to setup a Woocommerce and Learnpress plugins. I Use Woocommerce Checkout Add-ons commercial plugin which allows to create some additional checkout fields.

I would like to display conditionally some checkout fields only when certain Learnpress courses are present in the checkout cart.

The code present in the checkout plugin is as follows:

<?php if ( $add_on_fields ) : ?>

<?php
    foreach ( $add_on_fields as $key => $field ) :
        woocommerce_form_field( $key, $field, WC()->checkout()->get_value(
        $key ) );
    endforeach;
?>

<?php endif; ?>

So started going this route:

<?php
    $course_category = get_the_terms( $post->ID, 'course_category' );
    echo $course_category;
    if ($course_category == 'weekend-intensives') {
        foreach ( $add_on_fields as $key => $field ) :
            woocommerce_form_field( $key, $field, WC()->checkout()->get_value( $key ) );
        endforeach;
    } else {
        echo ('Proceed with checkout');
    }
?>

Right now I don't even get that initial echo for $course_category so I know that I am already wrong there...

I need to figure out what the code would be for getting the learnpress course category of the course in the checkout/cart.

I know there is a lot more to it than this and I am likely way off, but I am willing to work through it with some assistance.

Any help would be greatly appreciated.

Body:
You can use has_term() specific WordPress conditional function for custom taxonomies and custom taxonomies as "Product categories" or for your case "Course categories" that you can use easily.

1) You need to check cart items, to see if there is a cart item that remains to 'weekend-intensives' Course category and this has to be done at the beginning of the code. This way you can alter the existing condition if ( $add_on_fields ) :…

2) You need to be sure that the Course categories taxonomy are applicable to WooCommerce product custom post type. If not you will not be able to check for any Course categories cart items.

So the correct way to do it is:

<?php
    ## ---- Custom code start here ---- ##
    $is_in_cart = false;

    // Checking cart items for specific "Course category"
    foreach( WC->cart->get_cart() as $cart_item ){
        // Here your Course category
        if( has_term( 'weekend-intensives', 'course_category', $cart_item['product_id'] ){
            $is_in_cart = true; // Found
            break; // Stop the loop
        }
    }
    // adding our condition in existing code if statement
    if ( $add_on_fields && $is_in_cart ) :

    ## ---- Custom code Ends here ---- ##

    // if ( $add_on_fields ) :
?>

<div id="wc_checkout_add_ons">
<?php
    foreach ( $add_on_fields as $key => $field ) :
        woocommerce_form_field( $key, $field, WC()->checkout()->get_value( $key ) );
    endforeach;
?>
</div>

<?php endif; ?>

This is untested, but it should work (if Course categories are applicable to WC products)

UPDATE

Check if a product ID works with "weekend-intensives" course category:

Code goes in function.php file of your active child theme (or theme).

Set inside it the correct product ID to check and save.

Go in archives pages or product pages to see the result (once saved).

The code:

// Checking for "weekend-intensives" course category in shop and product pages
add_action( 'woocommerce_before_main_content', function(){
    // Only for admin user role
    if( ! current_user_can('edit_products')) return;

    // ==> BELOW set your product ID to check
    $product_id = 43;

    // Output the raw cart object data
    if( has_term( 'weekend-intensives', 'course_category', $product_id ){
        echo '<pre>YES! This product works with "weekend-intensives" course category</pre>';
    } else {
        echo '<pre>This product DOES NOT WORK with "weekend-intensives" course category</pre>';
    }
}, 987 );


来源: stackexchange

问:
Creating a program to store all the tweets off a page to be stored in a text file for analysis, however getting TypeErrors
I have started off by including Tweepy and managed to get a program that is able to output a correct output with a search parameter, however, while trying to create a program that can save and store a person timeline for data analysis I came across a TypeError: must be str, not ResultSet.

```<code>import tweepy

#API keys access
auth = tweepy.OAuthHandler("", "")
auth.set_access_token("", "")
client = tweepy.API(auth)

#Opening a file with the name of the user wanted
screen = input("Enter the screen name: ")
filename = (screen+".txt")
file = open(filename, "w")

#Getting the Users time line
user = client.get_user(screen_name=screen)
timeline = user.timeline()

#Writing new found data to the file.
file.write(timeline)
file.close()
</code>```

This code keeps on spitting out the error:

```<code>Traceback (most recent call last):
  File "GetTimeLine.py", line 20, in <module>
    file.write(timeline)
TypeError: must be str, not ResultSet
</code>```

However for the set line:

```<code>file.write(timeline)
</code>```

I add where I want it to become str through the user of

```<code>file.write(str(timeline))
</code>```

Throwing out an entirely different error.

```<code>Traceback (most recent call last):
  File "GetTimeLine.py", line 20, in <module>
    file.write(str(timeline))
  File "C:\Program Files (x86)\Python\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 4122-4123: character maps to <undefined>
</code>```

To try and fix this I tried to add .(encode"utf-8") however with no luck.
Any help greatly appreciated.

答:
Try this, I searched for how to convert ResultSet to string and found this

```<code>unicode.join(u'\n',map(unicode,result))
</code>```

Here "result" is your "timeline" variable, just put it and you will get it in string format. Doing simply str(timeline) will not encode it , that's why you are getting another error.

Just try it:) Cheers

ContentLicense: CC BY-SA 3.0

Body:
I have started off by including Tweepy and managed to get a program that is able to output a correct output with a search parameter, however, while trying to create a program that can save and store a person timeline for data analysis I came across a TypeError: must be str, not ResultSet.

import tweepy

#API keys access
auth = tweepy.OAuthHandler("", "")
auth.set_access_token("", "")
client = tweepy.API(auth)

#Opening a file with the name of the user wanted
screen = input("Enter the screen name: ")
filename = (screen+".txt")
file = open(filename, "w")

#Getting the Users time line
user = client.get_user(screen_name=screen)
timeline = user.timeline()

#Writing new found data to the file.
file.write(timeline)
file.close()

This code keeps on spitting out the error:

Traceback (most recent call last):
  File "GetTimeLine.py", line 20, in <module>
    file.write(timeline)
TypeError: must be str, not ResultSet

However for the set line:

file.write(timeline)

I add where I want it to become str through the user of

file.write(str(timeline))

Throwing out an entirely different error.

Traceback (most recent call last):
  File "GetTimeLine.py", line 20, in <module>
    file.write(str(timeline))
  File "C:\Program Files (x86)\Python\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 4122-4123: character maps to <undefined>

To try and fix this I tried to add .(encode"utf-8") however with no luck.
Any help greatly appreciated.

Body:
Try this, I searched for how to convert ResultSet to string and found this

unicode.join(u'\n',map(unicode,result))

Here "result" is your "timeline" variable, just put it and you will get it in string format. Doing simply str(timeline) will not encode it , that's why you are getting another error.

Just try it:) Cheers


问:
Google reCaptcha validation (siteverify) returns false
I've tried to implement a simple code to use reCAPTCHA on my site afterwards, but even this simple code doesn't work.

The problem is that the verify function always returns a bool (false) value.
I've checked the keys several times but they are the correct ones

```<code><head>
 <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
 <?php require_once "recaptchalib.php";  ?>

    <?php
        if(isset($_POST['new_comment']) && !empty($_POST['new_comment'])):
            if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) :

                $secret = "mysecretkey";

                    var_dump ($_POST['g-recaptcha-response']);

                $ip = $_SERVER['REMOTE_ADDR'];
                $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response'].'&remoteip='.$ip);

                    echo ("verifyresponse");
                    var_dump ($verifyResponse);

                $responseData = json_decode($verifyResponse, true);

                    echo ("responseData");
                    var_dump ($ResponseData);

                if ($response != null && $response->success) :

                    echo 'Form info successfully submitted';
                else:
                    $errMsg = 'Robot verification failed, please try again.';
                    echo $errMsg ;
                endif;
            else:
                $errMsg = 'Please click on the reCAPTCHA box.';
                echo $errMsg ;
            endif;
        else:
            $errMsg = '';
            $succMsg = '';
        endif;

        ?>

        <form name="form1" action="thisfile.php" method="post">
                    Enter Comment :<br />
                    <textarea name="new_comment" cols="75" rows="10"></textarea><br />
                    <div class="g-recaptcha" data-sitekey="mysitekey"></div>

                    <input type="submit" value="Envoyer" />
        </form>

</body>
</html>
</code>```

The var_dump ($_POST['g-recaptcha-response']) gives the expected long chain of characters, but the var_dump ($verifyResponse) gives a bool(false) value, and I never see the var_dump ($ResponseData).

Can anyone help me figure out what is wrong with this code?

I've narrowed down the problem to the fact that the file_get_content call returns a "false" value instead of the expected

{
        "success": true,
         "challenge_ts": "2017-12-10T15:09:12Z",
         "hostname": "mydomain"
     }

What is getting me crazy is that if echo the full string and copy it directly in the browser then I get the correct answer (above), so I can't figure out what is going wrong...

Here's the current 'stripped to the bone' version of my code (I've deleted the json_decode call and everything after that since as long as I get a wrong return value I know the rest won't work)

```<code><!doctype html>
<html>
<head>
    <script src="https://www.google.com/recaptcha/api.js" async defer>
</script>
</head>
<body>
    <?php

        define('GOOGLE_RECAPTCHA_KEY','xxx');
        define('GOOGLE_RECAPTCHA_SECRET_KEY','yyy');

        $message = false;

      if ( isset( $_POST['new_comment'], $_POST['g-recaptcha-response'] ) && !empty( $_POST['new_comment'] ) && !empty( $_POST['g-recaptcha-response'] ) ){

      echo 'Sauvegarde du commentaire' ;
            $secret = GOOGLE_RECAPTCHA_SECRET_KEY;
            $ip = $_SERVER['REMOTE_ADDR'];
                            var_dump($_POST['g-recaptcha-response']);

            $getResponse = 'https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response'];
                            var_dump($getResponse);

            $GoogleResponse = file_get_contents($getResponse) ;
                            var_dump($GoogleResponse) ;

      }

    ?>

    <form method='post'>
        Enter Comment :<br />
        <textarea name='new_comment' cols='75' rows='10'></textarea>
        <?php
            if( !empty( $message ) )echo $message;
        ?>
        <br />
        <div class='g-recaptcha' data-sitekey='<?php echo GOOGLE_RECAPTCHA_KEY;?>'></div>
        <input type='submit' value='Envoyer' />
    </form>
</body>
</html>
</code>```

答:
Check you variables:

```<code>if ($responseData!= null && $responseData['success']) {
</code>```

Additional edits for your code:

```<code>$secret = "Add Your Secret Key"; // may be you are adding here public key instead of private ? check it
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true); // if you add "true" then the response will be an array

if($response["success"] === true){
    echo "Form Submit Successfully.";
}else{
    echo "You are a robot";
}
</code>```

Also I advise you to look to these tutorial:

Google Recaptcha Tutorial

And this recaptcha example from Github:

```<code>require('/path/to/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
if ($resp->isSuccess()) {
    // verified!
    // if Domain Name Validation turned off don't forget to check hostname field
    // if($resp->getHostName() === $_SERVER['SERVER_NAME']) {  }
} else {
    $errors = $resp->getErrorCodes();
}
</code>```

Github link

Body:
I've tried to implement a simple code to use reCAPTCHA on my site afterwards, but even this simple code doesn't work.

The problem is that the verify function always returns a bool (false) value.
I've checked the keys several times but they are the correct ones

 <?php require_once "recaptchalib.php";  ?>

    <?php
        if(isset($_POST['new_comment']) && !empty($_POST['new_comment'])):
            if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) :

                $secret = "mysecretkey";

                    var_dump ($_POST['g-recaptcha-response']);

                $ip = $_SERVER['REMOTE_ADDR'];
                $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response'].'&remoteip='.$ip);

                    echo ("verifyresponse");
                    var_dump ($verifyResponse);

                $responseData = json_decode($verifyResponse, true);

                    echo ("responseData");
                    var_dump ($ResponseData);

                if ($response != null && $response->success) :

                    echo 'Form info successfully submitted';
                else:
                    $errMsg = 'Robot verification failed, please try again.';
                    echo $errMsg ;
                endif;
            else:
                $errMsg = 'Please click on the reCAPTCHA box.';
                echo $errMsg ;
            endif;
        else:
            $errMsg = '';
            $succMsg = '';
        endif;

        ?>

        <form name="form1" action="thisfile.php" method="post">
                    Enter Comment :

                    <textarea name="new_comment" cols="75" rows="10"></textarea>

                    <input type="submit" value="Envoyer" />
        </form>

The var_dump ($_POST['g-recaptcha-response']) gives the expected long chain of characters, but the var_dump ($verifyResponse) gives a bool(false) value, and I never see the var_dump ($ResponseData).

Can anyone help me figure out what is wrong with this code?

I've narrowed down the problem to the fact that the file_get_content call returns a "false" value instead of the expected

{
        "success": true,
         "challenge_ts": "2017-12-10T15:09:12Z",
         "hostname": "mydomain"
     }

What is getting me crazy is that if echo the full string and copy it directly in the browser then I get the correct answer (above), so I can't figure out what is going wrong...

Here's the current 'stripped to the bone' version of my code (I've deleted the json_decode call and everything after that since as long as I get a wrong return value I know the rest won't work)

<!doctype html>

    <?php

        define('GOOGLE_RECAPTCHA_KEY','xxx');
        define('GOOGLE_RECAPTCHA_SECRET_KEY','yyy');

        $message = false;

      if ( isset( $_POST['new_comment'], $_POST['g-recaptcha-response'] ) && !empty( $_POST['new_comment'] ) && !empty( $_POST['g-recaptcha-response'] ) ){

      echo 'Sauvegarde du commentaire' ;
            $secret = GOOGLE_RECAPTCHA_SECRET_KEY;
            $ip = $_SERVER['REMOTE_ADDR'];
                            var_dump($_POST['g-recaptcha-response']);

            $getResponse = 'https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response'];
                            var_dump($getResponse);

            $GoogleResponse = file_get_contents($getResponse) ;
                            var_dump($GoogleResponse) ;

      }

    ?>

    <form method='post'>
        Enter Comment :

        <textarea name='new_comment' cols='75' rows='10'></textarea>
        <?php
            if( !empty( $message ) )echo $message;
        ?>

        <div class='g-recaptcha' data-sitekey='<?php echo GOOGLE_RECAPTCHA_KEY;?>'>

        <input type='submit' value='Envoyer' />
    </form>

Body:
Check you variables:

if ($responseData!= null && $responseData['success']) {

Additional edits for your code:

$secret = "Add Your Secret Key"; // may be you are adding here public key instead of private ? check it
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true); // if you add "true" then the response will be an array

if($response["success"] === true){
    echo "Form Submit Successfully.";
}else{
    echo "You are a robot";
}

Also I advise you to look to these tutorial:

Google Recaptcha Tutorial

And this recaptcha example from Github:

require('/path/to/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
if ($resp->isSuccess()) {
    // verified!
    // if Domain Name Validation turned off don't forget to check hostname field
    // if($resp->getHostName() === $_SERVER['SERVER_NAME']) {  }
} else {
    $errors = $resp->getErrorCodes();
}

Github link


问:
Download files from USB-connected smartphone to Windows by script (or Python)
Is there a way to download to Windows (and later erase) files on an USB-connected smartphone? I'd like to create an automatic download and backup of pictures for a family smartphone... </p>

<p>I've seen hints only about Unix, and no indication on how copy files via USB on Windows. Finally, I'd like to use Python, so I looked into the libusb package, but this seemed far away from any files&folders model. I have not even been able to find any "mountpoint" on Windows (which I assumed to exist from the presentation of the smartphones in Windows Explorer). </p>

答:
What version of Windows are you running?

On Windows 10, at least, when my phone is plugged in I can right click on it in File Explorer (This PC), and choose 'Import Pictures and Videos', which then looks through all the folders on your phone for its picture and video files.  You can then import them to your PC, and from there copy them to a location of your choice.

This is probably the easiest way of achieving what you want to do.

Body:
Is there a way to download to Windows (and later erase) files on an USB-connected smartphone? I'd like to create an automatic download and backup of pictures for a family smartphone...

I've seen hints only about Unix, and no indication on how copy files via USB on Windows. Finally, I'd like to use Python, so I looked into the libusb package, but this seemed far away from any files&folders model. I have not even been able to find any "mountpoint" on Windows (which I assumed to exist from the presentation of the smartphones in Windows Explorer).


问:
What is the fastest way to insert text into a
 element with javascript?
I am writing a long series of numbers to my document, one at a time. document.write() handles this fine, but using innerHTML with a
 element is sluggish, and rather quickly crashes my tab.  Is there some way to insert text into a
 element that is as fast as document.write?

答:
Here is one way, based on Vlad idea that should be as fast as possible:

```<code>var arrData = [];
for (var i = 0; i <= 5000; i++)
    arrData.push(i);
var oDiv = document.getElementById("Output");
oDiv.innerHTML = arrData.join(", ");
</code>```

Instead of appending to a string or to the innerHTML which are both slow, append to array then use join to get the string out of the array. The above example will throw 5000 numbers into the output div and it takes 2 milliseconds instead of 2.5 seconds when doing it with oDiv.innerHTML += i + ", ";

Live test case available here: http://jsfiddle.net/yahavbr/mKx35/

ContentLicense: CC BY-SA 2.5

Title: What is the fastest way to insert text into a <div> element with javascript?

Body:
Here is one way, based on Vlad idea that should be as fast as possible:

var arrData = [];
for (var i = 0; i <= 5000; i++)
    arrData.push(i);
var oDiv = document.getElementById("Output");
oDiv.innerHTML = arrData.join(", ");

Instead of appending to a string or to the innerHTML which are both slow, append to array then use join to get the string out of the array. The above example will throw 5000 numbers into the output div and it takes 2 milliseconds instead of 2.5 seconds when doing it with oDiv.innerHTML += i + ", ";

Live test case available here: http://jsfiddle.net/yahavbr/mKx35/


问:
Insert Python Objects when sending email using Outlook
Simple question as the title：How can I insert or copy a Python object(like a matplotlib figure object just generated, not saved into the hard drive) into an email sending from Outlook?

I'm not using SMTP module but operate Outlook via win32com.client. Some of current codes are as follows:

```<code>import matplotlib.pyplot as plt
import win32com.client
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize = (20,30))
gs = gridspec.GridSpec(5,2)

ax = plt.subplot(gs[0,0])
ax.plot(range(10))

obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "Daily Report of Volatility"
newMail.HTMLBody = "<h1> \
                        This is a test \
                    </h1> \
                    <p> \
                        I am a email-robot \
                    </p> \
                    "

newMail.To = "Kyle"

newMail.display()
</code>```

Just want to insert the 'fig' object into the mail body.

Will appreciate any illustration! Thanks a lot!

答: You need to generate an image and then add a reference to the message body. </p>

Body:
Simple question as the title：How can I insert or copy a Python object(like a matplotlib figure object just generated, not saved into the hard drive) into an email sending from Outlook?

I'm not using SMTP module but operate Outlook via win32com.client. Some of current codes are as follows:

import matplotlib.pyplot as plt
import win32com.client
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize = (20,30))
gs = gridspec.GridSpec(5,2)

ax = plt.subplot(gs[0,0])
ax.plot(range(10))

obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "Daily Report of Volatility"
newMail.HTMLBody = "
 \
                        This is a test \

 \

 \
                        I am a email-robot \

 \
                    "

newMail.To = "Kyle"

newMail.display()

Just want to insert the 'fig' object into the mail body.

Will appreciate any illustration! Thanks a lot!


问:
Unsure of how to call my method to be run from main() with a switch statement
Problem: I'm relatively new to Java, and I'm trying to understand how to call a class (or are classes methods?) to the main class to be executed. Also will my System.out message be printed from where it is? I was trying to place it inside the doubleDice class, but was getting errors.

```<code>package dicerolling;
public class DiceRolling {

public static void main(String[] args) {

DoubleDice.doubleRoll();

    }

}
</code>```

What I hope to get: I'm hoping to get an output from the prompt that rolls the dice, and executes through the switch as well from a separate class.

What I'm getting now: Everything runs fine, but I don't know how to work with methods outside of the main.

EDIT:

```<code>public class DoubleDice {

public static void doubleRoll() {

    int maxNum = 6;
    int randomValue = 1 + (int) (Math.random() * maxNum);
    int randomValue2 = 1 + (int) (Math.random() * maxNum);
    int die1 = (randomValue);
    int die2 = (randomValue2);
    int sum = die1 + die2;

    System.out.println(
            "With a roll of the dice: " + die1
            + " + " + die2 + " = " + sum);

    switch (sum) {
        case 2:
            System.out.println("Snake Eyes!");
            break;
        case 7:
            System.out.println("Craps!");
            break;
        case 12:
            System.out.println("Box Cars!");
            break;

    }
  }
}
</code>```

What I'm getting now: I'm trying to call the DoubleDice class from a different file, but before I can do that; My system.out and switch statement are now showing errors.

EDIT: Solved!

Thank you for any help you can provide!

答:
Your main() method does not contain any operators. What it contains is a definition of a local class named doubleDice.

As it contains no operators, nothing happens when main() is run.

You could, for example, move that local class to a top level (that is, create a file named doubleDice.java containing that class definition inside it), and then instantiate it and call its method inside your main():

```<code>new doubleDice().combination();
</code>```

One more thing: according to standard Java naming convention, class names are started with a capital letter, so DoubleDice is preferred to doubleDice as class name.

Body:
Problem: I'm relatively new to Java, and I'm trying to understand how to call a class (or are classes methods?) to the main class to be executed. Also will my System.out message be printed from where it is? I was trying to place it inside the doubleDice class, but was getting errors.

package dicerolling;
public class DiceRolling {

public static void main(String[] args) {

DoubleDice.doubleRoll();

    }

}

What I hope to get: I'm hoping to get an output from the prompt that rolls the dice, and executes through the switch as well from a separate class.

What I'm getting now: Everything runs fine, but I don't know how to work with methods outside of the main.

EDIT:

public class DoubleDice {

public static void doubleRoll() {

    int maxNum = 6;
    int randomValue = 1 + (int) (Math.random() * maxNum);
    int randomValue2 = 1 + (int) (Math.random() * maxNum);
    int die1 = (randomValue);
    int die2 = (randomValue2);
    int sum = die1 + die2;

    System.out.println(
            "With a roll of the dice: " + die1
            + " + " + die2 + " = " + sum);

    switch (sum) {
        case 2:
            System.out.println("Snake Eyes!");
            break;
        case 7:
            System.out.println("Craps!");
            break;
        case 12:
            System.out.println("Box Cars!");
            break;

    }
  }
}

What I'm getting now: I'm trying to call the DoubleDice class from a different file, but before I can do that; My system.out and switch statement are now showing errors.

EDIT: Solved!

Thank you for any help you can provide!

Body:
Your main() method does not contain any operators. What it contains is a definition of a local class named doubleDice.

As it contains no operators, nothing happens when main() is run.

You could, for example, move that local class to a top level (that is, create a file named doubleDice.java containing that class definition inside it), and then instantiate it and call its method inside your main():

new doubleDice().combination();

One more thing: according to standard Java naming convention, class names are started with a capital letter, so DoubleDice is preferred to doubleDice as class name.


问:
GStreamer in OpenCV does not send video data over UDP
I'm trying to use GStreamer on Mac (10.12.6) to stream a video encoded from OpenCV frames via UDP. For some reason this does not work and I'm not getting any error output from GStreamer or OpenCV. This is how I open the writer in OpenCV:

```<code>    cv::VideoWriter writer(
    "appsrc ! videoconvert ! x264enc byte-stream=true threads=4 ! mpegtsmux ! udpsink host=localhost port=9999",
    cv::CAP_GSTREAMER,
    0,
    (double) 5,
    cv::Size(320, 240),
    true);
</code>```

This writer opens and I can feed frames into it but I don't get any output when listening to the port. The same pipeline works when compiled from (c++) source using the GStreamer API or when being launched via

```<code>/gst-launch-1.0 videotestsrc ! x264enc byte-stream=true threads=4 ! mpegtsmux ! udpsink host=localhost port=9999
</code>```

I don't think OpenCV or GStreamer itself is at fault because I am able to stream video to the autovideosink in OpenCV when opening the writer via

```<code>    cv::VideoWriter writer(
    "appsrc ! autovideosink",
    cv::CAP_GSTREAMER,
    0,
    (double) 5,
    cv::Size(320, 240),
    true);
</code>```

For reference - I installed GStreamer via Brew and built OpenCV myself using the following CMake Flags:

```<code>-DOPENCV_ENABLE_NONFREE=ON
-DWITH_OPENGL=ON
-DWITH_OPENVX=ON
-DWITH_OPENCL=ON
-DBUILD_PNG=ON
-DBUILD_TIFF=ON
-DOPENCV_EXTRA_MODULES_PATH=~/src/opencv_contrib/modules
-DWITH_1394=OFF
-DWITH_CUDA=OFF
-DWITH_GSTREAMER=ON.
</code>```

I'm relatively new to GStreamer so I could be missing something obvious. Any idea what I could be doing wrong here or what would help to track down the issue?

答:
Finally got it. Turning on GStreamer Debug Output via setting GST_DEBUG=2 yielded that x264enc was not found by OpenCV. I didn't notice that as it was found when compiling the pipeline via the GStreamer C++ API.

The reason for that was that while the GStreamer install packages on OSX installed the x264enc element, brew on mac didn't. Having compiled OpenCV myself - it used the brew install of GStreamer and not the framework.

Solved the problem by reinstalling the x264enc element for GStreamer via brew (brew install gst-plugins-ugly --with-x264).

Body:
I'm trying to use GStreamer on Mac (10.12.6) to stream a video encoded from OpenCV frames via UDP. For some reason this does not work and I'm not getting any error output from GStreamer or OpenCV. This is how I open the writer in OpenCV:

    cv::VideoWriter writer(
    "appsrc ! videoconvert ! x264enc byte-stream=true threads=4 ! mpegtsmux ! udpsink host=localhost port=9999",
    cv::CAP_GSTREAMER,
    0,
    (double) 5,
    cv::Size(320, 240),
    true);

This writer opens and I can feed frames into it but I don't get any output when listening to the port. The same pipeline works when compiled from (c++) source using the GStreamer API or when being launched via

/gst-launch-1.0 videotestsrc ! x264enc byte-stream=true threads=4 ! mpegtsmux ! udpsink host=localhost port=9999

I don't think OpenCV or GStreamer itself is at fault because I am able to stream video to the autovideosink in OpenCV when opening the writer via

    cv::VideoWriter writer(
    "appsrc ! autovideosink",
    cv::CAP_GSTREAMER,
    0,
    (double) 5,
    cv::Size(320, 240),
    true);

For reference - I installed GStreamer via Brew and built OpenCV myself using the following CMake Flags:

-DOPENCV_ENABLE_NONFREE=ON
-DWITH_OPENGL=ON
-DWITH_OPENVX=ON
-DWITH_OPENCL=ON
-DBUILD_PNG=ON
-DBUILD_TIFF=ON
-DOPENCV_EXTRA_MODULES_PATH=~/src/opencv_contrib/modules
-DWITH_1394=OFF
-DWITH_CUDA=OFF
-DWITH_GSTREAMER=ON.

I'm relatively new to GStreamer so I could be missing something obvious. Any idea what I could be doing wrong here or what would help to track down the issue?


问:
Generic RedBlack Driver
I'm Trying to insert data threw my driver but it is nothing is working I keep getting my inset highlighted red and telling me that it is not the correct data type.The main problem is I don't understand how to set a generic type Node.Thank you for your help.

Driver(I've been trying diffrent things no progrees):

```<code>public class Driver {
    public static <E> void main(String[] args){
          RedBlack<Integer> rb = new RedBlack<Integer>( );
          Node<Integer> item=32;
          rb.insert(item);
       }//close main
}//close driver
</code>```

REDBLACK CODE:

```<code>import java.util.NoSuchElementException;
public class RedBlack<E extends Comparable<? super E>>{
////////////////////////////////SETUP//////////////////////////////////////////
   private final static int Red=0;
   private final static int Black=1;
   private Node<E> nil;
   private Node<E> root;

   public RedBlack() {
      nil=new Node<E>(null);
      nil.left=nil.right=nil;
      root=new Node<E>(null);
      root.left=root.right=nil;
   }

   static class Node<E>{
      Node(E theData){
         this(theData,null,null);
      }

      Node(E theData,Node<E> lt,Node<E> rt){
            data=theData;
            left=lt;
            right=rt;
            color=RedBlack.Black;
      }

      E data;              // The data in the Node
      Node<E> left;        // Left child
      Node<E> right;       // Right child
      Node<E> parent;      // Above Node
      int color=Black;     // Color of Node
   }
////////////////////////////////INSERT////////////////////////////////
   public void insert(Node<E> item) {
      if(item==null) {
         throw new NoSuchElementException("Inset was null");
      }//close if
      Node<E> temp=root;
      if(root==nil) {
         root= item;
         item.color=Black;
         item.parent=nil;
      }//close if
      else {
         item.color=Red;
         while(item!=root) {
            if(compare(item.data,temp.data)<0) {
               if(temp.right==nil) {
                  temp.right=item;
                  item.parent=temp;
                  break;
               }//close if
               else {
                  temp=temp.right;
               }//close else
            }//close if
            else if(compare(item.data,temp.data)>0){
               if(temp.left==nil) {
                  temp.left=item;
                  item.parent=temp;
                  break;
               }//close if
               else {
                  temp=temp.left;
               }//close else
            }//close else if
         }//close while
         adjustment(item);
      }//close else
   }//close insert

   private void adjustment(Node<E> item) {
      while(item.parent.color==Red) {
         Node<E> uncle;
         if(item.parent==item.parent.parent.left) {
            uncle=item.parent.parent.right;
            if(uncle.color==Red && uncle!=nil) {   //the uncle needs to exist and and be red to recolored
               item.parent.color=Black;
               item.parent.parent.color=Red;
               uncle.color=Black;
               continue;
            }//close if
            if(item==item.parent.right) {
               item=item.parent;
               lR(item);
            }//close if
            item.parent.color=Black;
            item.parent.parent.color=Red;
            rR(item.parent.parent);
         }//close if
         else {
            uncle=item.parent.parent.left;
            if(uncle.color==Red&&uncle!=nil) {
               item.parent.color=Black;
               item.parent.parent.color=Red;
               uncle.color=Black;
               continue;
            }//close if
            if(item==item.parent.left) {
               item=item.parent;
               rR(item);
            }//close if
            item.parent.color=Black;
            item.parent.parent.color=Red;
            lR(item.parent.parent);
         }//close else
      }//close while
      root.color=Black;
   }//close adjustment

   private int compare(E item,E x) {
      if(x==root) {
         return 1;   //same as root will be placed on the right
      }//close if
      else return item.compareTo(x);
   }//close compare
////////////////////////////////ROTATE////////////////////////////////
   private void rR(Node<E> node) {
      if(node.parent!=nil) {
         if(node==node.parent.left) {
            node.parent.left=node.left;
         }//close if
         else {
            node.parent.right=node.left;
         }//close else
         node.left.parent=node.parent;
         node.parent=node.left;
         if(node.left.right!=nil) {
            node.left.right.parent=node;
         }//close if
         Node<E> left=root.left;
         root.left=root.left.right;
         left.right.parent=nil;
         root=left;
      }//close if
   }//close rR
   private void lR(Node<E> node) {
      if(node.parent!=nil) {
        if(node==node.parent.left) {
           node.parent.left=node.right;
        }//close if
        else {
           node.parent.right=node.right;
        }//close else
        node.right.parent=node.parent;
        node.parent=node.parent;
        if(node.right.left!=nil) {
           node.right.left.parent=node;
        }//close if
        node.right=node.right.left;
        node.parent.left=node;
      }//close if
      else {
         Node<E> right=root.right;
         root.right=right.left;
         right.left.parent=root;
         root.parent=right;
         right.left=root;
         right.parent=nil;
         root=right;
      }//close else
   }//close lR
////////////////////////////////DELETE////////////////////////////////
   public void delete(Node<E> node) {
      if((node=find(node,root))==null) {
         System.out.println("Node does not exist");
         return;
      }
      Node<E> node2;
      Node<E> temp=node;
      int tempColor=node.color;

      if(node.left==nil) {
         node2=node.right;
         switchNodes(node,node.right);
      }
      else if(node.right==nil) {
         node2=node.left;
         switchNodes(node,node.left);
      }
      else {
         temp=subTree(node.right);
         tempColor=temp.color;
         node2=temp.right;
         if(temp.parent==node) {
            node2.parent=temp;
         }
         else {
            switchNodes(temp,temp.right);
            temp.right=node.right;
            temp.right.parent=temp;
         }
         switchNodes(node,temp);
         temp.left=node.left;
         temp.left.parent=temp;
         temp.color=node.color;
      }
      if(tempColor==Black) {
         deleteAdjustment(node2);
      }
   }//close delete

   public void switchNodes(Node<E> node,Node<E> nodeOther) {
      if(node.parent==nil) {
         root=nodeOther;
      }
      else if(node==node.parent.left) {
         nodeOther.parent.left=nodeOther;
      }
      else {
         node.parent.right=nodeOther;
      }
      nodeOther.parent=node.parent;
   }

   public Node<E> subTree(Node<E> subRoot) {
      while(subRoot!=nil) {
         subRoot=subRoot.left;
      }
      return subRoot;
   }

   public void deleteAdjustment(Node<E> node) {
      while(node!=root && node.color==Black) {
         if(node==node.parent.left) {
            Node<E> brother=node.parent.right;
            if(brother.color==Red) {
               brother.color=Black;
               node.parent.color=Red;
               lR(node.parent);
               brother=node.parent.right;
            }//close if
            if(brother.left.color==Black && brother.right.color==Black) {
               brother.color=Red;
               node=node.parent;
               continue;
            }//close if
            else if(brother.right.color==Black) {
               brother.left.color=Black;
               brother.color=Red;
               rR(brother);
               brother=node.parent.right;
            }//close else if
            if(brother.right.color==Red) {
               brother.color=node.parent.color;
               node.parent.color=Black;
               brother.right.color=Black;
               lR(node.parent);
               node=root;
            }//close if
         }//close if
         else {
            Node<E> brother=node.parent.left;
            if(brother.color==Red) {
               brother.color=Black;
               node.parent.color=Red;
               rR(node.parent);
               brother=node.parent.left;
            }//close if
            if(brother.right.color==Black&&brother.left.color==Black) {
               brother.color=Red;
               node=node.parent;
               continue;
            }//close if
            else if(brother.left.color==Black) {
               brother.right.color=Black;
               brother.color=Red;
               lR(brother);
               brother=node.parent.left;
            }//close else if
            if(brother.left.color==Red) {
               brother.color=node.parent.color;
               node.parent.color=Black;
               brother.left.color=Black;
               rR(node.parent);
               node=root;
            }//close if
         }//close else
      }//close while
      node.color=Black;
   }//close deleteAdjustment
////////////////////////////////FIND////////////////////////////////

   public Node<E> find(Node<E> item) {
      if(item==null) {
         throw new NoSuchElementException("Item was null.");
      }//close if
      return find(item,root);
   }//close find

   private Node<E> find(Node<E> findNode,Node<E> node) {
      if(root==nil) {
         return null;
      }//close if
      if(compare(findNode.data,node.data)<0) {
         if (node.right != nil) {
            return find(findNode,node.right);
         }
      }
      else if(compare(findNode.data,node.data)>0) {
         if (node.left != nil) {
            return find(findNode,node.left);
         }//close if
      }//close if
      else if(findNode.data==node.data) {
         return node;
      }
      return null;
   }

////////////////////////////////Print////////////////////////////////

   public void printInOrder() {
      if(root==nil) {
         return;
      }//close if
      System.out.print("Key: "+root.data+"-Black");
      printTree(root);
   }//close printInOrder

   public void printTree(Node<E> node) {
      if(node==nil) {
         return;
      }//close if
      printTree(node.left);
      if(node.color==Black) {
         System.out.print("Key: "+node.data+"-Black");
      }//close if
      else {
         System.out.print("Key: "+node.data+"-Red");
      }//close else
      printTree(node.right);
   }//close printTree
}//close class
</code>```

答:
In your red uncle code:

```<code>    if(uncle.color==Red && uncle!=nil) {   //the uncle needs to exist and and be red to recolored
       item.parent.color=Black;
       item.parent.parent.color=Red;
       uncle.color=Black;
       continue;
    }//close if
</code>```

You correctly flip the colors but do not re-assign item for the next trip through the loop, item should be items' grandparent during the next iteration, so make it:

```<code>            if(uncle.color==Red && uncle!=nil) {   //the uncle needs to exist and and be red to recolored
               item.parent.color=Black;
               item.parent.parent.color=Red;
               uncle.color=Black;
item = item.parent.parent;
               continue;
            }//close if
</code>```

This change is needed for both uncle cases (item.parent is a left and right child).

Title: Generic RedBlack Driver

Body:
I'm Trying to insert data threw my driver but it is nothing is working I keep getting my inset highlighted red and telling me that it is not the correct data type.The main problem is I don't understand how to set a generic type Node.Thank you for your help.

Driver(I've been trying diffrent things no progrees):

public class Driver {
    public static <E> void main(String[] args){
          RedBlack<Integer> rb = new RedBlack<Integer>( );
          Node<Integer> item=32;
          rb.insert(item);
       }//close main
}//close driver

REDBLACK CODE:

import java.util.NoSuchElementException;
public class RedBlack<E extends Comparable<? super E>>{
////////////////////////////////SETUP//////////////////////////////////////////
   private final static int Red=0;
   private final static int Black=1;
   private Node<E> nil;
   private Node<E> root;

   public RedBlack() {
      nil=new Node<E>(null);
      nil.left=nil.right=nil;
      root=new Node<E>(null);
      root.left=root.right=nil;
   }

   static class Node<E>{
      Node(E theData){
         this(theData,null,null);
      }

      Node(E theData,Node<E> lt,Node<E> rt){
            data=theData;
            left=lt;
            right=rt;
            color=RedBlack.Black;
      }

      E data;              // The data in the Node
      Node<E> left;        // Left child
      Node<E> right;       // Right child
      Node<E> parent;      // Above Node
      int color=Black;     // Color of Node
   }
////////////////////////////////INSERT////////////////////////////////
   public void insert(Node<E> item) {
      if(item==null) {
         throw new NoSuchElementException("Inset was null");
      }//close if
      Node<E> temp=root;
      if(root==nil) {
         root= item;
         item.color=Black;
         item.parent=nil;
      }//close if
      else {
         item.color=Red;
         while(item!=root) {
            if(compare(item.data,temp.data)<0) {
               if(temp.right==nil) {
                  temp.right=item;
                  item.parent=temp;
                  break;
               }//close if
               else {
                  temp=temp.right;
               }//close else
            }//close if
            else if(compare(item.data,temp.data)>0){
               if(temp.left==nil) {
                  temp.left=item;
                  item.parent=temp;
                  break;
               }//close if
               else {
                  temp=temp.left;
               }//close else
            }//close else if
         }//close while
         adjustment(item);
      }//close else
   }//close insert

   private void adjustment(Node<E> item) {
      while(item.parent.color==Red) {
         Node<E> uncle;
         if(item.parent==item.parent.parent.left) {
            uncle=item.parent.parent.right;
            if(uncle.color==Red && uncle!=nil) {   //the uncle needs to exist and and be red to recolored
               item.parent.color=Black;
               item.parent.parent.color=Red;
               uncle.color=Black;
               continue;
            }//close if
            if(item==item.parent.right) {
               item=item.parent;
               lR(item);
            }//close if
            item.parent.color=Black;
            item.parent.parent.color=Red;
            rR(item.parent.parent);
         }//close if
         else {
            uncle=item.parent.parent.left;
            if(uncle.color==Red&&uncle!=nil) {
               item.parent.color=Black;
               item.parent.parent.color=Red;
               uncle.color=Black;
               continue;
            }//close if
            if(item==item.parent.left) {
               item=item.parent;
               rR(item);
            }//close if
            item.parent.color=Black;
            item.parent.parent.color=Red;
            lR(item.parent.parent);
         }//close else
      }//close while
      root.color=Black;
   }//close adjustment

   private int compare(E item,E x) {
      if(x==root) {
         return 1;   //same as root will be placed on the right
      }//close if
      else return item.compareTo(x);
   }//close compare
////////////////////////////////ROTATE////////////////////////////////
   private void rR(Node<E> node) {
      if(node.parent!=nil) {
         if(node==node.parent.left) {
            node.parent.left=node.left;
         }//close if
         else {
            node.parent.right=node.left;
         }//close else
         node.left.parent=node.parent;
         node.parent=node.left;
         if(node.left.right!=nil) {
            node.left.right.parent=node;
         }//close if
         Node<E> left=root.left;
         root.left=root.left.right;
         left.right.parent=nil;
         root=left;
      }//close if
   }//close rR
   private void lR(Node<E> node) {
      if(node.parent!=nil) {
        if(node==node.parent.left) {
           node.parent.left=node.right;
        }//close if
        else {
           node.parent.right=node.right;
        }//close else
        node.right.parent=node.parent;
        node.parent=node.parent;
        if(node.right.left!=nil) {
           node.right.left.parent=node;
        }//close if
        node.right=node.right.left;
        node.parent.left=node;
      }//close if
      else {
         Node<E> right=root.right;
         root.right=right.left;
         right.left.parent=root;
         root.parent=right;
         right.left=root;
         right.parent=nil;
         root=right;
      }//close else
   }//close lR
////////////////////////////////DELETE////////////////////////////////
   public void delete(Node<E> node) {
      if((node=find(node,root))==null) {
         System.out.println("Node does not exist");
         return;
      }
      Node<E> node2;
      Node<E> temp=node;
      int tempColor=node.color;

      if(node.left==nil) {
         node2=node.right;
         switchNodes(node,node.right);
      }
      else if(node.right==nil) {
         node2=node.left;
         switchNodes(node,node.left);
      }
      else {
         temp=subTree(node.right);
         tempColor=temp.color;
         node2=temp.right;
         if(temp.parent==node) {
            node2.parent=temp;
         }
         else {
            switchNodes(temp,temp.right);
            temp.right=node.right;
            temp.right.parent=temp;
         }
         switchNodes(node,temp);
         temp.left=node.left;
         temp.left.parent=temp;
         temp.color=node.color;
      }
      if(tempColor==Black) {
         deleteAdjustment(node2);
      }
   }//close delete

   public void switchNodes(Node<E> node,Node<E> nodeOther) {
      if(node.parent==nil) {
         root=nodeOther;
      }
      else if(node==node.parent.left) {
         nodeOther.parent.left=nodeOther;
      }
      else {
         node.parent.right=nodeOther;
      }
      nodeOther.parent=node.parent;
   }

   public Node<E> subTree(Node<E> subRoot) {
      while(subRoot!=nil) {
         subRoot=subRoot.left;
      }
      return subRoot;
   }

   public void deleteAdjustment(Node<E> node) {
      while(node!=root && node.color==Black) {
         if(node==node.parent.left) {
            Node<E> brother=node.parent.right;
            if(brother.color==Red) {
               brother.color=Black;
               node.parent.color=Red;
               lR(node.parent);
               brother=node.parent.right;
            }//close if
            if(brother.left.color==Black && brother.right.color==Black) {
               brother.color=Red;
               node=node.parent;
               continue;
            }//close if
            else if(brother.right.color==Black) {
               brother.left.color=Black;
               brother.color=Red;
               rR(brother);
               brother=node.parent.right;
            }//close else if
            if(brother.right.color==Red) {
               brother.color=node.parent.color;
               node.parent.color=Black;
               brother.right.color=Black;
               lR(node.parent);
               node=root;
            }//close if
         }//close if
         else {
            Node<E> brother=node.parent.left;
            if(brother.color==Red) {
               brother.color=Black;
               node.parent.color=Red;
               rR(node.parent);
               brother=node.parent.left;
            }//close if
            if(brother.right.color==Black&&brother.left.color==Black) {
               brother.color=Red;
               node=node.parent;
               continue;
            }//close if
            else if(brother.left.color==Black) {
               brother.right.color=Black;
               brother.color=Red;
               lR(brother);
               brother=node.parent.left;
            }//close else if
            if(brother.left.color==Red) {
               brother.color=node.parent.color;
               node.parent.color=Black;
               brother.left.color=Black;
               rR(node.parent);
               node=root;
            }//close if
         }//close else
      }//close while
      node.color=Black;
   }//close deleteAdjustment
////////////////////////////////FIND////////////////////////////////

   public Node<E> find(Node<E> item) {
      if(item==null) {
         throw new NoSuchElementException("Item was null.");
      }//close if
      return find(item,root);
   }//close find

   private Node<E> find(Node<E> findNode,Node<E> node) {
      if(root==nil) {
         return null;
      }//close if
      if(compare(findNode.data,node.data)<0) {
         if (node.right != nil) {
            return find(findNode,node.right);
         }
      }
      else if(compare(findNode.data,node.data)>0) {
         if (node.left != nil) {
            return find(findNode,node.left);
         }//close if
      }//close if
      else if(findNode.data==node.data) {
         return node;
      }
      return null;
   }

////////////////////////////////Print////////////////////////////////

   public void printInOrder() {
      if(root==nil) {
         return;
      }//close if
      System.out.print("Key: "+root.data+"-Black");
      printTree(root);
   }//close printInOrder

   public void printTree(Node<E> node) {
      if(node==nil) {
         return;
      }//close if
      printTree(node.left);
      if(node.color==Black) {
         System.out.print("Key: "+node.data+"-Black");
      }//close if
      else {
         System.out.print("Key: "+node.data+"-Red");
      }//close else
      printTree(node.right);
   }//close printTree
}//close class

Body:
In your red uncle code:

    if(uncle.color==Red && uncle!=nil) {   //the uncle needs to exist and and be red to recolored
       item.parent.color=Black;
       item.parent.parent.color=Red;
       uncle.color=Black;
       continue;
    }//close if

You correctly flip the colors but do not re-assign item for the next trip through the loop, item should be items' grandparent during the next iteration, so make it:

            if(uncle.color==Red && uncle!=nil) {   //the uncle needs to exist and and be red to recolored
               item.parent.color=Black;
               item.parent.parent.color=Red;
               uncle.color=Black;
item = item.parent.parent;
               continue;
            }//close if

This change is needed for both uncle cases (item.parent is a left and right child).


问:
Regular Expression python sql statements
I'm writing a regular expression code to extract items from a SQL statement.  I want to pull out a tuple of the items after SELECT * FROM and WHERE statements.

```<code>pattern = '''
    SELECT\s\*\sFROM\s ([a-zA-Z\s*\,*\=\.]+) \sWHERE \s*([a-zA-Z\d*\s*\,*\=*\.*]+)'''
</code>```

From the pattern above, I'm using it for the SQL statement below, and get the following results:

```<code>('A, B, C\n           ', 'A.ColA = B.ColB AND B.ColB2=C.ColC')
</code>```

I know it's because of the huge break before the WHERE, but how  do I factor that in and get rid of the huge space and /n after my first tuple?

```<code>q = """SELECT * FROM A, B, C
            WHERE A.ColA = B.ColB AND B.ColB2=C.ColC"""
</code>```

答:
You can loop over the returned result and use re.sub:

```<code>import re
results = ('A, B, C\n           ', 'A.ColA = B.ColB AND B.ColB2=C.ColC')
new_results = tuple(re.sub('\n\s+$', '', i) for i in results)
</code>```

Output:

```<code>('A, B, C', 'A.ColA = B.ColB AND B.ColB2=C.ColC')
</code>```

Or, you can alter your pattern:

```<code>import re
q = """SELECT * FROM A, B, C
        WHERE A.ColA = B.ColB AND B.ColB2=C.ColC"""
new_data = re.findall('(?<=SELECT \* FROM\s)[A-Z\s,]+(?=\n)|(?<=WHERE\s)[\w\W]+', q)
</code>```

Output:

```<code>['A, B, C', 'A.ColA = B.ColB AND B.ColB2=C.ColC']
</code>```

Body:
I'm writing a regular expression code to extract items from a SQL statement.  I want to pull out a tuple of the items after SELECT * FROM and WHERE statements.

pattern = '''
    SELECT\s\*\sFROM\s ([a-zA-Z\s*\,*\=\.]+) \sWHERE \s*([a-zA-Z\d*\s*\,*\=*\.*]+)'''

From the pattern above, I'm using it for the SQL statement below, and get the following results:

('A, B, C\n           ', 'A.ColA = B.ColB AND B.ColB2=C.ColC')

I know it's because of the huge break before the WHERE, but how  do I factor that in and get rid of the huge space and /n after my first tuple?

q = """SELECT * FROM A, B, C
            WHERE A.ColA = B.ColB AND B.ColB2=C.ColC"""

Body:
You can loop over the returned result and use re.sub:

import re
results = ('A, B, C\n           ', 'A.ColA = B.ColB AND B.ColB2=C.ColC')
new_results = tuple(re.sub('\n\s+$', '', i) for i in results)

Output:

('A, B, C', 'A.ColA = B.ColB AND B.ColB2=C.ColC')

Or, you can alter your pattern:

import re
q = """SELECT * FROM A, B, C
        WHERE A.ColA = B.ColB AND B.ColB2=C.ColC"""
new_data = re.findall('(?<=SELECT \* FROM\s)[A-Z\s,]+(?=\n)|(?<=WHERE\s)[\w\W]+', q)

Output:

['A, B, C', 'A.ColA = B.ColB AND B.ColB2=C.ColC']


问:
Stop carousel from scrolling when it gets to the end
I have setup a scrolling carousel, that when you scroll with the mouse wheel the carousel scrolls left/right.

When you scroll down the carousel moves right, and when the offset gets to zero it stops it from scrolling. When you scroll up though, and the carousel gets to the end of the carousel it pops back to the beginning. How can I make it so it stops when it gets to the end? I know my math is wrong on my second ternary operator but I am not sure what the math is for it.

https://jsfiddle.net/obo4LkLL/

```<code>// Stop the scroll from going backwards too far
this.offset = this.offset > 0 ? 0 : this.offset

// Stop the scroll from going forwards too far
this.offset = Math.abs(this.offset) + this.element.clientWidth > this.element.scrollWidth ?
  Math.abs(this.offset) + this.element.clientWidth : this.offset

// Set the offset foreach child in the carousel
this.items.forEach(item => {
  if (!item.style) return
  item.style.transform = `translateX(${this.offset}px)`
})
</code>```

答:
So, basic logic is - we need variable limit, which is equal to: total width of child divs in carousel - carousel/container width. To make all dynamic, you can do something like this:

```<code>class carousel {

  constructor(element) {
  this.total_width=0;

    this.element = element

    this.items = []
    this.offset = 0
    this.scrollSpeed = 20
    this.element.childNodes.forEach(node => this.items.push(node))
    this.element.childNodes.forEach(node => {if(node.nodeType===1) return this.total_width+=node.clientWidth})
    element.addEventListener('wheel', this.wheel.bind(this))

  }

  wheel(e) {
    // Scroll up
    if (e.deltaY < 0) {
      this.offset -= this.scrollSpeed
    }
    // Scroll down
    else {
      this.offset += this.scrollSpeed
    }
    // Stop the scroll from going backwards too far
   // console.log(this.offset);
    this.offset = this.offset > 0 ? 0 : this.offset

    //stop scroll
    this.limit=this.total_width-this.element.clientWidth;

    if(Math.abs(this.offset)>this.limit) {
    this.offset=-this.limit;
    }

    // Stop the scroll from going forwards too far
   /* this.offset = Math.abs(this.offset) + this.element.clientWidth > this.element.scrollWidth ?
      Math.abs(this.offset) + this.element.clientWidth : this.offset*/
    // Set the offset foreach child in the carousel
    this.items.forEach(item => {

      if (!item.style) return
      item.style.transform = `translateX(${this.offset}px)`
    })
  }
}

document.querySelectorAll('.carousel').forEach(e => new carousel(e))
</code>```

I've just added few vars (total_width, limit) and condition for stop scrolling.

Demo:

class carousel {

  constructor(element) {
  this.total_width=0;

    this.element = element

    this.items = []
    this.offset = 0
    this.scrollSpeed = 20
    this.element.childNodes.forEach(node => this.items.push(node))
    this.element.childNodes.forEach(node => {if(node.nodeType===1) return this.total_width+=node.clientWidth})
    element.addEventListener('wheel', this.wheel.bind(this))

  }

  wheel(e) {
    // Scroll up
    if (e.deltaY < 0) {
      this.offset -= this.scrollSpeed
    }
    // Scroll down
    else {
      this.offset += this.scrollSpeed
    }
    // Stop the scroll from going backwards too far
   // console.log(this.offset);
    this.offset = this.offset > 0 ? 0 : this.offset

    //stop scroll
    this.limit=this.total_width-this.element.clientWidth;

   // console.log(this.limit);

    if(Math.abs(this.offset)>this.limit) {
    this.offset=-this.limit;
    }

    // Stop the scroll from going forwards too far
   /* this.offset = Math.abs(this.offset) + this.element.clientWidth > this.element.scrollWidth ?
      Math.abs(this.offset) + this.element.clientWidth : this.offset*/
    // Set the offset foreach child in the carousel
    this.items.forEach(item => {

      if (!item.style) return
      item.style.transform = `translateX(${this.offset}px)`
    })
  }
}

document.querySelectorAll('.carousel').forEach(e => new carousel(e))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.carousel {
  width: 500px;
  overflow: hidden;
  white-space: nowrap;
  border:3px solid green;
}

.carousel>div {
  width: 100px;
  height: 100px;
  display: inline-block;
  margin-right:-4px;
}

.carousel>div:nth-child(even) {
  background: red;
}

.carousel>div:nth-child(odd) {
  background: blue;
}</code>```

1

2

3

4

5

6

7

8

```

Body:
I have setup a scrolling carousel, that when you scroll with the mouse wheel the carousel scrolls left/right.

When you scroll down the carousel moves right, and when the offset gets to zero it stops it from scrolling. When you scroll up though, and the carousel gets to the end of the carousel it pops back to the beginning. How can I make it so it stops when it gets to the end? I know my math is wrong on my second ternary operator but I am not sure what the math is for it.

https://jsfiddle.net/obo4LkLL/

// Stop the scroll from going backwards too far
this.offset = this.offset > 0 ? 0 : this.offset

// Stop the scroll from going forwards too far
this.offset = Math.abs(this.offset) + this.element.clientWidth > this.element.scrollWidth ?
  Math.abs(this.offset) + this.element.clientWidth : this.offset

// Set the offset foreach child in the carousel
this.items.forEach(item => {
  if (!item.style) return
  item.style.transform = `translateX(${this.offset}px)`
})

Body:
So, basic logic is - we need variable limit, which is equal to: total width of child divs in carousel - carousel/container width. To make all dynamic, you can do something like this:

class carousel {

  constructor(element) {
  this.total_width=0;

    this.element = element

    this.items = []
    this.offset = 0
    this.scrollSpeed = 20
    this.element.childNodes.forEach(node => this.items.push(node))
    this.element.childNodes.forEach(node => {if(node.nodeType===1) return this.total_width+=node.clientWidth})
    element.addEventListener('wheel', this.wheel.bind(this))

  }

  wheel(e) {
    // Scroll up
    if (e.deltaY < 0) {
      this.offset -= this.scrollSpeed
    }
    // Scroll down
    else {
      this.offset += this.scrollSpeed
    }
    // Stop the scroll from going backwards too far
   // console.log(this.offset);
    this.offset = this.offset > 0 ? 0 : this.offset

    //stop scroll
    this.limit=this.total_width-this.element.clientWidth;

    if(Math.abs(this.offset)>this.limit) {
    this.offset=-this.limit;
    }

    // Stop the scroll from going forwards too far
   /* this.offset = Math.abs(this.offset) + this.element.clientWidth > this.element.scrollWidth ?
      Math.abs(this.offset) + this.element.clientWidth : this.offset*/
    // Set the offset foreach child in the carousel
    this.items.forEach(item => {

      if (!item.style) return
      item.style.transform = `translateX(${this.offset}px)`
    })
  }
}

document.querySelectorAll('.carousel').forEach(e => new carousel(e))

I've just added few vars (total_width, limit) and condition for stop scrolling.

Demo:

class carousel {

  constructor(element) {
  this.total_width=0;

    this.element = element

    this.items = []
    this.offset = 0
    this.scrollSpeed = 20
    this.element.childNodes.forEach(node => this.items.push(node))
    this.element.childNodes.forEach(node => {if(node.nodeType===1) return this.total_width+=node.clientWidth})
    element.addEventListener('wheel', this.wheel.bind(this))

  }

  wheel(e) {
    // Scroll up
    if (e.deltaY < 0) {
      this.offset -= this.scrollSpeed
    }
    // Scroll down
    else {
      this.offset += this.scrollSpeed
    }
    // Stop the scroll from going backwards too far
   // console.log(this.offset);
    this.offset = this.offset > 0 ? 0 : this.offset

    //stop scroll
    this.limit=this.total_width-this.element.clientWidth;

   // console.log(this.limit);

    if(Math.abs(this.offset)>this.limit) {
    this.offset=-this.limit;
    }

    // Stop the scroll from going forwards too far
   /* this.offset = Math.abs(this.offset) + this.element.clientWidth > this.element.scrollWidth ?
      Math.abs(this.offset) + this.element.clientWidth : this.offset*/
    // Set the offset foreach child in the carousel
    this.items.forEach(item => {

      if (!item.style) return
      item.style.transform = `translateX(${this.offset}px)`
    })
  }
}

document.querySelectorAll('.carousel').forEach(e => new carousel(e))

.carousel {
  width: 500px;
  overflow: hidden;
  white-space: nowrap;
  border:3px solid green;
}

.carousel>div {
  width: 100px;
  height: 100px;
  display: inline-block;
  margin-right:-4px;
}

.carousel>div:nth-child(even) {
  background: red;
}

.carousel>div:nth-child(odd) {
  background: blue;
}

<div class="carousel">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</div>


问:
Why is "this" NULL? C++ Segmentation fault

I'm building a Qt app and it's crashing because of a segmentation fault. After investigation, I found out that the cause of the segfault is that "this" is NULL and I try to access a member variable in the readInputFile(QString path) method.
In this line input += line;

I don't understand why this is happening. how can "this" be NULL ?

Here's where the object is created

```<code>void MainWindow::on_inpFileCheck_clicked()
{
    if (ui->inpFileCheck->isChecked()) {
        QString filePath = QFileDialog::getOpenFileName(this,tr("Open CSV file"), "/home", tr("CSV  (*.csv)"));
        myAlgo->readInputFile(filePath);
        ui->inputEdit->clear();
        ui->inputEdit->appendPlainText(myAlgo->getInput());
    }
}
</code>```

Here's the BaseAlgorithm header

```<code>#include "qstring.h"
#include "qmainwindow.h"

class BaseAlgorithm
{
public:
    BaseAlgorithm();
    QString readInputFile(QString);
    int lenArr;

private:
    QString input;
    QString output;
};
</code>```

And here's the implementation and where the problem happens

```<code>#include "basealgorithm.h"
#include "qfile.h"
#include "qtextstream.h"

BaseAlgorithm::BaseAlgorithm() {

    numComparisons = 0;
    input = "";
    output = "";
    intArr = NULL;
}

QString BaseAlgorithm::readInputFile(QString path) {

    QFile inpFile(path);
    if (inpFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&inpFile);

        while (!in.atEnd()) {
            QString line = in.readLine();
            input += line; // crash happens here
        }
        return input;
    }

    else {
         return "ERROR";
    }

}
</code>```

答:
It is pretty obvious that this is NULL because myAlgo is NULL where it is called. So the question asked in the title here is answered.

Why is myAlgo NULL? We don't know because you didn't show that code.

Body:
I'm building a Qt app and it's crashing because of a segmentation fault. After investigation, I found out that the cause of the segfault is that "this" is NULL and I try to access a member variable in the readInputFile(QString path) method.
In this line input += line;

I don't understand why this is happening. how can "this" be NULL ?

Here's where the object is created

void MainWindow::on_inpFileCheck_clicked()
{
    if (ui->inpFileCheck->isChecked()) {
        QString filePath = QFileDialog::getOpenFileName(this,tr("Open CSV file"), "/home", tr("CSV  (*.csv)"));
        myAlgo->readInputFile(filePath);
        ui->inputEdit->clear();
        ui->inputEdit->appendPlainText(myAlgo->getInput());
    }
}

Here's the BaseAlgorithm header

#include "qstring.h"
#include "qmainwindow.h"

class BaseAlgorithm
{
public:
    BaseAlgorithm();
    QString readInputFile(QString);
    int lenArr;

private:
    QString input;
    QString output;
};

And here's the implementation and where the problem happens

#include "basealgorithm.h"
#include "qfile.h"
#include "qtextstream.h"

BaseAlgorithm::BaseAlgorithm() {

    numComparisons = 0;
    input = "";
    output = "";
    intArr = NULL;
}

QString BaseAlgorithm::readInputFile(QString path) {

    QFile inpFile(path);
    if (inpFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&inpFile);

        while (!in.atEnd()) {
            QString line = in.readLine();
            input += line; // crash happens here
        }
        return input;
    }

    else {
         return "ERROR";
    }

}


问:
plm: using fixef() to manually calculate fitted values for a fixed effects twoways model
Please note: I am trying to get the code to work with both time & individual fixed effects, and an unbalanced dataset. The sample code below works with a balanced dataset.

See edit below too, please

I am trying to manually calculate the fitted values of a fixed effects model (with both individual and time effects) using the plm package. This is more of an exercise to confirm I understand the mechanics of the model and the package, I know I can get the fitted values themselves from the plm object, from the two related questions (here and here).

From the plm vignette (p.2), the underlying model is:

y_it = alpha + beta_transposed * x_it + (mu_i + lambda_t + epsilon_it)

where mu_i is the individual component of the error term (a.k.a. "individual effect"), and lambda_t is the "time effect".

The fixed effects can be extracted by using fixef() and I thought I could use them (together with the independent variables) to calculate the fitted values for the model, using (with two independent variables) in this way:

fit_it = alpha + beta_1 * x1 + beta_2 * x2 + mu_i + lambda_t

This is where I fail -- the values I get are nowhere near the fitted values (which I get as the difference between the actual values and the residuals in the model object). For one, I do not see alpha anywhere. I tried playing with the fixed effects being shown as differences from the first, from the mean, etc., with no success.

What I am missing? It could well be a misunderstanding of the model, or an error in the code, I am afraid... Thanks in advance.

PS: One of the related questions hints that pmodel.response() should be related to my issue (and the reason there is no plm.fit function), but its help page does not help me understand what this function actually does, and I cannot find any examples how to interpret the result it produces.

Thanks!

Sample code of what I did:

```<code>library(data.table); library(plm)

set.seed(100)
DT <- data.table(CJ(id=c("a","b","c","d"), time=c(1:10)))
DT[, x1:=rnorm(40)]
DT[, x2:=rnorm(40)]
DT[, y:=x1 + 2*x2 + rnorm(40)/10]
DT <- DT[!(id=="a" & time==4)] # just to make it an unbalanced panel
setkey(DT, id, time)

summary(plmFEit <- plm(data=DT, id=c("id","time"), formula=y ~ x1 + x2, model="within", effect="twoways"))

# Extract the fitted values from the plm object
FV <- data.table(plmFEit$model, residuals=as.numeric(plmFEit$residuals))
FV[, y := as.numeric(y)]
FV[, x1 := as.numeric(x1)]
FV[, x2 := as.numeric(x2)]

DT <- merge(x=DT, y=FV, by=c("y","x1","x2"), all=TRUE)
DT[, fitted.plm := as.numeric(y) - as.numeric(residuals)]

FEI <- data.table(as.matrix(fixef(object=plmFEit, effect="individual", type="level")), keep.rownames=TRUE) # as.matrix needed to preserve the names?
setnames(FEI, c("id","fei"))
setkey(FEI, id)
setkey(DT, id)
DT <- DT[FEI] # merge the fei into the data, each id gets a single number for every row

FET <- data.table(as.matrix(fixef(object=plmFEit, effect="time", type="level")), keep.rownames=TRUE) # as.matrix needed to preserve the names?
setnames(FET, c("time","fet"))
FET[, time := as.integer(time)] # fixef returns time as character
setkey(FET, time)
setkey(DT, time)
DT <- DT[FET] # merge the fet into the data, each time gets a single number for every row

# calculate the fitted values (called calc to distinguish from those from plm)
DT[, fitted.calc := as.numeric(coef(plmFEit)[1] * x1 + coef(plmFEit)[2]*x2 + fei + fet)]
DT[, diff := as.numeric(fitted.plm - fitted.calc)]

all.equal(DT$fitted.plm, DT$fitted.calc)
</code>```

My session is as follows:

```<code>R version 3.2.2 (2015-08-14)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8 x64 (build 9200)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] plm_1.4-0           Formula_1.2-1       RJSONIO_1.3-0       jsonlite_0.9.17     readxl_0.1.0.9000   data.table_1.9.7    bit64_0.9-5         bit_1.1-12          RevoUtilsMath_3.2.2

loaded via a namespace (and not attached):
 [1] bdsmatrix_1.3-2  Rcpp_0.12.1      lattice_0.20-33  zoo_1.7-12       MASS_7.3-44      grid_3.2.2       chron_2.3-47     nlme_3.1-122     curl_0.9.3       rstudioapi_0.3.1 sandwich_2.3-4
[12] tools_3.2.2
</code>```

Edit: (2015-02-22)
Since this has attracted some interest, I will try to clarify further. I was trying to fit a "fixed effects" model (a.k.a. "within" or "least squares dummy variables", as the plm package vignette calls it on p.3, top paragraph) -- same slope(s), different intercepts.

This is the same as running an ordinary OLS regression after adding dummies for time and id. Using the code below I can duplicate the fitted values from the plm package using base lm(). With the dummies, it is explicit that the first elements of both id and time are the group to compare to. What I still cannot do is how to use the facilities of the plm package to do the same I can easily accomplish using lm().

```<code># fit the same with lm() and match the fitted values to those from plm()
lmF <- lm(data = DT, formula = y ~ x1 + x2 + factor(time) + factor(id))
time.lm <- coef(lmF)[grep(x = names(coef(lmF)), pattern = "time", fixed = TRUE)]
time.lm <- c(0, unname(time.lm)) # no need for names, the position index corresponds to time

id.lm <- coef(lmF)[grep(x = names(coef(lmF)), pattern = "id", fixed = TRUE)]
id.lm <- c(0, unname(id.lm))
names(id.lm) <- c("a","b","c","d") # set names so that individual values can be looked up below when generating the fit

DT[, by=list(id, time), fitted.lm := coef(lmF)[["(Intercept)"]]  +  coef(lmF)[["x1"]] * x1  +  coef(lmF)[["x2"]] * x2  +  time.lm[[time]]  +  id.lm[[id]]]
all.equal(DT$fitted.plm, DT$fitted.lm)
</code>```

Hope this is useful to others who might be interested. The issue might be something about how plm and fixef deal with the missing value I intentionally created. I tried playing with the type= parameter of fixef but to no effect.

答:
I'm getting pretty close with Helix123's suggestion to subtract the within_intercept (it gets included in each of the two fixed effects, so you need to correct for that).

There's a very suggestive pattern in my reconstruction errors: individual a is always off by -0.004858712 (for every time period). Individuals b, c, d are always off by 0.002839703 for every time period except in period 4 (where there is no observation for a), where they're off by -0.010981192.

Any ideas? It looks like the individual fixed effects are thrown off by unbalancing. Rerunning it balanced works correctly.

Full code:

```<code>DT <- data.table(CJ(id=c("a","b","c","d"), time=c(1:10)))
DT[, x1:=rnorm(40)]
DT[, x2:=rnorm(40)]
DT[, y:= x1 + 2*x2 + rnorm(40)/10]
DT <- DT[!(id=="a" & time==4)] # just to make it an unbalanced panel
setkey(DT, id, time)

plmFEit <- plm(formula=y ~ x1 + x2,
               data=DT,
               index=c("id","time"),
               effect="twoways",
               model="within")

summary(plmFEit)

DT[, resids := residuals(plmFEit)]

FEI <- data.table(as.matrix(fixef(plmFEit, effect="individual", type="level")), keep.rownames=TRUE) # as.matrix needed to preserve the names?
setnames(FEI, c("id","fei"))
setkey(FEI, id)
setkey(DT, id)
DT <- DT[FEI] # merge the fei into the data, each id gets a single number for every row

FET <- data.table(as.matrix(fixef(plmFEit, effect="time", type="level")), keep.rownames=TRUE) # as.matrix needed to preserve the names?
setnames(FET, c("time","fet"))
FET[, time := as.integer(time)] # fixef returns time as character
setkey(FET, time)
setkey(DT, time)
DT <- DT[FET] # merge the fet into the data, each time gets a single number for every row

DT[, fitted.calc := plmFEit$coefficients[[1]] * x1 + plmFEit$coefficients[[2]] * x2 +
     fei + fet - within_intercept(plmFEit)]

DT[, myresids := y - fitted.calc]
DT[, myerr := resids - myresids]
</code>```

Body:
Please note: I am trying to get the code to work with both time & individual fixed effects, and an unbalanced dataset. The sample code below works with a balanced dataset.

See edit below too, please

I am trying to manually calculate the fitted values of a fixed effects model (with both individual and time effects) using the plm package. This is more of an exercise to confirm I understand the mechanics of the model and the package, I know I can get the fitted values themselves from the plm object, from the two related questions (here and here).

From the plm vignette (p.2), the underlying model is:

y_it = alpha + beta_transposed * x_it + (mu_i + lambda_t + epsilon_it)

where mu_i is the individual component of the error term (a.k.a. "individual effect"), and lambda_t is the "time effect".

The fixed effects can be extracted by using fixef() and I thought I could use them (together with the independent variables) to calculate the fitted values for the model, using (with two independent variables) in this way:

fit_it = alpha + beta_1 * x1 + beta_2 * x2 + mu_i + lambda_t

This is where I fail -- the values I get are nowhere near the fitted values (which I get as the difference between the actual values and the residuals in the model object). For one, I do not see alpha anywhere. I tried playing with the fixed effects being shown as differences from the first, from the mean, etc., with no success.

What I am missing? It could well be a misunderstanding of the model, or an error in the code, I am afraid... Thanks in advance.

PS: One of the related questions hints that pmodel.response() should be related to my issue (and the reason there is no plm.fit function), but its help page does not help me understand what this function actually does, and I cannot find any examples how to interpret the result it produces.

Thanks!

Sample code of what I did:

library(data.table); library(plm)

set.seed(100)
DT <- data.table(CJ(id=c("a","b","c","d"), time=c(1:10)))
DT[, x1:=rnorm(40)]
DT[, x2:=rnorm(40)]
DT[, y:=x1 + 2*x2 + rnorm(40)/10]
DT <- DT[!(id=="a" & time==4)] # just to make it an unbalanced panel
setkey(DT, id, time)

summary(plmFEit <- plm(data=DT, id=c("id","time"), formula=y ~ x1 + x2, model="within", effect="twoways"))

# Extract the fitted values from the plm object
FV <- data.table(plmFEit$model, residuals=as.numeric(plmFEit$residuals))
FV[, y := as.numeric(y)]
FV[, x1 := as.numeric(x1)]
FV[, x2 := as.numeric(x2)]

DT <- merge(x=DT, y=FV, by=c("y","x1","x2"), all=TRUE)
DT[, fitted.plm := as.numeric(y) - as.numeric(residuals)]

FEI <- data.table(as.matrix(fixef(object=plmFEit, effect="individual", type="level")), keep.rownames=TRUE) # as.matrix needed to preserve the names?
setnames(FEI, c("id","fei"))
setkey(FEI, id)
setkey(DT, id)
DT <- DT[FEI] # merge the fei into the data, each id gets a single number for every row

FET <- data.table(as.matrix(fixef(object=plmFEit, effect="time", type="level")), keep.rownames=TRUE) # as.matrix needed to preserve the names?
setnames(FET, c("time","fet"))
FET[, time := as.integer(time)] # fixef returns time as character
setkey(FET, time)
setkey(DT, time)
DT <- DT[FET] # merge the fet into the data, each time gets a single number for every row

# calculate the fitted values (called calc to distinguish from those from plm)
DT[, fitted.calc := as.numeric(coef(plmFEit)[1] * x1 + coef(plmFEit)[2]*x2 + fei + fet)]
DT[, diff := as.numeric(fitted.plm - fitted.calc)]

all.equal(DT$fitted.plm, DT$fitted.calc)

My session is as follows:

R version 3.2.2 (2015-08-14)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8 x64 (build 9200)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] plm_1.4-0           Formula_1.2-1       RJSONIO_1.3-0       jsonlite_0.9.17     readxl_0.1.0.9000   data.table_1.9.7    bit64_0.9-5         bit_1.1-12          RevoUtilsMath_3.2.2

loaded via a namespace (and not attached):
 [1] bdsmatrix_1.3-2  Rcpp_0.12.1      lattice_0.20-33  zoo_1.7-12       MASS_7.3-44      grid_3.2.2       chron_2.3-47     nlme_3.1-122     curl_0.9.3       rstudioapi_0.3.1 sandwich_2.3-4
[12] tools_3.2.2

Edit: (2015-02-22)
Since this has attracted some interest, I will try to clarify further. I was trying to fit a "fixed effects" model (a.k.a. "within" or "least squares dummy variables", as the plm package vignette calls it on p.3, top paragraph) -- same slope(s), different intercepts.

This is the same as running an ordinary OLS regression after adding dummies for time and id. Using the code below I can duplicate the fitted values from the plm package using base lm(). With the dummies, it is explicit that the first elements of both id and time are the group to compare to. What I still cannot do is how to use the facilities of the plm package to do the same I can easily accomplish using lm().

# fit the same with lm() and match the fitted values to those from plm()
lmF <- lm(data = DT, formula = y ~ x1 + x2 + factor(time) + factor(id))
time.lm <- coef(lmF)[grep(x = names(coef(lmF)), pattern = "time", fixed = TRUE)]
time.lm <- c(0, unname(time.lm)) # no need for names, the position index corresponds to time

id.lm <- coef(lmF)[grep(x = names(coef(lmF)), pattern = "id", fixed = TRUE)]
id.lm <- c(0, unname(id.lm))
names(id.lm) <- c("a","b","c","d") # set names so that individual values can be looked up below when generating the fit

DT[, by=list(id, time), fitted.lm := coef(lmF)[["(Intercept)"]]  +  coef(lmF)[["x1"]] * x1  +  coef(lmF)[["x2"]] * x2  +  time.lm[[time]]  +  id.lm[[id]]]
all.equal(DT$fitted.plm, DT$fitted.lm)

Hope this is useful to others who might be interested. The issue might be something about how plm and fixef deal with the missing value I intentionally created. I tried playing with the type= parameter of fixef but to no effect.

Body:
I'm getting pretty close with Helix123's suggestion to subtract the within_intercept (it gets included in each of the two fixed effects, so you need to correct for that).

There's a very suggestive pattern in my reconstruction errors: individual a is always off by -0.004858712 (for every time period). Individuals b, c, d are always off by 0.002839703 for every time period except in period 4 (where there is no observation for a), where they're off by -0.010981192.

Any ideas? It looks like the individual fixed effects are thrown off by unbalancing. Rerunning it balanced works correctly.

Full code:

DT <- data.table(CJ(id=c("a","b","c","d"), time=c(1:10)))
DT[, x1:=rnorm(40)]
DT[, x2:=rnorm(40)]
DT[, y:= x1 + 2*x2 + rnorm(40)/10]
DT <- DT[!(id=="a" & time==4)] # just to make it an unbalanced panel
setkey(DT, id, time)

plmFEit <- plm(formula=y ~ x1 + x2,
               data=DT,
               index=c("id","time"),
               effect="twoways",
               model="within")

summary(plmFEit)

DT[, resids := residuals(plmFEit)]

FEI <- data.table(as.matrix(fixef(plmFEit, effect="individual", type="level")), keep.rownames=TRUE) # as.matrix needed to preserve the names?
setnames(FEI, c("id","fei"))
setkey(FEI, id)
setkey(DT, id)
DT <- DT[FEI] # merge the fei into the data, each id gets a single number for every row

FET <- data.table(as.matrix(fixef(plmFEit, effect="time", type="level")), keep.rownames=TRUE) # as.matrix needed to preserve the names?
setnames(FET, c("time","fet"))
FET[, time := as.integer(time)] # fixef returns time as character
setkey(FET, time)
setkey(DT, time)
DT <- DT[FET] # merge the fet into the data, each time gets a single number for every row

DT[, fitted.calc := plmFEit$coefficients[[1]] * x1 + plmFEit$coefficients[[2]] * x2 +
     fei + fet - within_intercept(plmFEit)]

DT[, myresids := y - fitted.calc]
DT[, myerr := resids - myresids]


问:
Programming style of method declaration of get/set method variables in C++?
Should you declare the getters/setters of the class inside the .h file and then define them in .cpp Or do both in .h file. Which style do you prefer and why? I personally like the latter wherein all of them are in .h and only methods which have logic associated with it other than setters/getters in .cpp. </p>

答:
For me this depends on what I'm doing with the code. For code that I want maintained and to last over time, I put everything in the .cc file for the following reasons:

The .h file can remain sparse as documentation for people who want to look for function and method definitions.

My group's coding guidelines state that we put everything in the .cpp file and like to follow those, even if the function definition only takes one line. This eliminates guessing games about where things actually live, because you know which file you should examine.

If you're doing frequent recompiles of a big project, keeping the function definition in the .cpp file saves you some time compared to keeping function definitions in header files. This was relevant very recently for us, as we recently went through the code and added a lot of runtime assert statements to validate input data for our classes, and that required a lot of modification to getters and setters. If these method declarations had lived in .cpp files, this would have turned into a clean recompile for us, which can take ~30min on my laptop.

That's not to say that I don't play fast-and-dirty with the rules occasionally and put things in .h files when implementing something really fast, but for code I'm serious about I all code (regardless of length) in the .cpp file. For big projects (some of) the rules are there for a reason, and following them can be a virtue.

Speaking of which, I just thought of yet another Perl script I can hack together to find violations of the coding guidelines. It's good to be popular. :)

LastEditorDisplayName: Eddie Parker

OwnerDisplayName: James Thompson


问:
How to make "watch" task forever false?
I am trying to deploy a static website from bitbucket to Netlify. It fails because "watch" is in waiting mode.

The logs from Netlify:

```<code>Done, without errors.
8:38:52 PM: Completed in 60.606s at Fri Dec 08 2017 17:38:43 GMT+0000 (UTC) - Waiting...
</code>```

My Gruntfile.js configuration is:

watch: {
      options: {
         livereload: true,
         atBegin: true,
         interval: 1000,
         forever: false,
         // spawn: false,
         // interrupt: true,
         // debounceDelay: 3000
        },```

Help me to make "watch" task end after building.

答:
As someone mentioned in the comments above, there needs to be some more information in your question about your config.

There needs to be a build target in the grunt config that does not use the local development server as watch is doing.

watch: {
  ....
},
build: {
  ....
}
```

<p>
Also you would need to register the task as in the following command:</p>

<pre class="lang-js prettyprint-override"><code>grunt.registerTask('build', ['target1', 'target2']);
</code>```

Then the build command in Netlify would be: grunt build rather than the command you are using.

Title: How to make "watch" task forever false?

Body:
I am trying to deploy a static website from bitbucket to Netlify. It fails because "watch" is in waiting mode.

The logs from Netlify:

Done, without errors.
8:38:52 PM: Completed in 60.606s at Fri Dec 08 2017 17:38:43 GMT+0000 (UTC) - Waiting...

My Gruntfile.js configuration is:

watch: {
      options: {
         livereload: true,
         atBegin: true,
         interval: 1000,
         forever: false,
         // spawn: false,
         // interrupt: true,
         // debounceDelay: 3000
        },

Help me to make "watch" task end after building.

Body:
As someone mentioned in the comments above, there needs to be some more information in your question about your config.

There needs to be a build target in the grunt config that does not use the local development server as watch is doing.

watch: {
  ....
},
build: {
  ....
}

Also you would need to register the task as in the following command:

grunt.registerTask('build', ['target1', 'target2']);

Then the build command in Netlify would be: grunt build rather than the command you are using.