问:
Modifying Wordpress PHP dynamic content
My page is bewitcheryinc.com
I am trying to re-arrange my home page. I need to switch the promotional area (section with 3 rectangles) with the text below it. I need to have the text displayed first and then the promotional area (section with 3 rectangles). I have contacted theme support, and they told me that the content is dynamic and the only solution to try is to replace header.php with the following code.

```<code><?php
/**
 * Displays the header content
 *
 * @package Theme Freesia
 * @subpackage Edge
 * @since Edge 1.0
 */
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<?php
$edge_settings = edge_get_theme_options(); ?>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="hfeed site">
<!-- Masthead ============================================= -->
<header id="masthead" class="site-header">
        <?php if ( function_exists( 'the_custom_header_markup' ) ) {
            if ( is_header_video_active() && ( has_header_video() || is_customize_preview() ) ) {
                echo '<div class="custom-header">
                    <div class="custom-header-media">';
                the_custom_header_markup();
                echo '</div>
                </div>';
            }else{
                if ( has_header_image() ) {?>
                    <a href="<?php echo esc_url(home_url('/'));?>"><img src="<?php header_image(); ?>" class="header-image" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="<?php echo esc_attr(get_bloginfo('name', 'display'));?>" /> </a>
                <?php }
            }
        } else { ?>
        <a href="<?php echo esc_url(home_url('/'));?>"><img src="<?php header_image(); ?>" class="header-image" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="<?php echo esc_attr(get_bloginfo('name', 'display'));?>" /> </a>
        <?php } ?>
        <div class="top-header">
            <div class="container clearfix">
                <?php
                if( is_active_sidebar( 'edge_header_info' )) {
                    dynamic_sidebar( 'edge_header_info' );
                }
                if($edge_settings['edge_top_social_icons'] == 0):
                    echo '<div class="header-social-block">';
                        do_action('social_links');
                    echo '</div>'.'<!-- end .header-social-block -->';
                endif;
                 do_action('edge_site_branding'); ?>
            </div> <!-- end .container -->
        </div> <!-- end .top-header -->
        <!-- Main Header============================================= -->
                <div id="sticky_header">
                    <div class="container clearfix">
                        <h3 class="nav-site-title">
                            <a href="<?php echo esc_url(home_url('/'));?>" title="<?php echo esc_attr(get_bloginfo('name', 'display'));?>"><?php bloginfo('name');?></a>
                        </h3>
                    <!-- end .nav-site-title -->
                        <!-- Main Nav ============================================= -->
                        <?php
                            if (has_nav_menu('primary')) { ?>
                        <?php $args = array(
                            'theme_location' => 'primary',
                            'container'      => '',
                            'items_wrap'     => '<ul id="primary-menu" class="menu nav-menu">%3$s</ul>',
                            ); ?>
                        <nav id="site-navigation" class="main-navigation clearfix">
                            <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false">
                                <span class="line-one"></span>
                                <span class="line-two"></span>
                                <span class="line-three"></span>
                            </button>
                            <!-- end .menu-toggle -->
                            <?php wp_nav_menu($args);//extract the content from apperance-> nav menu ?>
                        </nav> <!-- end #site-navigation -->
                        <?php } else {// extract the content from page menu only ?>
                        <nav id="site-navigation" class="main-navigation clearfix">
                            <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false">
                                <span class="line-one"></span>
                                <span class="line-two"></span>
                                <span class="line-three"></span>
                            </button>
                        <!-- end .menu-toggle -->
                            <?php   wp_page_menu(array('menu_class' => 'menu', 'items_wrap'     => '<ul id="primary-menu" class="menu nav-menu">%3$s</ul>')); ?>
                        </nav> <!-- end #site-navigation -->
                        <?php }
                        $search_form = $edge_settings['edge_search_custom_header'];
                        if (1 != $search_form) { ?>
                            <div id="search-toggle" class="header-search"></div>
                            <div id="search-box" class="clearfix">
                                <?php get_search_form();?>
                            </div>  <!-- end #search-box -->
                        <?php }

            echo '</div> <!-- end .container -->
            </div> <!-- end #sticky_header -->';
        $enable_slider = $edge_settings['edge_enable_slider'];
        edge_slider_value();
        if ($enable_slider=='frontpage'|| $enable_slider=='enitresite'){
            if(is_front_page() && ($enable_slider=='frontpage') ) {
                if($edge_settings['edge_slider_type'] == 'default_slider') {
                        edge_page_sliders();
                }else{
                    if(class_exists('Edge_Plus_Features')):
                        edge_image_sliders();
                    endif;
                }
            }
            if($enable_slider=='enitresite'){
                if($edge_settings['edge_slider_type'] == 'default_slider') {
                        edge_page_sliders();
                }else{
                    if(class_exists('Edge_Plus_Features')):
                        edge_image_sliders();
                    endif;
                }
            }
        } ?>
</header> <!-- end #masthead -->
<!-- Main Page Start ============================================= -->
<div id="content">
<div class="container clearfix">
<?php
if(is_front_page()){
    if( have_posts() ) {
        while( have_posts() ) {
        the_post();
        get_template_part( 'content', get_post_format() );
        }
    } else { ?>
    <h2 class="entry-title"> <?php esc_html_e( 'No Posts Found.', 'edge' ); ?> </h2>
    <?php }

    do_action('edge_display_frontpage_features');
}
if(!is_home()){?>
    <div class="page-header">
        <h1 class="page-title"><?php echo edge_header_title(); ?></h1>
        <!-- .page-title -->
        <?php edge_breadcrumb(); ?>
        <!-- .breadcrumb -->
    </div>
    <!-- .page-header -->
<?php }
</code>```

After I replace headr.php, I have to add the following css:

```<code>.home .entry-header, .home .entry-meta, section#post-417, .home .entry-footer {
display:none;
}
</code>```

When I follow these instructions, the home page displays my original page text as a blog post with "read more" tags, along with the meta tags. The read more link links back to the home page. I simply want the front page to display my page title, some text, and then the promotional picture boxes.

If it is helpful, I beleive that when promotional area is turned on, the theme uses front-page-feature.php template instead of an index page. It is bellow.

```<code><?php
function edge_frontpage_features(){
    $edge_settings = edge_get_theme_options();
    if($edge_settings['edge_disable_features'] != 1){
        $edge_features = '';
        $edge_total_page_no = 0;
        $edge_list_page = array();
        for( $i = 1; $i <= $edge_settings['edge_total_features']; $i++ ){
            if( isset ( $edge_settings['edge_frontpage_features_' . $i] ) && $edge_settings['edge_frontpage_features_' . $i] > 0 ){
                $edge_total_page_no++;

                $edge_list_page =   array_merge( $edge_list_page, array( $edge_settings['edge_frontpage_features_' . $i] ) );
            }

        }
        if ( !empty( $edge_list_page ) && $edge_total_page_no > 0 ) {
            echo '<!-- Promotional Area ============================================= -->';
                $edge_features  .= '<div class="promonational-area">';
                                $get_featured_posts         = new WP_Query(array(
                                'posts_per_page'        => $edge_settings['edge_total_features'],
                                'post_type'             => array('page'),
                                'post__in'              => $edge_list_page,
                                'orderby'               => 'post__in',
                            ));
                    $edge_features .= '<div class="column clearfix">';
                $j = 1;
                while ($get_featured_posts->have_posts()):$get_featured_posts->the_post();
                $attachment_id = get_post_thumbnail_id();
                $image_attributes = wp_get_attachment_image_src($attachment_id,'pixgraphy_promotional_image');
                            $excerpt                     = get_the_excerpt();
                    $edge_features .= '<div class="three-column">';
                    if ($image_attributes) {
                        $edge_features  .= '<div class="promonational-img" title="'.the_title('', '', false).'"' .' style="background-image:url(' ."'" .esc_url($image_attributes[0])."'" .')"> <a class="promonational-link" href="'.get_the_permalink().'"></a>   ';
                        $edge_features .= '<div class="promonational-overlay">
                                <h4>'.get_the_title().'</h4></div></div>';
                    }
                    $edge_features  .='</div><!-- end .three-column -->';
                    $j++;
                    endwhile;
                    $edge_features  .='</div><!-- .end column-->';
                    $edge_features  .='</div><!-- end .promonational-area -->';
                }
        echo $edge_features;
    }
        wp_reset_postdata();
}
add_action('edge_display_frontpage_features','edge_frontpage_features');
</code>```

Can anyone help? I am not proficient obviously in PHP/WordPress at all. Thank you!

答:
I think this would work:

In index.php move the

if(is_front_page()){
    do_action('edge_display_frontpage_features');
}

right before

```<code>get_template_part( 'pagination', 'none' );
</code>```

in header.php.

This would put the front-page feature after the 'main' content in the primary section of the post. Now you need to figure out how to put the right post content for the text. Currently it seems like it's not fetching the correct post type. It's probably the sample post in the post post type.

But is the text supposed to be static or changes with your recently posted content? If its supposed to static, you should go in Settings->Reading in the admin dashboard and set the front-page to a static page and then you can put in the text into that page content.

Title: Modifying Wordpress PHP dynamic content

Body:
My page is bewitcheryinc.com
I am trying to re-arrange my home page. I need to switch the promotional area (section with 3 rectangles) with the text below it. I need to have the text displayed first and then the promotional area (section with 3 rectangles). I have contacted theme support, and they told me that the content is dynamic and the only solution to try is to replace header.php with the following code.

<?php
/**
 * Displays the header content
 *
 * @package Theme Freesia
 * @subpackage Edge
 * @since Edge 1.0
 */
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<?php
$edge_settings = edge_get_theme_options(); ?>

<meta charset="<?php bloginfo( 'charset' ); ?>" />
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php wp_head(); ?>

<body <?php body_class(); ?>>

        <?php if ( function_exists( 'the_custom_header_markup' ) ) {
            if ( is_header_video_active() && ( has_header_video() || is_customize_preview() ) ) {
                echo '

';
                the_custom_header_markup();
                echo '

';
            }else{
                if ( has_header_image() ) {?>
                    <a href="<?php echo esc_url(home_url('/'));?>"><img src="<?php header_image(); ?>" class="header-image" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="<?php echo esc_attr(get_bloginfo('name', 'display'));?>" />
                <?php }
            }
        } else { ?>
        <a href="<?php echo esc_url(home_url('/'));?>"><img src="<?php header_image(); ?>" class="header-image" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="<?php echo esc_attr(get_bloginfo('name', 'display'));?>" />
        <?php } ?>

                <?php
                if( is_active_sidebar( 'edge_header_info' )) {
                    dynamic_sidebar( 'edge_header_info' );
                }
                if($edge_settings['edge_top_social_icons'] == 0):
                    echo '
