问:
Uploading multiple images using Protractor
I have a scenario in my test suite, where I need to

Click on a button.

Upload an image from a specified directory.

Wait for 15 seconds

Repeat Steps 1-3 for all the images in the specified directory.

How can I achieve this - uploading an array of images, or a group of images, in specified folder, one by one. The test also includes the check that an image should not have been uploaded before.
I am able to upload a single file using the code below -

```<code>var fileUpload = 'path_to_file';
absolutePath = path.resolve(__dirname,fileUpload);
console.log(absolutePath);
this.file_Upload2.sendKeys(absolutePath);
browser.actions().sendKeys(protractor.Key.ENTER).perform();
browser.sleep(20000);
</code>```

Please note that there is only a single button for uploading the images and it remains constant.

答:
If you change your fileUpload variable to point to the directory where the files are held, rather than the file itself, you can just loop over everything in the directory. Something like this:</p>

```<code>var fileUpload = 'path_to_directory';
var file_Upload2 = this.file_Upload2;
var absolutePath = path.resolve(__dirname, fileUpload);
fs.readdir(absolutePath, (err, files) => {
    for (i = 0; i < files.length; i++) {
        var fullPath = path.resolve(absolutePath, files[i]);
        file_Upload2.clear().sendKeys(fullPath);
        browser.actions().sendKeys(protractor.Key.ENTER).perform();
        browser.sleep(20000);
    }
});
</code>```

Body:
I have a scenario in my test suite, where I need to

Click on a button.

Upload an image from a specified directory.

Wait for 15 seconds

Repeat Steps 1-3 for all the images in the specified directory.

How can I achieve this - uploading an array of images, or a group of images, in specified folder, one by one. The test also includes the check that an image should not have been uploaded before.
I am able to upload a single file using the code below -

var fileUpload = 'path_to_file';
absolutePath = path.resolve(__dirname,fileUpload);
console.log(absolutePath);
this.file_Upload2.sendKeys(absolutePath);
browser.actions().sendKeys(protractor.Key.ENTER).perform();
browser.sleep(20000);

Please note that there is only a single button for uploading the images and it remains constant.

Body:
If you change your fileUpload variable to point to the directory where the files are held, rather than the file itself, you can just loop over everything in the directory. Something like this:

var fileUpload = 'path_to_directory';
var file_Upload2 = this.file_Upload2;
var absolutePath = path.resolve(__dirname, fileUpload);
fs.readdir(absolutePath, (err, files) => {
    for (i = 0; i < files.length; i++) {
        var fullPath = path.resolve(absolutePath, files[i]);
        file_Upload2.clear().sendKeys(fullPath);
        browser.actions().sendKeys(protractor.Key.ENTER).perform();
        browser.sleep(20000);
    }
});


来源: stackexchange

问:
'Pink tiles' when using GeoWebCache
I'm trying to test simple web map based on PostGIS/Geoserver/OpenLayers stack on Windows Server 2008. I've been using this tutorial and geoserver docs.

When I try to add WMS layer to my map using GeoWebCache:

```<code>    var index1d = new OpenLayers.Layer.WMS(
        "Index1",
        "http://localhost:1979/geoserver/gwc/service/wms",
        {'layers': "Index2000:index1d",
         'format': "image/png",
         'transparent': true
        },
        {'opacity': 1.0, 'isBaseLayer': true}

    );
    map.addLayer(index1d);
</code>```

I get infamous 'pink tiles'. Error in Geoserver says:

```<code>ERROR [geowebcache.GeoWebCacheDispatcher] - Requested horizontal resolution:
750.0000000000005 , best match: 632.4668417968734 exceeds 10% threshold.
Perhaps the client is configured  with an incorrect set of scales (resolutions),
or the DPI setting is off compared to the one in GWC ? http://localhost:
1979/geoserver/gwc/service/wms
</code>```

My layer seems to be configured correctly and when I serve it without GeoWebCache with simply:

```<code>"http://localhost:1979/geoserver/wms"
</code>```

everything works fine.

Could anyone point where I'm making mistake?

答:
I haven't used GWC, but I guess you have set up the cache yourself? If so, I suppose you had to set the scales where GWC would create it's tiles. Building on these assumptions, I would say that you then must use the same scale levels when accessing the tiles. Look over your GWC settings and maybe recreate the cache.

(Using WMS will work because the map data by default is rendered on the fly, taking whatever parameters you supply it with and rendering from that.)

ContentLicense: CC BY-SA 2.5

Title: 'Pink tiles' when using GeoWebCache

Body:
I'm trying to test simple web map based on PostGIS/Geoserver/OpenLayers stack on Windows Server 2008. I've been using this tutorial and geoserver docs.

When I try to add WMS layer to my map using GeoWebCache:

    var index1d = new OpenLayers.Layer.WMS(
        "Index1",
        "http://localhost:1979/geoserver/gwc/service/wms",
        {'layers': "Index2000:index1d",
         'format': "image/png",
         'transparent': true
        },
        {'opacity': 1.0, 'isBaseLayer': true}

    );
    map.addLayer(index1d);

I get infamous 'pink tiles'. Error in Geoserver says:

ERROR [geowebcache.GeoWebCacheDispatcher] - Requested horizontal resolution:
750.0000000000005 , best match: 632.4668417968734 exceeds 10% threshold.
Perhaps the client is configured  with an incorrect set of scales (resolutions),
or the DPI setting is off compared to the one in GWC ? http://localhost:
1979/geoserver/gwc/service/wms

My layer seems to be configured correctly and when I serve it without GeoWebCache with simply:

"http://localhost:1979/geoserver/wms"

everything works fine.

Could anyone point where I'm making mistake?


问:
how to read file line by line and change characters if line contain specific value
I have a FASTA file (testfile.fa), which contains title lines (contain > in the beginning) and lines with characters meaning some types of nucleotides (A, C, G, T, a, g, c, t, N).

```<code>>chr1
cccccccccttttttttaaaa
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>chr1_alt
TCTCTCTCTCTCTCTCTCTCT
gggtttccccccccccccccc
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>chr2
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>chr3
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
</code>```

I need to read this file line by line and change small characters (a, c, t, g) to N in every sequence except titles, which contain >. So I use the following code:

```<code>#!/bin/bash
while read line
do
    if [[ $line =~ ">" ]]
    then
        echo $line
    else
        tr 'c' 'N'
        echo $line
    fi
done < testfile.fa
</code>```

But the results are confusing:

```<code>>chr1
# the first line was missed
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>Nhr1_alt #the character was changed but the line contains >
TCTCTCTCTCTCTCTCTCTCT
gggtttNNNNNNNNNNNNNNN
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>Nhr2 #the character was changed but the line contains >
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>Nhr3 #the character was changed but the line contains >
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTTcccccccccttttttttaaaa #the first line from the first sequence comes here
</code>```

What can be the probable reason of these problems and how can I solve them? Thank you in advance!

答:
sed is a easy way to achieve this:

```<code>sed -i '/^>/ !s/[actg]/N/g' testfile.fa
</code>```

[ ] contains the characters which will be changed to N, and /^>/ ! part ignore line starting with >

-i will overwrite the current file, without it you will get the output on the standard output.

ContentLicense: CC BY-SA 3.0

Body:
I have a FASTA file (testfile.fa), which contains title lines (contain > in the beginning) and lines with characters meaning some types of nucleotides (A, C, G, T, a, g, c, t, N).

>chr1
cccccccccttttttttaaaa
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>chr1_alt
TCTCTCTCTCTCTCTCTCTCT
gggtttccccccccccccccc
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>chr2
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>chr3
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT

I need to read this file line by line and change small characters (a, c, t, g) to N in every sequence except titles, which contain >. So I use the following code:

#!/bin/bash
while read line
do
    if [[ $line =~ ">" ]]
    then
        echo $line
    else
        tr 'c' 'N'
        echo $line
    fi
done < testfile.fa

But the results are confusing:

>chr1
# the first line was missed
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>Nhr1_alt #the character was changed but the line contains >
TCTCTCTCTCTCTCTCTCTCT
gggtttNNNNNNNNNNNNNNN
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>Nhr2 #the character was changed but the line contains >
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>Nhr3 #the character was changed but the line contains >
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTTcccccccccttttttttaaaa #the first line from the first sequence comes here

What can be the probable reason of these problems and how can I solve them? Thank you in advance!

Body:
sed is a easy way to achieve this:

sed -i '/^>/ !s/[actg]/N/g' testfile.fa

[ ] contains the characters which will be changed to N, and /^>/ ! part ignore line starting with >

-i will overwrite the current file, without it you will get the output on the standard output.


问:
exc bad instruction code exc i386 invop swift With NSArray
I faced "exc bad instruction code exc i386 invop" issue. I struggling to solve this issue. If any one know this ping me...

