问:
WPF Custom ComboBox Showing "System.Windows.Styles" on item
I created a custom WPF ComboBox like this:

```<code><ComboBox
    x:Name="ComboBoxBtn"
    VerticalAlignment="Top"
    HorizontalAlignment="Left"
    Margin="0,0,0,-1"
    Width="300"
    ItemsSource="{Binding Source, RelativeSource={RelativeSource AncestorType=UserControl}}"
    SelectedItem="{Binding Path=Selected, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=UserControl}}"
        IsSynchronizedWithCurrentItem="True">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <ContentControl>
                    <Style TargetType="ContentControl">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Favorite}" Value="True">
                                <Setter Property="Content">
                                    <Setter.Value>
                                        <Grid>
                                            <Grid.Style>
                                                <Style TargetType="Grid">
                                                    <Setter Property="Background" Value="#FFE6E6FA"/>
                                                </Style>
                                            </Grid.Style>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="Auto" />
                                                <ColumnDefinition Width="Auto" />
                                            </Grid.ColumnDefinitions>
                                            <Label Content="{Binding}" Width="250" />
                                            <Button Grid.Column="1" Command="{Binding AddCommandButton, ElementName=root}"
                                                CommandParameter="{Binding}">+</Button>
                                        </Grid>
                                    </Setter.Value>
                                </Setter>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding Favorite}" Value="False">
                                <Setter Property="Content">
                                    <Setter.Value>
                                        <Grid>
                                            <Grid.Style>
                                                <Style TargetType="Grid">
                                                    <Setter Property="Background" Value="Yellow"/>
                                                </Style>
                                            </Grid.Style>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="Auto" />
                                                <ColumnDefinition Width="Auto" />
                                            </Grid.ColumnDefinitions>
                                            <Label Content="{Binding}" Width="250" />
                                            <Button Grid.Column="1" Command="{Binding RemoveCommandButton, ElementName=root}"
                                                CommandParameter="{Binding}">-</Button>
                                        </Grid>
                                    </Setter.Value>
                                </Setter>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </ContentControl>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
</code>```

The Source binding contains a ObservableColleciton where the client has a Favorite field and is supposed to show a different background and a different button. But when I open the ComboBox all the items have:

"System.Windows.Styles"

答:
In my case, I found that I had:

```<code><ComboBox>
    <Style>
    </Style>
</ComboBox>
</code>```

which was directly adding a style as an item, which is similar to the solution above.

Body:
I created a custom WPF ComboBox like this:

<ComboBox
    x:Name="ComboBoxBtn"
    VerticalAlignment="Top"
    HorizontalAlignment="Left"
    Margin="0,0,0,-1"
    Width="300"
    ItemsSource="{Binding Source, RelativeSource={RelativeSource AncestorType=UserControl}}"
    SelectedItem="{Binding Path=Selected, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=UserControl}}"
        IsSynchronizedWithCurrentItem="True">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <ContentControl>

                                            </Grid.Style>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="Auto" />
                                                <ColumnDefinition Width="Auto" />
                                            </Grid.ColumnDefinitions>

                                            <Button Grid.Column="1" Command="{Binding AddCommandButton, ElementName=root}"
                                                CommandParameter="{Binding}">+</Button>
                                        </Grid>
                                    </Setter.Value>
                                </Setter>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding Favorite}" Value="False">
                                <Setter Property="Content">
                                    <Setter.Value>
                                        <Grid>
                                            <Grid.Style>

                                            </Grid.Style>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="Auto" />
                                                <ColumnDefinition Width="Auto" />
                                            </Grid.ColumnDefinitions>

                                            <Button Grid.Column="1" Command="{Binding RemoveCommandButton, ElementName=root}"
                                                CommandParameter="{Binding}">-</Button>
                                        </Grid>
                                    </Setter.Value>
                                </Setter>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </ContentControl>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

The Source binding contains a ObservableColleciton where the client has a Favorite field and is supposed to show a different background and a different button. But when I open the ComboBox all the items have:

"System.Windows.Styles"

Body:
In my case, I found that I had:

<ComboBox>
    <Style>
    </Style>
</ComboBox>

which was directly adding a style as an item, which is similar to the solution above.


来源: stackexchange

问:
SQLAlchemy - Multiple Foreign key pointing to same table same attribute
My data base structure....

```<code>class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    user = db.relationship("BankSlip", back_populates="person_user")
    reference = db.relationship("BankSlip", back_populates="person_reference")

class BankSlip(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    person_user_id = db.Column(db.Integer, db.ForeignKey(Person.id))
    person_ref_id = db.Column(db.Integer, db.ForeignKey(Person.id))

    person_user = db.relationship("Person", back_populates="user", uselist=False, foreign_keys=[person_user_id])
    person_reference = db.relationship("Person", back_populates="reference", uselist=False, foreign_keys=[person_ref_id])
</code>```

I get the following errors while running at sqlite with Flask-SQLAlchemy

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Person.user - there are multiple foreign key paths linking the tables.  Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.

Here is my pip freeze

```<code>appdirs==1.4.3
APScheduler==3.3.1
bcrypt==3.1.3
blinker==1.4
cffi==1.9.1
click==6.7
cssselect==1.0.1
cssutils==1.0.2
Flask==0.12
Flask-Login==0.4.0
Flask-Mail==0.9.1
Flask-Principal==0.4.0
Flask-SQLAlchemy==2.2
Flask-WTF==0.14.2
gunicorn==19.7.1
itsdangerous==0.24
Jinja2==2.9.5
lxml==3.7.3
MarkupSafe==1.0
nose==1.3.7
packaging==16.8
pkg-resources==0.0.0
premailer==3.0.1
pycparser==2.17
pyparsing==2.2.0
python-dateutil==2.6.0
pytz==2017.2
requests==2.13.0
schedule==0.4.2
six==1.10.0
SQLAlchemy==1.1.6
tzlocal==1.4
uWSGI==2.0.15
Werkzeug==0.12.1
WTForms==2.1
</code>```

Edit: One BankSlip can have one user and one reference.... It should be a one-to-one relationship where parent -> child is BankSlip -> User or BankSlip -> Reference. So, a child can have multiple parents!

答:
Provide the required foreign_keys argument, as instructed by the error message:

```<code>class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    user = db.relationship("BankSlip", foreign_keys='BankSlip.person_user_id', back_populates="person_user")
    reference = db.relationship("BankSlip", foreign_keys='BankSlip.person_ref_id', back_populates="person_reference")
</code>```

With Declarative you can define the foreign keys as a string, which will help in resolving the circular dependency. Alternatively you could use backref instead of back_populates:

```<code>class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class BankSlip(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    person_user_id = db.Column(db.Integer, db.ForeignKey(Person.id))
    person_ref_id = db.Column(db.Integer, db.ForeignKey(Person.id))

    person_user = db.relationship("Person", backref="user", uselist=False, foreign_keys=[person_user_id])
    person_reference = db.relationship("Person", backref="reference", uselist=False, foreign_keys=[person_ref_id])
</code>```

Note that you've got the uselist=False at the wrong end of the relationship, or it is redundant, since a Person can be referenced by multiple BankSlips. It belongs at Persons's side, so:

```<code>from sqlalchemy.orm import backref

...
    person_user = db.relationship("Person", backref=backref("user", uselist=False), foreign_keys=[person_user_id])
    person_reference = db.relationship("Person", backref=backref("reference", uselist=False), foreign_keys=[person_ref_id])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My data base structure....

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    user = db.relationship("BankSlip", back_populates="person_user")
    reference = db.relationship("BankSlip", back_populates="person_reference")

class BankSlip(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    person_user_id = db.Column(db.Integer, db.ForeignKey(Person.id))
    person_ref_id = db.Column(db.Integer, db.ForeignKey(Person.id))

    person_user = db.relationship("Person", back_populates="user", uselist=False, foreign_keys=[person_user_id])
    person_reference = db.relationship("Person", back_populates="reference", uselist=False, foreign_keys=[person_ref_id])

I get the following errors while running at sqlite with Flask-SQLAlchemy

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Person.user - there are multiple foreign key paths linking the tables.  Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.

Here is my pip freeze

appdirs==1.4.3
APScheduler==3.3.1
bcrypt==3.1.3
blinker==1.4
cffi==1.9.1
click==6.7
cssselect==1.0.1
cssutils==1.0.2
Flask==0.12
Flask-Login==0.4.0
Flask-Mail==0.9.1
Flask-Principal==0.4.0
Flask-SQLAlchemy==2.2
Flask-WTF==0.14.2
gunicorn==19.7.1
itsdangerous==0.24
Jinja2==2.9.5
lxml==3.7.3
MarkupSafe==1.0
nose==1.3.7
packaging==16.8
pkg-resources==0.0.0
premailer==3.0.1
pycparser==2.17
pyparsing==2.2.0
python-dateutil==2.6.0
pytz==2017.2
requests==2.13.0
schedule==0.4.2
six==1.10.0
SQLAlchemy==1.1.6
tzlocal==1.4
uWSGI==2.0.15
Werkzeug==0.12.1
WTForms==2.1

Edit: One BankSlip can have one user and one reference.... It should be a one-to-one relationship where parent -> child is BankSlip -> User or BankSlip -> Reference. So, a child can have multiple parents!

Body:
Provide the required foreign_keys argument, as instructed by the error message:

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    user = db.relationship("BankSlip", foreign_keys='BankSlip.person_user_id', back_populates="person_user")
    reference = db.relationship("BankSlip", foreign_keys='BankSlip.person_ref_id', back_populates="person_reference")

With Declarative you can define the foreign keys as a string, which will help in resolving the circular dependency. Alternatively you could use backref instead of back_populates:

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class BankSlip(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    person_user_id = db.Column(db.Integer, db.ForeignKey(Person.id))
    person_ref_id = db.Column(db.Integer, db.ForeignKey(Person.id))

    person_user = db.relationship("Person", backref="user", uselist=False, foreign_keys=[person_user_id])
    person_reference = db.relationship("Person", backref="reference", uselist=False, foreign_keys=[person_ref_id])

Note that you've got the uselist=False at the wrong end of the relationship, or it is redundant, since a Person can be referenced by multiple BankSlips. It belongs at Persons's side, so:

from sqlalchemy.orm import backref

...
    person_user = db.relationship("Person", backref=backref("user", uselist=False), foreign_keys=[person_user_id])
    person_reference = db.relationship("Person", backref=backref("reference", uselist=False), foreign_keys=[person_ref_id])


问:
"The system cannot find the file specified" en-parser-chunking.bin
I have two projects in my eclipse for sentence parsing with Apache Open NLP. One project is working fine. But for the other project I'm getting below error.

Here is my project structure, Both project has the "en-parser-chunking.bin" file.

OpenNLP project is working fine (I got that project from the internet). So I copied that "en-parser-chunking.bin" file from there and pasted it on my books application project also. But I'm getting above error. What happened to my code ? Is there any other way to import "en-parser-chunking.bin" file to my books application project ?

below is the code I use in books application

```<code>public void parserAction() throws Exception {
    InputStream is = new FileInputStream("en-parser-chunking.bin");
    ParserModel model = new ParserModel(is);
    Parser parser = ParserFactory.create(model);
    Parse topParses[] = ParserTool.parseLine(line, parser, 1);
    for (Parse p : topParses){
        //p.show();
        getNounPhrases(p);
    }
}
</code>```

答:
You should put it into a Directory which is part of the classpath. in modern projects it is under /src/main/resources/. If you have copied it to this Location you can get the File with.

```<code>InputStream is =MyClass.class.getResourceAsStream("/en-parser-chunking.bin");
</code>```

where MyClass is the name of your class

Body:
I have two projects in my eclipse for sentence parsing with Apache Open NLP. One project is working fine. But for the other project I'm getting below error.

Here is my project structure, Both project has the "en-parser-chunking.bin" file.

OpenNLP project is working fine (I got that project from the internet). So I copied that "en-parser-chunking.bin" file from there and pasted it on my books application project also. But I'm getting above error. What happened to my code ? Is there any other way to import "en-parser-chunking.bin" file to my books application project ?

below is the code I use in books application

public void parserAction() throws Exception {
    InputStream is = new FileInputStream("en-parser-chunking.bin");
    ParserModel model = new ParserModel(is);
    Parser parser = ParserFactory.create(model);
    Parse topParses[] = ParserTool.parseLine(line, parser, 1);
    for (Parse p : topParses){
        //p.show();
        getNounPhrases(p);
    }
}

Body:
You should put it into a Directory which is part of the classpath. in modern projects it is under /src/main/resources/. If you have copied it to this Location you can get the File with.

InputStream is =MyClass.class.getResourceAsStream("/en-parser-chunking.bin");

where MyClass is the name of your class


问:
Retrieving the MethodInfo of of the correct overload of a generic method
I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func<T> parameter) using reflection. The problem however is that I can't find the correct parameter type to supply the Type.GetMethod(string, Type[]) method with.

Here is my class definition:

```<code>public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}
</code>```

And this is what I've come up with, unfortunately without succes:

```<code>[TestMethod]
public void Test1()
{
    Type parameterType = typeof(Func<>);

    var method = typeof(Foo).GetMethod("Bar", new Type[] { parameterType });

    Assert.IsNotNull(method); // Fails
}
</code>```

How can I get the MethodInfo of a generic method of which I know the parameters?

答:
Surprisingly, it looks like you'll need to call GetMethods() and loop over the methods until you find the one you want.

For example:

```<code>var yourMethod = typeof(Foo).GetMethods()
    .First(m => m.Name == "Bar"
             && m.GetParameters().Length == 1
             && m.GetParameters()[0].ParameterType.ContainsGenericParameters
             && m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(Func<>));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func<T> parameter) using reflection. The problem however is that I can't find the correct parameter type to supply the Type.GetMethod(string, Type[]) method with.

Here is my class definition:

public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}

And this is what I've come up with, unfortunately without succes:

[TestMethod]
public void Test1()
{
    Type parameterType = typeof(Func<>);

    var method = typeof(Foo).GetMethod("Bar", new Type[] { parameterType });

    Assert.IsNotNull(method); // Fails
}

How can I get the MethodInfo of a generic method of which I know the parameters?

Body:
Surprisingly, it looks like you'll need to call GetMethods() and loop over the methods until you find the one you want.

For example:

var yourMethod = typeof(Foo).GetMethods()
    .First(m => m.Name == "Bar"
             && m.GetParameters().Length == 1
             && m.GetParameters()[0].ParameterType.ContainsGenericParameters
             && m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(Func<>));


问:
Select the key:value pairs from a dictionary in Python
I have a Python Dict like as follows:

```<code>a = {"a":1,"b":2,"c":3,"f":4,"d":5}
</code>```

and I have a list like as follows:

```<code>b= ["b","c"]
</code>```

What I want to do is selecting the key:value pairs from the dict a with keys in b.
So the output should be a dictionary like:

```<code>out = {"b":2,"c":3}
</code>```

I could simply create another dictionary and update it using the key:value pair with iteration but I have RAM problems and the dictionary a is very large. b includes a few points so I thought popping from a does not work. What can I do to solve this issue?

Edit: Out is actually an update on a. So I will update the a as out.

Thanks :)

答:
If you don't have any problem with modifing the exsisting dict then try this :

```<code>out = {}
for key in b:
        out[key] = a.pop(key)
</code>```

This wouldn't take any extra space, as we're transferring the values required from old to new dict, and would solve the problem of slow selective popping as well(as we're not traversing through all but only the selective one's which are required).

Body:
I have a Python Dict like as follows:

a = {"a":1,"b":2,"c":3,"f":4,"d":5}

and I have a list like as follows:

b= ["b","c"]

What I want to do is selecting the key:value pairs from the dict a with keys in b.
So the output should be a dictionary like:

out = {"b":2,"c":3}

I could simply create another dictionary and update it using the key:value pair with iteration but I have RAM problems and the dictionary a is very large. b includes a few points so I thought popping from a does not work. What can I do to solve this issue?

Edit: Out is actually an update on a. So I will update the a as out.

Thanks :)

Body:
If you don't have any problem with modifing the exsisting dict then try this :

out = {}
for key in b:
        out[key] = a.pop(key)

This wouldn't take any extra space, as we're transferring the values required from old to new dict, and would solve the problem of slow selective popping as well(as we're not traversing through all but only the selective one's which are required).


问:
Nesting two ng-repeats
I'm trying to show some data in a table with two ng-repeats. But the second ng-repeat doesn't seem to work. This is what I'm trying:

```<code><tbody>
    <tr class="admin-detail-rows" ng-repeat="lesson in lessons | orderBy:sortType:sortReverse">
       <div ng-repeat="group in lesson.groups">
           <td>{{ working_days[lesson.day - 1] }}</td>
           <td>{{ lesson.start_time }} - {{ lesson.end_time }}</td>
           <td>{{ group.available_seats ? group.max_seats - group.available_seats : 0 }} / {{ group.max_seats }}</td>
           <td>{{ lesson.room }}</td>
           <td>{{ lesson.teacher }}</td>
           <td>{{ group.group_name }}</td>
           <td>{{ lesson.groupDetails  }}</td>
           <td ng-click="removeLesson(lesson)" class="delete-button">✖</td>
      </div>
   </tr>
</tbody>
</code>```

But it never does the second repeat more than once, and it doesn't know a lot of the properties.

A lesson that I'm iterating through in the first ng-repeat could look like this:

```<code> {
    "id":140,
    "course_id":156,
    "start_time":"08:45",
    "end_time":"10:30",
    "day":2,
    "type":1,
    "course_description":"The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
    "room":"OVk.41 left",
    "teacher":"Test teacher","created_at":"2017-04-11 13:43:29",
    "course": {
    "id":156,
    "code":"Test code",
    "name":"The Business Dimension of Europe",
    "credits":3,
    "category_id":20,
    "entry_requirements":null,
    "assessment_materials":null,
    "study_materials":null,
    "outline":null,
    "description":null,
    "created_at":"2017-04-11 13:41:45"
},
    "groups":[{
    "id":181,"timetable_id":140,
    "course_id":156,
    "group_name":"P",
    "group_details":null,
    "max_seats":3,
    "available_seats":-4,
    "created_at":"2017-04-11 13:43:29"
    }, {
    "id":182,
    "timetable_id":140,
    "course_id":156,
    "group_name":"Q",
    "group_details":null,"max_seats":3,
    "available_seats":null,
    "created_at":"2017-04-11 13:43:29"
    },{"id":183,
    "timetable_id":140,
    "course_id":156,
    "group_name":"R",
    "group_details":null,
    "max_seats":3,"available_seats":null,
    "created_at":"2017-04-11 13:43:29"}
    ]}
</code>```

Assigning the lesson to the scope:

```<code>$scope.$watch(function () {
  return lessonsService.getLessons();
}, function (lessons) {
  $scope.lessons = lessons;
});
</code>```

What am I doing wrong?

答:
Your inner ng-repeat should be groups instead of group,

```<code><div ng-repeat="group in lesson.groups">
</code>```