';
                        do_action('social_links');
                    echo '
'.'';
                endif;
                 do_action('edge_site_branding'); ?>

                            <a href="<?php echo esc_url(home_url('/'));?>" title="<?php echo esc_attr(get_bloginfo('name', 'display'));?>"><?php bloginfo('name');?>

                        <?php
                            if (has_nav_menu('primary')) { ?>
                        <?php $args = array(
                            'theme_location' => 'primary',
                            'container'      => '',
                            'items_wrap'     => '
%3$s
',
                            ); ?>

                            <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false">

                            </button>

                            <?php wp_nav_menu($args);//extract the content from apperance-> nav menu ?>

                        <?php } else {// extract the content from page menu only ?>

                            <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false">

                            </button>

                            <?php   wp_page_menu(array('menu_class' => 'menu', 'items_wrap'     => '
%3$s
')); ?>

                        <?php }
                        $search_form = $edge_settings['edge_search_custom_header'];
                        if (1 != $search_form) { ?>

                                <?php get_search_form();?>

                        <?php }

            echo '

 ';
        $enable_slider = $edge_settings['edge_enable_slider'];
        edge_slider_value();
        if ($enable_slider=='frontpage'|| $enable_slider=='enitresite'){
            if(is_front_page() && ($enable_slider=='frontpage') ) {
                if($edge_settings['edge_slider_type'] == 'default_slider') {
                        edge_page_sliders();
                }else{
                    if(class_exists('Edge_Plus_Features')):
                        edge_image_sliders();
                    endif;
                }
            }
            if($enable_slider=='enitresite'){
                if($edge_settings['edge_slider_type'] == 'default_slider') {
                        edge_page_sliders();
                }else{
                    if(class_exists('Edge_Plus_Features')):
                        edge_image_sliders();
                    endif;
                }
            }
        } ?>

<?php
if(is_front_page()){
    if( have_posts() ) {
        while( have_posts() ) {
        the_post();
        get_template_part( 'content', get_post_format() );
        }
    } else { ?>

 <?php esc_html_e( 'No Posts Found.', 'edge' ); ?>

    <?php }

    do_action('edge_display_frontpage_features');
}
if(!is_home()){?>

<?php echo edge_header_title(); ?>

        <?php edge_breadcrumb(); ?>

<?php }

After I replace headr.php, I have to add the following css:

.home .entry-header, .home .entry-meta, section#post-417, .home .entry-footer {
display:none;
}

When I follow these instructions, the home page displays my original page text as a blog post with "read more" tags, along with the meta tags. The read more link links back to the home page. I simply want the front page to display my page title, some text, and then the promotional picture boxes.

If it is helpful, I beleive that when promotional area is turned on, the theme uses front-page-feature.php template instead of an index page. It is bellow.

<?php
function edge_frontpage_features(){
    $edge_settings = edge_get_theme_options();
    if($edge_settings['edge_disable_features'] != 1){
        $edge_features = '';
        $edge_total_page_no = 0;
        $edge_list_page = array();
        for( $i = 1; $i <= $edge_settings['edge_total_features']; $i++ ){
            if( isset ( $edge_settings['edge_frontpage_features_' . $i] ) && $edge_settings['edge_frontpage_features_' . $i] > 0 ){
                $edge_total_page_no++;

                $edge_list_page =   array_merge( $edge_list_page, array( $edge_settings['edge_frontpage_features_' . $i] ) );
            }

        }
        if ( !empty( $edge_list_page ) && $edge_total_page_no > 0 ) {
            echo '';
                $edge_features  .= '
';
                                $get_featured_posts         = new WP_Query(array(
                                'posts_per_page'        => $edge_settings['edge_total_features'],
                                'post_type'             => array('page'),
                                'post__in'              => $edge_list_page,
                                'orderby'               => 'post__in',
                            ));
                    $edge_features .= '
';
                $j = 1;
                while ($get_featured_posts->have_posts()):$get_featured_posts->the_post();
                $attachment_id = get_post_thumbnail_id();
                $image_attributes = wp_get_attachment_image_src($attachment_id,'pixgraphy_promotional_image');
                            $excerpt                     = get_the_excerpt();
                    $edge_features .= '
';
                    if ($image_attributes) {
                        $edge_features  .= '
    ';
                        $edge_features .= '

'.get_the_title().'

';
                    }
                    $edge_features  .='
';
                    $j++;
                    endwhile;
                    $edge_features  .='
';
                    $edge_features  .='
';
                }
        echo $edge_features;
    }
        wp_reset_postdata();
}
add_action('edge_display_frontpage_features','edge_frontpage_features');

Can anyone help? I am not proficient obviously in PHP/WordPress at all. Thank you!

Body:
I think this would work:

In index.php move the

if(is_front_page()){
    do_action('edge_display_frontpage_features');
}

right before

get_template_part( 'pagination', 'none' );

in header.php.

This would put the front-page feature after the 'main' content in the primary section of the post. Now you need to figure out how to put the right post content for the text. Currently it seems like it's not fetching the correct post type. It's probably the sample post in the post post type.

But is the text supposed to be static or changes with your recently posted content? If its supposed to static, you should go in Settings->Reading in the admin dashboard and set the front-page to a static page and then you can put in the text into that page content.


来源: stackexchange

问:
What is the proper way to use Protractor with SystemJS?
This problem should apply to requirejs as well.

The specifics:

Protractor

SystemJS loading ES6 BabelJS transpiled system modules

Cucumber.js

Chai, chai-as-promised

The reason I'm asking is because I have just a couple very basic cucumber tests and sometimes I get errors (inconsistently) involving timeouts or waiting to sync with the page etc. Other times my tests pass and no timeout errors are given. There is not a ton of authoritative information on these problems. Mainly just a bunch of SO and github issues.

What is the proper way to use Protractor with SystemJS?

答:
These don't sound like issues specific to SystemJS.

Rather, in my experience, they are pretty much the joys of working with Protractor.

Things the you can do to mitigate the issues however include:

Add browser.manage().timeouts().implicitlyWait(5000); before any tests run. Perhaps in your protractor onPrepare config method

Try browser.waitForAngular();

Theoretically its called internally in Protractor, but somethings it seems to be needed..?

Wait for elements to be clickable, before clicking them:
browser.wait(protractor.ExpectedConditions.elementToBeClickable(elm), 2000);
elm.click();

You may also be interested to see that there is a new project that hopes to avoid all the pitfalls with selenium based test frameworks.. by not using selenium at all. It claims to be much simpler, faster and less error-prone: https://www.cypress.io/

ContentLicense: CC BY-SA 3.0


问:
How to test PayPal free trial subscriptions with IPN?
We are trying to implement Free trials with PayPal subscriptions.

Currently we don't offer any trials, so PayPal sends a transaction notification every month for a particular subscription and we renew the license (basically add 30 more days to it and wait for the next transaction info after 30 days).

Now we are trying to offer 7-day free trials. So my question is, will it work like monthly, without-trial, subscriptions? Will PayPal notify our IPN on the 8th for a monthly payment. If it does, then we add 30 days. Currently we just add 7 days and wait for the monthly payment notification (to keep it in sync with our current logic). We don't handle cancellation notifications, just to make it clear. If the the user cancels on, say, 18th day, he can enjoy the subscription till 30th days. But it won't renew since we won't receive a payment notification to add 30 more days.

I saw a similar question IPN Question, but that doesn't answer our specific problem.

答:
How to test

'How to test' is answered by the PayPal IPN Sandbox.

will it work like monthly, without-trial, subscriptions? Will PayPal notify our IPN on the 8th for a monthly payment.

You will get two messages: subscr_signup and subscr_payment, in either order, as soon as he subscribes, and you will get further subscr_payment messages: at the start of the 2nd trial period if any, and then at each payment. If there are free trial periods, the mc_amount fields in the corresponding subscr_payment messages will be zero. As always, you need to check everything against your own records of what the subscription plan is.


问:
JQuery not keyword
```<code>$("li a").click(function() {
    $(this).parent().css({ width: 160 });
    $("li").unbind('mouseenter mouseleave');
    $("#Container").css({ width: 200 }).animate({ width: 700 }, 1000);
});
</code>```

I wanna set width 120 for all li's except current(this).

Thanks

答:
You can try

```<code>    $(this).parent().siblings().css({ width: 160 })
</code>```

Working sample here

ContentLicense: CC BY-SA 2.5

Title: JQuery not keyword

Body:
$("li a").click(function() {
    $(this).parent().css({ width: 160 });
    $("li").unbind('mouseenter mouseleave');
    $("#Container").css({ width: 200 }).animate({ width: 700 }, 1000);
});

I wanna set width 120 for all li's except current(this).

Thanks

Body:
You can try

    $(this).parent().siblings().css({ width: 160 })

Working sample here


问:
Error while building APK Android Studio 2.2.3
I am trying to generate a signed APK to test my app on a physical device. The app was working functionally before I tried to add the Google AdMob banner ad to my app. I keep getting this error:

```<code>Error:Execution failed for task ':app:transformClassesWithDexForRelease'.
com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzkf;
</code>```

Here is my build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.coolappsforall.fartboard"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 2
        versionName "1.0.1"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false;
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.gms:play-services-ads:11.6.0'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'

    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-appindexing:8.4.0'
}
</code>```

Not exactly sure what is causing the problem, if anyone knows, or if you need anything else, please let me know.

Thank you very much for your time and assistance in this matter.

答:
This error happens when you have some classes that are overlapping from different libraries. Try to add this:</p>

```<code>compile 'com.android.support:multidex:1.0.1'
</code>```

Body:
I am trying to generate a signed APK to test my app on a physical device. The app was working functionally before I tried to add the Google AdMob banner ad to my app. I keep getting this error:

Error:Execution failed for task ':app:transformClassesWithDexForRelease'.
com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzkf;

Here is my build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.coolappsforall.fartboard"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 2
        versionName "1.0.1"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false;
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.gms:play-services-ads:11.6.0'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'

    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-appindexing:8.4.0'
}

Not exactly sure what is causing the problem, if anyone knows, or if you need anything else, please let me know.

Thank you very much for your time and assistance in this matter.

Body:
This error happens when you have some classes that are overlapping from different libraries. Try to add this:

compile 'com.android.support:multidex:1.0.1'


问:
Codeigniter timespan does not work properly
My code like below :

```<code>$post_date = '2017-11-15 21:04:31';
$now = new DateTime();
$units = 7;
echo timespan($post_date, $now, $units);
</code>```

It return me this :

asked 47 Years, 10 Months, 2 Weeks, 1 Day, 23 Hours, 53 Minutes

where's 47 years coming from?

UPDATE

I want to calculate the difference between active time now since he has in the $post_date. For example $post_date = '2017-11-15 21:04:31'; it's should be 1 day, 8 hours, 9 minutes since he was posted.

how can I fix it?

答:
Epoctime time starts at 1st January 1970 midnight so your function is returning timespan from that date.

47 years passed since 1970.

Clarify what you want to achieve so we can help better.

Body:
My code like below :

$post_date = '2017-11-15 21:04:31';
$now = new DateTime();
$units = 7;
echo timespan($post_date, $now, $units);

It return me this :

asked 47 Years, 10 Months, 2 Weeks, 1 Day, 23 Hours, 53 Minutes

where's 47 years coming from?

UPDATE

I want to calculate the difference between active time now since he has in the $post_date. For example $post_date = '2017-11-15 21:04:31'; it's should be 1 day, 8 hours, 9 minutes since he was posted.

how can I fix it?


问:
Pair items in two lists
i have two lists:

```<code>foo = ['learn.py', 'work.py','entertain.py','else']
bar = ['A.learn.py', '3.entertain.py','&work.py']
</code>```

The result i want is

```<code>('learn.py', 'A.learn.py'), ('work.py', '&work.py'),
('entertain.py','3.entertain.py'), ('else','else')]
</code>```

Here follows my codes:

```<code>zoo = []
for j in bar:
    for i in foo:
        if i in j:
            zoo.append((i,j))