Issue

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("didselect")

    if(tableView == self.tabledata){
        print("Entered into tableview of listing")
        let savearr : NSArray = UserDefaults.standard.object(forKey: "savedarray") as! NSArray

        let addarr: NSArray = savearr.value(forKeyPath:"country") as! NSArray
        let sumarr: NSArray = savearr.value(forKeyPath:"description") as! NSArray
        let titarr: NSArray = savearr.value(forKeyPath:"title") as! NSArray
</code>```

Then I Tried This code:

```<code>    if let savearr : NSArray = UserDefaults.standard.object(forKey: "savedarray") as? NSArray
        {
        let addarr: NSArray = savearr.value(forKeyPath:"country") as! NSArray
        let sumarr: NSArray = savearr.value(forKeyPath:"description") as! NSArray
        let titarr: NSArray = savearr.value(forKeyPath:"title") as! NSArray
    let MenuViewController = self.storyboard?.instantiateViewController(withIdentifier: "five") as! FiveStepsViewController

    MenuViewController.writeTitleString = String(describing: titarr[indexPath.row])

    MenuViewController.writeSummaryString = String(describing: sumarr[indexPath.row])

    MenuViewController.writeAddressString = String(describing: addarr[indexPath.row])

    //MenuViewController.writePriceString = String(describing: self.appDelegate.fivepricearray[indexPath.row])

        self.present(MenuViewController, animated: true, completion: nil)
        }
        else {
            print("Error Occured while listing")
        }
</code>```

Its always goes to else part..

答:
This type of issues arises generally when we try to forcefully unwrap the nil data. Recheck your keys. And try to follow as shown in below code snippet.</p>

```<code>guard let savearr = UserDefaults.standard.object(forked: "savedArray") as? NSArray,
  let addarr = savearr.value(forKeyPath: "country") as? NSArray,
  let summer = savearr.value(forKeyPath: "description") as? NSArray,
  let titter = savearr.value(forKeyPath: "title") as? NSArray

  else { return nil }
</code>```

Body:
I faced "exc bad instruction code exc i386 invop" issue. I struggling to solve this issue. If any one know this ping me...

Issue

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("didselect")

    if(tableView == self.tabledata){
        print("Entered into tableview of listing")
        let savearr : NSArray = UserDefaults.standard.object(forKey: "savedarray") as! NSArray

        let addarr: NSArray = savearr.value(forKeyPath:"country") as! NSArray
        let sumarr: NSArray = savearr.value(forKeyPath:"description") as! NSArray
        let titarr: NSArray = savearr.value(forKeyPath:"title") as! NSArray

Then I Tried This code:

    if let savearr : NSArray = UserDefaults.standard.object(forKey: "savedarray") as? NSArray
        {
        let addarr: NSArray = savearr.value(forKeyPath:"country") as! NSArray
        let sumarr: NSArray = savearr.value(forKeyPath:"description") as! NSArray
        let titarr: NSArray = savearr.value(forKeyPath:"title") as! NSArray
    let MenuViewController = self.storyboard?.instantiateViewController(withIdentifier: "five") as! FiveStepsViewController

    MenuViewController.writeTitleString = String(describing: titarr[indexPath.row])

    MenuViewController.writeSummaryString = String(describing: sumarr[indexPath.row])

    MenuViewController.writeAddressString = String(describing: addarr[indexPath.row])

    //MenuViewController.writePriceString = String(describing: self.appDelegate.fivepricearray[indexPath.row])

        self.present(MenuViewController, animated: true, completion: nil)
        }
        else {
            print("Error Occured while listing")
        }

Its always goes to else part..

Body:
This type of issues arises generally when we try to forcefully unwrap the nil data. Recheck your keys. And try to follow as shown in below code snippet.

guard let savearr = UserDefaults.standard.object(forked: "savedArray") as? NSArray,
  let addarr = savearr.value(forKeyPath: "country") as? NSArray,
  let summer = savearr.value(forKeyPath: "description") as? NSArray,
  let titter = savearr.value(forKeyPath: "title") as? NSArray

  else { return nil }


问:
Safari (mobile) IOS - Input doesn't loses focus when clicking outside
I'm doing a search bar that gives results (similar to an autocomplete) but on iOS' Safari it doesn't loses focus when tapping outside of the input tag when the keyboard is open.

I did a simple jsfiddle to demonstrate the minimal code that reproduces this issue:

https://jsfiddle.net/coppolaemilio/0bqrLcwe/4/

HTML

```<code><input class="selector" type="text">
<ul>
  <li>element</li>
</ul>
</code>```

JS (jQuery)

```<code>$('.selector').focus(function() {
    $('ul').addClass('visible');
});
$('.selector').focusout(function() {
    $('ul').removeClass('visible');
});
</code>```

CSS

```<code>.selector{
  margin: 20px;
}
ul {
  display: none;
}
ul.visible {
  display: block;
}
</code>```

答:
I managed to find a solution by using this:

```<code>$(document).on('touchstart', function (event) {
  if (!$(event.target).closest('.country-selector').length) {
    if ($('.country-selector').is(":visible")) {
      $('input.country-selector').blur();
    }
  }
});
</code>```

https://jsfiddle.net/coppolaemilio/0bqrLcwe/5/

Body:
I'm doing a search bar that gives results (similar to an autocomplete) but on iOS' Safari it doesn't loses focus when tapping outside of the input tag when the keyboard is open.

I did a simple jsfiddle to demonstrate the minimal code that reproduces this issue:

https://jsfiddle.net/coppolaemilio/0bqrLcwe/4/

HTML

<input class="selector" type="text">

element

JS (jQuery)

$('.selector').focus(function() {
    $('ul').addClass('visible');
});
$('.selector').focusout(function() {
    $('ul').removeClass('visible');
});

CSS

.selector{
  margin: 20px;
}
ul {
  display: none;
}
ul.visible {
  display: block;
}

Body:
I managed to find a solution by using this:

$(document).on('touchstart', function (event) {
  if (!$(event.target).closest('.country-selector').length) {
    if ($('.country-selector').is(":visible")) {
      $('input.country-selector').blur();
    }
  }
});

https://jsfiddle.net/coppolaemilio/0bqrLcwe/5/


问:
Function returning "This" object in C++
So, following is a member function of Class Sales_data which is defined outside the class,

```<code>Sales_data& Sales_data::combine(const Sales_data &rhs) {
    units_sold += rhs.units_sold;
    revenue += rhs.revenue; //adding the members of rhs into the members of "this" object
    return *this;
} //units_sold and revenue are both data members of class
</code>```

When the function is called, it is called like

```<code>total.combine(trans); //total and trans are the objects of class
</code>```

What i am not understanding is the function returning *this,
i understand it returns an instance of the object but it is not returning that instance to anything as we can see during function call, also if i don't write the return statement, would it work any differently.

Someone please explain elaborately because i am just not getting it.

答:
One benefit of defining the function as you have defined with return statement is that it allows consecutive calls like the code below possible:

```<code>// assuming that trans1 and trans2 are defined and initialized properly earlier
total.combine(trans1).combine(trans2);
// now total contains values from trans1 and trans2
</code>```

This is equivalent to:

```<code>// assuming that trans1 and trans2 are defined and initialized properly earlier
total.combine(trans1);
total.combine(trans2);
// now total contains values from trans1 and trans2
</code>```

but it is a little more succinct and brief.

However, if you do not need or like to use the earlier version, you can declare the function to return void.

Title: Function returning "This" object in C++

Body:
So, following is a member function of Class Sales_data which is defined outside the class,

Sales_data& Sales_data::combine(const Sales_data &rhs) {
    units_sold += rhs.units_sold;
    revenue += rhs.revenue; //adding the members of rhs into the members of "this" object
    return *this;
} //units_sold and revenue are both data members of class

When the function is called, it is called like

total.combine(trans); //total and trans are the objects of class

What i am not understanding is the function returning *this,
i understand it returns an instance of the object but it is not returning that instance to anything as we can see during function call, also if i don't write the return statement, would it work any differently.

Someone please explain elaborately because i am just not getting it.

Body:
One benefit of defining the function as you have defined with return statement is that it allows consecutive calls like the code below possible:

// assuming that trans1 and trans2 are defined and initialized properly earlier
total.combine(trans1).combine(trans2);
// now total contains values from trans1 and trans2

This is equivalent to:

// assuming that trans1 and trans2 are defined and initialized properly earlier
total.combine(trans1);
total.combine(trans2);
// now total contains values from trans1 and trans2

but it is a little more succinct and brief.

However, if you do not need or like to use the earlier version, you can declare the function to return void.


问:
Something like lambda expressions in Go (merge similar methods)
I have a struct in Go which has more than ten methods. And all of them are almost the same. In fact, the difference is only in one line.

Let's see the simplified example. Here is the first method:

```<code>func (s *service) GetUser(i int, s string) (*SomeObject, error) {
    CommonMethod1()
    CommonMethod2()

    user, err := s.internalLayer.GetUser(i, s)

    if err != nil {
        CommonMethod3()
    }
    return user, err
}
</code>```

And the second one:

```<code>func (s *service) CheckUser(i int) (bool, error) {
    CommonMethod1()
    CommonMethod2()

    exists, err := s.internalLayer.CheckUser(i)

    if err != nil {
        CommonMethod3()
    }
    return exists, err
}
</code>```

And there are almost 10 others with a lot of copy and paste. I'd like to ameliorate this code and the idea is to create some common method that I'll call everywhere.

It should

call CommonMethod1()

call CommonMethod2()

call some method that I pass to it in the parameter

call CommonMethod3() in case of error

return parameters

Can you tell me if it's possible to implement in Go such common method?

```<code>user, err := s.GetUser(i, s)
exists, err := s.CheckUser(i)
</code>```

Has different parameters count and different return types.

答:
You can DRY it using closures:</p>

```<code>func GetUser2(i int, s string) (*User, error) {
    var u *User
    err := do(func() error {
        var err error
        u, err = getUser(i, s)
        return err
    })
    return u, err
}

func CheckUser2(i int) (bool, error) {
    var b bool
    err := do(func() error {
        var err error
        b, err = checkUser(i)
        return err
    })
    return b, err
}

func do(f func() error) error {
    CommonMethod1()
    CommonMethod2()

    err := f()
    if err != nil {
        CommonMethod3()
    }
    return err
}
</code>```

Body:
I have a struct in Go which has more than ten methods. And all of them are almost the same. In fact, the difference is only in one line.

Let's see the simplified example. Here is the first method:

func (s *service) GetUser(i int, s string) (*SomeObject, error) {
    CommonMethod1()
    CommonMethod2()

    user, err := s.internalLayer.GetUser(i, s)

    if err != nil {
        CommonMethod3()
    }
    return user, err
}

And the second one:

func (s *service) CheckUser(i int) (bool, error) {
    CommonMethod1()
    CommonMethod2()

    exists, err := s.internalLayer.CheckUser(i)

    if err != nil {
        CommonMethod3()
    }
    return exists, err
}

And there are almost 10 others with a lot of copy and paste. I'd like to ameliorate this code and the idea is to create some common method that I'll call everywhere.

It should

call CommonMethod1()

call CommonMethod2()

call some method that I pass to it in the parameter

call CommonMethod3() in case of error

return parameters

Can you tell me if it's possible to implement in Go such common method?

user, err := s.GetUser(i, s)
exists, err := s.CheckUser(i)

Has different parameters count and different return types.

Body:
You can DRY it using closures:

func GetUser2(i int, s string) (*User, error) {
    var u *User
    err := do(func() error {
        var err error
        u, err = getUser(i, s)
        return err
    })
    return u, err
}

func CheckUser2(i int) (bool, error) {
    var b bool
    err := do(func() error {
        var err error
        b, err = checkUser(i)
        return err
    })
    return b, err
}

func do(f func() error) error {
    CommonMethod1()
    CommonMethod2()

    err := f()
    if err != nil {
        CommonMethod3()
    }
    return err
}


问:
Git workflow for small web team
I know there are already many questions here on this topic, but I've had trouble finding exactly what I need.

We're a small team of developers currently using SVN but soon to be making a switch to Git.  We are used to checking in changes and pushing to the live website throughout the day but currently lack any formal testing procedures, which is something we'd like to add.  The way I'm used to doing this with SVN is:

develop in a personal test environment

check in your changes

send the current repository files to a global (production-like) testing webserver, and test

send the current repository files to the live webservers

This obviously can create some problems, especially if communication is not good.  I've experienced times when untested changes have gone live and that's something we'd definitely like to avoid.

What I'm envisioning is a master Git repository that holds the tested code that is running on the live servers.  Then have a clone of that repository that is used to test revisions.  I'd like to have a script that is responsible for pulling changes from the requesting developer, putting them in a branch on the test repository, and running some automated tests to make sure nothing major is broken.  When that all checks out, that branch can be merged and pushed up to the master and out to the live servers.

I'd like to hear any comments about this possible workflow and any suggestions for improvement or how to do it differently.  Also, any specifics on how to set this up would also be appreciated.  Thanks!

EDIT: I've used the above method for a while now and it's worked out pretty well.

答:
Have you considered code review? Gerrit might help.

(See Android's Gerrit instance for an idea of the functionality you get.)

You could then set up a testing environment that would pull a change or set of changes from refs/for/master to the test server.

This is quite fuzzy in my head, but maybe you find it a useful pointer.

Title: Git workflow for small web team


问:
unable to select top 10 records per group in sparksql
Hi I am new to spark sql. I have a data frame like this.

```<code>  ---+----------+----+----+----+------------------------+
 |tag id|timestamp|listner| orgid |org2id|RSSI
 +---+----------+----+----+----+------------------------+
 |  4|1496745912| 362|   4|   3|                    0.60|
 |  4|1496745924|1901|   4|   3|                    0.60|
 |  4|1496746030|1901|   4|   3|                    0.60|
 |  4|1496746110| 718|   4|   3|                    0.30|
 |  2|1496746128| 718|   4|   3|                    0.60|
 |  2|1496746188|1901|   4|   3|                    0.10|
</code>```

I want to select for each listner top 10 timestamp values in spark sql.

I tried the following query.It throws errors.

```<code>  val avg = sqlContext.sql("select top 10 * from avg_table") // throws error.

  val avg = sqlContext.sql("select rssi,timestamp,tagid from avg_table order by desc limit 10")  // it prints only 10 records.
</code>```

I want to select for each listner I need to take top 10 timestamp values. Any help will be appreciated.

答:
Use "limit" in your query. (limit 10 in your case)

```<code>EXAMPLE: sqlContext.sql("SELECT text FROM yourTable LIMIT 10")
</code>```

Or you can select all from your table and save result to DataFrame or DataSet
(or to RDD, but then you need to call rdd.toDS() or to DF() method)
Then you can just call show(10) method.

ContentLicense: CC BY-SA 4.0

Body:
Hi I am new to spark sql. I have a data frame like this.

  ---+----------+----+----+----+------------------------+
 |tag id|timestamp|listner| orgid |org2id|RSSI
 +---+----------+----+----+----+------------------------+
 |  4|1496745912| 362|   4|   3|                    0.60|
 |  4|1496745924|1901|   4|   3|                    0.60|
 |  4|1496746030|1901|   4|   3|                    0.60|
 |  4|1496746110| 718|   4|   3|                    0.30|
 |  2|1496746128| 718|   4|   3|                    0.60|
 |  2|1496746188|1901|   4|   3|                    0.10|

I want to select for each listner top 10 timestamp values in spark sql.

I tried the following query.It throws errors.

  val avg = sqlContext.sql("select top 10 * from avg_table") // throws error.

  val avg = sqlContext.sql("select rssi,timestamp,tagid from avg_table order by desc limit 10")  // it prints only 10 records.

I want to select for each listner I need to take top 10 timestamp values. Any help will be appreciated.

Body:
Use "limit" in your query. (limit 10 in your case)

EXAMPLE: sqlContext.sql("SELECT text FROM yourTable LIMIT 10")

Or you can select all from your table and save result to DataFrame or DataSet
(or to RDD, but then you need to call rdd.toDS() or to DF() method)
Then you can just call show(10) method.


问:
JavaFX throws ArrayIndexOutOfBoundsException
I'm experimenting with JavaFX labels and Groups with moving them over the screen by mouse dragging. New nodes are added to the animation group from some Threads.
However, sometimes I see the following exception out of the sudden - I assume, when some nodes are overlapping. But I don't know what the problem is... because my code is not involved. Does anybody know this exception and root cause (using JDK 1.8.0.-112)?
Thanks

```<code>'JavaFX Application Thread' lambda$main$68 - Thread[JavaFX Application Thread,5,main] threw an uncaught exception: java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.elementData(ArrayList.java:418) ~[?:1.8.0_112]
    at java.util.ArrayList.get(ArrayList.java:431) ~[?:1.8.0_112]
    at com.sun.javafx.collections.ObservableListWrapper.get(ObservableListWrapper.java:89) ~[jfxrt.jar:?]
    at com.sun.javafx.collections.VetoableListDecorator.get(VetoableListDecorator.java:306) ~[jfxrt.jar:?]
    at javafx.scene.Parent.updateCachedBounds(Parent.java:1591) ~[jfxrt.jar:?]
    at javafx.scene.Parent.recomputeBounds(Parent.java:1535) ~[jfxrt.jar:?]
    at javafx.scene.Parent.impl_computeGeomBounds(Parent.java:1388) ~[jfxrt.jar:?]
    at javafx.scene.layout.Region.impl_computeGeomBounds(Region.java:3078) ~[jfxrt.jar:?]
    at javafx.scene.Node.updateGeomBounds(Node.java:3579) ~[jfxrt.jar:?]
    at javafx.scene.Node.getGeomBounds(Node.java:3532) ~[jfxrt.jar:?]
    at javafx.scene.Node.getLocalBounds(Node.java:3480) ~[jfxrt.jar:?]
    at javafx.scene.Node.updateTxBounds(Node.java:3643) ~[jfxrt.jar:?]
    at javafx.scene.Node.getTransformedBounds(Node.java:3426) ~[jfxrt.jar:?]
    at javafx.scene.Parent.getChildTransformedBounds(Parent.java:1732) ~[jfxrt.jar:?]
    at javafx.scene.Parent.updateCachedBounds(Parent.java:1596) ~[jfxrt.jar:?]
    at javafx.scene.Parent.recomputeBounds(Parent.java:1535) ~[jfxrt.jar:?]
    at javafx.scene.Parent.impl_computeGeomBounds(Parent.java:1388) ~[jfxrt.jar:?]
    at javafx.scene.Node.updateGeomBounds(Node.java:3579) ~[jfxrt.jar:?]
    at javafx.scene.Node.getGeomBounds(Node.java:3532) ~[jfxrt.jar:?]
    at javafx.scene.Node.getLocalBounds(Node.java:3480) ~[jfxrt.jar:?]
    at javafx.scene.Node.impl_intersectsBounds(Node.java:5015) ~[jfxrt.jar:?]
    at javafx.scene.Parent.impl_pickNodeLocal(Parent.java:705) ~[jfxrt.jar:?]
    at javafx.scene.Node.impl_pickNode(Node.java:4914) ~[jfxrt.jar:?]
    at javafx.scene.Scene$MouseHandler.pickNode(Scene.java:3899) ~[jfxrt.jar:?]
    at javafx.scene.Scene$MouseHandler.access$1600(Scene.java:3485) ~[jfxrt.jar:?]
    at javafx.scene.Scene.pick(Scene.java:1942) ~[jfxrt.jar:?]
    at javafx.scene.Scene.access$6700(Scene.java:159) ~[jfxrt.jar:?]
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3799) ~[jfxrt.jar:?]
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485) ~[jfxrt.jar:?]
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762) ~[jfxrt.jar:?]
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494) ~[jfxrt.jar:?]
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381) ~[jfxrt.jar:?]
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295) ~[jfxrt.jar:?]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_112]
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417) ~[jfxrt.jar:?]
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389) ~[jfxrt.jar:?]
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416) ~[jfxrt.jar:?]
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555) ~[jfxrt.jar:?]
    at com.sun.glass.ui.View.notifyMouse(View.java:937) ~[jfxrt.jar:?]
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) ~[jfxrt.jar:?]
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191) ~[jfxrt.jar:?]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_112]
</code>```

I assume, it has something to do with the Label (=BorderPane) adding method. I introduced it to shorten the Java FX Application thread processing time. Is there a problem with that?

```<code>private Queue<BacklogGroupAction> todoList = new ConcurrentLinkedQueue<>();