DEMO

 angular.module('myApp',[]).controller('myCtrl', function($scope){

   $scope.lessons  =[{
 "id": 140,
 "course_id": 156,
 "start_time": "08:45",
 "end_time": "10:30",
 "day": 2,
 "type": 1,
 "course_description": "The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
 "room": "OVk.41 left",
 "teacher": "Kerkhof van de B.K.W.",
 "created_at": "2017-04-11 13:43:29",
 "course": {
  "id": 156,
  "code": "ES-ISBMDIMEUR-16",
  "name": "The Business Dimension of Europe",
  "credits": 3,
  "category_id": 20,
  "entry_requirements": null,
  "assessment_materials": null,
  "study_materials": null,
  "outline": null,
  "description": null,
  "created_at": "2017-04-11 13:41:45"
 },
 "groups": [{
  "id": 181,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "P",
  "group_details": null,
  "max_seats": 3,
  "available_seats": -4,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 182,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "Q",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 183,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "R",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }]
}];

 });

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<table>
    <tr  ng-repeat="lesson in lessons ">
       <div ng-repeat="group in lesson.groups">
           <td>{{ working_days[lesson.day - 1] }}     </td>
           <td>{{ lesson.start_time }} - {{ lesson.end_time }}   </td>
           <td>{{ group.available_seats  }} / {{ group.max_seats }}  </td>
           <td>{{ lesson.room }}   </td>
           <td>{{ lesson.teacher }}   </td>
           <td>{{ group.group_name }}   </td>
           <td>{{ lesson.groupDetails  }}   </td>
           <td ng-click="removeLesson(lesson)" class="delete-button">✖</td>
      </div>
   </tr>
</table>
</div></code>```

Title: Nesting two ng-repeats

Body:
I'm trying to show some data in a table with two ng-repeats. But the second ng-repeat doesn't seem to work. This is what I'm trying:

           {{ working_days[lesson.day - 1] }}
           {{ lesson.start_time }} - {{ lesson.end_time }}
           {{ group.available_seats ? group.max_seats - group.available_seats : 0 }} / {{ group.max_seats }}
           {{ lesson.room }}
           {{ lesson.teacher }}
           {{ group.group_name }}
           {{ lesson.groupDetails  }}
           ✖

But it never does the second repeat more than once, and it doesn't know a lot of the properties.

A lesson that I'm iterating through in the first ng-repeat could look like this:

 {
    "id":140,
    "course_id":156,
    "start_time":"08:45",
    "end_time":"10:30",
    "day":2,
    "type":1,
    "course_description":"The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
    "room":"OVk.41 left",
    "teacher":"Test teacher","created_at":"2017-04-11 13:43:29",
    "course": {
    "id":156,
    "code":"Test code",
    "name":"The Business Dimension of Europe",
    "credits":3,
    "category_id":20,
    "entry_requirements":null,
    "assessment_materials":null,
    "study_materials":null,
    "outline":null,
    "description":null,
    "created_at":"2017-04-11 13:41:45"
},
    "groups":[{
    "id":181,"timetable_id":140,
    "course_id":156,
    "group_name":"P",
    "group_details":null,
    "max_seats":3,
    "available_seats":-4,
    "created_at":"2017-04-11 13:43:29"
    }, {
    "id":182,
    "timetable_id":140,
    "course_id":156,
    "group_name":"Q",
    "group_details":null,"max_seats":3,
    "available_seats":null,
    "created_at":"2017-04-11 13:43:29"
    },{"id":183,
    "timetable_id":140,
    "course_id":156,
    "group_name":"R",
    "group_details":null,
    "max_seats":3,"available_seats":null,
    "created_at":"2017-04-11 13:43:29"}
    ]}

Assigning the lesson to the scope:

$scope.$watch(function () {
  return lessonsService.getLessons();
}, function (lessons) {
  $scope.lessons = lessons;
});

What am I doing wrong?

Body:
Your inner ng-repeat should be groups instead of group,

<div ng-repeat="group in lesson.groups">

DEMO

 angular.module('myApp',[]).controller('myCtrl', function($scope){

   $scope.lessons  =[{
 "id": 140,
 "course_id": 156,
 "start_time": "08:45",
 "end_time": "10:30",
 "day": 2,
 "type": 1,
 "course_description": "The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
 "room": "OVk.41 left",
 "teacher": "Kerkhof van de B.K.W.",
 "created_at": "2017-04-11 13:43:29",
 "course": {
  "id": 156,
  "code": "ES-ISBMDIMEUR-16",
  "name": "The Business Dimension of Europe",
  "credits": 3,
  "category_id": 20,
  "entry_requirements": null,
  "assessment_materials": null,
  "study_materials": null,
  "outline": null,
  "description": null,
  "created_at": "2017-04-11 13:41:45"
 },
 "groups": [{
  "id": 181,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "P",
  "group_details": null,
  "max_seats": 3,
  "available_seats": -4,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 182,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "Q",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 183,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "R",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }]
}];

 });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<table>
    <tr  ng-repeat="lesson in lessons ">
       <div ng-repeat="group in lesson.groups">
           <td>{{ working_days[lesson.day - 1] }} &nbsp;&nbsp;&nbsp;&nbsp;</td>
           <td>{{ lesson.start_time }} - {{ lesson.end_time }}&nbsp;&nbsp;&nbsp;</td>
           <td>{{ group.available_seats  }} / {{ group.max_seats }}&nbsp;&nbsp;</td>
           <td>{{ lesson.room }}&nbsp;&nbsp;&nbsp;</td>
           <td>{{ lesson.teacher }}&nbsp;&nbsp;&nbsp;</td>
           <td>{{ group.group_name }}&nbsp;&nbsp;&nbsp;</td>
           <td>{{ lesson.groupDetails  }}&nbsp;&nbsp;&nbsp;</td>
           <td ng-click="removeLesson(lesson)" class="delete-button">✖</td>
      </div>
   </tr>
</table>
</div>


问:
The '--lang=en_US' Chromium switcher contains unsupported language value
I am using JxBrowser 6.14, and I get this error when starting a jxbrowser instance:

```<code>com.teamdev.jxbrowser.chromium.internal.ipc.IPCException: Failed to start IPC process.
    at com.teamdev.jxbrowser.chromium.internal.ipc.d.run(SourceFile:190)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: The '--lang=en_US' Chromium switcher contains unsupported language value. Use one of the following language values: am, ar, bg, bn, ca, cs, da, de, el, en, en_gb, es, es_419, et, fa, fi, fil, fr, gu, he, hi, hr, hu, id, it, ja, kn, ko, lt, lv, ml, mr, ms, nb, nl, pl, pt_br, pt_pt, ro, ru, sk, sl, sr, sv, sw, ta, te, th, tr, uk, vi, zh_cn, zh_tw.
    at com.teamdev.jxbrowser.chromium.internal.ipc.ChromiumProcess.a(SourceFile:178)
    at com.teamdev.jxbrowser.chromium.internal.ipc.ChromiumProcess.start(SourceFile:103)
    at com.teamdev.jxbrowser.chromium.internal.ipc.d.run(SourceFile:184)
    ... 1 more
</code>```

I didn't have that problem yesterday. I don't know what changed.

答:
I believe the issue wasn't reproducible with an old JxBrowser version. Once you upgraded to 6.14, you started seeing this error message. The reason is that in one of the latest JxBrowser versions, language check functionality has been updated. Now it validates the --lang=en_US parameter and checks whether Chromium has appropriate language resource (*.pak).

The error message indicates that the en_US.pak file doesn't exist in Chromium, so you have to use one of the suggested languages. To solve the issue use the --lang=en switcher.

Body:
I am using JxBrowser 6.14, and I get this error when starting a jxbrowser instance:

com.teamdev.jxbrowser.chromium.internal.ipc.IPCException: Failed to start IPC process.
    at com.teamdev.jxbrowser.chromium.internal.ipc.d.run(SourceFile:190)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: The '--lang=en_US' Chromium switcher contains unsupported language value. Use one of the following language values: am, ar, bg, bn, ca, cs, da, de, el, en, en_gb, es, es_419, et, fa, fi, fil, fr, gu, he, hi, hr, hu, id, it, ja, kn, ko, lt, lv, ml, mr, ms, nb, nl, pl, pt_br, pt_pt, ro, ru, sk, sl, sr, sv, sw, ta, te, th, tr, uk, vi, zh_cn, zh_tw.
    at com.teamdev.jxbrowser.chromium.internal.ipc.ChromiumProcess.a(SourceFile:178)
    at com.teamdev.jxbrowser.chromium.internal.ipc.ChromiumProcess.start(SourceFile:103)
    at com.teamdev.jxbrowser.chromium.internal.ipc.d.run(SourceFile:184)
    ... 1 more

I didn't have that problem yesterday. I don't know what changed.


问:
JSON Parsing using Swift 3
I am calling a soap service in my application. I am getting this response in JSON from server

```<code>{
  "CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "IsCorporate":false,
  "ID":48,
  "Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "GroupID":null,
  "GroupName":null,
  "CustomerID":48
}
</code>```

I have tried what online tutorial suggests but I am not able to parse data. It gives me error that "Invalid value around character 0." My Code is this

```<code> let is_URL: String = "http://labs2.unitedtracker.com/WTService.asmx?op=GetTerminalNumber"

    let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
    let session = URLSession.shared

    lobj_Request.httpMethod = "POST"
    lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
    lobj_Request.addValue("labs2.unitedtracker.com", forHTTPHeaderField: "Host")
    lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    lobj_Request.addValue(String(is_SoapMessage.characters.count), forHTTPHeaderField: "Content-Length")
    lobj_Request.addValue("http://tempuri.org/GetTerminalNumber", forHTTPHeaderField: "SOAPAction")

    let task = session.dataTask(with: lobj_Request as URLRequest, completionHandler: {data, response, error -> Void in

        do {
            if let data = data,
                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                let customerID = json["CustomerID"] as? [[String: Any]] {
                print(customerID)
            }
        } catch {
            print("Error deserializing JSON: \(error)")
        }

        if error != nil
        {
            print("Error: " + String(describing: error))
        }
    })
    task.resume()
