问:
Sklearn predict python3.5
I am training a Logistic Regression model using sklearn LogisticRegression.
I am getting a TypeError when trying to predict for the test set.

CODE:

```<code>test_features=test[["Sex","Age","Pclass","Fare","Embarked"]].values
myprediction=myfit2.predict(test_features)
</code>```

ERROR:

float() argument must be a string or a number

I've checked the syntax a few times.Could this be because I'm using Python 3.5. Because this seems to work fine on python 2.7. Would greatly appreciate help to resolve this error.

答:
The problem is that the data contain NaN:

Code:

```<code>import pandas as pd
from numpy import nanmean
import numpy as np
from sklearn.linear_model import LogisticRegression

train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")

test["Sex"][test["Sex"]=="male"]=0
test["Sex"][test["Sex"]=="female"]=1
test["Embarked"][test["Embarked"]=='S']=0
test["Embarked"][test["Embarked"]=='C']=1
test["Embarked"][test["Embarked"]=='Q']=2

train["Sex"][train["Sex"]=="male"]=0
train["Sex"][train["Sex"]=="female"]=1
train["Embarked"][train["Embarked"]=='S']=0
train["Embarked"][train["Embarked"]=='C']=1
train["Embarked"][train["Embarked"]=='Q']=2

nan_mean_age = nanmean(test.iloc[:,4])
test = test.fillna(value = nan_mean_age)

nan_mean_age2 = nanmean(train.iloc[:,5])
train = train.fillna(value = nan_mean_age2)

train_features=train[["Sex","Age","Pclass","Fare","Embarked"]].values
test_features=test[["Sex","Age","Pclass","Fare","Embarked"]].values

train_features = np.asarray(train_features)
test_features = np.asarray(test_features)

lg = LogisticRegression()
#define your target variable y and then fit
y_train = train.iloc[:,1]

lg.fit(train_features,y_train)
lg.predict(test_features)
</code>```

result:

```<code>array([0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1,
       1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0,
       0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1,
       1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0,
       1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
       0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
       1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1,
       0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0,
       1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1,
       0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0,
       0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1,
       0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1,
       0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0,
       0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0,
       0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
       1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1,
       1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1,
       1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0,
       1, 0, 0, 0], dtype=int64)
</code>```

Something like this should work fine

Title: Sklearn predict python3.5

Body:
I am training a Logistic Regression model using sklearn LogisticRegression.
I am getting a TypeError when trying to predict for the test set.

CODE:

test_features=test[["Sex","Age","Pclass","Fare","Embarked"]].values
myprediction=myfit2.predict(test_features)

ERROR:

float() argument must be a string or a number

I've checked the syntax a few times.Could this be because I'm using Python 3.5. Because this seems to work fine on python 2.7. Would greatly appreciate help to resolve this error.

Body:
The problem is that the data contain NaN:

Code:

import pandas as pd
from numpy import nanmean
import numpy as np
from sklearn.linear_model import LogisticRegression

train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")

test["Sex"][test["Sex"]=="male"]=0
test["Sex"][test["Sex"]=="female"]=1
test["Embarked"][test["Embarked"]=='S']=0
test["Embarked"][test["Embarked"]=='C']=1
test["Embarked"][test["Embarked"]=='Q']=2

train["Sex"][train["Sex"]=="male"]=0
train["Sex"][train["Sex"]=="female"]=1
train["Embarked"][train["Embarked"]=='S']=0
train["Embarked"][train["Embarked"]=='C']=1
train["Embarked"][train["Embarked"]=='Q']=2

nan_mean_age = nanmean(test.iloc[:,4])
test = test.fillna(value = nan_mean_age)

nan_mean_age2 = nanmean(train.iloc[:,5])
train = train.fillna(value = nan_mean_age2)

train_features=train[["Sex","Age","Pclass","Fare","Embarked"]].values
test_features=test[["Sex","Age","Pclass","Fare","Embarked"]].values

train_features = np.asarray(train_features)
test_features = np.asarray(test_features)

lg = LogisticRegression()
#define your target variable y and then fit
y_train = train.iloc[:,1]

lg.fit(train_features,y_train)
lg.predict(test_features)

result:

array([0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1,
       1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0,
       0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1,
       1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0,
       1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
       0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
       1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1,
       0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0,
       1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1,
       0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0,
       0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1,
       0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1,
       0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0,
       0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0,
       0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
       1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1,
       1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1,
       1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0,
       1, 0, 0, 0], dtype=int64)

Something like this should work fine


来源: stackexchange

问:
Problems with loading data from API - want to use async/await instead
From my component I'm calling on the method in the service which gets me a order from the API.

My service:

```<code> getOrder(orderId: number): Observable<Order> {
 const url = `${this.ordersUrl}/getOrder?orderId=${orderId}&country=${Cookie.get('country')}`;
 return this.http.get(url, {headers: this.headers}).map(response => response.json()).catch(this.errorService.handleError);
</code>```

}

My component:

```<code> ngOnInit() {
this.sub = this.route.params.subscribe(params => {
  this.orderId = +params['orderId'];
  this.orderService.getOrder(this.orderId)
  .subscribe( order => {
    this.order = order;
    console.log(this.order.commentAdmin);},
    error => this.errorMessage = <any>error);
});
</code>```

When I load my template for my component with the data I get from "order" I get that the data is undefined. But if I console.log it, I get the correct response.
I'm thinking that it loads the data before it loads the template and there is something that goes wrong there. I want to try and use async and await to get and show the data but I'm not sure how to do this. We've solved this problem by using delays since none of us have used Angular before. How can I do this correctly by using await and async?

答:
you can use an elvis operator in your template to handle order being undefined.

```<code><p>{{ order?.commentAdmin }}<p>
</code>```

the reason this is happening is that angular is binding the order object before data has been returned from the endpoint and is breaking the templating.

ContentLicense: CC BY-SA 3.0

Body:
From my component I'm calling on the method in the service which gets me a order from the API.

My service:

 getOrder(orderId: number): Observable<Order> {
 const url = `${this.ordersUrl}/getOrder?orderId=${orderId}&country=${Cookie.get('country')}`;
 return this.http.get(url, {headers: this.headers}).map(response => response.json()).catch(this.errorService.handleError);

}