class BacklogGroupAction {
    boolean add;
    boolean visibleState;
    BorderPane dv;

    public BacklogGroupAction(boolean add, boolean visibleState, BorderPane dv) {
        this.add = add;
        this.visibleState = visibleState;
        this.dv = dv;
    }

}

private synchronized void processBacklogGroupList() {
    if (Platform.isFxApplicationThread()) {
        while (!todoList.isEmpty()) {
            BacklogGroupAction p = todoList.poll();
            if (p.add) {
                p.dv.setVisible(p.visibleState);
                backlogGroup.getChildren()
                .add(p.dv);
            } else
                backlogGroup.getChildren()
                .remove(p.dv);
        }
        backlogGroup.applyCss();
        backlogGroup.layout();
    } else
        logger.error("This is not FX Application Thread");
}
</code>```

答:
thanks for all your help.
The code above "processBacklogGroupList" is actually correct and works... (so why -1..?)

The problem was in a totally different place, where an animation was defined not running in JFX Application Thread - but exception occured a bit later.

So thanks to @sillyfly for pointing me to the real problem

This usually happens when trying to change an ObservableList bound to
  a node from a thread other than the JavaFX UI thread, or else when
  manipulating the list during a change. In both cases usually wrapping
  the offending call in a Platform.runLater solves the problem. See e.g.
  this related question. – sillyfly Jun 27 at 10:03"

Body:
I'm experimenting with JavaFX labels and Groups with moving them over the screen by mouse dragging. New nodes are added to the animation group from some Threads.
However, sometimes I see the following exception out of the sudden - I assume, when some nodes are overlapping. But I don't know what the problem is... because my code is not involved. Does anybody know this exception and root cause (using JDK 1.8.0.-112)?
Thanks

'JavaFX Application Thread' lambda$main$68 - Thread[JavaFX Application Thread,5,main] threw an uncaught exception: java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.elementData(ArrayList.java:418) ~[?:1.8.0_112]
    at java.util.ArrayList.get(ArrayList.java:431) ~[?:1.8.0_112]
    at com.sun.javafx.collections.ObservableListWrapper.get(ObservableListWrapper.java:89) ~[jfxrt.jar:?]
    at com.sun.javafx.collections.VetoableListDecorator.get(VetoableListDecorator.java:306) ~[jfxrt.jar:?]
    at javafx.scene.Parent.updateCachedBounds(Parent.java:1591) ~[jfxrt.jar:?]
    at javafx.scene.Parent.recomputeBounds(Parent.java:1535) ~[jfxrt.jar:?]
    at javafx.scene.Parent.impl_computeGeomBounds(Parent.java:1388) ~[jfxrt.jar:?]
    at javafx.scene.layout.Region.impl_computeGeomBounds(Region.java:3078) ~[jfxrt.jar:?]
    at javafx.scene.Node.updateGeomBounds(Node.java:3579) ~[jfxrt.jar:?]
    at javafx.scene.Node.getGeomBounds(Node.java:3532) ~[jfxrt.jar:?]
    at javafx.scene.Node.getLocalBounds(Node.java:3480) ~[jfxrt.jar:?]
    at javafx.scene.Node.updateTxBounds(Node.java:3643) ~[jfxrt.jar:?]
    at javafx.scene.Node.getTransformedBounds(Node.java:3426) ~[jfxrt.jar:?]
    at javafx.scene.Parent.getChildTransformedBounds(Parent.java:1732) ~[jfxrt.jar:?]
    at javafx.scene.Parent.updateCachedBounds(Parent.java:1596) ~[jfxrt.jar:?]
    at javafx.scene.Parent.recomputeBounds(Parent.java:1535) ~[jfxrt.jar:?]
    at javafx.scene.Parent.impl_computeGeomBounds(Parent.java:1388) ~[jfxrt.jar:?]
    at javafx.scene.Node.updateGeomBounds(Node.java:3579) ~[jfxrt.jar:?]
    at javafx.scene.Node.getGeomBounds(Node.java:3532) ~[jfxrt.jar:?]
    at javafx.scene.Node.getLocalBounds(Node.java:3480) ~[jfxrt.jar:?]
    at javafx.scene.Node.impl_intersectsBounds(Node.java:5015) ~[jfxrt.jar:?]
    at javafx.scene.Parent.impl_pickNodeLocal(Parent.java:705) ~[jfxrt.jar:?]
    at javafx.scene.Node.impl_pickNode(Node.java:4914) ~[jfxrt.jar:?]
    at javafx.scene.Scene$MouseHandler.pickNode(Scene.java:3899) ~[jfxrt.jar:?]
    at javafx.scene.Scene$MouseHandler.access$1600(Scene.java:3485) ~[jfxrt.jar:?]
    at javafx.scene.Scene.pick(Scene.java:1942) ~[jfxrt.jar:?]
    at javafx.scene.Scene.access$6700(Scene.java:159) ~[jfxrt.jar:?]
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3799) ~[jfxrt.jar:?]
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485) ~[jfxrt.jar:?]
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762) ~[jfxrt.jar:?]
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494) ~[jfxrt.jar:?]
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381) ~[jfxrt.jar:?]
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295) ~[jfxrt.jar:?]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_112]
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417) ~[jfxrt.jar:?]
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389) ~[jfxrt.jar:?]
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416) ~[jfxrt.jar:?]
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555) ~[jfxrt.jar:?]
    at com.sun.glass.ui.View.notifyMouse(View.java:937) ~[jfxrt.jar:?]
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) ~[jfxrt.jar:?]
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191) ~[jfxrt.jar:?]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_112]

I assume, it has something to do with the Label (=BorderPane) adding method. I introduced it to shorten the Java FX Application thread processing time. Is there a problem with that?

private Queue<BacklogGroupAction> todoList = new ConcurrentLinkedQueue<>();

class BacklogGroupAction {
    boolean add;
    boolean visibleState;
    BorderPane dv;

    public BacklogGroupAction(boolean add, boolean visibleState, BorderPane dv) {
        this.add = add;
        this.visibleState = visibleState;
        this.dv = dv;
    }

}

private synchronized void processBacklogGroupList() {
    if (Platform.isFxApplicationThread()) {
        while (!todoList.isEmpty()) {
            BacklogGroupAction p = todoList.poll();
            if (p.add) {
                p.dv.setVisible(p.visibleState);
                backlogGroup.getChildren()
                .add(p.dv);
            } else
                backlogGroup.getChildren()
                .remove(p.dv);
        }
        backlogGroup.applyCss();
        backlogGroup.layout();
    } else
        logger.error("This is not FX Application Thread");
}


问:
Forward arrow operator not found
I'm confused with the nature of ->, I cannot get its definition like I can with other operators and it doesn't behave like <-. See below:

```<code>print(`<-`) # .Primitive("<-")
print(`->`) # Error in print(`->`) : object '->' not found
</code>```

Also, I can't hijack it, though R won't fire any error if I try to :

```<code>`->` = `+`  # attempting to hijack `->`, no error
print(`->`) # function (e1, e2)  .Primitive("+"), seems like it worked
1 -> 3      # Error in 3 <- 1 : invalid (do_set) left-hand side to assignment
1 -> test1
print(test1) # 1, hijacking failed
`->`(1,3)   # 4, this works
</code>```

With <- (or any other operator I tried), I can do it:

```<code>`<-` = `+`
print(`<-`)
1 <- 3      # 4
1 <- test2  # Error: object 'test2' not found