In [3]: zoo
Out[3]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]
</code>```

or,

```<code>zoo = []
for i in foo:
    for j in bar:
        if i in j:
            zoo.append((i,j))
In [5]: zoo
Out[5]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]
</code>```

How to solve such a problem?

答:
You can do this by using the string endswith() method to check for matches and an else: on inner for j in bar: loop to handle the situation when no matches are found:

```<code>foo = ['learn.py', 'work.py', 'entertain.py', 'else']
bar = ['A.learn.py', '3.entertain.py', '&work.py']

zoo = []
for i in foo:
    for j in bar:
        if j.endswith(i):  # Match?
            zoo.append((i, j))
            break
    else:
        zoo.append((i, i))

print(zoo)
</code>```

Output:

[('learn.py', 'A.learn.py'), ('work.py', '&work.py'), ('entertain.py', '3.entertain.py'), ('else', 'else')]
```

Title: Pair items in two lists

Body:
i have two lists:

foo = ['learn.py', 'work.py','entertain.py','else']
bar = ['A.learn.py', '3.entertain.py','&work.py']

The result i want is

('learn.py', 'A.learn.py'), ('work.py', '&work.py'),
('entertain.py','3.entertain.py'), ('else','else')]

Here follows my codes:

zoo = []
for j in bar:
    for i in foo:
        if i in j:
            zoo.append((i,j))
In [3]: zoo
Out[3]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]

or,

zoo = []
for i in foo:
    for j in bar:
        if i in j:
            zoo.append((i,j))
In [5]: zoo
Out[5]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]

How to solve such a problem?

Body:
You can do this by using the string endswith() method to check for matches and an else: on inner for j in bar: loop to handle the situation when no matches are found:

foo = ['learn.py', 'work.py', 'entertain.py', 'else']
bar = ['A.learn.py', '3.entertain.py', '&work.py']

zoo = []
for i in foo:
    for j in bar:
        if j.endswith(i):  # Match?
            zoo.append((i, j))
            break
    else:
        zoo.append((i, i))

print(zoo)

Output:

[('learn.py', 'A.learn.py'), ('work.py', '&work.py'), ('entertain.py', '3.entertain.py'), ('else', 'else')]


问:
How can I make .change() fire when the text changes without using input from a keyboard?
I am using the jQuery.change() method and it works fine if I actually change something via the keyboard. Meaning to say that if I type something in the <input type="text"> field on my HTML page, then I change a character I mouse out the .change() method fires.

However, the problem now is that I am changing the text in the <input type="text"> via jQuery itself and now the .change() doesn't fire when the text changes cause it's not via an input keyboard. I have already tried various methods, but it doesn't seem to work. It only works when I do a change via keyboard inputs.

How can I make .change() fire when the text changes without using input from a keyboard?

This is the HTML part:

```<code><label for="AddLongitude">*Longitude: </label>
<label id="Add_Long_Label" style="color:red"></label>
<input type="text" id="AddLongitude" name="Add_ServiceCompany"
    placeholder="Tap on the map" maxlength="18" data-clear-btn="true"  readonly/>

<label for="AddLatitude">*Latitude: </label>
<label id="Add_Lat_Label" style="color:red"></label>
<input type="text" id="AddLatitude" name="Add_ServiceCompany"
    placeholder="Tap on the map" maxlength="18" data-clear-btn="true" readonly/>
</code>```

This is the jQuery part:

```<code>$("#AddLongitude").change(function () {
            if ($("#AddLongitude").val() == "") {
                $("#Add_Long_Label").text("This field is mandatory.");
                $("#Add_Lat_Label").text("This field is mandatory.");
            }
            else {
                $("#Add_Long_Label").text("");
                $("#Add_Lat_Label").text("");
            }
        });
</code>```

This is the part where the value changes:

```<code>$("#AddLongitude").val(e.latlng.lng);
$("#AddLatitude").val(e.latlng.lat);
</code>```

where e.latlng.lng or e.latlng.lat is the variable holding the values to be written.

答:
You have to trigger change() function manually after changing the value since it is not an user input. change() method fire only user changed the value.</p>