My component:

 ngOnInit() {
this.sub = this.route.params.subscribe(params => {
  this.orderId = +params['orderId'];
  this.orderService.getOrder(this.orderId)
  .subscribe( order => {
    this.order = order;
    console.log(this.order.commentAdmin);},
    error => this.errorMessage = <any>error);
});

When I load my template for my component with the data I get from "order" I get that the data is undefined. But if I console.log it, I get the correct response.
I'm thinking that it loads the data before it loads the template and there is something that goes wrong there. I want to try and use async and await to get and show the data but I'm not sure how to do this. We've solved this problem by using delays since none of us have used Angular before. How can I do this correctly by using await and async?

Body:
you can use an elvis operator in your template to handle order being undefined.

<p>{{ order?.commentAdmin }}<p>

the reason this is happening is that angular is binding the order object before data has been returned from the endpoint and is breaking the templating.


问:
how to move left and right thumb of seek bar at a time in android
Very good morning all of you.
I am new in android developing and i have one little query regarding the seek bar in android.
Actually i am developing one application in which i play video and and under the video i use custom seek bar with custom class.
Now my question is that when i select video and its duration is assume 1 minute, But i want to set right thumb of seek bar at 15th second position every time.
And when i move left thumb of seek bar the right thumb must have to move automatically with it. And its mandatory to maintain seek bar with 15th seconds from both right and left side.

Please help me to solve this issue. Thanks in advance.

答:
As you have given any specific details, i assume you are using RangeSeekBar
for maintaining constant distance between thumbs try using the difference
(progress value of leftThumb - progress value of rightThumb).

if the difference is equal to your desired value (15 in your example) then disable the seek bar.

checkhere
How to set range between two thumbs in range seek bar in android?

Second method you can use is:

get the current progress value of leftThumb and rightThumb

if the difference between them is '15' then set the progress of the rightThumb
as

seekTo (progress value of leftThumb + 15) under the if condition

(progress value of leftThumb - progress value of rightThumb) == 15

cant use exact and proper variables here add some more details.
hope it helps


问:
How to create two columns RDLC report C#, my second column does not show data
I am trying to create two column report for labeling purposes, I followed instructions on the following link: blogs.wrox.com/article/creating-mailing-labels-in-sql-server-reporting-services

But the data keeps appearing on one column and not on both columns, I changed all sizes and tried tables and lists same results, it just won't populate the second column.

When I added a second field, column 2 shifted to the right, changing the the size of the report.

|Field 1 | -- |Field 1 Copy| -----> Column 2 (shifted)

I continued anyway and it shows two of the same values side by side, but in reality they are on the same column, which means I have two fields on the same column, if I hide one, the second will shift and show on the lift side, I have changed the font style to distinguish them from the attached photo.

| Customer1 | -- | Customer1 |

| Customer2 |

答: Check your width of report viewer, It seems from image that expr1 and expr2 having more width and also delete second expr2</p>


问:
kibana development environment is too slow
I use bin/kibana.bat --dev to run kibana server

When there is a changing on src code, webpack will monitor and pack src code to
bundle.js

The procedure can be very very long and usually the browser will crash somehow.

It will cost almost five minutes when I do a very small change on even .css file and refresh to see the result.

How can I speed up the bundle speed on dev envionment ?Thanks

答:
Add

```<code>optimize.unsafeCache: false
</code>```

To your kibana.yml
That will disable the webpack optimizaton

Body:
Add

optimize.unsafeCache: false

To your kibana.yml
That will disable the webpack optimizaton


问:
Android - add YouTube Data API to project
I am trying to include youtube data api in my application, but I cant figure it out how to do it correctly.

Here is the folder of the library that I downloaded:

Folder content Image

How can I add it to android studio's project?\
I tried to add one of the jar files in the photo, but then the jars in the libs folder, cant be used.

** I want all the content of the folder to be applied in android studio.

答:
Please check youtube video search demo app

https://github.com/Keshava11/LatentLoader


问:
Docker: cd into directory using regular expressions
I have to build a Docker image and in the Dockerfile I have move into a directory whose name contains a dynamic id, e.g myfolder12345, that can become myfolder56789 in another build. As I don't know which can be this id everytime I do the build, I have tried to use regular expressions to achieve that.

I've tried with

```<code>WORKDIR myfolder*
</code>```

but the current directory remains /.
How can be solved?

答:
how about trying the regex syntax?

```<code>WORKDIR workdir[\d]+
</code>```

Let me know if that works for you.

Body:
I have to build a Docker image and in the Dockerfile I have move into a directory whose name contains a dynamic id, e.g myfolder12345, that can become myfolder56789 in another build. As I don't know which can be this id everytime I do the build, I have tried to use regular expressions to achieve that.

I've tried with

WORKDIR myfolder*

but the current directory remains /.
How can be solved?

Body:
how about trying the regex syntax?

WORKDIR workdir[\d]+

Let me know if that works for you.


问:
Overlapping border div
i want to create a table just with div tag. I use only two class and it works well.

The only problem is the border of cell inside the table have double width of the table border and it looks ugly. I know the reason is all cell have border around but i can not fix it. I've try some solution in other post but it does not work in this case.

Can some one please help me? Thanks a lot. Note that i don't want to add more class.

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
</div></code>```

答:
@Duanxx

Explanation for my answer:

Look at the following code.For code 1

```<code><html>
  <head>
    <style type="text/css">
      .parentDiv{
        background-color: black;
        justify-content: space-around;
        display: flex;
      }
      .childDiv{
        width: 50%;
        height:100px;
        font-size: 30px;
        margin: 10px 10px;
      }
    </style>
  </head>
  <body>
    <div class="parentDiv">
        <div class="childDiv" style="background-color: pink">Child 1</div>
        <div class="childDiv" style="background-color: bisque">Child 2</div>
    </div>

  </body>
</html>
</code>```

Have a look at this now:

```<code><html>
  <head>
    <style type="text/css">
      .parentDiv{
        background-color: black;
        justify-content: space-around;
        display: flex;
      }
      .childDiv{
        width: 50%;
        height:100px;
        font-size: 30px;
        margin: -5px 10px;
      }
    </style>
  </head>
  <body>
    <div class="parentDiv">
        <div class="childDiv" style="background-color: pink">Child 1</div>
        <div class="childDiv" style="background-color: bisque">Child 2</div>
    </div>
  </body>
</html>
</code>```

For code 2

Compare the two. The children are supposed to fit inside the parent. That is why negative margins are not used.

Title: Overlapping border div

Body:
i want to create a table just with div tag. I use only two class and it works well.

The only problem is the border of cell inside the table have double width of the table border and it looks ugly. I know the reason is all cell have border around but i can not fix it. I've try some solution in other post but it does not work in this case.

Can some one please help me? Thanks a lot. Note that i don't want to add more class.

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}

x

x

x

x

x

x

x

x

x

x

Body:
@Duanxx

Explanation for my answer:

Look at the following code.For code 1

<html>
  <head>
    <style type="text/css">
      .parentDiv{
        background-color: black;
        justify-content: space-around;
        display: flex;
      }
      .childDiv{
        width: 50%;
        height:100px;
        font-size: 30px;
        margin: 10px 10px;
      }
    </style>
  </head>
  <body>
    <div class="parentDiv">
        <div class="childDiv" style="background-color: pink">Child 1</div>
        <div class="childDiv" style="background-color: bisque">Child 2</div>
    </div>

  </body>
</html>

Have a look at this now:

<html>
  <head>
    <style type="text/css">
      .parentDiv{
        background-color: black;
        justify-content: space-around;
        display: flex;
      }
      .childDiv{
        width: 50%;
        height:100px;
        font-size: 30px;
        margin: -5px 10px;
      }
    </style>
  </head>
  <body>
    <div class="parentDiv">
        <div class="childDiv" style="background-color: pink">Child 1</div>
        <div class="childDiv" style="background-color: bisque">Child 2</div>
    </div>
  </body>
</html>

For code 2

Compare the two. The children are supposed to fit inside the parent. That is why negative margins are not used.


问:
ConfigParser removes quotes from empty values
I have an INI windows file with the following format:

```<code>[STRINGS]
property 1 = "hello"
property 2 = ""
PROPERTY 3 = ""
</code>```

but if I get values using ConfigParser

```<code>init_values= ConfigParser.RawConfigParser(allow_no_value=True)
init_values.optionxform = str
init_values.read(init_file)
</code>```

and modify one of them (p.e. property 1)

```<code>init_values.set('STRINGS', 'property 1', '"world"')
init_values.write(configfile)
</code>```

I get the following result:

```<code>[STRINGS]
property 1 = "world"
property 2 =
PROPERTY 3 =
</code>```

All the quotes from empty values are removed.

How can I force to use quotes even in empty values?

答:
Let's take have an INI windows file with the following format:

```<code>[STRINGS]
property 1 = "hello"
property 2 = ""
PROPERTY 3 = ""
</code>```

You can do it by following way. For example:

```<code>import ConfigParser

filename='config'
parser=ConfigParser.SafeConfigParser()
parser.read([filename])
print(parser.sections())
# ['section']
for section in parser.sections():
    print(parser.options(section))
    # ['id', 'rb', 'person']
    for option in parser.options(section):
        try:
            value=parser.getint(section,option)
        except ValueError:
            value=parser.get(section,option)
        print(option,value,type(value))
print(parser.items('section'))
# [('property1', 'world'), ('property2', ''), ('property3', '')]
</code>```

Body:
I have an INI windows file with the following format:

[STRINGS]
property 1 = "hello"
property 2 = ""
PROPERTY 3 = ""

but if I get values using ConfigParser

init_values= ConfigParser.RawConfigParser(allow_no_value=True)
init_values.optionxform = str
init_values.read(init_file)

and modify one of them (p.e. property 1)

init_values.set('STRINGS', 'property 1', '"world"')
init_values.write(configfile)

I get the following result:

[STRINGS]
property 1 = "world"
property 2 =
PROPERTY 3 =

All the quotes from empty values are removed.

How can I force to use quotes even in empty values?

Body:
Let's take have an INI windows file with the following format:

[STRINGS]
property 1 = "hello"
property 2 = ""
PROPERTY 3 = ""

You can do it by following way. For example:

import ConfigParser

filename='config'
parser=ConfigParser.SafeConfigParser()
parser.read([filename])
print(parser.sections())
# ['section']
for section in parser.sections():
    print(parser.options(section))
    # ['id', 'rb', 'person']
    for option in parser.options(section):
        try:
            value=parser.getint(section,option)
        except ValueError:
            value=parser.get(section,option)
        print(option,value,type(value))
print(parser.items('section'))
# [('property1', 'world'), ('property2', ''), ('property3', '')]


问:
Retrieve Facebook Post Comments Using Graph API
I tried to get Facebook comments using:

```<code>http://graph.facebook.com/[post_id]/comments
</code>```

It results only 2 of 15 comments, and without count info.

{
    "data": [
        {
            "id": "[post_id]",
            "from": {
                "name": "[name]",
                "id": "[id]"
             },
             "message": "[message]",
             "created_time": "2011-01-23T02:36:23+0000"
        },
        {
             "id": "[id]",
             "from": {
             "name": "[name]",
                 "id": "[id]"
             },
            "message": "[message]",
            "created_time": "2011-01-23T05:16:56+0000"
        }
    ]
}
```

Anyone know why only 2 comments?

Also, I want to retrieve comments (default number) or retrieve comments with my limit number, and get its comments count. Any idea? (Please use Graph API).

答:
After Successfully Login call this method facebookComments()

parameters.putString("fields", "message"); .............//  Its Important

```<code> AccessToken accessToken = AccessToken.getCurrentAccessToken();
    public void facebookComments() {
        try {
            getFriends(accessToken, new GraphRequest.Callback() {
                        public void onCompleted(GraphResponse response) {
                            Log.e("keshav", "one" + response);
                            CommonMethod.showAlert("res  --> " + response, MainActivity.this);
                        }
                    }
            );
        } catch (Exception e) {
            CommonMethod.showAlert("Exception is -> " + e, MainActivity.this);
        }
    }

    public void getFriends(AccessToken token, GraphRequest.Callback callback)
    {
        // TODO Comments Working but id return only
        GraphRequest requestt = new GraphRequest(token, "744511125731315_751199848395776/comments",
                null, HttpMethod.GET, callback);
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id");           // todo in use imp
        parameters.putString("fields", "name");           // todo in use imp
        parameters.putString("fields", "from");           // todo in use imp
        parameters.putString("fields", "message");           // todo in use imp
        requestt.setParameters(parameters);
        requestt.executeAsync();
    }
</code>```

Body:
I tried to get Facebook comments using:

http://graph.facebook.com/[post_id]/comments

It results only 2 of 15 comments, and without count info.

{
    "data": [
        {
            "id": "[post_id]",
            "from": {
                "name": "[name]",
                "id": "[id]"
             },
             "message": "[message]",
             "created_time": "2011-01-23T02:36:23+0000"
        },
        {
             "id": "[id]",
             "from": {
             "name": "[name]",
                 "id": "[id]"
             },
            "message": "[message]",
            "created_time": "2011-01-23T05:16:56+0000"
        }
    ]
}

Anyone know why only 2 comments?

Also, I want to retrieve comments (default number) or retrieve comments with my limit number, and get its comments count. Any idea? (Please use Graph API).

Body:
After Successfully Login call this method facebookComments()

parameters.putString("fields", "message"); .............//  Its Important

 AccessToken accessToken = AccessToken.getCurrentAccessToken();
    public void facebookComments() {
        try {
            getFriends(accessToken, new GraphRequest.Callback() {
                        public void onCompleted(GraphResponse response) {
                            Log.e("keshav", "one" + response);
                            CommonMethod.showAlert("res  --> " + response, MainActivity.this);
                        }
                    }
            );
        } catch (Exception e) {
            CommonMethod.showAlert("Exception is -> " + e, MainActivity.this);
        }
    }

    public void getFriends(AccessToken token, GraphRequest.Callback callback)
    {
        // TODO Comments Working but id return only
        GraphRequest requestt = new GraphRequest(token, "744511125731315_751199848395776/comments",
                null, HttpMethod.GET, callback);
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id");           // todo in use imp
        parameters.putString("fields", "name");           // todo in use imp
        parameters.putString("fields", "from");           // todo in use imp
        parameters.putString("fields", "message");           // todo in use imp
        requestt.setParameters(parameters);
        requestt.executeAsync();
    }


问:
error: ‘nl_socket_alloc’ was not declared in this scope
I get tis error when I'm compiling the following code,the point is that I know there is some error with the declaration of  nl_socket_alloc but I cannot see where exactly I screw it up.

the compiler complains when I inicializate the sockets in the .cpp, so I'm guessing that maybe they're bad declared.

Thanks in advance

```<code>#include "ibrcommon/net/NetLink3Manager.h"
#include "ibrcommon/net/vsocket.h"
#include "ibrcommon/Logger.h"

#include <netlink/netlink.h>
#include <netlink/route/link.h>
#include <netlink/route/addr.h>
#include <netlink/route/rtnl.h>
#include <netlink/socket.h>
#include <netlink/msg.h>
//#include <net/if.h>
#include <string.h>

namespace ibrcommon
{
    static int nl3_callback(struct nl_msg *msg, void *arg)
    {
        NetLink3Manager *m = static_cast<NetLink3Manager *>(arg);
        NetLink3ManagerEvent evt(msg);
        m->callback(evt);
        return 0;
    }

    void add_addr_to_list(struct nl_object *obj, void *data)
    {
        char buf[INET6_ADDRSTRLEN+5];
        std::list<vaddress> *list = static_cast<std::list<vaddress>*>(data);

        struct nl_addr *naddr = rtnl_addr_get_local((struct rtnl_addr *) obj);
        int ifindex = 0;
        int scope = rtnl_addr_get_scope((struct rtnl_addr *) obj);

        if (scope == rtnl_str2scope("link"))
            ifindex = rtnl_addr_get_ifindex((struct rtnl_addr *) obj);

        if (naddr)
        {
            int family = nl_addr_get_family(naddr);
            nl_addr2str( naddr, buf, sizeof( buf ) );
            vaddress vaddr(vaddress::Family(family), vaddress::strip_netmask(std::string(buf)), ifindex, false);
            list->push_back( vaddr );
        }

        struct nl_addr *baddr = rtnl_addr_get_broadcast((struct rtnl_addr *) obj);

        if (baddr)
        {
            int family = nl_addr_get_family(baddr);
            nl_addr2str( baddr, buf, sizeof( buf ) );
            vaddress vaddr(vaddress::Family(family), vaddress::strip_netmask(std::string(buf)), ifindex, true);
            list->push_back( vaddr );
        }
    }

    NetLink3Manager::NetLink3Manager()
     : _refresh_cache(false), _running(true), _sock(NULL)
    {
        // initialize the sockets
        _nl_notify_sock = nl_socket_alloc();//=>First error
        _nl_query_sock = nl_socket_alloc();//=>Second error

        // disable seq check for notify socket
        nl_socket_disable_seq_check(_nl_notify_sock);

        // define callback method
        nl_socket_modify_cb(_nl_notify_sock, NL_CB_VALID, NL_CB_CUSTOM, nl3_callback, this);

        // connect to routing netlink protocol
        nl_connect(_nl_notify_sock, NETLINK_ROUTE);
        nl_connect(_nl_query_sock, NETLINK_ROUTE);

        // init route messages
        nl_socket_add_memberships(_nl_notify_sock, RTNLGRP_IPV4_IFADDR);

//      IPv6 requires further support in the parsing procedures!
//      nl_socket_add_membership(_nl_notify_sock, RTNLGRP_IPV6_IFADDR);
        nl_socket_add_memberships(_nl_notify_sock, RTNLGRP_LINK);

        // create a cache for the links
        if (rtnl_link_alloc_cache(_nl_query_sock, AF_UNSPEC, &_link_cache) < 0)
        {
            nl_socket_free(_nl_notify_sock);
            nl_socket_free(_nl_query_sock);
            // error
            throw ibrcommon::vsocket_exception("netlink cache allocation failed");
        }

        // create a cache for addresses
        if (rtnl_addr_alloc_cache(_nl_query_sock, &_addr_cache) < 0)
        {
            nl_socket_free(_nl_notify_sock);
            nl_socket_free(_nl_query_sock);
            // error
            nl_cache_free(_link_cache);
            _link_cache = NULL;
            throw ibrcommon::vsocket_exception("netlink cache allocation failed");
        }

        // create a new socket for the netlink interface
        _sock = new ibrcommon::vsocket();
    }

    NetLink3Manager::~NetLink3Manager()
    {
        stop();
        join();

        // destroy the socket for the netlink interface
        delete _sock;

        nl_cache_free(_addr_cache);
        nl_cache_free(_link_cache);

        nl_socket_free(_nl_notify_sock);
        nl_socket_free(_nl_query_sock);
    }

    const std::string NetLink3Manager::getInterface(int index) const
    {
        char buf[256];
        rtnl_link_i2name(_link_cache, index, (char*)&buf, sizeof buf);
        return std::string((char*)&buf);
    }

    const std::list<vaddress> NetLink3Manager::getAddressList(const vinterface &iface, const vaddress::Family f)
    {
        ibrcommon::MutexLock l(_call_mutex);

        if (_refresh_cache)
        {
            nl_cache_free(_addr_cache);
            nl_cache_free(_link_cache);

            // create a cache for the links
            if (rtnl_link_alloc_cache(_nl_query_sock, AF_UNSPEC, &_link_cache) < 0)
            {
                // error
                throw ibrcommon::vsocket_exception("netlink cache allocation failed");
            }

            // create a cache for addresses
            if (rtnl_addr_alloc_cache(_nl_query_sock, &_addr_cache) < 0)
            {
                // error
                nl_cache_free(_link_cache);
                _link_cache = NULL;
                throw ibrcommon::vsocket_exception("netlink cache allocation failed");
            }

            // mark the cache as refreshed
            _refresh_cache = false;
        }

        std::list<vaddress> addresses;

        struct rtnl_addr *filter = rtnl_addr_alloc();
        const std::string i = iface.toString();
        rtnl_addr_set_ifindex(filter, rtnl_link_name2i(_link_cache, i.c_str()));

        if (f == vaddress::VADDRESS_UNSPEC)
        {
            rtnl_addr_set_family(filter, AF_INET6);
            nl_cache_foreach_filter(_addr_cache, (struct nl_object *) filter,
                                    add_addr_to_list, &addresses);

            rtnl_addr_set_family(filter, AF_INET);
            nl_cache_foreach_filter(_addr_cache, (struct nl_object *) filter,
                                    add_addr_to_list, &addresses);
        }
        else
        {
            rtnl_addr_set_family(filter, f);
            nl_cache_foreach_filter(_addr_cache, (struct nl_object *) filter,
                                    add_addr_to_list, &addresses);
        }

        rtnl_addr_put(filter);

        return addresses;
    }

    void NetLink3Manager::callback(const NetLink3ManagerEvent &lme)
    {
        // ignore if the event is unknown
        if (lme.getType() == LinkManagerEvent::EVENT_UNKOWN) return;

        // ignore if this is an wireless extension event
        if (lme.isWirelessExtension()) return;

        // need to refresh the cache
        {
            ibrcommon::MutexLock l(_call_mutex);
            _refresh_cache = true;
        }

        // print out some debugging
        IBRCOMMON_LOGGER_DEBUG(10) << lme.toString() << IBRCOMMON_LOGGER_ENDL;

        // notify all subscribers about this event
        raiseEvent(lme);
    }

    void NetLink3Manager::run()
    {
        // add netlink fd to vsocket
        _sock->add(nl_socket_get_fd(_nl_notify_sock));

        try {
            while (_running)
            {
                std::list<int> fds;
                _sock->select(fds, NULL);

                nl_recvmsgs_default(_nl_notify_sock);
            }
        } catch (const vsocket_exception&) {
            // stopped / interrupted
            IBRCOMMON_LOGGER(error) << "NetLink connection stopped" << IBRCOMMON_LOGGER_ENDL;
        }
    }

    void NetLink3Manager::__cancellation()
    {
        _running = false;
        _sock->close();
    }

    /** read a netlink message from the socket and create a new netlink event object **/
    NetLink3ManagerEvent::NetLink3ManagerEvent(struct nl_msg *msg)
     : _type(EVENT_UNKOWN), _state(0), _wireless(false)
    {
        int attrlen, nlmsg_len, rta_len, rtl;
        struct rtattr *attr;
        struct rtattr *rth;
        struct ifaddrmsg *ifa;
        struct ifinfomsg *ifi;
        struct nlmsghdr *nlh;

        // cast netlink message
        nlh = nlmsg_hdr(msg);

        switch (nlh->nlmsg_type)
        {
            case RTM_BASE:
            {
                ifi = (struct ifinfomsg *) NLMSG_DATA(nlh);

                nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
                attrlen = nlh->nlmsg_len - nlmsg_len;

                if (attrlen < 0) break;

                attr = (struct rtattr *) (((char *) ifi) + nlmsg_len);

                rta_len = RTA_ALIGN(sizeof(struct rtattr));
                while (RTA_OK(attr, attrlen))
                {
                    size_t rta_length = RTA_PAYLOAD(attr);

                    switch (attr->rta_type)
                    {
                    case IFLA_IFNAME:
                        _interface = ibrcommon::vinterface( std::string((char*)RTA_DATA(attr), rta_length) );
                        _type = EVENT_LINK_STATE;
                        break;

                    case IFLA_OPERSTATE:
                    {
                        char s;
                        ::memcpy(&s, (char*)RTA_DATA(attr), 1);
                        _state = s;
                        break;
                    }

                    case IFLA_WIRELESS:
                        _wireless = true;
                        break;

                    default:
                        _attributes[attr->rta_type] = std::string((char*)RTA_DATA(attr), rta_length);
                        break;
                    }

                    attr = RTA_NEXT(attr, attrlen);
                }
                break;
            }

            case RTM_NEWADDR:
            {
                ifa = (struct ifaddrmsg *) NLMSG_DATA(nlh);
                rth = IFA_RTA(ifa);
                rtl = IFA_PAYLOAD(nlh);

                // parse all attributes
                while (rtl && RTA_OK(rth, rtl))
                {
                    switch (rth->rta_type)
                    {
                        // local address
                        case IFA_LOCAL:
                        {
                            char address[256];

                            uint32_t ipaddr = htonl(*((uint32_t *)RTA_DATA(rth)));
                            sprintf(address, "%d.%d.%d.%d", (ipaddr >> 24) & 0xff, (ipaddr >> 16) & 0xff, (ipaddr >> 8) & 0xff, ipaddr & 0xff);

                            _address = ibrcommon::vaddress(ibrcommon::vaddress::VADDRESS_INET, std::string(address));
                            _type = EVENT_ADDRESS_ADDED;
                            break;
                        }

                        // interface name
                        case IFA_LABEL:
                        {
                            //char name[IFNAMSIZ];
                            char *name = (char *)RTA_DATA(rth);
                            _interface = ibrcommon::vinterface(name);
                            break;
                        }
                    }
                    rth = RTA_NEXT(rth, rtl);
                }
                break;
            }

            case RTM_DELADDR:
            {
                ifa = (struct ifaddrmsg *) NLMSG_DATA(nlh);
                rth = IFA_RTA(ifa);
                rtl = IFA_PAYLOAD(nlh);

                // parse all attributes
                while (rtl && RTA_OK(rth, rtl))
                {
                    switch (rth->rta_type)
                    {
                        // local address
                        case IFA_LOCAL:
                        {
                            char address[256];

                            uint32_t ipaddr = htonl(*((uint32_t *)RTA_DATA(rth)));
                            sprintf(address, "%d.%d.%d.%d", (ipaddr >> 24) & 0xff, (ipaddr >> 16) & 0xff, (ipaddr >> 8) & 0xff, ipaddr & 0xff);

                            _address = ibrcommon::vaddress(ibrcommon::vaddress::VADDRESS_INET, std::string(address));
                            _type = EVENT_ADDRESS_REMOVED;
                            break;
                        }

                        // interface name
                        case IFA_LABEL:
                        {
                            //char name[IFNAMSIZ];
                            char *name = (char *)RTA_DATA(rth);
                            _interface = ibrcommon::vinterface(name);
                            break;
                        }
                    }
                    rth = RTA_NEXT(rth, rtl);
                }
                break;
            }

            default:
                IBRCOMMON_LOGGER_DEBUG(10) << "unknown netlink type received: " << nlh->nlmsg_type << IBRCOMMON_LOGGER_ENDL;
                break;
        }
    }

    NetLink3ManagerEvent::~NetLink3ManagerEvent()
    {
    }

    const ibrcommon::vinterface& NetLink3ManagerEvent::getInterface() const
    {
        return _interface;
    }

    const ibrcommon::vaddress& NetLink3ManagerEvent::getAddress() const
    {
        return _address;
    }

    unsigned int NetLink3ManagerEvent::getState() const
    {
        return _state;
    }

    bool NetLink3ManagerEvent::isWirelessExtension() const
    {
        return _wireless;
    }

    LinkManagerEvent::EventType NetLink3ManagerEvent::getType() const
    {
        return _type;
    }

    const std::string NetLink3ManagerEvent::toString() const
    {
        std::stringstream ss;
        ss << "NetLinkManagerEvent on " << getInterface().toString() << "; Type: " << getType();

        switch (getType())
        {
        case EVENT_LINK_STATE:
            ss << "; State: " << getState();
            break;

        case EVENT_ADDRESS_ADDED:
            ss << "; Address added: " << getAddress().toString();
            break;

        case EVENT_ADDRESS_REMOVED:
            ss << "; Address removed: " << getAddress().toString();
            break;

        default:
            break;
        };

        return ss.str();
    }

    void NetLink3ManagerEvent::debug() const
    {
//      for (std::map<int, std::string>::const_iterator iter = attr.begin(); iter != attr.end(); iter++)
//      {
//          std::stringstream ss;
//          const std::string &value = (*iter).second;
//
//          for (std::string::const_iterator si = value.begin(); si != value.end(); si++)
//          {
//              const char &c = (*si);
//              ss << std::hex << "0x" << (int)c << " ";
//          }
//
//          IBRCOMMON_LOGGER_DEBUG(10) << (*iter).first << ": " << ss.str() << IBRCOMMON_LOGGER_ENDL;
//      }
    }
} /* namespace ibrcommon */
</code>```

The eclipse output:

```<code>./ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:66:37: error: ‘nl_socket_alloc’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:70:46: error: ‘nl_socket_disable_seq_check’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:73:85: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘int nl_socket_modify_cb(nl_handle*, nl_cb_type, nl_cb_kind, nl_recvmsg_msg_cb_t, void*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:76:44: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘int nl_connect(nl_handle*, int)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:77:43: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘int nl_connect(nl_handle*, int)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:80:65: error: ‘nl_socket_add_memberships’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:87:68: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘nl_cache* rtnl_link_alloc_cache(nl_handle*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:89:34: error: ‘nl_socket_free’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:96:57: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘nl_cache* rtnl_addr_alloc_cache(nl_handle*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:98:34: error: ‘nl_socket_free’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp: In destructor ‘virtual ibrcommon::NetLink3Manager::~NetLink3Manager()’:
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:121:33: error: ‘nl_socket_free’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp: In member function ‘virtual const std::list<ibrcommon::vaddress> ibrcommon::NetLink3Manager::getAddressList(const ibrcommon::vinterface&, ibrcommon::vaddress::Family)’:
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:142:69: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘nl_cache* rtnl_link_alloc_cache(nl_handle*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:149:58: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘nl_cache* rtnl_addr_alloc_cache(nl_handle*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp: In member function ‘virtual void ibrcommon::NetLink3Manager::run()’:
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:213:46: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘int nl_socket_get_fd(nl_handle*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:221:40: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘int nl_recvmsgs_default(nl_handle*)’
make: *** [ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.o] Error 1
</code>```

There the headers of the function NetLink3Manager.h

```<code>#ifndef NETLINK3MANAGER_H_
#define NETLINK3MANAGER_H_

#include "ibrcommon/net/LinkManager.h"
#include "ibrcommon/thread/Mutex.h"
#include "ibrcommon/thread/Thread.h"
#include "ibrcommon/net/vsocket.h"

#include <netlink/netlink.h>
#include <netlink/socket.h>
#include <netlink/route/link.h>
#include <netlink/msg.h>

namespace ibrcommon
{
    class NetLink3ManagerEvent : public LinkManagerEvent
    {
    public:
        NetLink3ManagerEvent(struct nl_msg *msg);
        virtual ~NetLink3ManagerEvent();

        virtual const ibrcommon::vinterface& getInterface() const;
        virtual const ibrcommon::vaddress& getAddress() const;
        virtual unsigned int getState() const;
        virtual EventType getType() const;

        virtual bool isWirelessExtension() const;

        void debug() const;
        const std::string toString() const;

    private:
        EventType _type;
        unsigned int _state;
        bool _wireless;
        ibrcommon::vinterface _interface;
        ibrcommon::vaddress _address;
        std::map<int, std::string> _attributes;
    };

    class NetLink3Manager : public ibrcommon::LinkManager, public ibrcommon::JoinableThread
    {
        friend class LinkManager;

    public:
        virtual ~NetLink3Manager();

        const std::string getInterface(int index) const;
        const std::list<vaddress> getAddressList(const vinterface &iface, const vaddress::Family f);

        class parse_exception : public Exception
        {
        public:
            parse_exception(string error) : Exception(error)
            {};
        };

        void callback(const NetLink3ManagerEvent &evt);

    protected:
        void run();
        void __cancellation();

    private:
        NetLink3Manager();

        struct nl_sock *_nl_notify_sock;
        struct nl_sock *_nl_query_sock;

        // local link cache
        struct nl_cache *_link_cache;
        struct nl_cache *_addr_cache;

        // mutex for the link cache
        ibrcommon::Mutex _call_mutex;

        bool _refresh_cache;
        bool _running;

        ibrcommon::vsocket *_sock;
    };
} /* namespace ibrcommon */
#endif /* NETLINK3MANAGER_H_ */
</code>```

答:
somehow necro - but I just stumbled over the same issue - so maybe this can help someone.

First of all: you need to install the libnetlink development headers.
On my ancient Debian 8 box

```<code>> sudo apt-get install libnl-3-dev
</code>```

does the trick.

The documentation of the netlink library contains a part about the library structure. In this part you can find all information about required headers and how to link against the library. It basically boils down to include netlink/netlink.h. But sometimes (as on my Debian box) the devel package is installed but the directory containing the header files are not part of the default search path. You could run a find over your entire filesystem looking for netlink.h - this could give you a wrong direction (of course - if you dig out something using find you would always check twice to include the right file). But there is a more systematic approach available...

Provided you run a box using the Debian packaging system, you can check what netlink libraries are installed:

```<code>> dpkg --list libnl*
...
ii  libnl-3-200:amd64               3.2.24-2             amd64                library for dealing with netlink sockets
ii  libnl-3-dev                     3.2.24-2             amd64                development library and headers for libnl-3
un  libnl-dev                       <none>               <none>               (no description available)
ii  libnl-genl-3-200:amd64          3.2.24-2             amd64                library for dealing with netlink sockets - generic netlink
ii  libnl-route-3-200:amd64         3.2.24-2             amd64                library for dealing with netlink sockets - route interface
un  libnl2-dev                      <none>               <none>               (no description available)
un  libnl3-dev                      <none>               <none>               (no description available)
</code>```

The one(s) with the leading ii are the relevant ones. Now use dpkg to get a list of the files provided by the package (and filter for the required one):

```<code>> dpkg  -L  libnl-3-dev | grep  "netlink\.h"

/usr/include/libnl3/netlink/netlink.h
</code>```

As /usr/include/ is part of the default include paths (you can check the paths used by gcc using the answer given here) you would need to add the prefix libnl3 to your include statements. To prevent yourself from the need to change the includes if the library version changes, simply add /usr/include/libnl3 to your include path. For gcc this can be done using the flag

```<code>-I /usr/include/libnl3
</code>```

and for a cmake based build system just add a include_diretories() directive:

```<code>include_directories("/usr/include/libnl3")
</code>```

Body:
I get tis error when I'm compiling the following code,the point is that I know there is some error with the declaration of  nl_socket_alloc but I cannot see where exactly I screw it up.

the compiler complains when I inicializate the sockets in the .cpp, so I'm guessing that maybe they're bad declared.

Thanks in advance

#include "ibrcommon/net/NetLink3Manager.h"
#include "ibrcommon/net/vsocket.h"
#include "ibrcommon/Logger.h"

#include <netlink/netlink.h>
#include <netlink/route/link.h>
#include <netlink/route/addr.h>
#include <netlink/route/rtnl.h>
#include <netlink/socket.h>
#include <netlink/msg.h>
//#include <net/if.h>
#include <string.h>

namespace ibrcommon
{
    static int nl3_callback(struct nl_msg *msg, void *arg)
    {
        NetLink3Manager *m = static_cast<NetLink3Manager *>(arg);
        NetLink3ManagerEvent evt(msg);
        m->callback(evt);
        return 0;
    }

    void add_addr_to_list(struct nl_object *obj, void *data)
    {
        char buf[INET6_ADDRSTRLEN+5];
        std::list<vaddress> *list = static_cast<std::list<vaddress>*>(data);

        struct nl_addr *naddr = rtnl_addr_get_local((struct rtnl_addr *) obj);
        int ifindex = 0;
        int scope = rtnl_addr_get_scope((struct rtnl_addr *) obj);

        if (scope == rtnl_str2scope("link"))
            ifindex = rtnl_addr_get_ifindex((struct rtnl_addr *) obj);

        if (naddr)
        {
            int family = nl_addr_get_family(naddr);
            nl_addr2str( naddr, buf, sizeof( buf ) );
            vaddress vaddr(vaddress::Family(family), vaddress::strip_netmask(std::string(buf)), ifindex, false);
            list->push_back( vaddr );
        }

        struct nl_addr *baddr = rtnl_addr_get_broadcast((struct rtnl_addr *) obj);

        if (baddr)
        {
            int family = nl_addr_get_family(baddr);
            nl_addr2str( baddr, buf, sizeof( buf ) );
            vaddress vaddr(vaddress::Family(family), vaddress::strip_netmask(std::string(buf)), ifindex, true);
            list->push_back( vaddr );
        }
    }

    NetLink3Manager::NetLink3Manager()
     : _refresh_cache(false), _running(true), _sock(NULL)
    {
        // initialize the sockets
        _nl_notify_sock = nl_socket_alloc();//=>First error
        _nl_query_sock = nl_socket_alloc();//=>Second error

        // disable seq check for notify socket
        nl_socket_disable_seq_check(_nl_notify_sock);

        // define callback method
        nl_socket_modify_cb(_nl_notify_sock, NL_CB_VALID, NL_CB_CUSTOM, nl3_callback, this);

        // connect to routing netlink protocol
        nl_connect(_nl_notify_sock, NETLINK_ROUTE);
        nl_connect(_nl_query_sock, NETLINK_ROUTE);

        // init route messages
        nl_socket_add_memberships(_nl_notify_sock, RTNLGRP_IPV4_IFADDR);

//      IPv6 requires further support in the parsing procedures!
//      nl_socket_add_membership(_nl_notify_sock, RTNLGRP_IPV6_IFADDR);
        nl_socket_add_memberships(_nl_notify_sock, RTNLGRP_LINK);

        // create a cache for the links
        if (rtnl_link_alloc_cache(_nl_query_sock, AF_UNSPEC, &_link_cache) < 0)
        {
            nl_socket_free(_nl_notify_sock);
            nl_socket_free(_nl_query_sock);
            // error
            throw ibrcommon::vsocket_exception("netlink cache allocation failed");
        }

        // create a cache for addresses
        if (rtnl_addr_alloc_cache(_nl_query_sock, &_addr_cache) < 0)
        {
            nl_socket_free(_nl_notify_sock);
            nl_socket_free(_nl_query_sock);
            // error
            nl_cache_free(_link_cache);
            _link_cache = NULL;
            throw ibrcommon::vsocket_exception("netlink cache allocation failed");
        }

        // create a new socket for the netlink interface
        _sock = new ibrcommon::vsocket();
    }

    NetLink3Manager::~NetLink3Manager()
    {
        stop();
        join();

        // destroy the socket for the netlink interface
        delete _sock;

        nl_cache_free(_addr_cache);
        nl_cache_free(_link_cache);

        nl_socket_free(_nl_notify_sock);
        nl_socket_free(_nl_query_sock);
    }

    const std::string NetLink3Manager::getInterface(int index) const
    {
        char buf[256];
        rtnl_link_i2name(_link_cache, index, (char*)&buf, sizeof buf);
        return std::string((char*)&buf);
    }

    const std::list<vaddress> NetLink3Manager::getAddressList(const vinterface &iface, const vaddress::Family f)
    {
        ibrcommon::MutexLock l(_call_mutex);

        if (_refresh_cache)
        {
            nl_cache_free(_addr_cache);
            nl_cache_free(_link_cache);

            // create a cache for the links
            if (rtnl_link_alloc_cache(_nl_query_sock, AF_UNSPEC, &_link_cache) < 0)
            {
                // error
                throw ibrcommon::vsocket_exception("netlink cache allocation failed");
            }

            // create a cache for addresses
            if (rtnl_addr_alloc_cache(_nl_query_sock, &_addr_cache) < 0)
            {
                // error
                nl_cache_free(_link_cache);
                _link_cache = NULL;
                throw ibrcommon::vsocket_exception("netlink cache allocation failed");
            }

            // mark the cache as refreshed
            _refresh_cache = false;
        }

        std::list<vaddress> addresses;

        struct rtnl_addr *filter = rtnl_addr_alloc();
        const std::string i = iface.toString();
        rtnl_addr_set_ifindex(filter, rtnl_link_name2i(_link_cache, i.c_str()));

        if (f == vaddress::VADDRESS_UNSPEC)
        {
            rtnl_addr_set_family(filter, AF_INET6);
            nl_cache_foreach_filter(_addr_cache, (struct nl_object *) filter,
                                    add_addr_to_list, &addresses);

            rtnl_addr_set_family(filter, AF_INET);
            nl_cache_foreach_filter(_addr_cache, (struct nl_object *) filter,
                                    add_addr_to_list, &addresses);
        }
        else
        {
            rtnl_addr_set_family(filter, f);
            nl_cache_foreach_filter(_addr_cache, (struct nl_object *) filter,
                                    add_addr_to_list, &addresses);
        }

        rtnl_addr_put(filter);

        return addresses;
    }

    void NetLink3Manager::callback(const NetLink3ManagerEvent &lme)
    {
        // ignore if the event is unknown
        if (lme.getType() == LinkManagerEvent::EVENT_UNKOWN) return;

        // ignore if this is an wireless extension event
        if (lme.isWirelessExtension()) return;

        // need to refresh the cache
        {
            ibrcommon::MutexLock l(_call_mutex);
            _refresh_cache = true;
        }

        // print out some debugging
        IBRCOMMON_LOGGER_DEBUG(10) << lme.toString() << IBRCOMMON_LOGGER_ENDL;

        // notify all subscribers about this event
        raiseEvent(lme);
    }

    void NetLink3Manager::run()
    {
        // add netlink fd to vsocket
        _sock->add(nl_socket_get_fd(_nl_notify_sock));

        try {
            while (_running)
            {
                std::list<int> fds;
                _sock->select(fds, NULL);

                nl_recvmsgs_default(_nl_notify_sock);
            }
        } catch (const vsocket_exception&) {
            // stopped / interrupted
            IBRCOMMON_LOGGER(error) << "NetLink connection stopped" << IBRCOMMON_LOGGER_ENDL;
        }
    }

    void NetLink3Manager::__cancellation()
    {
        _running = false;
        _sock->close();
    }

    /** read a netlink message from the socket and create a new netlink event object **/
    NetLink3ManagerEvent::NetLink3ManagerEvent(struct nl_msg *msg)
     : _type(EVENT_UNKOWN), _state(0), _wireless(false)
    {
        int attrlen, nlmsg_len, rta_len, rtl;
        struct rtattr *attr;
        struct rtattr *rth;
        struct ifaddrmsg *ifa;
        struct ifinfomsg *ifi;
        struct nlmsghdr *nlh;

        // cast netlink message
        nlh = nlmsg_hdr(msg);

        switch (nlh->nlmsg_type)
        {
            case RTM_BASE:
            {
                ifi = (struct ifinfomsg *) NLMSG_DATA(nlh);

                nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
                attrlen = nlh->nlmsg_len - nlmsg_len;

                if (attrlen < 0) break;

                attr = (struct rtattr *) (((char *) ifi) + nlmsg_len);

                rta_len = RTA_ALIGN(sizeof(struct rtattr));
                while (RTA_OK(attr, attrlen))
                {
                    size_t rta_length = RTA_PAYLOAD(attr);

                    switch (attr->rta_type)
                    {
                    case IFLA_IFNAME:
                        _interface = ibrcommon::vinterface( std::string((char*)RTA_DATA(attr), rta_length) );
                        _type = EVENT_LINK_STATE;
                        break;

                    case IFLA_OPERSTATE:
                    {
                        char s;
                        ::memcpy(&s, (char*)RTA_DATA(attr), 1);
                        _state = s;
                        break;
                    }

                    case IFLA_WIRELESS:
                        _wireless = true;
                        break;

                    default:
                        _attributes[attr->rta_type] = std::string((char*)RTA_DATA(attr), rta_length);
                        break;
                    }

                    attr = RTA_NEXT(attr, attrlen);
                }
                break;
            }

            case RTM_NEWADDR:
            {
                ifa = (struct ifaddrmsg *) NLMSG_DATA(nlh);
                rth = IFA_RTA(ifa);
                rtl = IFA_PAYLOAD(nlh);

                // parse all attributes
                while (rtl && RTA_OK(rth, rtl))
                {
                    switch (rth->rta_type)
                    {
                        // local address
                        case IFA_LOCAL:
                        {
                            char address[256];

                            uint32_t ipaddr = htonl(*((uint32_t *)RTA_DATA(rth)));
                            sprintf(address, "%d.%d.%d.%d", (ipaddr >> 24) & 0xff, (ipaddr >> 16) & 0xff, (ipaddr >> 8) & 0xff, ipaddr & 0xff);

                            _address = ibrcommon::vaddress(ibrcommon::vaddress::VADDRESS_INET, std::string(address));
                            _type = EVENT_ADDRESS_ADDED;
                            break;
                        }

                        // interface name
                        case IFA_LABEL:
                        {
                            //char name[IFNAMSIZ];
                            char *name = (char *)RTA_DATA(rth);
                            _interface = ibrcommon::vinterface(name);
                            break;
                        }
                    }
                    rth = RTA_NEXT(rth, rtl);
                }
                break;
            }

            case RTM_DELADDR:
            {
                ifa = (struct ifaddrmsg *) NLMSG_DATA(nlh);
                rth = IFA_RTA(ifa);
                rtl = IFA_PAYLOAD(nlh);

                // parse all attributes
                while (rtl && RTA_OK(rth, rtl))
                {
                    switch (rth->rta_type)
                    {
                        // local address
                        case IFA_LOCAL:
                        {
                            char address[256];

                            uint32_t ipaddr = htonl(*((uint32_t *)RTA_DATA(rth)));
                            sprintf(address, "%d.%d.%d.%d", (ipaddr >> 24) & 0xff, (ipaddr >> 16) & 0xff, (ipaddr >> 8) & 0xff, ipaddr & 0xff);

                            _address = ibrcommon::vaddress(ibrcommon::vaddress::VADDRESS_INET, std::string(address));
                            _type = EVENT_ADDRESS_REMOVED;
                            break;
                        }

                        // interface name
                        case IFA_LABEL:
                        {
                            //char name[IFNAMSIZ];
                            char *name = (char *)RTA_DATA(rth);
                            _interface = ibrcommon::vinterface(name);
                            break;
                        }
                    }
                    rth = RTA_NEXT(rth, rtl);
                }
                break;
            }

            default:
                IBRCOMMON_LOGGER_DEBUG(10) << "unknown netlink type received: " << nlh->nlmsg_type << IBRCOMMON_LOGGER_ENDL;
                break;
        }
    }

    NetLink3ManagerEvent::~NetLink3ManagerEvent()
    {
    }

    const ibrcommon::vinterface& NetLink3ManagerEvent::getInterface() const
    {
        return _interface;
    }

    const ibrcommon::vaddress& NetLink3ManagerEvent::getAddress() const
    {
        return _address;
    }

    unsigned int NetLink3ManagerEvent::getState() const
    {
        return _state;
    }

    bool NetLink3ManagerEvent::isWirelessExtension() const
    {
        return _wireless;
    }

    LinkManagerEvent::EventType NetLink3ManagerEvent::getType() const
    {
        return _type;
    }

    const std::string NetLink3ManagerEvent::toString() const
    {
        std::stringstream ss;
        ss << "NetLinkManagerEvent on " << getInterface().toString() << "; Type: " << getType();

        switch (getType())
        {
        case EVENT_LINK_STATE:
            ss << "; State: " << getState();
            break;

        case EVENT_ADDRESS_ADDED:
            ss << "; Address added: " << getAddress().toString();
            break;

        case EVENT_ADDRESS_REMOVED:
            ss << "; Address removed: " << getAddress().toString();
            break;

        default:
            break;
        };

        return ss.str();
    }

    void NetLink3ManagerEvent::debug() const
    {
//      for (std::map<int, std::string>::const_iterator iter = attr.begin(); iter != attr.end(); iter++)
//      {
//          std::stringstream ss;
//          const std::string &value = (*iter).second;
//
//          for (std::string::const_iterator si = value.begin(); si != value.end(); si++)
//          {
//              const char &c = (*si);
//              ss << std::hex << "0x" << (int)c << " ";
//          }
//
//          IBRCOMMON_LOGGER_DEBUG(10) << (*iter).first << ": " << ss.str() << IBRCOMMON_LOGGER_ENDL;
//      }
    }
} /* namespace ibrcommon */

The eclipse output:

./ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:66:37: error: ‘nl_socket_alloc’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:70:46: error: ‘nl_socket_disable_seq_check’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:73:85: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘int nl_socket_modify_cb(nl_handle*, nl_cb_type, nl_cb_kind, nl_recvmsg_msg_cb_t, void*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:76:44: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘int nl_connect(nl_handle*, int)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:77:43: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘int nl_connect(nl_handle*, int)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:80:65: error: ‘nl_socket_add_memberships’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:87:68: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘nl_cache* rtnl_link_alloc_cache(nl_handle*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:89:34: error: ‘nl_socket_free’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:96:57: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘nl_cache* rtnl_addr_alloc_cache(nl_handle*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:98:34: error: ‘nl_socket_free’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp: In destructor ‘virtual ibrcommon::NetLink3Manager::~NetLink3Manager()’:
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:121:33: error: ‘nl_socket_free’ was not declared in this scope
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp: In member function ‘virtual const std::list<ibrcommon::vaddress> ibrcommon::NetLink3Manager::getAddressList(const ibrcommon::vinterface&, ibrcommon::vaddress::Family)’:
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:142:69: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘nl_cache* rtnl_link_alloc_cache(nl_handle*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:149:58: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘nl_cache* rtnl_addr_alloc_cache(nl_handle*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp: In member function ‘virtual void ibrcommon::NetLink3Manager::run()’:
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:213:46: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘int nl_socket_get_fd(nl_handle*)’
../ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.cpp:221:40: error: cannot convert ‘ibrcommon::nl_sock*’ to ‘nl_handle*’ for argument ‘1’ to ‘int nl_recvmsgs_default(nl_handle*)’
make: *** [ibrcommon-0.8.0/ibrcommon/net/NetLink3Manager.o] Error 1

There the headers of the function NetLink3Manager.h

#ifndef NETLINK3MANAGER_H_
#define NETLINK3MANAGER_H_

#include "ibrcommon/net/LinkManager.h"
#include "ibrcommon/thread/Mutex.h"
#include "ibrcommon/thread/Thread.h"
#include "ibrcommon/net/vsocket.h"

#include <netlink/netlink.h>
#include <netlink/socket.h>
#include <netlink/route/link.h>
#include <netlink/msg.h>

namespace ibrcommon
{
    class NetLink3ManagerEvent : public LinkManagerEvent
    {
    public:
        NetLink3ManagerEvent(struct nl_msg *msg);
        virtual ~NetLink3ManagerEvent();

        virtual const ibrcommon::vinterface& getInterface() const;
        virtual const ibrcommon::vaddress& getAddress() const;
        virtual unsigned int getState() const;
        virtual EventType getType() const;

        virtual bool isWirelessExtension() const;

        void debug() const;
        const std::string toString() const;

    private:
        EventType _type;
        unsigned int _state;
        bool _wireless;
        ibrcommon::vinterface _interface;
        ibrcommon::vaddress _address;
        std::map<int, std::string> _attributes;
    };

    class NetLink3Manager : public ibrcommon::LinkManager, public ibrcommon::JoinableThread
    {
        friend class LinkManager;

    public:
        virtual ~NetLink3Manager();

        const std::string getInterface(int index) const;
        const std::list<vaddress> getAddressList(const vinterface &iface, const vaddress::Family f);

        class parse_exception : public Exception
        {
        public:
            parse_exception(string error) : Exception(error)
            {};
        };

        void callback(const NetLink3ManagerEvent &evt);

    protected:
        void run();
        void __cancellation();

    private:
        NetLink3Manager();

        struct nl_sock *_nl_notify_sock;
        struct nl_sock *_nl_query_sock;

        // local link cache
        struct nl_cache *_link_cache;
        struct nl_cache *_addr_cache;

        // mutex for the link cache
        ibrcommon::Mutex _call_mutex;

        bool _refresh_cache;
        bool _running;

        ibrcommon::vsocket *_sock;
    };
} /* namespace ibrcommon */
#endif /* NETLINK3MANAGER_H_ */

Body:
somehow necro - but I just stumbled over the same issue - so maybe this can help someone.

First of all: you need to install the libnetlink development headers.
On my ancient Debian 8 box

> sudo apt-get install libnl-3-dev

does the trick.

The documentation of the netlink library contains a part about the library structure. In this part you can find all information about required headers and how to link against the library. It basically boils down to include netlink/netlink.h. But sometimes (as on my Debian box) the devel package is installed but the directory containing the header files are not part of the default search path. You could run a find over your entire filesystem looking for netlink.h - this could give you a wrong direction (of course - if you dig out something using find you would always check twice to include the right file). But there is a more systematic approach available...

Provided you run a box using the Debian packaging system, you can check what netlink libraries are installed:

> dpkg --list libnl*
...
ii  libnl-3-200:amd64               3.2.24-2             amd64                library for dealing with netlink sockets
ii  libnl-3-dev                     3.2.24-2             amd64                development library and headers for libnl-3
un  libnl-dev                       <none>               <none>               (no description available)
ii  libnl-genl-3-200:amd64          3.2.24-2             amd64                library for dealing with netlink sockets - generic netlink
ii  libnl-route-3-200:amd64         3.2.24-2             amd64                library for dealing with netlink sockets - route interface
un  libnl2-dev                      <none>               <none>               (no description available)
un  libnl3-dev                      <none>               <none>               (no description available)

The one(s) with the leading ii are the relevant ones. Now use dpkg to get a list of the files provided by the package (and filter for the required one):

> dpkg  -L  libnl-3-dev | grep  "netlink\.h"

/usr/include/libnl3/netlink/netlink.h

As /usr/include/ is part of the default include paths (you can check the paths used by gcc using the answer given here) you would need to add the prefix libnl3 to your include statements. To prevent yourself from the need to change the includes if the library version changes, simply add /usr/include/libnl3 to your include path. For gcc this can be done using the flag

-I /usr/include/libnl3

and for a cmake based build system just add a include_diretories() directive:

include_directories("/usr/include/libnl3")


问:
How to assign colors according to median value in box plot?
I have an issue with a color palette of my box plot. I want that the colors get assigned according to median values. The higher is the median value, the darker is a color. I selected the palette YlGnBu. However, colors are assigned just as a gradient - darker colors are on the right, while lighter colors are on the left:

```<code>df = sns.load_dataset("tips")

norm = plt.Normalize(df["total_bill"].values.min(), df["total_bill"].values.max())
colors = plt.cm.YlGnBu(norm(df["total_bill"]))
flierprops = dict(markerfacecolor='0.75', markersize=5,linestyle='none')

plt.figure(figsize=(12,8))
ax = sns.boxplot(x="day", y="total_bill", data=df,
                 palette=colors,
                 flierprops=flierprops) # hue="smoker",
plt.xticks(rotation='vertical')
ax.get_xaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x,p: str(x)+":00"))
ax.get_yaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x,p: locale.format('%d', x, 1)))
ax.grid(b=True, which='major', color='#d3d3d3', linewidth=1.0)
ax.grid(b=True, which='minor', color='#d3d3d3', linewidth=0.5)
plt.show()
</code>```

答:
Your problem is that your setting up your colormap based on the whole range of total_bill values in your dataframe. If you want the colormap to reflect the median values per day of the week, you have to set up using those median values.

```<code>df = sns.load_dataset("tips")

median_vals = df.groupby('day')['total_bill'].median()
norm = plt.Normalize(median_vals.min(), median_vals.max())
colors = plt.cm.YlGnBu(norm(median_vals))

plt.figure(figsize=(12,8))
ax = sns.boxplot(x="day", y="total_bill", data=df, palette=colors)
plt.show()
</code>```

Body:
I have an issue with a color palette of my box plot. I want that the colors get assigned according to median values. The higher is the median value, the darker is a color. I selected the palette YlGnBu. However, colors are assigned just as a gradient - darker colors are on the right, while lighter colors are on the left:

df = sns.load_dataset("tips")

norm = plt.Normalize(df["total_bill"].values.min(), df["total_bill"].values.max())
colors = plt.cm.YlGnBu(norm(df["total_bill"]))
flierprops = dict(markerfacecolor='0.75', markersize=5,linestyle='none')

plt.figure(figsize=(12,8))
ax = sns.boxplot(x="day", y="total_bill", data=df,
                 palette=colors,
                 flierprops=flierprops) # hue="smoker",
plt.xticks(rotation='vertical')
ax.get_xaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x,p: str(x)+":00"))
ax.get_yaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x,p: locale.format('%d', x, 1)))
ax.grid(b=True, which='major', color='#d3d3d3', linewidth=1.0)
ax.grid(b=True, which='minor', color='#d3d3d3', linewidth=0.5)
plt.show()

Body:
Your problem is that your setting up your colormap based on the whole range of total_bill values in your dataframe. If you want the colormap to reflect the median values per day of the week, you have to set up using those median values.

df = sns.load_dataset("tips")

median_vals = df.groupby('day')['total_bill'].median()
norm = plt.Normalize(median_vals.min(), median_vals.max())
colors = plt.cm.YlGnBu(norm(median_vals))

plt.figure(figsize=(12,8))
ax = sns.boxplot(x="day", y="total_bill", data=df, palette=colors)
plt.show()


问:
How Google App Engine limit Python?
Does anybody know, how GAE limit Python interpreter? For example, how they block IO operations, or URL operations.

Shared hosting also do it in some way?

答:
From Google's site:

An application can only access other
computers on the Internet through the
provided URL fetch and email
services. Other computers can only
connect to the application by making
HTTP (or HTTPS) requests on the
standard ports.

An application cannot write to the
file system. An app can read files,
but only files uploaded with the
application code. The app must use
the App Engine datastore, memcache or
other services for all data that
persists between requests.

Application code only runs in
response to a web request, a queued
task, or a scheduled task, and must
return response data within 30
seconds in any case. A request
handler cannot spawn a sub-process or
execute code after the response has
been sent.

Beyond that, you're stuck with Python 2.5, you can't use any C-based extensions, more up-to-date versions of web frameworks won't work in some cases (Python 2.5 again).

You can read the whole article What is Google App Engine?.

ContentLicense: CC BY-SA 2.5

Title: How Google App Engine limit Python?


问:
Safety of ptrace on x86_64
From Wikipedia:

long: Long signed integer type. Capable of containing at least the [−2,147,483,647, +2,147,483,647] range; thus, it is at least 32 bits in size.

From man ptrace:

```<code>long ptrace(enum __ptrace_request request, pid_t pid,
            void *addr, void *data);
</code>```

Remember that signed overflow is undefined behavior in C. The registers on x86_64 store 64-bit values.

Is it thus unsafe to read the contents of the registers (e.g. ORIG_RAX) with ptrace on x86_64?

答:
ptrace() is not specified in POSIX. It's available on Linux and some other systems, all of which have in common that they use the LP64 data model on x86_64. With these platforms, you have 64bit long. So, this is safe.

(Windows on the other hand uses LLP64, only long long is 64bit on x86_64)

Title: Safety of ptrace on x86_64

Body:
From Wikipedia:

long: Long signed integer type. Capable of containing at least the [−2,147,483,647, +2,147,483,647] range; thus, it is at least 32 bits in size.

From man ptrace:

long ptrace(enum __ptrace_request request, pid_t pid,
            void *addr, void *data);

Remember that signed overflow is undefined behavior in C. The registers on x86_64 store 64-bit values.

Is it thus unsafe to read the contents of the registers (e.g. ORIG_RAX) with ptrace on x86_64?


问:
DI Constructor Injection Neatness
Okay so I am looking for some specific tips about Dependency Injection and how to use it.

Basically I have a MVC website which uses Ninject (and the Ninject MVC package). So when I am creating the MVC page I use constructor injection in the controllers. This is okay but IMO a bit 'ugly', but the main thing I don't like is having to pass all of the injected repositories into the other classes, it just seems a bit OTT having to pass like 6 repositories-8 repositories into a static method or object constructor.

Not to mention that on some of my pages I am having to work on almost every repository so the controller consructor gets huge and not the most manageable.

Are there any other options that wont clutter my code up as much? I don't really want to pass them in as single 'setting' objects either as that just moves the problem to a different line of code.

I also use the same class libraries for console/desktop applications. I like the idea of using DependencyResolver.Current in the class libraries but everyone says this is an anti-pattern and constructor injection should be used.

Maybe have an MyProjectDIContext class which has a dictionary which i can populate with the injected types in the controller constructors then pass the context to all methods as needed?

I have had a look for the answer bit I can't quite seem to find something that fits well.

答:
It seems that your controller is shuffling repositories to other classes. Let Ninject supply those classes to you instead:

```<code>public class Controller
{
    public Controller(IDependencyFactory dependency) { }
}

public interface IDependencyFactory
{
    IDependency CreateDependency();
}

public interface IDependency
{
}

public class Dependency : IDependency
{
    public Dependency() { }
}

public class Program
{
    public static void Main()
    {
        var standardKernel = new StandardKernel();
        standardKernel.Bind<IDependencyFactory>().ToFactory();
        standardKernel.Bind<IDependency>().To<Dependency>();
    }
}
</code>```

You don't have to write an implementation of IDependencyFactory, that is handled by the factory extension. Your Dependency-class will get it's dependencies injected by Ninject.

Title: DI Constructor Injection Neatness

Body:
It seems that your controller is shuffling repositories to other classes. Let Ninject supply those classes to you instead:

public class Controller
{
    public Controller(IDependencyFactory dependency) { }
}

public interface IDependencyFactory
{
    IDependency CreateDependency();
}

public interface IDependency
{
}

public class Dependency : IDependency
{
    public Dependency() { }
}

public class Program
{
    public static void Main()
    {
        var standardKernel = new StandardKernel();
        standardKernel.Bind<IDependencyFactory>().ToFactory();
        standardKernel.Bind<IDependency>().To<Dependency>();
    }
}

You don't have to write an implementation of IDependencyFactory, that is handled by the factory extension. Your Dependency-class will get it's dependencies injected by Ninject.


问:
Get object property name as a string
Is it possible to get the object property name as a string

```<code>person = {};
person.first_name = 'Jack';
person.last_name = 'Trades';
person.address = {};
person.address.street = 'Factory 1';
person.address.country = 'USA';
</code>```

I'd like to use it like this:

```<code>var pn = propName( person.address.country ); // should return 'country' or 'person.address.country'
var pn = propName( person.first_name );      // should return 'first_name' or 'person.first_name'
</code>```

NOTE: this code is exactly what I'm looking for. I understand it sounds even stupid, but it's not.

This is what I want to do with it.

HTML

```<code>person = {};
person.id_first_name = 'Jack';
person.id_last_name = 'Trades';
person.address = {};
person.address.id_address = 'Factory 1';
person.address.id_country = 'USA';

extPort.postMessage
(
  {
    message : MSG_ACTION,
    propName( person.first_name ): person.first_name
  }
};
</code>```

----------------------ANSWER-----------------------

Got it thanks to ibu. He pointed the right way and I used a recursive function

```<code>var res = '';

function propName(prop, value) {
    for (var i in prop) {
        if (typeof prop[i] == 'object') {
            if (propName(prop[i], value)) {
                return res;
            }
        } else {
            if (prop[i] == value) {
                res = i;
                return res;
            }
        }
    }
    return undefined;
}

var pn = propName(person, person.first_name); // returns 'first_name'
var pn = propName(person, person.address.country); // returns 'country'
</code>```

DEMO: http://jsbin.com/iyabal/1/edit

答:
I am in same situation.

Here is thy way to get it done using Lodash or UnderScore library, with one limitation of value to be unique:

```<code>var myObject = {
'a': 1,
'b': 2,
'c': 3
}
_.findKey(myObject, function( curValue ) { return myObject.a === curValue });
</code>```

Plain JavaScript

```<code>function getPropAsString( source, value ){
    var keys = Object.keys( source );

    var curIndex,
        total,
        foundKey;

    for(curIndex = 0, total = keys.length; curIndex < total; curIndex++){
        var curKey = keys[ curIndex ];
        if ( source[ curKey ] === value ){
            foundKey = curKey;
            break;
        }
    }

    return foundKey;
}

var myObject = {
'a': 1,
'b': 2,
'c': 3
}
getPropAsString( myObject, myObject.a )
</code>```

But, I would prefer to fix the code as solution. An example:

```<code>var myObject = {
'a': {key:'a', value:1},
'b': {key:'b', value:2},
'c': {key:'c', value:3}
}

console.log( myObject.a.key )
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get object property name as a string

Body:
Is it possible to get the object property name as a string

person = {};
person.first_name = 'Jack';
person.last_name = 'Trades';
person.address = {};
person.address.street = 'Factory 1';
person.address.country = 'USA';

I'd like to use it like this:

var pn = propName( person.address.country ); // should return 'country' or 'person.address.country'
var pn = propName( person.first_name );      // should return 'first_name' or 'person.first_name'

NOTE: this code is exactly what I'm looking for. I understand it sounds even stupid, but it's not.

This is what I want to do with it.

HTML

person = {};
person.id_first_name = 'Jack';
person.id_last_name = 'Trades';
person.address = {};
person.address.id_address = 'Factory 1';
person.address.id_country = 'USA';

extPort.postMessage
(
  {
    message : MSG_ACTION,
    propName( person.first_name ): person.first_name
  }
};

----------------------ANSWER-----------------------

Got it thanks to ibu. He pointed the right way and I used a recursive function

var res = '';

function propName(prop, value) {
    for (var i in prop) {
        if (typeof prop[i] == 'object') {
            if (propName(prop[i], value)) {
                return res;
            }
        } else {
            if (prop[i] == value) {
                res = i;
                return res;
            }
        }
    }
    return undefined;
}

var pn = propName(person, person.first_name); // returns 'first_name'
var pn = propName(person, person.address.country); // returns 'country'

DEMO: http://jsbin.com/iyabal/1/edit

Body:
I am in same situation.

Here is thy way to get it done using Lodash or UnderScore library, with one limitation of value to be unique:

var myObject = {
'a': 1,
'b': 2,
'c': 3
}
_.findKey(myObject, function( curValue ) { return myObject.a === curValue });

Plain JavaScript

function getPropAsString( source, value ){
    var keys = Object.keys( source );

    var curIndex,
        total,
        foundKey;

    for(curIndex = 0, total = keys.length; curIndex < total; curIndex++){
        var curKey = keys[ curIndex ];
        if ( source[ curKey ] === value ){
            foundKey = curKey;
            break;
        }
    }

    return foundKey;
}

var myObject = {
'a': 1,
'b': 2,
'c': 3
}
getPropAsString( myObject, myObject.a )

But, I would prefer to fix the code as solution. An example:

var myObject = {
'a': {key:'a', value:1},
'b': {key:'b', value:2},
'c': {key:'c', value:3}
}

console.log( myObject.a.key )


问:
Compare two arrays contains integers, return the difference
I want to compare 2 arrays with integers.

what I have:

```<code>function findDeletedNumber(array $arr, array $mixedArr): int {
  $diff = array_diff($arr, $mixedArr);
  if ($diff != NULL) { return($diff); }
  return 0;
}
</code>```

But the problem is that I need to return the difference as a string. Not an array. the difference is always gonna be only one value

答:
Based on your function name, you are returning one number at most, you can use current() like this:</p>

```<code>return ($diff=array_diff($arr,$mixedArr))?current($diff):0;
</code>```

Body:
I want to compare 2 arrays with integers.

what I have:

function findDeletedNumber(array $arr, array $mixedArr): int {
  $diff = array_diff($arr, $mixedArr);
  if ($diff != NULL) { return($diff); }
  return 0;
}

But the problem is that I need to return the difference as a string. Not an array. the difference is always gonna be only one value

Body:
Based on your function name, you are returning one number at most, you can use current() like this:

return ($diff=array_diff($arr,$mixedArr))?current($diff):0;


问:
making a directory and then cd'ing in it directly without a new command
So I am making a Bash Script to make a timestamp directory but the problem I am facing is that it makes a timestamp directory but doesn't cd's into it here is the code:

```<code>#!/bin/bash
now=$(date +"%Y-%m-%d-%S")
mkcd () {
   mkdir "$now"
   cd "$now"
}
mkdir /var/mobile/backup
cd /var/mobile/backup
mkcd /var/mobile/backup/$now
echo yep
</code>```

by the way this script is for ios

答:
I think the simplest way to do this is to use $_, which basically represents the last argument of the preceding command.

```<code>now=$(date +"%Y-%m-%d-%S")
mkcd () {mkdir $now && cd $_}
</code>```

As a sidenote I would put the now variable inside the function, so that mkcd does not depend on variables created outside of the function itself

```<code>mkcd () {
    now=$(date +"%Y-%m-%d-%S")
    mkdir $1$now && cd $_
}
</code>```

Example call:

```<code>mkcd ~/
</code>```

This creates a directory /home/yourusername/2017-07-07-27 for example.

Body:
So I am making a Bash Script to make a timestamp directory but the problem I am facing is that it makes a timestamp directory but doesn't cd's into it here is the code:

#!/bin/bash
now=$(date +"%Y-%m-%d-%S")
mkcd () {
   mkdir "$now"
   cd "$now"
}
mkdir /var/mobile/backup
cd /var/mobile/backup
mkcd /var/mobile/backup/$now
echo yep

by the way this script is for ios

Body:
I think the simplest way to do this is to use $_, which basically represents the last argument of the preceding command.

now=$(date +"%Y-%m-%d-%S")
mkcd () {mkdir $now && cd $_}

As a sidenote I would put the now variable inside the function, so that mkcd does not depend on variables created outside of the function itself

mkcd () {
    now=$(date +"%Y-%m-%d-%S")
    mkdir $1$now && cd $_
}

Example call:

mkcd ~/

This creates a directory /home/yourusername/2017-07-07-27 for example.


问:
Push an element at the end of an array
I have an array called result which I generate like this

```<code> while something
           $result[] = $row;
           array_push($result,$row['fld_ConsumptionValue'] * $energy_type_unit_price) // this won't do
    endwhile
</code>```

$result array is filled with db records. What I wanna do is to push another value I calculated like above. output is like this:

```<code>    result -> Array[6]
    [0] -> Array[34]
    [1] -> Calculated Value For 1st Record
    [2] -> Array[34]
    [3] -> Calculated Value For 2nd Record
...
...
...
</code>```

What I'm trying is to get this output

```<code> result -> Array[6]
    [0] -> Array[35]
    [1] -> Array[35]
...
...
</code>```

What am I doing wrong?

答:
You don't need to do this, instead do it in the simple way:

```<code>$result[] = $row['fld_ConsumptionValue'] * $energy_type_unit_price;
</code>```

The above will add the value to the end of the array. If you want to use the array Array[34], add that then. Not sure how do you generate that array with 34 items. Or if I get it right, you gotta do this:

```<code>$row [] = $row['fld_ConsumptionValue'] * $energy_type_unit_price
$result[] = $row;
</code>```

The above adds the new one to the $row and you add all the 35 to the main $result.

Title: Push an element at the end of an array

Body:
I have an array called result which I generate like this

 while something
           $result[] = $row;
           array_push($result,$row['fld_ConsumptionValue'] * $energy_type_unit_price) // this won't do
    endwhile

$result array is filled with db records. What I wanna do is to push another value I calculated like above. output is like this:

    result -> Array[6]
    [0] -> Array[34]
    [1] -> Calculated Value For 1st Record
    [2] -> Array[34]
    [3] -> Calculated Value For 2nd Record
...
...
...

What I'm trying is to get this output

 result -> Array[6]
    [0] -> Array[35]
    [1] -> Array[35]
...
...

What am I doing wrong?

Body:
You don't need to do this, instead do it in the simple way:

$result[] = $row['fld_ConsumptionValue'] * $energy_type_unit_price;

The above will add the value to the end of the array. If you want to use the array Array[34], add that then. Not sure how do you generate that array with 34 items. Or if I get it right, you gotta do this:

$row [] = $row['fld_ConsumptionValue'] * $energy_type_unit_price
$result[] = $row;

The above adds the new one to the $row and you add all the 35 to the main $result.


问:
CSS underline animation - Reading direction
I found a code to animate the underline of a link but I would like to be on the other direction, as we read (left to right) which is actually the opposite. Here is a JSFiddle

.sliding-u-l-r-l-inverse {
  display: inline-block;
  position: relative;
  padding-bottom: 3px;
}

.sliding-u-l-r-l-inverse:before {
  content: '';
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  transition: width 0s ease;
}

.sliding-u-l-r-l-inverse:after {
  content: '';
  display: block;
  position: absolute;
  right: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:before {
  width: 0%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:after {
  width: 0%;
  background: transparent;
  transition: width 0s ease;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sliding-u-l-r-l-inverse">
  I want it to slide on the other direction.
</div></code>```

答:
.sliding-u-l-r-l-inverse {
  display: inline-block;
  position: relative;
  padding-bottom: 3px;
}

.sliding-u-l-r-l-inverse:before {
  content: '';
  display: block;
  position: absolute;
  right: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  transition: width 0s ease;
}

.sliding-u-l-r-l-inverse:after {
  content: '';
  display: block;
  position: absolute;
  left: 0; /* changed from 'right' */
  bottom: 0;
  height: 3px;
  width: 100%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:before {
  width: 0%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:after {
  width: 0%;
  background: transparent;
  transition: width 0s ease;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sliding-u-l-r-l-inverse">
  I want it to slide on the other direction.
</div></code>```

Body:
I found a code to animate the underline of a link but I would like to be on the other direction, as we read (left to right) which is actually the opposite. Here is a JSFiddle

.sliding-u-l-r-l-inverse {
  display: inline-block;
  position: relative;
  padding-bottom: 3px;
}

.sliding-u-l-r-l-inverse:before {
  content: '';
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  transition: width 0s ease;
}

.sliding-u-l-r-l-inverse:after {
  content: '';
  display: block;
  position: absolute;
  right: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:before {
  width: 0%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:after {
  width: 0%;
  background: transparent;
  transition: width 0s ease;
}

  I want it to slide on the other direction.

Body:
.sliding-u-l-r-l-inverse {
  display: inline-block;
  position: relative;
  padding-bottom: 3px;
}

.sliding-u-l-r-l-inverse:before {
  content: '';
  display: block;
  position: absolute;
  right: 0;
  bottom: 0;
  height: 3px;
  width: 100%;
  transition: width 0s ease;
}

.sliding-u-l-r-l-inverse:after {
  content: '';
  display: block;
  position: absolute;
  left: 0; /* changed from 'right' */
  bottom: 0;
  height: 3px;
  width: 100%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:before {
  width: 0%;
  background: blue;
  transition: width .8s ease;
}

.sliding-u-l-r-l-inverse:hover:after {
  width: 0%;
  background: transparent;
  transition: width 0s ease;
}

<div class="sliding-u-l-r-l-inverse">
  I want it to slide on the other direction.
</div>


问:
Azure private build agent : No agent could be found with the following capabilities: npm, azureps
I am trying to use a local server as a build agent to build a project. The server already has

VS 2015,

VS 2017

Node 6,7,8 via NVM

NPM 4,5,6 via NVM

I can build the project locally via npm build or yarn build.

I have downloaded and configured and registered the private build agent already and I have it in the agent pool in the portal - xxx.visualstudio.com/xxx.

But when I try to schedule a build from the portal the following message is displayed :

No agent could be found with the following capabilities: npm, azureps

What do I need to fix so the build can run locally?

答:
The problem was simple - I did not see where the Capabilities tab was. IMHO Requests and Capabilities are not easily discoverable. I saw it and I set the two variables to true and it started to work even though I did not know for sure if true is the right value.

Another problem was that NVM SYMLINK was not working as expected and the build agent could not find node.exe at all. It was not in the PATH at all. I uninstalled nvm and used only node 8.1.2 with npm 5 in order to make it run.

UPDATE
As of today you can add a 'node tool installer' task to your definition - this is the better solution that is available today as D.J. points out in the comment section.


问:
Calling to lambda function in structure
I have a structure that defines the lambda function. Below is the code for that structure

AccumulateUtils.cpp file

```<code>#include <functional>

template <typename T>
struct AccumulateUtils {
        std::function<T()> add_first = [] (T value, const T& pair) {
            return value + pair.first;
        };
};
</code>```

In the main() this structure is used with std::accumulate to count sum of first indexes of map. Here is the code:

main.cpp file

```<code>#include <iostream>
#include <map>
#include <numeric>
#include "AccumulateUtils.cpp"

int main() {
    std::map<double, int> data = /*some map*/;
    AccumulateUtils<double> utils;

    std::cout << std::accumulate(data.begin(), data.end(), 0.0, utils.add_first);

    return 0;
}
</code>```

Сompiler gives the following errors:

Error C2228   left of '.first' must have class/struct/union

  Error C2664   'std::function::function(std::function
  &&)': cannot convert argument 1 from
  'AccumulateUtils::'
  to 'std::nullptr_t

Why were these errors? What's wrong in the code?

答:
Your lambda function has the signature ???(T, T const &) which is not covertible to T(), the signature of the std::function.
In addition, the lambda itself is broken, because T cannot be both a value and a pair of values. Something like

```<code>std::function<T(T, std::pair<T, T> const &)> fun =
[](T value, std::pair<T, T> const & pair)
{
  return value + pair.first;
};
</code>```

works but I'm not sure that is what you want to accomplish.

Title: Calling to lambda function in structure

Body:
I have a structure that defines the lambda function. Below is the code for that structure

AccumulateUtils.cpp file

#include <functional>

template <typename T>
struct AccumulateUtils {
        std::function<T()> add_first = [] (T value, const T& pair) {
            return value + pair.first;
        };
};

In the main() this structure is used with std::accumulate to count sum of first indexes of map. Here is the code:

main.cpp file

#include <iostream>
#include <map>
#include <numeric>
#include "AccumulateUtils.cpp"

int main() {
    std::map<double, int> data = /*some map*/;
    AccumulateUtils<double> utils;

    std::cout << std::accumulate(data.begin(), data.end(), 0.0, utils.add_first);

    return 0;
}

Сompiler gives the following errors:

Error C2228   left of '.first' must have class/struct/union

  Error C2664   'std::function::function(std::function
  &&)': cannot convert argument 1 from
  'AccumulateUtils::'
  to 'std::nullptr_t

Why were these errors? What's wrong in the code?

Body:
Your lambda function has the signature ???(T, T const &) which is not covertible to T(), the signature of the std::function.
In addition, the lambda itself is broken, because T cannot be both a value and a pair of values. Something like

std::function<T(T, std::pair<T, T> const &)> fun =
[](T value, std::pair<T, T> const & pair)
{
  return value + pair.first;
};

works but I'm not sure that is what you want to accomplish.