rm(list=ls()) # back to sanity
</code>```

So what's going on ?

答:
More a comment than an answer, but it was maybe to long.

It seems that the -> is handled by the parser, which detects the left and right side of the assignment and then calls <-. Following your hacks:

```<code>`<-` = `+`
1 -> 3
#[1] 4
</code>```

See what happened? There is basically no time to the -> operator to act, since the parser doesn't allow it, unless you call it explicitly:

```<code>`->` = `+`
`->`(5,6)
#[1] 11
</code>```

Title: Forward arrow operator not found

Body:
I'm confused with the nature of ->, I cannot get its definition like I can with other operators and it doesn't behave like <-. See below:

print(`<-`) # .Primitive("<-")
print(`->`) # Error in print(`->`) : object '->' not found

Also, I can't hijack it, though R won't fire any error if I try to :

`->` = `+`  # attempting to hijack `->`, no error
print(`->`) # function (e1, e2)  .Primitive("+"), seems like it worked
1 -> 3      # Error in 3 <- 1 : invalid (do_set) left-hand side to assignment
1 -> test1
print(test1) # 1, hijacking failed
`->`(1,3)   # 4, this works

With <- (or any other operator I tried), I can do it:

`<-` = `+`
print(`<-`)
1 <- 3      # 4
1 <- test2  # Error: object 'test2' not found

rm(list=ls()) # back to sanity

So what's going on ?

Body:
More a comment than an answer, but it was maybe to long.

It seems that the -> is handled by the parser, which detects the left and right side of the assignment and then calls <-. Following your hacks:

`<-` = `+`
1 -> 3
#[1] 4

See what happened? There is basically no time to the -> operator to act, since the parser doesn't allow it, unless you call it explicitly:

`->` = `+`
`->`(5,6)
#[1] 11


问:
undefined columns selected (Bayesian analysis)
I am replicating a R code for the Bayesian analysis but I got this error that I have tried to solve it, also reading other questions here but still it does not work.
I use the same dataset and same variables (from OECD). Can anyone tell me why it does not work?
My code is this:

```<code>rm(list=ls())
# Name of variables to be extracted
v.resp=c("pv1math") # Response Variable
v.treat=c("IC02Q01","IC02Q02","IC02Q03") # Treatment variable(s)
# Student Confoundings
v.student.conf=c("Age", "Gender", "isced_0", "IMMIG", "HEDRES", "WEALTH", "ESCS","FAMSTRUC","hisced","hisei","HOMEPOS", "TIMEINT")
# School Confoundings
v.school.conf=c("CLSIZE","SCMATEDU","STRATIO","SMRATIO","PublicPrivate")

## LOAD DATA
dat <- read.dta("name.dta")
## Weighted sample with weights in the w vector
w=dat$W_FSTUWT
</code>```

Subset data in R

```<code>dat=dat[c(v.resp,v.treat,v.student.conf,v.school.conf)]
names(dat)[names(dat)==v.resp]="y"
w=w[complete.cases(dat)]
w=w/sum(w)
nw=function(w) w/sum(w)
dat=dat[complete.cases(dat),]
dim(dat)
</code>```

When I run the line
dat=dat[c(v.resp,v.treat,v.student.conf,v.school.conf)] I got the error
Error in [.data.frame(dat, c(v.resp, v.treat, v.student.conf, v.school.conf)) :undefined columns selected

I have 25000 observation and 900 variables but I want to subset my data with 21 variables and the observations related to them (less than 25000 for sure). I put comma between )] but nothing, run other lines I lose all data.

I also run this code from "Quick-R website" but again the same error message

```<code># select variables v1, v2, v3
myvars <- c("v1", "v2", "v3")
newdata <- mydata[myvars]
</code>```

I would like to understand why it does not work. I am copying and pasting these codes from a paper that used them for the same dataset.
Thank you.

答:
The message stated: undefined columns selected. That is just what is the situation here: you only selected the rows you wanted, but forgot to tell which columns. When you use [ ] for subsetting, you must specify the rows and the columns. So, you need a comma to separate the info for the rows and for the columns. Since you have no selection on rows, you don't need to specify anything after the comma. But the comma is needed. The adjusted code:

```<code>dat=dat[c(v.resp,v.treat,v.student.conf,v.school.conf),]
</code>```

The only difference is the comma before the closing ]

Body:
I am replicating a R code for the Bayesian analysis but I got this error that I have tried to solve it, also reading other questions here but still it does not work.
I use the same dataset and same variables (from OECD). Can anyone tell me why it does not work?
My code is this:

rm(list=ls())
# Name of variables to be extracted
v.resp=c("pv1math") # Response Variable
v.treat=c("IC02Q01","IC02Q02","IC02Q03") # Treatment variable(s)
# Student Confoundings
v.student.conf=c("Age", "Gender", "isced_0", "IMMIG", "HEDRES", "WEALTH", "ESCS","FAMSTRUC","hisced","hisei","HOMEPOS", "TIMEINT")
# School Confoundings
v.school.conf=c("CLSIZE","SCMATEDU","STRATIO","SMRATIO","PublicPrivate")

## LOAD DATA
dat <- read.dta("name.dta")
## Weighted sample with weights in the w vector
w=dat$W_FSTUWT

Subset data in R

dat=dat[c(v.resp,v.treat,v.student.conf,v.school.conf)]
names(dat)[names(dat)==v.resp]="y"
w=w[complete.cases(dat)]
w=w/sum(w)
nw=function(w) w/sum(w)
dat=dat[complete.cases(dat),]
dim(dat)

When I run the line
dat=dat[c(v.resp,v.treat,v.student.conf,v.school.conf)] I got the error
Error in [.data.frame(dat, c(v.resp, v.treat, v.student.conf, v.school.conf)) :undefined columns selected

I have 25000 observation and 900 variables but I want to subset my data with 21 variables and the observations related to them (less than 25000 for sure). I put comma between )] but nothing, run other lines I lose all data.

I also run this code from "Quick-R website" but again the same error message

# select variables v1, v2, v3
myvars <- c("v1", "v2", "v3")
newdata <- mydata[myvars]

I would like to understand why it does not work. I am copying and pasting these codes from a paper that used them for the same dataset.
Thank you.

Body:
The message stated: undefined columns selected. That is just what is the situation here: you only selected the rows you wanted, but forgot to tell which columns. When you use [ ] for subsetting, you must specify the rows and the columns. So, you need a comma to separate the info for the rows and for the columns. Since you have no selection on rows, you don't need to specify anything after the comma. But the comma is needed. The adjusted code:

dat=dat[c(v.resp,v.treat,v.student.conf,v.school.conf),]

The only difference is the comma before the closing ]


问:
Reading XML in C#
I have the following xml

```<code><Objects>
    <Object>
        <ViewAngle>90</ViewAngle>
        <ViewMode>ThirdPerson</ViewMode>
        <Top>50</Top>
        <Left>100</Left>
    </Object>
