问:
cmdline argument parsing using tcl?
I am trying to pass the parameters to Spirent test center tool  using command line arguments, where I am passing slots, ports, frame size and load. I want to store the Slots and ports in array, where number of ports are dynamic.
I tried simple code with cmdline which can handle fixed ports

```<code>package require cmdline

set parameters {
    {s.arg ""   "Slot"}
    {p.arg ""   "Port"}
    {l.arg "100"   "Load"}
    {f.arg "256"   "Framesize"}
    {debug      "Turn on debugging, default=off"}
}
#set option(l) 100
set usage "- A simple script to demo cmdline parsing"

if {[catch {array set options [cmdline::getoptions ::argv $parameters $usage]}]} {
    puts [cmdline::usage $parameters $usage]
} else {
    parray options
}
#puts [array get options]
puts $options(l)
puts $options(f)
</code>```

script Output:

```<code>C:\Tcl\bin>tclsh opt.tcl -s 1 -f 128
options(debug) = 0
options(f)     = 128
options(l)     = 100
options(p)     =
options(s)     = 1
100
128
</code>```

Here I would like to pass all the ports for each slots onetime ,

```<code>tclsh opt.tcl -s 1 2 -p 11 12 13 14 -f 256 -l 100
</code>```

Where slots are 1 and 2 and ports in each slot are 11,12,13,14 and need to create array of slot and ports. Could you please suggest some method to achieve this.

答:
I tried the following method with some corrections:

```<code>     set arglen [llength $argv]
     while {$index < $arglen} {
     set arg [lindex $argv $index]
     #puts $arg
     switch -exact -- $arg {
          -s {
        set args($arg) [lindex $argv [incr index]]
        set slot($y) $args($arg)
        incr y
            }
        -p {
           set args($arg) [lindex $argv [incr index]]
            set port($z) $args($arg)
            incr z
            }
           -l {
                 set args($arg) [lindex $argv [incr index]]
                global Load
                set Load $args($arg)
                }
            -f {
                set args($arg) [lindex $argv [incr index]]
                set frameLength $args($arg)
                }

          }
            incr index
          }
</code>```

Command to run:

```<code>           C:\Tcl\bin>tclsh l1.tcl -s 1 -p 11 -p 12 -l 10 -f 1
</code>```

Title: cmdline argument parsing using tcl?

Body:
I am trying to pass the parameters to Spirent test center tool  using command line arguments, where I am passing slots, ports, frame size and load. I want to store the Slots and ports in array, where number of ports are dynamic.
I tried simple code with cmdline which can handle fixed ports

package require cmdline

set parameters {
    {s.arg ""   "Slot"}
    {p.arg ""   "Port"}
    {l.arg "100"   "Load"}
    {f.arg "256"   "Framesize"}
    {debug      "Turn on debugging, default=off"}
}
#set option(l) 100
set usage "- A simple script to demo cmdline parsing"

if {[catch {array set options [cmdline::getoptions ::argv $parameters $usage]}]} {
    puts [cmdline::usage $parameters $usage]
} else {
    parray options
}
#puts [array get options]
puts $options(l)
puts $options(f)

script Output:

C:\Tcl\bin>tclsh opt.tcl -s 1 -f 128
options(debug) = 0
options(f)     = 128
options(l)     = 100
options(p)     =
options(s)     = 1
100
128

Here I would like to pass all the ports for each slots onetime ,

tclsh opt.tcl -s 1 2 -p 11 12 13 14 -f 256 -l 100

Where slots are 1 and 2 and ports in each slot are 11,12,13,14 and need to create array of slot and ports. Could you please suggest some method to achieve this.

Body:
I tried the following method with some corrections:

     set arglen [llength $argv]
     while {$index < $arglen} {
     set arg [lindex $argv $index]
     #puts $arg
     switch -exact -- $arg {
          -s {
        set args($arg) [lindex $argv [incr index]]
        set slot($y) $args($arg)
        incr y
            }
        -p {
           set args($arg) [lindex $argv [incr index]]
            set port($z) $args($arg)
            incr z
            }
           -l {
                 set args($arg) [lindex $argv [incr index]]
                global Load
                set Load $args($arg)
                }
            -f {
                set args($arg) [lindex $argv [incr index]]
                set frameLength $args($arg)
                }

          }
            incr index
          }

Command to run:

           C:\Tcl\bin>tclsh l1.tcl -s 1 -p 11 -p 12 -l 10 -f 1


来源: stackexchange

问:
Which is the good way to conforms to UITableView protocols?
I am following this guideline to implement UITableView protocols. But right now, it's showing me an error, what I am doing wrong?

'RequestsViewController' does not conform to protocol 'UITableViewDataSource'.

```<code>class RequestsViewController: UIViewController {
    ...
    ...
}

extension RequestsViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrayRequests.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> RequestsTableViewCell {
        let cell:RequestsTableViewCell = (tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! RequestsTableViewCell)
        //Doing some assignments.
        return cell
    }
}

extension RequestsViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }
}
</code>```

答:
CHANGE THIS

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> RequestsTableViewCell
</code>```

TO:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am following this guideline to implement UITableView protocols. But right now, it's showing me an error, what I am doing wrong?

'RequestsViewController' does not conform to protocol 'UITableViewDataSource'.

class RequestsViewController: UIViewController {
    ...
    ...
}

extension RequestsViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrayRequests.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> RequestsTableViewCell {
        let cell:RequestsTableViewCell = (tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! RequestsTableViewCell)
        //Doing some assignments.
        return cell
    }
}

extension RequestsViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }
}

Body:
CHANGE THIS

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> RequestsTableViewCell

TO:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell


问:
API working fine in postman but not in angular2
I have an API to send an OTP to mobile. It is working fine via PostMan but not via angular2.

I am getting this error "Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response."

Any help

Thanks in advance

答: Include Allow-Cross-Origin header in your POST call.


问:
Learning C# prior to learning ASP.NET MVC?
With only mild programming experience in the past, I was wondering about C# and ASP.NET MVC..

Do you guys think it's a better idea to learn C# before learning ASP.NET MVC?  I've already delved a little into both of these already, but I still need some help deciding.

I think I would be a much stronger MVC user if I had more knowledge of the C# language itself.

What do you guys think?

Thanks!

答:
Asp.net MVC is a framework for web development on top of .net developed in C#.

So if you want to know the priorities(not necessarily in a waterfall model, you can learn them in parallel):

First you must learn C#(some oo priciples and the way you must structure your code).

Second you must learn the rules and techniques
   in web development (Html, Css, javascript, Web Architecture and the way it works(concepts like session management, cookies, etc) ...)

and Last learn
   the Asp.net MVC

ContentLicense: CC BY-SA 2.5


问:
junit test cases for this custom reader
I am new in writing junit test cases.

I have one custom item reader ,which is reading files from directory and returning pojo. Can you plz tell me how to write junit test cases for this custom reader.

Thanks in advance

答:
You can test individual step independently. Reader,processor and writer will be tested.

Reference code

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { YourConfig.class })
public classSampleTests {

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

 @setup
 public void setup()
 {
    // do setup needed for your setp
 }

    @Test
    public void testStep() throws Exception {
        JobExecution jobExecution = jobLauncherTestUtils.launchStep("yourStep");

        Assert.assertEquals("COMPLETED", jobExecution.getExitStatus());
    }
}
</code>```

Title: junit test cases for this custom reader

Body:
You can test individual step independently. Reader,processor and writer will be tested.

Reference code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { YourConfig.class })
public classSampleTests {

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

 @setup
 public void setup()
 {
    // do setup needed for your setp
 }

    @Test
    public void testStep() throws Exception {
        JobExecution jobExecution = jobLauncherTestUtils.launchStep("yourStep");

        Assert.assertEquals("COMPLETED", jobExecution.getExitStatus());
    }
}


问:
Angular4 ng-content gets built when ngIf is false
I have a problem with the new ng-content transclusion.

Let's say I have a component my-component that, in its ngOnInit() function does some heavy operation on load (for now, just a console.log()).

I have a wrapper, that displays the content via transclusion (my-wrapper.component.html).

```<code><ng-content></ng-content>
</code>```

If I set the surroundings up like this, the log statement doesn't show:

```<code><my-wrapper *ngIf="false">
    <my-component></my-component>
</my-wrapper>
</code>```

I assume, the my-wrapper component does not get built, so the content is ignored.

But if I try to move the logic into the my-wrapper component like this (my-wrapper.component.html):

```<code><ng-container *ngIf="false">
    <ng-content></ng-content>
</ng-container>
</code>```

I always see the console.log() output. I guess, the my-component gets built and then stored away until the *ngIf becomes true inside my-wrapper.

The intention was to build a generic "list-item + detail" component. Say I have a list of N overview-elements (my-wrapper), that get rendered in a *ngFor loop. Every of those elements has its own detail component (my-component) that is supposed to load its own data, once I decide to show more infos to a specific item.

overview.html:

```<code><ng-container *ngFor="let item of items">
    <my-wrapper>
        <my-component id="item.id"></my-component>
    </my-wrapper>
</ng-container>
</code>```

my-wrapper.component.html:

```<code><div (click)="toggleDetail()">Click for more</div>
<div *ngIf="showDetail">
    <ng-content></ng-content>
</div>
</code>```

Is there a way to tell Angular, to ignore the transcluded content until it is necessary to be added to the page? Analogously to how it was in AngularJS.

答:
Based on the comment of @nsinreal I found an answer. I find it to be a bit abstruse, so I'm trying to post it here:

The answer is to work with ng-template and *ngTemplateOutlet.

In the my-wrapper component, set up the template like this (my-wrapper.component.html):

```<code><div (click)="toggleDetail()">Click for more</div>
<div *ngIf="showDetail" [hidden]="!isInitialized">
    <ng-container *ngTemplateOutlet="detailRef"></ng-container>
</div>
</code>```

Note, that the [hidden] there is not really necessary, it hides the "raw" template of the child until it decides it is done loading. Just make sure, not to put it in a *ngIf, otherwise the *ngTemplateOutlet will never get triggered, leading to nothing happening at all.

To set the detailRef, put this in the component code (my-wrapper.component.ts):

```<code>import { ContentChild, TemplateRef } from '@angular/core';

@Component({ ... })
export class MyWrapperComponent {
    @ContentChild(TemplateRef) detailRef;

    ...
}
</code>```