</code>```

Can anyone suggest me what is wrong i m doing. And how should be such JSON response from Soap Service should be parsed.

Here is complete response from my Server.

```<code><?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetAuthenticateUserResponse xmlns="http://tempuri.org/"><GetAuthenticateUserResult>[{"CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ","IsCorporate":false,"ID":48,"Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ","GroupID":null,"GroupName":null,"CustomerID":48}]</GetAuthenticateUserResult></GetAuthenticateUserResponse></soap:Body></soap:Envelope>
</code>```

答:
The problem is that you receive XML from the server and try to parse it as JSON. You have to extract the JSON payload from the XML envelope first. This is the whole response:

```<code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <GetAuthenticateUserResponse xmlns="http://tempuri.org/">
      <GetAuthenticateUserResult>[{"CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ","IsCorporate":false,"ID":48,"Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ","GroupID":null,"GroupName":null,"CustomerID":48}]</GetAuthenticateUserResult>
    </GetAuthenticateUserResponse>
  </soap:Body>
</soap:Envelope>
</code>```

You need to extract the contents of the <GetAuthenticateUserResult> tag as a string and only then you can use NSJSONSerialization to parse that. A bit like this:

```<code>class Extractor: NSObject, XMLParserDelegate {

    var payload = ""
    private var recording = false
    let wantedElement = "GetAuthenticateUserResult"

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?,
        qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        if elementName == wantedElement {
            recording = true
        }
    }

    func parser(_ parser: XMLParser, foundCharacters string: String) {
        if recording {
            payload += string
        }
    }

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        recording = false
    }
}

let response = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><GetAuthenticateUserResponse xmlns=\"http://tempuri.org/\"><GetAuthenticateUserResult>[{\"CustomerName\":\"Muneer Ahmad/ Ejaz Ahmad (User)\",\"IsCorporate\":false,\"ID\":48,\"Name\":\"Muneer Ahmad/ Ejaz Ahmad (User)  \",\"GroupID\":null,\"GroupName\":null,\"CustomerID\":48}]</GetAuthenticateUserResult></GetAuthenticateUserResponse></soap:Body></soap:Envelope>"
let parser = XMLParser(data: response.data(using: .utf8)!)
let extractor = Extractor()
parser.delegate = extractor
parser.parse()
let payload = extractor.payload
let parsedPayload = try? JSONSerialization.jsonObject(with: payload.data(using: .utf8)!, options: [])
</code>```

That gives you:

```<code>{
    CustomerID = 48;
    CustomerName = "Muneer Ahmad/ Ejaz Ahmad (User)";
    GroupID = "<null>";
    GroupName = "<null>";
    ID = 48;
    IsCorporate = 0;
    Name = "Muneer Ahmad/ Ejaz Ahmad (User)  ";
}
</code>```

The XML extraction code is a bit stupid since I don’t know any better built-in XML parser.

Title: JSON Parsing using Swift 3

Body:
I am calling a soap service in my application. I am getting this response in JSON from server

{
  "CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "IsCorporate":false,
  "ID":48,
  "Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "GroupID":null,
  "GroupName":null,
  "CustomerID":48
}

I have tried what online tutorial suggests but I am not able to parse data. It gives me error that "Invalid value around character 0." My Code is this

 let is_URL: String = "http://labs2.unitedtracker.com/WTService.asmx?op=GetTerminalNumber"

    let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
    let session = URLSession.shared

    lobj_Request.httpMethod = "POST"
    lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
    lobj_Request.addValue("labs2.unitedtracker.com", forHTTPHeaderField: "Host")
    lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    lobj_Request.addValue(String(is_SoapMessage.characters.count), forHTTPHeaderField: "Content-Length")
    lobj_Request.addValue("http://tempuri.org/GetTerminalNumber", forHTTPHeaderField: "SOAPAction")

    let task = session.dataTask(with: lobj_Request as URLRequest, completionHandler: {data, response, error -> Void in

        do {
            if let data = data,
                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                let customerID = json["CustomerID"] as? [[String: Any]] {
                print(customerID)
            }
        } catch {
            print("Error deserializing JSON: \(error)")
        }

        if error != nil
        {
            print("Error: " + String(describing: error))
        }
    })
    task.resume()

Can anyone suggest me what is wrong i m doing. And how should be such JSON response from Soap Service should be parsed.

Here is complete response from my Server.

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetAuthenticateUserResponse xmlns="http://tempuri.org/"><GetAuthenticateUserResult>[{"CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ","IsCorporate":false,"ID":48,"Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ","GroupID":null,"GroupName":null,"CustomerID":48}]</GetAuthenticateUserResult></GetAuthenticateUserResponse></soap:Body></soap:Envelope>

Body:
The problem is that you receive XML from the server and try to parse it as JSON. You have to extract the JSON payload from the XML envelope first. This is the whole response:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <GetAuthenticateUserResponse xmlns="http://tempuri.org/">
      <GetAuthenticateUserResult>[{"CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ","IsCorporate":false,"ID":48,"Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ","GroupID":null,"GroupName":null,"CustomerID":48}]</GetAuthenticateUserResult>
    </GetAuthenticateUserResponse>
  </soap:Body>
</soap:Envelope>

You need to extract the contents of the <GetAuthenticateUserResult> tag as a string and only then you can use NSJSONSerialization to parse that. A bit like this:

class Extractor: NSObject, XMLParserDelegate {

    var payload = ""
    private var recording = false
    let wantedElement = "GetAuthenticateUserResult"

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?,
        qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        if elementName == wantedElement {
            recording = true
        }
    }

    func parser(_ parser: XMLParser, foundCharacters string: String) {
        if recording {
            payload += string
        }
    }

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        recording = false
    }
}

let response = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><GetAuthenticateUserResponse xmlns=\"http://tempuri.org/\"><GetAuthenticateUserResult>[{\"CustomerName\":\"Muneer Ahmad/ Ejaz Ahmad (User)\",\"IsCorporate\":false,\"ID\":48,\"Name\":\"Muneer Ahmad/ Ejaz Ahmad (User)  \",\"GroupID\":null,\"GroupName\":null,\"CustomerID\":48}]</GetAuthenticateUserResult></GetAuthenticateUserResponse></soap:Body></soap:Envelope>"
let parser = XMLParser(data: response.data(using: .utf8)!)
let extractor = Extractor()
parser.delegate = extractor
parser.parse()
let payload = extractor.payload
let parsedPayload = try? JSONSerialization.jsonObject(with: payload.data(using: .utf8)!, options: [])

That gives you:

{
    CustomerID = 48;
    CustomerName = "Muneer Ahmad/ Ejaz Ahmad (User)";
    GroupID = "<null>";
    GroupName = "<null>";
    ID = 48;
    IsCorporate = 0;
    Name = "Muneer Ahmad/ Ejaz Ahmad (User)  ";
}

The XML extraction code is a bit stupid since I don’t know any better built-in XML parser.


问:
execute Spark jobs, with Livy, using `--master yarn-cluster` without making systemwide changes
I'd like to execute a Spark job, via an HTTP call from outside the cluster using Livy, where the Spark jar already exists in HDFS.

I'm able to spark-submit the job from shell on the cluster nodes, e.g.:

```<code>spark-submit --class io.woolford.Main --master yarn-cluster hdfs://hadoop01:8020/path/to/spark-job.jar
</code>```

Note that the --master yarn-cluster is necessary to access HDFS where the jar resides.

I'm also able to submit commands, via Livy, using curl. For example, this request:

```<code>curl -X POST --data '{"file": "/path/to/spark-job.jar", "className": "io.woolford.Main"}' -H "Content-Type: application/json" hadoop01:8998/batches
</code>```

... executes the following command on the cluster:

```<code>spark-submit --class io.woolford.Main hdfs://hadoop01:8020/path/to/spark-job.jar
</code>```

This is the same as the command that works, minus the --master yarn-cluster params. This was verified by tailing /var/log/livy/livy-livy-server.out.

So, I just need to modify the curl command to include --master yarn-cluster when it's executed by Livy. At first glance, it seems like this should be possible by adding arguments to the JSON dictionary. Unfortunately, these aren't passed through.

Does anyone know how to pass --master yarn-cluster to Livy so that jobs are executed on YARN without making systemwide changes?

答:
spark.master = yarn-cluster

set it in the spark conf, for me:/etc/spark2/conf/spark-defaults.conf

Body:
I'd like to execute a Spark job, via an HTTP call from outside the cluster using Livy, where the Spark jar already exists in HDFS.

I'm able to spark-submit the job from shell on the cluster nodes, e.g.:

spark-submit --class io.woolford.Main --master yarn-cluster hdfs://hadoop01:8020/path/to/spark-job.jar

Note that the --master yarn-cluster is necessary to access HDFS where the jar resides.

I'm also able to submit commands, via Livy, using curl. For example, this request:

curl -X POST --data '{"file": "/path/to/spark-job.jar", "className": "io.woolford.Main"}' -H "Content-Type: application/json" hadoop01:8998/batches

... executes the following command on the cluster:

spark-submit --class io.woolford.Main hdfs://hadoop01:8020/path/to/spark-job.jar

This is the same as the command that works, minus the --master yarn-cluster params. This was verified by tailing /var/log/livy/livy-livy-server.out.

So, I just need to modify the curl command to include --master yarn-cluster when it's executed by Livy. At first glance, it seems like this should be possible by adding arguments to the JSON dictionary. Unfortunately, these aren't passed through.

Does anyone know how to pass --master yarn-cluster to Livy so that jobs are executed on YARN without making systemwide changes?


问:
IOS UI tests without simulator or device
I want to write UI tests for ios.

can I run them (from xcode) without device or simulator as destination?

for example: I want to test click on btn and check if something happened, but not want that test run it on simulator or device.

(I know that in android you can use robolectric to do it).

答: I'm sorry but there is no other solutions for it. You can only make a choice between device or simulator.</p>


问:
Show on Scroll and Fade Javascript
At the moment my code is this

```<code>    myID = document.getElementById("responsive-menu-button");

`enter code here`var myScrollFunc = function() {
  var y = window.scrollY;
  if (y >= 200) {
    myID.className = "bottomMenu show"
  } else {
    myID.className = "bottomMenu hide"
  }
};