```<code>$("#AddLongitude").val(e.latlng.lng).change();
$("#AddLatitude").val(e.latlng.lat).change();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using the jQuery.change() method and it works fine if I actually change something via the keyboard. Meaning to say that if I type something in the <input type="text"> field on my HTML page, then I change a character I mouse out the .change() method fires.

However, the problem now is that I am changing the text in the <input type="text"> via jQuery itself and now the .change() doesn't fire when the text changes cause it's not via an input keyboard. I have already tried various methods, but it doesn't seem to work. It only works when I do a change via keyboard inputs.

How can I make .change() fire when the text changes without using input from a keyboard?

This is the HTML part:

*Longitude:

<input type="text" id="AddLongitude" name="Add_ServiceCompany"
    placeholder="Tap on the map" maxlength="18" data-clear-btn="true"  readonly/>

*Latitude:

<input type="text" id="AddLatitude" name="Add_ServiceCompany"
    placeholder="Tap on the map" maxlength="18" data-clear-btn="true" readonly/>

This is the jQuery part:

$("#AddLongitude").change(function () {
            if ($("#AddLongitude").val() == "") {
                $("#Add_Long_Label").text("This field is mandatory.");
                $("#Add_Lat_Label").text("This field is mandatory.");
            }
            else {
                $("#Add_Long_Label").text("");
                $("#Add_Lat_Label").text("");
            }
        });

This is the part where the value changes:

$("#AddLongitude").val(e.latlng.lng);
$("#AddLatitude").val(e.latlng.lat);

where e.latlng.lng or e.latlng.lat is the variable holding the values to be written.

Body:
You have to trigger change() function manually after changing the value since it is not an user input. change() method fire only user changed the value.

$("#AddLongitude").val(e.latlng.lng).change();
$("#AddLatitude").val(e.latlng.lat).change();


答:
df.show() shows only content.

e.g.

```<code>df.show()
Out[11]:
+----+-------+
| age|   name|
+----+-------+
|null|Michael|
|  30|   Andy|
|  19| Justin|
+----+-------+
</code>```

df.collect() shows content and structure/metadata.e.g.

```<code>df.collect()
Out[11]:
[Row(age=None, name=u'Michael'),
Row(age=30, name=u'Andy'),
Row(age=19, name=u'Justin')]
</code>```

df.take(some number) can be used to shows content and structure/metadata for a limited number of rows for a very large dataset. note it flattens out the data and shows in a single row.

e.g. to see only first two rows of the dataframe

```<code>df.take(2)
Out[13]:
[Row(age=None, name=u'Michael'), Row(age=30, name=u'Andy')]
</code>```

Title: Spark: Difference between collect(), take() and show() outputs after conversion toDF

Body:
I am using Spark 1.5.

I have a column of 30 ids which I am loading as integers from a database:

val numsRDD = sqlContext
     .table(constants.SOURCE_DB + "." + IDS)
     .select("id")
     .distinct
     .map(row=>row.getInt(0))

This is the output of numsRDD:

numsRDD.collect.foreach(println(_))

643761
30673603
30736590
30773400
30832624
31104189
31598495
31723487
32776244
32801792
32879386
32981901
33469224
34213505
34709608
37136455
37260344
37471301
37573190
37578690
37582274
37600896
37608984
37616677
37618105
37644500
37647770
37648497
37720353
37741608

Right next, I want to produce all combinations of 3 for those ids then save each combination as a tuple of the form: < tripletID: String, triplet: Array(Int)> and convert it into a dataframe, which I do as follows:

// |combinationsDF| = 4060 combinations
val combinationsDF = sc
  .parallelize(numsRDD
     .collect
     .combinations(3)
     .toArray
     .map(row => row.sorted)
     .map(row => (
        List(row(0), row(1), row(2)).mkString(","),
        List(row(0), row(1), row(2)).toArray)))
  .toDF("tripletID","triplet")

As soon as I do that I try to print some of the combinationsDF's contents just to make sure that everything is the way it should be. So I try this:

combinationsDF.show

which returns:

+--------------------+--------------------+
|           tripletID|             triplet|
+--------------------+--------------------+
|,37136455,3758227...|[32776244, 371364...|
|,37136455,3761667...|[32776244, 371364...|
|,32776244,3713645...|[31723487, 327762...|
|,37136455,3757869...|[32776244, 371364...|
|,32776244,3713645...|[31598495, 327762...|
|,37136455,3760089...|[32776244, 371364...|
|,37136455,3764849...|[32776244, 371364...|
|,37136455,3764450...|[32776244, 371364...|
|,37136455,3747130...|[32776244, 371364...|
|,32981901,3713645...|[32776244, 329819...|
|,37136455,3761810...|[32776244, 371364...|
|,34213505,3713645...|[32776244, 342135...|
|,37136455,3726034...|[32776244, 371364...|
|,37136455,3772035...|[32776244, 371364...|
|2776244,37136455...|[643761, 32776244...|
|,37136455,3764777...|[32776244, 371364...|
|,37136455,3760898...|[32776244, 371364...|
|,32879386,3713645...|[32776244, 328793...|
|,32776244,3713645...|[31104189, 327762...|
|,32776244,3713645...|[30736590, 327762...|
+--------------------+--------------------+
only showing top 20 rows

As it is evident, the first element of every tripletID is missing. So, just to be 100% sure I use take(20) as follows:

combinationsDF.take(20).foreach(println(_))

which returns a more detailed representation as per below:

[,37136455,37582274,WrappedArray(32776244, 37136455, 37582274)]
[,37136455,37616677,WrappedArray(32776244, 37136455, 37616677)]
[,32776244,37136455,WrappedArray(31723487, 32776244, 37136455)]
[,37136455,37578690,WrappedArray(32776244, 37136455, 37578690)]
[,32776244,37136455,WrappedArray(31598495, 32776244, 37136455)]
[,37136455,37600896,WrappedArray(32776244, 37136455, 37600896)]
[,37136455,37648497,WrappedArray(32776244, 37136455, 37648497)]
[,37136455,37644500,WrappedArray(32776244, 37136455, 37644500)]
[,37136455,37471301,WrappedArray(32776244, 37136455, 37471301)]
[,32981901,37136455,WrappedArray(32776244, 32981901, 37136455)]
[,37136455,37618105,WrappedArray(32776244, 37136455, 37618105)]
[,34213505,37136455,WrappedArray(32776244, 34213505, 37136455)]
[,37136455,37260344,WrappedArray(32776244, 37136455, 37260344)]
[,37136455,37720353,WrappedArray(32776244, 37136455, 37720353)]
[2776244,37136455,WrappedArray(643761, 32776244, 37136455)]
[,37136455,37647770,WrappedArray(32776244, 37136455, 37647770)]
[,37136455,37608984,WrappedArray(32776244, 37136455, 37608984)]
[,32879386,37136455,WrappedArray(32776244, 32879386, 37136455)]
[,32776244,37136455,WrappedArray(31104189, 32776244, 37136455)]
[,32776244,37136455,WrappedArray(30736590, 32776244, 37136455)]

So now I am sure that the first id from tripletID is somehow for whatever reason deprecated. But still, if I try to use collect instead of take(20):

combinationsDF.collect.foreach(println(_))

everything goes back to being fine again (!!!):

[32776244,37136455,37582274,WrappedArray(32776244, 37136455, 37582274)]
[32776244,37136455,37616677,WrappedArray(32776244, 37136455, 37616677)]
[31723487,32776244,37136455,WrappedArray(31723487, 32776244, 37136455)]
[32776244,37136455,37578690,WrappedArray(32776244, 37136455, 37578690)]
[31598495,32776244,37136455,WrappedArray(31598495, 32776244, 37136455)]
[32776244,37136455,37600896,WrappedArray(32776244, 37136455, 37600896)]
[32776244,37136455,37648497,WrappedArray(32776244, 37136455, 37648497)]
[32776244,37136455,37644500,WrappedArray(32776244, 37136455, 37644500)]
[32776244,37136455,37471301,WrappedArray(32776244, 37136455, 37471301)]
[32776244,32981901,37136455,WrappedArray(32776244, 32981901, 37136455)]
[32776244,37136455,37618105,WrappedArray(32776244, 37136455, 37618105)]
[32776244,34213505,37136455,WrappedArray(32776244, 34213505, 37136455)]
[32776244,37136455,37260344,WrappedArray(32776244, 37136455, 37260344)]
[32776244,37136455,37720353,WrappedArray(32776244, 37136455, 37720353)]
[643761,32776244,37136455,WrappedArray(643761, 32776244, 37136455)]
[32776244,37136455,37647770,WrappedArray(32776244, 37136455, 37647770)]
[32776244,37136455,37608984,WrappedArray(32776244, 37136455, 37608984)]
[32776244,32879386,37136455,WrappedArray(32776244, 32879386, 37136455)]
[31104189,32776244,37136455,WrappedArray(31104189, 32776244, 37136455)]
[30736590,32776244,37136455,WrappedArray(30736590, 32776244, 37136455)]
...

1. I have exhaustively queried the steps just before I parallelize the array of combinations into an RDD and everything is ok.
 2. I have also printed the output right after parallelize is applied and again everything is ok.
 3. The problem appears to be related with the conversion of the numsRDD to a DF and despite my best efforts I cannot deal with it.
 4. I was also incapable of reproducing the problem with mock data using the same code snippet.

So first: What's causing this problem?
and second: How do I fix it?

Body:
df.show() shows only content.

e.g.

df.show()
Out[11]:
+----+-------+
| age|   name|
+----+-------+
|null|Michael|
|  30|   Andy|
|  19| Justin|
+----+-------+

df.collect() shows content and structure/metadata.e.g.

df.collect()
Out[11]:
[Row(age=None, name=u'Michael'),
Row(age=30, name=u'Andy'),
Row(age=19, name=u'Justin')]

df.take(some number) can be used to shows content and structure/metadata for a limited number of rows for a very large dataset. note it flattens out the data and shows in a single row.

e.g. to see only first two rows of the dataframe

df.take(2)
Out[13]:
[Row(age=None, name=u'Michael'), Row(age=30, name=u'Andy')]


问:
How do you create a new script in Greasemonkey 4?
Greasemonkey 4.0 has changed its interface, and for the life of me I cannot find any way to create a new script.

答:
Update: this was fixed in version 4.1 on 11-Dec-2017 (thankfully someone opened a bug for it)

It really seems like version 4.0 has no way to do this (and is very poorly documented) and so my workaround was just to install a simple/short script that seemed low risk and then just edit that script to make it my own.

I used this script (source code to check for safety) and clicked the green "Install" button near the upper right of the page:

This installed it into Greasemonkey.

After that, you can click on the Greasemonkey toolbar icon, click on the script you just added, and then click "Edit" in the submenu to edit it.


问:
LINQ to Entities does not recognize the method Boolean ContainsAny
Error

LINQ to Entities does not recognize the method 'Boolean
  ContainsAny(System.String, System.String[])' method, and this method
  cannot be translated into a store expression.

Code

```<code>var predicate = FilterClients(clientRequest);
clients = db.Clients.Where(predicate).Include(x => x.Organization)
.Include(x => x.Department).ToList();

private Expression<Func<Client, bool>> FilterClients(ClientRequest clientRequest)
{
   var predicate = PredicateBuilder.True<Client>();

   if (clientRequest.IsBySearchPatternFullName)
   {
      var searchPatternFullName = clientRequest.SearchPatternFullName.Trim();
      var matches = Regex.Matches(searchPatternFullName, @"\w+[^\s]*\w+|\w");
      var words = new List<string>();
      foreach (Match match in matches)
      {
         var word = match.Value;
         words.Add(word);
      }
      var wordArray = words.ToArray();
      predicate = predicate.And(x => x.LastName.ContainsAny(wordArray) || x.FirstName.ContainsAny(wordArray) || x.MiddleName.ContainsAny(wordArray));
   }
   return predicate;
}
</code>```

There is similar question C# LINQ to Entities does not recognize the method 'Boolean'

But I would like to optimize this part somehow

```<code> predicate = predicate.And(x => x.LastName.ContainsAny(wordArray) || x.FirstName.ContainsAny(wordArray) || x.MiddleName.ContainsAny(wordArray));
</code>```

Any clue people?

答:
Oh! I just did it!</p>

```<code>foreach (Match match in matches)
{
   var word = match.Value;
   predicate = predicate.And(x => x.LastName.Contains(word) || x.FirstName.Contains(word) || x.MiddleName.Contains(word));
}
</code>```

Body:
Error

LINQ to Entities does not recognize the method 'Boolean
  ContainsAny(System.String, System.String[])' method, and this method
  cannot be translated into a store expression.

Code

var predicate = FilterClients(clientRequest);
clients = db.Clients.Where(predicate).Include(x => x.Organization)
.Include(x => x.Department).ToList();

private Expression<Func<Client, bool>> FilterClients(ClientRequest clientRequest)
{
   var predicate = PredicateBuilder.True<Client>();

   if (clientRequest.IsBySearchPatternFullName)
   {
      var searchPatternFullName = clientRequest.SearchPatternFullName.Trim();
      var matches = Regex.Matches(searchPatternFullName, @"\w+[^\s]*\w+|\w");
      var words = new List<string>();
      foreach (Match match in matches)
      {
         var word = match.Value;
         words.Add(word);
      }
      var wordArray = words.ToArray();
      predicate = predicate.And(x => x.LastName.ContainsAny(wordArray) || x.FirstName.ContainsAny(wordArray) || x.MiddleName.ContainsAny(wordArray));
   }
   return predicate;
}

There is similar question C# LINQ to Entities does not recognize the method 'Boolean'

But I would like to optimize this part somehow

 predicate = predicate.And(x => x.LastName.ContainsAny(wordArray) || x.FirstName.ContainsAny(wordArray) || x.MiddleName.ContainsAny(wordArray));

Any clue people?

Body:
Oh! I just did it!

foreach (Match match in matches)
{
   var word = match.Value;
   predicate = predicate.And(x => x.LastName.Contains(word) || x.FirstName.Contains(word) || x.MiddleName.Contains(word));
}


问:
Identity Generator in Hibernate with Sybase
I am using hibernate 3.5 with Sybase ASE database.I have a primary key PK1 in my table Table.
I used the select generator class for my primary key generation.

```<code><id name="pk1" type="java.math.BigInteger">
            <column name="PK_ID" />
              <generator class="select">
                  <param name="key">unique</param>
              </generator>
</id>
</code>```

I have one more class which uses the PK_ID as foreign key but not a primary key.I have kept the mapping for it as,

```<code><property name="PK_ID1" type="java.math.BigInteger">
            <column name="SHIP_EVENT_ID" length="23" not-null="false" />
