问:
wordpress -override number of posts in loop
See: http://jasondaydesign.com/portfolio

Also, for this custom loop, how would I override the number of posts as set by WP Settings > Reading > show 10 posts.

thanks!

```<code><?php
/*
Template Name: Portfolio
*/
?>

<?php get_header(); ?>

<ul id="portfolio-filter">
  <li><a href="#all">All</a></li>
  <li><a href="#web-design">Web</a></li>
  <li><a href="#logo-and-branding-design">Logo</a></li>
  <li><a href="#print-and-graphic-design">Print</a></li>
  <li><a href="#sculpture">Sculpture </a></li>
  <li><a href="#for-sale">For Sale </a></li>
 </ul>

        <ul id="portfolio-list">
        <?php query_posts('cat=5&showposts='); ?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<!-- ** store the category slugs for each post in a variable $catSlug ** -->
  <li class="<?php foreach((get_the_category()) as $category ) { echo $category->category_nicename . ' '; } ?>all">

 <!-- ** This is my own plugin to get the thumbnail from the post - you may use some custom field you have to get the image. ** -->
                    <a href='<?php the_permalink() ?>' title='<?php the_title(); ?>'><img src='<?php woo_image('width='.$woo_options['woo_thumb_w'].'&height='.$woo_options['woo_thumb_h'].'&class=thumbnail '.$woo_options['woo_thumb_align']); ?>' alt='<?php the_title(); ?>' /></a>

                    <p><?php the_title(); ?></p>
     <p><?php the_excerpt(); ?></p>

                </li>
            <? endwhile; ?>
        <? endif; ?>
  <?php wp_reset_query(); ?>
        </ul>

<?php get_footer(); ?>
</code>```

答:
```<code><?php
/*
Template Name: Portfolio
*/
?>

<?php get_header(); ?>

<ul id="portfolio-filter">
  <li><a href="#all">All</a></li>
  <li><a href="#web-design">Web</a></li>
  <li><a href="#logo-and-branding-design">Logo</a></li>
  <li><a href="#print-and-graphic-design">Print</a></li>
  <li><a href="#sculpture">Sculpture </a></li>
  <li><a href="#for-sale">For Sale </a></li>
 </ul>

    <ul id="portfolio-list">

    <?php $show_posts = get_posts( array( 'numberposts' => 'xx', 'category' => '5' ) ); ?>

    <?php foreach($show_posts as $posts) : the_post(); ?>

        <li class="<?php foreach((get_the_category()) as $category ) { echo $category->category_nicename . ' '; } ?>all">

        <!-- ** This is my own plugin to get the thumbnail from the post - you may use some custom field you have to get the image. ** -->
        <a href='<?php the_permalink() ?>' title='<?php the_title(); ?>'><img src='<?php woo_image('width='.$woo_options['woo_thumb_w'].'&height='.$woo_options['woo_thumb_h'].'&class=thumbnail '.$woo_options['woo_thumb_align']); ?>' alt='<?php the_title(); ?>' /></a>

        <p><?php the_title(); ?></p>
        <p><?php the_excerpt(); ?></p>

        </li>

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

Body:
See: http://jasondaydesign.com/portfolio

Also, for this custom loop, how would I override the number of posts as set by WP Settings > Reading > show 10 posts.

thanks!

<?php
/*
Template Name: Portfolio
*/
?>

<?php get_header(); ?>

All

Web

Logo

Print

Sculpture

For Sale

        <?php query_posts('cat=5&showposts='); ?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

  <li class="<?php foreach((get_the_category()) as $category ) { echo $category->category_nicename . ' '; } ?>all">

                    <a href='<?php the_permalink() ?>' title='<?php the_title(); ?>'><img src='<?php woo_image('width='.$woo_options['woo_thumb_w'].'&height='.$woo_options['woo_thumb_h'].'&class=thumbnail '.$woo_options['woo_thumb_align']); ?>' alt='<?php the_title(); ?>' />

<?php the_title(); ?>

<?php the_excerpt(); ?>

            <? endwhile; ?>
        <? endif; ?>
  <?php wp_reset_query(); ?>

<?php get_footer(); ?>


来源: stackexchange

问:
Owl carousel i cannot add 2 caroousel in 2 rows
I want o add two owl-carousel in one page HTML
example  row 1 .  =  owl-carousel1
         row 2 .  =  owl-carosoul2

```<code>                <div class="item">
                <!-- Item Image -->
                <div class="item-image"><img src="assets/img/image1.jpg" class="img-medium" alt="Ceo"></div>
                <!-- Item Image End -->

                <!-- Item Description -->
                <div class="item-desc">
                    <a class="link" href="#">
                        <div class="desc-content">
                            <span class="yellow">CEO</span>
                            <span class="title">Name Lastname</span>
                        </div>
                    </a>
                    <ul class="social-icons social-white nav-default clearfix">
                        <li><a href="https://www.facebook.com/#"><i class="fa fa-facebook"></i></a></li>
                        <li><a href="#"><i class="fa fa-twitter"></i></a></li>
                        <li><a href="#"><i class="fa fa-google"></i></a></li>
                    </ul>
                </div>
                <!-- Item Description End -->
            </div>
        <!-- Item List End -->
    </div>
</code>```

when i add example a new  it doesnt appear in the 2nd column ?
anybody help my is HTML

答:
here is a little bit code of  owl-team.js</p>

```<code>    $.fn.owlCarousel = function (options) {
    return this.each(function () {
        if ($(this).data("owl-init") === true) {
            return false;
        }
        $(this).data("owl-init", true);
        var carousel = Object.create(Carousel);
        carousel.init(options, this);
        $.data(this, "owlCarousel", carousel);
    });
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want o add two owl-carousel in one page HTML
example  row 1 .  =  owl-carousel1
         row 2 .  =  owl-carosoul2

                            CEO
                            Name Lastname

when i add example a new  it doesnt appear in the 2nd column ?
anybody help my is HTML

Body:
here is a little bit code of  owl-team.js

    $.fn.owlCarousel = function (options) {
    return this.each(function () {
        if ($(this).data("owl-init") === true) {
            return false;
        }
        $(this).data("owl-init", true);
        var carousel = Object.create(Carousel);
        carousel.init(options, this);
        $.data(this, "owlCarousel", carousel);
    });
};


问:
Angular 2 change the style of a button onClick
I am having a lot of trouble trying to update the styling for a button on click.

First, here is the original markup:

```<code><button class="btn btn-add" (click)="handleButtonClick(id)">
  Add<i class="fa fa-plus-circle"></i>
</button>
</code>```

On clicking the button, I am trying to:

Change the class from "btn btn-add" to "btn btn-remove"

Change the  to

How can I do this the angular 2 way?  Right now I just added a boolean and flip that, and show different templates based on the value.  However, it seems there should be a way to handle this through some function right? In the documentation it says you can use strings delimited by a space for multiple classes, but I am not sure how to do that.

答:
To toggle the button's text too:

```<code><button class="btn" [ngClass]="{'btn-add': !clicked, 'btn-remove': clicked}" (click)="clicked = !clicked">
    {{clicked ? 'Remove' : 'Add'}}
    <i class="fa" [ngClass]="{'fa-plus-circle': !clicked, 'fa-minus-circle': clicked}"></i>
</button>
</code>```

Body:
I am having a lot of trouble trying to update the styling for a button on click.

First, here is the original markup:

<button class="btn btn-add" (click)="handleButtonClick(id)">
  Add
</button>

On clicking the button, I am trying to:

Change the class from "btn btn-add" to "btn btn-remove"

Change the  to

How can I do this the angular 2 way?  Right now I just added a boolean and flip that, and show different templates based on the value.  However, it seems there should be a way to handle this through some function right? In the documentation it says you can use strings delimited by a space for multiple classes, but I am not sure how to do that.

Body:
To toggle the button's text too:

<button class="btn" [ngClass]="{'btn-add': !clicked, 'btn-remove': clicked}" (click)="clicked = !clicked">
    {{clicked ? 'Remove' : 'Add'}}
    <i class="fa" [ngClass]="{'fa-plus-circle': !clicked, 'fa-minus-circle': clicked}"></i>
</button>


问:
How to use angularJs code inside of JSP file?
I am trying adding angular code inside of .jsp file but getting some error like :

"Multiple annotations found at this line:
    - Start tag of element
    - Undefined attribute name
     (ng-app)."

So can anyone help how to proceed with it !

答: Probably those errors are just from the html validator and can be ignored. I never used it but you could try a plugin like this https://github.com/angelozerr/angularjs-eclipse</p>


问:
MySQL: Get the difference between timestamps

Possible Duplicate:

  MySQL: how to get the difference between two timestamps in seconds

How can I get the difference in seconds (or any other unit) between two timestamps? If I use select NOW() - '2012-01-01 00:00:00' I get 20110121168303 which is wrong.

My favorite solution

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_timestampdiff

答:
UNIX_TIMESTAMP returns an offset number of seconds from epoch. Taking the difference between the two of these is in the unit Seconds.</p>

```<code>select UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP('2012-01-01 00:00:00')
</code>```

Body:
UNIX_TIMESTAMP returns an offset number of seconds from epoch. Taking the difference between the two of these is in the unit Seconds.

select UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP('2012-01-01 00:00:00')

ContentLicense: CC BY-SA 2.5


问:
how to zip a file having spaces in the filename in unix
Is there a way we can zip a file having spaces in the filename? I am actually working on a scenario. Any help on how to handle this is extremely useful. Thanks in advance.

I have a text file containing list of multiple filenames. The terrible part is the filenames consists of a space in the end of the file name.
Example: Text file - DMI.txt

data in DMI.txt

```<code>DMI1 .txt
DMI2 .txt
DMI3 .txt
</code>```

I need to zip each text file but the zip command is treating "DMI1" as 1 file and ".txt" as another file.

code

```<code>recdmi=$(cat $jobdir/import_dmi_hourly_file_list.txt)
while IFS= read -r recdmi
do
    echo $recdmi
    zip "$srcdir/\"${recdmi}\".zip" $srcdir/\"${recdmi}\"
    #mv "$srcdir/\"${recdmi}\".zip" $arcdir
    #rm $srcdir/\"${recdmi}\"
    echo "$srcdir/\"${recdmi}\".zip $srcdir/\"${recdmi}\""
done < $srcdir/import_dmi_hourly_file_list.txt
</code>```

The output error is

```<code>/home/nkoka/nk_dmi_partner_ingestion/"DMI_2017-11-20_10 .txt".zip /home/nkoka/nk_dmi_partner_ingestion/"DMI_2017-11-20_10 .txt"

zip warning: name not matched: /home/nkoka/nk_dmi_partner_ingestion/"DMI_2017-11-20_10

zip warning: name not matched: .txt"

zip error: Nothing to do! (/home/nkoka/nk_dmi_partner_ingestion/"DMI_2017-11-20_10 .txt".zip)
</code>```

答:
The escaped quotes are causing the quotes to be treated as literal parts of the filename. You don't need it.

```<code>zip "$srcdir/${recdmi}.zip" "$srcdir/${recdmi}"
</code>```

Also, the first line

```<code>recdmi=$(cat $jobdir/import_dmi_hourly_file_list.txt)
</code>```

is not needed, since you're immediately reassigning the variable with read -r recdmi.

Body:
Is there a way we can zip a file having spaces in the filename? I am actually working on a scenario. Any help on how to handle this is extremely useful. Thanks in advance.

I have a text file containing list of multiple filenames. The terrible part is the filenames consists of a space in the end of the file name.
Example: Text file - DMI.txt

data in DMI.txt

DMI1 .txt
DMI2 .txt
DMI3 .txt

I need to zip each text file but the zip command is treating "DMI1" as 1 file and ".txt" as another file.

code

recdmi=$(cat $jobdir/import_dmi_hourly_file_list.txt)
while IFS= read -r recdmi
do
    echo $recdmi
    zip "$srcdir/\"${recdmi}\".zip" $srcdir/\"${recdmi}\"
    #mv "$srcdir/\"${recdmi}\".zip" $arcdir
    #rm $srcdir/\"${recdmi}\"
    echo "$srcdir/\"${recdmi}\".zip $srcdir/\"${recdmi}\""
done < $srcdir/import_dmi_hourly_file_list.txt

The output error is

/home/nkoka/nk_dmi_partner_ingestion/"DMI_2017-11-20_10 .txt".zip /home/nkoka/nk_dmi_partner_ingestion/"DMI_2017-11-20_10 .txt"

zip warning: name not matched: /home/nkoka/nk_dmi_partner_ingestion/"DMI_2017-11-20_10

zip warning: name not matched: .txt"

zip error: Nothing to do! (/home/nkoka/nk_dmi_partner_ingestion/"DMI_2017-11-20_10 .txt".zip)

Body:
The escaped quotes are causing the quotes to be treated as literal parts of the filename. You don't need it.

zip "$srcdir/${recdmi}.zip" "$srcdir/${recdmi}"

Also, the first line

recdmi=$(cat $jobdir/import_dmi_hourly_file_list.txt)

is not needed, since you're immediately reassigning the variable with read -r recdmi.


问:
“Access is denied” on IE browser for browser.min.js in react.js
Screenshot of IE 1 ,Screenshot of IE 2 I am getting error in browser.min.js of Access denied on IE browser for browser.min.js in react.js.

IE gives me the error message "Access denied" while in every other browser I don't notice this behaviour. Since I have tried many things and still cannot imagine where the problem lies I'd like to ask you what you think the problem might be?

答:
IE has trouble with some of the babel es6 syntax, so the community has created polyfills to patch needed functionality.

Generally, adding a require('es6-promise').polyfill(); to my source code fixes that issue. You can seek out other polyfills if that one doesn't do the trick.


问:
Convert an integer to an array of digits
I try to convert an integer to an array. For example, 1234 to int[] arr = {1,2,3,4};.

I've written a function:

```<code>public static void convertInt2Array(int guess)  {
    String temp = Integer.toString(guess);
    String temp2;
    int temp3;
    int [] newGuess = new int[temp.length()];
    for(int i=0; i<=temp.length(); i++) {
        if (i!=temp.length()) {
            temp2 = temp.substring(i, i+1);
        } else {
            temp2 = temp.substring(i);
            //System.out.println(i);
        }
        temp3 =  Integer.parseInt(temp2);
        newGuess[i] = temp3;
    }

    for(int i=0; i<=newGuess.length; i++) {
        System.out.println(newGuess[i]);
    }
}
</code>```

But an exception is thrown:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:504)