window.addEventListener("scroll", myScrollFunc);
</code>```

but at the moment it just shows and hides the DIV. I am wanting to add a fade affect such as .fadeIn(); but i cant get this working at all within chromes development tool in the code snippet.

Any ideas? All the scripts with '$' in then seem to not work in chromes code snippet tester.

Thanks

答:
You can achieve it using simple CSS and js

CSS is #responsive-menu-button{transition: all ease .6s;}

And JavaScript

```<code>if (y >= 200) {
   myID.className = "bottomMenu"
   myID.style.opacity='.1';
   setTimeout(function(){myID.style.display='none'},600);
}
else {
  myID.className = "bottomMenu"
  myID.style.display='';
  myID.style.opacity='1';
}
</code>```

Title: Show on Scroll and Fade Javascript

Body:
At the moment my code is this

    myID = document.getElementById("responsive-menu-button");

`enter code here`var myScrollFunc = function() {
  var y = window.scrollY;
  if (y >= 200) {
    myID.className = "bottomMenu show"
  } else {
    myID.className = "bottomMenu hide"
  }
};

window.addEventListener("scroll", myScrollFunc);

but at the moment it just shows and hides the DIV. I am wanting to add a fade affect such as .fadeIn(); but i cant get this working at all within chromes development tool in the code snippet.

Any ideas? All the scripts with '$' in then seem to not work in chromes code snippet tester.

Thanks

Body:
You can achieve it using simple CSS and js

CSS is #responsive-menu-button{transition: all ease .6s;}

And JavaScript

if (y >= 200) {
   myID.className = "bottomMenu"
   myID.style.opacity='.1';
   setTimeout(function(){myID.style.display='none'},600);
}
else {
  myID.className = "bottomMenu"
  myID.style.display='';
  myID.style.opacity='1';
}


问:
embedded widget that relies of jquery, what if main page has jquery already loaded?
If I create a widget, where someon just links to:

```<code>www.example.com/my.js
</code>```

which places a small widget on their website, and my widget relies on jquery, how can first check if is loaded already on the page?

what if 1.3.1 is loaded and I require 1.4.2?

答:
If I recall there is a function in jQuery "$().jquery" that returns the version. Or "jQuery.fn.jquery;"

To check for jQuery entirely do something like

if(typeof(jQuery) != "undefined")
{
   Bla bla code
}

Body:
If I create a widget, where someon just links to:

www.example.com/my.js

which places a small widget on their website, and my widget relies on jquery, how can first check if is loaded already on the page?

what if 1.3.1 is loaded and I require 1.4.2?


问:
Google Charts colors for Column Chart
I have Pie and Column charts from the same source data.

I want colors in bar chart to have the corrsponding colors like in Pie chart. These are default Google Charts colors (in order). So first column should be blue, second red, third yellow and fourth green. How to achieve this?

答:
in a column chart, values in the same series are the same color by default

series are defined by columns, to have different colors by default,

place each value in a separate column

however, this presents a problem

if you structure the data as follows, then you lose the x-axis labels

you only have one label for all columns

```<code>var data = google.visualization.arrayToDataTable([
  ['x', 'y0', 'y1', 'y2', 'y3'],
  ['Razina0', 898, 37319, 8980, 35400]
]);
</code>```

if you try the next approach, then the columns will not be spaced properly

there will be gaps for the null values

```<code>var data = google.visualization.arrayToDataTable([
  ['x', 'y0', 'y1', 'y2', 'y3'],
  ['Razina0', 898, null, null, null],
  ['Razina1', null, 37319, null, null],
  ['Razina2', null, null, 8980, null],
  ['Razina3', null, null, null, 35400],
]);
</code>```

the best option is to use a style column

this will allow you to keep the current data structure

and provide different colors for each column

the only drawback is you have to provide the color

so you lose the default colors

as such, recommend drawing the pie chart first

then use the colors assigned to each slice

when the pie chart's 'ready' event fires

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0'],
    ['Razina0', 898],
    ['Razina1', 37319],
    ['Razina2', 8980],
    ['Razina3', 35400]
  ]);

  var chartPie = new google.visualization.PieChart(document.getElementById('chart_pie'));
  var chartColumn = new google.visualization.ColumnChart(document.getElementById('chart_column'));

  google.visualization.events.addListener(chartPie, 'ready', function () {
    var colIndex = data.addColumn({type: 'string', role: 'style'});
    $.each($('#chart_pie path'), function (rowIndex) {
      data.setValue(rowIndex, colIndex, $(this).attr('fill'));
    });

    chartColumn.draw(data, {
      legend: {
        position: 'none'
      }
    });
  });

  chartPie.draw(data, {
    height: 240
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  display: inline-block;
}</code>```

