问:
Strange or inaccurate result with rolling sum (floating point precision)
I have a series I get from an outside source (x). It's all positive, and is mostly zero.

```<code>x.describe()
count    23275.000000
mean         0.015597
std          0.411720
min          0.000000
25%          0.000000
50%          0.000000
75%          0.000000
max         26.000000
dtype: float64
</code>```

However, running rolling_sum on it produces values smaller than zero. Why does it happen? Any way to avoid/bypass it?

```<code>rolling_sum(x, window=100).iloc[-1]
-1.4743761767e-13
(rolling_sum(x, window=100)<0).sum()
16291
</code>```

What's even weirder is that these two calculations (which to the best of my knowledge should yield the same value) does not:

```<code>rolling_sum(x, window=100).iloc[-1]
-1.4743761767e-13
rolling_sum(x.iloc[-100:], window=100).iloc[-1]
0.0
</code>```

(This is both with pandas 0.14.1 and 0.15.2)

答:
This issue is also with the pd.rolling() method and also occurs if you include a large positive integer in a list of relatively smaller values with high precision.

```<code>import pandas as pd
x = pd.DataFrame([0, 1, 2, 2.23425304, 3.2342352934, 4.32423857239])
x.rolling(window=2).mean()
          0
0       NaN
1  0.500000
2  1.500000
3  2.117127
4  2.734244
5  3.779237
</code>```

Replacing the second element with 1E15...

```<code>x = pd.DataFrame([0, 1, 1E15, 2.23425304, 3.2342352934, 4.32423857239])
x.rolling(window=2).mean()
              0
0           NaN
1  5.000000e-01
2  5.000000e+14
3  5.000000e+14
4  2.750000e+00
5  3.794993e+00
</code>```

It's more pronounced with the rolling standard deviation...

```<code>x = pd.DataFrame([0, 1, 2, 2.23425304, 3.2342352934, 4.32423857239])
x.rolling(window=2).std()
          0
0       NaN
1  0.707107
2  0.707107
3  0.165642
4  0.707094
5  0.770749

x = pd.DataFrame([0, 1, 1E15, 2.23425304, 3.2342352934, 4.32423857239])
x.rolling(window=2).std()
              0
0           NaN
1  7.071068e-01
2  7.071068e+14
3  7.071068e+14
4  1.186328e+07
5  1.186328e+07
</code>```

The only solution seems to sacrifice the performance benefits for accuracy, i.e. do the rolling mean directly.

```<code>def rolling_window_slow(window, df):
    df_mean = []
    for i in range(len(df) - window):
        df_mean.append(df.iloc[i:i+window, :].mean())
    return df_mean
</code>```

Body:
I have a series I get from an outside source (x). It's all positive, and is mostly zero.

x.describe()
count    23275.000000
mean         0.015597
std          0.411720
min          0.000000
25%          0.000000
50%          0.000000
75%          0.000000
max         26.000000
dtype: float64

However, running rolling_sum on it produces values smaller than zero. Why does it happen? Any way to avoid/bypass it?

rolling_sum(x, window=100).iloc[-1]
-1.4743761767e-13
(rolling_sum(x, window=100)<0).sum()
16291

What's even weirder is that these two calculations (which to the best of my knowledge should yield the same value) does not:

rolling_sum(x, window=100).iloc[-1]
-1.4743761767e-13
rolling_sum(x.iloc[-100:], window=100).iloc[-1]
0.0

(This is both with pandas 0.14.1 and 0.15.2)

Body:
This issue is also with the pd.rolling() method and also occurs if you include a large positive integer in a list of relatively smaller values with high precision.

import pandas as pd
x = pd.DataFrame([0, 1, 2, 2.23425304, 3.2342352934, 4.32423857239])
x.rolling(window=2).mean()
          0
0       NaN
1  0.500000
2  1.500000
3  2.117127
4  2.734244
5  3.779237

Replacing the second element with 1E15...

x = pd.DataFrame([0, 1, 1E15, 2.23425304, 3.2342352934, 4.32423857239])
x.rolling(window=2).mean()
              0
0           NaN
1  5.000000e-01
2  5.000000e+14
3  5.000000e+14
4  2.750000e+00
5  3.794993e+00

It's more pronounced with the rolling standard deviation...

x = pd.DataFrame([0, 1, 2, 2.23425304, 3.2342352934, 4.32423857239])
x.rolling(window=2).std()
          0
0       NaN
1  0.707107
2  0.707107
3  0.165642
4  0.707094
5  0.770749

x = pd.DataFrame([0, 1, 1E15, 2.23425304, 3.2342352934, 4.32423857239])
x.rolling(window=2).std()
              0
0           NaN
1  7.071068e-01
2  7.071068e+14
3  7.071068e+14
4  1.186328e+07
5  1.186328e+07

The only solution seems to sacrifice the performance benefits for accuracy, i.e. do the rolling mean directly.

def rolling_window_slow(window, df):
    df_mean = []
    for i in range(len(df) - window):
        df_mean.append(df.iloc[i:i+window, :].mean())
    return df_mean


来源: stackexchange

问:
Position of picture changed
The position of the picture was the same until I changed the pictures.

These are the position of the pictures with the old photos

This is the position with the new photos

.column-2 {
  float: left;
  width: 33.3%;
  padding: 5px;
  padding-right: 30px;
  display: inline-block;
}

.column-3 {
  float: right;
  width: 30%;
  display: inline-block;
  padding-right: 30px;
  padding
}

.section-team {
  text-align: center;
}

.members {
  border-radius: 50%;
}