</Objects>
</code>```

I have the following code to read this xml

```<code>           XmlDataDocument doc = new XmlDataDocument();
           doc.Load(xmlPath);
           XmlElement root = doc.DocumentElement;
           XmlNodeList nodes = root.SelectNodes("/Objects/Object");
           foreach (XmlNode node in nodes)
           {
                if (node.InnerXml.Contains("View"))
                {
                  string viewType=node["View"].InnerText;
                  //..... other stuffs
                }
                if (node.InnerXml.Contains("ViewAngle"))
                {
                  string viewAngle=node["ViewAngle"].InnerText;
                  //..... other stuffs
                }
                if (node.InnerXml.Contains("ViewMode"))
                {
                  string viewMode=node["ViewMode"].InnerText;
                  //..... other stuffs
                }
           }
</code>```

Above code is working fine if my xml contains one more tag i.e. <View>3dView</View>. But if it does not contains the View tag, then it produces error.

The InnerXml.Contains() is a simple string method that checks for the sub-string is present in the string or not.

In my case the Contains("View") returns true as View is present in ViewAngle and in ViewMode that is why it is going inside the if block of View but when it tries to read the node["View"], it produces error as View node is not exists in the xml.

How to resolve this error?

答:
if trageting 3.5 or above u can use linq

```<code>XDocument XDoc = XDocument.Load(@"C:\UrXMLFile.xml");

var q = from b in xml.Descendants("product")
        select new
        {
            View      = (string)b.Element("View") ?? "3dView",
            ViewAngle = (double?)b.Element("ViewAngle") ?? 90.0,
            ViewMode  = (string)b.Element("ViewMode") ?? ThirdPerson,
            Top       = (double?)b.Element("Top") ?? 0.0,
            Left      = (double?)b.Element("Left") ?? 0.0
        };
</code>```

So if View is not found it have a default value always. Also u can create ur class object in select new. Note: I have not compiled it.

Title: Reading XML in C#

Body:
I have the following xml

<Objects>
    <Object>
        <ViewAngle>90</ViewAngle>
        <ViewMode>ThirdPerson</ViewMode>
        <Top>50</Top>
        <Left>100</Left>
    </Object>
</Objects>

I have the following code to read this xml

           XmlDataDocument doc = new XmlDataDocument();
           doc.Load(xmlPath);
           XmlElement root = doc.DocumentElement;
           XmlNodeList nodes = root.SelectNodes("/Objects/Object");
           foreach (XmlNode node in nodes)
           {
                if (node.InnerXml.Contains("View"))
                {
                  string viewType=node["View"].InnerText;
                  //..... other stuffs
                }
                if (node.InnerXml.Contains("ViewAngle"))
                {
                  string viewAngle=node["ViewAngle"].InnerText;
                  //..... other stuffs
                }
                if (node.InnerXml.Contains("ViewMode"))
                {
                  string viewMode=node["ViewMode"].InnerText;
                  //..... other stuffs
                }
           }

Above code is working fine if my xml contains one more tag i.e. <View>3dView</View>. But if it does not contains the View tag, then it produces error.

The InnerXml.Contains() is a simple string method that checks for the sub-string is present in the string or not.

In my case the Contains("View") returns true as View is present in ViewAngle and in ViewMode that is why it is going inside the if block of View but when it tries to read the node["View"], it produces error as View node is not exists in the xml.

How to resolve this error?

Body:
if trageting 3.5 or above u can use linq

XDocument XDoc = XDocument.Load(@"C:\UrXMLFile.xml");

var q = from b in xml.Descendants("product")
        select new
        {
            View      = (string)b.Element("View") ?? "3dView",
            ViewAngle = (double?)b.Element("ViewAngle") ?? 90.0,
            ViewMode  = (string)b.Element("ViewMode") ?? ThirdPerson,
            Top       = (double?)b.Element("Top") ?? 0.0,
            Left      = (double?)b.Element("Left") ?? 0.0
        };

So if View is not found it have a default value always. Also u can create ur class object in select new. Note: I have not compiled it.


问:
Redux Saga - Take Every is never Called
I have this simple saga:

export function* priceComparisonSaga() {
    yield takeEvery(RECORD_PRICE, priceComparison);
}

But whenever I dispatch the event, it is never called. What's going on?

答:
It turns out the action in question had an extra "type" property.

When using the shortcut to create actions like this,

export const addBalance = makeActionCreator(ADD_BALANCE,"balance","type");

This action won't work, because the second type property overwrites "ADD_BALANCE". Instead, this works:

export const addBalance = makeActionCreator(ADD_BALANCE,"balance","balancetype");

Title: Redux Saga - Take Every is never Called


问:
Iterating over several GUI elements
I have a GUI based form with a series of fields on it and want to update the corresponding label when text is entered into one field.  I've been able to get it to work using the following code

```<code>$objTextBoxRD1.add_keyup({$objLabelLU1.Text = Get-Date})
$objTextBoxRD2.add_keyup({$objLabelLU2.Text = Get-Date})
$objTextBoxRD3.add_keyup({$objLabelLU3.Text = Get-Date})
$objTextBoxRD4.add_keyup({$objLabelLU4.Text = Get-Date})
</code>```

Is there a more elegant way to achieve the same result?

I tried the following but when I enter text into any $objTextBoxRD fields it only updates $objLabelU4.

```<code>$Count = 1
foreach ($User in $ISDept) {
    $objTextBoxRD = Get-Variable -Name ('objTextBoxRD' + ([string]$Count)) | Select -Expand Value
    $objLabelLU = Get-Variable -Name ('objLabelLU' + ([string]$Count)) | Select -Expand Value

    $objTextBoxRD.add_keyup({$objLabelLU.Text = Get-Date})
    $Count++
}
</code>```

The $objTextBoxRD and $objLabelLU variables have been generated from arrays and would like to automate this section as the number of variables that get created can vary.

答:
Collect your textbox elements in an array instead of using individual variables, so you can iterate over them with a for loop. Since you want to use corresponding variables in a scriptblock you probably need to generate that scriptblock, though. Try this:

```<code>for ($i=0; $i -lt $objTextBoxRD.Count; $i++) {
    $sb = [scriptblock]::Create("`$objLabelLU$($i+1).Text = Get-Date")
    $objTextBoxRD[$i].Add_Keyup($sb)
}
</code>```

Title: Iterating over several GUI elements

Body:
I have a GUI based form with a series of fields on it and want to update the corresponding label when text is entered into one field.  I've been able to get it to work using the following code

$objTextBoxRD1.add_keyup({$objLabelLU1.Text = Get-Date})
$objTextBoxRD2.add_keyup({$objLabelLU2.Text = Get-Date})
$objTextBoxRD3.add_keyup({$objLabelLU3.Text = Get-Date})
$objTextBoxRD4.add_keyup({$objLabelLU4.Text = Get-Date})

Is there a more elegant way to achieve the same result?

I tried the following but when I enter text into any $objTextBoxRD fields it only updates $objLabelU4.

$Count = 1
foreach ($User in $ISDept) {
    $objTextBoxRD = Get-Variable -Name ('objTextBoxRD' + ([string]$Count)) | Select -Expand Value
    $objLabelLU = Get-Variable -Name ('objLabelLU' + ([string]$Count)) | Select -Expand Value

    $objTextBoxRD.add_keyup({$objLabelLU.Text = Get-Date})
    $Count++
}

The $objTextBoxRD and $objLabelLU variables have been generated from arrays and would like to automate this section as the number of variables that get created can vary.

Body:
Collect your textbox elements in an array instead of using individual variables, so you can iterate over them with a for loop. Since you want to use corresponding variables in a scriptblock you probably need to generate that scriptblock, though. Try this:

for ($i=0; $i -lt $objTextBoxRD.Count; $i++) {
    $sb = [scriptblock]::Create("`$objLabelLU$($i+1).Text = Get-Date")
    $objTextBoxRD[$i].Add_Keyup($sb)
}


问:
How to cancel/revert changes to an observable model (or replace model in array with untouched copy)
I have a viewModel with an observableArray of objects with observable variables.

My template shows the data with an edit button that hides the display elements and shows input elements with the values bound. You can start editing the data and then you have the option to cancel. I would like this cancel to revert to the unchanged version of the object.

I have tried clone the object by doing something like this:

```<code>viewModel.tempContact = jQuery.extend({}, contact);
</code>```

or

```<code>viewModel.tempContact = jQuery.extend(true, {}, contact);
</code>```

but viewModel.tempContact gets modified as soon as contact does.

Is there anything built into KnockoutJS to handle this kind of situation or am I best off to just create a new contact with exactly the same details and replace the modified contact with the new contact on cancel?

Any advice is greatly appreciated. Thanks!

答:
I needed something similar, and I couldn't use the protected observables, as I needed the computed to update on the temporary values. So I wrote this knockout extension:

This extension creates an underscore version of each observable ie self.Comments() -> self._Comments()

```<code>ko.Underscore = function (data) {
    var obj = data;
    var result = {};
    // Underscore Property Check
    var _isOwnProperty = function (isUnderscore, prop) {
        return (isUnderscore == null || prop.startsWith('_') == isUnderscore) && typeof obj[prop] == 'function' && obj.hasOwnProperty(prop) && ko.isObservable(obj[prop]) && !ko.isComputed(obj[prop])
    }
    // Creation of Underscore Properties
    result.init = function () {
        for (var prop in obj) {
            if (_isOwnProperty(null, prop)) {
                var val = obj[prop]();
                var temp = '_' + prop;
                if (obj[prop].isObservableArray)
                    obj[temp] = ko.observableArray(val);
                else
                    obj[temp] = ko.observable(val);
            }
        }
    };
    // Cancel
    result.Cancel = function () {
        for (var prop in obj) {
            if (_isOwnProperty(false, prop)) {
                var val = obj[prop]();
                var p = '_' + prop;
                obj[p](val);
            }
        }
    }
    // Confirm
    result.Confirm = function () {
        for (var prop in obj) {
            if (_isOwnProperty(true, prop)) {
                var val = obj[prop]();
                var p = prop.replace('_', '');
                obj[p](val);
            }
        }
    }
    // Observables
    result.Properties = function () {
        var obs = [];
        for (var prop in obj) {
            if (typeof obj[prop] == 'function' && obj.hasOwnProperty(prop) && ko.isObservable(obj[prop]) && !ko.isComputed(obj[prop])) {
                var val = obj[prop]();
                obs.push({ 'Name': prop, 'Value': val });
            }
        }
        return obs;
    }

    if (obj != null)
        result.init();

    return result;
}
</code>```

This extension will save you writing duplicates of each of your observables and ignores your computed. It works like this:

```<code>var BF_BCS = function (data) {
    var self = this;

    self.Score = ko.observable(null);
    self.Comments = ko.observable('');

    self.Underscore = ko.Underscore(self);

    self.new = function () {
        self._Score(null);
        self._Comments('');
        self.Confirm();
    }

    self.Cancel = function () {
        self.Pause();
        self.Underscore.Cancel();
        self.Resume();
    }

    self.Confirm = function () {
        self.Pause();
        self.Underscore.Confirm();
        self.Resume();
    }

    self.Pause = function () {

    }

    self.Resume = function () {

    }

    self.setData = function (data) {
        self.Pause();

        self._Score(data.Score);
        self._Comments(data.Comments);
        self.Confirm();
        self.Resume();
    }

    if (data != null)
        self.setData(data);
    else
        self.new();
};
</code>```