</property>
</code>```

When I use identity generator this seems to work fine.But when I change it to select generator.It shows me constraint violation exception.Although the new value is being generated and set to the pojo class for the second table.

Please Help!

Regards,
Dwarak

答: With an engine like ASE in the back end, it is not a good idea to use some OO front end to do your DDL changes.  Sure, this is a bug in the front end, but this is not the only one. More important you have access to only about 5% of Sybase functionality. Why don't use the Sybase Client softwarw that comes free with ASE.  SybaseCentralfor all your DDL and Administrative tasks  and InteractiveSQL for all your SQL tasks (DML, stored procs, testing SQL). It is not only more direct, it is much faster development time. Once you have the objects set up and tested, use whatever front end you like to execute commands (either stored procs or tested SQL) against those objects.

Body:
I am using hibernate 3.5 with Sybase ASE database.I have a primary key PK1 in my table Table.
I used the select generator class for my primary key generation.

<id name="pk1" type="java.math.BigInteger">
            <column name="PK_ID" />
              <generator class="select">
                  <param name="key">unique</param>
              </generator>
</id>

I have one more class which uses the PK_ID as foreign key but not a primary key.I have kept the mapping for it as,

<property name="PK_ID1" type="java.math.BigInteger">
            <column name="SHIP_EVENT_ID" length="23" not-null="false" />
</property>

When I use identity generator this seems to work fine.But when I change it to select generator.It shows me constraint violation exception.Although the new value is being generated and set to the pojo class for the second table.

Please Help!

Regards,
Dwarak


问:
How to count number of ways to parenthesize boolean expression string to evaluate to desired result
Straight out of CTCI, 8.14: Given a boolean expression consisting of the symbols 0 (false), 1 (true), & (AND), | (OR), and ^(XOR), and a desired boolean result value result, implement a function to count the number of ways of parenthesizing the expression such that it evaluates to result.

I'm attempting a brute force approach that calculates every single possible combo, if matches desired result, add it to an array(combos) and return that result length. It seems to work for most expressions, but not the 2nd example given. What do I seem to be missing?

```<code>function countEval(s, goalBool, combos = []) {
    // on first call make s into array since theyre easier to work with
    if (!(s instanceof Array)) {
        // and turn 1s and 0s into their bool equivalent
        s = s.split('').map((item) => {
            if (item === '1') {
                return true;
            } else if (item === '0'){
                return false;
            } else {
                return item;
            }
        });
    }
    if (s.length === 1 && s[0] === goalBool) {
        combos.push(s[0]); // can be anything really
    } else {
        for (let i = 0; i < s.length - 2; i = i + 2) {
            // splice out the next 3 items
            const args = s.splice(i, 3);
            // pass them to see what they evaluate too
            const result = evalHelper(args[0], args[1], args[2]);
            // splice that result back in s array
            s.splice(i, 0, result);
            // pass that array to recurse
            countEval(s, goalBool, combos);
            // remove said item that was just put in
            s.splice(i, 1);
            // and reset array for next iteration
            s.splice(i, 0, ...args);
        }
    }
    return combos.length;
}

function evalHelper(a, op, b) {
    if (op === '|') {
        return a || b;
    } else if (op === '&') {
        return a && b;
    } else if (op === '^') {
        return a !== b;
    }
}
</code>```

With the 2 examples given it works for the first one, but not the second...

```<code>console.log(countEval('1^0|0|1', false)); // 2, correct
console.log(countEval('0&0&0&1^1|0', true)); // 30, should be 10!?!?!
</code>```

答:
The Bug

Your program is not taking into account overlap.

Example

Consider your program when s = '1|1|1|1'.

In one of the depth-first search iterations, your algorithm will make the reduction s = (1|1)|1|1. Then in a deeper recursive level in the same search, your algorithm will make the reduction s = (1|1)|(1|1). Now s is fully reduced, so you increment the length of combos.

In a different depth-first search iteration, your algorithm will first make the reduction s = 1|1|(1|1). Then in a deeper recursive level in the same search, your algorithm will make the reduction s = (1|1)|(1|1). Now s is fully reduced, so you increment the length of combos.

Notice that for both cases, s was parenthesized the same way, thus your program does not take into account overlap.

A Better Solution

A lot of times, when a problem is asking the number of ways something can be done, this is usually a big indicator that dynamic programming could be a potential solution. The recurrence relation to this problem is a bit tricky.

We just need to pick a "principle" operator, then determine the number of ways the left and right side could evaluate to true or false. Then, based on the "principle" operator and the goal boolean, we can derive a formula for the number of ways the expression could evaluate to the goal boolean given that the operator we picked was the "principle" operator.

Code

```<code>function ways(expr, res, i, j, cache, spaces) {
  if (i == j) {
    return parseInt(expr[i]) == res ? 1 : 0;
  } else if (!([i, j, res] in cache)) {
    var ans = 0;
    for (var k = i + 1; k < j; k += 2) {
      var op = expr[k];
      var leftTrue = ways(expr, 1, i, k - 1, cache);
      var leftFalse = ways(expr, 0, i, k - 1, cache);
      var rightTrue = ways(expr, 1, k + 1, j, cache);
      var rightFalse = ways(expr, 0, k + 1, j, cache);
      if (op == '|') {
        if (res) {
          ans += leftTrue * rightTrue + leftTrue * rightFalse + leftFalse * rightTrue;
        } else {
          ans += leftFalse * rightFalse;
        }
      } else if (op == '^') {
        if (res) {
          ans += leftTrue * rightFalse + leftFalse * rightTrue;
        } else {
          ans += leftTrue * rightTrue + leftFalse * rightFalse;
        }
      } else if (op == '&') {
        if (res) {
          ans += leftTrue * rightTrue;
        } else {
          ans += leftFalse * rightFalse + leftTrue * rightFalse + leftFalse * rightTrue;
        }
      }
    }
    cache[[i, j, res]] = ans;
  }
  return cache[[i, j, res]];
}