Now, you can use the wrapper like this:

```<code><my-wrapper>
    <ng-template>
        <my-component></my-component>
    </ng-template>
</my-wrapper>
</code>```

I am not sure, why it needs such complicated "workarounds", when it used to be so easy to do this in AngularJS.

Body:
I have a problem with the new ng-content transclusion.

Let's say I have a component my-component that, in its ngOnInit() function does some heavy operation on load (for now, just a console.log()).

I have a wrapper, that displays the content via transclusion (my-wrapper.component.html).

<ng-content></ng-content>

If I set the surroundings up like this, the log statement doesn't show:

<my-wrapper *ngIf="false">
    <my-component></my-component>
</my-wrapper>

I assume, the my-wrapper component does not get built, so the content is ignored.

But if I try to move the logic into the my-wrapper component like this (my-wrapper.component.html):

<ng-container *ngIf="false">
    <ng-content></ng-content>
</ng-container>

I always see the console.log() output. I guess, the my-component gets built and then stored away until the *ngIf becomes true inside my-wrapper.

The intention was to build a generic "list-item + detail" component. Say I have a list of N overview-elements (my-wrapper), that get rendered in a *ngFor loop. Every of those elements has its own detail component (my-component) that is supposed to load its own data, once I decide to show more infos to a specific item.

overview.html:

<ng-container *ngFor="let item of items">
    <my-wrapper>
        <my-component id="item.id"></my-component>
    </my-wrapper>
</ng-container>

my-wrapper.component.html:

Click for more

    <ng-content></ng-content>

Is there a way to tell Angular, to ignore the transcluded content until it is necessary to be added to the page? Analogously to how it was in AngularJS.

Body:
Based on the comment of @nsinreal I found an answer. I find it to be a bit abstruse, so I'm trying to post it here:

The answer is to work with ng-template and *ngTemplateOutlet.

In the my-wrapper component, set up the template like this (my-wrapper.component.html):

<div (click)="toggleDetail()">Click for more</div>
<div *ngIf="showDetail" [hidden]="!isInitialized">
    <ng-container *ngTemplateOutlet="detailRef"></ng-container>
</div>

Note, that the [hidden] there is not really necessary, it hides the "raw" template of the child until it decides it is done loading. Just make sure, not to put it in a *ngIf, otherwise the *ngTemplateOutlet will never get triggered, leading to nothing happening at all.

To set the detailRef, put this in the component code (my-wrapper.component.ts):

import { ContentChild, TemplateRef } from '@angular/core';

@Component({ ... })
export class MyWrapperComponent {
    @ContentChild(TemplateRef) detailRef;

    ...
}

Now, you can use the wrapper like this:

<my-wrapper>
    <ng-template>
        <my-component></my-component>
    </ng-template>
</my-wrapper>

I am not sure, why it needs such complicated "workarounds", when it used to be so easy to do this in AngularJS.


问:
Multi option dropdown with Angular in WordPress
I have a WP website with filtration built with Angular. Basically, it takes queries and filters it by Name / Location. How can I turn filtration from a single location to multiple locations filtration? </p>

<p>Let's say I have a dropdown select with multiple options. Once I pick any option - it displays with fitting results. I want to be able to check multiple option in the dropdown and see results accordingly. </p>

```<code><select ng-dropdown-multiselect class="physician_select_filter specialty_select dropdown-multiselect" ng-model="specialty_select" ng-click="toggleDropdown()">
                        <option value="all" selected>All</option>

        $choices = get_field('specialty_options', 'option', false);

        // explode the value so that each line is a new array piece
        $choices = explode("\n", $choices);

        // remove any unwanted white space
        $choices = array_map('trim', $choices);

        // loop through array and add to field 'choices'
        if( is_array($choices) ) {

            foreach( $choices as $choice ) {

                echo '<option value="'.$choice.'">'.$choice.'</option>';

            }

        }
</select>
</code>```

答:
Try adding multiple attribute to your <select> element and see the result.

<select multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>```
</div>
</div>
</p>

<blockquote>
  <p><strong>multiple</strong></p>

  <p>This Boolean attribute indicates that multiple options can be
  selected in the list. If it is not specified, then only one option can
  be selected at a time.</p>
</blockquote>

<p><strong>Your example:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>table,
th,
td {
  border: 1px solid black;
}

thead {
  color: green;
}</code>```

      Single select
      Multi select

        <select ng-dropdown-multiselect class="physician_select_filter specialty_select dropdown-multiselect" ng-model="specialty_select" ng-click="toggleDropdown()">
<option value="all" selected>All</option>
<option value="1" selected>Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3" selected>Option 3</option>
<option value="4" selected>Option 4</option>
<option value="5" selected>Option 5</option>
<option value="6" selected>Option 6</option>
</select>

        <select ng-dropdown-multiselect class="physician_select_filter specialty_select dropdown-multiselect" ng-model="specialty_select" ng-click="toggleDropdown()" multiple>
<option value="all" selected>All</option>
<option value="1" selected>Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3" selected>Option 3</option>
<option value="4" selected>Option 4</option>
<option value="5" selected>Option 5</option>
<option value="6" selected>Option 6</option>
</select>

```
</div>
</div>
</p>

<p><strong>Implementing chosen plugin for multiselect</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.chosen-select').chosen({
  width: "100%"
});
$('.chosen-select').on('change', function(evt, params) {
  console.log(params);
});</code>```

<link href="https://harvesthq.github.io/chosen/chosen.css" rel="stylesheet" />