.upm {
  padding-top: 25px;
  padding-right: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section-team" id="team">
  <div class="row">
    <h2>team members</h2>
  </div>
  <div class="column-2">
    <img src="img/Picture1.jpg" class="members" alt="members" style="width:50%">
    <h3>Adam</h3>
  </div>
  <div class="column-2">
    <img src="img/Picture2.jpg" class="members" alt="members" style="width:50%">
    <h3>Adam</h3>
  </div>
  <div class="column-2">
    <img src="img/Picture3.jpg" class="members" alt="members" style="width:50%">
    <h3>Adam</h3>
  </div>
  <div class="column-2">
    <img src="img/Picture5.jpg" class="members" alt="members" style="width:50%">
    <h3>Adam</h3>
  </div>
  <div class="column-2">
    <img src="img/Picture4.png" class="members" alt="members" style="width:50%">
    <h3>Adam</h3>
  </div>
  <div class="column-2">
    <img src="img/Picture6.jpg" class="members" alt="members" style="width:50%">
    <h3>Adam</h3>
  </div>
  <div class="column-3">
    <img src="img/upm.jpg" class="upm" alt="upm" style="width:30%">
    <h4>Partnered with UPM</h4>
  </div></code>```

I hope someone can show me how to the make position  of the current photos like the one in the first picture.

答:
The problem is that you're not treating your divs like containers.  ".column-2" and ".column-3" should not be defining by how much space the image takes up, but how much space the thing that holds the image takes up.

To fix this, you need to accommodate the padding with calc() based widths.  If a container has 35px of padding, you need to subtract that from the container's width to make sure that it all adds up to 100% after non-relative measurements are excluded.  Secondly, .column-3 needs to be based on 100% width if it is the only column in the row.

A third suggestion (though not absolutely necessary to make this script work) is to refactor your columns. These classes are not going to be very reusable as they are so to make sure you can use these same classes in other places, you want to do the following:  Most themes have a maximum number of columns supported (usually 12), so you name each column class name based on how many of these 12 columns the element will occupy.  Since you want .column-2 to be 1/3rd of a row, you would name it .column-4, and since you want .column-3 to be a whole row, you would name it .column-12.  You can make additional classes for all of the other divisions as needed.  You should also standardise the behaviors of your columns so they all use the same floats and paddings, and only use the sub-elements to give them their unique properties.

```<code>.column-4 { /* was column-2 */
  float: left;
  box-sizing: border-box; /* includes padding as part of width */
  width: 33.3%;
  display: inline-block;
  padding: 5px;
  padding-right: 30px;
}

.column-12 { /* was column-3 */
  float: left; /* made the same as column-4 for consistency */
  box-sizing: border-box; /* includes padding as part of width */
  width: 100%;
  display: inline-block;
  padding: 5px; /* moved here from upm for consistancy. */
  padding-right: 30px;
}

.upm {
  float: right; /* Added float right here instead of column-12 to make column-12 more reusable. */
  padding-top: 20px; /* subtracted 5px since it inherits 5px from it's container. */
  /* removed padding: 5px; because it should belong to column-12 */
}

/* make sure to update column class names in your HTML to match */
</code>```

ContentLicense: CC BY-SA 4.0

Title: Position of picture changed

Body:
The position of the picture was the same until I changed the pictures.

These are the position of the pictures with the old photos

This is the position with the new photos

.column-2 {
  float: left;
  width: 33.3%;
  padding: 5px;
  padding-right: 30px;
  display: inline-block;
}

.column-3 {
  float: right;
  width: 30%;
  display: inline-block;
  padding-right: 30px;
  padding
}

.section-team {
  text-align: center;
}

.members {
  border-radius: 50%;
}

.upm {
  padding-top: 25px;
  padding-right: 5px;
}

team members

Adam

Adam

Adam

Adam

Adam

Adam

Partnered with UPM

I hope someone can show me how to the make position  of the current photos like the one in the first picture.

Body:
The problem is that you're not treating your divs like containers.  ".column-2" and ".column-3" should not be defining by how much space the image takes up, but how much space the thing that holds the image takes up.

To fix this, you need to accommodate the padding with calc() based widths.  If a container has 35px of padding, you need to subtract that from the container's width to make sure that it all adds up to 100% after non-relative measurements are excluded.  Secondly, .column-3 needs to be based on 100% width if it is the only column in the row.

A third suggestion (though not absolutely necessary to make this script work) is to refactor your columns. These classes are not going to be very reusable as they are so to make sure you can use these same classes in other places, you want to do the following:  Most themes have a maximum number of columns supported (usually 12), so you name each column class name based on how many of these 12 columns the element will occupy.  Since you want .column-2 to be 1/3rd of a row, you would name it .column-4, and since you want .column-3 to be a whole row, you would name it .column-12.  You can make additional classes for all of the other divisions as needed.  You should also standardise the behaviors of your columns so they all use the same floats and paddings, and only use the sub-elements to give them their unique properties.

.column-4 { /* was column-2 */
  float: left;
  box-sizing: border-box; /* includes padding as part of width */
  width: 33.3%;
  display: inline-block;
  padding: 5px;
  padding-right: 30px;
}

.column-12 { /* was column-3 */
  float: left; /* made the same as column-4 for consistency */
  box-sizing: border-box; /* includes padding as part of width */
  width: 100%;
  display: inline-block;
  padding: 5px; /* moved here from upm for consistancy. */
  padding-right: 30px;
}

.upm {
  float: right; /* Added float right here instead of column-12 to make column-12 more reusable. */
  padding-top: 20px; /* subtracted 5px since it inherits 5px from it's container. */
  /* removed padding: 5px; because it should belong to column-12 */
}

/* make sure to update column class names in your HTML to match */


问:
IIS not gzipping large dynamic JSON response
I see other responses from same server getting gzipped. I have a certain URL that is not getting gzipped. I can only think the problem may be the size of the content but I see no setting in IIS 8 that pertains to a size limit.

All static and dynamic and url and http compression is installed and enabled. I can't find any logs that contain any helpful info on why this URL is not getting compressed.

For example, a response that is gzipped from IIS. (See response header Content-Encoding: gzip)

```<code>curl 'http://....../small_json/' -H 'Accept-Encoding: gzip, deflate' -H 'Accept: application/json, text/plain, */*' --compressed -D /tmp/headers.txt -o /dev/null; cat /tmp/headers.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 65382  100 65382    0     0   233k      0 --:--:-- --:--:-- --:--:--  233k
HTTP/1.1 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Content-Encoding: gzip
Content-Language: en
Vary: Accept, Accept-Language, Cookie,Accept-Encoding
Server: Microsoft-IIS/8.5
X-Frame-Options: SAMEORIGIN
Date: Sun, 08 Apr 2018 01:50:54 GMT
Content-Length: 65382
</code>```

Larger JSON response does not have Content-Encoding: gzip:

```<code>curl 'http://....../big_json/'  -H 'Accept-Encoding: gzip, deflate' -H 'Accept: application/json, text/plain, */*' --compressed -D /tmp/headers.txt -o /dev/null; cat /tmp/headers.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 4755k    0 4755k    0     0  1018k      0 --:--:--  0:00:04 --:--:-- 1373k

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Content-Language: en
Vary: Accept, Accept-Language, Cookie
Server: Microsoft-IIS/8.5
X-Frame-Options: SAMEORIGIN
Date: Sun, 08 Apr 2018 01:51:11 GMT
</code>```

I've set compression settings to be very liberal:

FERB info for the compressed response:

FERB info for the non-compressed response:

答:
I don't know if it still rellevant,
But you have to set dynamicCompressionLevel to a high value.
By default is 0.

ContentLicense: CC BY-SA 3.0

Body:
I see other responses from same server getting gzipped. I have a certain URL that is not getting gzipped. I can only think the problem may be the size of the content but I see no setting in IIS 8 that pertains to a size limit.

All static and dynamic and url and http compression is installed and enabled. I can't find any logs that contain any helpful info on why this URL is not getting compressed.

For example, a response that is gzipped from IIS. (See response header Content-Encoding: gzip)

curl 'http://....../small_json/' -H 'Accept-Encoding: gzip, deflate' -H 'Accept: application/json, text/plain, */*' --compressed -D /tmp/headers.txt -o /dev/null; cat /tmp/headers.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 65382  100 65382    0     0   233k      0 --:--:-- --:--:-- --:--:--  233k
HTTP/1.1 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Content-Encoding: gzip
Content-Language: en
Vary: Accept, Accept-Language, Cookie,Accept-Encoding
Server: Microsoft-IIS/8.5
X-Frame-Options: SAMEORIGIN
Date: Sun, 08 Apr 2018 01:50:54 GMT
Content-Length: 65382

Larger JSON response does not have Content-Encoding: gzip:

curl 'http://....../big_json/'  -H 'Accept-Encoding: gzip, deflate' -H 'Accept: application/json, text/plain, */*' --compressed -D /tmp/headers.txt -o /dev/null; cat /tmp/headers.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 4755k    0 4755k    0     0  1018k      0 --:--:--  0:00:04 --:--:-- 1373k

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Content-Language: en
Vary: Accept, Accept-Language, Cookie
Server: Microsoft-IIS/8.5
X-Frame-Options: SAMEORIGIN
Date: Sun, 08 Apr 2018 01:51:11 GMT

I've set compression settings to be very liberal:

FERB info for the compressed response:

FERB info for the non-compressed response:


问:
Replace for loop with if statements by vectorised function in R
I'm having some trouble with a for loop that contains to many conditions and runs for ages (due to the size of the data frame). Hence, I would like to replace it with a vectorised function of the apply family. I have a variable of the format month/year and would like to define a year variable, depending on whether the month is smaller or equal to 10 (October), which would be defined as the very year, or larger than 10, which would be the year + 1 (e.g. 09/2001 = 2001, whereas 12/2001 = 2002). The date variable contains some NAs. Below I give a simplified version of my data frame, including the for-loop that I applied. Any hint for a vectorised function would be appreciated.

Example dataset:

```<code>d <- data.frame("10/2010")
names(d) <- "data"
d$data <- as.character(d$data)
d <- rbind(d, "11/2010","12/2009","08/2008", NA)
</code>```

For-loop:

```<code>d$ano <- NA
for(i in 1:length(d$data)){
  month <- as.numeric(substring(d$data[i],1,2))
  if(!is.na(d$data[i]) & month <=10){
    d$ano[i] <- substring(d$data[i],4,7)
  }
  if(!is.na(d$data[i]) & month >10){
      d$ano[i] <- as.numeric(substring(d$data[i],4,7))+1
  }
}
</code>```

答:
1) Convert it to class yearmon which represents year and month as the year + 0 for Jan, year + 1/12 for Feb, year + 2/12 for Mar and so on.  Then add 2 months, i.e. 2/12, and take the year.

```<code>library(zoo)

transform(d, ano = as.integer(as.yearmon(data, format = "%m/%Y") + 2/12))
</code>```

giving:

```<code>     data  ano
1 10/2010 2010
2 11/2010 2011
3 12/2009 2010
4 08/2008 2008
5    <NA>   NA
</code>```

2) Alternately, this could also be done in base R with POSIXlt noting that in that case we must add offsets 1900 to the year component and 1 to the mon component.  In this case add 1 to the year if mon+1 exceeds 10.

```<code>transform(d, ano = with(as.POSIXlt(paste(data, 1),
  format = "%m/%Y %d"), year + 1900 + (mon + 1 > 10)))
</code>```

3) A different base R solution is to read data using read.table and manipulate the month and year from that:

```<code>transform(d, ano = with(read.table(text = data, sep = "/", fill = TRUE),
  V2 + (V1 > 10)))
</code>```

Body:
I'm having some trouble with a for loop that contains to many conditions and runs for ages (due to the size of the data frame). Hence, I would like to replace it with a vectorised function of the apply family. I have a variable of the format month/year and would like to define a year variable, depending on whether the month is smaller or equal to 10 (October), which would be defined as the very year, or larger than 10, which would be the year + 1 (e.g. 09/2001 = 2001, whereas 12/2001 = 2002). The date variable contains some NAs. Below I give a simplified version of my data frame, including the for-loop that I applied. Any hint for a vectorised function would be appreciated.

Example dataset:

d <- data.frame("10/2010")
names(d) <- "data"
d$data <- as.character(d$data)
d <- rbind(d, "11/2010","12/2009","08/2008", NA)

For-loop:

d$ano <- NA
for(i in 1:length(d$data)){
  month <- as.numeric(substring(d$data[i],1,2))
  if(!is.na(d$data[i]) & month <=10){
    d$ano[i] <- substring(d$data[i],4,7)
  }
  if(!is.na(d$data[i]) & month >10){
      d$ano[i] <- as.numeric(substring(d$data[i],4,7))+1
  }
}

Body:
1) Convert it to class yearmon which represents year and month as the year + 0 for Jan, year + 1/12 for Feb, year + 2/12 for Mar and so on.  Then add 2 months, i.e. 2/12, and take the year.

library(zoo)

transform(d, ano = as.integer(as.yearmon(data, format = "%m/%Y") + 2/12))

giving:

     data  ano
1 10/2010 2010
2 11/2010 2011
3 12/2009 2010
4 08/2008 2008
5    <NA>   NA

2) Alternately, this could also be done in base R with POSIXlt noting that in that case we must add offsets 1900 to the year component and 1 to the mon component.  In this case add 1 to the year if mon+1 exceeds 10.

transform(d, ano = with(as.POSIXlt(paste(data, 1),
  format = "%m/%Y %d"), year + 1900 + (mon + 1 > 10)))

3) A different base R solution is to read data using read.table and manipulate the month and year from that:

transform(d, ano = with(read.table(text = data, sep = "/", fill = TRUE),
  V2 + (V1 > 10)))


问:
PHP/MySQL - Multiple Selects For Query
I'm writing an simple Musicians database that has a search function that will e-mail details of musicians to people when they search for a specific instrument in that database. I have people who play more then one instrument therefore I have 5 tables, instrument, instrument2, instrument3, instrument4, instrument5.

I have a MYSQL query on my e-mail function but I cannot get it to search more then one table.

Here is the code:

```<code>$query = "SELECT * FROM instruments WHERE (instrument, instrument2, instrument3, instrument4, instrument5) = '$search'";
</code>```

Am I being stupid with my syntax or am I going about the wrong way with this.

Many thanks.

答:
Best would be use 2 tables - Musicians and Instruments. Each row in Instruments table has a field 'musician_id', which refers to the corresponding musician. This is called 1-N relation.

Now, when you want to query the database, you do:

```<code>SELECT * FROM musicians m LEFT JOIN instruments i ON (m.id = i.musician_id) WHERE i.name = "Oboe";
</code>```

This JOINS the two tables together, returning to you a row for every instrument a person plays.

Or, if you already know the Musician ID, query only instruments:

```<code>SELECT * FROM instruments WHERE musician_id = 123;
</code>```

Title: PHP/MySQL - Multiple Selects For Query

Body:
I'm writing an simple Musicians database that has a search function that will e-mail details of musicians to people when they search for a specific instrument in that database. I have people who play more then one instrument therefore I have 5 tables, instrument, instrument2, instrument3, instrument4, instrument5.

I have a MYSQL query on my e-mail function but I cannot get it to search more then one table.

Here is the code:

$query = "SELECT * FROM instruments WHERE (instrument, instrument2, instrument3, instrument4, instrument5) = '$search'";

Am I being stupid with my syntax or am I going about the wrong way with this.

Many thanks.

Body:
Best would be use 2 tables - Musicians and Instruments. Each row in Instruments table has a field 'musician_id', which refers to the corresponding musician. This is called 1-N relation.

Now, when you want to query the database, you do:

SELECT * FROM musicians m LEFT JOIN instruments i ON (m.id = i.musician_id) WHERE i.name = "Oboe";

This JOINS the two tables together, returning to you a row for every instrument a person plays.

Or, if you already know the Musician ID, query only instruments:

SELECT * FROM instruments WHERE musician_id = 123;


问:
webdriverIO - Unhandled promise rejection: NoSuchSessionError: invalid session id
I'm learning UI testing with Jasmine & WebdriverIO. I use it with NodeJS.
I have the next test code:

const projectsPage = require('../../lib/pages/projects.page');
const by = require('selenium-webdriver').By;

describe('Projects page', () => {
  it('Search google', async() => {
    await projectsPage.navigateTo();
    driver.getTitle().then(function(title) {
      expect(title).toBe('Google');
    });
    driver.findElement(by.name('q')).sendKeys('test');
  })
});```
</div>
</div>
</p>

<p>When I run it, I receive the error:</p>

```Unhandled promise rejection: NoSuchSessionError: invalid session id
      (Driver info: chromedriver=2.46.628411 (3324f4c8be9ff2f70a05a30ebc72ffb013e1a71e),platform=Mac OS X 10.14.5 x86_64)
```

<p>But the code below performs successfully:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>describe('Projects page', () => {
  it('Search google', async() => {
    await projectsPage.navigateTo();
    driver.getTitle().then(function(title) {
      expect(title).toBe('Google');
    });
    driver.findElement(by.name('q'))
  })
});</code>```

Where I was wrong?

答:
Your test ended before the code really runs, you should wait for each async statements</p>

```<code>const projectsPage = require('../../lib/pages/projects.page');
const by = require('selenium-webdriver').By;

describe('Projects page', () => {
  it('Search google', async() => {
    await projectsPage.navigateTo();
    const title = await driver.getTitle();
    expect(title).toBe('Google');
    const q = await driver.findElement(by.name('q'));
    await q.sendKeys('test');
  })
});
</code>```

Body:
I'm learning UI testing with Jasmine & WebdriverIO. I use it with NodeJS.
I have the next test code:

const projectsPage = require('../../lib/pages/projects.page');
const by = require('selenium-webdriver').By;

describe('Projects page', () => {
  it('Search google', async() => {
    await projectsPage.navigateTo();
    driver.getTitle().then(function(title) {
      expect(title).toBe('Google');
    });
    driver.findElement(by.name('q')).sendKeys('test');
  })
});

When I run it, I receive the error:

Unhandled promise rejection: NoSuchSessionError: invalid session id
      (Driver info: chromedriver=2.46.628411 (3324f4c8be9ff2f70a05a30ebc72ffb013e1a71e),platform=Mac OS X 10.14.5 x86_64)

But the code below performs successfully:

describe('Projects page', () => {
  it('Search google', async() => {
    await projectsPage.navigateTo();
    driver.getTitle().then(function(title) {
      expect(title).toBe('Google');
    });
    driver.findElement(by.name('q'))
  })
});

Where I was wrong?

Body:
Your test ended before the code really runs, you should wait for each async statements

const projectsPage = require('../../lib/pages/projects.page');
const by = require('selenium-webdriver').By;

describe('Projects page', () => {
  it('Search google', async() => {
    await projectsPage.navigateTo();
    const title = await driver.getTitle();
    expect(title).toBe('Google');
    const q = await driver.findElement(by.name('q'));
    await q.sendKeys('test');
  })
});


问:
coercing to Unicode: need string or buffer, NoneType found when rendering in django admin
I have this error since a long time but can't figure it out :

Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found

It happens in admin when I try to add or modify on one of my models (display works fine)

This is the model:

```<code>class PS(models.Model):
    id_ps = models.IntegerField(null=True)
    client = models.ForeignKey(Client, null=True, blank=True)
    nom_du_site = models.CharField(max_length=250)
    rue_livraison = models.TextField(null=True)
    complement_adresse = models.TextField(null=True)
    code_postal_livraison = models.CharField(max_length=50, null=True)
    ville_livraison = models.CharField(max_length=200, null=True)
    pays_livraison = models.CharField(max_length=200, null=True)
    distributeur = models.CharField(max_length=50, null=True)
    tarif = models.CharField(max_length=250, null=True)
    type_tarif = models.CharField(max_length=50, null=True)
    type_installation = models.CharField(max_length=50, null=True)

    def __unicode__(self):
        return self.nom_du_site

    @property
    def pce(self):
        try:
            return PCE.objects.filter(ps=self)[0]
        except IndexError:
            return
    #
    def get_pce(self):
        from pce.models import PCE
        return PCE.objects.filter(ps=self).exclude(frequence='6M')
    #
    def get_pce_6m(self):
        from pce.models import PCE
        return PCE.objects.filter(ps=self,frequence='6M')
</code>```

Any idea what am i doing wrong here?

Traceback:

```<code>    Environment:

    Request Method: GET
    Request URL: http://127.0.0.1:8026/admin/ps/ps/add/
    Django Version: 1.2.5
    Python Version: 2.7.2
    Installed Applications:
    ['django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.sites',
     'django.contrib.messages',
     'django.contrib.admin',
     'easy_thumbnails',
     'django_extensions',
     'contentadmin',
     'south',
     'sentry',
     'sentry.client',
     'indexer',
     'file_uploader',
     'paging',
     'pagination',
     'consommation',
     'ps',
     'pce',
     'profil',
     'analytics',
     'document']
    Installed Middleware:
    ('annoying.middlewares.StaticServe',
     'django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'pagination.middleware.PaginationMiddleware')

    Template error:
    In template /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19
       Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found
       9 :             {% for field in line %}

       10 :                 <div{% if not line.fields|length_is:'1' %} class="field-box{% if not field.is_readonly and field.errors %} errors{% endif %}"{% endif %}>

       11 :                     {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}

       12 :                     {% if field.is_checkbox %}

       13 :                         {{ field.field }}{{ field.label_tag }}

       14 :                     {% else %}

       15 :                         {{ field.label_tag }}

       16 :                         {% if field.is_readonly %}

       17 :                             <p>{{ field.contents }}</p>

       18 :                         {% else %}

       19 :                              {{ field.field }}

       20 :                         {% endif %}

       21 :                     {% endif %}

       22 :                     {% if field.field.field.help_text %}

       23 :                         <p class="help">{{ field.field.field.help_text|safe }}</p>

       24 :                     {% endif %}

       25 :                 </div>

       26 :             {% endfor %}

       27 :         </div>

       28 :     {% endfor %}

       29 : </fieldset>

    Traceback:
    File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
      100.                     response = callback(request, *callback_args, **callback_kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
      288.                 return self.admin_site.admin_view(view)(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
      76.                     response = view_func(request, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
      78.         response = view_func(request, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
      190.             return view(request, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
      21.             return decorator(bound_func)(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
      76.                     response = view_func(request, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
      17.                 return func(self, *args2, **kwargs2)
    File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py" in _commit_on_success
      299.                     res = func(*args, **kw)
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in add_view
      909.         return self.render_change_form(request, context, form_url=form_url, add=True)
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in render_change_form
      692.         ], context, context_instance=context_instance)
    File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render_to_response
      20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
      186.     return t.render(context_instance)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      173.             return self._render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
      167.         return self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
      125.         return compiled_parent._render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
      167.         return self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
      125.         return compiled_parent._render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
      167.         return self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
      62.             result = block.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
      174.                 nodelist.append(node.render(context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
      139.             return self.template.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      173.             return self._render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
      167.         return self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
      174.                 nodelist.append(node.render(context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
      174.                 nodelist.append(node.render(context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
      260.             return self.nodelist_false.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
      260.             return self.nodelist_false.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render
      91.             output = force_unicode(output)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_unicode
      66.                 s = unicode(s)
    File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in __unicode__
      408.         return self.as_widget()
    File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in as_widget
      450.         return widget.render(name, data, attrs=attrs)
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/widgets.py" in render
      247.         output = [self.widget.render(name, value, *args, **kwargs)]
    File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render
      447.         options = self.render_options(choices, [value])
    File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render_options
      464.         for option_value, option_label in chain(self.choices, choices):
    File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in __iter__
      898.                 yield self.choice(obj)
    File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in choice
      904.         return (self.field.prepare_value(obj), self.field.label_from_instance(obj))
    File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in label_from_instance
      955.         return smart_unicode(obj)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in smart_unicode
      39.     return force_unicode(s, encoding, strings_only, errors)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_unicode
      66.                 s = unicode(s)

    Exception Type: TemplateSyntaxError at /admin/ps/ps/add/
    Exception Value: Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found
</code>```

答:
Replace the earlier function with the provided one. The simplest solution is:</p>

```<code>def __unicode__(self):

    return unicode(self.nom_du_site)
</code>```

Body:
I have this error since a long time but can't figure it out :

Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found

It happens in admin when I try to add or modify on one of my models (display works fine)

This is the model:

class PS(models.Model):
    id_ps = models.IntegerField(null=True)
    client = models.ForeignKey(Client, null=True, blank=True)
    nom_du_site = models.CharField(max_length=250)
    rue_livraison = models.TextField(null=True)
    complement_adresse = models.TextField(null=True)
    code_postal_livraison = models.CharField(max_length=50, null=True)
    ville_livraison = models.CharField(max_length=200, null=True)
    pays_livraison = models.CharField(max_length=200, null=True)
    distributeur = models.CharField(max_length=50, null=True)
    tarif = models.CharField(max_length=250, null=True)
    type_tarif = models.CharField(max_length=50, null=True)
    type_installation = models.CharField(max_length=50, null=True)

    def __unicode__(self):
        return self.nom_du_site

    @property
    def pce(self):
        try:
            return PCE.objects.filter(ps=self)[0]
        except IndexError:
            return
    #
    def get_pce(self):
        from pce.models import PCE
        return PCE.objects.filter(ps=self).exclude(frequence='6M')
    #
    def get_pce_6m(self):
        from pce.models import PCE
        return PCE.objects.filter(ps=self,frequence='6M')

Any idea what am i doing wrong here?

Traceback:

    Environment:

    Request Method: GET
    Request URL: http://127.0.0.1:8026/admin/ps/ps/add/
    Django Version: 1.2.5
    Python Version: 2.7.2
    Installed Applications:
    ['django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.sites',
     'django.contrib.messages',
     'django.contrib.admin',
     'easy_thumbnails',
     'django_extensions',
     'contentadmin',
     'south',
     'sentry',
     'sentry.client',
     'indexer',
     'file_uploader',
     'paging',
     'pagination',
     'consommation',
     'ps',
     'pce',
     'profil',
     'analytics',
     'document']
    Installed Middleware:
    ('annoying.middlewares.StaticServe',
     'django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'pagination.middleware.PaginationMiddleware')

    Template error:
    In template /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19
       Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found
       9 :             {% for field in line %}

       10 :

       11 :                     {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}

       12 :                     {% if field.is_checkbox %}

       13 :                         {{ field.field }}{{ field.label_tag }}

       14 :                     {% else %}

       15 :                         {{ field.label_tag }}

       16 :                         {% if field.is_readonly %}

       17 :
{{ field.contents }}

       18 :                         {% else %}

       19 :                              {{ field.field }}

       20 :                         {% endif %}

       21 :                     {% endif %}

       22 :                     {% if field.field.field.help_text %}

       23 :
{{ field.field.field.help_text|safe }}

       24 :                     {% endif %}

       25 :

       26 :             {% endfor %}

       27 :

       28 :     {% endfor %}

       29 : </fieldset>

    Traceback:
    File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
      100.                     response = callback(request, *callback_args, **callback_kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
      288.                 return self.admin_site.admin_view(view)(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
      76.                     response = view_func(request, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
      78.         response = view_func(request, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
      190.             return view(request, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
      21.             return decorator(bound_func)(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
      76.                     response = view_func(request, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
      17.                 return func(self, *args2, **kwargs2)
    File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py" in _commit_on_success
      299.                     res = func(*args, **kw)
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in add_view
      909.         return self.render_change_form(request, context, form_url=form_url, add=True)
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in render_change_form
      692.         ], context, context_instance=context_instance)
    File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render_to_response
      20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
      186.     return t.render(context_instance)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      173.             return self._render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
      167.         return self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
      125.         return compiled_parent._render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
      167.         return self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
      125.         return compiled_parent._render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
      167.         return self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
      62.             result = block.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
      174.                 nodelist.append(node.render(context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
      139.             return self.template.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      173.             return self._render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
      167.         return self.nodelist.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
      174.                 nodelist.append(node.render(context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
      174.                 nodelist.append(node.render(context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
      260.             return self.nodelist_false.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
      260.             return self.nodelist_false.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
      796.                 bits.append(self.render_node(node, context))
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
      72.             result = node.render(context)
    File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render
      91.             output = force_unicode(output)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_unicode
      66.                 s = unicode(s)
    File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in __unicode__
      408.         return self.as_widget()
    File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in as_widget
      450.         return widget.render(name, data, attrs=attrs)
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/widgets.py" in render
      247.         output = [self.widget.render(name, value, *args, **kwargs)]
    File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render
      447.         options = self.render_options(choices, [value])
    File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render_options
      464.         for option_value, option_label in chain(self.choices, choices):
    File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in __iter__
      898.                 yield self.choice(obj)
    File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in choice
      904.         return (self.field.prepare_value(obj), self.field.label_from_instance(obj))
    File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in label_from_instance
      955.         return smart_unicode(obj)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in smart_unicode
      39.     return force_unicode(s, encoding, strings_only, errors)
    File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_unicode
      66.                 s = unicode(s)

    Exception Type: TemplateSyntaxError at /admin/ps/ps/add/
    Exception Value: Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found

Body:
Replace the earlier function with the provided one. The simplest solution is:

def __unicode__(self):

    return unicode(self.nom_du_site)


问:
How can I select only some child nodes from an XML file in C#?
I have an XML file that I want to parse. It is longer than what I shall post here, but only this part interests me in this question:

```<code>       <Team>
        <TeamId>1187457</TeamId>
        <TeamName>Zanardi Redwings</TeamName>
        <Arena>
          <ArenaId>1184019</ArenaId>
          <ArenaName>Evolution</ArenaName>
        </Arena>
        <League>
          <LeagueId>37</LeagueId>
          <LeagueName>România</LeagueName>
        </League>
        <Country>
          <CountryId>36</CountryId>
          <CountryName>România</CountryName>
        </Country>
        <LeagueLevelUnit>
          <LeagueLevelUnitId>4109</LeagueLevelUnitId>
          <LeagueLevelUnitName>V.171</LeagueLevelUnitName>
        </LeagueLevelUnit>
        <Region>
          <RegionId>799</RegionId>
          <RegionName>Prahova</RegionName>
        </Region>
        <YouthTeam>
          <YouthTeamId>2337461</YouthTeamId>
          <YouthTeamName>Little Redwings</YouthTeamName>
          <YouthLeague>
            <YouthLeagueId>436902</YouthLeagueId>
            <YouthLeagueName>Normandie Ligue des jeunes</YouthLeagueName>
          </YouthLeague>
        </YouthTeam>
      </Team>
</code>```

From the part above, I only need to read the data from the TeamId and TeamName child nodes. To achieve this, I wrote the following code:

```<code>Nodes = Node.SelectNodes("Team");
foreach (XmlNode j in Nodes)
  {
    XmlNodeList TeamDetails = j.SelectNodes("*");
    foreach (XmlNode k in TeamDetails)
      {
         switch (k.Name)
           {
             case "TeamName":
               {
                  UserTeamNames[counter] = k.InnerXml;
                  break;
               }
             case "TeamId":
               {
                  if (!int.TryParse(k.InnerXml, out UserTeamIDs[counter]))
                   {
                      ShowErrorMessageBox("Parsing TeamID from XML file failed!"); //A function which sets some parameters for MessageBox.Show() then calls it
                   }
                  break;
                }
            }
       }
   }
</code>```

In the code above, counter is an int variable, which I need in other part of the code.

The code works perfectly, but I want to eliminate the useless looping and testing when the node I am working on is not either TeamName or TeamID.

I suspect the answer I am looking for has something to do with XPath expressions, but I am not sure.

How can I read the data from only the mentioned nodes, without any useless operations?

答:
Here is another option using LINQ to XML.First create your own class that will hold that data you are looking for like this: </p>

```<code>public class TeamInfo
{
    public string TeamName { get; set; }
    public int TeamId { get; set; }
}
</code>```

<p>Then you would parse the xml into a list of objects like this: </p>

```<code>var data =
            "<Team><TeamId>1187457</TeamId><TeamName>Zanardi Redwings</TeamName><Arena><ArenaId>1184019</ArenaId><ArenaName>Evolution</ArenaName></Arena><League><LeagueId>37</LeagueId><LeagueName>România</LeagueName></League><Country><CountryId>36</CountryId><CountryName>România</CountryName></Country><LeagueLevelUnit><LeagueLevelUnitId>4109</LeagueLevelUnitId><LeagueLevelUnitName>V.171</LeagueLevelUnitName></LeagueLevelUnit><Region><RegionId>799</RegionId><RegionName>Prahova</RegionName></Region><YouthTeam><YouthTeamId>2337461</YouthTeamId><YouthTeamName>Little Redwings</YouthTeamName><YouthLeague><YouthLeagueId>436902</YouthLeagueId><YouthLeagueName>Normandie Ligue des jeunes</YouthLeagueName></YouthLeague></YouthTeam></Team>";
        var elm = new XElement("Base",data);
        var decoded = System.Web.HttpUtility.HtmlDecode(elm.ToString());//this is to remove any formatting issues when we call .ToString()

        var doc = XDocument.Parse(decoded);

        var result = doc.Root.Descendants("Team")
            .Select(y => new TeamInfo
            {
                TeamId = Convert.ToInt32(y.Element("TeamId").Value),
                TeamName = y.Element("TeamName").Value
            }).ToList();

    }
</code>```

Body:
I have an XML file that I want to parse. It is longer than what I shall post here, but only this part interests me in this question:

       <Team>
        <TeamId>1187457</TeamId>
        <TeamName>Zanardi Redwings</TeamName>
        <Arena>
          <ArenaId>1184019</ArenaId>
          <ArenaName>Evolution</ArenaName>
        </Arena>
        <League>
          <LeagueId>37</LeagueId>
          <LeagueName>România</LeagueName>
        </League>
        <Country>
          <CountryId>36</CountryId>
          <CountryName>România</CountryName>
        </Country>
        <LeagueLevelUnit>
          <LeagueLevelUnitId>4109</LeagueLevelUnitId>
          <LeagueLevelUnitName>V.171</LeagueLevelUnitName>
        </LeagueLevelUnit>
        <Region>
          <RegionId>799</RegionId>
          <RegionName>Prahova</RegionName>
        </Region>
        <YouthTeam>
          <YouthTeamId>2337461</YouthTeamId>
          <YouthTeamName>Little Redwings</YouthTeamName>
          <YouthLeague>
            <YouthLeagueId>436902</YouthLeagueId>
            <YouthLeagueName>Normandie Ligue des jeunes</YouthLeagueName>
          </YouthLeague>
        </YouthTeam>
      </Team>

From the part above, I only need to read the data from the TeamId and TeamName child nodes. To achieve this, I wrote the following code:

Nodes = Node.SelectNodes("Team");
foreach (XmlNode j in Nodes)
  {
    XmlNodeList TeamDetails = j.SelectNodes("*");
    foreach (XmlNode k in TeamDetails)
      {
         switch (k.Name)
           {
             case "TeamName":
               {
                  UserTeamNames[counter] = k.InnerXml;
                  break;
               }
             case "TeamId":
               {
                  if (!int.TryParse(k.InnerXml, out UserTeamIDs[counter]))
                   {
                      ShowErrorMessageBox("Parsing TeamID from XML file failed!"); //A function which sets some parameters for MessageBox.Show() then calls it
                   }
                  break;
                }
            }
       }
   }

In the code above, counter is an int variable, which I need in other part of the code.

The code works perfectly, but I want to eliminate the useless looping and testing when the node I am working on is not either TeamName or TeamID.

I suspect the answer I am looking for has something to do with XPath expressions, but I am not sure.

How can I read the data from only the mentioned nodes, without any useless operations?

Body:
Here is another option using LINQ to XML.First create your own class that will hold that data you are looking for like this:

public class TeamInfo
{
    public string TeamName { get; set; }
    public int TeamId { get; set; }
}

Then you would parse the xml into a list of objects like this:

var data =
            "<Team><TeamId>1187457</TeamId><TeamName>Zanardi Redwings</TeamName><Arena><ArenaId>1184019</ArenaId><ArenaName>Evolution</ArenaName></Arena><League><LeagueId>37</LeagueId><LeagueName>România</LeagueName></League><Country><CountryId>36</CountryId><CountryName>România</CountryName></Country><LeagueLevelUnit><LeagueLevelUnitId>4109</LeagueLevelUnitId><LeagueLevelUnitName>V.171</LeagueLevelUnitName></LeagueLevelUnit><Region><RegionId>799</RegionId><RegionName>Prahova</RegionName></Region><YouthTeam><YouthTeamId>2337461</YouthTeamId><YouthTeamName>Little Redwings</YouthTeamName><YouthLeague><YouthLeagueId>436902</YouthLeagueId><YouthLeagueName>Normandie Ligue des jeunes</YouthLeagueName></YouthLeague></YouthTeam></Team>";
        var elm = new XElement("Base",data);
        var decoded = System.Web.HttpUtility.HtmlDecode(elm.ToString());//this is to remove any formatting issues when we call .ToString()

        var doc = XDocument.Parse(decoded);

        var result = doc.Root.Descendants("Team")
            .Select(y => new TeamInfo
            {
                TeamId = Convert.ToInt32(y.Element("TeamId").Value),
                TeamName = y.Element("TeamName").Value
            }).ToList();

    }


问:
Selecting from a database from Today onwards
Im trying to select a bunch of stuff from a database. Each have a date and i'd like to only display the ones whose date is equal to today onwards.

$sql="SELECT * FROM bs_events WHERE NOW() ORDER BY eventDate ";

I have tried looking everywhere and cannot find anything.

Thanks for any help guys

答:
```<code>$sql = "SELECT * FROM bs_events WHERE eventDate >= CURDATE() ORDER BY eventDate";
</code>```


问:
Number not Printing in python when returning amount
I have some code which reads from a text file and is meant to print max and min altitudes but the min altitude is not printing and there is no errors.

```<code>altitude = open("Altitude.txt","r")

read = altitude.readlines()

count = 0

for line in read:
    count += 1

count = count - 1
print("Number of Different Altitudes: ",count)

def maxAlt(read):
    maxA = (max(read))
    return maxA

def minAlt(read):
    minA = (min(read))
    return minA

print()
print("Max Altitude:",maxAlt(read))
print("Min Altitude:",minAlt(read))
altitude.close()
</code>```

I will include the Altitude text file if it is needed and once again the minimum altitude is not printing

答:
I'm assuming, your file probably contains numbers & line-breaks (\n)

You are reading it here:

```<code>read = altitude.readlines()
</code>```

At this point read is a list of strings.

Now, when you do:

```<code>minA = (min(read))
</code>```

It's trying to get "the smallest string in read"

The smallest string is usually the empty string "" - which most probably exists at the end of your file.

So your minAlt is actually getting printed. But it happens to be the empty string.

You can fix it by parsing the lines you read into numbers.

```<code>read = [float(a) for a in altitude.readlines() if a]
</code>```

Body:
I have some code which reads from a text file and is meant to print max and min altitudes but the min altitude is not printing and there is no errors.

altitude = open("Altitude.txt","r")

read = altitude.readlines()

count = 0

for line in read:
    count += 1

count = count - 1
print("Number of Different Altitudes: ",count)

def maxAlt(read):
    maxA = (max(read))
    return maxA

def minAlt(read):
    minA = (min(read))
    return minA

print()
print("Max Altitude:",maxAlt(read))
print("Min Altitude:",minAlt(read))
altitude.close()

I will include the Altitude text file if it is needed and once again the minimum altitude is not printing

Body:
I'm assuming, your file probably contains numbers & line-breaks (\n)

You are reading it here:

read = altitude.readlines()

At this point read is a list of strings.

Now, when you do:

minA = (min(read))

It's trying to get "the smallest string in read"

The smallest string is usually the empty string "" - which most probably exists at the end of your file.

So your minAlt is actually getting printed. But it happens to be the empty string.

You can fix it by parsing the lines you read into numbers.

read = [float(a) for a in altitude.readlines() if a]


问:
How to determine when Fragment becomes visible in ViewPager
Problem: Fragment onResume() in ViewPager is fired before the fragment becomes actually visible.

For example, I have 2 fragments with ViewPager and FragmentPagerAdapter. The second fragment is only available for authorized users and I need to ask the user to log in when the fragment becomes visible (using an alert dialog).

BUT the ViewPager creates the second fragment when the first is visible in order to cache the second fragment and makes it visible when the user starts swiping.

So the onResume() event is fired in the second fragment long before it becomes visible. That's why I'm trying to find an event which fires when the second fragment becomes visible to show a dialog at the appropriate moment.

How can this be done?

答:
A simple way of implementing that is checking whether user is logged in before going to the fragment.

In your MainActivity you may do something like this inside the onNavigationItemSelected method.

```<code> case R.id.nav_profile_side:

                if (User_is_logged_in) {

                    fragmentManager.beginTransaction()
                            .replace(R.id.content_frame
                                    , new FragmentProfile())
                            .commit();
                }else {

                    ShowLoginOrRegisterDialog(fragmentManager);

                }

                break;
</code>```

However, if you are using navigation drawer, the selection in the drawer will have changed to Profile though we have not gone to the ProfileFragment.

To reset the selection to the current selection run the code below

```<code>        navigationView.getMenu().getItem(0).setChecked(true);
</code>```

Body:
A simple way of implementing that is checking whether user is logged in before going to the fragment.

In your MainActivity you may do something like this inside the onNavigationItemSelected method.

 case R.id.nav_profile_side:

                if (User_is_logged_in) {

                    fragmentManager.beginTransaction()
                            .replace(R.id.content_frame
                                    , new FragmentProfile())
                            .commit();
                }else {

                    ShowLoginOrRegisterDialog(fragmentManager);

                }

                break;

However, if you are using navigation drawer, the selection in the drawer will have changed to Profile though we have not gone to the ProfileFragment.

To reset the selection to the current selection run the code below

        navigationView.getMenu().getItem(0).setChecked(true);


问:
Query to show label values in Grafana (using prometheus)
I've a metric in below format:

```<code>code_smells_count{BLOCKER="176",CRITICAL="52",MAJOR="3784",instance="localhost:8080",job="my-metrics",domainId="65",domain="Sales",product="EmployeeSales",project_key="employee-sales"} 5000
</code>```

I'm trying to write a query that will only display the value of BLOCKER in a gauge.

I tried:

```<code>sum(code_smells_count{product="[[product]]"})by (BLOCKER)
</code>```

But this doesn't work, as it returns value of code_smells_count{product="[[product]]", whereas I want only BLOCKER="176"

Any suggestions?

Thank you

答:
In Grafana, you can display the value of a tag with:

visualization: single stat

query: format should be table

visualization: should then display a drop-down menu of the tag to show (the name by default)

Body:
I've a metric in below format:

code_smells_count{BLOCKER="176",CRITICAL="52",MAJOR="3784",instance="localhost:8080",job="my-metrics",domainId="65",domain="Sales",product="EmployeeSales",project_key="employee-sales"} 5000

I'm trying to write a query that will only display the value of BLOCKER in a gauge.

I tried:

sum(code_smells_count{product="[[product]]"})by (BLOCKER)

But this doesn't work, as it returns value of code_smells_count{product="[[product]]", whereas I want only BLOCKER="176"

Any suggestions?

Thank you


问:
implement time delay in c
I don't know exactly how to word a search for this.. so I haven't had any luck finding anything.. :S

I need to implement a time delay in C.

for example I want to do some stuff, then wait say 1 minute, then continue on doing stuff.

Did that make sense? Can anyone help me out?

答:
// Provides ANSI C method of delaying x milliseconds</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void delayMillis(unsigned long ms) {
    clock_t start_ticks = clock();
    unsigned long millis_ticks = CLOCKS_PER_SEC/1000;
    while (clock()-start_ticks < ms*millis_ticks) {
    }
}

/*
 * Example output:
 *
 * CLOCKS_PER_SEC:[1000000]
 *
 * Test Delay of 800 ms....
 *
 * start[2054], end[802058],
 * elapsedSec:[0.802058]
 */
int testDelayMillis() {

    printf("CLOCKS_PER_SEC:[%lu]\n\n", CLOCKS_PER_SEC);
    clock_t start_t, end_t;
    start_t = clock();
    printf("Test Delay of 800 ms....\n", CLOCKS_PER_SEC);
    delayMillis(800);
    end_t = clock();
    double elapsedSec = end_t/(double)CLOCKS_PER_SEC;
    printf("\nstart[%lu], end[%lu], \nelapsedSec:[%f]\n", start_t, end_t, elapsedSec);

}

int main() {
    testDelayMillis();
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: implement time delay in c

Body:
// Provides ANSI C method of delaying x milliseconds

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void delayMillis(unsigned long ms) {
    clock_t start_ticks = clock();
    unsigned long millis_ticks = CLOCKS_PER_SEC/1000;
    while (clock()-start_ticks < ms*millis_ticks) {
    }
}

/*
 * Example output:
 *
 * CLOCKS_PER_SEC:[1000000]
 *
 * Test Delay of 800 ms....
 *
 * start[2054], end[802058],
 * elapsedSec:[0.802058]
 */
int testDelayMillis() {

    printf("CLOCKS_PER_SEC:[%lu]\n\n", CLOCKS_PER_SEC);
    clock_t start_t, end_t;
    start_t = clock();
    printf("Test Delay of 800 ms....\n", CLOCKS_PER_SEC);
    delayMillis(800);
    end_t = clock();
    double elapsedSec = end_t/(double)CLOCKS_PER_SEC;
    printf("\nstart[%lu], end[%lu], \nelapsedSec:[%f]\n", start_t, end_t, elapsedSec);

}

int main() {
    testDelayMillis();
}


答:
Try below solution</p>

```<code>altitudeFile = open("Altitude.txt","r")

Altitudes = [float(line) for line in altitudeFile if line] #get file data into list.

Max_Altitude = max(Altitudes)
Min_Altitude = min(Altitudes)

altitudeFile.close()
</code>```

Title: Number not Printing in python when returning amount

Body:
Try below solution

altitudeFile = open("Altitude.txt","r")

Altitudes = [float(line) for line in altitudeFile if line] #get file data into list.

Max_Altitude = max(Altitudes)
Min_Altitude = min(Altitudes)

altitudeFile.close()


问:
count unique cases that fall within overlapping posixct ymd hms intervals by the second
have a posixct start time and end time and am trying to count the unique cases of items that have overlapping times by the second

cant change the posixct ymd hms using lubridate or it changes the hms to an odd time. the data was in mm:ss originally as a character. I added 00: to the beginning using strings manipulation but cant get into proper hh:mm:ss for a dplyr or loop that works

```<code>`head(Fish_20180424_001_New) #my data table

      Survey ID          Clip ID                 Species         Enter Frame          Exit Frame
1: 20180424 001 20180424 001 001 Catostomus occidentalis 2019-05-23 00:01:03 2019-05-23 00:01:08
2: 20180424 001 20180424 001 001   Ptychocheilus grandis 2019-05-23 00:01:16 2019-05-23 00:01:18
3: 20180424 001 20180424 001 001 Catostomus occidentalis 2019-05-23 00:01:48 2019-05-23 00:01:52
4: 20180424 001 20180424 001 001 Catostomus occidentalis 2019-05-23 00:02:04 2019-05-23 00:02:06
5: 20180424 001 20180424 001 001                   Unkn. 2019-05-23 00:02:06 2019-05-23 00:02:08
6: 20180424 001 20180424 001 001   Ptychocheilus grandis 2019-05-23 00:02:07 2019-05-23 00:02:11

setkey(Fish_20180424_001_New, Species, `Enter Frame`, `Exit Frame`)
vecTime <- seq(from=Fish_20180424_001_New$`Enter Frame`[1],to=Fish_20180424_001_New$`Exit Frame`[nrow(Fish_20180424_001_New)],by=1)
res <- data.frame(time=vecTime)

for(i in 1:length(unique(Fish_20180424_001_New$Species)) ) {
addz <- array(0,length(vecTime))
remz <- array(0,length(vecTime))

Fish_20180424_001_New_Final <- Fish_20180424_001_New[J(unique(Fish_20180424_001_New$Species)[i]),] # Subset a certain species

startAgg <- aggregate(Fish_20180424_001_New_Final$`Enter Frame`,by=list(Fish_20180424_001_New_Final$`Enter Frame`),length)
endAgg <- aggregate(Fish_20180424_001_New_Final$`Exit Frame`,by=list(Fish_20180424_001_New_Final$`Exit Frame`),length)
addz[which(vecTime %in% startAgg$Group.1 )] <- startAgg$x
remz[which(vecTime %in% endAgg$Group.1)] <- -endAgg$x

res[,c( unique(Fish_20180424_001_New$Species)[i] )] <- cumsum(addz + remz)
</code>```

}

```<code>res2<-res%>%filter(time < "2019-05-23 00:20:01")

max(res2$`Catostomus occidentalis`)
max(res2$`Micropterus sp`)
max(res2$`Micropeterus salmoides`)
max(res2$`Morone saxatilis`)
max(res2$`Ptychocheilus grandis`)
max(res2$Unidentified)
max(res2$Unkn.)
</code>```

the vecTime only has a length of 66 and seems to start at the right spot (00:01:03) but ends early where the first start time overlaps an end time (02:06)

need to get the appropriate sequence which should end at the length of the last entry in the end time which is 00:51:27

答:
by changing the second portion of the vecTime argument (to=) to max(exit frame), I was able to achieve the appropriate answer and eliminate issues where start and stop times overlap.

still open to exploring other answers, if anyone feels like posting additional thoughts

Body:
have a posixct start time and end time and am trying to count the unique cases of items that have overlapping times by the second

cant change the posixct ymd hms using lubridate or it changes the hms to an odd time. the data was in mm:ss originally as a character. I added 00: to the beginning using strings manipulation but cant get into proper hh:mm:ss for a dplyr or loop that works

`head(Fish_20180424_001_New) #my data table

      Survey ID          Clip ID                 Species         Enter Frame          Exit Frame
1: 20180424 001 20180424 001 001 Catostomus occidentalis 2019-05-23 00:01:03 2019-05-23 00:01:08
2: 20180424 001 20180424 001 001   Ptychocheilus grandis 2019-05-23 00:01:16 2019-05-23 00:01:18
3: 20180424 001 20180424 001 001 Catostomus occidentalis 2019-05-23 00:01:48 2019-05-23 00:01:52
4: 20180424 001 20180424 001 001 Catostomus occidentalis 2019-05-23 00:02:04 2019-05-23 00:02:06
5: 20180424 001 20180424 001 001                   Unkn. 2019-05-23 00:02:06 2019-05-23 00:02:08
6: 20180424 001 20180424 001 001   Ptychocheilus grandis 2019-05-23 00:02:07 2019-05-23 00:02:11

setkey(Fish_20180424_001_New, Species, `Enter Frame`, `Exit Frame`)
vecTime <- seq(from=Fish_20180424_001_New$`Enter Frame`[1],to=Fish_20180424_001_New$`Exit Frame`[nrow(Fish_20180424_001_New)],by=1)
res <- data.frame(time=vecTime)

for(i in 1:length(unique(Fish_20180424_001_New$Species)) ) {
addz <- array(0,length(vecTime))
remz <- array(0,length(vecTime))

Fish_20180424_001_New_Final <- Fish_20180424_001_New[J(unique(Fish_20180424_001_New$Species)[i]),] # Subset a certain species

startAgg <- aggregate(Fish_20180424_001_New_Final$`Enter Frame`,by=list(Fish_20180424_001_New_Final$`Enter Frame`),length)
endAgg <- aggregate(Fish_20180424_001_New_Final$`Exit Frame`,by=list(Fish_20180424_001_New_Final$`Exit Frame`),length)
addz[which(vecTime %in% startAgg$Group.1 )] <- startAgg$x
remz[which(vecTime %in% endAgg$Group.1)] <- -endAgg$x

res[,c( unique(Fish_20180424_001_New$Species)[i] )] <- cumsum(addz + remz)

}

res2<-res%>%filter(time < "2019-05-23 00:20:01")

max(res2$`Catostomus occidentalis`)
max(res2$`Micropterus sp`)
max(res2$`Micropeterus salmoides`)
max(res2$`Morone saxatilis`)
max(res2$`Ptychocheilus grandis`)
max(res2$Unidentified)
max(res2$Unkn.)

the vecTime only has a length of 66 and seems to start at the right spot (00:01:03) but ends early where the first start time overlaps an end time (02:06)

need to get the appropriate sequence which should end at the length of the last entry in the end time which is 00:51:27


问:
How to split training data and testing data by account(one variable)
I'm trying to fit logistic regression. I want to split training and testing data by account (a variable that doesn't play a role into fitting). I want them to be split by account, and each account can have lots of variables. For example, 80% of the account will be training, 20% account will be testing.

I've tried the following, but this code just give me 80% training and 20% testing randomly. Then in training data, it will give me some account, but in testing data, it will also give me that exactly account just with different variables. That's not what I want.

X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.20,random_state=0)

Please advise. Thank you!

答:
What about this

```<code>import numpy as np

def group_train_test_split(X, y, test_size, random_state, stratify):
    X = X.copy()
    X['_target'] = y

    X = X.set_index(stratify)
    index = X.index

    index_values = index.unique().values
    np.random.seed(random_state)
    np.random.shuffle(index_values)

    cut = np.round(index_values.shape[0] * test_size).astype('<i4')

    X_test, X_train = X.loc[index_values[:cut]], X.loc[index_values[cut:]]

    return X_test['_target'], X_train['_target'], X_test.drop('_target', axis=1), X_train.drop('_target', axis=1)

y_test, y_train, X_test, X_train = group_train_test_split(X=X, y=y, test_size=0.2, random_state=41, stratify='account')
</code>```

This way it will take 20% of the accounts into test data, while the rest will be in the training data.

Body:
What about this

import numpy as np

def group_train_test_split(X, y, test_size, random_state, stratify):
    X = X.copy()
    X['_target'] = y

    X = X.set_index(stratify)
    index = X.index

    index_values = index.unique().values
    np.random.seed(random_state)
    np.random.shuffle(index_values)

    cut = np.round(index_values.shape[0] * test_size).astype('<i4')

    X_test, X_train = X.loc[index_values[:cut]], X.loc[index_values[cut:]]

    return X_test['_target'], X_train['_target'], X_test.drop('_target', axis=1), X_train.drop('_target', axis=1)

y_test, y_train, X_test, X_train = group_train_test_split(X=X, y=y, test_size=0.2, random_state=41, stratify='account')

This way it will take 20% of the accounts into test data, while the rest will be in the training data.


问:
Trouble with SimpleXMLElement Namespaces
I'm having trouble parsing XML with Namespaces using SimpleXMLElement.

I've tried using looping through the xml and also tried using xpath without success.

$data_url="http://isni.oclc.nl/sru/0000000123121970?query=pica.isn+%3D+%220000000123121970%22&version=1.1&operation=searchRetrieve&stylesheet=http%3A%2F%2Fisni.oclc.nl%2Fsru%2FDB%3D1.2%2F%3Fxsl%3DsearchRetrieveResponse&recordSchema=isni-b&maximumRecords=10&startRecord=1&recordPacking=xml&sortKeys=none&x-info-5-mg-requestGroupings=none";
$data = file_get_contents($data_url);
$xml = simplexml_load_string($data);

$org_names = $xml->children('srw', true)->records->children('srw', true)->record->children('srw', true)->recordData->responseRecord->isniassigned->isnimetadata->identity->organisation->organisationnamevariant->mainname;

foreach($org_names as $a)
{
  echo "a: $a\n";
}
```

<p>I'm expecting to get a list of organisationnamevariant->mainname items:</p>

```Academia lugduno-batava
Leiden university
Leidse universiteit
etc.
```

However, I'm getting this error: Trying to get property of non-object

答:
Having such a deep hierarchy is difficult to navigate using the normal -> structure, but you also have to be careful when changing namespace.  You only need to do the ->children('srw', true) once and then all of the child nodes will be for that namespace.  BUT you also have to switch back at <responseRecord> by using ->children().

You also need to be careful that you use the proper case for each tag name...

```<code>$org_names = $xml->children('srw', true)->records->record->recordData->children()->
       responseRecord->ISNIAssigned->ISNIMetadata->identity->organisation->
       organisationNameVariant->mainName;

echo (string)$org_names;
</code>```

An alternative is to use XPath (as xpath() returns a list of matches, I use [0] to only use the first one)...

```<code>$org_names = $xml->xpath("//organisationNameVariant/mainName");

echo (string)$org_names[0];
</code>```

I know that echo casts the value to a string, but if you use this in any other scenario, you may end up with a SimpleXMLElement instead, so I tend to add the case to string in just to make the point.

Body:
I'm having trouble parsing XML with Namespaces using SimpleXMLElement.

I've tried using looping through the xml and also tried using xpath without success.

$data_url="http://isni.oclc.nl/sru/0000000123121970?query=pica.isn+%3D+%220000000123121970%22&version=1.1&operation=searchRetrieve&stylesheet=http%3A%2F%2Fisni.oclc.nl%2Fsru%2FDB%3D1.2%2F%3Fxsl%3DsearchRetrieveResponse&recordSchema=isni-b&maximumRecords=10&startRecord=1&recordPacking=xml&sortKeys=none&x-info-5-mg-requestGroupings=none";
$data = file_get_contents($data_url);
$xml = simplexml_load_string($data);

$org_names = $xml->children('srw', true)->records->children('srw', true)->record->children('srw', true)->recordData->responseRecord->isniassigned->isnimetadata->identity->organisation->organisationnamevariant->mainname;

foreach($org_names as $a)
{
  echo "a: $a\n";
}

I'm expecting to get a list of organisationnamevariant->mainname items:

Academia lugduno-batava
Leiden university
Leidse universiteit
etc.

However, I'm getting this error: Trying to get property of non-object

Body:
Having such a deep hierarchy is difficult to navigate using the normal -> structure, but you also have to be careful when changing namespace.  You only need to do the ->children('srw', true) once and then all of the child nodes will be for that namespace.  BUT you also have to switch back at <responseRecord> by using ->children().

You also need to be careful that you use the proper case for each tag name...

$org_names = $xml->children('srw', true)->records->record->recordData->children()->
       responseRecord->ISNIAssigned->ISNIMetadata->identity->organisation->
       organisationNameVariant->mainName;

echo (string)$org_names;

An alternative is to use XPath (as xpath() returns a list of matches, I use [0] to only use the first one)...

$org_names = $xml->xpath("//organisationNameVariant/mainName");

echo (string)$org_names[0];

I know that echo casts the value to a string, but if you use this in any other scenario, you may end up with a SimpleXMLElement instead, so I tend to add the case to string in just to make the point.


问:
Django DRF Token Authentication
I'm having issues with DRF's token based authentication. Following is my landing page code (after login):

```<code>@api_view(['GET','POST'],)
def landing(request):
    this_tenant=request.user.tenant
    end=date_first.date.today()
    start=end-date_first.timedelta(days=30)
    sales_daily=sales_day_wise(start, end, this_tenant)
    invoice_value=sales_raised_value(start, end, this_tenant)
    payment_value=sales_collected_value(start, end, this_tenant)
    return render(request,'landing.html', {'sales_daily':json.dumps(sales_daily, cls=DjangoJSONEncoder),\
        'invoice_value':json.dumps(invoice_value, cls=DjangoJSONEncoder), \
        'payment_value':json.dumps(payment_value, cls=DjangoJSONEncoder)})
</code>```

I was using Django's built-in login view to authenticate and log in a user, then I revised to consider putting token in the header. But that is also not working

This is my login code:

```<code>#Redirect authenticated users to landing page
def custom_login(request):
    if request.user.is_authenticated():
        token, created = Token.objects.get_or_create(user=request.user)
        request.session['AUTHORIZATION'] = "TOKEN "+token.key
        return redirect(landing)
    else:
        return login(request)
</code>```

Following is my DRF settings:

```<code>REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}
</code>```

Issue is, when I'm logging in and going to the landing page via browser, DRF is not working and I'm getting the following error:

```<code>{"detail":"Authentication credentials were not provided."}
</code>```

The reason is the custom DRF header (AUTHENTICATION = TOEKN XXXXXXXXXX) is not present in the request.

However, if I use Postman and put in the custom header (AUTHENTICATION = TOKEN XXXXXXXXXXXX), then it works.

How do I solve it?

Would this mean I would need a custom header for every view?

And on using DRF Token, does it open up CSRF vulnerability (this question: Django DRF - How to do CSRF validation with token authentication )?

Thanks a lot!!

答:
How do I solve it? Would this mean I would need a custom header for every view?
TokenAuthentication is used for Single Page App and the token in Request Header needs to be provided by API client(Postman, Javascript or any other client) on each request. In your case, if you want to use Django views you should activate SessionAuthentication. TokenAuthentication and SessionAuthentication can co-exist.
One way is to save the token in the cookie in your in custom login view and read it by javascript client.

On using DRF Token, does it open up CSRF vulnerability (this question: Django DRF - How to do CSRF validation with token authentication )?
Yes. But there are ways to secure the requests.
According to DRF documentation
"If you use token authentication in production you must ensure that your API is only available over https".
Also, make sure set ALLOWED_HOSTS in settings to the domains that you want Django to respond to so the server does not respond to requests with other origins. There other more secure Auths can be used beside TokenAuthentication like JWT that has been mentioned above.

Title: Django DRF Token Authentication

Body:
I'm having issues with DRF's token based authentication. Following is my landing page code (after login):

@api_view(['GET','POST'],)
def landing(request):
    this_tenant=request.user.tenant
    end=date_first.date.today()
    start=end-date_first.timedelta(days=30)
    sales_daily=sales_day_wise(start, end, this_tenant)
    invoice_value=sales_raised_value(start, end, this_tenant)
    payment_value=sales_collected_value(start, end, this_tenant)
    return render(request,'landing.html', {'sales_daily':json.dumps(sales_daily, cls=DjangoJSONEncoder),\
        'invoice_value':json.dumps(invoice_value, cls=DjangoJSONEncoder), \
        'payment_value':json.dumps(payment_value, cls=DjangoJSONEncoder)})

I was using Django's built-in login view to authenticate and log in a user, then I revised to consider putting token in the header. But that is also not working

This is my login code:

#Redirect authenticated users to landing page
def custom_login(request):
    if request.user.is_authenticated():
        token, created = Token.objects.get_or_create(user=request.user)
        request.session['AUTHORIZATION'] = "TOKEN "+token.key
        return redirect(landing)
    else:
        return login(request)

Following is my DRF settings:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

Issue is, when I'm logging in and going to the landing page via browser, DRF is not working and I'm getting the following error:

{"detail":"Authentication credentials were not provided."}

The reason is the custom DRF header (AUTHENTICATION = TOEKN XXXXXXXXXX) is not present in the request.

However, if I use Postman and put in the custom header (AUTHENTICATION = TOKEN XXXXXXXXXXXX), then it works.

How do I solve it?

Would this mean I would need a custom header for every view?

And on using DRF Token, does it open up CSRF vulnerability (this question: Django DRF - How to do CSRF validation with token authentication )?

Thanks a lot!!


问:
How do I change the color of the PaneToggleButton in a UWP NavigationView?
I am trying to change color of the hamburger button in a NavigationView. I can change the colors of the NavigationViewItems and the Buttons, but the code below does not change the PaneToggleButton.

```<code><Page.Resources>
        <Style TargetType="controls:NavigationViewItem">
            <Setter Property="Foreground" Value="White"/>
        </Style>
        <Style TargetType="Button">
            <Setter Property="Foreground" Value="White"/>
        </Style>
 </Page.Resources>
</code>```

Revised code below fixed the issue

```<code> <controls:NavigationView.Resources>
     <SolidColorBrush x:Key="NavigationViewItemForeground" Color="White"/>
     <SolidColorBrush x:Key="NavigationViewItemForegroundPointerOver"Color="Yellow"/>
     <SolidColorBrush x:Key="NavigationViewItemForegroundPressed"Color="LightGreen"/>
     <SolidColorBrush x:Key="NavigationViewItemForegroundSelected"Color="White"/>
     <SolidColorBrush x:Key="NavigationViewItemForegroundSelectedPointerOver" Color="Orange"/>
     <SolidColorBrush x:Key="NavigationViewItemForegroundSelectedPressed" Color="Pink"/>
 </controls:NavigationView.Resources>

 <controls:NavigationView.PaneToggleButtonStyle>
     <Style TargetType="Button" BasedOn="{StaticResource PaneToggleButtonStyle}">
          <Setter Property="Foreground" Value="White"/>
      </Style>
  </controls:NavigationView.PaneToggleButtonStyle>
</code>```

答:
This worked for me</p>

```<code><Page.Resources>
    <Style x:Key="CustomNavigationMenuStyle" TargetType="Button" BasedOn="{StaticResource PaneToggleButtonStyle}">
        <Setter Property="Foreground" Value="#C21334" />
    </Style>
</Page.Resources>

 <NavigationView x:Name="nvMainLevelNavigation"
                PaneDisplayMode="LeftMinimal"
                IsSettingsVisible="false"
                Header="Title"
                PaneToggleButtonStyle="{StaticResource CustomNavigationIconStyle}"
                ItemInvoked="nvMainLevelNavigation_ItemInvoked"
                SelectionChanged="nvMainLevelNavigation_SelectionChanged"
                Loaded="nvMainLevelNavigation_Loaded">
 </NavigationView>
</code>```

Body:
I am trying to change color of the hamburger button in a NavigationView. I can change the colors of the NavigationViewItems and the Buttons, but the code below does not change the PaneToggleButton.

<Page.Resources>

 </Page.Resources>

Revised code below fixed the issue

 <controls:NavigationView.Resources>
     <SolidColorBrush x:Key="NavigationViewItemForeground" Color="White"/>
     <SolidColorBrush x:Key="NavigationViewItemForegroundPointerOver"Color="Yellow"/>
     <SolidColorBrush x:Key="NavigationViewItemForegroundPressed"Color="LightGreen"/>
     <SolidColorBrush x:Key="NavigationViewItemForegroundSelected"Color="White"/>
     <SolidColorBrush x:Key="NavigationViewItemForegroundSelectedPointerOver" Color="Orange"/>
     <SolidColorBrush x:Key="NavigationViewItemForegroundSelectedPressed" Color="Pink"/>
 </controls:NavigationView.Resources>

 <controls:NavigationView.PaneToggleButtonStyle>

  </controls:NavigationView.PaneToggleButtonStyle>

Body:
This worked for me

<Page.Resources>
    <Style x:Key="CustomNavigationMenuStyle" TargetType="Button" BasedOn="{StaticResource PaneToggleButtonStyle}">
        <Setter Property="Foreground" Value="#C21334" />
    </Style>
</Page.Resources>

 <NavigationView x:Name="nvMainLevelNavigation"
                PaneDisplayMode="LeftMinimal"
                IsSettingsVisible="false"
                Header="Title"
                PaneToggleButtonStyle="{StaticResource CustomNavigationIconStyle}"
                ItemInvoked="nvMainLevelNavigation_ItemInvoked"
                SelectionChanged="nvMainLevelNavigation_SelectionChanged"
                Loaded="nvMainLevelNavigation_Loaded">
 </NavigationView>


问:
Pandas Merge and filter
I used merge to create a dataframe between 2 of my query's.
Now in the dataframe I want to put a filter on a column but I cannot get it to work. I am trying to add filter component date is null or blank.

```<code>    ##reading data from sql
    package = pd.read_sql(sql,con)
    component = pd.read_sql(sqla,con)

    ##doing the left join
    test2 = pd.merge(package,component, on = ['identifier','date'], how='left')

    ##shrinking the dataframe
    test3 = test2[['identifier_x']].copy()
</code>```

i've tried doing the below but cannot get it to work. Getting date_y not defined. I also tried with just date, as when I merge my dataframes the like columns get labelled x and y.

```<code> test2 = pd.merge(package,component, on = ['identifier','date'], how='left'), component.query(date_y == '')
</code>```

Now trying:

```<code>test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2.query('date_y == \'\'')
</code>```

And

```<code>test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2[test2.date_y == '']
</code>```

Also tried:

```<code>test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2 = test2.date_y == ''
</code>```

Sample data:

```<code>+------------+------------+------------+------------+
|   date_x   | identifier |   date_y   | identifier |
+------------+------------+------------+------------+
| 13/03/2019 | 3582191409 | 13/03/2019 | 3582191410 |
| 13/03/2019 | 3582191289 | 13/03/2019 | 3582191290 |
| 13/03/2019 | 3582190137 | 13/03/2019 | 3582190138 |
| 13/03/2019 | 3582185931 | 13/03/2019 | 3582185930 |
| 13/03/2019 | 3582184503 |            | 3582184502 |
| 13/03/2019 | 3582195631 |            | 3582195632 |
| 13/03/2019 | 3582191374 |            | 3582191373 |
| 13/03/2019 | 3582185917 |            | 3582185916 |
| 13/03/2019 | 3582185863 |            | 3582185862 |
+------------+------------+------------+------------+
</code>```

Im trying to filter date y = blanks

答:
You're most likely reading in blanks.  I would first make sure date_x and date_y are timestamps and replace all blanks with np.nan:</p>

```<code>test2['date_y']=test2['date_y'].replace(' ',np.nan)
test2['date_x']=pd.to_datetime(test2['date_x'])
test2['date_y']=pd.to_datetime(test2['date_y'])
test2_filtered=test2.loc[test2['date_y'].isnull()]
</code>```

Title: Pandas Merge and filter

Body:
I used merge to create a dataframe between 2 of my query's.
Now in the dataframe I want to put a filter on a column but I cannot get it to work. I am trying to add filter component date is null or blank.

    ##reading data from sql
    package = pd.read_sql(sql,con)
    component = pd.read_sql(sqla,con)

    ##doing the left join
    test2 = pd.merge(package,component, on = ['identifier','date'], how='left')

    ##shrinking the dataframe
    test3 = test2[['identifier_x']].copy()

i've tried doing the below but cannot get it to work. Getting date_y not defined. I also tried with just date, as when I merge my dataframes the like columns get labelled x and y.

 test2 = pd.merge(package,component, on = ['identifier','date'], how='left'), component.query(date_y == '')

Now trying:

test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2.query('date_y == \'\'')

And

test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2[test2.date_y == '']

Also tried:

test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2 = test2.date_y == ''

Sample data:

+------------+------------+------------+------------+
|   date_x   | identifier |   date_y   | identifier |
+------------+------------+------------+------------+
| 13/03/2019 | 3582191409 | 13/03/2019 | 3582191410 |
| 13/03/2019 | 3582191289 | 13/03/2019 | 3582191290 |
| 13/03/2019 | 3582190137 | 13/03/2019 | 3582190138 |
| 13/03/2019 | 3582185931 | 13/03/2019 | 3582185930 |
| 13/03/2019 | 3582184503 |            | 3582184502 |
| 13/03/2019 | 3582195631 |            | 3582195632 |
| 13/03/2019 | 3582191374 |            | 3582191373 |
| 13/03/2019 | 3582185917 |            | 3582185916 |
| 13/03/2019 | 3582185863 |            | 3582185862 |
+------------+------------+------------+------------+

Im trying to filter date y = blanks

Body:
You're most likely reading in blanks.  I would first make sure date_x and date_y are timestamps and replace all blanks with np.nan:

test2['date_y']=test2['date_y'].replace(' ',np.nan)
test2['date_x']=pd.to_datetime(test2['date_x'])
test2['date_y']=pd.to_datetime(test2['date_y'])
test2_filtered=test2.loc[test2['date_y'].isnull()]


问:
Is there a way to pass an String Array as Variable for the server sided Xquery script?
Im trying to improve the Search of my Spring-Boot Services by implementing a server-sided xquery search which is triggered by java invokation

I tried some stuff with loops but it didnt work

....

```<code>protected DatabaseClient databaseClient;

public DocumentDTO searchDocument(String language, String documentId, String... culsterIds) throws JAXBException {
        ServerEvaluationCall invoker = databaseClient.newServerEval();
      invoker.modulePath("/main/searchForDocuments.xqy")
                .addVariable("language", language)
                .addVariable("documentId", documentId)
                .addVariable("clusterIds", consentTemplateIds);
....
</code>```

the variables should be inserted in the xqy script to get the corresponding
search result for the parameters.

答:
As you've determined, addVariable() only takes single values.

You could serialize the list of values as a JSON array and send the JSON array using a JSONWriteHandle.  Then, in XQuery, use xdmp:from-json() to convert the JSON array node to an in-memory array.

Or, if you're using a recent version of MarkLogic 9, you could use a Data Service to produce a client interface specify to your endpoint module:

http://docs.marklogic.com/guide/java/DataServices

Hoping that helps,

Body:
Im trying to improve the Search of my Spring-Boot Services by implementing a server-sided xquery search which is triggered by java invokation

I tried some stuff with loops but it didnt work

....

protected DatabaseClient databaseClient;

public DocumentDTO searchDocument(String language, String documentId, String... culsterIds) throws JAXBException {
        ServerEvaluationCall invoker = databaseClient.newServerEval();
      invoker.modulePath("/main/searchForDocuments.xqy")
                .addVariable("language", language)
                .addVariable("documentId", documentId)
                .addVariable("clusterIds", consentTemplateIds);
....

the variables should be inserted in the xqy script to get the corresponding
search result for the parameters.


答:
Change your code to this

```<code>with open('numbers.txt') as nums:
        lines = nums.read().splitlines()

results = list(map(int, lines))
print(results)
print(max(results))
</code>```

the first two lines read file and store it as a list. third line convert string list to integer and the last one search in list and return max, use min for minimum.

Body:
Change your code to this

with open('numbers.txt') as nums:
        lines = nums.read().splitlines()

results = list(map(int, lines))
print(results)
print(max(results))

the first two lines read file and store it as a list. third line convert string list to integer and the last one search in list and return max, use min for minimum.