So as you can see if you have buttons on html:

```<code><div class="panel-footer bf-panel-footer">
    <div class="bf-panel-footer-50" data-bind="click: Cancel.bind($data)">
        Cancel
    </div>
    <div class="bf-panel-footer-50" data-bind="click: Confirm.bind($data)">
        Save
    </div>
</div>
</code>```

Cancel will undo and revert your observables back to what they were, as were save will update the real values with the temp values in one line

Body:
I have a viewModel with an observableArray of objects with observable variables.

My template shows the data with an edit button that hides the display elements and shows input elements with the values bound. You can start editing the data and then you have the option to cancel. I would like this cancel to revert to the unchanged version of the object.

I have tried clone the object by doing something like this:

viewModel.tempContact = jQuery.extend({}, contact);

or

viewModel.tempContact = jQuery.extend(true, {}, contact);

but viewModel.tempContact gets modified as soon as contact does.

Is there anything built into KnockoutJS to handle this kind of situation or am I best off to just create a new contact with exactly the same details and replace the modified contact with the new contact on cancel?

Any advice is greatly appreciated. Thanks!

Body:
I needed something similar, and I couldn't use the protected observables, as I needed the computed to update on the temporary values. So I wrote this knockout extension:

This extension creates an underscore version of each observable ie self.Comments() -> self._Comments()

ko.Underscore = function (data) {
    var obj = data;
    var result = {};
    // Underscore Property Check
    var _isOwnProperty = function (isUnderscore, prop) {
        return (isUnderscore == null || prop.startsWith('_') == isUnderscore) && typeof obj[prop] == 'function' && obj.hasOwnProperty(prop) && ko.isObservable(obj[prop]) && !ko.isComputed(obj[prop])
    }
    // Creation of Underscore Properties
    result.init = function () {
        for (var prop in obj) {
            if (_isOwnProperty(null, prop)) {
                var val = obj[prop]();
                var temp = '_' + prop;
                if (obj[prop].isObservableArray)
                    obj[temp] = ko.observableArray(val);
                else
                    obj[temp] = ko.observable(val);
            }
        }
    };
    // Cancel
    result.Cancel = function () {
        for (var prop in obj) {
            if (_isOwnProperty(false, prop)) {
                var val = obj[prop]();
                var p = '_' + prop;
                obj[p](val);
            }
        }
    }
    // Confirm
    result.Confirm = function () {
        for (var prop in obj) {
            if (_isOwnProperty(true, prop)) {
                var val = obj[prop]();
                var p = prop.replace('_', '');
                obj[p](val);
            }
        }
    }
    // Observables
    result.Properties = function () {
        var obs = [];
        for (var prop in obj) {
            if (typeof obj[prop] == 'function' && obj.hasOwnProperty(prop) && ko.isObservable(obj[prop]) && !ko.isComputed(obj[prop])) {
                var val = obj[prop]();
                obs.push({ 'Name': prop, 'Value': val });
            }
        }
        return obs;
    }

    if (obj != null)
        result.init();

    return result;
}

This extension will save you writing duplicates of each of your observables and ignores your computed. It works like this:

var BF_BCS = function (data) {
    var self = this;

    self.Score = ko.observable(null);
    self.Comments = ko.observable('');

    self.Underscore = ko.Underscore(self);

    self.new = function () {
        self._Score(null);
        self._Comments('');
        self.Confirm();
    }

    self.Cancel = function () {
        self.Pause();
        self.Underscore.Cancel();
        self.Resume();
    }

    self.Confirm = function () {
        self.Pause();
        self.Underscore.Confirm();
        self.Resume();
    }

    self.Pause = function () {

    }

    self.Resume = function () {

    }

    self.setData = function (data) {
        self.Pause();

        self._Score(data.Score);
        self._Comments(data.Comments);
        self.Confirm();
        self.Resume();
    }

    if (data != null)
        self.setData(data);
    else
        self.new();
};

So as you can see if you have buttons on html:

<div class="panel-footer bf-panel-footer">
    <div class="bf-panel-footer-50" data-bind="click: Cancel.bind($data)">
        Cancel
    </div>
    <div class="bf-panel-footer-50" data-bind="click: Confirm.bind($data)">
        Save
    </div>
</div>

Cancel will undo and revert your observables back to what they were, as were save will update the real values with the temp values in one line


问:
Angular js - Call function inside controller from view in ng-admin
I am working with the feature of multiple languages for ng-admin.
In the file header.html, I have added a dropdown with a list of languages. Clicking each option fires a function call.

The function itself is inside a controller in /js/main.js

Clicking in any of the languages results in ReferenceError: serve_language is not defined.

This is the content of both files:

header.html

```<code><ul class="nav navbar-top-links navbar-right hidden-xs">
    <li uib-dropdown ng-controller="languageCtrl">
        <a uib-dropdown-toggle href="#" aria-expanded="true">
            <i class="fa fa-user fa-lg"></i>  Language <i class="fa fa-caret-down"></i>
        </a>
        <ul class="dropdown-menu dropdown-user" role="menu">
            <li><a href="#" onclick="serve_language('en')"><i class="fa fa-sign-out fa-fw"></i> English</a></li>
            <li><a href="#" onclick="serve_language('ge')"><i class="fa fa-sign-out fa-fw"></i> German</a></li>
            <li><a href="#" onclick="serve_language('fr')"><i class="fa fa-sign-out fa-fw"></i> French</a></li>
            <li><a href="#" onclick="serve_language('sp')"><i class="fa fa-sign-out fa-fw"></i> Spanish</a></li>
        </ul>
    </li>
</ul>
</code>```

main.js

```<code>'use strict'
var myApp = angular.module('myApp', ['ng-admin','ng-admin.jwt-auth', 'nvd3']);
myApp.controller('languageCtrl', ['$translate', '$scope', function ($translate, $scope) {
    $scope.serve_language = function (langKey) {
       console.log("@langctrl");
    };
}]);
</code>```

I also tried calling the function as languageCtrl.serve_language(), but that resulted in ReferenceError: languageCtrl is not defined

答: Use ng-click as angularjs does not support onclick

Body:
I am working with the feature of multiple languages for ng-admin.
In the file header.html, I have added a dropdown with a list of languages. Clicking each option fires a function call.

The function itself is inside a controller in /js/main.js

Clicking in any of the languages results in ReferenceError: serve_language is not defined.

This is the content of both files:

header.html

              Language

 English

 German

 French

 Spanish

main.js

'use strict'
var myApp = angular.module('myApp', ['ng-admin','ng-admin.jwt-auth', 'nvd3']);
myApp.controller('languageCtrl', ['$translate', '$scope', function ($translate, $scope) {
    $scope.serve_language = function (langKey) {
       console.log("@langctrl");
    };
}]);

I also tried calling the function as languageCtrl.serve_language(), but that resulted in ReferenceError: languageCtrl is not defined


问:
Execute query on enter php page
I need a query to execute when entering a page (php). I've already added this to the top.

Code:-

```<code>mysql_query("INSERT INTO `table_name` (`player_id`, `unit1`, `unit2`, `unit3`, `unit4`)
VALUES ('".$_SESSION['user']['id']."', 0, 0, 0, 0)");
</code>```

When my users enter the page that contains that, the query should be executed. Yes database connection is included.

How do I fix this? (also will it duplicate player_id)?

答:
First mysql is deprecated use mysqli.

Your query is fine how i can see, but your table could be a problem.

You should not have primary key on player_id if you wish to duplicate player_id. (Otherwise keep the primary key).

Also if you wish to have one player_id with those results (not multiple / duplicates), then you could create query in this way:

```<code>$query = "INSERT INTO `table_name` (`player_id`, `unit1`, `unit2`, `unit3`, `unit4`)
          VALUES ('".$_SESSION['user']['id']."', 0, 0, 0, 0)
          ON DUPLICATE KEY UPDATE `unit1`=0, `unit2`=0, `unit3`=0, `unit4`=0";
</code>```

UPDATE:

Also there could be a problem that you are missing a database identifier at mysql_query:

mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )

like mysql_query("MYQUERY", $mylinkISavedAtConnectingToDatabase);

Title: Execute query on enter php page

Body:
I need a query to execute when entering a page (php). I've already added this to the top.

Code:-

mysql_query("INSERT INTO `table_name` (`player_id`, `unit1`, `unit2`, `unit3`, `unit4`)
VALUES ('".$_SESSION['user']['id']."', 0, 0, 0, 0)");

When my users enter the page that contains that, the query should be executed. Yes database connection is included.

How do I fix this? (also will it duplicate player_id)?

Body:
First mysql is deprecated use mysqli.

Your query is fine how i can see, but your table could be a problem.

You should not have primary key on player_id if you wish to duplicate player_id. (Otherwise keep the primary key).

Also if you wish to have one player_id with those results (not multiple / duplicates), then you could create query in this way:

$query = "INSERT INTO `table_name` (`player_id`, `unit1`, `unit2`, `unit3`, `unit4`)
          VALUES ('".$_SESSION['user']['id']."', 0, 0, 0, 0)
          ON DUPLICATE KEY UPDATE `unit1`=0, `unit2`=0, `unit3`=0, `unit4`=0";

UPDATE:

Also there could be a problem that you are missing a database identifier at mysql_query:

mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )

like mysql_query("MYQUERY", $mylinkISavedAtConnectingToDatabase);


问:
how to create multiple udp clients listenning to the same port in java nio?
for normal io ,  I can do it like this:

```<code>s1=new DatagramSocket(1234)
s2=new DatagramSocket(1234)

bytes=xxxxxx
packet = DatagramPacket(bytes, bytes.size,InetSocketAddress("localhost",1234))
new DatagramSocket().send(packet)
//  and then the s1 and s2 can receive the packet.
</code>```

but in nio.  how to do this? I tried like this:

first:

```<code>s1=DatagramChannel.open()
s1.bind(new Inetsocketaddress("localhost",1234)

s2=DatagramChannel.open()
s2.bind(new Inetsocketaddress("localhost",1234)// will throw an exception
</code>```

second:

```<code>s1=DatagramChannel.open()
s1.setOption(StandardSocketOptions.SO_REUSEADDR, true);
s1.bind(new Inetsocketaddress("localhost",1234)

s2=DatagramChannel.open()
s2.setOption(StandardSocketOptions.SO_REUSEADDR, true);
s2.bind(new Inetsocketaddress("localhost",1234)

//these code will not throw exception. but s2 cannot receive any data.
// when i close s1,  then s2 will receive data.
</code>```