<select data-placeholder="Choose your favourite countries..." class="chosen-select" multiple="" tabindex="-1">
            <option value=""></option>
            <option value="United States">United States</option>
            <option value="United Kingdom">United Kingdom</option>
            <option value="Afghanistan">Afghanistan</option>
            <option value="Aland Islands">Aland Islands</option>
            <option value="Albania">Albania</option>
            <option value="Algeria">Algeria</option>
            <option value="American Samoa">American Samoa</option>
            <option value="Andorra">Andorra</option>
            <option value="Angola">Angola</option>
            <option value="Anguilla">Anguilla</option>
            <option value="Antarctica">Antarctica</option>
            <option value="Antigua and Barbuda">Antigua and Barbuda</option>
            <option value="Argentina">Argentina</option>
            <option value="Armenia">Armenia</option>
            <option value="Aruba">Aruba</option>
            <option value="Australia">Australia</option>
            <option value="Austria">Austria</option>
            <option value="Azerbaijan">Azerbaijan</option>
            <option value="Bahamas">Bahamas</option>
            <option value="Bahrain">Bahrain</option>
            <option value="Bangladesh">Bangladesh</option>
            <option value="Barbados">Barbados</option>
            <option value="Belarus">Belarus</option>
            <option value="Belgium">Belgium</option>
            <option value="Belize">Belize</option>
            <option value="Benin">Benin</option>
            <option value="Bermuda">Bermuda</option>
            <option value="Bhutan">Bhutan</option>
            <option value="Bolivia, Plurinational State of">Bolivia, Plurinational State of</option>
            <option value="Bonaire, Sint Eustatius and Saba">Bonaire, Sint Eustatius and Saba</option>
            <option value="Bosnia and Herzegovina">Bosnia and Herzegovina</option>
            <option value="Botswana">Botswana</option>
            <option value="Bouvet Island">Bouvet Island</option>
            <option value="Brazil">Brazil</option>
            <option value="British Indian Ocean Territory">British Indian Ocean Territory</option>
            <option value="Brunei Darussalam">Brunei Darussalam</option>
            <option value="Bulgaria">Bulgaria</option>
            <option value="Burkina Faso">Burkina Faso</option>
            <option value="Burundi">Burundi</option>
            <option value="Cambodia">Cambodia</option>
            <option value="Cameroon">Cameroon</option>
            <option value="Canada">Canada</option>
            <option value="Cape Verde">Cape Verde</option>
            <option value="Cayman Islands">Cayman Islands</option>
            <option value="Central African Republic">Central African Republic</option>
            <option value="Chad">Chad</option>
            <option value="Chile">Chile</option>
            <option value="China">China</option>
            <option value="Christmas Island">Christmas Island</option>
            <option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option>
            <option value="Colombia">Colombia</option>
            <option value="Comoros">Comoros</option>
            <option value="Congo">Congo</option>
            <option value="Congo, The Democratic Republic of The">Congo, The Democratic Republic of The</option>
            <option value="Cook Islands">Cook Islands</option>
            <option value="Costa Rica">Costa Rica</option>
            <option value="Cote D'ivoire">Cote D'ivoire</option>
            <option value="Croatia">Croatia</option>
            <option value="Cuba">Cuba</option>
            <option value="Curacao">Curacao</option>
            <option value="Cyprus">Cyprus</option>
            <option value="Czech Republic">Czech Republic</option>
            <option value="Denmark">Denmark</option>
            <option value="Djibouti">Djibouti</option>
            <option value="Dominica">Dominica</option>
            <option value="Dominican Republic">Dominican Republic</option>
            <option value="Ecuador">Ecuador</option>
            <option value="Egypt">Egypt</option>
            <option value="El Salvador">El Salvador</option>
            <option value="Equatorial Guinea">Equatorial Guinea</option>
            <option value="Eritrea">Eritrea</option>
            <option value="Estonia">Estonia</option>
            <option value="Ethiopia">Ethiopia</option>
            <option value="Falkland Islands (Malvinas)">Falkland Islands (Malvinas)</option>
            <option value="Faroe Islands">Faroe Islands</option>
            <option value="Fiji">Fiji</option>
            <option value="Finland">Finland</option>
            <option value="France">France</option>
            <option value="French Guiana">French Guiana</option>
            <option value="French Polynesia">French Polynesia</option>
            <option value="French Southern Territories">French Southern Territories</option>
            <option value="Gabon">Gabon</option>
            <option value="Gambia">Gambia</option>
            <option value="Georgia">Georgia</option>
            <option value="Germany">Germany</option>
            <option value="Ghana">Ghana</option>
            <option value="Gibraltar">Gibraltar</option>
            <option value="Greece">Greece</option>
            <option value="Greenland">Greenland</option>
            <option value="Grenada">Grenada</option>
            <option value="Guadeloupe">Guadeloupe</option>
            <option value="Guam">Guam</option>
            <option value="Guatemala">Guatemala</option>
            <option value="Guernsey">Guernsey</option>
            <option value="Guinea">Guinea</option>
            <option value="Guinea-bissau">Guinea-bissau</option>
            <option value="Guyana">Guyana</option>
            <option value="Haiti">Haiti</option>
            <option value="Heard Island and Mcdonald Islands">Heard Island and Mcdonald Islands</option>
            <option value="Holy See (Vatican City State)">Holy See (Vatican City State)</option>
            <option value="Honduras">Honduras</option>
            <option value="Hong Kong">Hong Kong</option>
            <option value="Hungary">Hungary</option>
            <option value="Iceland">Iceland</option>
            <option value="India">India</option>
            <option value="Indonesia">Indonesia</option>
            <option value="Iran, Islamic Republic of">Iran, Islamic Republic of</option>
            <option value="Iraq">Iraq</option>
            <option value="Ireland">Ireland</option>
            <option value="Isle of Man">Isle of Man</option>
            <option value="Israel">Israel</option>
            <option value="Italy">Italy</option>
            <option value="Jamaica">Jamaica</option>
            <option value="Japan">Japan</option>
            <option value="Jersey">Jersey</option>
            <option value="Jordan">Jordan</option>
            <option value="Kazakhstan">Kazakhstan</option>
            <option value="Kenya">Kenya</option>
            <option value="Kiribati">Kiribati</option>
            <option value="Korea, Democratic People's Republic of">Korea, Democratic People's Republic of</option>
            <option value="Korea, Republic of">Korea, Republic of</option>
            <option value="Kuwait">Kuwait</option>
            <option value="Kyrgyzstan">Kyrgyzstan</option>
            <option value="Lao People's Democratic Republic">Lao People's Democratic Republic</option>
            <option value="Latvia">Latvia</option>
            <option value="Lebanon">Lebanon</option>
            <option value="Lesotho">Lesotho</option>
            <option value="Liberia">Liberia</option>
            <option value="Libya">Libya</option>
            <option value="Liechtenstein">Liechtenstein</option>
            <option value="Lithuania">Lithuania</option>
            <option value="Luxembourg">Luxembourg</option>
            <option value="Macao">Macao</option>
            <option value="Macedonia, The Former Yugoslav Republic of">Macedonia, The Former Yugoslav Republic of</option>
            <option value="Madagascar">Madagascar</option>
            <option value="Malawi">Malawi</option>
            <option value="Malaysia">Malaysia</option>
            <option value="Maldives">Maldives</option>
            <option value="Mali">Mali</option>
            <option value="Malta">Malta</option>
            <option value="Marshall Islands">Marshall Islands</option>
            <option value="Martinique">Martinique</option>
            <option value="Mauritania">Mauritania</option>
            <option value="Mauritius">Mauritius</option>
            <option value="Mayotte">Mayotte</option>
            <option value="Mexico">Mexico</option>
            <option value="Micronesia, Federated States of">Micronesia, Federated States of</option>
            <option value="Moldova, Republic of">Moldova, Republic of</option>
            <option value="Monaco">Monaco</option>
            <option value="Mongolia">Mongolia</option>
            <option value="Montenegro">Montenegro</option>
            <option value="Montserrat">Montserrat</option>
            <option value="Morocco">Morocco</option>
            <option value="Mozambique">Mozambique</option>
            <option value="Myanmar">Myanmar</option>
            <option value="Namibia">Namibia</option>
            <option value="Nauru">Nauru</option>
            <option value="Nepal">Nepal</option>
            <option value="Netherlands">Netherlands</option>
            <option value="New Caledonia">New Caledonia</option>
            <option value="New Zealand">New Zealand</option>
            <option value="Nicaragua">Nicaragua</option>
            <option value="Niger">Niger</option>
            <option value="Nigeria">Nigeria</option>
            <option value="Niue">Niue</option>
            <option value="Norfolk Island">Norfolk Island</option>
            <option value="Northern Mariana Islands">Northern Mariana Islands</option>
            <option value="Norway">Norway</option>
            <option value="Oman">Oman</option>
            <option value="Pakistan">Pakistan</option>
            <option value="Palau">Palau</option>
            <option value="Palestinian Territory, Occupied">Palestinian Territory, Occupied</option>
            <option value="Panama">Panama</option>
            <option value="Papua New Guinea">Papua New Guinea</option>
            <option value="Paraguay">Paraguay</option>
            <option value="Peru">Peru</option>
            <option value="Philippines">Philippines</option>
            <option value="Pitcairn">Pitcairn</option>
            <option value="Poland">Poland</option>
            <option value="Portugal">Portugal</option>
            <option value="Puerto Rico">Puerto Rico</option>
            <option value="Qatar">Qatar</option>
            <option value="Reunion">Reunion</option>
            <option value="Romania">Romania</option>
            <option value="Russian Federation">Russian Federation</option>
            <option value="Rwanda">Rwanda</option>
            <option value="Saint Barthelemy">Saint Barthelemy</option>
            <option value="Saint Helena, Ascension and Tristan da Cunha">Saint Helena, Ascension and Tristan da Cunha</option>
            <option value="Saint Kitts and Nevis">Saint Kitts and Nevis</option>
            <option value="Saint Lucia">Saint Lucia</option>
            <option value="Saint Martin (French part)">Saint Martin (French part)</option>
            <option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option>
            <option value="Saint Vincent and The Grenadines">Saint Vincent and The Grenadines</option>
            <option value="Samoa">Samoa</option>
            <option value="San Marino">San Marino</option>
            <option value="Sao Tome and Principe">Sao Tome and Principe</option>
            <option value="Saudi Arabia">Saudi Arabia</option>
            <option value="Senegal">Senegal</option>
            <option value="Serbia">Serbia</option>
            <option value="Seychelles">Seychelles</option>
            <option value="Sierra Leone">Sierra Leone</option>
            <option value="Singapore">Singapore</option>
            <option value="Sint Maarten (Dutch part)">Sint Maarten (Dutch part)</option>
            <option value="Slovakia">Slovakia</option>
            <option value="Slovenia">Slovenia</option>
            <option value="Solomon Islands">Solomon Islands</option>
            <option value="Somalia">Somalia</option>
            <option value="South Africa">South Africa</option>
            <option value="South Georgia and The South Sandwich Islands">South Georgia and The South Sandwich Islands</option>
            <option value="South Sudan">South Sudan</option>
            <option value="Spain">Spain</option>
            <option value="Sri Lanka">Sri Lanka</option>
            <option value="Sudan">Sudan</option>
            <option value="Suriname">Suriname</option>
            <option value="Svalbard and Jan Mayen">Svalbard and Jan Mayen</option>
            <option value="Swaziland">Swaziland</option>
            <option value="Sweden">Sweden</option>
            <option value="Switzerland">Switzerland</option>
            <option value="Syrian Arab Republic">Syrian Arab Republic</option>
            <option value="Taiwan, Province of China">Taiwan, Province of China</option>
            <option value="Tajikistan">Tajikistan</option>
            <option value="Tanzania, United Republic of">Tanzania, United Republic of</option>
            <option value="Thailand">Thailand</option>
            <option value="Timor-leste">Timor-leste</option>
            <option value="Togo">Togo</option>
            <option value="Tokelau">Tokelau</option>
            <option value="Tonga">Tonga</option>
            <option value="Trinidad and Tobago">Trinidad and Tobago</option>
            <option value="Tunisia">Tunisia</option>
            <option value="Turkey">Turkey</option>
            <option value="Turkmenistan">Turkmenistan</option>
            <option value="Turks and Caicos Islands">Turks and Caicos Islands</option>
            <option value="Tuvalu">Tuvalu</option>
            <option value="Uganda">Uganda</option>
            <option value="Ukraine">Ukraine</option>
            <option value="United Arab Emirates">United Arab Emirates</option>
            <option value="United Kingdom">United Kingdom</option>
            <option value="United States">United States</option>
            <option value="United States Minor Outlying Islands">United States Minor Outlying Islands</option>
            <option value="Uruguay">Uruguay</option>
            <option value="Uzbekistan">Uzbekistan</option>
            <option value="Vanuatu">Vanuatu</option>
            <option value="Venezuela, Bolivarian Republic of">Venezuela, Bolivarian Republic of</option>
            <option value="Viet Nam">Viet Nam</option>
            <option value="Virgin Islands, British">Virgin Islands, British</option>
            <option value="Virgin Islands, U.S.">Virgin Islands, U.S.</option>
            <option value="Wallis and Futuna">Wallis and Futuna</option>
            <option value="Western Sahara">Western Sahara</option>
            <option value="Yemen">Yemen</option>
            <option value="Zambia">Zambia</option>
            <option value="Zimbabwe">Zimbabwe</option>
          </select>```

Body:
I have a WP website with filtration built with Angular. Basically, it takes queries and filters it by Name / Location. How can I turn filtration from a single location to multiple locations filtration?

Let's say I have a dropdown select with multiple options. Once I pick any option - it displays with fitting results. I want to be able to check multiple option in the dropdown and see results accordingly.

<select ng-dropdown-multiselect class="physician_select_filter specialty_select dropdown-multiselect" ng-model="specialty_select" ng-click="toggleDropdown()">
                        <option value="all" selected>All</option>

        $choices = get_field('specialty_options', 'option', false);

        // explode the value so that each line is a new array piece
        $choices = explode("\n", $choices);

        // remove any unwanted white space
        $choices = array_map('trim', $choices);

        // loop through array and add to field 'choices'
        if( is_array($choices) ) {

            foreach( $choices as $choice ) {

                echo '<option value="'.$choice.'">'.$choice.'</option>';

            }

        }
</select>

Body:
Try adding multiple attribute to your <select> element and see the result.

<select multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

multiple

This Boolean attribute indicates that multiple options can be
  selected in the list. If it is not specified, then only one option can
  be selected at a time.

Your example:

table,
th,
td {
  border: 1px solid black;
}

thead {
  color: green;
}

<table>
  <thead>
    <tr>
      <th>Single select</th>
      <th>Multi select</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <select ng-dropdown-multiselect class="physician_select_filter specialty_select dropdown-multiselect" ng-model="specialty_select" ng-click="toggleDropdown()">
<option value="all" selected>All</option>
<option value="1" selected>Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3" selected>Option 3</option>
<option value="4" selected>Option 4</option>
<option value="5" selected>Option 5</option>
<option value="6" selected>Option 6</option>
</select>
      </td>
      <td>
        <select ng-dropdown-multiselect class="physician_select_filter specialty_select dropdown-multiselect" ng-model="specialty_select" ng-click="toggleDropdown()" multiple>
<option value="all" selected>All</option>
<option value="1" selected>Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3" selected>Option 3</option>
<option value="4" selected>Option 4</option>
<option value="5" selected>Option 5</option>
<option value="6" selected>Option 6</option>
</select>
      </td>
    </tr>
  </tbody>
</table>

Implementing chosen plugin for multiselect

$('.chosen-select').chosen({
  width: "100%"
});
$('.chosen-select').on('change', function(evt, params) {
  console.log(params);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://harvesthq.github.io/chosen/chosen.jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://harvesthq.github.io/chosen/chosen.css" rel="stylesheet" />

<select data-placeholder="Choose your favourite countries..." class="chosen-select" multiple="" tabindex="-1">
            <option value=""></option>
            <option value="United States">United States</option>
            <option value="United Kingdom">United Kingdom</option>
            <option value="Afghanistan">Afghanistan</option>
            <option value="Aland Islands">Aland Islands</option>
            <option value="Albania">Albania</option>
            <option value="Algeria">Algeria</option>
            <option value="American Samoa">American Samoa</option>
            <option value="Andorra">Andorra</option>
            <option value="Angola">Angola</option>
            <option value="Anguilla">Anguilla</option>
            <option value="Antarctica">Antarctica</option>
            <option value="Antigua and Barbuda">Antigua and Barbuda</option>
            <option value="Argentina">Argentina</option>
            <option value="Armenia">Armenia</option>
            <option value="Aruba">Aruba</option>
            <option value="Australia">Australia</option>
            <option value="Austria">Austria</option>
            <option value="Azerbaijan">Azerbaijan</option>
            <option value="Bahamas">Bahamas</option>
            <option value="Bahrain">Bahrain</option>
            <option value="Bangladesh">Bangladesh</option>
            <option value="Barbados">Barbados</option>
            <option value="Belarus">Belarus</option>
            <option value="Belgium">Belgium</option>
            <option value="Belize">Belize</option>
            <option value="Benin">Benin</option>
            <option value="Bermuda">Bermuda</option>
            <option value="Bhutan">Bhutan</option>
            <option value="Bolivia, Plurinational State of">Bolivia, Plurinational State of</option>
            <option value="Bonaire, Sint Eustatius and Saba">Bonaire, Sint Eustatius and Saba</option>
            <option value="Bosnia and Herzegovina">Bosnia and Herzegovina</option>
            <option value="Botswana">Botswana</option>
            <option value="Bouvet Island">Bouvet Island</option>
            <option value="Brazil">Brazil</option>
            <option value="British Indian Ocean Territory">British Indian Ocean Territory</option>
            <option value="Brunei Darussalam">Brunei Darussalam</option>
            <option value="Bulgaria">Bulgaria</option>
            <option value="Burkina Faso">Burkina Faso</option>
            <option value="Burundi">Burundi</option>
            <option value="Cambodia">Cambodia</option>
            <option value="Cameroon">Cameroon</option>
            <option value="Canada">Canada</option>
            <option value="Cape Verde">Cape Verde</option>
            <option value="Cayman Islands">Cayman Islands</option>
            <option value="Central African Republic">Central African Republic</option>
            <option value="Chad">Chad</option>
            <option value="Chile">Chile</option>
            <option value="China">China</option>
            <option value="Christmas Island">Christmas Island</option>
            <option value="Cocos (Keeling) Islands">Cocos (Keeling) Islands</option>
            <option value="Colombia">Colombia</option>
            <option value="Comoros">Comoros</option>
            <option value="Congo">Congo</option>
            <option value="Congo, The Democratic Republic of The">Congo, The Democratic Republic of The</option>
            <option value="Cook Islands">Cook Islands</option>
            <option value="Costa Rica">Costa Rica</option>
            <option value="Cote D'ivoire">Cote D'ivoire</option>
            <option value="Croatia">Croatia</option>
            <option value="Cuba">Cuba</option>
            <option value="Curacao">Curacao</option>
            <option value="Cyprus">Cyprus</option>
            <option value="Czech Republic">Czech Republic</option>
            <option value="Denmark">Denmark</option>
            <option value="Djibouti">Djibouti</option>
            <option value="Dominica">Dominica</option>
            <option value="Dominican Republic">Dominican Republic</option>
            <option value="Ecuador">Ecuador</option>
            <option value="Egypt">Egypt</option>
            <option value="El Salvador">El Salvador</option>
            <option value="Equatorial Guinea">Equatorial Guinea</option>
            <option value="Eritrea">Eritrea</option>
            <option value="Estonia">Estonia</option>
            <option value="Ethiopia">Ethiopia</option>
            <option value="Falkland Islands (Malvinas)">Falkland Islands (Malvinas)</option>
            <option value="Faroe Islands">Faroe Islands</option>
            <option value="Fiji">Fiji</option>
            <option value="Finland">Finland</option>
            <option value="France">France</option>
            <option value="French Guiana">French Guiana</option>
            <option value="French Polynesia">French Polynesia</option>
            <option value="French Southern Territories">French Southern Territories</option>
            <option value="Gabon">Gabon</option>
            <option value="Gambia">Gambia</option>
            <option value="Georgia">Georgia</option>
            <option value="Germany">Germany</option>
            <option value="Ghana">Ghana</option>
            <option value="Gibraltar">Gibraltar</option>
            <option value="Greece">Greece</option>
            <option value="Greenland">Greenland</option>
            <option value="Grenada">Grenada</option>
            <option value="Guadeloupe">Guadeloupe</option>
            <option value="Guam">Guam</option>
            <option value="Guatemala">Guatemala</option>
            <option value="Guernsey">Guernsey</option>
            <option value="Guinea">Guinea</option>
            <option value="Guinea-bissau">Guinea-bissau</option>
            <option value="Guyana">Guyana</option>
            <option value="Haiti">Haiti</option>
            <option value="Heard Island and Mcdonald Islands">Heard Island and Mcdonald Islands</option>
            <option value="Holy See (Vatican City State)">Holy See (Vatican City State)</option>
            <option value="Honduras">Honduras</option>
            <option value="Hong Kong">Hong Kong</option>
            <option value="Hungary">Hungary</option>
            <option value="Iceland">Iceland</option>
            <option value="India">India</option>
            <option value="Indonesia">Indonesia</option>
            <option value="Iran, Islamic Republic of">Iran, Islamic Republic of</option>
            <option value="Iraq">Iraq</option>
            <option value="Ireland">Ireland</option>
            <option value="Isle of Man">Isle of Man</option>
            <option value="Israel">Israel</option>
            <option value="Italy">Italy</option>
            <option value="Jamaica">Jamaica</option>
            <option value="Japan">Japan</option>
            <option value="Jersey">Jersey</option>
            <option value="Jordan">Jordan</option>
            <option value="Kazakhstan">Kazakhstan</option>
            <option value="Kenya">Kenya</option>
            <option value="Kiribati">Kiribati</option>
            <option value="Korea, Democratic People's Republic of">Korea, Democratic People's Republic of</option>
            <option value="Korea, Republic of">Korea, Republic of</option>
            <option value="Kuwait">Kuwait</option>
            <option value="Kyrgyzstan">Kyrgyzstan</option>
            <option value="Lao People's Democratic Republic">Lao People's Democratic Republic</option>
            <option value="Latvia">Latvia</option>
            <option value="Lebanon">Lebanon</option>
            <option value="Lesotho">Lesotho</option>
            <option value="Liberia">Liberia</option>
            <option value="Libya">Libya</option>
            <option value="Liechtenstein">Liechtenstein</option>
            <option value="Lithuania">Lithuania</option>
            <option value="Luxembourg">Luxembourg</option>
            <option value="Macao">Macao</option>
            <option value="Macedonia, The Former Yugoslav Republic of">Macedonia, The Former Yugoslav Republic of</option>
            <option value="Madagascar">Madagascar</option>
            <option value="Malawi">Malawi</option>
            <option value="Malaysia">Malaysia</option>
            <option value="Maldives">Maldives</option>
            <option value="Mali">Mali</option>
            <option value="Malta">Malta</option>
            <option value="Marshall Islands">Marshall Islands</option>
            <option value="Martinique">Martinique</option>
            <option value="Mauritania">Mauritania</option>
            <option value="Mauritius">Mauritius</option>
            <option value="Mayotte">Mayotte</option>
            <option value="Mexico">Mexico</option>
            <option value="Micronesia, Federated States of">Micronesia, Federated States of</option>
            <option value="Moldova, Republic of">Moldova, Republic of</option>
            <option value="Monaco">Monaco</option>
            <option value="Mongolia">Mongolia</option>
            <option value="Montenegro">Montenegro</option>
            <option value="Montserrat">Montserrat</option>
            <option value="Morocco">Morocco</option>
            <option value="Mozambique">Mozambique</option>
            <option value="Myanmar">Myanmar</option>
            <option value="Namibia">Namibia</option>
            <option value="Nauru">Nauru</option>
            <option value="Nepal">Nepal</option>
            <option value="Netherlands">Netherlands</option>
            <option value="New Caledonia">New Caledonia</option>
            <option value="New Zealand">New Zealand</option>
            <option value="Nicaragua">Nicaragua</option>
            <option value="Niger">Niger</option>
            <option value="Nigeria">Nigeria</option>
            <option value="Niue">Niue</option>
            <option value="Norfolk Island">Norfolk Island</option>
            <option value="Northern Mariana Islands">Northern Mariana Islands</option>
            <option value="Norway">Norway</option>
            <option value="Oman">Oman</option>
            <option value="Pakistan">Pakistan</option>
            <option value="Palau">Palau</option>
            <option value="Palestinian Territory, Occupied">Palestinian Territory, Occupied</option>
            <option value="Panama">Panama</option>
            <option value="Papua New Guinea">Papua New Guinea</option>
            <option value="Paraguay">Paraguay</option>
            <option value="Peru">Peru</option>
            <option value="Philippines">Philippines</option>
            <option value="Pitcairn">Pitcairn</option>
            <option value="Poland">Poland</option>
            <option value="Portugal">Portugal</option>
            <option value="Puerto Rico">Puerto Rico</option>
            <option value="Qatar">Qatar</option>
            <option value="Reunion">Reunion</option>
            <option value="Romania">Romania</option>
            <option value="Russian Federation">Russian Federation</option>
            <option value="Rwanda">Rwanda</option>
            <option value="Saint Barthelemy">Saint Barthelemy</option>
            <option value="Saint Helena, Ascension and Tristan da Cunha">Saint Helena, Ascension and Tristan da Cunha</option>
            <option value="Saint Kitts and Nevis">Saint Kitts and Nevis</option>
            <option value="Saint Lucia">Saint Lucia</option>
            <option value="Saint Martin (French part)">Saint Martin (French part)</option>
            <option value="Saint Pierre and Miquelon">Saint Pierre and Miquelon</option>
            <option value="Saint Vincent and The Grenadines">Saint Vincent and The Grenadines</option>
            <option value="Samoa">Samoa</option>
            <option value="San Marino">San Marino</option>
            <option value="Sao Tome and Principe">Sao Tome and Principe</option>
            <option value="Saudi Arabia">Saudi Arabia</option>
            <option value="Senegal">Senegal</option>
            <option value="Serbia">Serbia</option>
            <option value="Seychelles">Seychelles</option>
            <option value="Sierra Leone">Sierra Leone</option>
            <option value="Singapore">Singapore</option>
            <option value="Sint Maarten (Dutch part)">Sint Maarten (Dutch part)</option>
            <option value="Slovakia">Slovakia</option>
            <option value="Slovenia">Slovenia</option>
            <option value="Solomon Islands">Solomon Islands</option>
            <option value="Somalia">Somalia</option>
            <option value="South Africa">South Africa</option>
            <option value="South Georgia and The South Sandwich Islands">South Georgia and The South Sandwich Islands</option>
            <option value="South Sudan">South Sudan</option>
            <option value="Spain">Spain</option>
            <option value="Sri Lanka">Sri Lanka</option>
            <option value="Sudan">Sudan</option>
            <option value="Suriname">Suriname</option>
            <option value="Svalbard and Jan Mayen">Svalbard and Jan Mayen</option>
            <option value="Swaziland">Swaziland</option>
            <option value="Sweden">Sweden</option>
            <option value="Switzerland">Switzerland</option>
            <option value="Syrian Arab Republic">Syrian Arab Republic</option>
            <option value="Taiwan, Province of China">Taiwan, Province of China</option>
            <option value="Tajikistan">Tajikistan</option>
            <option value="Tanzania, United Republic of">Tanzania, United Republic of</option>
            <option value="Thailand">Thailand</option>
            <option value="Timor-leste">Timor-leste</option>
            <option value="Togo">Togo</option>
            <option value="Tokelau">Tokelau</option>
            <option value="Tonga">Tonga</option>
            <option value="Trinidad and Tobago">Trinidad and Tobago</option>
            <option value="Tunisia">Tunisia</option>
            <option value="Turkey">Turkey</option>
            <option value="Turkmenistan">Turkmenistan</option>
            <option value="Turks and Caicos Islands">Turks and Caicos Islands</option>
            <option value="Tuvalu">Tuvalu</option>
            <option value="Uganda">Uganda</option>
            <option value="Ukraine">Ukraine</option>
            <option value="United Arab Emirates">United Arab Emirates</option>
            <option value="United Kingdom">United Kingdom</option>
            <option value="United States">United States</option>
            <option value="United States Minor Outlying Islands">United States Minor Outlying Islands</option>
            <option value="Uruguay">Uruguay</option>
            <option value="Uzbekistan">Uzbekistan</option>
            <option value="Vanuatu">Vanuatu</option>
            <option value="Venezuela, Bolivarian Republic of">Venezuela, Bolivarian Republic of</option>
            <option value="Viet Nam">Viet Nam</option>
            <option value="Virgin Islands, British">Virgin Islands, British</option>
            <option value="Virgin Islands, U.S.">Virgin Islands, U.S.</option>
            <option value="Wallis and Futuna">Wallis and Futuna</option>
            <option value="Western Sahara">Western Sahara</option>
            <option value="Yemen">Yemen</option>
            <option value="Zambia">Zambia</option>
            <option value="Zimbabwe">Zimbabwe</option>
          </select>


问:
Can one upload files using AMP validated html?
Can one upload files using AMP validated html?  It seems that the input type="file" is disabled in the amp-form html.</p>

答:
No. We can't upload file till now with AMP validation. AMP HTML is HTML with some restrictions for reliable performance. In future AMP will give some options to upload file. But at present there is no solution for file upload page with AMP validated HTML.

AMP Inputs and Fields:

Allowed:

Other form-related elements, including: <textarea>, <select>, <option>, <fieldset>, , <input type=text>, <input type=submit>, and so on.

[amp-selector][1]

Not Allowed:

<input type=button>, <input type=file>, <input type=image> and <input type=password>

Most of the form-related attributes on inputs including: form, formaction, formtarget, formmethod and others.

Body:
No. We can't upload file till now with AMP validation. AMP HTML is HTML with some restrictions for reliable performance. In future AMP will give some options to upload file. But at present there is no solution for file upload page with AMP validated HTML.

AMP Inputs and Fields:

Allowed:

Other form-related elements, including: <textarea>, <select>, <option>, <fieldset>, <label>, <input type=text>, <input type=submit>, and so on.

[amp-selector][1]

Not Allowed:

<input type=button>, <input type=file>, <input type=image> and <input type=password>

Most of the form-related attributes on inputs including: form, formaction, formtarget, formmethod and others.


问:
2d scatter chart Matplotlib
```<code>import matplotlib.pyplot as plt
x = [1,2,3,4,5,-6,7,8]
y = [5,2,4,-2,1,4,5,2]
plt.scatter(x,y, label='test', color='k', s=25, marker="o")
plt.xlabel('x')
plt.ylabel('y')
plt.title('Test')
plt.legend()
plt.show()
plt.legend()
plt.show()
</code>```

When the value is y changes to negative i am trying to change color='r'
and when the value of x change to negative i am trying to change marker="o" to "x". I am new to matplotlib.

As a add on question, how to affect color and marker for x and y falling in ranges like -1 to -.5, .5 to 0, 0 to .5, .5 to 1. I am need of four markers in two colors amounting to 8 variations.

答:
This is a case where Altair would be a breeze.

```<code>import pandas as pd