function countEval(expr, res) {
  return ways(expr, res ? 1 : 0, 0, expr.length - 1, {});
}
</code>```

Body:
Straight out of CTCI, 8.14: Given a boolean expression consisting of the symbols 0 (false), 1 (true), & (AND), | (OR), and ^(XOR), and a desired boolean result value result, implement a function to count the number of ways of parenthesizing the expression such that it evaluates to result.

I'm attempting a brute force approach that calculates every single possible combo, if matches desired result, add it to an array(combos) and return that result length. It seems to work for most expressions, but not the 2nd example given. What do I seem to be missing?

function countEval(s, goalBool, combos = []) {
    // on first call make s into array since theyre easier to work with
    if (!(s instanceof Array)) {
        // and turn 1s and 0s into their bool equivalent
        s = s.split('').map((item) => {
            if (item === '1') {
                return true;
            } else if (item === '0'){
                return false;
            } else {
                return item;
            }
        });
    }
    if (s.length === 1 && s[0] === goalBool) {
        combos.push(s[0]); // can be anything really
    } else {
        for (let i = 0; i < s.length - 2; i = i + 2) {
            // splice out the next 3 items
            const args = s.splice(i, 3);
            // pass them to see what they evaluate too
            const result = evalHelper(args[0], args[1], args[2]);
            // splice that result back in s array
            s.splice(i, 0, result);
            // pass that array to recurse
            countEval(s, goalBool, combos);
            // remove said item that was just put in
            s.splice(i, 1);
            // and reset array for next iteration
            s.splice(i, 0, ...args);
        }
    }
    return combos.length;
}

function evalHelper(a, op, b) {
    if (op === '|') {
        return a || b;
    } else if (op === '&') {
        return a && b;
    } else if (op === '^') {
        return a !== b;
    }
}

With the 2 examples given it works for the first one, but not the second...

console.log(countEval('1^0|0|1', false)); // 2, correct
console.log(countEval('0&0&0&1^1|0', true)); // 30, should be 10!?!?!

Body:
The Bug

Your program is not taking into account overlap.

Example

Consider your program when s = '1|1|1|1'.

In one of the depth-first search iterations, your algorithm will make the reduction s = (1|1)|1|1. Then in a deeper recursive level in the same search, your algorithm will make the reduction s = (1|1)|(1|1). Now s is fully reduced, so you increment the length of combos.

In a different depth-first search iteration, your algorithm will first make the reduction s = 1|1|(1|1). Then in a deeper recursive level in the same search, your algorithm will make the reduction s = (1|1)|(1|1). Now s is fully reduced, so you increment the length of combos.

Notice that for both cases, s was parenthesized the same way, thus your program does not take into account overlap.

A Better Solution

A lot of times, when a problem is asking the number of ways something can be done, this is usually a big indicator that dynamic programming could be a potential solution. The recurrence relation to this problem is a bit tricky.

We just need to pick a "principle" operator, then determine the number of ways the left and right side could evaluate to true or false. Then, based on the "principle" operator and the goal boolean, we can derive a formula for the number of ways the expression could evaluate to the goal boolean given that the operator we picked was the "principle" operator.

Code

function ways(expr, res, i, j, cache, spaces) {
  if (i == j) {
    return parseInt(expr[i]) == res ? 1 : 0;
  } else if (!([i, j, res] in cache)) {
    var ans = 0;
    for (var k = i + 1; k < j; k += 2) {
      var op = expr[k];
      var leftTrue = ways(expr, 1, i, k - 1, cache);
      var leftFalse = ways(expr, 0, i, k - 1, cache);
      var rightTrue = ways(expr, 1, k + 1, j, cache);
      var rightFalse = ways(expr, 0, k + 1, j, cache);
      if (op == '|') {
        if (res) {
          ans += leftTrue * rightTrue + leftTrue * rightFalse + leftFalse * rightTrue;
        } else {
          ans += leftFalse * rightFalse;
        }
      } else if (op == '^') {
        if (res) {
          ans += leftTrue * rightFalse + leftFalse * rightTrue;
        } else {
          ans += leftTrue * rightTrue + leftFalse * rightFalse;
        }
      } else if (op == '&') {
        if (res) {
          ans += leftTrue * rightTrue;
        } else {
          ans += leftFalse * rightFalse + leftTrue * rightFalse + leftFalse * rightTrue;
        }
      }
    }
    cache[[i, j, res]] = ans;
  }
  return cache[[i, j, res]];
}

function countEval(expr, res) {
  return ways(expr, res ? 1 : 0, 0, expr.length - 1, {});
}


问:
Does users of PWS have the role of Admin?
I want to know if when you create an account in Pivotal you have the role of an Admin.

Here are the roles according to cloud foundry documentation https://docs.cloudfoundry.org/concepts/roles.html

答: When you create an account, you will be OrgManager of the org that is created for you, as well as SpaceManager and SpaceDeveloper of the default space created.


问:
Any way to change the color of drawing pen in OneNote?

Greeting All,

I am trying to find a way or any API which can change the color of the pen brush in OneNote.
The purpose is to let users can use custom colors to draw or to text.

The existing official doc seems cannot provide the answer. Please suggest if any.

Thanks in advance!

答:
Onenote is really abysmal, as far as I'm aware, there is no API supported to do anything like setting pen colour and thickness.
Though it has been asked for many times.
I just want the Radial Menu back!
In the desktop Onenote you can't even change a favourite pen colour or thickness without deleting and readding it.

The best you can do is create a keyboard script to go through the menus from 'Alt'.


问:
Make single column into multiple columns based on another column
I have a tidy data frame, with one term and topic per row. It looks like this:

```<code>num_topic, term
1, blue
1, green
2, dog
2, cat
</code>```

I would like to arrange each topic in a separate column, for human readability

```<code>topic1, topic2
blue, dog
green, cat
</code>```

This seems pretty intuitive, but I cannot figure out how to do it. It is not the same as the linked question, because there are no unique identifiers for each term. There are just lists of terms for each topic.

答:
How about the following.
Note this assumes that entries per num_topic group are "in order", i.e. blue belongs to dog, green belongs to cat, and so on.

```<code>df <- read.csv(text =
    "num_topic,term
    1,blue
    1,green
    2,dog
    2,cat");

df <- as.data.frame(sapply(split(df, df$num_topic), function(x) x$term));
df;
#       1    2
#1   blue  dog
#2  green  cat
</code>```

Explanation: Split on num_topic and bind columns term together.

Body:
I have a tidy data frame, with one term and topic per row. It looks like this:

num_topic, term
1, blue
1, green
2, dog
2, cat

I would like to arrange each topic in a separate column, for human readability

topic1, topic2
blue, dog
green, cat

This seems pretty intuitive, but I cannot figure out how to do it. It is not the same as the linked question, because there are no unique identifiers for each term. There are just lists of terms for each topic.

Body:
How about the following.
Note this assumes that entries per num_topic group are "in order", i.e. blue belongs to dog, green belongs to cat, and so on.

df <- read.csv(text =
    "num_topic,term
    1,blue
    1,green
    2,dog
    2,cat");

df <- as.data.frame(sapply(split(df, df$num_topic), function(x) x$term));
df;
#       1    2
#1   blue  dog
#2  green  cat

Explanation: Split on num_topic and bind columns term together.


问:
How to remove a Gitlab project?
I have created several repositories in GitLab. One of those was for testing purposes and has some commits and branches. I want to delete or remove this repository. How can I do this? </p>

答:
To remove a project, you have to be the owner of this project, or the administrator of gitlab. Otherwise you can only see "rename project" but no "remove project".

NOTE THAT: the creator project is NOT always the owner of the project. If the project is in a project-group, and the project-group is created by another one, then the owner is the creator of the project-group by default.

You can find the owner's name of the project in the page Settings -> Members.

Title: How to remove a Gitlab project?


答:
You can query against list of word in following way :</p>

```<code> predicate = predicate.And(x => wordArray.Contains(x.LastName) || wordArray.Contains(x.FirstName) || wordArray.Contains(x.MiddleName));
</code>```

Title: LINQ to Entities does not recognize the method Boolean ContainsAny

Body:
You can query against list of word in following way :

 predicate = predicate.And(x => wordArray.Contains(x.LastName) || wordArray.Contains(x.FirstName) || wordArray.Contains(x.MiddleName));


问:
How to set list count in growing list/table title in ui5?
In sap.m.Table/List, I defined a title

```<code>            <Title
                id="lineItemsHeader"
                text="{tableView>/lineItemListTitle}"/>
</code>```

Get count logic is in updateFinished function,

```<code>        onListUpdateFinished : function (oEvent) {
            var sTitle,
                iTotalItems = oEvent.getParameter("total"),
                oViewModel = this.getModel("tableView");

            // only update the counter if the length is final
            if (this._oTable.getBinding("items").isLengthFinal()) {
                if (iTotalItems) {
                    sTitle = this.getResourceBundle().getText("DETAIL_TABLE_HEADING_COUNT", [iTotalItems]);
                } else {
                    //Display 'Line Items' instead of 'Line items (0)'
                    sTitle = this.getResourceBundle().getText("DETAIL_TABLE_HEADING");
                }
                oViewModel.setProperty("/lineItemListTitle", sTitle);
            }
        }
</code>```

But if I set growing="true", when data is more than 20 items(default growing threshold), this._oTable.getBinding("items").isLengthFinal() will return false.

So I came up an idea, use $count directly to get count data.

```<code>                this._oModel.read("/ControlSet/$count", {
                        success: this._updateListItemCount.bind(this),
                        error: this.errorCallback.bind(this)
                });
</code>```

But the question came up when I try to get count of filter result, I know the call is /ControlSet/$count?$filter=(substringof('a',name) or substringof('a',description)), and I've already maintain a filter state:

```<code>            this._oListFilterState = {
                aSearch : [new Filter...]
            };
</code>```

Did not find any clue in https://sapui5.hana.ondemand.com/#/api/sap.ui.model.Filter

Any suggestion? Try do fix this in an elegant/ui5 way, better not use        $.get

答:
Fixed by :</p>

```<code>            this._oListFilterState = {
                aSearch : undefined
            };

        onUpdateFinished : function () {
            this.byId("pullToRefresh").hide();

            if(this._oListFilterState.aSearch) {
                 this._oModel.read("/ControlSet/$count", {
                    filters: [this._oListFilterState.aSearch],
                    success: this._updateListItemCount.bind(this),
                    error: this.errorCallback.bind(this)
                });
            }else {
                this._oModel.read("/ControlSet/$count", {
                    success: this._updateListItemCount.bind(this),
                    error: this.errorCallback.bind(this)
                });
            }
        },
</code>```

Body:
In sap.m.Table/List, I defined a title

            <Title
                id="lineItemsHeader"
                text="{tableView>/lineItemListTitle}"/>

Get count logic is in updateFinished function,

        onListUpdateFinished : function (oEvent) {
            var sTitle,
                iTotalItems = oEvent.getParameter("total"),
                oViewModel = this.getModel("tableView");

            // only update the counter if the length is final
            if (this._oTable.getBinding("items").isLengthFinal()) {
                if (iTotalItems) {
                    sTitle = this.getResourceBundle().getText("DETAIL_TABLE_HEADING_COUNT", [iTotalItems]);
                } else {
                    //Display 'Line Items' instead of 'Line items (0)'
                    sTitle = this.getResourceBundle().getText("DETAIL_TABLE_HEADING");
                }
                oViewModel.setProperty("/lineItemListTitle", sTitle);
            }
        }

But if I set growing="true", when data is more than 20 items(default growing threshold), this._oTable.getBinding("items").isLengthFinal() will return false.

So I came up an idea, use $count directly to get count data.

                this._oModel.read("/ControlSet/$count", {
                        success: this._updateListItemCount.bind(this),
                        error: this.errorCallback.bind(this)
                });

But the question came up when I try to get count of filter result, I know the call is /ControlSet/$count?$filter=(substringof('a',name) or substringof('a',description)), and I've already maintain a filter state:

            this._oListFilterState = {
                aSearch : [new Filter...]
            };

Did not find any clue in https://sapui5.hana.ondemand.com/#/api/sap.ui.model.Filter

Any suggestion? Try do fix this in an elegant/ui5 way, better not use        $.get

Body:
Fixed by :

            this._oListFilterState = {
                aSearch : undefined
            };

        onUpdateFinished : function () {
            this.byId("pullToRefresh").hide();

            if(this._oListFilterState.aSearch) {
                 this._oModel.read("/ControlSet/$count", {
                    filters: [this._oListFilterState.aSearch],
                    success: this._updateListItemCount.bind(this),
                    error: this.errorCallback.bind(this)
                });
            }else {
                this._oModel.read("/ControlSet/$count", {
                    success: this._updateListItemCount.bind(this),
                    error: this.errorCallback.bind(this)
                });
            }
        },


问:
Is it possible to pass parameters from server package to client package using RPC?
I have a GWT project in which I have a web interface programmed in the client package and the code that connects to a remote server in the server package. The interface presents certain parameters to the user and he/she has to select them and make a query to the remote server.

I have passed the user-selected parameters to the server package using a RPC call, but I would like to know if it is possible to to the inverse operation, because I would like to draw the data retrieved from the server on an embedded Google map (retrieved data is georeferenced) and all this drawing things is done in the client package with pure-GWT classes.

What do you think? Is it possible? Any idea? Do I have to draw the georeferenced data on the client side?

Thanks to all.

答: you can use jwebscoket or websocket to do RRPC(Reverse RPC).More info is available at http://jwebsocket.org/. </p>


问:
the common language runtime was unable to set the breakpoint
This is actually another part of this question.

Error settings breakpoints but only on some lines while debugging

I'm remote debugging a CRM 2011 plugin in vs 2010.

I'n one of my source files I can set breakpoint all throughout the code except in a few places.

When I try to set a breakpoint I get this error
"The following breakpoint cannot be set:" and "The Common Language Runtime was unable to set the breakpoint."

```<code>protected override void ExecutePlugin()
{
    SetStateResponse response = new SetStateResponse(); // Breakpoint works

    // Message switch
    switch (_crmMessage) // Breakpoint error
    {
        case CrmPluginMessageEnum.Create:

        Entity pimage = null; // Breakpoint error
        if (_context.PostEntityImages.ContainsKey("postcreate")) // Breakpoint works
            pimage = _context.PostEntityImages["postcreate"]; // Breakpoint error

        break; // Breakpoint error
        }
} // Breakpoint error
</code>```

UPDATE
Also, in the modules window it shows the dll as Optimized: No User Code: Yes Symbol Status: Symbols Loaded

答: I got this error when start run debugging the project, and I solve it by Clean All Project and Rebuild All Project, after rebuild the error disappear.</p>

Body:
This is actually another part of this question.

Error settings breakpoints but only on some lines while debugging

I'm remote debugging a CRM 2011 plugin in vs 2010.

I'n one of my source files I can set breakpoint all throughout the code except in a few places.

When I try to set a breakpoint I get this error
"The following breakpoint cannot be set:" and "The Common Language Runtime was unable to set the breakpoint."

protected override void ExecutePlugin()
{
    SetStateResponse response = new SetStateResponse(); // Breakpoint works

    // Message switch
    switch (_crmMessage) // Breakpoint error
    {
        case CrmPluginMessageEnum.Create:

        Entity pimage = null; // Breakpoint error
        if (_context.PostEntityImages.ContainsKey("postcreate")) // Breakpoint works
            pimage = _context.PostEntityImages["postcreate"]; // Breakpoint error

        break; // Breakpoint error
        }
} // Breakpoint error

UPDATE
Also, in the modules window it shows the dll as Optimized: No User Code: Yes Symbol Status: Symbols Loaded


问:
Add copy constructor based on template parameters
I have a container-like class, that I would like to be move-only if the underlying type is move-only, but copyable otherwise. To make things simple, let's assume copyability is determined by a single bool template parameter:

```<code>template<bool IsCopyable>
struct Foo
{
    Foo();
    Foo(const Foo&);    // only include this when IsCopyable is true
    Foo(Foo&&);

    Foo& operator=(const Foo&);  // only when IsCopyable
    Foo& operator=(Foo&&);
};
</code>```

Now, I can't just SFINAE the copy ctor away, because that requires making it templated and a templated function can't be a copy ctor. Also, I can't just do a static_assert() within the copy ctor. Although this will catch erroneous uses of the copy ctor, it also makes the class inherently copy constructible from the outside (the std::is_copy_constructible type trait will yield true).

By the way, an unfortunate requirement is that it needs to compile in VC++ 2012, so I can't use fancy expression SFINAE, inheriting ctors, defaulted/deleted functions or constexpr if (nevertheless, if you have a neat solution for C++17 I'd still like to hear it :))

The obvious method is to use template specialization. I'd rather not go this route, because in reality Foo has quite a lot of functionality and I don't like to repeat myself. Nevertheless, this seems my only option, and I can implement some code sharing using a base class, like so:

```<code>// Base functionality
template<bool IsCopyable>
struct FooBase
{
    FooBase();

    // move ctor and assignment can go here
    FooBase(FooBase&&);
    FooBase& operator=(FooBase&&);

    // some generic conversion ctor and assignment that I happen to need
    template<class T> FooBase(T&& t);
    template<class T> FooBase& operator=(T&&);

    // ... all sorts of functionality and datamembers
};

// Foo<false>
template<bool IsCopyable>
struct Foo : FooBase<IsCopyable>
{
    // can't use inheriting ctors in VS 2012, wrap the calls manually:
    Foo() { }
    Foo(Foo&& other) : FooBase<IsCopyable>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<IsCopyable>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<IsCopyable>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<IsCopyable>::operator=(std::forward<T>(t));
        return *this;
    }
};