答:
If you really need the message to be processed by all the clients, you need a multi-cast / broad-cast protocol. In this sense, as stated in a previous question (Does Java NIO support broadcast or multicast?), NIO2 Supports multi-cast and broad-cast but not using the DatagramChannel class. Instead you have the MultiCastChannel interface (you can find official documentation in http://javanio.info/filearea/nioserver/WhatsNewNIO2.pdf and an example in: How do I implement a multicast client in NIO.2?).
Regarding your code, it should look like:

```<code>   NetworkInterface netInterface = NetworkInterface.getByName("em1");
   InetAddress group = InetAddress.getByName("localhost");

   // Reader 1
   System.out.println("Create Reader 1");
   DatagramChannel s1 = DatagramChannel.open(StandardProtocolFamily.INET);
   s1.setOption(StandardSocketOptions.SO_REUSEADDR, true);
   s1.bind(new InetSocketAddress(PORT));
   s1.setOption(StandardSocketOptions.IP_MULTICAST_IF, netInterface);

   // Reader 2
   System.out.println("Create Reader 2");
   DatagramChannel s2 = DatagramChannel.open(StandardProtocolFamily.INET);
   s2.setOption(StandardSocketOptions.SO_REUSEADDR, true);
   s2.bind(new InetSocketAddress(PORT));
   s2.setOption(StandardSocketOptions.IP_MULTICAST_IF, netInterface);
</code>```

Be aware that multi-cast / broad-cast must be supported by your underlying hardware stack. Otherwise, the join method will throw an exception.

If you don't need the message to be processed by all the clients but rather you need any of them to process it without blocking the others, you can set the non-blocking socket option. Considering the code you provided, I add below a solution with non-blocking:

```<code>import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;

public class Main {

    private static final String HOST = "localhost";
    private static final int PORT = 1234;

    private static final String MESSAGE = "HelloWorld";
    private static final int MESSAGE_SIZE = MESSAGE.length();

    public static void main(String[] args) throws IOException {
        // Reader 1
        System.out.println("Create Reader 1");
        DatagramChannel s1 = DatagramChannel.open();
        s1.configureBlocking(false);
        s1.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        s1.bind(new InetSocketAddress(HOST, PORT));

        // Reader 2
        System.out.println("Create Reader 2");
        DatagramChannel s2 = DatagramChannel.open();
        s2.configureBlocking(false);
        s2.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        s2.bind(new InetSocketAddress(HOST, PORT));

        // Writer
        System.out.println("Create Writer");
        DatagramChannel s3 = DatagramChannel.open();

        // Send and receive messages
        System.out.println("Send message");
        send(s3);
        System.out.println("Receive message on Reader 1");
        receive(s1);
        System.out.println("Receive message on Reader 2");
        receive(s2);

        // Close
        System.out.println("Close");
        s1.close();
        s2.close();
        s3.close();
    }

    private static void send(DatagramChannel channel) throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(MESSAGE_SIZE);
        buf.clear();
        buf.put(MESSAGE.getBytes());
        buf.flip();

        int bytesSent = channel.send(buf, new InetSocketAddress(HOST, PORT));
        System.out.println("Sent: " + bytesSent);
    }

    private static void receive(DatagramChannel channel) throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(MESSAGE_SIZE);
        buf.clear();

        channel.receive(buf);

        String str = new String(buf.array(), StandardCharsets.UTF_8);
        System.out.println("Received: " + str);
    }

}
</code>```

Which output is:

```<code>Create Reader 1
Create Reader 2
Create Writer
Send message
Sent: 10
Receive message on Reader 1
Received:
Receive message on Reader 2
Received: HelloWorld
Close
</code>```

Body:
for normal io ,  I can do it like this:

s1=new DatagramSocket(1234)
s2=new DatagramSocket(1234)

bytes=xxxxxx
packet = DatagramPacket(bytes, bytes.size,InetSocketAddress("localhost",1234))
new DatagramSocket().send(packet)
//  and then the s1 and s2 can receive the packet.

but in nio.  how to do this? I tried like this:

first:

s1=DatagramChannel.open()
s1.bind(new Inetsocketaddress("localhost",1234)

s2=DatagramChannel.open()
s2.bind(new Inetsocketaddress("localhost",1234)// will throw an exception

second:

s1=DatagramChannel.open()
s1.setOption(StandardSocketOptions.SO_REUSEADDR, true);
s1.bind(new Inetsocketaddress("localhost",1234)

s2=DatagramChannel.open()
s2.setOption(StandardSocketOptions.SO_REUSEADDR, true);
s2.bind(new Inetsocketaddress("localhost",1234)

//these code will not throw exception. but s2 cannot receive any data.
// when i close s1,  then s2 will receive data.

Body:
If you really need the message to be processed by all the clients, you need a multi-cast / broad-cast protocol. In this sense, as stated in a previous question (Does Java NIO support broadcast or multicast?), NIO2 Supports multi-cast and broad-cast but not using the DatagramChannel class. Instead you have the MultiCastChannel interface (you can find official documentation in http://javanio.info/filearea/nioserver/WhatsNewNIO2.pdf and an example in: How do I implement a multicast client in NIO.2?).
Regarding your code, it should look like:

   NetworkInterface netInterface = NetworkInterface.getByName("em1");
   InetAddress group = InetAddress.getByName("localhost");

   // Reader 1
   System.out.println("Create Reader 1");
   DatagramChannel s1 = DatagramChannel.open(StandardProtocolFamily.INET);
   s1.setOption(StandardSocketOptions.SO_REUSEADDR, true);
   s1.bind(new InetSocketAddress(PORT));
   s1.setOption(StandardSocketOptions.IP_MULTICAST_IF, netInterface);

   // Reader 2
   System.out.println("Create Reader 2");
   DatagramChannel s2 = DatagramChannel.open(StandardProtocolFamily.INET);
   s2.setOption(StandardSocketOptions.SO_REUSEADDR, true);
   s2.bind(new InetSocketAddress(PORT));
   s2.setOption(StandardSocketOptions.IP_MULTICAST_IF, netInterface);

Be aware that multi-cast / broad-cast must be supported by your underlying hardware stack. Otherwise, the join method will throw an exception.

If you don't need the message to be processed by all the clients but rather you need any of them to process it without blocking the others, you can set the non-blocking socket option. Considering the code you provided, I add below a solution with non-blocking:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;

public class Main {

    private static final String HOST = "localhost";
    private static final int PORT = 1234;

    private static final String MESSAGE = "HelloWorld";
    private static final int MESSAGE_SIZE = MESSAGE.length();

    public static void main(String[] args) throws IOException {
        // Reader 1
        System.out.println("Create Reader 1");
        DatagramChannel s1 = DatagramChannel.open();
        s1.configureBlocking(false);
        s1.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        s1.bind(new InetSocketAddress(HOST, PORT));

        // Reader 2
        System.out.println("Create Reader 2");
        DatagramChannel s2 = DatagramChannel.open();
        s2.configureBlocking(false);
        s2.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        s2.bind(new InetSocketAddress(HOST, PORT));

        // Writer
        System.out.println("Create Writer");
        DatagramChannel s3 = DatagramChannel.open();

        // Send and receive messages
        System.out.println("Send message");
        send(s3);
        System.out.println("Receive message on Reader 1");
        receive(s1);
        System.out.println("Receive message on Reader 2");
        receive(s2);

        // Close
        System.out.println("Close");
        s1.close();
        s2.close();
        s3.close();
    }

    private static void send(DatagramChannel channel) throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(MESSAGE_SIZE);
        buf.clear();
        buf.put(MESSAGE.getBytes());
        buf.flip();

        int bytesSent = channel.send(buf, new InetSocketAddress(HOST, PORT));
        System.out.println("Sent: " + bytesSent);
    }

    private static void receive(DatagramChannel channel) throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(MESSAGE_SIZE);
        buf.clear();

        channel.receive(buf);

        String str = new String(buf.array(), StandardCharsets.UTF_8);
        System.out.println("Received: " + str);
    }

}

Which output is:

Create Reader 1
Create Reader 2
Create Writer
Send message
Sent: 10
Receive message on Reader 1
Received:
Receive message on Reader 2
Received: HelloWorld
Close


问:
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

```<code>int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}
</code>```

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

```<code>int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
</code>```

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

答:
A routine which uses a local flag is, in terms of state analysis, equivalent to the same code, copied out twice, with one copy corresponding to the flag being true, and the other copy being equivalent to the flag being false, and any code which changes the state of the flag jumping between them.  If there are n flags, the equivalent would be 2^n copies of the code (though if some flags are mutually exclusive, some of those may be unreachable and irrelevant).

While there are certainly times that flags are the most practical way to do things, they add complexity to the code.  When the complexity is really necessary, flags may be the cleanest way to provide it.  When there's a clean and practical way to write code which avoids the flags, one should do so.  There are certainly times when it may be unclear whether it's better to use or avoid a flag (e.g.

```
  flag = condition_which_must_be_tested_here();
  action_which_will_disturb_the_condition();
  if (flag)
    do_something();
  else
    do_something_else();
```

versus

```
  if (condition_which_must_be_tested_here())
  {
    action_which_will_disturb_the_condition();
    do_something();
  }
  else
  {
    action_which_will_disturb_the_condition();
    do_something_else();
  }
```

but in cases where no code can be written without a flag and without having to duplicate anything, such a version is generally preferable.

Body:
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

Body:
A routine which uses a local flag is, in terms of state analysis, equivalent to the same code, copied out twice, with one copy corresponding to the flag being true, and the other copy being equivalent to the flag being false, and any code which changes the state of the flag jumping between them.  If there are n flags, the equivalent would be 2^n copies of the code (though if some flags are mutually exclusive, some of those may be unreachable and irrelevant).

While there are certainly times that flags are the most practical way to do things, they add complexity to the code.  When the complexity is really necessary, flags may be the cleanest way to provide it.  When there's a clean and practical way to write code which avoids the flags, one should do so.  There are certainly times when it may be unclear whether it's better to use or avoid a flag (e.g.

  flag = condition_which_must_be_tested_here();
  action_which_will_disturb_the_condition();
  if (flag)
    do_something();
  else
    do_something_else();

versus

  if (condition_which_must_be_tested_here())
  {
    action_which_will_disturb_the_condition();
    do_something();
  }
  else
  {
    action_which_will_disturb_the_condition();
    do_something_else();
  }

but in cases where no code can be written without a flag and without having to duplicate anything, such a version is generally preferable.


问:
NumericUpDown ValueChanged preventDefault?
I want to create a form that allows the user to set a certain amount of points in five different fields (NumericUpDown). When that amount of points reaches 0, the user can't add any more. (I still want the user to be able to remove points, though.)

Here is my code so far:

```<code>private void calculateValue() {
  decimal tempValue = CMB_num_Aim.Value + CMB_num_Reflexes.Value +
  CMB_num_Positioning.Value + CMB_num_Movement.Value + CMB_num_Teamwork.Value;
  controlValue = currentValue - tempValue;
  MyBox.CMB_tb_cv.Text = controlValue.ToString();
}
</code>```

This Method (calculateValue) is calculates how many points the user have left (controlValue).

```<code>private void CMB_num_Aim_ValueChanged(object sender, EventArgs e) {
  calculateValue();
  if (controlValue < 0) {
     //Prevent Default here
     MessageBox.Show("You are out of points!");
  }
}
</code>```

This method (CMB_num_Aim_ValueChanged) fires when the value of the NumericUpDown control has changed. I have one of these for each field, each doing the same thing.

The method fires as expected, but I can't prevent it from happening - the user can apply more points than they have. How can I prevent the user from applying more points?

(I thought about making a mouseUp method, but I don't know if the user will use the mouse or if he will type in the value using the keyboard.)

答:
Seems like you want to create a point distribution system between some skills - aim, movement, teamwork etc. You can do that easily by setting Maximum value of NumericUpDown control when you enter it. Subscribe all skill updown controls to the same event handler:

```<code>private void SkillNumericUpDown_Enter(object sender, EventArgs e)
{
   var skill = (NumericUpDown)sender;
   var availablePoints = 42;
   var maxSkillPoints = 20; // usually you cannot assign all points to one skill
   var unassignedPoints = availablePoints - SkillPointsAssigned;
   skill.Maximum = Math.Min(maxSkillPoints, unassignedPoints  + skill.Value);

   if (unassignedPoints == 0)
   {
       MessageBox.Show("You are out of points!");
       return;
   }

   if (skill.Value == maxSkillPoints)
   {
       MessageBox.Show("Skill maximized!");
       return;
   }
}

private decimal SkillPointsAssigned =>
    CMB_num_Aim.Value +
    CMB_num_Reflexes.Value +
    CMB_num_Positioning.Value +
    CMB_num_Movement.Value +
    CMB_num_Teamwork.Value;
</code>```

Benefit - you will not be able to input illegal value neither by arrows nor manually.

Body:
I want to create a form that allows the user to set a certain amount of points in five different fields (NumericUpDown). When that amount of points reaches 0, the user can't add any more. (I still want the user to be able to remove points, though.)

Here is my code so far:

private void calculateValue() {
  decimal tempValue = CMB_num_Aim.Value + CMB_num_Reflexes.Value +
  CMB_num_Positioning.Value + CMB_num_Movement.Value + CMB_num_Teamwork.Value;
  controlValue = currentValue - tempValue;
  MyBox.CMB_tb_cv.Text = controlValue.ToString();
}

This Method (calculateValue) is calculates how many points the user have left (controlValue).

private void CMB_num_Aim_ValueChanged(object sender, EventArgs e) {
  calculateValue();
  if (controlValue < 0) {
     //Prevent Default here
     MessageBox.Show("You are out of points!");
  }
}

This method (CMB_num_Aim_ValueChanged) fires when the value of the NumericUpDown control has changed. I have one of these for each field, each doing the same thing.

The method fires as expected, but I can't prevent it from happening - the user can apply more points than they have. How can I prevent the user from applying more points?

(I thought about making a mouseUp method, but I don't know if the user will use the mouse or if he will type in the value using the keyboard.)

Body:
Seems like you want to create a point distribution system between some skills - aim, movement, teamwork etc. You can do that easily by setting Maximum value of NumericUpDown control when you enter it. Subscribe all skill updown controls to the same event handler:

private void SkillNumericUpDown_Enter(object sender, EventArgs e)
{
   var skill = (NumericUpDown)sender;
   var availablePoints = 42;
   var maxSkillPoints = 20; // usually you cannot assign all points to one skill
   var unassignedPoints = availablePoints - SkillPointsAssigned;
   skill.Maximum = Math.Min(maxSkillPoints, unassignedPoints  + skill.Value);

   if (unassignedPoints == 0)
   {
       MessageBox.Show("You are out of points!");
       return;
   }

   if (skill.Value == maxSkillPoints)
   {
       MessageBox.Show("Skill maximized!");
       return;
   }
}

private decimal SkillPointsAssigned =>
    CMB_num_Aim.Value +
    CMB_num_Reflexes.Value +
    CMB_num_Positioning.Value +
    CMB_num_Movement.Value +
    CMB_num_Teamwork.Value;

Benefit - you will not be able to input illegal value neither by arrows nor manually.


问:
Amazon AWS - some regions won't authenticate, others will?
All the time I've been with AWS, I've been using eu-west-1 and the c# code I've written authenticates just fine. It was always the intention that multiple regions would be used, so the regionURL(s) are a configuration option; literally a list of strings. Up to now the list has been 1 long.

The general way of the app working is: within a loop that enumerates the configured URLs, it creates a client and looks for an instance with a particular name pattern that is not running, and then starts it. Up to now there was only eu-west-1 configured so it would only use that regionURL when creating the client, enumerating only the stopped instances in that region

I've recently started adding EC2 instances into another region eu-central-1 so I've added the eu-central-1 region base URL to the config. I know the loop that iterates the config works properly (I've attached a debugger and inspected the string for trailing characters etc - all looks fine), and these are the configured region URLs:

```<code>https://eu-west-1.ec2.amazonaws.com
https://ec2.eu-central-1.amazonaws.com
</code>```

Whenever the app comes to enumerate the region URLs it gets eu-west-1 first and that works fine, but when the loop comes around to eu-central-1 the call to .DescribeInstances(...) fails with:

AWS was not able to validate the provided access credentials

There isn't any practical difference in the way the clients are created; this is literally the exact same code that just worked for eu-west-1. I don't make any particular special effort to provide credentials to anything in code; the web.config just has key value pairs for AWSAccessKey and AWSSecretKey. I've always assumed that the AWS SDK accesses them implicitly by virtue of being a dll part of the app..

Is there something I have to do in the console to enable credentials for a region? Is the fact that the region URLs look in different orders significant (I got the central URL off amazon help docs, the west url is as it always has been)?

答:
I upgraded the AWS SDK from 1.5 to version 3.3, changing the names of various classes to reflect breaking changes to the schema of AWS namespaces but keeping all the same logic.

I also switched from specifying the region URLs in the config, to region names in the config, as the region URLs seem to be built into the SDK itself when using the static call RegionEndpoint.GetBySystemName("eu-west-1")

These were the only changes, and all started working automagically; the API keys still specified n the web config only, still operating under the assumption that the SDK finds them there itself as I don't use them in my code..

Body:
All the time I've been with AWS, I've been using eu-west-1 and the c# code I've written authenticates just fine. It was always the intention that multiple regions would be used, so the regionURL(s) are a configuration option; literally a list of strings. Up to now the list has been 1 long.

The general way of the app working is: within a loop that enumerates the configured URLs, it creates a client and looks for an instance with a particular name pattern that is not running, and then starts it. Up to now there was only eu-west-1 configured so it would only use that regionURL when creating the client, enumerating only the stopped instances in that region

I've recently started adding EC2 instances into another region eu-central-1 so I've added the eu-central-1 region base URL to the config. I know the loop that iterates the config works properly (I've attached a debugger and inspected the string for trailing characters etc - all looks fine), and these are the configured region URLs:

https://eu-west-1.ec2.amazonaws.com
https://ec2.eu-central-1.amazonaws.com

Whenever the app comes to enumerate the region URLs it gets eu-west-1 first and that works fine, but when the loop comes around to eu-central-1 the call to .DescribeInstances(...) fails with:

AWS was not able to validate the provided access credentials

There isn't any practical difference in the way the clients are created; this is literally the exact same code that just worked for eu-west-1. I don't make any particular special effort to provide credentials to anything in code; the web.config just has key value pairs for AWSAccessKey and AWSSecretKey. I've always assumed that the AWS SDK accesses them implicitly by virtue of being a dll part of the app..

Is there something I have to do in the console to enable credentials for a region? Is the fact that the region URLs look in different orders significant (I got the central URL off amazon help docs, the west url is as it always has been)?


问:
Installing pzmq with Cygwin
For two days I have been struggling to install pyzmq and I am really not sure what the issue is.

The error message I receive after:

```<code>pip install pyzmq
</code>```

is:

```<code> error: command 'gcc' failed with exit status 1
</code>```

I have gcc installed.

```<code>which gcc
/usr/bin/gcc
</code>```

Python is installed at the same location. I am really struggling to find a solution.

Edit: Adding to the output from the error, here is the output that describes the error further:

```<code> bundled/zeromq/src/signaler.cpp:62:25: fatal error: sys/eventfd.h: No  such file or directory
  #include <sys/eventfd.h>
                         ^
compilation terminated.
error: command 'gcc' failed with exit status 1

----------------------------------------
Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip- build-INbMj2/pyzmq/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'),
__file__, 'exec'))" install --record /tmp/pip-n8hQ_h-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-INbMj2/pyzmq
</code>```

Edit Two: Following installation instructions from https://github.com/zeromq/pyzmq/issues/391

```<code>pip install pyzmq --install-option="fetch_libzmq"
</code>```

Yields :

```<code>#include <sys/eventfd.h>
                         ^
compilation terminated.
error: command 'gcc' failed with exit status 1
</code>```

Next:

```<code>pip install --no-use-wheel pyzmq --global-option='fetch_libzmq' --install-option='--zmq=bundled'
</code>```

Yields:

```<code>#include <sys/eventfd.h>
                         ^
compilation terminated.
error: command 'gcc' failed with exit status 1
</code>```

答:
python3-zmq is a package in cygwin. Assuming you are trying to install for python 3, if you are using apt-cyg package manager, you can install it using</p>

```<code>apt-cyg install python3-zmq
</code>```

Title: Installing pzmq with Cygwin

Body:
For two days I have been struggling to install pyzmq and I am really not sure what the issue is.

The error message I receive after:

pip install pyzmq

is:

 error: command 'gcc' failed with exit status 1

I have gcc installed.

which gcc
/usr/bin/gcc

Python is installed at the same location. I am really struggling to find a solution.

Edit: Adding to the output from the error, here is the output that describes the error further:

 bundled/zeromq/src/signaler.cpp:62:25: fatal error: sys/eventfd.h: No  such file or directory
  #include <sys/eventfd.h>
                         ^
compilation terminated.
error: command 'gcc' failed with exit status 1

----------------------------------------
Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip- build-INbMj2/pyzmq/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'),
__file__, 'exec'))" install --record /tmp/pip-n8hQ_h-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-INbMj2/pyzmq

Edit Two: Following installation instructions from https://github.com/zeromq/pyzmq/issues/391

pip install pyzmq --install-option="fetch_libzmq"

Yields :

#include <sys/eventfd.h>
                         ^
compilation terminated.
error: command 'gcc' failed with exit status 1

Next:

pip install --no-use-wheel pyzmq --global-option='fetch_libzmq' --install-option='--zmq=bundled'

Yields:

#include <sys/eventfd.h>
                         ^
compilation terminated.
error: command 'gcc' failed with exit status 1

Body:
python3-zmq is a package in cygwin. Assuming you are trying to install for python 3, if you are using apt-cyg package manager, you can install it using

apt-cyg install python3-zmq