x = [1,2,3,4,5,-6,7,8]
y = [5,2,4,-2,1,4,5,2]

df = pd.DataFrame({'x':x, 'y':y})
df['cat_y'] = pd.cut(df['y'], bins=[-5, -1, 1, 5])
df['x>0'] = df['x']>0
Chart(df).mark_point().encode(x='x',y='y',color='cat_y', shape='x>0').configure_cell(width=200, height=200)
</code>```

Title: 2d scatter chart Matplotlib

Body:
import matplotlib.pyplot as plt
x = [1,2,3,4,5,-6,7,8]
y = [5,2,4,-2,1,4,5,2]
plt.scatter(x,y, label='test', color='k', s=25, marker="o")
plt.xlabel('x')
plt.ylabel('y')
plt.title('Test')
plt.legend()
plt.show()
plt.legend()
plt.show()

When the value is y changes to negative i am trying to change color='r'
and when the value of x change to negative i am trying to change marker="o" to "x". I am new to matplotlib.

As a add on question, how to affect color and marker for x and y falling in ranges like -1 to -.5, .5 to 0, 0 to .5, .5 to 1. I am need of four markers in two colors amounting to 8 variations.

Body:
This is a case where Altair would be a breeze.

import pandas as pd

x = [1,2,3,4,5,-6,7,8]
y = [5,2,4,-2,1,4,5,2]

df = pd.DataFrame({'x':x, 'y':y})
df['cat_y'] = pd.cut(df['y'], bins=[-5, -1, 1, 5])
df['x>0'] = df['x']>0
Chart(df).mark_point().encode(x='x',y='y',color='cat_y', shape='x>0').configure_cell(width=200, height=200)


问:
NodeJS Async - Continue execution for multiple http requests even if some fail
I am trying to make multiple HTTP requests and cumulate, display the results in NodeJS using the following code:

```<code>const async = require('async');
const request = require('request');