// Foo<true>
template<>
struct Foo<true> : FooBase<true>
{
    // add these
    Foo(const Foo&);
    Foo& operator=(const Foo&);

    // wrapping calls because of VS 2012:
    Foo() { }
    Foo(Foo&& other) : FooBase<true>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<true>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<true>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<true>::operator=(std::forward<T>(t));
        return *this;
    }
};
</code>```

It's still a bit verbose. Fortunately it gets cleaner once you can use inheriting ctors and defaulted functions. Nevertheless, I was hoping there is a simpler way, ideally by not using a base class.

答:
I don't know if can work with your VC++2012 but... if I remember correctly, there is a method that i think a little better that inheriting from FooBase.

A sort of auto-inheritance.

You can declare the struct

```<code>template <bool>
struct Bar;
</code>```

and specialize the true version with all constructor/operators

```<code>template <>
struct Bar<true>
 {
   Bar ()
    { std::cout << "Bar ()" << std::endl; };

   Bar (Bar &&)
    { std::cout << "Bar (Bar &&)" << std::endl; }

   Bar (Bar const &)
    { std::cout << "Bar (Bar const &)" << std::endl; }

   Bar & operator= (Bar &&)
    { std::cout << "operator= (Bar &&)" << std::endl; return *this; }

   Bar & operator= (Bar const &)
    { std::cout << "operator= (Bar const &)" << std::endl; return *this; }
 };
</code>```

Now you can specialize the false version inheriting from Bar<true>, confirming (= default) what you want and deleting (= delete) what do you don't want; something like

```<code>template <>
struct Bar<false> : public Bar<true>
 {
   using Bar<true>::Bar;

   // confirmed constructor/operators
   Bar ()                   = default;
   Bar (Bar &&)             = default;
   Bar & operator= (Bar &&) = default;

   // deleted constructor/operators
   Bar (Bar const &)             = delete;
   Bar & operator= (Bar const &) = delete;
 };
</code>```

The following is a full working example

```<code>#include <iostream>

template <bool>
struct Bar;

template <>
struct Bar<true>
 {
   Bar ()
    { std::cout << "Bar ()" << std::endl; };

   Bar (Bar &&)
    { std::cout << "Bar (Bar &&)" << std::endl; }

   Bar (Bar const &)
    { std::cout << "Bar (Bar const &)" << std::endl; }

   Bar & operator= (Bar &&)
    { std::cout << "operator= (Bar &&)" << std::endl; return *this; }

   Bar & operator= (Bar const &)
    { std::cout << "operator= (Bar const &)" << std::endl; return *this; }
 };

template <>
struct Bar<false> : public Bar<true>
 {
   using Bar<true>::Bar;

   // confirmed constructor/operators
   Bar ()                   = default;
   Bar (Bar &&)             = default;
   Bar & operator= (Bar &&) = default;

   // deleted constructor/operators
   Bar (Bar const &)             = delete;
   Bar & operator= (Bar const &) = delete;
 };

int main ()
 {
   Bar<true>   bt1;
   Bar<false>  bf1;

   auto bt2 = bt1;
   // auto bf2 = bf1; compilation error (copy constructor deleted)

   auto bt3 = std::move(bt1);
   auto bf3 = std::move(bf1);

   Bar<true>   bt4;
   Bar<false>  bf4;

   bt4 = bt3;
   // bf4 = bf3; compilation error (operator= (Bar const &) deleted)

   bt3 = std::move(bt4);
   bf3 = std::move(bf4);
 }
</code>```

Body:
I have a container-like class, that I would like to be move-only if the underlying type is move-only, but copyable otherwise. To make things simple, let's assume copyability is determined by a single bool template parameter:

template<bool IsCopyable>
struct Foo
{
    Foo();
    Foo(const Foo&);    // only include this when IsCopyable is true
    Foo(Foo&&);

    Foo& operator=(const Foo&);  // only when IsCopyable
    Foo& operator=(Foo&&);
};

Now, I can't just SFINAE the copy ctor away, because that requires making it templated and a templated function can't be a copy ctor. Also, I can't just do a static_assert() within the copy ctor. Although this will catch erroneous uses of the copy ctor, it also makes the class inherently copy constructible from the outside (the std::is_copy_constructible type trait will yield true).

By the way, an unfortunate requirement is that it needs to compile in VC++ 2012, so I can't use fancy expression SFINAE, inheriting ctors, defaulted/deleted functions or constexpr if (nevertheless, if you have a neat solution for C++17 I'd still like to hear it :))

The obvious method is to use template specialization. I'd rather not go this route, because in reality Foo has quite a lot of functionality and I don't like to repeat myself. Nevertheless, this seems my only option, and I can implement some code sharing using a base class, like so:

// Base functionality
template<bool IsCopyable>
struct FooBase
{
    FooBase();

    // move ctor and assignment can go here
    FooBase(FooBase&&);
    FooBase& operator=(FooBase&&);

    // some generic conversion ctor and assignment that I happen to need
    template<class T> FooBase(T&& t);
    template<class T> FooBase& operator=(T&&);

    // ... all sorts of functionality and datamembers
};

// Foo<false>
template<bool IsCopyable>
struct Foo : FooBase<IsCopyable>
{
    // can't use inheriting ctors in VS 2012, wrap the calls manually:
    Foo() { }
    Foo(Foo&& other) : FooBase<IsCopyable>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<IsCopyable>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<IsCopyable>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<IsCopyable>::operator=(std::forward<T>(t));
        return *this;
    }
};

// Foo<true>
template<>
struct Foo<true> : FooBase<true>
{
    // add these
    Foo(const Foo&);
    Foo& operator=(const Foo&);

    // wrapping calls because of VS 2012:
    Foo() { }
    Foo(Foo&& other) : FooBase<true>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<true>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<true>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<true>::operator=(std::forward<T>(t));
        return *this;
    }
};

It's still a bit verbose. Fortunately it gets cleaner once you can use inheriting ctors and defaulted functions. Nevertheless, I was hoping there is a simpler way, ideally by not using a base class.

Body:
I don't know if can work with your VC++2012 but... if I remember correctly, there is a method that i think a little better that inheriting from FooBase.

A sort of auto-inheritance.

You can declare the struct

template <bool>
struct Bar;

and specialize the true version with all constructor/operators

template <>
struct Bar<true>
 {
   Bar ()
    { std::cout << "Bar ()" << std::endl; };

   Bar (Bar &&)
    { std::cout << "Bar (Bar &&)" << std::endl; }

   Bar (Bar const &)
    { std::cout << "Bar (Bar const &)" << std::endl; }

   Bar & operator= (Bar &&)
    { std::cout << "operator= (Bar &&)" << std::endl; return *this; }

   Bar & operator= (Bar const &)
    { std::cout << "operator= (Bar const &)" << std::endl; return *this; }
 };

Now you can specialize the false version inheriting from Bar<true>, confirming (= default) what you want and deleting (= delete) what do you don't want; something like

template <>
struct Bar<false> : public Bar<true>
 {
   using Bar<true>::Bar;

   // confirmed constructor/operators
   Bar ()                   = default;
   Bar (Bar &&)             = default;
   Bar & operator= (Bar &&) = default;

   // deleted constructor/operators
   Bar (Bar const &)             = delete;
   Bar & operator= (Bar const &) = delete;
 };

The following is a full working example

#include <iostream>

template <bool>
struct Bar;

template <>
struct Bar<true>
 {
   Bar ()
    { std::cout << "Bar ()" << std::endl; };

   Bar (Bar &&)
    { std::cout << "Bar (Bar &&)" << std::endl; }

   Bar (Bar const &)
    { std::cout << "Bar (Bar const &)" << std::endl; }

   Bar & operator= (Bar &&)
    { std::cout << "operator= (Bar &&)" << std::endl; return *this; }

   Bar & operator= (Bar const &)
    { std::cout << "operator= (Bar const &)" << std::endl; return *this; }
 };

template <>
struct Bar<false> : public Bar<true>
 {
   using Bar<true>::Bar;

   // confirmed constructor/operators
   Bar ()                   = default;
   Bar (Bar &&)             = default;
   Bar & operator= (Bar &&) = default;

   // deleted constructor/operators
   Bar (Bar const &)             = delete;
   Bar & operator= (Bar const &) = delete;
 };

int main ()
 {
   Bar<true>   bt1;
   Bar<false>  bf1;

   auto bt2 = bt1;
   // auto bf2 = bf1; compilation error (copy constructor deleted)

   auto bt3 = std::move(bt1);
   auto bf3 = std::move(bf1);

   Bar<true>   bt4;
   Bar<false>  bf4;

   bt4 = bt3;
   // bf4 = bf3; compilation error (operator= (Bar const &) deleted)

   bt3 = std::move(bt4);
   bf3 = std::move(bf4);
 }


问:
Java password checker with strings
Been fighting with this for awhile, still new to java and really struggling with this assignment. We're meant to make a password checker assignment that checks if 2 entered passwords are the same. Then also check them against some "requirements" such as password length of at least 8 characters, one special character, one upper and one lower case, no repeating characters more than 3 times consecutively, (ie "aaa").

Any input or criticism is very much appreciated and thank you in advance.

```<code>import java.util.Scanner;