```

Title: Google Charts colors for Column Chart

Body:
in a column chart, values in the same series are the same color by default

series are defined by columns, to have different colors by default,

place each value in a separate column

however, this presents a problem

if you structure the data as follows, then you lose the x-axis labels

you only have one label for all columns

var data = google.visualization.arrayToDataTable([
  ['x', 'y0', 'y1', 'y2', 'y3'],
  ['Razina0', 898, 37319, 8980, 35400]
]);

if you try the next approach, then the columns will not be spaced properly

there will be gaps for the null values

var data = google.visualization.arrayToDataTable([
  ['x', 'y0', 'y1', 'y2', 'y3'],
  ['Razina0', 898, null, null, null],
  ['Razina1', null, 37319, null, null],
  ['Razina2', null, null, 8980, null],
  ['Razina3', null, null, null, 35400],
]);

the best option is to use a style column

this will allow you to keep the current data structure

and provide different colors for each column

the only drawback is you have to provide the color

so you lose the default colors

as such, recommend drawing the pie chart first

then use the colors assigned to each slice

when the pie chart's 'ready' event fires

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0'],
    ['Razina0', 898],
    ['Razina1', 37319],
    ['Razina2', 8980],
    ['Razina3', 35400]
  ]);

  var chartPie = new google.visualization.PieChart(document.getElementById('chart_pie'));
  var chartColumn = new google.visualization.ColumnChart(document.getElementById('chart_column'));

  google.visualization.events.addListener(chartPie, 'ready', function () {
    var colIndex = data.addColumn({type: 'string', role: 'style'});
    $.each($('#chart_pie path'), function (rowIndex) {
      data.setValue(rowIndex, colIndex, $(this).attr('fill'));
    });

    chartColumn.draw(data, {
      legend: {
        position: 'none'
      }
    });
  });

  chartPie.draw(data, {
    height: 240
  });
}

div {
  display: inline-block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_pie"></div>
<div id="chart_column"></div>


问:
random element from a list
Is there a way in python to select a random element form a list without considering a current element?

In other word, I want to do this

```<code>L=[1,2,3,4,5,6,7,8,9,10]
i=0
while(i<len(L):
  random.choice(L-L[i])
  i+=1
</code>```

For example, at iteration 0 I do not want to have the element 1
and at iteration 1 I do not want to have the element 2.

答:
You could create a new list based on slicing:

```<code>L = [1,2,3,4,5,6,7,8,9,10]
i = 0
while i < len(L):
    random.choice(L[:i] + L[i+1:])  # L without the i-th element
    i += 1
</code>```

Or simply draw a random index until you draw an index that isn't equal to i:

```<code>while i < len(L):
    while True:
        num = random.randrange(0, len(L))  # draw an index
        if num != i:                       # stop drawing if it's not the current index
            break
    random_choice = L[num]
    i += 1
</code>```

If you need performance you could also just draw an index between 0 and len(L)-1 and increment it by 1 if it's equal or higher than i. That way you don't need to re-draw and index i is excluded:

```<code>while i < len(L):
    idx = random.randrange(0, len(L) - 1)
    if idx >= i:
        idx += 1
    random_choice = L[idx]
    i += 1
</code>```

Title: random element from a list

Body:
Is there a way in python to select a random element form a list without considering a current element?

In other word, I want to do this

L=[1,2,3,4,5,6,7,8,9,10]
i=0
while(i<len(L):
  random.choice(L-L[i])
  i+=1

For example, at iteration 0 I do not want to have the element 1
and at iteration 1 I do not want to have the element 2.

Body:
You could create a new list based on slicing:

L = [1,2,3,4,5,6,7,8,9,10]
i = 0
while i < len(L):
    random.choice(L[:i] + L[i+1:])  # L without the i-th element
    i += 1

Or simply draw a random index until you draw an index that isn't equal to i:

while i < len(L):
    while True:
        num = random.randrange(0, len(L))  # draw an index
        if num != i:                       # stop drawing if it's not the current index
            break
    random_choice = L[num]
    i += 1

If you need performance you could also just draw an index between 0 and len(L)-1 and increment it by 1 if it's equal or higher than i. That way you don't need to re-draw and index i is excluded:

while i < len(L):
    idx = random.randrange(0, len(L) - 1)
    if idx >= i:
        idx += 1
    random_choice = L[idx]
    i += 1


问:
Can't connect to HSQL Database from Java code when HSQL Database Manager is Connected
When I have opened and connected HSQL DB Manager (Swing), Java code can't connect to database throwing this:

```<code>java.sql.SQLException: Database lock acquisition failure: lockFile: org.hsqldb.persist.LockFile@cf53680[file =C:\somedb\db.lck ...
</code>```

But as soon as I close the connection to database from Database Manager, Java code starts to work fine.

What is this?

答:
HSQLDB is primarily an embedded database engine. That means that if you run it embedded, only one process (=JVM) can use the database. Connections from other processes are not possible.

The only way around that is to start HSQLDB in server mode where HSQLDB runs in its own process (JVM) and accepts connections from other processes - essentially the same setup as a "traditional" database server like Postgres or Oracle.

Details on how to start HSQLD in server mode are documented in the manual:

http://hsqldb.org/doc/2.0/guide/running-chapt.html#rgc_server_modes

Body:
When I have opened and connected HSQL DB Manager (Swing), Java code can't connect to database throwing this:

java.sql.SQLException: Database lock acquisition failure: lockFile: org.hsqldb.persist.LockFile@cf53680[file =C:\somedb\db.lck ...

But as soon as I close the connection to database from Database Manager, Java code starts to work fine.

What is this?


问:
Deciding on port value of messenger service which is not XMPP based
I am going to launch new messenger service. However, it is not XMPP based. Instead I am using my own protocol (for certain reasons).
What I am not able to decide on is what port shall I use for this service. A typical XMPP based messenger uses port 5222. Shall I use the same or different port?

Here are pros and cons I can think of...

If I use same port 5222 like other XMPP messengers, being standard port for messenger service my service will also use same port (But are there any cons here for my protocol being non-XMPP?)

If I use some other port, I fear that many firewalls will not allow traffic on non-standard port. Also anti-spywares too might flag my application as suspicious.

Please I need advice from experts.

答: Just wrap your protocol into TLS connection on 443 port: it will be never blocked by firewalls (just because https connections uses this in the same way) and TLS traffic cannot be identified by "anti-spyware" software</p>


问:
Wagtail 1.10.1 elastic search issue
We upgraded Wagtail to 1.10.1, all went fine but we also had to increase the version of the elasticsearch python module, now the admin search only returns records that have been added since the upgrade.

I've tried python manage.py update_index but it says

Updating backend: default
Backend 'default' doesn't require rebuilding

Any ideas as to why old pages/images are no longer searchable?

Thanks

Joss

答: I need to run the update_index referencing a specific setting, it then worked. Though still not sure why the index had to be rebuilt after a Wagtail Upgrade?</p>

Title: Wagtail 1.10.1 elastic search issue


问:
Adding links to text from an html textarea
Is this possible? What I would like to do is designate certain text that the user writes in a text area as a link. This text is inserted into a MySQL database then pulled, and displayed elsewhere. Also the links will never really be in the same spot.</p>

答:
Can you describe this process a bit more?  How will the specific text within the textarea be known to be a "link"?  What will it link to?  (Side note, be very careful with cross-site-scripting and such.  A JavaScript command can be in a link.)

Why not use a rich text editor which allows the user to create links?  Maybe something that supports markdown like this site does?


问:
Console.WriteLine() doesn't exist error in Visual Studio
I have little problem because I'm trying to run a powershell script in a console but Visual Studio is telling that Console.WriteLine() or Console.ReadKey() doesn't exist

答:
Add this to your class:

```<code>using System;
</code>```

The using statement is usually included as default, but if you use tools to "Remove Unnecessary Usings", then it may get removed. If you then later add code that requires the System namespace, then you have to include it again.

You could probably also fix the issue in by placing the marker on the Console in the Visual Studio code editor, and press Ctrl + '.'(period), to open the Quick Actions and Refactoring context menu.

Body:
Add this to your class:

using System;

The using statement is usually included as default, but if you use tools to "Remove Unnecessary Usings", then it may get removed. If you then later add code that requires the System namespace, then you have to include it again.

You could probably also fix the issue in by placing the marker on the Console in the Visual Studio code editor, and press Ctrl + '.'(period), to open the Quick Actions and Refactoring context menu.


问:
How to recursively filter an array if value exists on another array
I have two arrays.
The first one is the structure, an associative array that containts all elements inside categories. the name of the categories are keys inside this array. The categories can have different levels of depth:
check this example:

```<code>$structure = [
            'fruits'    => [
                'sweet' => [
                    'red' => [
                        'watermelon' =>['id' => 1],
                        'cherry' =>['id' => 2],
                        'litchi' =>['id' => 3]
                    ],
                    'white' => [
                        'coco' =>['id' => 13],
                        'lucuma' =>['id' => 14],
                    ]

                ],
                'sour'  => [
                    'lemon' =>['id' => 4],
                    'orange' =>['id' => 5],
                    'tangerine' =>['id' => 6]
                ],
            ],
            'colors'   => [
                'black' =>['id' => 7],
                'green' =>['id' => 8],
                'blue' => ['id' => 9]
            ],
            'names'   => [
                'jack' =>['id' => 10],
                'paul' =>['id' => 11],
                'peter' =>['id' => 12]
            ]
        ];
</code>```

I have a second array, with the elements that I want to search:

```<code>$results = ['coco', 'green','peter'];
</code>```

I need to write a function that gives an output array with the elements and the tree of categories where they belong. Something like this:

```<code>$resultsInStructure = [
            'fruits'    => [
                'sweet' => [
                    'white' => [
                        'coco' => ['id' => 13]
                    ]
                ]
            ],
            'colors'   => [
                'green' =>['id' => 8]
            ],
            'names'   => [
                'peter' =>['id' => 12]
            ]
        ];
</code>```

The function needs to be recursive, of course. Either walking the first of the second array, it's just that I can't manage to get it right... any help is appreciated !

答:
You can use RecursiveIteratorIterator to traverse the structure and references to put the value into the right place of the resulting array:

```<code>$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($structure),
    RecursiveIteratorIterator::SELF_FIRST
);

$filters = array_flip($results);

$keys = [];

$resultsInStructure = [];
foreach ($iterator as $key => $value) {
    if ($key === 'id') {
        continue;
    }

    // Put key to the stack, so we can get the path of results.
    $keys[$iterator->getDepth()] = $key;

    if (!isset($filters[$key])) {
        continue;
    }

    // Put the result in the right place in the tree structure.
    $tmp =& $resultsInStructure;
    foreach (array_slice($keys, 0, $iterator->getDepth()) as $_key) {
        if (!isset($tmp[$_key])) {
            $tmp[$_key] = [];
        }
        $tmp =& $tmp[$_key];
    }
    $tmp[$key] = $value;
}
</code>```

Here is working demo.

Body:
I have two arrays.
The first one is the structure, an associative array that containts all elements inside categories. the name of the categories are keys inside this array. The categories can have different levels of depth:
check this example:

$structure = [
            'fruits'    => [
                'sweet' => [
                    'red' => [
                        'watermelon' =>['id' => 1],
                        'cherry' =>['id' => 2],
                        'litchi' =>['id' => 3]
                    ],
                    'white' => [
                        'coco' =>['id' => 13],
                        'lucuma' =>['id' => 14],
                    ]

                ],
                'sour'  => [
                    'lemon' =>['id' => 4],
                    'orange' =>['id' => 5],
                    'tangerine' =>['id' => 6]
                ],
            ],
            'colors'   => [
                'black' =>['id' => 7],
                'green' =>['id' => 8],
                'blue' => ['id' => 9]
            ],
            'names'   => [
                'jack' =>['id' => 10],
                'paul' =>['id' => 11],
                'peter' =>['id' => 12]
            ]
        ];

I have a second array, with the elements that I want to search:

$results = ['coco', 'green','peter'];

I need to write a function that gives an output array with the elements and the tree of categories where they belong. Something like this:

$resultsInStructure = [
            'fruits'    => [
                'sweet' => [
                    'white' => [
                        'coco' => ['id' => 13]
                    ]
                ]
            ],
            'colors'   => [
                'green' =>['id' => 8]
            ],
            'names'   => [
                'peter' =>['id' => 12]
            ]
        ];

The function needs to be recursive, of course. Either walking the first of the second array, it's just that I can't manage to get it right... any help is appreciated !

Body:
You can use RecursiveIteratorIterator to traverse the structure and references to put the value into the right place of the resulting array:

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($structure),
    RecursiveIteratorIterator::SELF_FIRST
);

$filters = array_flip($results);

$keys = [];

$resultsInStructure = [];
foreach ($iterator as $key => $value) {
    if ($key === 'id') {
        continue;
    }

    // Put key to the stack, so we can get the path of results.
    $keys[$iterator->getDepth()] = $key;

    if (!isset($filters[$key])) {
        continue;
    }

    // Put the result in the right place in the tree structure.
    $tmp =& $resultsInStructure;
    foreach (array_slice($keys, 0, $iterator->getDepth()) as $_key) {
        if (!isset($tmp[$_key])) {
            $tmp[$_key] = [];
        }
        $tmp =& $tmp[$_key];
    }
    $tmp[$key] = $value;
}

Here is working demo.


问:
How are xsd schema ref and type attribute values' namespaces aliased/bound?
Given a couple of example XSD definitions:

http://docs.oasis-open.org/security/saml/v2.0/saml-schema-assertion-2.0.xsd

https://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd

Both XSD documents define elements, attributes, attributeGroups and/or types that self-reference other definitions within the same document. In the case of the first, these types seem to be namespaced using the saml namespace alias/binding. Example:

```<code><attributeGroup ref="saml:IDNameQualifiers"/>
</code>```

and in the case of the second, they are namespaced using the ds namespace alias/binding. Example:

```<code><element ref="ds:SignedInfo"/>
</code>```

However, viewing either document in Firefox, I cannot see in either document where these namespace aliases or bindings are defined.

The first document's root element gives a targetNamespace attribute:

```<code>targetNamespace="urn:oasis:names:tc:SAML:2.0:assertion"
</code>```

as does the second:

```<code>targetNamespace="http://www.w3.org/2000/09/xmldsig#"
</code>```

but is it just convention that aliases the first to saml and the second to ds? If so, where could one look to find these conventions? If not, what is going on to resolve these namespaces?

答:
The namespace bindings are defined (as is best practice) in the root element of the schema with xmlns: attributes:

saml-schema-assertion-2.0.xsd

```<code><schema
  xmlns="http://www.w3.org/2001/XMLSchema"
  xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
  [...]
  targetNamespace="urn:oasis:names:tc:SAML:2.0:assertion"
  [...]>
</code>```

xmldsig-core-schema.xsd

```<code><schema
  xmlns="http://www.w3.org/2001/XMLSchema"
  xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
  targetNamespace="http://www.w3.org/2000/09/xmldsig#"
  [...]>
</code>```

These bindings do not only apply to element and attribute names (in a schema, which is also an XML document, they are mostly in the XML Schema namespace or in no namespace), but also to attribute values that are declared as QNames in the associated schema (in this case, the XML Schema Schema).

This is the case of the ref and type attributes (quoting from the above linked schema schema):

```<code><xs:attribute name="ref" type="xs:QName"/>
<xs:attribute name="type" type="xs:QName"/>
<!-- observe how the declaration for the type attribute uses itself! -->
</code>```

This is the reason why, in any schema that references its own element/attribute/type declarations and that has a target namespace, this target namespace needs to be bound to a prefix (or made default) for use in the ref and type attribute values.

In a nutshell, the key idea to understanding the machinery involved here is to forget, for a moment, that the two .xsd documents are schemas, and to see them instead as any other XML documents that are valid against the XML Schema Schema. And more: the XML Schema Schema is an XML document as well, which is valid against... itself. This is how XML Schema bootstraps itself.

Body:
Given a couple of example XSD definitions:

http://docs.oasis-open.org/security/saml/v2.0/saml-schema-assertion-2.0.xsd

https://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd

Both XSD documents define elements, attributes, attributeGroups and/or types that self-reference other definitions within the same document. In the case of the first, these types seem to be namespaced using the saml namespace alias/binding. Example:

<attributeGroup ref="saml:IDNameQualifiers"/>

and in the case of the second, they are namespaced using the ds namespace alias/binding. Example:

<element ref="ds:SignedInfo"/>

However, viewing either document in Firefox, I cannot see in either document where these namespace aliases or bindings are defined.

The first document's root element gives a targetNamespace attribute:

targetNamespace="urn:oasis:names:tc:SAML:2.0:assertion"

as does the second:

targetNamespace="http://www.w3.org/2000/09/xmldsig#"

but is it just convention that aliases the first to saml and the second to ds? If so, where could one look to find these conventions? If not, what is going on to resolve these namespaces?

Body:
The namespace bindings are defined (as is best practice) in the root element of the schema with xmlns: attributes:

saml-schema-assertion-2.0.xsd

<schema
  xmlns="http://www.w3.org/2001/XMLSchema"
  xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
  [...]
  targetNamespace="urn:oasis:names:tc:SAML:2.0:assertion"
  [...]>

xmldsig-core-schema.xsd

<schema
  xmlns="http://www.w3.org/2001/XMLSchema"
  xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
  targetNamespace="http://www.w3.org/2000/09/xmldsig#"
  [...]>

These bindings do not only apply to element and attribute names (in a schema, which is also an XML document, they are mostly in the XML Schema namespace or in no namespace), but also to attribute values that are declared as QNames in the associated schema (in this case, the XML Schema Schema).

This is the case of the ref and type attributes (quoting from the above linked schema schema):

<xs:attribute name="ref" type="xs:QName"/>
<xs:attribute name="type" type="xs:QName"/>
<!-- observe how the declaration for the type attribute uses itself! -->

This is the reason why, in any schema that references its own element/attribute/type declarations and that has a target namespace, this target namespace needs to be bound to a prefix (or made default) for use in the ref and type attribute values.

In a nutshell, the key idea to understanding the machinery involved here is to forget, for a moment, that the two .xsd documents are schemas, and to see them instead as any other XML documents that are valid against the XML Schema Schema. And more: the XML Schema Schema is an XML document as well, which is valid against... itself. This is how XML Schema bootstraps itself.


问:
Angular 2 lever checkbox input
I would like to implement a lever checkbox which is used to show/hide columns of the table. Showing and hiding works fine and lever is shown correctly initially (ON position), and when I click the first time it is switched correctly to OFF position, but after that, every subsequent click leaves it at off position</p>

```<code><a class="dropdown-item" >
    <div class="switch">
        <label>
            <input type="checkbox" (click)="HideId = !HideId" [checked]="!HideId">
            <span class="lever"></span>
            ID
        </label>
    </div>
</a>
</code>```

答:
First of all: Use camelCase variable names.

Check out this Plunker I made. This will toggle visibility of the  element.
https://plnkr.co/edit/wt2JyzphmzcCdipYA9Me?p=preview

Title: Angular 2 lever checkbox input

Body:
I would like to implement a lever checkbox which is used to show/hide columns of the table. Showing and hiding works fine and lever is shown correctly initially (ON position), and when I click the first time it is switched correctly to OFF position, but after that, every subsequent click leaves it at off position

            <input type="checkbox" (click)="HideId = !HideId" [checked]="!HideId">

            ID

Body:
First of all: Use camelCase variable names.

Check out this Plunker I made. This will toggle visibility of the <span class="lever"></span> element.
https://plnkr.co/edit/wt2JyzphmzcCdipYA9Me?p=preview


问:
Android toolbar layout width and height getting changed automatically?
I'm new to Android Studio and it is creating a lot of problem to me while setting my toolbar in and activity,the problem is whenever i change it layout width and height to the following

layout_width=match_parent

layout_height=attr/actionBarsize

it is getting back to change to the following

layout_width=368dp

layout_height=56dp

No matter how many times it tried to change it is giving me the same result again and again.

答:
XML:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay"
    android:id="@+id/coach_bar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="#F4B702"
        app:popupTheme="@style/AppTheme.PopupOverlay" >

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

 <!--<Your Design>-->

</RelativeLayout >
</code>```

Java

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setLogo(R.drawable.my_icon);
setSupportActionBar(toolbar);
if(getSupportActionBar()!=null)
  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
</code>```

Manifest.xml

```<code><activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar"/>
</code>```

Body:
XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay"
    android:id="@+id/coach_bar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="#F4B702"
        app:popupTheme="@style/AppTheme.PopupOverlay" >

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

 <!--<Your Design>-->

</RelativeLayout >

Java

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setLogo(R.drawable.my_icon);
setSupportActionBar(toolbar);
if(getSupportActionBar()!=null)
  getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Manifest.xml

<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar"/>


问:
cURL - How do i disable it requesting a response
im using a cURL script to post parameters to pages on my others sites as a update for clients, my problem is that my curl script stops while its waiting from a response to one site before continuing on to the other sites, also if one page time outs it takes ages to get on to the next, ive tryed using curl_setopt to set connectiontimeout and timeout to 0 and that doesnt work on the responses side of my problem. So getting down to it, how do i stop curl waiting for a response from the target server before moving on to the next one?

Thanks,
John

答: Firstly, you should check response, to know if everything went OK or give a second try. Solution might be to run multiple curl request at once: curl_multi_init, and if you really don't want to wait, set small timeout (but not too small, give some time to fetch DNS record and send request, try with CURLOPT_CONNECTTIMEOUT_MS) and set CURLOPT_NOBODY to true (or CURLOPT_CUSTOMREQUEST to HEAD), so curl won't wait to get whole response.


问:
parse text and get number of hours
i have a pandas dataframe with text attribute as

```<code>loc_id   text
1        'Monday: 8:30 AM \x96 5:30 PM,Tuesday: 8:30 AM \x96 5:30 PM,Wednesday: 8:30 AM \x96 5:30 PM,Thursday: 8:30 AM \x96 5:30 PM,Friday: 8:30 AM \x96 5:30 PM,Saturday: Closed,Sunday: Closed'
2         ''
3         'Monday: Open 24 hours,Tuesday: Open 24 hours,Wednesday: Open 24 hours,Thursday: Open 24 hours,Friday: Open 24 hours,Saturday: Open 24 hours,Sunday: Open 24 hours
</code>```

its a text data and i want to compute the total number of opening hours when it was open like this

```<code>loc_id      openingHours
1           45
2           NAN
3           168
</code>```

i am new to text mining so have no idea how to parse and convert it.The text only have these two formats as mentioned.

答:
This is a working solution specific to your problem!

Explanations given below.

```<code>import re
from datetime import datetime
sumtime = 0
sumlist=[]
list_of_strings = ['''Monday: 8:30 AM \x96 5:30 PM,Tuesday: 8:30 AM \x96 5:30 PM,Wednesday: 8:30 AM \x96 5:30 PM,Thursday: 8:30 AM
\x96 5:30 PM,Friday: 8:30 AM \x96 5:30 PM,Saturday: Closed,Sunday: Closed''','''Monday: Open 24 hours,Tuesday: Open 24 hours,Wednesday: Open
24 hours,Thursday: Open 24 hours,Friday: Open 24 hours,Saturday: Open 24 hours,Sunday: Open 24 hours''']

for s in list_of_strings: #Text for each loc_id
    if 'Open' not in s:
     #If the word 'Open' isn't present in the text then do below
            times = [line[0] for line in re.findall(r'\b((1[0-2]|0?[1-9]):([0-5][0-9]) ([AaPp][Mm]))',s)]
            times = [[i,j] for i,j in zip(times[0::2], times[1::2])]
            fmt = '%I:%M %p'
            time_objects = [datetime.strptime(b,fmt)-datetime.strptime(a,fmt)
                            for a,b in times]
            finaltime = [td.seconds//3600 for td in time_objects]
            sumtime=sum(finaltime)
            sumlist.append(sumtime)
    else:
    #If Open is present in the text

            open_times = [int(st) for st in s.split() if st.isdigit()]
            sumlist.append(sum(open_times))
print(sumlist)
</code>```

1) re.findall returns each and every match found in the string. It's ouput would be something like this

[('8:30 AM', '8', '30', 'AM'),('5:30 PM', '5', '30', 'PM'), ('8:30 AM', '8', '30', 'AM')]

Hence line[0] would give the first one from the tuple. i.e '8:30 AM' which we require

```<code>[line[0] for line in re.findall(r'\b((1[0-2]|0?[1-9]):([0-5][0-9]) ([AaPp][Mm]))',s)]
</code>```

2) The output of the above will be

```<code>['8:30 AM', '5:30 PM', '8:30 AM', '5:30 PM', '8:30 AM', '5:30 PM', '8:30 AM', '5:30 PM', '8:30 AM', '5:30 PM']
</code>```

3) Now every even element (0,2,4,..) of the list will be paired with odd one (1,3,5,..). Note times[0::2] here gives a list of elements starting from index 0 incrementing every index by 2. Similarly starting from index 1
incrementing by 2. And zip them together. You get this,

[['8:30 AM', '5:30 PM'], ['8:30 AM', '5:30 PM'],...and so on]

```<code>times = [[i,j] for i,j in zip(times[0::2], times[1::2])]
</code>```

4) fmt is the format fmt = '%I:%M %p'. Note it would be %H:%M but since we are using %p
the documentation clearly specifies that in that case we should us %I instead of %H. Otherwise %H is fine. Use datetime.strptime on our a,b which is [8:30 AM', '5:30 PM'] to get a datetime object. Subtract them to get a timedelta object. Convert it into seconds using timdelta_object.seconds.

```<code> [datetime.strptime(b,fmt)-datetime.strptime(a,fmt) for a,b in times]
</code>```

Then you can use td.days to get days , td//3600 to get hours

5) Find the sum of this list using sum(your_list) to get the sum which is 45 in your case. Append that to a list.

6) If the word Open is present in your text,

then get the numbers alone from the text as int and find their sum.

7) Finally the output list would be

[45, 168]

This is a working solution to the problem you have in hand. Assuming you get text either in this format

```<code>'Monday: 8:30 AM \x96 5:30 PM,Tuesday: 8:30 AM \x96 5:30 PM,Wednesday: 8:30 AM \x96 5:30 PM,Thursday: 8:30 AM \x96 5:30 PM,Friday: 8:30 AM \x96 5:30 PM,Saturday: Closed,Sunday: Closed'
</code>```

or this format

```<code>'Monday: Open 24 hours,Tuesday: Open 24 hours,Wednesday: Open 24 hours,Thursday: Open 24 hours,Friday: Open 24 hours,Saturday: Open 24 hours,Sunday: Open 24 hours'
</code>```

And also be sure to take a look at dateparser

Title: parse text and get number of hours

Body:
i have a pandas dataframe with text attribute as

loc_id   text
1        'Monday: 8:30 AM \x96 5:30 PM,Tuesday: 8:30 AM \x96 5:30 PM,Wednesday: 8:30 AM \x96 5:30 PM,Thursday: 8:30 AM \x96 5:30 PM,Friday: 8:30 AM \x96 5:30 PM,Saturday: Closed,Sunday: Closed'
2         ''
3         'Monday: Open 24 hours,Tuesday: Open 24 hours,Wednesday: Open 24 hours,Thursday: Open 24 hours,Friday: Open 24 hours,Saturday: Open 24 hours,Sunday: Open 24 hours

its a text data and i want to compute the total number of opening hours when it was open like this

loc_id      openingHours
1           45
2           NAN
3           168

i am new to text mining so have no idea how to parse and convert it.The text only have these two formats as mentioned.

Body:
This is a working solution specific to your problem!

Explanations given below.

import re
from datetime import datetime
sumtime = 0
sumlist=[]
list_of_strings = ['''Monday: 8:30 AM \x96 5:30 PM,Tuesday: 8:30 AM \x96 5:30 PM,Wednesday: 8:30 AM \x96 5:30 PM,Thursday: 8:30 AM
\x96 5:30 PM,Friday: 8:30 AM \x96 5:30 PM,Saturday: Closed,Sunday: Closed''','''Monday: Open 24 hours,Tuesday: Open 24 hours,Wednesday: Open
24 hours,Thursday: Open 24 hours,Friday: Open 24 hours,Saturday: Open 24 hours,Sunday: Open 24 hours''']

for s in list_of_strings: #Text for each loc_id
    if 'Open' not in s:
     #If the word 'Open' isn't present in the text then do below
            times = [line[0] for line in re.findall(r'\b((1[0-2]|0?[1-9]):([0-5][0-9]) ([AaPp][Mm]))',s)]
            times = [[i,j] for i,j in zip(times[0::2], times[1::2])]
            fmt = '%I:%M %p'
            time_objects = [datetime.strptime(b,fmt)-datetime.strptime(a,fmt)
                            for a,b in times]
            finaltime = [td.seconds//3600 for td in time_objects]
            sumtime=sum(finaltime)
            sumlist.append(sumtime)
    else:
    #If Open is present in the text

            open_times = [int(st) for st in s.split() if st.isdigit()]
            sumlist.append(sum(open_times))
print(sumlist)

1) re.findall returns each and every match found in the string. It's ouput would be something like this

[('8:30 AM', '8', '30', 'AM'),('5:30 PM', '5', '30', 'PM'), ('8:30 AM', '8', '30', 'AM')]

Hence line[0] would give the first one from the tuple. i.e '8:30 AM' which we require

[line[0] for line in re.findall(r'\b((1[0-2]|0?[1-9]):([0-5][0-9]) ([AaPp][Mm]))',s)]

2) The output of the above will be

['8:30 AM', '5:30 PM', '8:30 AM', '5:30 PM', '8:30 AM', '5:30 PM', '8:30 AM', '5:30 PM', '8:30 AM', '5:30 PM']

3) Now every even element (0,2,4,..) of the list will be paired with odd one (1,3,5,..). Note times[0::2] here gives a list of elements starting from index 0 incrementing every index by 2. Similarly starting from index 1
incrementing by 2. And zip them together. You get this,

[['8:30 AM', '5:30 PM'], ['8:30 AM', '5:30 PM'],...and so on]

times = [[i,j] for i,j in zip(times[0::2], times[1::2])]

4) fmt is the format fmt = '%I:%M %p'. Note it would be %H:%M but since we are using %p
the documentation clearly specifies that in that case we should us %I instead of %H. Otherwise %H is fine. Use datetime.strptime on our a,b which is [8:30 AM', '5:30 PM'] to get a datetime object. Subtract them to get a timedelta object. Convert it into seconds using timdelta_object.seconds.

 [datetime.strptime(b,fmt)-datetime.strptime(a,fmt) for a,b in times]

Then you can use td.days to get days , td//3600 to get hours

5) Find the sum of this list using sum(your_list) to get the sum which is 45 in your case. Append that to a list.

6) If the word Open is present in your text,

then get the numbers alone from the text as int and find their sum.

7) Finally the output list would be

[45, 168]

This is a working solution to the problem you have in hand. Assuming you get text either in this format

'Monday: 8:30 AM \x96 5:30 PM,Tuesday: 8:30 AM \x96 5:30 PM,Wednesday: 8:30 AM \x96 5:30 PM,Thursday: 8:30 AM \x96 5:30 PM,Friday: 8:30 AM \x96 5:30 PM,Saturday: Closed,Sunday: Closed'

or this format

'Monday: Open 24 hours,Tuesday: Open 24 hours,Wednesday: Open 24 hours,Thursday: Open 24 hours,Friday: Open 24 hours,Saturday: Open 24 hours,Sunday: Open 24 hours'

And also be sure to take a look at dateparser


问:
Laravel - hasMany() and belongsTo() not working correctly for me in @foreach loop
I got following error when I try to use this on my page

Trying to get property of non-object

I have two tables:

```<code>cvicenis
  id
  title
  body
  category_id
categories
  id
  name
</code>```

My Cviceni model:

```<code>namespace App;
use Illuminate\Database\Eloquent\Model;

class Cviceni extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category', 'id');
    }
}
</code>```

My Category model:

```<code>namespace App;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function cviceni()
    {
        return $this->hasMany('App\Cviceni', 'category_id');
    }
}
</code>```

My controller:

```<code>public function index()
{
    $cviceni = Cviceni::all();
    return view('excercises.index', compact('cviceni'));
}
</code>```

My index.blade:

```<code>@extends('layouts.app')