function httpGet(url, callback) {
  const options = {
    url :  url,
    json : true
  };
  request(options,
    function(err, res, body) {
      console.log("invoked")
      callback(err, body);
    }
  ).on('error', function(err) {
    console.log(err)
  });
}

const urls= [
  "http://1.2.3.4:30500/status/health/summary",
  "http://5.6.7.8:30505/status/health/summary"
];

async.map(urls, httpGet, function (err, res){
  if (err)
    console.log(err);
  else
    console.log(res);
});
</code>```

The problem here is, if the first request(http://1.2.3.4:30500/status/health/summary) fails (like connection refused etc.), the second one does not go through. I know that I am making a silly mistake but cannot find it. Any help appreciated !

答:
If you want async.map NOT to fail fast you could do it like this

```<code>const async = require('async');
const request = require('request');

function httpGet(url, callback) {
  const options = {
    url :  url,
    json : true
  };
  request(options,
    function alwaysReportSuccess(err, res, body) {
      callback(null, {
        success: !err,
        result: err ? err : body
      });
    }
  ).on('error', function(err) {
    console.log(err)
  });
}

const urls= [
  "http://1.2.3.4:30500/status/health/summary",
  "http://5.6.7.8:30505/status/health/summary"
];

async.map(urls, httpGet, function alwaysOk(_, res){
    console.log(res); // will be an array with success flags and results
});
</code>```

Body:
I am trying to make multiple HTTP requests and cumulate, display the results in NodeJS using the following code:

const async = require('async');
const request = require('request');

function httpGet(url, callback) {
  const options = {
    url :  url,
    json : true
  };
  request(options,
    function(err, res, body) {
      console.log("invoked")
      callback(err, body);
    }
  ).on('error', function(err) {
    console.log(err)
  });
}

const urls= [
  "http://1.2.3.4:30500/status/health/summary",
  "http://5.6.7.8:30505/status/health/summary"
];

async.map(urls, httpGet, function (err, res){
  if (err)
    console.log(err);
  else
    console.log(res);
});

The problem here is, if the first request(http://1.2.3.4:30500/status/health/summary) fails (like connection refused etc.), the second one does not go through. I know that I am making a silly mistake but cannot find it. Any help appreciated !

Body:
If you want async.map NOT to fail fast you could do it like this

const async = require('async');
const request = require('request');

function httpGet(url, callback) {
  const options = {
    url :  url,
    json : true
  };
  request(options,
    function alwaysReportSuccess(err, res, body) {
      callback(null, {
        success: !err,
        result: err ? err : body
      });
    }
  ).on('error', function(err) {
    console.log(err)
  });
}

const urls= [
  "http://1.2.3.4:30500/status/health/summary",
  "http://5.6.7.8:30505/status/health/summary"
];

async.map(urls, httpGet, function alwaysOk(_, res){
    console.log(res); // will be an array with success flags and results
});


问:
When I git commit some code, it prompts some errors as follows, what's wrong?

And the code management system that I used is Gerrit.

答:
It seems that you've set your editor to mate. Your shell does not find the command, because the editor is either not in your path or not installed.

You could set the editor to an editor of your choice (it's vim in the example) by running this command:

```<code>git config --global core.editor "vim"
</code>```

Body:
It seems that you've set your editor to mate. Your shell does not find the command, because the editor is either not in your path or not installed.

You could set the editor to an editor of your choice (it's vim in the example) by running this command:

git config --global core.editor "vim"


问:
method argument is not accessible by name inside method
Is it a bug in android studio or java, don't know. I was working on an astronomy application. I have created a method to get phase of moon. It takes two argument but only one argument is accessible by name. In debugger it says argument not found but when I assign to some other variable, it gets assigned. No runtime error in execution.

Argument that is not accessible is moon_degrees but when I assign it's value to variable moon_degree it works.

Don't know what's happening

Android studio Version 2.0

windows 7 X86

答:
This may be a known bug:

https://issuetracker.google.com/issues/37019591

You could provide your case to the bug report to help to find the cause of this.


问:
Difference between ./usr and /usr when running a command
I have two directories in my new CentOS7:

Work_Folder1/my_project/linux_dev.cfg

Work_Folder2/my_project/linux_dev.cfg

If I try to run the command ./usr/bin/buildout -c linux_dev.cfg the build works fine from dir (1). If I try the same from (2) it says the ./usr/bin/buildout not exists.

After trying I see that from (2), /usr/bin/buildout -c linux_dev.cfg command works. So whats the role of . in here?

答:
The . indicates that you want to start looking for the buildout executable in the directory you are currently in. So for ./usr/bin/buildout, we are looking for a usr directory under the current directory, a bin directory under that, and a buildout executable under that.

Without the dot (i.e. /usr/bin/buildout), we begin looking in the root of the filesystem (i.e. /) for a usr directory, and then bin and buildout.

I'll bet if you look in your Work_Folder1/my_project/linux_dev.cfg directory, you'll find a usr directory. If you look in Work_Folder2/my_project/linux_dev.cfg, you won't.


问:
Why constraints is always Zero,is Storyboard preventing from edges?
Let me trying to explain my question.I have noted from long time during app designing in Storyboard/Xib. In all cases for eg while dragging some controls into storyboard obviously it shows the blue lines helps to us place controls correctly.But it's seems prevent controls from UIView(main view) layout to place edges on controller.

When we trying to place controls the blue lines prevents us from edges.see below image

But why constraints always zero  even we are not placed at edges..it should be approximately 10,10,10..,

So my Qus is

Is Storyboard/Autolayout preventing to place controls at edges?

If yes.Then why all constraints is Zero ?

If No.Then what is the use of corner blue lines(eg:first image)?

答:
Storyboard/Autolayout is not preventing to place controls at edges, you can always place your objects there and apply auto layout by unchecking "Constrain to margin" option in auto layout menu.

It is zero because "Constrain to margin" option is checked. Placed object distance will be calculated from that bound margin line as long as "Constrain to margin" option is checked. Uncheck it and you will get exact values from edges.

The use of this blue line is... if you add any UIScreenEdgePanGestureRecognizer, it will work outside those margin lines. placing an object between the edge and provided blue line may interfere with this kind of gesture recognizers.


问:
How to change a DHCP interfaces to STATIC interfaces in OVH VPS on Ubuntu 16.04
Im new into LINUX and i need your help for my OVH VPS Ubuntu Server 16.04LTS interface actually on DHCP to STATIC

Actually my /etc/network/interfaces file is :

```<code># This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# Source interfaces
# Please check /etc/network/interfaces.d before changing this file
# as interfaces may have been defined in /etc/network/interfaces.d
# See LP: #1262951
source /etc/network/interfaces.d/*.cfg
</code>```

The source path /etc/network/interfaces.d/*.cfg have only one file named : 50-cloud-init.cfg and this file contain :

```<code>auto lo
iface lo inet loopback

auto ens3
iface ens3 inet dhcp
</code>```

So my IP address is 149.xxx.xxx.61, I need to transform this to have an iface ens3 static for my IP address.

Actually ifconfig -a is :

```<code>ens3      Link encap:Ethernet  HWaddr fa:16:3e:ae:e3:83
          inet addr:149.xxx.xxx.61  Bcast:149.xxx.xxx.61  Mask:255.255.255.255
          inet6 addr: fe80::xxxx:xxxx:feae:e383/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:894526 errors:0 dropped:0 overruns:0 frame:0
          TX packets:297070 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:102187906 (102.1 MB)  TX bytes:63602471 (63.6 MB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:14743 errors:0 dropped:0 overruns:0 frame:0
          TX packets:14743 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:31459525 (31.4 MB)  TX bytes:31459525 (31.4 MB)
</code>```

How can I do this ?

答:
First, you must find your IP and Gateway for IPv6. They can be found in your OVH manager.

Modify your network config file with this command (use sudo if you are not root) :

nano /etc/network/interfaces.d/50-cloud-init.cfg

Add these lines :

```<code>iface eth0 inet6 static
    address YOUR_IPV6
    netmask IPV6_PREFIX
    post-up /sbin/ip -f inet6 route add IPV6_GATEWAY dev eth0
    post-up /sbin/ip -f inet6 route add default via IPV6_GATEWAY
    pre-down /sbin/ip -f inet6 route del IPV6_GATEWAY dev eth0
    pre-down /sbin/ip -f inet6 route del default via IPV6_GATEWAY
</code>```

YOUR_IPV6 must be replaced with your IPv6.
IPV6_PREFIX must be replaced with 128.
IPV6_GATEWAY must be replaced with your IPv6 gateway.

Reboot your VPS.

Reference : http://docs.ovh.ca/fr/guides-network-ipv6.html#debian-derivatives-ubuntu-crunchbang-steamos

Body:
Im new into LINUX and i need your help for my OVH VPS Ubuntu Server 16.04LTS interface actually on DHCP to STATIC

Actually my /etc/network/interfaces file is :

# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# Source interfaces
# Please check /etc/network/interfaces.d before changing this file
# as interfaces may have been defined in /etc/network/interfaces.d
# See LP: #1262951
source /etc/network/interfaces.d/*.cfg

The source path /etc/network/interfaces.d/*.cfg have only one file named : 50-cloud-init.cfg and this file contain :

auto lo
iface lo inet loopback

auto ens3
iface ens3 inet dhcp

So my IP address is 149.xxx.xxx.61, I need to transform this to have an iface ens3 static for my IP address.

Actually ifconfig -a is :

ens3      Link encap:Ethernet  HWaddr fa:16:3e:ae:e3:83
          inet addr:149.xxx.xxx.61  Bcast:149.xxx.xxx.61  Mask:255.255.255.255
          inet6 addr: fe80::xxxx:xxxx:feae:e383/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:894526 errors:0 dropped:0 overruns:0 frame:0
          TX packets:297070 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:102187906 (102.1 MB)  TX bytes:63602471 (63.6 MB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:14743 errors:0 dropped:0 overruns:0 frame:0
          TX packets:14743 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:31459525 (31.4 MB)  TX bytes:31459525 (31.4 MB)

How can I do this ?

Body:
First, you must find your IP and Gateway for IPv6. They can be found in your OVH manager.

Modify your network config file with this command (use sudo if you are not root) :

nano /etc/network/interfaces.d/50-cloud-init.cfg

Add these lines :

iface eth0 inet6 static
    address YOUR_IPV6
    netmask IPV6_PREFIX
    post-up /sbin/ip -f inet6 route add IPV6_GATEWAY dev eth0
    post-up /sbin/ip -f inet6 route add default via IPV6_GATEWAY
    pre-down /sbin/ip -f inet6 route del IPV6_GATEWAY dev eth0
    pre-down /sbin/ip -f inet6 route del default via IPV6_GATEWAY

YOUR_IPV6 must be replaced with your IPv6.
IPV6_PREFIX must be replaced with 128.
IPV6_GATEWAY must be replaced with your IPv6 gateway.

Reboot your VPS.

Reference : http://docs.ovh.ca/fr/guides-network-ipv6.html#debian-derivatives-ubuntu-crunchbang-steamos


问:
Azure AD Graph API - App Role Assignments List
There is no documentation around how the Application Role Assignments list that is generated from this AAD Graph API call is determined:

https://graph.windows.net/contoso.com/users/simon@contoso.com/appRoleAssignments

For instance, if the user has Office 365, no assigned Office 365 Apps appear in the Graph API response, yet if this user browses to https://myapps.microsoft.com/contoso.com they see them listed.

Can someone clarify the logic used to build the Apps returned in this list and if it is possible to retrieve all the applications assigned to the user?

答:
The user's appRoleAssignments navigation property should contain all of the roles that the user has been assigned on apps. In case an app does not declare any appRoles that can be assigned to users, there will still be one entity here with an all-zeros GUID.

For example, I've assigned one of my test users to an app that has no roles, and Get-AzureADUserAppRoleAssignment -ObjectId user-object-id returns:

```<code>DeletionTimestamp    :
ObjectId             : 1YoOkUy2bESZDaQwZRhU0S-UYlhvd3FJsJikOAWHrsI
ObjectType           : AppRoleAssignment
CreationTimestamp    : 17.1.2016 15.40.03
Id                   : 00000000-0000-0000-0000-000000000000
PrincipalDisplayName : Test User
PrincipalId          : 910e8ad5-b64c-446c-990d-a430651854d1
PrincipalType        : User
ResourceDisplayName  : TodoService
ResourceId           : 6b5b5ad6-54ce-415f-ad04-0a276ce086b0
</code>```

And also one for an app that does specify roles:

```<code>DeletionTimestamp    :
ObjectId             : 1YoOkUy2bESZDaQwZRhU0YAvk4B2fQdPqcTGnjNiP_0
ObjectType           : AppRoleAssignment
CreationTimestamp    :
Id                   : 06608f41-55fb-400a-8da2-3d51909a0449
PrincipalDisplayName : Test User
PrincipalId          : 910e8ad5-b64c-446c-990d-a430651854d1
PrincipalType        : User
ResourceDisplayName  : TestApp
ResourceId           : ecf84db8-3333-43d0-809a-aaef620a14bf
</code>```

Note the Id property specifies the id of the role that the user has on that app. In the case of the first one, they just have general access.

As for why Office 365 apps don't show up there, if I recall correctly you do not assign them the same way through the Azure AD user management? The app assignments may be an internal thing in O365 and Azure AD does not know about it. License assignments can be found from the licenseDetails navigation property of the user (or Get-AzureADUserLicenseDetail with Azure AD v2 PowerShell).

Body:
The user's appRoleAssignments navigation property should contain all of the roles that the user has been assigned on apps. In case an app does not declare any appRoles that can be assigned to users, there will still be one entity here with an all-zeros GUID.

For example, I've assigned one of my test users to an app that has no roles, and Get-AzureADUserAppRoleAssignment -ObjectId user-object-id returns:

DeletionTimestamp    :
ObjectId             : 1YoOkUy2bESZDaQwZRhU0S-UYlhvd3FJsJikOAWHrsI
ObjectType           : AppRoleAssignment
CreationTimestamp    : 17.1.2016 15.40.03
Id                   : 00000000-0000-0000-0000-000000000000
PrincipalDisplayName : Test User
PrincipalId          : 910e8ad5-b64c-446c-990d-a430651854d1
PrincipalType        : User
ResourceDisplayName  : TodoService
ResourceId           : 6b5b5ad6-54ce-415f-ad04-0a276ce086b0

And also one for an app that does specify roles:

DeletionTimestamp    :
ObjectId             : 1YoOkUy2bESZDaQwZRhU0YAvk4B2fQdPqcTGnjNiP_0
ObjectType           : AppRoleAssignment
CreationTimestamp    :
Id                   : 06608f41-55fb-400a-8da2-3d51909a0449
PrincipalDisplayName : Test User
PrincipalId          : 910e8ad5-b64c-446c-990d-a430651854d1
PrincipalType        : User
ResourceDisplayName  : TestApp
ResourceId           : ecf84db8-3333-43d0-809a-aaef620a14bf

Note the Id property specifies the id of the role that the user has on that app. In the case of the first one, they just have general access.

As for why Office 365 apps don't show up there, if I recall correctly you do not assign them the same way through the Azure AD user management? The app assignments may be an internal thing in O365 and Azure AD does not know about it. License assignments can be found from the licenseDetails navigation property of the user (or Get-AzureADUserLicenseDetail with Azure AD v2 PowerShell).


问:
WPF Binding Issue - UI Updates, Object Does Not
I'm having yet another WPF binding issue.  Just when I think I've got this stuff figured out, I run into more problems...  :S

Anyway... I've created a custom user control for selecting files.  It's a simple textbox followed by a button contained within a grid.  The property of the control with which I am working is called FilePath and the TextBox on this control is bound to that property.  When the button is clicked, a SaveFileDialog is opened and the user selects a file.  The UI correctly updates after the user selects the file.

The problem I seem to be having is that when I bind an object to the control (in this instance I have an object with a DocumentFilePath property) the object doesn't update when a new file is selected.

Here's the relevant code within my user control:

```<code>public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register("FilePath", typeof(string), typeof(FileSave), new UIPropertyMetadata(string.Empty, OnFilePathChanged));

public string FilePath
{
    get
    {
        return this.GetValue(FilePathProperty) as string;
    }
    set
    {
        this.SetValue(FilePathProperty, value);
        this.OnPropertyChanged("FilePath");
    }
}

private void OnPropertyChanged(string propName)
{
    if (PropertyChanged != null)
    {
       PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

private static void OnFilePathChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    ((FileSave)sender).OnPropertyChanged("FilePath");
}
</code>```

And the user control is added into my Window programatically by using reflection on my object:

```<code>private void AddFileSave(PropertyInfo pi)
{
     FileSave fs = new FileSave();
     Binding b = new Binding(pi.Name);

     fs.SetBinding(FileSave.FilePathProperty, b);
     this.AddToGrid(fs); //adds the control into my window's grid in the correct row and column; nothing fancy here
}
</code>```

It may be worth noting that if I load the window with an existing object, my user control displays properly but still won't register any changes within the object to which it is bound.

Please let me know if you guys need any more info.

Thanks in advance,

Sonny

EDIT:  I've found a way around the problem, but this probably isn't a good solution.  By watching the debugger carefully I found that when I set the FilePath property within my control, the object was being unbound.  If anyone can shed some light on that, I would be most appreciative.  In the mean time, I've changed the code that opens my SaveFileDialog to look like this:

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();

    ofd.Multiselect = false;
    ofd.Title = "Select document to import...";
    ofd.ValidateNames = true;

    ofd.ShowDialog();

    if (this.GetBindingExpression(FilePathProperty) == null)
    {
        this.FilePath = ofd.FileName;
    }
    else //set value on bound object (THIS IS THE NEW PORTION I JUST ADDED)
    {
        BindingExpression be = this.GetBindingExpression(FilePathProperty);
        string propName = be.ParentBinding.Path.Path;
        object entity = be.DataItem;
        System.Reflection.PropertyInfo pi = entity.GetType().GetProperty(propName);

        pi.SetValue(entity, ofd.FileName, null);
    }

    if (!string.IsNullOrWhiteSpace(this.FilePath))
    {
        _fileContents = new MemoryStream();
        using (StreamReader sr = new StreamReader(this.FilePath))
        {
            _fileContents = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(sr.ReadToEnd()));
        }
    }
    else
    {
        _fileContents = null;
    }
}
</code>```

答:
First, you don't need to raise the PropertyChanged event when a dependency property changes; with dependency properties, change notification comes for free.

What's probably happening here:  The default behavior for UpdateSourceTrigger is LostFocus, i.e. the source gets updated when the user presses TAB to move to the next field, or clicks on another control, or whatever.  The text box isn't losing focus after your SaveFileDialog sets Text (since it probably doesn't even have the focus in the first place), so the source update never gets triggered.

To make it update the source whenever the Text property changes, set the UpdateSourceTrigger to PropertyChanged.

If that doesn't work, watch the Output window for binding errors.

Edit:

Here's a little prototype application I built.  It works just fine: typing in the text box sets the property, clicking on the "Save" button sets the property, and the binding in the main window gets updated properly no matter what.

```<code><Window x:Class="DependencyPropertyBindingDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:demo="clr-namespace:DependencyPropertyBindingDemo"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <demo:FilePicker x:Name="Picker"
                         DockPanel.Dock="Top"
                         Margin="5" />
        <TextBox DockPanel.Dock="Top"
                Text="{Binding ElementName=Picker, Path=FilePath}" />
        <TextBlock />
    </DockPanel>
</Window>

<UserControl x:Class="DependencyPropertyBindingDemo.FilePicker"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DockPanel>
        <TextBox DockPanel.Dock="Left"
                 Width="200"
                 Text="{Binding FilePath, UpdateSourceTrigger=PropertyChanged}" />
        <Button Width="50"
                DockPanel.Dock="Left"
                Command="{Binding Path=SaveCommand}">Save</Button>
        <TextBlock />
    </DockPanel>
</UserControl>

public partial class FilePicker : UserControl
{
    public FilePicker()
    {
        SaveCommand = new FilePickerSaveCommand(this);
        DataContext = this;
        InitializeComponent();
    }

    public ICommand SaveCommand { get; set; }

    public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register("FilePath", typeof(string), typeof(FilePicker));

    public string FilePath
    {
        get
        {
            return GetValue(FilePathProperty) as string;
        }
        set
        {
            SetValue(FilePathProperty, value);
        }
    }
}

public class FilePickerSaveCommand : ICommand
{
    private FilePicker _FilePicker;

    public FilePickerSaveCommand(FilePicker picker)
    {
        _FilePicker = picker;
    }

    public void Execute(object parameter)
    {
        _FilePicker.FilePath = "Testing";
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;
}
</code>```

Body:
I'm having yet another WPF binding issue.  Just when I think I've got this stuff figured out, I run into more problems...  :S

Anyway... I've created a custom user control for selecting files.  It's a simple textbox followed by a button contained within a grid.  The property of the control with which I am working is called FilePath and the TextBox on this control is bound to that property.  When the button is clicked, a SaveFileDialog is opened and the user selects a file.  The UI correctly updates after the user selects the file.

The problem I seem to be having is that when I bind an object to the control (in this instance I have an object with a DocumentFilePath property) the object doesn't update when a new file is selected.

Here's the relevant code within my user control:

public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register("FilePath", typeof(string), typeof(FileSave), new UIPropertyMetadata(string.Empty, OnFilePathChanged));

public string FilePath
{
    get
    {
        return this.GetValue(FilePathProperty) as string;
    }
    set
    {
        this.SetValue(FilePathProperty, value);
        this.OnPropertyChanged("FilePath");
    }
}

private void OnPropertyChanged(string propName)
{
    if (PropertyChanged != null)
    {
       PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

private static void OnFilePathChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    ((FileSave)sender).OnPropertyChanged("FilePath");
}

And the user control is added into my Window programatically by using reflection on my object:

private void AddFileSave(PropertyInfo pi)
{
     FileSave fs = new FileSave();
     Binding b = new Binding(pi.Name);

     fs.SetBinding(FileSave.FilePathProperty, b);
     this.AddToGrid(fs); //adds the control into my window's grid in the correct row and column; nothing fancy here
}

It may be worth noting that if I load the window with an existing object, my user control displays properly but still won't register any changes within the object to which it is bound.

Please let me know if you guys need any more info.

Thanks in advance,

Sonny

EDIT:  I've found a way around the problem, but this probably isn't a good solution.  By watching the debugger carefully I found that when I set the FilePath property within my control, the object was being unbound.  If anyone can shed some light on that, I would be most appreciative.  In the mean time, I've changed the code that opens my SaveFileDialog to look like this:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();

    ofd.Multiselect = false;
    ofd.Title = "Select document to import...";
    ofd.ValidateNames = true;

    ofd.ShowDialog();

    if (this.GetBindingExpression(FilePathProperty) == null)
    {
        this.FilePath = ofd.FileName;
    }
    else //set value on bound object (THIS IS THE NEW PORTION I JUST ADDED)
    {
        BindingExpression be = this.GetBindingExpression(FilePathProperty);
        string propName = be.ParentBinding.Path.Path;
        object entity = be.DataItem;
        System.Reflection.PropertyInfo pi = entity.GetType().GetProperty(propName);

        pi.SetValue(entity, ofd.FileName, null);
    }

    if (!string.IsNullOrWhiteSpace(this.FilePath))
    {
        _fileContents = new MemoryStream();
        using (StreamReader sr = new StreamReader(this.FilePath))
        {
            _fileContents = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(sr.ReadToEnd()));
        }
    }
    else
    {
        _fileContents = null;
    }
}

Body:
First, you don't need to raise the PropertyChanged event when a dependency property changes; with dependency properties, change notification comes for free.

What's probably happening here:  The default behavior for UpdateSourceTrigger is LostFocus, i.e. the source gets updated when the user presses TAB to move to the next field, or clicks on another control, or whatever.  The text box isn't losing focus after your SaveFileDialog sets Text (since it probably doesn't even have the focus in the first place), so the source update never gets triggered.

To make it update the source whenever the Text property changes, set the UpdateSourceTrigger to PropertyChanged.

If that doesn't work, watch the Output window for binding errors.

Edit:

Here's a little prototype application I built.  It works just fine: typing in the text box sets the property, clicking on the "Save" button sets the property, and the binding in the main window gets updated properly no matter what.

<Window x:Class="DependencyPropertyBindingDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:demo="clr-namespace:DependencyPropertyBindingDemo"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <demo:FilePicker x:Name="Picker"
                         DockPanel.Dock="Top"
                         Margin="5" />
        <TextBox DockPanel.Dock="Top"
                Text="{Binding ElementName=Picker, Path=FilePath}" />
        <TextBlock />
    </DockPanel>
</Window>

<UserControl x:Class="DependencyPropertyBindingDemo.FilePicker"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DockPanel>
        <TextBox DockPanel.Dock="Left"
                 Width="200"
                 Text="{Binding FilePath, UpdateSourceTrigger=PropertyChanged}" />
        <Button Width="50"
                DockPanel.Dock="Left"
                Command="{Binding Path=SaveCommand}">Save</Button>
        <TextBlock />
    </DockPanel>
</UserControl>

public partial class FilePicker : UserControl
{
    public FilePicker()
    {
        SaveCommand = new FilePickerSaveCommand(this);
        DataContext = this;
        InitializeComponent();
    }

    public ICommand SaveCommand { get; set; }

    public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register("FilePath", typeof(string), typeof(FilePicker));

    public string FilePath
    {
        get
        {
            return GetValue(FilePathProperty) as string;
        }
        set
        {
            SetValue(FilePathProperty, value);
        }
    }
}

public class FilePickerSaveCommand : ICommand
{
    private FilePicker _FilePicker;

    public FilePickerSaveCommand(FilePicker picker)
    {
        _FilePicker = picker;
    }

    public void Execute(object parameter)
    {
        _FilePicker.FilePath = "Testing";
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;
}


问:
Textbox compulsory when radio button is selected
I have a view where add to electronic has 2 radiobuttons yes & no. And a submit button. When yes radiobutton is clicked. the quantity textbox should not be empty. But it can be empty if no radiobutton is clicked.
This functionality should work when submit button is clicked with yes radiobutton is selected.

```<code> <HTML>
    <head>
    radio
    </head>
    <body>
    <form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No<br />
    <label>Quantity</label><input type="text"size="25"name="dir"id="dir" required/>
<button type=submit name=insert>insert</button>
</body>
<div>
<script src="~/Scripts/radiobuttonvalidation.js"></script>
</div>
</html>
</code>```

I'm new to mvc and javascript. Please help me with javascript code too, and the way i should link it with my view. Javascript:

```<code>function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}
</code>```

答:
You are calling your validate function only first radio button just call it on both radio button. Or you can use jQuery to add event to your radio buttons. One more thing there is no name specified in your form for radio button add one for sending data to server.

$(function(){
  $("input[name=add_to_ele]").change(function(){
    if($(this).val()=="yes")
    {
      $('#dir').attr('required','required');
        alert("Text Box required");
    }
    else
    {
      $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form >
Add to electronic  <input type="radio" name="add_to_ele" id="yes" value="yes"/> Yes <input value="no" type="radio" name="add_to_ele" id="no" />No<br />
    <label>Quantity</label><input type="text"size="25" name="dir" id="dir" required/>
<button type=submit name=insert>insert</button>
</form ></code>```

Body:
I have a view where add to electronic has 2 radiobuttons yes & no. And a submit button. When yes radiobutton is clicked. the quantity textbox should not be empty. But it can be empty if no radiobutton is clicked.
This functionality should work when submit button is clicked with yes radiobutton is selected.

    radio

    <form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No

    Quantity<input type="text"size="25"name="dir"id="dir" required/>
<button type=submit name=insert>insert</button>

I'm new to mvc and javascript. Please help me with javascript code too, and the way i should link it with my view. Javascript:

function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}

Body:
You are calling your validate function only first radio button just call it on both radio button. Or you can use jQuery to add event to your radio buttons. One more thing there is no name specified in your form for radio button add one for sending data to server.

$(function(){
  $("input[name=add_to_ele]").change(function(){
    if($(this).val()=="yes")
    {
      $('#dir').attr('required','required');
        alert("Text Box required");
    }
    else
    {
      $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form >
Add to electronic  <input type="radio" name="add_to_ele" id="yes" value="yes"/> Yes <input value="no" type="radio" name="add_to_ele" id="no" />No<br />
    <label>Quantity</label><input type="text"size="25" name="dir" id="dir" required/>
<button type=submit name=insert>insert</button>
</form >


问:
sorting and partitioning data based on dynamic serial ordered input stream in java
I want to sort elements and group them as follows, How shall I achieve that using java streams sort, group and partition by.

The input is comming in streams that means after getting the below input after sometime the input like A16,17 may come the data structure must reorganize and regroup.

Input A10, A4, A11, A3, A12,A15 ....B19,B2,B20...

Output A3-A4,A10-A12,A15,B2,B19-B20.

I could able to sort as below

```<code>array.sort(Comparator   .comparing(...)
                                .thenComparing(Comparator.comparing(...)));
</code>```

but not sure how to partition and regroup for chaning input using streams in most optimised way.

```<code> array.stream().collect(Collectors.partitionBy(...))
</code>```

What should be the logic in function for partition by in above in order to achieve serial order grouping ?

答:
You can do easily if you write your own Comparator and your own Collector, making use of Java8 Stream interface:

```<code>array.stream().sorted(new MyComparator()).collect(new MyCollector());
</code>```

The Comparator is plain easy to write:

```<code>class MyComparator implements Comparator<String> {

    @Override
    public int compare(String s1, String s2) {
        if(s1.substring(0, 1).compareTo(s2.substring(0,1)) < 0) {
            return -1;
        } else if (s1.substring(0, 1).compareTo(s2.substring(0,1)) > 0) {
            return 1;
        } else { //first char is equal
            if(Integer.parseInt(s1.substring(1, s1.length())) < Integer.parseInt(s2.substring(1, s2.length()))) {
                return -1;
            } else if (Integer.parseInt(s1.substring(1, s1.length())) > Integer.parseInt(s2.substring(1, s2.length()))) {
                return 1;
            }
        }
        return 0;
    }
}
</code>```

It basically checks for the letter at the beginning, and then checks for the numbers afterwards. Trying to use natural alphabetical order will put your A10, A11... before your A2,A3... because 1<2.

I'm leaving the Collector intentionally unwritten for you to do that part, as it is an interesting exercise.

But if you don't want to use a Collector because you find it too hard, you can always use the newly ordered List to grab its elements two by two and create another List containing the result you are looking for.

Body:
I want to sort elements and group them as follows, How shall I achieve that using java streams sort, group and partition by.

The input is comming in streams that means after getting the below input after sometime the input like A16,17 may come the data structure must reorganize and regroup.

Input A10, A4, A11, A3, A12,A15 ....B19,B2,B20...

Output A3-A4,A10-A12,A15,B2,B19-B20.

I could able to sort as below

array.sort(Comparator   .comparing(...)
                                .thenComparing(Comparator.comparing(...)));

but not sure how to partition and regroup for chaning input using streams in most optimised way.

 array.stream().collect(Collectors.partitionBy(...))

What should be the logic in function for partition by in above in order to achieve serial order grouping ?

Body:
You can do easily if you write your own Comparator and your own Collector, making use of Java8 Stream interface:

array.stream().sorted(new MyComparator()).collect(new MyCollector());

The Comparator is plain easy to write:

class MyComparator implements Comparator<String> {

    @Override
    public int compare(String s1, String s2) {
        if(s1.substring(0, 1).compareTo(s2.substring(0,1)) < 0) {
            return -1;
        } else if (s1.substring(0, 1).compareTo(s2.substring(0,1)) > 0) {
            return 1;
        } else { //first char is equal
            if(Integer.parseInt(s1.substring(1, s1.length())) < Integer.parseInt(s2.substring(1, s2.length()))) {
                return -1;
            } else if (Integer.parseInt(s1.substring(1, s1.length())) > Integer.parseInt(s2.substring(1, s2.length()))) {
                return 1;
            }
        }
        return 0;
    }
}

It basically checks for the letter at the beginning, and then checks for the numbers afterwards. Trying to use natural alphabetical order will put your A10, A11... before your A2,A3... because 1<2.

I'm leaving the Collector intentionally unwritten for you to do that part, as it is an interesting exercise.

But if you don't want to use a Collector because you find it too hard, you can always use the newly ordered List to grab its elements two by two and create another List containing the result you are looking for.