/**
 *
 * @author Jonot
 */
public class Passwords {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //Asks and records users inputted passwords
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter your password");
        String password = input.nextLine();
        System.out.println("Please re-enter your password");
        String passwordCheck = input.nextLine();
        //boolean to check if the inputted passwords meets requirements set below
        boolean check;
        check = isConfirmed(password);
        while (!password.equals(passwordCheck) || (!check)) {
            System.out.println("The password you entered is invalid");
            System.out.println("Please try again");
            password = input.nextLine();
            System.out.println("please re-enter");
            passwordCheck = input.nextLine();

            check = isConfirmed(password);
            //String password = input.nextLine();
            //check = isConfirmed(password);

            //if passwords meets boolean requirements,
            if (isConfirmed(password)) {
                //this will print out. Doesn't work right now.
                System.out.println("password is valid");
            } else {
            }

        }

    }
    //Boolean variables and they're set requirements. Do not work right now.
    //Not sure why.

    public static boolean isConfirmed(String password) {
        Boolean leastOneUpperCase = false;
        Boolean leastOneLowerCase = false;
        Boolean leastOneDigit = false;
        Boolean oneSpecialCharacter = false;

        if (password.length() < 8) {
            return false;
        }

        for (int i = 0; i < password.length(); i++) {
            if (Character.isUpperCase(password.charAt {i

                    ));

                    {
              leastOneUpperCase = true;
                }
                else if (Character.isLowerCase(password.charAt(i)));
                {
                    leastOneLowerCase = true;
                }
                else if (Character.isDigit(password.charAt(i)));
                {
                    leastOneDigit = true;
                }
            }
            return (leastOneUpperCase && leastOneLowerCase && leastOneDigit);

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

答:
There was one primary problem, in the isConfirmed method.  The return statement with the variables in it was inside the loop that checked each character.  So, the return statement was executed after the first character was checked and therefore always returned false, since two out of the three booleans would still be false.

Also, looked like some semicolons were out of place in your charAt checks.  Not sure if that's a formatting error introduced during your post.  Finally, I thought the code would be more readable by pulling the current character being checked into a variable and using that instead of calling charAt a bunch of times.

Here's the revised code:

```<code>import java.util.Scanner;

/**
 *
 * @author Jonot
 */
public class Passwords {

    /**
     * @param args the command line arguments
     */
    public static final void main(String[] args) {
        //Asks and records users inputted passwords
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter your password");
        String password = input.nextLine();
        System.out.println("Please re-enter your password");
        String passwordCheck = input.nextLine();
        //boolean to check if the inputted passwords meets requirements set below
        boolean check;
        check = isConfirmed(password);
        while (!password.equals(passwordCheck) || (!check)) {
            System.out.println("The password you entered is invalid");
            System.out.println("Please try again");
            password = input.nextLine();
            System.out.println("please re-enter");
            passwordCheck = input.nextLine();

            check = isConfirmed(password);
            //String password = input.nextLine();
            //check = isConfirmed(password);

            //if passwords meets boolean requirements,
            if (isConfirmed(password)) {
                //this will print out. Doesn't work right now.
                System.out.println("password is valid");
            } else {
            }

        }

    }
    //Boolean variables and they're set requirements. Do not work right now.
    //Not sure why.

    public static boolean isConfirmed(String password) {
        Boolean leastOneUpperCase = false;
        Boolean leastOneLowerCase = false;
        Boolean leastOneDigit = false;
        Boolean oneSpecialCharacter = false;

        if (password.length() < 8) {
            return false;
        }

        for (int i = 0; i < password.length(); i++) {
            char c = password.charAt(i);

            if (Character.isUpperCase(c))
            {
                leastOneUpperCase = true;
            }
            else if (Character.isLowerCase(c))
            {
                leastOneLowerCase = true;
            }
            else if (Character.isDigit(c))
            {
                leastOneDigit = true;
            }
                System.out.println("password is valid");
            } else {
            }

        }

    }
    //Boolean variables and they're set requirements. Do not work right now.
    //Not sure why.

    public static boolean isConfirmed(String password) {
        Boolean leastOneUpperCase = false;
        Boolean leastOneLowerCase = false;
        Boolean leastOneDigit = false;
        Boolean oneSpecialCharacter = false;

        if (password.length() < 8) {
            return false;
        }

        for (int i = 0; i < password.length(); i++) {
            char c = password.charAt(i);

            if (Character.isUpperCase(c))
            {
                leastOneUpperCase = true;
            }
            else if (Character.isLowerCase(c))
            {
                leastOneLowerCase = true;
            }
            else if (Character.isDigit(c))
            {
                leastOneDigit = true;
            }
        }

        return (leastOneUpperCase && leastOneLowerCase && leastOneDigit);
    }
}
</code>```

Title: Java password checker with strings

Body:
Been fighting with this for awhile, still new to java and really struggling with this assignment. We're meant to make a password checker assignment that checks if 2 entered passwords are the same. Then also check them against some "requirements" such as password length of at least 8 characters, one special character, one upper and one lower case, no repeating characters more than 3 times consecutively, (ie "aaa").

Any input or criticism is very much appreciated and thank you in advance.

import java.util.Scanner;

/**
 *
 * @author Jonot
 */
public class Passwords {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //Asks and records users inputted passwords
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter your password");
        String password = input.nextLine();
        System.out.println("Please re-enter your password");
        String passwordCheck = input.nextLine();
        //boolean to check if the inputted passwords meets requirements set below
        boolean check;
        check = isConfirmed(password);
        while (!password.equals(passwordCheck) || (!check)) {
            System.out.println("The password you entered is invalid");
            System.out.println("Please try again");
            password = input.nextLine();
            System.out.println("please re-enter");
            passwordCheck = input.nextLine();

            check = isConfirmed(password);
            //String password = input.nextLine();
            //check = isConfirmed(password);

            //if passwords meets boolean requirements,
            if (isConfirmed(password)) {
                //this will print out. Doesn't work right now.
                System.out.println("password is valid");
            } else {
            }

        }

    }
    //Boolean variables and they're set requirements. Do not work right now.
    //Not sure why.

    public static boolean isConfirmed(String password) {
        Boolean leastOneUpperCase = false;
        Boolean leastOneLowerCase = false;
        Boolean leastOneDigit = false;
        Boolean oneSpecialCharacter = false;

        if (password.length() < 8) {
            return false;
        }

        for (int i = 0; i < password.length(); i++) {
            if (Character.isUpperCase(password.charAt {i

                    ));

                    {
              leastOneUpperCase = true;
                }
                else if (Character.isLowerCase(password.charAt(i)));
                {
                    leastOneLowerCase = true;
                }
                else if (Character.isDigit(password.charAt(i)));
                {
                    leastOneDigit = true;
                }
            }
            return (leastOneUpperCase && leastOneLowerCase && leastOneDigit);

        }
        return false;
    }

Body:
There was one primary problem, in the isConfirmed method.  The return statement with the variables in it was inside the loop that checked each character.  So, the return statement was executed after the first character was checked and therefore always returned false, since two out of the three booleans would still be false.

Also, looked like some semicolons were out of place in your charAt checks.  Not sure if that's a formatting error introduced during your post.  Finally, I thought the code would be more readable by pulling the current character being checked into a variable and using that instead of calling charAt a bunch of times.

Here's the revised code:

import java.util.Scanner;

/**
 *
 * @author Jonot
 */
public class Passwords {

    /**
     * @param args the command line arguments
     */
    public static final void main(String[] args) {
        //Asks and records users inputted passwords
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter your password");
        String password = input.nextLine();
        System.out.println("Please re-enter your password");
        String passwordCheck = input.nextLine();
        //boolean to check if the inputted passwords meets requirements set below
        boolean check;
        check = isConfirmed(password);
        while (!password.equals(passwordCheck) || (!check)) {
            System.out.println("The password you entered is invalid");
            System.out.println("Please try again");
            password = input.nextLine();
            System.out.println("please re-enter");
            passwordCheck = input.nextLine();

            check = isConfirmed(password);
            //String password = input.nextLine();
            //check = isConfirmed(password);

            //if passwords meets boolean requirements,
            if (isConfirmed(password)) {
                //this will print out. Doesn't work right now.
                System.out.println("password is valid");
            } else {
            }

        }

    }
    //Boolean variables and they're set requirements. Do not work right now.
    //Not sure why.

    public static boolean isConfirmed(String password) {
        Boolean leastOneUpperCase = false;
        Boolean leastOneLowerCase = false;
        Boolean leastOneDigit = false;
        Boolean oneSpecialCharacter = false;

        if (password.length() < 8) {
            return false;
        }

        for (int i = 0; i < password.length(); i++) {
            char c = password.charAt(i);

            if (Character.isUpperCase(c))
            {
                leastOneUpperCase = true;
            }
            else if (Character.isLowerCase(c))
            {
                leastOneLowerCase = true;
            }
            else if (Character.isDigit(c))
            {
                leastOneDigit = true;
            }
                System.out.println("password is valid");
            } else {
            }

        }

    }
    //Boolean variables and they're set requirements. Do not work right now.
    //Not sure why.

    public static boolean isConfirmed(String password) {
        Boolean leastOneUpperCase = false;
        Boolean leastOneLowerCase = false;
        Boolean leastOneDigit = false;
        Boolean oneSpecialCharacter = false;

        if (password.length() < 8) {
            return false;
        }

        for (int i = 0; i < password.length(); i++) {
            char c = password.charAt(i);

            if (Character.isUpperCase(c))
            {
                leastOneUpperCase = true;
            }
            else if (Character.isLowerCase(c))
            {
                leastOneLowerCase = true;
            }
            else if (Character.isDigit(c))
            {
                leastOneDigit = true;
            }
        }

        return (leastOneUpperCase && leastOneLowerCase && leastOneDigit);
    }
}