at java.lang.Integer.parseInt(Integer.java:527)

at q4.test.convertInt2Array(test.java:28)

at q4.test.main(test.java:14)

Java Result: 1

How can I fix this?

答:
You can just do:

char[] digits = string.toCharArray();

And then you can evaluate the chars as integers.

For example:

```<code>char[] digits = "12345".toCharArray();
int digit = Character.getNumericValue(digits[0]);
System.out.println(digit); // Prints 1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to convert an integer to an array. For example, 1234 to int[] arr = {1,2,3,4};.

I've written a function:

public static void convertInt2Array(int guess)  {
    String temp = Integer.toString(guess);
    String temp2;
    int temp3;
    int [] newGuess = new int[temp.length()];
    for(int i=0; i<=temp.length(); i++) {
        if (i!=temp.length()) {
            temp2 = temp.substring(i, i+1);
        } else {
            temp2 = temp.substring(i);
            //System.out.println(i);
        }
        temp3 =  Integer.parseInt(temp2);
        newGuess[i] = temp3;
    }

    for(int i=0; i<=newGuess.length; i++) {
        System.out.println(newGuess[i]);
    }
}

But an exception is thrown:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:504)

at java.lang.Integer.parseInt(Integer.java:527)

at q4.test.convertInt2Array(test.java:28)

at q4.test.main(test.java:14)

Java Result: 1

How can I fix this?

Body:
You can just do:

char[] digits = string.toCharArray();

And then you can evaluate the chars as integers.

For example:

char[] digits = "12345".toCharArray();
int digit = Character.getNumericValue(digits[0]);
System.out.println(digit); // Prints 1


问:
Is it normal multiconfig is very slow to parse?
I have tried using the multiconfig setup for 6 machines but it is extremely slow, around 7 times slower.

I tested by just parsing (-p) one image for one machine on both setup.

Is it possible some optimizations were not done and the feature is not completely ready?

Thanks

答:
multiconfig allows the setups to run in parallel and the seventh setup is likely the "no multiconfig" setup which many people overlook when counting them.

multiconfig is not expected to generate parsing speed improvements, its designed to let you run multiple builds with parallelisation and a simple command. This is therefore not something which has been optimized or is planned to be optimized either, at least as things stand as that isn't an area where we can see optimizations we can make.


问:
Static Buttons in React VR
I understand how vrButtons work, but how would someone go about creating buttons that are overlayed onto the vr hud. Buttons that are static, and stay on the screen regardless of how the camera is oriented.</p>

答:
I want to step back a moment and think about this.

The main question would be, is this for VR view or are you just using a 3D view on a web-page without intending people to go into VR?

When you create something that, in VR, "always stays stationary" what you are doing is creating a floating object that the user can't shake off. It'll feel very, very strange in VR.

Worse, as they move their head around, the floating object will seem to penetrate other objects, depending on your precise headset and the optics. It'll be at a neutral distance (focal plane) and cause some focusing problems as well. This might trigger the vergence-accomodation sickness issue. (This is actually more of a fatigue issue than sickness, but YSMV - your stomach may vary).

It really is best to make a 3D UI when you are in a 3D world. It's hard, it really is - this is a field that entire PhD's have been granted in over the years. (VR is not, despite popular conception, new).

Sorry for the "non-answer answer" ... I hope this helps a little bit.

Title: Static Buttons in React VR


问:
Using linter from WSL (Ubuntu for Windows) in Visual Studio Code
I'm setting up a Python environment in VS Code and have already installed the plugin.

VSCode is suggesting that it can't run pylint:

However, pylint is installed in my local WSL (though not on Windows). If I click the Install Pylint button, the WSL terminal embedded in VSCode shows the following:

```<code>$ python -m pip install pylint
Requirement already satisfied: pylint in /home/mao/anaconda3/lib/python3.6/site-packages
</code>```

How do I get VS Code to use this installed pylint?

答:
Make sure that the Python interpreter you have selected for your workspace matches the one you want to have Pylint installed into (if you're running the latest version of the extension you can see it specified down in the status bar in the lower-left of your window). You can also set the python.pylint.pylintPath setting to point to the pylint command location explicitly.

Do realize, though, that as of at least version 0.8.0, there isn't official support for WSL in the Python extension (yet, although it is planned).

Body:
I'm setting up a Python environment in VS Code and have already installed the plugin.

VSCode is suggesting that it can't run pylint:

However, pylint is installed in my local WSL (though not on Windows). If I click the Install Pylint button, the WSL terminal embedded in VSCode shows the following:

$ python -m pip install pylint
Requirement already satisfied: pylint in /home/mao/anaconda3/lib/python3.6/site-packages

How do I get VS Code to use this installed pylint?


问:
Karma Uncaught RangeError: Maximum call stack size exceeded
I'm getting this error from Karma when trying to run grunt karma:debug:

```<code>11 11 2017 00:00:00.000:INFO [Chrome 62.0.3202 (Linux 0.0.0)]: Connected on socket /#AAAA-AAAAAAAAAAAAAAA with id 99999999
Chrome 61.0.0000 (Linux 0.0.0) ERROR
  Uncaught RangeError: Maximum call stack size exceeded
  at http://localhost:9876/context.html
Chrome 61.0.0000 (Linux 0.0.0) ERROR
  Uncaught RangeError: Maximum call stack size exceeded
  at http://localhost:9876/context.html