@section('content')
    <div class="row">
        <div class="col-sm-6 col-md-6 col-lg-3">
            <h1>Přehled cvičení</h1>
            @if(count($cviceni) > 0)
            <ul>
                @foreach ($cviceni as $c)
                    <li> {{ $c->category->name }}</li>
                @endforeach
            </ul>
            @else
                <h2>There is nothing to display</h2>
            @endif
        </div><!-- end of column -->
    </div><!-- end of row -->
@endsection
</code>```

If I use in my controller Cviceni::find(1) then I can get the value from $cviceni->category->name
But not when I use a foreach loop.
Can somebody help me please?

答:
You need to eager load the models if you need them:</p>

```<code>public function index()
{
    $cviceni = Cviceni::with("category")->get();
    return view('excercises.index', compact('cviceni'));
}
</code>```

Body:
I got following error when I try to use this on my page

Trying to get property of non-object

I have two tables:

cvicenis
  id
  title
  body
  category_id
categories
  id
  name

My Cviceni model:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Cviceni extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category', 'id');
    }
}

My Category model:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function cviceni()
    {
        return $this->hasMany('App\Cviceni', 'category_id');
    }
}

My controller:

public function index()
{
    $cviceni = Cviceni::all();
    return view('excercises.index', compact('cviceni'));
}

My index.blade:

@extends('layouts.app')

@section('content')

Přehled cvičení

            @if(count($cviceni) > 0)

                @foreach ($cviceni as $c)

 {{ $c->category->name }}

                @endforeach

            @else

There is nothing to display

            @endif

@endsection

If I use in my controller Cviceni::find(1) then I can get the value from $cviceni->category->name
But not when I use a foreach loop.
Can somebody help me please?

Body:
You need to eager load the models if you need them:

public function index()
{
    $cviceni = Cviceni::with("category")->get();
    return view('excercises.index', compact('cviceni'));
}