Chrome 61.0.0000 (Linux 0.0.0): Executed 0 of 0 ERROR (1.035 secs / 0 secs)
</code>```

What can be the cause? it started to happen overnight after a commit with some big JSON files. If I go back to the commit without the JSON files, the command starts working again.

答:
I found the problem in my karma.conf.js file:

```<code>config.set({
    ...
    files: [
        ...
        { pattern: "path/to/fixtures/**/*.json" },
        ...
    ]
</code>```

That line makes Karma include the JSON files inside the HTML page, and seems it had trouble with the amount of JSON files I was adding. The solution is to tell Karma to not include those files inside the HTML but to serve them as a WebServer:

```<code>config.set({
    ...
    files: [
        ...
        { pattern: "path/to/fixtures/**/*.json", included: false },
        ...
    ]
</code>```

Relevant documentation is here:

```<code>included
Type. Boolean
Default. true
Description. Should the files be included in the browser using
             <script> tag? Use false if you want to load them manually,
             eg. using Require.js.
</code>```

Body:
I'm getting this error from Karma when trying to run grunt karma:debug:

11 11 2017 00:00:00.000:INFO [Chrome 62.0.3202 (Linux 0.0.0)]: Connected on socket /#AAAA-AAAAAAAAAAAAAAA with id 99999999
Chrome 61.0.0000 (Linux 0.0.0) ERROR
  Uncaught RangeError: Maximum call stack size exceeded
  at http://localhost:9876/context.html
Chrome 61.0.0000 (Linux 0.0.0) ERROR
  Uncaught RangeError: Maximum call stack size exceeded
  at http://localhost:9876/context.html
Chrome 61.0.0000 (Linux 0.0.0): Executed 0 of 0 ERROR (1.035 secs / 0 secs)

What can be the cause? it started to happen overnight after a commit with some big JSON files. If I go back to the commit without the JSON files, the command starts working again.

Body:
I found the problem in my karma.conf.js file:

config.set({
    ...
    files: [
        ...
        { pattern: "path/to/fixtures/**/*.json" },
        ...
    ]

That line makes Karma include the JSON files inside the HTML page, and seems it had trouble with the amount of JSON files I was adding. The solution is to tell Karma to not include those files inside the HTML but to serve them as a WebServer:

config.set({
    ...
    files: [
        ...
        { pattern: "path/to/fixtures/**/*.json", included: false },
        ...
    ]

Relevant documentation is here:

included
Type. Boolean
Default. true
Description. Should the files be included in the browser using
             <script> tag? Use false if you want to load them manually,
             eg. using Require.js.


问:
HTML5 Video - Start video at certain time and play for x amount of time
I'm trying to create buttons that start my local video at a certain point in time and have it play for a certain duration. I've got it to play at a certain point but not sure how to let it play for only certain duration.

Here's the code.

HTML:

```<code><video id="myvideo" width="1000">
        <source src="video.mp4" type="video/mp4">
        Your browser does not support HTML5 video.
</video>
    <div>
        <p>
            <button id="playme">Play/Pause Video</button>
        </p>
        <p>
            <button id="jump">Jump to 4 seconds</button>
        </p>
        <p>
            <button id="jump2">Jump to 11 seconds</button>
        </p>
    </div>
</code>```

Javascript:

```<code>var myvideo = document.getElementById('myvideo'),
playbutton = document.getElementById('playme'),
jumplink = document.getElementById('jump'),
jumplink2 = document.getElementById('jump2');

jumplink.addEventListener("click", function (event) {
    event.preventDefault();
    myvideo.play();
    myvideo.pause();
    myvideo.currentTime = 4;
    myvideo.play();
}, false);

jumplink2.addEventListener("click", function (event) {
    event.preventDefault();
    myvideo.play();
    myvideo.pause();
    myvideo.currentTime = 11;
    myvideo.play();
}, false);

playbutton.addEventListener("click", function () {
    if (myvideo.paused) {
        myvideo.play();
    } else {
        myvideo.pause();
    }
}, false);
</code>```

答:
In order to achieve this you need to poll the video's currentTime property as it's playing, perhaps with something like this general code...

```<code>var button = document.getElementById('play')
var video = document.getElementById('video');
var startTime = 10;
var endTime = 20;

button.addEventListener('click', playVideo, !1);

function playVideo(e) {

    function checkTime() {
        if (video.currentTime >= endTime) {
           video.pause();
        } else {
           /* call checkTime every 1/10th
              second until endTime */
           setTimeout(checkTime, 100);
        }
    }

    video.currentTime = startTime;
    video.play();
    checkTime();
}
</code>```

UPDATE

Let's look at how you might implement this for your app.

You have two 'jump' buttons and a play button. When any of these buttons are activated you could call a single function which sets the start time and end time according to the HTML id of the clicked button.  Those values could them be passed into something like the function I've already outlined above.

To begin with, assign an event listener to each button...

```<code>var myvideo = document.getElementById('myvideo');

/* add the same event and
   handler function to each
   of the three buttons */
var buttons = ['playme','jump','jump2'];

buttons.forEach(function(bn) {
    document.getElementById(bn).addEventListener(
        'click', buttonEvents, !1
    );
});
</code>```

Here each of you three HTML buttons will call a buttonEvents() function when clicked.  That function might look something like this...

```<code>function buttonEvents(e) {
    /* get the id of the clicked button */
    var element_id = e.target.id;
    /* E.G. element_id = 'playme', 'jump', or 'jump2' */

    /* declare variables before setting them */
    var timeStart = 0;
    var timeEnd = 0;

    /* set start and end values depending
       on which button was clicked */
    switch(element_id) {
        case 'playme':
            /* example values... */
            timeStart = 0;
            timeEnd = 100;
            break;
        case 'jump':
            timeStart = 4;
            timeEnd = 12;
            break;
        case 'jump2':
            timeStart = 12;
            timeEnd = 24;
    }

    /* call 'playVideo()' */
    playVideo(timeStart, timeEnd);
}
</code>```

Combining your 'playbutton' function with the general function outlined above would give us something like this: a function that receives a start and end time as it's arguments and plays the video if it's paused or jumps to a new start time if it's playing...

```<code>function playVideo(startTime, endTime) {

    function checkTime() {
        if (myvideo.currentTime >= endTime) {
           myvideo.pause();
        } else {
           /* call checkTime every 1/10th
              second until endTime */
           setTimeout(checkTime, 100);
        }
    }

    /* stop if playing (otherwise ignored) */
    myvideo.pause();
    /* set video start time */
    myvideo.currentTime = startTime;
    /* play video */
    myvideo.play();
    /* check the current time and
       pause IF/WHEN endTime is reached */
    checkTime();
}
</code>```

Hope that helped.

Body:
I'm trying to create buttons that start my local video at a certain point in time and have it play for a certain duration. I've got it to play at a certain point but not sure how to let it play for only certain duration.

Here's the code.

HTML:

<video id="myvideo" width="1000">
        <source src="video.mp4" type="video/mp4">
        Your browser does not support HTML5 video.
</video>

            <button id="playme">Play/Pause Video</button>

            <button id="jump">Jump to 4 seconds</button>

            <button id="jump2">Jump to 11 seconds</button>

Javascript:

var myvideo = document.getElementById('myvideo'),
playbutton = document.getElementById('playme'),
jumplink = document.getElementById('jump'),
jumplink2 = document.getElementById('jump2');

jumplink.addEventListener("click", function (event) {
    event.preventDefault();
    myvideo.play();
    myvideo.pause();
    myvideo.currentTime = 4;
    myvideo.play();
}, false);

jumplink2.addEventListener("click", function (event) {
    event.preventDefault();
    myvideo.play();
    myvideo.pause();
    myvideo.currentTime = 11;
    myvideo.play();
}, false);

playbutton.addEventListener("click", function () {
    if (myvideo.paused) {
        myvideo.play();
    } else {
        myvideo.pause();
    }
}, false);

Body:
In order to achieve this you need to poll the video's currentTime property as it's playing, perhaps with something like this general code...

var button = document.getElementById('play')
var video = document.getElementById('video');
var startTime = 10;
var endTime = 20;

button.addEventListener('click', playVideo, !1);

function playVideo(e) {

    function checkTime() {
        if (video.currentTime >= endTime) {
           video.pause();
        } else {
           /* call checkTime every 1/10th
              second until endTime */
           setTimeout(checkTime, 100);
        }
    }

    video.currentTime = startTime;
    video.play();
    checkTime();
}

UPDATE

Let's look at how you might implement this for your app.

You have two 'jump' buttons and a play button. When any of these buttons are activated you could call a single function which sets the start time and end time according to the HTML id of the clicked button.  Those values could them be passed into something like the function I've already outlined above.

To begin with, assign an event listener to each button...

var myvideo = document.getElementById('myvideo');

/* add the same event and
   handler function to each
   of the three buttons */
var buttons = ['playme','jump','jump2'];

buttons.forEach(function(bn) {
    document.getElementById(bn).addEventListener(
        'click', buttonEvents, !1
    );
});

Here each of you three HTML buttons will call a buttonEvents() function when clicked.  That function might look something like this...

function buttonEvents(e) {
    /* get the id of the clicked button */
    var element_id = e.target.id;
    /* E.G. element_id = 'playme', 'jump', or 'jump2' */

    /* declare variables before setting them */
    var timeStart = 0;
    var timeEnd = 0;

    /* set start and end values depending
       on which button was clicked */
    switch(element_id) {
        case 'playme':
            /* example values... */
            timeStart = 0;
            timeEnd = 100;
            break;
        case 'jump':
            timeStart = 4;
            timeEnd = 12;
            break;
        case 'jump2':
            timeStart = 12;
            timeEnd = 24;
    }

    /* call 'playVideo()' */
    playVideo(timeStart, timeEnd);
}

Combining your 'playbutton' function with the general function outlined above would give us something like this: a function that receives a start and end time as it's arguments and plays the video if it's paused or jumps to a new start time if it's playing...

function playVideo(startTime, endTime) {

    function checkTime() {
        if (myvideo.currentTime >= endTime) {
           myvideo.pause();
        } else {
           /* call checkTime every 1/10th
              second until endTime */
           setTimeout(checkTime, 100);
        }
    }

    /* stop if playing (otherwise ignored) */
    myvideo.pause();
    /* set video start time */
    myvideo.currentTime = startTime;
    /* play video */
    myvideo.play();
    /* check the current time and
       pause IF/WHEN endTime is reached */
    checkTime();
}

Hope that helped.


问:
Want to hang-up from my Twilio Java client
I have a Java application which uses the Twilio API to connect to Twilio and pass it a number in my org. to call. Twilio calls the number, I play it a message from my phone system and then I want my Java program to read Twilio's transcription of that message.

The problem I have is that Twilio doesn't know when to hang-up! I can't tell it to hang-up after the <record> verb as it does a submit at that point, so I want to do a Thread.sleep(20 * 1000) in my Java and then end the call from the Java? Possible? I can't see how to do it via the API. I've tried:

```<code>Call.updater(phoneHome.getSid()).setStatus(UpdateStatus.COMPLETED);
</code>```

and:

```<code>Call.deleter(phoneHome.getSid()).delete();
</code>```

but to no avail!

Also open to other ways of achieving same end in the TwiML, etc. Had a look at the <gather> and <redirect> but not sure I could make that work if the recording is playing, that only seems to work if nothing is played, i.e. silence from the called-party (my org.)

答:
Ok, so what I didn't want to have to do is send the GET request from the <record> verb anywhere as that would entail opening up a firewall gap into my organization, not an easy process.

So, I sent a get request to another TwiML document on Twilio which has a <Hangup/> verb in it. The sent recording never leaves Twilio, but that's Ok. I just wanted the call to end and the maxLength="20" on the <record> verb dictates when it ends. HTH.

Body:
I have a Java application which uses the Twilio API to connect to Twilio and pass it a number in my org. to call. Twilio calls the number, I play it a message from my phone system and then I want my Java program to read Twilio's transcription of that message.

The problem I have is that Twilio doesn't know when to hang-up! I can't tell it to hang-up after the <record> verb as it does a submit at that point, so I want to do a Thread.sleep(20 * 1000) in my Java and then end the call from the Java? Possible? I can't see how to do it via the API. I've tried:

Call.updater(phoneHome.getSid()).setStatus(UpdateStatus.COMPLETED);

and:

Call.deleter(phoneHome.getSid()).delete();

but to no avail!

Also open to other ways of achieving same end in the TwiML, etc. Had a look at the <gather> and <redirect> but not sure I could make that work if the recording is playing, that only seems to work if nothing is played, i.e. silence from the called-party (my org.)


问:
Select all elements but the last

I need to select all elements of a div but the last of this code:

```<code><div class="menu">
    <div>
       <a class="link" href="/">link 1</a>
       <div class="subMenu">
           <a class="link" href="/">link 2</a>
           <a class="link" href="/">link 3</a>
           <a class="link" href="/">link 4</a>
       </div>
       <a class="link" href="/">link 5</a>
   </div>
</div>
</code>```

I have tried .menu .link:not(:last-child) but the link 4 is selected as the last child but I want that the last child to be link 5. How can I do it?

Thanks you.

答:
Notes:

the examples below will also work when your last child is a submenu.

I assumed that your empty
 was a typo

the solution uses the direct children selector (.parent > .direct-children)

You could do that:

.menu > .link:not(:last-child),
.menu > .subMenu:not(:last-child) .link {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Last is a single link:

<div class="menu">
    link 1
    <div class="subMenu">
        link 2
        link 3
        link 4
    </div>
    link 5
</div>

<br />

Last is a submenu:

<div class="menu">
    link 1
    link 2
    <div class="subMenu">
        link 3
        link 4
        link 5
    </div>
</div></code>```

But I'd suggest to do the inverse:

.menu .link {
  color: red;
}

.menu > :last-child,
.menu > :last-child .link {
  color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Last is a single link:

<div class="menu">
    link 1
    <div class="subMenu">
        link 2
        link 3
        link 4
    </div>
    link 5
</div>

<br />

Last is a submenu:

<div class="menu">
    link 1
    link 2
    <div class="subMenu">
        link 3
        link 4
        link 5
    </div>
</div></code>```

Title: Select all elements but the last

Body:
I need to select all elements of a div but the last of this code:

       link 1

           link 2
           link 3
           link 4

       link 5

I have tried .menu .link:not(:last-child) but the link 4 is selected as the last child but I want that the last child to be link 5. How can I do it?

Thanks you.

Body:
Notes:

the examples below will also work when your last child is a submenu.

I assumed that your empty <div> was a typo

the solution uses the direct children selector (.parent > .direct-children)

You could do that:

.menu > .link:not(:last-child),
.menu > .subMenu:not(:last-child) .link {
  color: red;
}

Last is a single link:

<div class="menu">
    <a class="link" href="/">link 1</a>
    <div class="subMenu">
        <a class="link" href="/">link 2</a>
        <a class="link" href="/">link 3</a>
        <a class="link" href="/">link 4</a>
    </div>
    <a class="link" href="/">link 5</a>
</div>

<br />

Last is a submenu:

<div class="menu">
    <a class="link" href="/">link 1</a>
    <a class="link" href="/">link 2</a>
    <div class="subMenu">
        <a class="link" href="/">link 3</a>
        <a class="link" href="/">link 4</a>
        <a class="link" href="/">link 5</a>
    </div>
</div>

But I'd suggest to do the inverse:

.menu .link {
  color: red;
}

.menu > :last-child,
.menu > :last-child .link {
  color: blue;
}

Last is a single link:

<div class="menu">
    <a class="link" href="/">link 1</a>
    <div class="subMenu">
        <a class="link" href="/">link 2</a>
        <a class="link" href="/">link 3</a>
        <a class="link" href="/">link 4</a>
    </div>
    <a class="link" href="/">link 5</a>
</div>

<br />

Last is a submenu:

<div class="menu">
    <a class="link" href="/">link 1</a>
    <a class="link" href="/">link 2</a>
    <div class="subMenu">
        <a class="link" href="/">link 3</a>
        <a class="link" href="/">link 4</a>
        <a class="link" href="/">link 5</a>
    </div>
</div>


问:
CURL won't get the data from this website
I'm trying to retrieve data from www.dotabuff.com for a list of steam ID, but I only get in return "We couldn't find what you are looking for!".

The goal is to go to the website, search a player with his steam ID and extract his win rate.

(This is intended for very small lists, which will not bother dotabuff).

Here is my code (example with a static steam ID):

```<code>//create array of data to be posted
$post_data['utf8'] = '✓';
$post_data['q'] = '76561198055615656';
$post_data['commit'] = 'Search';

//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}

//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);

//create cURL connection
$curl_connection =
curl_init('https://www.dotabuff.com//');

//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

//set data to be posted
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);

//perform our request
$result = curl_exec($curl_connection);
echo $result;

//close the connection
curl_close($curl_connection);
</code>```

答:
Init curl without the URL, or assemble a GET version of the URL and post it to the site.

For example, if you want info on user  'USH!'  (I reandomly selected one).  the URL you'd synthesize would look like this:

```<code>https://www.dotabuff.com/search?utf8=%E2%9C%93&q=USH%21&button=
</code>```

I's suggest using urlencode to convert the player ID to a GET URI safe string

ex:

```<code>$safe_player_id = urlencode($player_id)

$URI = sprintf("https://www.dotabuff.com/search?q=%s&button=",$safe_player_id);
</code>```

Or, if you know their player ID code (int) then this would work to get the page of stats (this works):

```<code>https://www.dotabuff.com/players/76561198055615656
</code>```

Then you just need to parse the page for what you want.

Body:
I'm trying to retrieve data from www.dotabuff.com for a list of steam ID, but I only get in return "We couldn't find what you are looking for!".

The goal is to go to the website, search a player with his steam ID and extract his win rate.

(This is intended for very small lists, which will not bother dotabuff).

Here is my code (example with a static steam ID):

//create array of data to be posted
$post_data['utf8'] = '✓';
$post_data['q'] = '76561198055615656';
$post_data['commit'] = 'Search';

//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}

//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);

//create cURL connection
$curl_connection =
curl_init('https://www.dotabuff.com//');

//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

//set data to be posted
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);

//perform our request
$result = curl_exec($curl_connection);
echo $result;

//close the connection
curl_close($curl_connection);

Body:
Init curl without the URL, or assemble a GET version of the URL and post it to the site.

For example, if you want info on user  'USH!'  (I reandomly selected one).  the URL you'd synthesize would look like this:

https://www.dotabuff.com/search?utf8=%E2%9C%93&q=USH%21&button=

I's suggest using urlencode to convert the player ID to a GET URI safe string

ex:

$safe_player_id = urlencode($player_id)

$URI = sprintf("https://www.dotabuff.com/search?q=%s&button=",$safe_player_id);

Or, if you know their player ID code (int) then this would work to get the page of stats (this works):

https://www.dotabuff.com/players/76561198055615656

Then you just need to parse the page for what you want.


问:
Tensorboard - visualize weights of LSTM
I am using several LSTM layers to form a deep recurrent neural network. I would like to monitor the weights of each LSTM layer during training. However, I couldn't find out how to attach summaries of the LSTM layer weights to TensorBoard.

Any suggestions on how this can be done?

The code is as follows:

cells = []

with tf.name_scope("cell_1"):
    cell1 = tf.contrib.rnn.LSTMCell(self.embd_size, state_is_tuple=True, initializer=self.initializer)
    cell1 = tf.contrib.rnn.DropoutWrapper(cell1,
                input_keep_prob=self.input_dropout,
                output_keep_prob=self.output_dropout,
                state_keep_prob=self.recurrent_dropout)
    cells.append(cell1)

with tf.name_scope("cell_2"):
    cell2 = tf.contrib.rnn.LSTMCell(self.n_hidden, state_is_tuple=True, initializer=self.initializer)
    cell2 = tf.contrib.rnn.DropoutWrapper(cell2,
                output_keep_prob=self.output_dropout,
                state_keep_prob=self.recurrent_dropout)
    cells.append(cell2)

with tf.name_scope("cell_3"):
    cell3 = tf.contrib.rnn.LSTMCell(self.embd_size, state_is_tuple=True, initializer=self.initializer)
    # cell has no input dropout since previous cell already has output dropout
    cell3 = tf.contrib.rnn.DropoutWrapper(cell3,
                output_keep_prob=self.output_dropout,
                state_keep_prob=self.recurrent_dropout)
    cells.append(cell3)

cell = tf.contrib.rnn.MultiRNNCell(
    cells, state_is_tuple=True)

output, self.final_state = tf.nn.dynamic_rnn(
    cell,
    inputs=self.inputs,
    initial_state=self.init_state)
```

答:
tf.contrib.rnn.LSTMCell objects have a property called variables that works for this. There's just one trick: The property returns an empty list until your cell goes through tf.nn.dynamic_rnn. At least this is the case when using a single LSTMCell. I can't speak for MultiRNNCell. So I expect this would work:

```<code>output, self.final_state = tf.nn.dynamic_rnn(...)
for one_lstm_cell in cells:
    one_kernel, one_bias = one_lstm_cell.variables
    # I think TensorBoard handles summaries with the same name fine.
    tf.summary.histogram("Kernel", one_kernel)
    tf.summary.histogram("Bias", one_bias)
</code>```

And then you probably know how to do it from there, but

```<code>summary_op = tf.summary.merge_all()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    train_writer = tf.summary.FileWriter(
        "my/preferred/logdir/train", graph=tf.get_default_graph())
    for step in range(1, training_steps+1):
        ...
        _, step_summary = sess.run([train_op, summary_op])
        train_writer.add_summary(step_summary)
</code>```

Looking at the TensorFlow documentation I linked above, there's also a weights property. I don't know the difference, if there is any. And, the order of the variables return isn't documented. I figured it out by printing the resulting list and looking at the variable names.

Now, MultiRNNCell has the same variables property according to its doc and it says it returns all layer variables. I honestly don't know how MultiRNNCell works, so I cannot tell you whether these are variables belonging exclusively to MultiRNNCell or if it includes variables from the cells that go into it. Either way, knowing the property exists should be a nice tip! Hope this helps.

Although variables is documented for most (all?) RNN classes, it does break for DropoutWrapper. The property has been documented since r1.2, but accessing the property causes an exception in 1.2 and 1.4 (and looks like 1.3, but untested). Specifically,

```<code>from tensorflow.contrib import rnn
...
lstm_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0)
wrapped_cell = rnn.DropoutWrapper(lstm_cell)
outputs, states = rnn.static_rnn(wrapped_cell, x, dtype=tf.float32)
print("LSTM vars!", lstm_cell.variables)
print("Wrapped vars!", wrapped_cell.variables)
</code>```

will throw AttributeError: 'DropoutWrapper' object has no attribute 'trainable'. From the traceback (or a long stare at the DropoutWrapper source), I noticed that variables is implemented in DropoutWrapper's super RNNCell's super Layer. Dizzy yet? Indeed, we find the documented variables property here. It returns the (documented) weights property. The weights property returns the (documented) self.trainable_weights + self.non_trainable_weights properties. And finally the root of the problem:

```<code>@property
def trainable_weights(self):
    return self._trainable_weights if self.trainable else []

@property
def non_trainable_weights(self):
    if self.trainable:
        return self._non_trainable_weights
    else:
        return self._trainable_weights + self._non_trainable_weights
</code>```

That is, variables does not work for a DropoutWrapper instance. Neither will trainable_weights or non_trainable_weights sinceself.trainable is not defined.

One step deeper, Layer.__init__ defaults self.trainable to True, but DropoutWrapper never calls it. To quote a TensorFlow contributor on Github,

DropoutWrapper does not have variables because it does not itself store any. It wraps a cell that may have variables; but it's not clear what the semantics should be if you access the DropoutWrapper.variables. For example, all keras layers only report back the variables that they own; and so only one layer ever owns any variable. That said, this should probably return [], and the reason it doesn't is that DropoutWrapper never calls super().__init__ in its constructor. That should be an easy fix; PRs welcome.

So for instance, to access the LSTM variables in the above example, lstm_cell.variables suffices.

Edit: To the best of my knowledge, Mike Khan's PR has been incorporated into 1.5. Now, the variables property of the dropout layer returns an empty list.

Title: Tensorboard - visualize weights of LSTM

Body:
tf.contrib.rnn.LSTMCell objects have a property called variables that works for this. There's just one trick: The property returns an empty list until your cell goes through tf.nn.dynamic_rnn. At least this is the case when using a single LSTMCell. I can't speak for MultiRNNCell. So I expect this would work:

output, self.final_state = tf.nn.dynamic_rnn(...)
for one_lstm_cell in cells:
    one_kernel, one_bias = one_lstm_cell.variables
    # I think TensorBoard handles summaries with the same name fine.
    tf.summary.histogram("Kernel", one_kernel)
    tf.summary.histogram("Bias", one_bias)

And then you probably know how to do it from there, but

summary_op = tf.summary.merge_all()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    train_writer = tf.summary.FileWriter(
        "my/preferred/logdir/train", graph=tf.get_default_graph())
    for step in range(1, training_steps+1):
        ...
        _, step_summary = sess.run([train_op, summary_op])
        train_writer.add_summary(step_summary)

Looking at the TensorFlow documentation I linked above, there's also a weights property. I don't know the difference, if there is any. And, the order of the variables return isn't documented. I figured it out by printing the resulting list and looking at the variable names.

Now, MultiRNNCell has the same variables property according to its doc and it says it returns all layer variables. I honestly don't know how MultiRNNCell works, so I cannot tell you whether these are variables belonging exclusively to MultiRNNCell or if it includes variables from the cells that go into it. Either way, knowing the property exists should be a nice tip! Hope this helps.

Although variables is documented for most (all?) RNN classes, it does break for DropoutWrapper. The property has been documented since r1.2, but accessing the property causes an exception in 1.2 and 1.4 (and looks like 1.3, but untested). Specifically,

from tensorflow.contrib import rnn
...
lstm_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0)
wrapped_cell = rnn.DropoutWrapper(lstm_cell)
outputs, states = rnn.static_rnn(wrapped_cell, x, dtype=tf.float32)
print("LSTM vars!", lstm_cell.variables)
print("Wrapped vars!", wrapped_cell.variables)

will throw AttributeError: 'DropoutWrapper' object has no attribute 'trainable'. From the traceback (or a long stare at the DropoutWrapper source), I noticed that variables is implemented in DropoutWrapper's super RNNCell's super Layer. Dizzy yet? Indeed, we find the documented variables property here. It returns the (documented) weights property. The weights property returns the (documented) self.trainable_weights + self.non_trainable_weights properties. And finally the root of the problem:

@property
def trainable_weights(self):
    return self._trainable_weights if self.trainable else []

@property
def non_trainable_weights(self):
    if self.trainable:
        return self._non_trainable_weights
    else:
        return self._trainable_weights + self._non_trainable_weights

That is, variables does not work for a DropoutWrapper instance. Neither will trainable_weights or non_trainable_weights sinceself.trainable is not defined.

One step deeper, Layer.__init__ defaults self.trainable to True, but DropoutWrapper never calls it. To quote a TensorFlow contributor on Github,

DropoutWrapper does not have variables because it does not itself store any. It wraps a cell that may have variables; but it's not clear what the semantics should be if you access the DropoutWrapper.variables. For example, all keras layers only report back the variables that they own; and so only one layer ever owns any variable. That said, this should probably return [], and the reason it doesn't is that DropoutWrapper never calls super().__init__ in its constructor. That should be an easy fix; PRs welcome.

So for instance, to access the LSTM variables in the above example, lstm_cell.variables suffices.

Edit: To the best of my knowledge, Mike Khan's PR has been incorporated into 1.5. Now, the variables property of the dropout layer returns an empty list.


问:
Passing table name from a list of tables to a SELECT query
My organisation will soon be receiving a varying number of datasets every month which our Data Services team loads each dataset into their own table i.e. 47 files submitted, 47 tables in the database. Not a pretty approach but it will be improved in time. The year and month of submission is part of the table name. i.e. CMorgNZ322_200701PLD ….. NZ322_200701 being the variable part of the table name; NZ322X is the origin of the data and 200701 being April 2007 (based on financial year)

I don’t want to be a slave to editing a SELECT query just to amend the table name month after month so I want to write a stored procedure that passes the table name from one SELECT query to a 2nd SELECT query

This is my first foray into using LOOPS so I’m wondering what is the best approach and how do I pass the table name into the 2nd SELECT query from the initial SELECT query

```<code>DECLARE cur_filestoprocess
DECLARE @vcYrMth VarChar(6)
SET @vcYrMth = ‘200701’

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE ‘CMOrg%’ + @vcYrMth + ‘PLD’;

SELECT  COLa,
        COLb,
        COLc,
        COLd,
        SUM(COLg) AS ‘Activity’,
        SUM(COLk) AS ‘Costs’
INTO    RegionABC200701Summary
FROM  tablename1
GROUP BY COLa,
         COLb,
         COLc,
         COLd
</code>```

In advance, thanks for your help…..

答:
Use a dynamic SQL this might not be the most elegant but you should get the idea

```<code>DECLARE @tableName NVARCHAR(MAX)

DECLARE @vcYrMth VARCHAR(6)
SET @vcYrMth = '200701'

IF OBJECT_ID('tempdb.dbo.#tmp', 'U') IS NOT NULL
    DROP TABLE #tmp;

SELECT TABLE_NAME
INTO #tmp
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'CMOrg%' + @vcYrMth + 'PLD'

DECLARE @rowNum INT
SET @rowNum = 0

DECLARE @length INT
SELECT @length = COUNT(*) FROM #tmp

WHILE (@rowNum < @length)
BEGIN

    SELECT @tableName = TABLE_NAME
    FROM #tmp
    ORDER BY TABLE_NAME OFFSET @rowNum ROWS
    FETCH NEXT 1 ROWS ONLY

    SELECT @sql = 'SELECT  COLa,
                COLb,
                COLc,
                COLd,
                SUM(COLg) AS ‘Activity’,
                SUM(COLk) AS ‘Costs’
           INTO    Region'+@tableName+'Summary
           FROM  tablename1
           GROUP BY COLa,
                 COLb,
                 COLc,
                 COLd'
    FROM #tmp

    --PRINT (@sql)
    EXEC (@sql)

    SET @rowNum = @rowNum + 1
END
</code>```

Edited
The above will only work for SQL 2012 and above, use this snippet if using a version below

Replace

```<code>SELECT @tableName = TABLE_NAME
FROM #tmp
ORDER BY TABLE_NAME OFFSET @rowNum ROWS
FETCH NEXT 1 ROWS ONLY
</code>```

With

```<code>SELECT @tableName = TABLE_NAME
FROM (
    SELECT TABLE_NAME, ROW_NUMBER() OVER (ORDER BY TABLE_NAME) AS RowNumber
    FROM #tmp
    ) a
WHERE RowNumber = @rowNum
</code>```

Body:
My organisation will soon be receiving a varying number of datasets every month which our Data Services team loads each dataset into their own table i.e. 47 files submitted, 47 tables in the database. Not a pretty approach but it will be improved in time. The year and month of submission is part of the table name. i.e. CMorgNZ322_200701PLD ….. NZ322_200701 being the variable part of the table name; NZ322X is the origin of the data and 200701 being April 2007 (based on financial year)

I don’t want to be a slave to editing a SELECT query just to amend the table name month after month so I want to write a stored procedure that passes the table name from one SELECT query to a 2nd SELECT query

This is my first foray into using LOOPS so I’m wondering what is the best approach and how do I pass the table name into the 2nd SELECT query from the initial SELECT query

DECLARE cur_filestoprocess
DECLARE @vcYrMth VarChar(6)
SET @vcYrMth = ‘200701’

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE ‘CMOrg%’ + @vcYrMth + ‘PLD’;

SELECT  COLa,
        COLb,
        COLc,
        COLd,
        SUM(COLg) AS ‘Activity’,
        SUM(COLk) AS ‘Costs’
INTO    RegionABC200701Summary
FROM  tablename1
GROUP BY COLa,
         COLb,
         COLc,
         COLd

In advance, thanks for your help…..

Body:
Use a dynamic SQL this might not be the most elegant but you should get the idea

DECLARE @tableName NVARCHAR(MAX)

DECLARE @vcYrMth VARCHAR(6)
SET @vcYrMth = '200701'

IF OBJECT_ID('tempdb.dbo.#tmp', 'U') IS NOT NULL
    DROP TABLE #tmp;

SELECT TABLE_NAME
INTO #tmp
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'CMOrg%' + @vcYrMth + 'PLD'

DECLARE @rowNum INT
SET @rowNum = 0

DECLARE @length INT
SELECT @length = COUNT(*) FROM #tmp

WHILE (@rowNum < @length)
BEGIN

    SELECT @tableName = TABLE_NAME
    FROM #tmp
    ORDER BY TABLE_NAME OFFSET @rowNum ROWS
    FETCH NEXT 1 ROWS ONLY

    SELECT @sql = 'SELECT  COLa,
                COLb,
                COLc,
                COLd,
                SUM(COLg) AS ‘Activity’,
                SUM(COLk) AS ‘Costs’
           INTO    Region'+@tableName+'Summary
           FROM  tablename1
           GROUP BY COLa,
                 COLb,
                 COLc,
                 COLd'
    FROM #tmp

    --PRINT (@sql)
    EXEC (@sql)

    SET @rowNum = @rowNum + 1
END

Edited
The above will only work for SQL 2012 and above, use this snippet if using a version below

Replace

SELECT @tableName = TABLE_NAME
FROM #tmp
ORDER BY TABLE_NAME OFFSET @rowNum ROWS
FETCH NEXT 1 ROWS ONLY

With

SELECT @tableName = TABLE_NAME
FROM (
    SELECT TABLE_NAME, ROW_NUMBER() OVER (ORDER BY TABLE_NAME) AS RowNumber
    FROM #tmp
    ) a
WHERE RowNumber = @rowNum


问:
Php is not getting any information from database
Why in ,txt file (I'm using test mail server tool) displays line SELECT mail FROM check_out instead of mail address? Example is in the photo

EDITED CODE (STILL NOT WORKING):

```<code><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT mail FROM check_out";
$to = "SELECT mail FROM check_out";

mail($to , "ORDER", "Your order is placed !","From: vape@v.com");
$_SESSION['message'] = "Order placed succesfuly";
header('location:index.php');

if  (isset($_GET['up'])) {
$orderid = $_GET['up'];
mysqli_query($db, "DELETE FROM check_out WHERE id=$orderid");
header('location:index.php');
}

$conn->close();
?>
</code>```

Thanks for the help

How email address is displayed

答:
I am not completely aware of the purpose of this script but I tried to fix it.
Maybe that helps:</p>

```<code><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
session_start();

$result = $conn->query('SELECT mail FROM check_out ORDER BY id DESC LIMIT 1');
$to = $result->fetch_assoc();

mail($to['mail'] , "ORDER", "Your order is placed !","From: vape@v.com");
$_SESSION['message'] = "Order placed successfuly";

if  (isset($_GET['up'])) {
    $Orderid = (int) $_GET['up'];
    $stmt = $conn->prepare('DELETE FROM check_out WHERE id=?');
    $stmt->bind_param('i', $Orderid);
    $stmt->execute();
}

$conn->close();

header('location:index.php');
</code>```

Body:
Why in ,txt file (I'm using test mail server tool) displays line SELECT mail FROM check_out instead of mail address? Example is in the photo

EDITED CODE (STILL NOT WORKING):

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT mail FROM check_out";
$to = "SELECT mail FROM check_out";

mail($to , "ORDER", "Your order is placed !","From: vape@v.com");
$_SESSION['message'] = "Order placed succesfuly";
header('location:index.php');

if  (isset($_GET['up'])) {
$orderid = $_GET['up'];
mysqli_query($db, "DELETE FROM check_out WHERE id=$orderid");
header('location:index.php');
}

$conn->close();
?>

Thanks for the help

How email address is displayed

Body:
I am not completely aware of the purpose of this script but I tried to fix it.
Maybe that helps:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
session_start();

$result = $conn->query('SELECT mail FROM check_out ORDER BY id DESC LIMIT 1');
$to = $result->fetch_assoc();

mail($to['mail'] , "ORDER", "Your order is placed !","From: vape@v.com");
$_SESSION['message'] = "Order placed successfuly";

if  (isset($_GET['up'])) {
    $Orderid = (int) $_GET['up'];
    $stmt = $conn->prepare('DELETE FROM check_out WHERE id=?');
    $stmt->bind_param('i', $Orderid);
    $stmt->execute();
}

$conn->close();

header('location:index.php');


问:
create a folder on an SD card
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

```<code>public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}
</code>```

答:
[Possible duplicate]

If you need to create files on the SDCard you can use publics directories like Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DCIM)

This answer is on this link

Title: create a folder on an SD card

Body:
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}


问:
Sum an a nested array in an array of objects
I have a react component with a state that looks like this:

```<code>this.state = {
            categoryGroups: [
                {
                    groupName: 'Immediate Obligations',
                    budgeted: '5,000.00',
                    activity: '3,275.76',
                    subcategories: [
                        {
                            category: 'food',
                            budgeted: '500.00',
                            activity: '300.76'
                        },
                        {
                            category: 'rent',
                            budgeted: '1,000.00',
                            activity: '1,000.00'
                        }
                    ]
                },
                {
                    groupName: 'True Expenses',
                    budgeted: '2,000.00',
                    activity: '1,000.33',
                    subcategories: [
                        {
                            category: 'Car Insurance',
                            budgeted: '60.00',
                            activity: '60.00'
                        },
                        {
                            category: 'Gas',
                            budgeted: '100.00',
                            activity: '34.50'
                        }
                    ]
                }
            ]
        }
</code>```

I want to find the total budgeted amount for all of the subcategories in each category group. How can I do this?

答:
You could achieve this with a simple for-loop. JavaScript offers some nice functions on arrays, though.

See Mozilla's Documentation.

For summing things up, Array.prototype.reduce comes to mind. You can use it e.g. as follows:

```<code>this.state.categoryGroups.reduce(sumCategoryGroups, 0);

function sumCategoryGroups(sum, categoryGroup) {
    return sum + categoryGroup.subcategories.reduce(sumSubCategories, 0);
}

function sumSubCategories(sum, subCategory) {
    return sum + subCategory.budgeted;
}
</code>```

edit:
As I didn't recognize that the budgeted amount is stored as a String, the above solution probably wouldn't do what the user who asked the question intended it to.

Depending on how certain you can be that the number-String is always formatted the same way, you could use something like the following:

```<code>function budgetToNumber(budgetString) {
    return Number(budgetString.replace(/,/g, ''));
}
</code>```

With the prior code changing to:

```<code>this.state.categoryGroups.reduce(sumCategoryGroups, 0);

function sumCategoryGroups(sum, categoryGroup) {
    return sum + categoryGroup.subcategories.reduce(sumSubCategories, 0);
}

function sumSubCategories(sum, subCategory) {
    return sum + budgetToNumber(subCategory.budgeted);
}
</code>```

Notice though, that there are quite a few ways this could be dangerous to do; i.e. when the format of the budget amount changes.

Body:
I have a react component with a state that looks like this:

this.state = {
            categoryGroups: [
                {
                    groupName: 'Immediate Obligations',
                    budgeted: '5,000.00',
                    activity: '3,275.76',
                    subcategories: [
                        {
                            category: 'food',
                            budgeted: '500.00',
                            activity: '300.76'
                        },
                        {
                            category: 'rent',
                            budgeted: '1,000.00',
                            activity: '1,000.00'
                        }
                    ]
                },
                {
                    groupName: 'True Expenses',
                    budgeted: '2,000.00',
                    activity: '1,000.33',
                    subcategories: [
                        {
                            category: 'Car Insurance',
                            budgeted: '60.00',
                            activity: '60.00'
                        },
                        {
                            category: 'Gas',
                            budgeted: '100.00',
                            activity: '34.50'
                        }
                    ]
                }
            ]
        }

I want to find the total budgeted amount for all of the subcategories in each category group. How can I do this?

Body:
You could achieve this with a simple for-loop. JavaScript offers some nice functions on arrays, though.

See Mozilla's Documentation.

For summing things up, Array.prototype.reduce comes to mind. You can use it e.g. as follows:

this.state.categoryGroups.reduce(sumCategoryGroups, 0);

function sumCategoryGroups(sum, categoryGroup) {
    return sum + categoryGroup.subcategories.reduce(sumSubCategories, 0);
}

function sumSubCategories(sum, subCategory) {
    return sum + subCategory.budgeted;
}

edit:
As I didn't recognize that the budgeted amount is stored as a String, the above solution probably wouldn't do what the user who asked the question intended it to.

Depending on how certain you can be that the number-String is always formatted the same way, you could use something like the following:

function budgetToNumber(budgetString) {
    return Number(budgetString.replace(/,/g, ''));
}

With the prior code changing to:

this.state.categoryGroups.reduce(sumCategoryGroups, 0);

function sumCategoryGroups(sum, categoryGroup) {
    return sum + categoryGroup.subcategories.reduce(sumSubCategories, 0);
}

function sumSubCategories(sum, subCategory) {
    return sum + budgetToNumber(subCategory.budgeted);
}

Notice though, that there are quite a few ways this could be dangerous to do; i.e. when the format of the budget amount changes.


问:
WPF Creating a Command Library
New to WPF/XAML and looking to build a Command library for my application. Current version of my application is "flat" meaning all the code behind resides in my MainWindow.cs file. I've decided to separate things out into User Controls and all the UI part so far works great but....

I'm having trouble binding my commands to things now that I've done this. To make it simple I created a new WPF project, added my Menu control (Controls\Menu.xaml) and referenced this in my MainWindow.xaml. Now, I've gone ahead and added a CommandLibrary class and can't seem to get anything working. Here is my File -> New command code:

```<code>public static class MyAppCommands
{

    private static RoutedUICommand _NewItem;

    static MyAppCommands()
    {
        _NewItem = new RoutedUICommand("Create a new project", "NewItem", typeof(MyAppCommands));
    }

    public static RoutedUICommand NewItem
    {
        get { return _NewItem; }
    }

    private string filePath = null;
    private bool dataChanged = false;

    public static void NewItem_Executed(object sender, ExecutedRoutedEventArgs e)
    {

        if (dataChanged)
        {
            string sf = SaveFirst();
            if (sf != "Cancel")
            {
                ClearState();
            }
        }
        else
        {
            ClearState();
        }
    }

    public static void NewItem_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    public static void BindCommandsToWindow(Window window)
    {
        window.CommandBindings.Add(new CommandBinding(NewItem, NewItem_Executed, NewItem_CanExecute));

    }
</code>```

Where do I put the below in my class as a lot of my command will be using them...?

```<code>private string filePath = null;
private bool dataChanged = false;
</code>```

Many Thanks!

答:
I think you could benefit from setting up some design patterns like MVC or MVVM.

Check out these frameworks:

Caliburn (my favorite)

Prism

You can also follow MVC or MVVM just using a couple small helper classes, check out ariticles around the web, like this one MVVM.

Check this if you want a light-weight framework: MVVM Foundation

Title: WPF Creating a Command Library

Body:
New to WPF/XAML and looking to build a Command library for my application. Current version of my application is "flat" meaning all the code behind resides in my MainWindow.cs file. I've decided to separate things out into User Controls and all the UI part so far works great but....

I'm having trouble binding my commands to things now that I've done this. To make it simple I created a new WPF project, added my Menu control (Controls\Menu.xaml) and referenced this in my MainWindow.xaml. Now, I've gone ahead and added a CommandLibrary class and can't seem to get anything working. Here is my File -> New command code:

public static class MyAppCommands
{

    private static RoutedUICommand _NewItem;

    static MyAppCommands()
    {
        _NewItem = new RoutedUICommand("Create a new project", "NewItem", typeof(MyAppCommands));
    }

    public static RoutedUICommand NewItem
    {
        get { return _NewItem; }
    }

    private string filePath = null;
    private bool dataChanged = false;

    public static void NewItem_Executed(object sender, ExecutedRoutedEventArgs e)
    {

        if (dataChanged)
        {
            string sf = SaveFirst();
            if (sf != "Cancel")
            {
                ClearState();
            }
        }
        else
        {
            ClearState();
        }
    }

    public static void NewItem_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    public static void BindCommandsToWindow(Window window)
    {
        window.CommandBindings.Add(new CommandBinding(NewItem, NewItem_Executed, NewItem_CanExecute));

    }

Where do I put the below in my class as a lot of my command will be using them...?

private string filePath = null;
private bool dataChanged = false;

Many Thanks!


问:
Laravel QB Collection
I have a collection that returns the correct users however using this substring_index function does not alphabetize the entire collection by the user's name as desired. Is there a better method I need to use here.</p>

```<code>{{ dd(App\User::whereHas('roles', function($q) {
       $q->where('name', '=', 'rprm');
   })->orderByRaw('substring_index(trim("name"), " ", -1)')->pluck('name', 'id')) }}
</code>```

答:
You need to change your query.

```<code>{{ dd(App\User::whereHas('roles', function($q) {
       $q->where('name', '=', 'rprm');
   })->orderByRaw('substring_index(TRIM(name), " ", 1)')->pluck('name', 'id'))
}}
</code>```

I assume you want to use MySQL's TRIM function.

Title: Laravel QB Collection

Body:
I have a collection that returns the correct users however using this substring_index function does not alphabetize the entire collection by the user's name as desired. Is there a better method I need to use here.

{{ dd(App\User::whereHas('roles', function($q) {
       $q->where('name', '=', 'rprm');
   })->orderByRaw('substring_index(trim("name"), " ", -1)')->pluck('name', 'id')) }}

Body:
You need to change your query.

{{ dd(App\User::whereHas('roles', function($q) {
       $q->where('name', '=', 'rprm');
   })->orderByRaw('substring_index(TRIM(name), " ", 1)')->pluck('name', 'id'))
}}

I assume you want to use MySQL's TRIM function.


问:
sed not replacing as expected
Why I am getting the same output as the input while I am expecting 'search replace subject' as output:</p>

```<code>x="search='some thing' replace='something' subject=/path"

echo $x
echo "$x" | sed 's/\(\w+\)=/\1\n/g'
</code>```

答:
By default sed uses old-style regular expressions. If you want new style (aka "extended") regular expressions you should use sed -r. And anyway you are using a mixture of old-style and new style regular expressions which will never work (you cannot have at the same time \(...\) and +); so either

```<code>sed -e 's/\(\w\+\)=/\1\n/g'
</code>```

or

```<code>sed -re 's/(\w+)=/\1\n/g'
</code>```

Any of the above would produce

```<code>search
'some thing' replace
'something' subject
/path
</code>```

If you are actually expecting the output to be search replace subject then

```<code>sed -re "s/=('[^']*'|[^']\\S*)//g"
</code>```

That is, delete all matches of an equal sign followed either by

' any number of non-' and a final ', or

a sequence of 1 or more non-blanks starting with anything but '.

(But this has nothing to do with the regex in the original question. I cannot relate the desired output with the regex in the question.)

Title: sed not replacing as expected

Body:
Why I am getting the same output as the input while I am expecting 'search replace subject' as output:

x="search='some thing' replace='something' subject=/path"

echo $x
echo "$x" | sed 's/\(\w+\)=/\1\n/g'

Body:
By default sed uses old-style regular expressions. If you want new style (aka "extended") regular expressions you should use sed -r. And anyway you are using a mixture of old-style and new style regular expressions which will never work (you cannot have at the same time \(...\) and +); so either

sed -e 's/\(\w\+\)=/\1\n/g'

or

sed -re 's/(\w+)=/\1\n/g'

Any of the above would produce

search
'some thing' replace
'something' subject
/path

If you are actually expecting the output to be search replace subject then

sed -re "s/=('[^']*'|[^']\\S*)//g"

That is, delete all matches of an equal sign followed either by

' any number of non-' and a final ', or

a sequence of 1 or more non-blanks starting with anything but '.

(But this has nothing to do with the regex in the original question. I cannot relate the desired output with the regex in the question.)


问:
I need to convert vowels to the "@" symbol in Scala
The idea of this program is to read lines in and take out all vowels and replace them with the "@" character. Input will stop with the user typing "--quit--" and it will return those lines with the function applied to them. I can't figure out what the syntax should be for the part of the function I've included "lst.map("aeiouAEIOU" => '@')" . I think I'm missing something.</p>

```<code>import scala.io.StdIn._

def readList: List[String] = {
  val n = readLine
  if (n == "--quit--") {
    return Nil
  } else {
    return n::readList
  }
}

def vowelsToAt(lst: List[String]): List[String] = {

  lst.map("aeiouAEIOU" => '@')

}

val wordList = readList
println(vowelsToAt(wordList).mkString("\n"))
</code>```

答:
Instead of lst.map("aeiouAEIOU" => '@') you can use

```<code>lst.map(_.map(c => if ("aeiouAEIOU" contains c) '@' else c))
</code>```

The inner map transforms a string char-by-char by replacing vowels with @s, and the outer map applies this transformation to every element of the list.

Your expression "aeiouAEIOU" => '@' is not valid, the left hand side must be an arbitrary char (the argument of your lambda), and not the string containing the chars you want to map. Another possibility that is similiar to your approach (but a bit convoluted):

```<code>list.map(_.map {
  case 'a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E' | 'I' | 'O' | 'U' => '@'
  case c => c
})
</code>```

One side note: In your method readList, you do not have to use return, as the last statement is also interpreted as the return value.

Body:
The idea of this program is to read lines in and take out all vowels and replace them with the "@" character. Input will stop with the user typing "--quit--" and it will return those lines with the function applied to them. I can't figure out what the syntax should be for the part of the function I've included "lst.map("aeiouAEIOU" => '@')" . I think I'm missing something.

import scala.io.StdIn._

def readList: List[String] = {
  val n = readLine
  if (n == "--quit--") {
    return Nil
  } else {
    return n::readList
  }
}

def vowelsToAt(lst: List[String]): List[String] = {

  lst.map("aeiouAEIOU" => '@')

}

val wordList = readList
println(vowelsToAt(wordList).mkString("\n"))

Body:
Instead of lst.map("aeiouAEIOU" => '@') you can use

lst.map(_.map(c => if ("aeiouAEIOU" contains c) '@' else c))

The inner map transforms a string char-by-char by replacing vowels with @s, and the outer map applies this transformation to every element of the list.

Your expression "aeiouAEIOU" => '@' is not valid, the left hand side must be an arbitrary char (the argument of your lambda), and not the string containing the chars you want to map. Another possibility that is similiar to your approach (but a bit convoluted):

list.map(_.map {
  case 'a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E' | 'I' | 'O' | 'U' => '@'
  case c => c
})

One side note: In your method readList, you do not have to use return, as the last statement is also interpreted as the return value.


问:
Share Contact Via Twillion to iPhone
I am looking to create a script to send a contact from Twillio to my iPhone. The purpose is the contact I send from Twillio to phone should look exactly the way contact shared by iPhone. Can someone help me,

PS: Is it doable ?

答:
Twilio developer evangelist here.

This kind of depends. Contacts are sent as MMS messages (as it's a file of information). Twilio supports sending MMS messages in the US and Canada, so you can do this if that is where you are sending your messages. If you are sending elsewhere in the world, then I'm afraid you can't do so with Twilio and make it look the same as a shared contact.

Let me know if that helps at all.

Title: Share Contact Via Twillion to iPhone


问:
Window form execute a batch file
I am new to C# programming. I would like to have an application contains 1 text box and 1 submit button to exec a batch file.

The file is d:\XMLupdate.bat, but the program appends a number on the command line to the file
for example d:\XMLupdate.bat 10 or d:\XMLupdate.bat 15

Another thing is that the submission has to be validated to either 1 -999 or ALL

In Java way:

```<code> Runtime rt = Runtime.getRuntime();
                            Process pr = rt.exec(command);
                        }
                else{
                try{
int boxNumber = Integer.parseInt(jTextField1.getText());
                        if((boxNumber > 0) && boxNumber < 1000)
                            {
                                String arguments = jTextField1.getText();
                                String command = "CMD /C start d:/XMLupdate.bat " + arguments;
                                Runtime rt = Runtime.getRuntime();

rt.exec(command);

                            }
                         else{
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                            }
 }catch(Exception e)
                        {
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                        }
                    }
</code>```

However, the machine can not install JVM. Therefore, i have to build it in exe. My programming language is C#:

Here is the source code:

```<code>public partial class Form1 : Form
    {

        //private System.Windows.Forms.TextBox textBox1;  //Input text
        //private System.Windows.Forms.Button button1;   //Sumbit button

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //get text
           // string str_inputText = textBox1.Text;
            if (!(textBox1.Text.Equals("")))
            {
                  if (textBox1.Text.Equals("ALL"))
                      {
                          try
                          {

                              Process p = new Process();
                              p.StartInfo.FileName = "CMD.exe"; //Execute command
                              p.StartInfo.WorkingDirectory = "c:\temp"; //Diretory
                              p.StartInfo.Arguments = "xmlupdate.bat" + int.Parse(textBox1.Text);
                              p.Start();

                              p.WaitForExit();

                          }

                          catch (Exception ex)
                          {

                              Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                              MessageBox.Show("Invalid value entered");

                          }
                      }

            }

        }

        private void textBox1_TextChanged(object sender, CancelEventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //Check the input number, only allow from 0 until 1000
            try
            {
                int numberEntered = int.Parse(textBox1.Text);
                if (numberEntered < 1 || numberEntered > 10)
                {
                   // e.Cancel = true;

                }
            }
            catch (FormatException)
            {
               // e.Cancel = true;
                MessageBox.Show("You need to enter a number between 1 and 999");
            }
        }

    }
</code>```

My main question is about process method,  can i execute it like that?  thanks

答:
"can i execute it like that?"

Does your solution compile?

If so, what happens when you run it?

On thing I noticed off the bat is this line

```<code> p.StartInfo.Arguments = "xmlupdate.bat" + int.Parse(textBox1.Text);
</code>```

You need a space between the batch file and the next argument.

```<code> p.StartInfo.Arguments = "xmlupdate.bat " + int.Parse(textBox1.Text);
</code>```

Title: Window form execute a batch file

Body:
I am new to C# programming. I would like to have an application contains 1 text box and 1 submit button to exec a batch file.

The file is d:\XMLupdate.bat, but the program appends a number on the command line to the file
for example d:\XMLupdate.bat 10 or d:\XMLupdate.bat 15

Another thing is that the submission has to be validated to either 1 -999 or ALL

In Java way:

 Runtime rt = Runtime.getRuntime();
                            Process pr = rt.exec(command);
                        }
                else{
                try{
int boxNumber = Integer.parseInt(jTextField1.getText());
                        if((boxNumber > 0) && boxNumber < 1000)
                            {
                                String arguments = jTextField1.getText();
                                String command = "CMD /C start d:/XMLupdate.bat " + arguments;
                                Runtime rt = Runtime.getRuntime();

rt.exec(command);

                            }
                         else{
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                            }
 }catch(Exception e)
                        {
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                        }
                    }

However, the machine can not install JVM. Therefore, i have to build it in exe. My programming language is C#:

Here is the source code:

public partial class Form1 : Form
    {

        //private System.Windows.Forms.TextBox textBox1;  //Input text
        //private System.Windows.Forms.Button button1;   //Sumbit button

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //get text
           // string str_inputText = textBox1.Text;
            if (!(textBox1.Text.Equals("")))
            {
                  if (textBox1.Text.Equals("ALL"))
                      {
                          try
                          {

                              Process p = new Process();
                              p.StartInfo.FileName = "CMD.exe"; //Execute command
                              p.StartInfo.WorkingDirectory = "c:\temp"; //Diretory
                              p.StartInfo.Arguments = "xmlupdate.bat" + int.Parse(textBox1.Text);
                              p.Start();

                              p.WaitForExit();

                          }

                          catch (Exception ex)
                          {

                              Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                              MessageBox.Show("Invalid value entered");

                          }
                      }

            }

        }

        private void textBox1_TextChanged(object sender, CancelEventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //Check the input number, only allow from 0 until 1000
            try
            {
                int numberEntered = int.Parse(textBox1.Text);
                if (numberEntered < 1 || numberEntered > 10)
                {
                   // e.Cancel = true;

                }
            }
            catch (FormatException)
            {
               // e.Cancel = true;
                MessageBox.Show("You need to enter a number between 1 and 999");
            }
        }

    }

My main question is about process method,  can i execute it like that?  thanks

Body:
"can i execute it like that?"

Does your solution compile?

If so, what happens when you run it?

On thing I noticed off the bat is this line

 p.StartInfo.Arguments = "xmlupdate.bat" + int.Parse(textBox1.Text);

You need a space between the batch file and the next argument.

 p.StartInfo.Arguments = "xmlupdate.bat " + int.Parse(textBox1.Text);


问:
Ajax call not appending to div
My ajax call

```<code>$('#searchform').submit(function(event) {
  $.ajax({
  type: "get",
  url: "/list",
  dataType: "text",
  data: $("#searchform").serialize(),
   beforeSend: function() {
              $(".se-pre-con").show();
           },
  success: function(data)
  {
    console.log(data);
    $("#testcontent").append(data);
    location.href="/test?"+$("#searchform").serialize();
  }

});
  event.preventDefault();
});
</code>```

This ajax call does not append the data to the testcontentdiv. I get the console log for data very well, but it just does not want to append. The div #testcontentis always empty.

What am I doing wrong.

答:
Your functionality works. If there is an issue, it's outside the scope of the source code that was given. I would suggest wrapping your redirect with a setTimeout() Method and letting the user know the will be redirect in X amount of seconds.

/* Variable Defaults */
var dummyURL = 'https://jsonplaceholder.typicode.com/posts/1';

/* Bind Submit Event to Form */
$('#searchform').on('submit', function(event) {
  $.ajax({
    type: 'get',
    url: dummyURL,
    dataType: 'text',
    data: $('#searchform').serialize(),
    beforeSend: function() {
      $('.se-pre-con').show();
    },
    success: function(data) {
      $('#testcontent').append(data);
      console.log('Redirected To:', '/test?' + $('#searchform').serialize());
    }

  });
  event.preventDefault();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.se-pre-con {
  display: none;
}</code>```

<form id="searchform">
  First Name:
  <input type="text" name="first_name">

  Last Name:
  <input type="text" name="first_name">

  <button type="submit">Submit</button>
</form>

  Show Me Before Send!

```

Title: Ajax call not appending to div

Body:
My ajax call

$('#searchform').submit(function(event) {
  $.ajax({
  type: "get",
  url: "/list",
  dataType: "text",
  data: $("#searchform").serialize(),
   beforeSend: function() {
              $(".se-pre-con").show();
           },
  success: function(data)
  {
    console.log(data);
    $("#testcontent").append(data);
    location.href="/test?"+$("#searchform").serialize();
  }

});
  event.preventDefault();
});

This ajax call does not append the data to the testcontentdiv. I get the console log for data very well, but it just does not want to append. The div #testcontentis always empty.

What am I doing wrong.

Body:
Your functionality works. If there is an issue, it's outside the scope of the source code that was given. I would suggest wrapping your redirect with a setTimeout() Method and letting the user know the will be redirect in X amount of seconds.

/* Variable Defaults */
var dummyURL = 'https://jsonplaceholder.typicode.com/posts/1';

/* Bind Submit Event to Form */
$('#searchform').on('submit', function(event) {
  $.ajax({
    type: 'get',
    url: dummyURL,
    dataType: 'text',
    data: $('#searchform').serialize(),
    beforeSend: function() {
      $('.se-pre-con').show();
    },
    success: function(data) {
      $('#testcontent').append(data);
      console.log('Redirected To:', '/test?' + $('#searchform').serialize());
    }

  });
  event.preventDefault();
});

.se-pre-con {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="searchform">
  <label>First Name:</label>
  <input type="text" name="first_name">
  <br>
  <label>Last Name:</label>
  <input type="text" name="first_name">
  <br>
  <button type="submit">Submit</button>
</form>

<p class="se-pre-con">
  Show Me Before Send!
</p>

<p id="testcontent"></p>