问:
ASP .NET MVC multiple models in one view
I have this two classes:

```<code>public class Kolobezka : IEntity1
{
    public virtual int Id { get; set; }
    public virtual int VelikostKola { get; set; }
    public virtual string Znacka { get; set; }
    public virtual string Stav { get; set; }
    public virtual string Description { get; set; }
    public virtual Kategorie_kolobezek Kategorie { get; set; }
    public virtual int Dostupnost { get; set; }

}
public class Rezervace : IEntity1
    {
        public virtual int Id { get; set; }
        public virtual Kolobezka Rez_kolobezky { get; set; }
        [Required(ErrorMessage = "Jméno je požadováno!")]
        public virtual string Jmeno { get; set; }
        [Required(ErrorMessage = "Příjmení je požadováno!")]
        public virtual string Prijmeni { get; set; }
        [Required(ErrorMessage = "Datum začátku rezervace je požadováno!")]
        public virtual DateTime Datum_od { get; set; }
        [Required(ErrorMessage = "Datum konce rezervace je požadováno!")]
        public virtual DateTime Datum_do { get; set; }
        public virtual string Popis { get; set; }
    }
</code>```

So I need in one view called Index use two Ilists from those two clases because of this:

```<code>@foreach (Kolobezka k in Model)
        {

            foreach (Rezervace r1 in r)
            {
                if(k.Id == r1.Rez_kolobezky.Id && r1.Datum_od < DateTime.Now && r1.Datum_do > DateTime.Now)
                {
                    k.Dostupnost = 1;
                }
            }

            if (k.Dostupnost == 0)
            {
                <tr class="bg-danger">
                    <td>
                        @Ajax.ActionLink(k.Id.ToString(), "Detail", new { id = k.Id },
                       new AjaxOptions() { UpdateTargetId = "modalContent",
                           InsertionMode = InsertionMode.Replace, OnBegin = "openModalWindow" })
                    </td>
                    <td>@k.VelikostKola</td>
                    <td>@k.Znacka</td>
                    <td>@k.Kategorie.Nazev</td>
                    <td>@k.Stav</td>
                </tr>
            }
</code>```

Whot should I write instead r in the second foreach.
The beginning of index view looks like this:

```<code>@using ClassLibrary1.Model
@model IList<Kolobezka>

@{
    ViewBag.Title = "Index";
}
</code>```

Thank you a lot.

答:
I don't think you need two models. The below is not using any HTML markup why do you need to do in view. You have to do this in controller and pass Kolobezka list to view

```<code>foreach (Rezervace r1 in r)
        {
            if(k.Id == r1.Rez_kolobezky.Id && r1.Datum_od < DateTime.Now && r1.Datum_do > DateTime.Now)
            {
                k.Dostupnost = 1;
            }
        }
</code>```

But if still want two models passed to view create a view model and add these classes to it as properties

```<code>public class viewmodel
{
public Rezervace model1 { get;set;}
public Kolobezka model2 { get;set;}
}
</code>```

Body:
I have this two classes:

public class Kolobezka : IEntity1
{
    public virtual int Id { get; set; }
    public virtual int VelikostKola { get; set; }
    public virtual string Znacka { get; set; }
    public virtual string Stav { get; set; }
    public virtual string Description { get; set; }
    public virtual Kategorie_kolobezek Kategorie { get; set; }
    public virtual int Dostupnost { get; set; }

}
public class Rezervace : IEntity1
    {
        public virtual int Id { get; set; }
        public virtual Kolobezka Rez_kolobezky { get; set; }
        [Required(ErrorMessage = "Jméno je požadováno!")]
        public virtual string Jmeno { get; set; }
        [Required(ErrorMessage = "Příjmení je požadováno!")]
        public virtual string Prijmeni { get; set; }
        [Required(ErrorMessage = "Datum začátku rezervace je požadováno!")]
        public virtual DateTime Datum_od { get; set; }
        [Required(ErrorMessage = "Datum konce rezervace je požadováno!")]
        public virtual DateTime Datum_do { get; set; }
        public virtual string Popis { get; set; }
    }

So I need in one view called Index use two Ilists from those two clases because of this:

@foreach (Kolobezka k in Model)
        {

            foreach (Rezervace r1 in r)
            {
                if(k.Id == r1.Rez_kolobezky.Id && r1.Datum_od < DateTime.Now && r1.Datum_do > DateTime.Now)
                {
                    k.Dostupnost = 1;
                }
            }

            if (k.Dostupnost == 0)
            {

                        @Ajax.ActionLink(k.Id.ToString(), "Detail", new { id = k.Id },
                       new AjaxOptions() { UpdateTargetId = "modalContent",
                           InsertionMode = InsertionMode.Replace, OnBegin = "openModalWindow" })

                    @k.VelikostKola
                    @k.Znacka
                    @k.Kategorie.Nazev
                    @k.Stav

            }

Whot should I write instead r in the second foreach.
The beginning of index view looks like this:

@using ClassLibrary1.Model
@model IList<Kolobezka>

@{
    ViewBag.Title = "Index";
}

Thank you a lot.

Body:
I don't think you need two models. The below is not using any HTML markup why do you need to do in view. You have to do this in controller and pass Kolobezka list to view

foreach (Rezervace r1 in r)
        {
            if(k.Id == r1.Rez_kolobezky.Id && r1.Datum_od < DateTime.Now && r1.Datum_do > DateTime.Now)
            {
                k.Dostupnost = 1;
            }
        }

But if still want two models passed to view create a view model and add these classes to it as properties

public class viewmodel
{
public Rezervace model1 { get;set;}
public Kolobezka model2 { get;set;}
}


来源: stackexchange

问:
AMQP implementations with Celery
I wanted to get your opinions on the merits of different AMQP implementations to be used with celery. I am looking particularly at message prioritization and job queue sizes.
What are your thoughts?  </p>

答: After reading some docs and trying out a few options, I have found that RabbitMQ suffices for most purposes.</p>

ContentLicense: CC BY-SA 2.5

Title: AMQP implementations with Celery


问:
Controller in its own dependency injection
I am not aware of latest release of angularjs. I saw a piece of code like below

```<code>angular.module('app')
    .controller('myApp', [myApp]);

function myApp() {
      var vm = this;
      vm.title = 'Customers';
      vm.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
    };
</code>```

instead of code i used to write earlier like

```<code>angular.module('app')
    .controller('myApp', function($scope){
      $scope.title = 'Customers';
      $scope.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
});
</code>```

So why are we injecting the functionality required for the controller? what advantage does it provide. Correct me if my understanding is wrong.

答:
What it does is instead of calling an anonymous function from controller its separate the function from the controller and call the function.In this case, function name is myApp

reason to call it with square brackets is when you are using angular minify version, dependency injector unable to identify the dependency so it produces an error.

In order to identify the relevant dependency by the injector, angular allow you to write dependency as string array when you are initializing controller. Since there is no dependency in this example only empty square brackets appear.

If you have a dependency, let's say $scope then you need to inject it like this

```<code>angular.module('app')
    .controller('myApp', ['$scope',myApp]);

function myApp($scope) {
      var vm = this;
      vm.title = 'Customers';
      vm.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
    };
</code>```

This also can be done using $inject also

```<code>angular.module('app')
        .controller('myApp',myApp);

    myApp.$inject = ['$scope'];

    function myApp($scope) {
          var vm = this;
          vm.title = 'Customers';
          vm.customers = [
            {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
            ];
        };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am not aware of latest release of angularjs. I saw a piece of code like below

angular.module('app')
    .controller('myApp', [myApp]);

function myApp() {
      var vm = this;
      vm.title = 'Customers';
      vm.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
    };

instead of code i used to write earlier like

angular.module('app')
    .controller('myApp', function($scope){
      $scope.title = 'Customers';
      $scope.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
});

So why are we injecting the functionality required for the controller? what advantage does it provide. Correct me if my understanding is wrong.

Body:
What it does is instead of calling an anonymous function from controller its separate the function from the controller and call the function.In this case, function name is myApp

reason to call it with square brackets is when you are using angular minify version, dependency injector unable to identify the dependency so it produces an error.

In order to identify the relevant dependency by the injector, angular allow you to write dependency as string array when you are initializing controller. Since there is no dependency in this example only empty square brackets appear.

If you have a dependency, let's say $scope then you need to inject it like this

angular.module('app')
    .controller('myApp', ['$scope',myApp]);

function myApp($scope) {
      var vm = this;
      vm.title = 'Customers';
      vm.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
    };

This also can be done using $inject also

angular.module('app')
        .controller('myApp',myApp);

    myApp.$inject = ['$scope'];

    function myApp($scope) {
          var vm = this;
          vm.title = 'Customers';
          vm.customers = [
            {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
            ];
        };


问:
 link is not working on the div

STEAK HOUSE
RESTAURANT

Jeddah

      Name:

Steak House Restaurant

 Location:

Jeddah

```

The  element is the parent of the class "txt" and when I try to make  the parent of the entire "gallery-cell" class it doesn't work!
I want the entire cell to be clickable, not just the text.

If you want, take a look at this website to test it out: http://urbanphenomena.net/

答:
Add This CSS</p>

```<code>.highslide-gallery {
    height: 100%;
    width: 100%;
}
.highslide {
    display: block;
    height: 100%;
    outline: medium none;
    width: 100%;
}
</code>```

Title: <a> link is not working on the div

Body:
STEAK HOUSE
RESTAURANT

Jeddah

      Name:

Steak House Restaurant

 Location:

Jeddah

The  element is the parent of the class "txt" and when I try to make  the parent of the entire "gallery-cell" class it doesn't work!
I want the entire cell to be clickable, not just the text.

If you want, take a look at this website to test it out: http://urbanphenomena.net/

Body:
Add This CSS

.highslide-gallery {
    height: 100%;
    width: 100%;
}
.highslide {
    display: block;
    height: 100%;
    outline: medium none;
    width: 100%;
}


问:
How can array state be changed?
I can't understand how to make array passed via combinereducers.

After action dispatched, I want to concatenate input text with array.(state d)

An example in redux site says as below, in reducer,and I did just like it.(checkD_E function)

```<code>return Object.assign({}, state, {
    todos: [
      ...state.todos,
      {
        text: action.text,
        completed: false
       }
    ]
      })
</code>```

d is always updated only to concatenate undefined and last inputed text.

first "undefined" is caused from that initialState isn't read.(const initialState variable)

```<code>    const ADD_TODO = 'ADD_TODO'
    const BDD_TODO = 'BDD_TODO'
    const DDD_TODO = 'DDD_TODO'
    const EDD_TODO = 'EDD_TODO'
    const {PropTypes} = React;
    const {createStore,combineReducers} = Redux;
    const { Provider, connect} = ReactRedux;
    let store = createStore(rootReducer)

    function changeA(text) {
      return { type: ADD_TODO, text }
    }
    function changeB(text) {
      return { type: BDD_TODO, text }
    }
    function changeD(text) {
      return { type: DDD_TODO, text }
    }
    function changeE(text) {
      return { type: EDD_TODO, text }
    }

    function checkA_B(state={},action){
      switch (action.type) {
        case ADD_TODO:
          return Object.assign({}, state.checkA_B, {a:action.text})
        case BDD_TODO:
          return Object.assign({}, state.checkA_B, {b:action.text})
        case DDD_TODO:
          return state
        default:
          return state
                     }
    }
    function checkD_E(state=[],action){
      switch (action.type) {
        case DDD_TODO:
          return Object.assign({}, state,{
        d: [...state.d,action.text]
          } )
        case EDD_TODO:
          return Object.assign({}, state, {e:action.text})
        default:
          return state

    const initialState ={
      a:"aaa",b:"bbb",c:"ccc",d:[],e:"eee"
    }
    function rootReducer(state = initialState,action){
      return {
        checkA_B:checkA_B(state,action),
        checkD_E:checkD_E(state,action)
      }
    class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = {a:props.a,b:props.b,d:props.d,e:props.e,inputText:props.inputText,onClick:props.onClick};
        this.onInput = this.onInput.bind(this)
        this.onSubmit = this.onSubmit.bind(this)
      }
      onInput(e){
        this.setState({inputText:e.target.value})
      }
      onSubmit(e){
        e.preventDefault()
        this.state.onClick(this.state.inputText)
        this.setState({inputText:""})
      }
      render() {
        return (
          <div>
        <form onSubmit={this.onSubmit}>
          <input value={this.state.inputText} onChange={this.onInput} />
          <button type="submit">Add Todo</button>
        </form>
        <label>{console.log(this.props.d.map(x=>return x))}</label><label>{this.state.b}</label><label>{this.state.c}</label>
          </div>
        );
      }
    }
    Clock.propTypes = {

      inputText:PropTypes.string.isRequired,
      onClick:PropTypes.func.isRequired,
      a:PropTypes.string.isRequired,
      b:PropTypes.string.isRequired,
      d:PropTypes.array.isRequired,
      e:PropTypes.string.isRequired
    }
    function mapDispatchToProps(dispatch){
     return {onClick:(x)=>{
      dispatch(changeD(x))
     }
      }
    }
    function mapStateToProps(state,ownProps){
      return {d:state.checkD_E.d}
    }
    Clock = connect(mapStateToProps,mapDispatchToProps)(Clock)
    ReactDOM.render(
         <Provider store={store}><Clock /></Provider>,
      document.getElementById('root')
    );

index.html
    <div id="root">
      <!-- This element's contents will be replaced with your component. -->
    </div>
</code>```

I guess returned value in mapStatetoProps has to be changed.

But I have no idea.

答:
You have at least two issues.

(1) Your rootReducer doesn't call combineReducer. Consider something like:

```<code>const rootReducer = combineReducers({
  checkA_B: checkA_B,
  checkD_E: checkD_E,
});
</code>```

Note the values are functions.

(2) The shape of your state doesn't match your intended reducer structure.
It should be closer to:

```<code>const initialState = {
  checkA_B: { a: "aaa", b: "bbb" },
  checkD_E: { d: [], e: "eee" },
}
</code>```

The keys of 'initialState' match the keys of the argument of 'combineReducers'.  (I left out 'c' from initialState because it's not clear with which reducer it is associated.)

The good news is, you are correctly making a copy of the state in your reducer.

This may not be every issue with your code, but it should get you closer.

Title: How can array state be changed?

Body:
I can't understand how to make array passed via combinereducers.

After action dispatched, I want to concatenate input text with array.(state d)

An example in redux site says as below, in reducer,and I did just like it.(checkD_E function)

return Object.assign({}, state, {
    todos: [
      ...state.todos,
      {
        text: action.text,
        completed: false
       }
    ]
      })

d is always updated only to concatenate undefined and last inputed text.

first "undefined" is caused from that initialState isn't read.(const initialState variable)

    const ADD_TODO = 'ADD_TODO'
    const BDD_TODO = 'BDD_TODO'
    const DDD_TODO = 'DDD_TODO'
    const EDD_TODO = 'EDD_TODO'
    const {PropTypes} = React;
    const {createStore,combineReducers} = Redux;
    const { Provider, connect} = ReactRedux;
    let store = createStore(rootReducer)

    function changeA(text) {
      return { type: ADD_TODO, text }
    }
    function changeB(text) {
      return { type: BDD_TODO, text }
    }
    function changeD(text) {
      return { type: DDD_TODO, text }
    }
    function changeE(text) {
      return { type: EDD_TODO, text }
    }

    function checkA_B(state={},action){
      switch (action.type) {
        case ADD_TODO:
          return Object.assign({}, state.checkA_B, {a:action.text})
        case BDD_TODO:
          return Object.assign({}, state.checkA_B, {b:action.text})
        case DDD_TODO:
          return state
        default:
          return state
                     }
    }
    function checkD_E(state=[],action){
      switch (action.type) {
        case DDD_TODO:
          return Object.assign({}, state,{
        d: [...state.d,action.text]
          } )
        case EDD_TODO:
          return Object.assign({}, state, {e:action.text})
        default:
          return state

    const initialState ={
      a:"aaa",b:"bbb",c:"ccc",d:[],e:"eee"
    }
    function rootReducer(state = initialState,action){
      return {
        checkA_B:checkA_B(state,action),
        checkD_E:checkD_E(state,action)
      }
    class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = {a:props.a,b:props.b,d:props.d,e:props.e,inputText:props.inputText,onClick:props.onClick};
        this.onInput = this.onInput.bind(this)
        this.onSubmit = this.onSubmit.bind(this)
      }
      onInput(e){
        this.setState({inputText:e.target.value})
      }
      onSubmit(e){
        e.preventDefault()
        this.state.onClick(this.state.inputText)
        this.setState({inputText:""})
      }
      render() {
        return (

        <form onSubmit={this.onSubmit}>
          <input value={this.state.inputText} onChange={this.onInput} />
          <button type="submit">Add Todo</button>
        </form>
        {console.log(this.props.d.map(x=>return x))}{this.state.b}{this.state.c}

        );
      }
    }
    Clock.propTypes = {

      inputText:PropTypes.string.isRequired,
      onClick:PropTypes.func.isRequired,
      a:PropTypes.string.isRequired,
      b:PropTypes.string.isRequired,
      d:PropTypes.array.isRequired,
      e:PropTypes.string.isRequired
    }
    function mapDispatchToProps(dispatch){
     return {onClick:(x)=>{
      dispatch(changeD(x))
     }
      }
    }
    function mapStateToProps(state,ownProps){
      return {d:state.checkD_E.d}
    }
    Clock = connect(mapStateToProps,mapDispatchToProps)(Clock)
    ReactDOM.render(
         <Provider store={store}><Clock /></Provider>,
      document.getElementById('root')
    );

index.html

I guess returned value in mapStatetoProps has to be changed.

But I have no idea.

Body:
You have at least two issues.

(1) Your rootReducer doesn't call combineReducer. Consider something like:

const rootReducer = combineReducers({
  checkA_B: checkA_B,
  checkD_E: checkD_E,
});

Note the values are functions.

(2) The shape of your state doesn't match your intended reducer structure.
It should be closer to:

const initialState = {
  checkA_B: { a: "aaa", b: "bbb" },
  checkD_E: { d: [], e: "eee" },
}

The keys of 'initialState' match the keys of the argument of 'combineReducers'.  (I left out 'c' from initialState because it's not clear with which reducer it is associated.)

The good news is, you are correctly making a copy of the state in your reducer.

This may not be every issue with your code, but it should get you closer.


问:
How to get arguments from two lists which makes the value of any function maximum?
```<code>any_func=lambda x,y:x/(y+1)
list1=[1,2,3,4,5,6,7,8]
list2=[4,5,6,7,9,2,3,5,7,8]
</code>```

I have two lists list1 and list2,I want to Step 1:get element pair from the two lists which makes the function any_func has maximum value, and step2: then remove these two elements from original lists, continue step 1 and step 2 until list1 or list2 is empty,summation of all results of any_func.
Is there any trick with python?

答:
It sounds like you are looking for the cartesian product of the 2 lists, itertools.product() gives you the cartesian product.

If you want the max then the key argument to max() defines how you evaluate the max:

```<code>>>> import itertools as it
>>> max(it.product(list1, list2), key=lambda x: any_func(x[0], x[1]))
(8, 2)
</code>```

However it sounds like you just want the sum of this product:

```<code>>>> sum(any_func(a, b) for a, b in it.product(list1, list2))
61.94285714285714
</code>```

Body:
any_func=lambda x,y:x/(y+1)
list1=[1,2,3,4,5,6,7,8]
list2=[4,5,6,7,9,2,3,5,7,8]

I have two lists list1 and list2,I want to Step 1:get element pair from the two lists which makes the function any_func has maximum value, and step2: then remove these two elements from original lists, continue step 1 and step 2 until list1 or list2 is empty,summation of all results of any_func.
Is there any trick with python?

Body:
It sounds like you are looking for the cartesian product of the 2 lists, itertools.product() gives you the cartesian product.

If you want the max then the key argument to max() defines how you evaluate the max:

>>> import itertools as it
>>> max(it.product(list1, list2), key=lambda x: any_func(x[0], x[1]))
(8, 2)

However it sounds like you just want the sum of this product:

>>> sum(any_func(a, b) for a, b in it.product(list1, list2))
61.94285714285714


问:
gfortran error: unexpected element '\' in format string at (1)
I have a project written in VS2010 with Intel Visual Fortran. I have a dump subroutine to write a 2D matrix into file:

```<code>subroutine Dump2D(Name,Nx,Ny,Res)
    implicit none
    integer i,j,Nx,Ny
    real(8) :: Res(Nx,Ny)
    character(len=30) name,Filename
    logical alive
    write(filename,*) trim(Name),".dat"
    Write(*,*) "Saving ",trim(Name)," Please wait..."
    open (10,file=filename)
    do i=1,Ny
           Write(10,FMt="(D21.13\)")   (Res(j,i),j=1,Nx)
           Write(10,*)
    end do
    close(10)
    Write(*,*) "Save ",trim(Name),"Complete!"
    return
end subroutine Dump2D
</code>```

It is ok to compile and run. But when I compile in emacs using gfortran it gives me the error:

I think it's because the gfortran doesn't recognize \ in a format for a write command. How do I fix this problem?

```<code>                Write(10,FMt="(D21.13\)") (Res(j,i),j=1,Nx)
                                   1
Error: Unexpected element '\' in format string at (1)
</code>```

答:
Another approach (although francescalus answer is better in your case) would be to build a format string that contains the number of elements to include in your row. One way of doing this is to use the following to build the format string (which uses an explicit space character to separate elements within a line in the file):

```<code>WRITE(fmtString, '(A,I0,A)') '(', Nx, '(D21.13,:,1X))'    *
</code>```

Then use the format string variable in your WRITE statement as so:

```<code>do i=1,Ny
   Write(10,FMt=fmtString)   (Res(j,i),j=1,Nx)
end do
</code>```

This approach can also be very useful if you want to use something other than spaces to separate elements (e.g. commas or semicolons).

*As that's a little difficult to read, I will provide an example. For Nx = 3, this would be equivalent to:

```<code>fmtString = '(3(D21.13,:,1X))'
</code>```

Which is 2 numbers formatted using D21.13, each followed by a space, and a final number formatted using D21.13, but without a space after it (as the ":" stops at the final item).

Body:
I have a project written in VS2010 with Intel Visual Fortran. I have a dump subroutine to write a 2D matrix into file:

subroutine Dump2D(Name,Nx,Ny,Res)
    implicit none
    integer i,j,Nx,Ny
    real(8) :: Res(Nx,Ny)
    character(len=30) name,Filename
    logical alive
    write(filename,*) trim(Name),".dat"
    Write(*,*) "Saving ",trim(Name)," Please wait..."
    open (10,file=filename)
    do i=1,Ny
           Write(10,FMt="(D21.13\)")   (Res(j,i),j=1,Nx)
           Write(10,*)
    end do
    close(10)
    Write(*,*) "Save ",trim(Name),"Complete!"
    return
end subroutine Dump2D

It is ok to compile and run. But when I compile in emacs using gfortran it gives me the error:

I think it's because the gfortran doesn't recognize \ in a format for a write command. How do I fix this problem?

                Write(10,FMt="(D21.13\)") (Res(j,i),j=1,Nx)
                                   1
Error: Unexpected element '\' in format string at (1)

Body:
Another approach (although francescalus answer is better in your case) would be to build a format string that contains the number of elements to include in your row. One way of doing this is to use the following to build the format string (which uses an explicit space character to separate elements within a line in the file):

WRITE(fmtString, '(A,I0,A)') '(', Nx, '(D21.13,:,1X))'    *

Then use the format string variable in your WRITE statement as so:

do i=1,Ny
   Write(10,FMt=fmtString)   (Res(j,i),j=1,Nx)
end do

This approach can also be very useful if you want to use something other than spaces to separate elements (e.g. commas or semicolons).

*As that's a little difficult to read, I will provide an example. For Nx = 3, this would be equivalent to:

fmtString = '(3(D21.13,:,1X))'

Which is 2 numbers formatted using D21.13, each followed by a space, and a final number formatted using D21.13, but without a space after it (as the ":" stops at the final item).


问:
Can Windivert injects packets larger than MTU?
I used winpcap and I got errors on "pcap_sendpacket", I fragmented the packet in little IP packets with the size of the MTU and did not work even wireshark didnt show errors in the packets which I fragmented.

Now I have this question, Can windivert inject packets larger than MTU? I need to know that before try to disable the "large send offload", if I disable that will me be able to send packet with winpcap larger than MTU, and with windivert? Is the only way to solve this?.

Sometimes in my program I have to fordward packet which I receive in winpcap with a size of 2300 bytes and my MTU has 1500 and It fails. If i receive the packet with windivert and send it with windivert will I have errors? Is a solution to disable the LSO?.

Regards.

答:
Now I have this question, Can windivert inject packets larger than MTU?

Yes you should be able to "inject" it.  However, the packet may be dropped (IPv6) or fragmented (IPv4) by the network en route to the destination.


问:
How does it start the device in tensorflow？
How does it start the device in tensorflow？And where can I found the details  in source code.  I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.   </p>

答:
You can assign a task to a device like this:

```<code># Creates a graph.
with tf.device('/cpu:0'):
  a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
  b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
  c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print sess.run(c)
</code>```

taken from here

Body:
You can assign a task to a device like this:

# Creates a graph.
with tf.device('/cpu:0'):
  a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
  b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
  c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print sess.run(c)

taken from here


问:
JSON Array of objects to plain old java object
this is my first time making an external api call in Java, so please bear with me as I'm not very experienced. I got the http request working and got a response, but now I need to parse it.

I'm trying to convert a json array to java objects. I understand the gist of it, but all examples I've seen don't apply to my issue.

I need the 'entities' objects from the json string. The details (which are an array, too) can contain any key/value pair, so I was thinking of putting that in a hashmap in each Entity object. I've tried the gson library, but I can't find any gson example that goes deeper than a single dimensional json array.

I realize this is kind of a broad question, and I don't expect anyone to deliver me a working solution, but a few tips or a link to a relevant guide would go a long way. :)

```<code>{
   "return": {
      "entities": [
         {
            "id": 2385,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "John Wick",
                  "match": false
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2385"
         },
         {
            "id": 2384,
            "details": [
               {
                  "name": "Discord ID",
                  "value": "159985870458322944",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561197991558078",
                  "match": true
               },
               {
                  "name": "SteamVanity",
                  "value": "test",
                  "match": false
               },
               {
                  "name": "PS4",
                  "value": "John_S",
                  "match": false
               },
               {
                  "name": "XBox",
                  "value": "John S",
                  "match": false
               },
               {
                  "name": "Email",
                  "value": "john_smith@gmail.com",
                  "match": true
               },
               {
                  "name": "Comment",
                  "value": "Test user",
                  "match": false
               },
               {
                  "name": "Other Known Name",
                  "value": "Jonathan",
                  "match": false
               },
               {
                  "name": "Reddit",
                  "value": "/u/johns",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2384"
         },
         {
            "id": 1680,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "Johny",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198213003675",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1680"
         },
         {
            "id": 1689,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "JohnnyPeto",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198094228192",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1689"
         }
      ],
      "notice": "Showing 4 out of 4 matches."
   }
}
</code>```

答:
As my fellow stackoverflow users have previously posted, for this kind of initilization Jackson API would be better. I have however posted the solution for your question with Gson.

I noticed that you like your details to be stored as a HashMap with id as key. However, it seems like this id is actually related to the entities and not to the details.

Disclaimer, I got lazy and used an online POJO generator because I did not want to create objects for all of the Json elements ;) It still showcases how it should be done:

```<code>class Main{

public static void main(String[] args) throws FileNotFoundException {
//this is just to load the json file
    String input = new Scanner(new File("test.txt")).useDelimiter("\\Z").next();

    System.out.println(input);
    Gson gson = new Gson();
    Example arr = gson.fromJson(input, Example.class);

    System.out.println(arr);
}

public class Detail {

    @SerializedName("name")
    @Expose
    public String name;
    @SerializedName("value")
    @Expose
    public String value;
    @SerializedName("match")
    @Expose
    public Boolean match;
    @Override
    public String toString() {
        return "Detail [name=" + name + ", value=" + value + ", match=" + match + "]";
    }

    }

public class Entity {

    @SerializedName("id")
    @Expose
    public Integer id;
    @SerializedName("details")
    @Expose
    public List<Detail> details = null;
    @SerializedName("proofs")
    @Expose
    public List<Object> proofs = null;
    @SerializedName("link")
    @Expose
    public String link;
    @Override
    public String toString() {
        return "Entity [id=" + id + ", details=" + details + ", proofs=" + proofs + ", link=" + link + "]";
    }

    }

public class Example {

    @SerializedName("return")
    @Expose
    public Return _return;

    @Override
    public String toString() {
        return "Example [_return=" + _return + "]";
    }

    }
public class Return {

    @SerializedName("entities")
    @Expose
    public List<Entity> entities = null;
    @SerializedName("notice")
    @Expose
    public String notice;
    @Override
    public String toString() {
        return "Return [entities=" + entities + ", notice=" + notice + "]";
    }

    }
}
</code>```

Output

```<code>Example [_return=Return [entities=[Entity [id=2385, details=[Detail [name=Other Known Name, value=John Wick, match=false]], proofs=[], link=http://domain.gg/users?id=2385], Entity [id=2384, details=[Detail [name=Discord ID, value=159985870458322944, match=false], Detail [name=SteamID64, value=76561197991558078, match=true], Detail [name=SteamVanity, value=test, match=false], Detail [name=PS4, value=John_S, match=false], Detail [name=XBox, value=John S, match=false], Detail [name=Email, value=john_smith@gmail.com, match=true], Detail [name=Comment, value=Test user, match=false], Detail [name=Other Known Name, value=Jonathan, match=false], Detail [name=Reddit, value=/u/johns, match=true]], proofs=[], link=http://domain.gg/users?id=2384], Entity [id=1680, details=[Detail [name=Other Known Name, value=Johny, match=false], Detail [name=SteamID64, value=76561198213003675, match=true]], proofs=[], link=http://domain.gg/users?id=1680], Entity [id=1689, details=[Detail [name=Other Known Name, value=JohnnyPeto, match=false], Detail [name=SteamID64, value=76561198094228192, match=true]], proofs=[], link=http://domain.gg/users?id=1689]], notice=Showing 4 out of 4 matches.]]
</code>```

Body:
this is my first time making an external api call in Java, so please bear with me as I'm not very experienced. I got the http request working and got a response, but now I need to parse it.

I'm trying to convert a json array to java objects. I understand the gist of it, but all examples I've seen don't apply to my issue.

I need the 'entities' objects from the json string. The details (which are an array, too) can contain any key/value pair, so I was thinking of putting that in a hashmap in each Entity object. I've tried the gson library, but I can't find any gson example that goes deeper than a single dimensional json array.

I realize this is kind of a broad question, and I don't expect anyone to deliver me a working solution, but a few tips or a link to a relevant guide would go a long way. :)

{
   "return": {
      "entities": [
         {
            "id": 2385,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "John Wick",
                  "match": false
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2385"
         },
         {
            "id": 2384,
            "details": [
               {
                  "name": "Discord ID",
                  "value": "159985870458322944",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561197991558078",
                  "match": true
               },
               {
                  "name": "SteamVanity",
                  "value": "test",
                  "match": false
               },
               {
                  "name": "PS4",
                  "value": "John_S",
                  "match": false
               },
               {
                  "name": "XBox",
                  "value": "John S",
                  "match": false
               },
               {
                  "name": "Email",
                  "value": "john_smith@gmail.com",
                  "match": true
               },
               {
                  "name": "Comment",
                  "value": "Test user",
                  "match": false
               },
               {
                  "name": "Other Known Name",
                  "value": "Jonathan",
                  "match": false
               },
               {
                  "name": "Reddit",
                  "value": "/u/johns",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2384"
         },
         {
            "id": 1680,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "Johny",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198213003675",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1680"
         },
         {
            "id": 1689,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "JohnnyPeto",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198094228192",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1689"
         }
      ],
      "notice": "Showing 4 out of 4 matches."
   }
}

Body:
As my fellow stackoverflow users have previously posted, for this kind of initilization Jackson API would be better. I have however posted the solution for your question with Gson.

I noticed that you like your details to be stored as a HashMap with id as key. However, it seems like this id is actually related to the entities and not to the details.

Disclaimer, I got lazy and used an online POJO generator because I did not want to create objects for all of the Json elements ;) It still showcases how it should be done:

class Main{

public static void main(String[] args) throws FileNotFoundException {
//this is just to load the json file
    String input = new Scanner(new File("test.txt")).useDelimiter("\\Z").next();

    System.out.println(input);
    Gson gson = new Gson();
    Example arr = gson.fromJson(input, Example.class);

    System.out.println(arr);
}

public class Detail {

    @SerializedName("name")
    @Expose
    public String name;
    @SerializedName("value")
    @Expose
    public String value;
    @SerializedName("match")
    @Expose
    public Boolean match;
    @Override
    public String toString() {
        return "Detail [name=" + name + ", value=" + value + ", match=" + match + "]";
    }

    }

public class Entity {

    @SerializedName("id")
    @Expose
    public Integer id;
    @SerializedName("details")
    @Expose
    public List<Detail> details = null;
    @SerializedName("proofs")
    @Expose
    public List<Object> proofs = null;
    @SerializedName("link")
    @Expose
    public String link;
    @Override
    public String toString() {
        return "Entity [id=" + id + ", details=" + details + ", proofs=" + proofs + ", link=" + link + "]";
    }

    }

public class Example {

    @SerializedName("return")
    @Expose
    public Return _return;

    @Override
    public String toString() {
        return "Example [_return=" + _return + "]";
    }

    }
public class Return {

    @SerializedName("entities")
    @Expose
    public List<Entity> entities = null;
    @SerializedName("notice")
    @Expose
    public String notice;
    @Override
    public String toString() {
        return "Return [entities=" + entities + ", notice=" + notice + "]";
    }

    }
}

Output

Example [_return=Return [entities=[Entity [id=2385, details=[Detail [name=Other Known Name, value=John Wick, match=false]], proofs=[], link=http://domain.gg/users?id=2385], Entity [id=2384, details=[Detail [name=Discord ID, value=159985870458322944, match=false], Detail [name=SteamID64, value=76561197991558078, match=true], Detail [name=SteamVanity, value=test, match=false], Detail [name=PS4, value=John_S, match=false], Detail [name=XBox, value=John S, match=false], Detail [name=Email, value=john_smith@gmail.com, match=true], Detail [name=Comment, value=Test user, match=false], Detail [name=Other Known Name, value=Jonathan, match=false], Detail [name=Reddit, value=/u/johns, match=true]], proofs=[], link=http://domain.gg/users?id=2384], Entity [id=1680, details=[Detail [name=Other Known Name, value=Johny, match=false], Detail [name=SteamID64, value=76561198213003675, match=true]], proofs=[], link=http://domain.gg/users?id=1680], Entity [id=1689, details=[Detail [name=Other Known Name, value=JohnnyPeto, match=false], Detail [name=SteamID64, value=76561198094228192, match=true]], proofs=[], link=http://domain.gg/users?id=1689]], notice=Showing 4 out of 4 matches.]]


问:
js find Elements with same innerHTML
I have a button that has some text and I get that text by innerHTML

```<code>var helpName = helpButton.parentElement.querySelector('span').innerHTML;
</code>```

Then I have a few other buttons that trigger accordion boxes

```<code>var helpAccordions = modal.getElementsByClassName('accordion');
</code>```

I would like to select one element from helpAccordions that matches helpName and set it as a var.

```<code>    <div class="modal-content">
        <span class="close">×</span>
        <h3 class="modal-title">Help</h3>

        <button class="accordion">Key Partners</button>
    </div>

    <div class="section-header">
        <span>Key Partners</span>
        <div class="help-icon"></div>
    </div>
</code>```

答:
If you can't use jQuery, I made a fiddle showing it working, below is the relevant code.</p>

```<code>var helpName = helpButton.parentElement.querySelector('span').innerHTML;
var helpAccordions = modal.getElementsByClassName('accordion');
var length = helpAccordions.length;

var myButton;
for(var i = 0; i < length; i++) {
    var button = helpAccordions[i];
    if(button.innerHTML === helpName) {
        myButton = button;
        break;
    }
}
console.log(myButton) // the button with Key Partners as the text
</code>```

Title: js find Elements with same innerHTML

Body:
I have a button that has some text and I get that text by innerHTML

var helpName = helpButton.parentElement.querySelector('span').innerHTML;

Then I have a few other buttons that trigger accordion boxes

var helpAccordions = modal.getElementsByClassName('accordion');

I would like to select one element from helpAccordions that matches helpName and set it as a var.

        ×

Help

        <button class="accordion">Key Partners</button>

        Key Partners

Body:
If you can't use jQuery, I made a fiddle showing it working, below is the relevant code.

var helpName = helpButton.parentElement.querySelector('span').innerHTML;
var helpAccordions = modal.getElementsByClassName('accordion');
var length = helpAccordions.length;

var myButton;
for(var i = 0; i < length; i++) {
    var button = helpAccordions[i];
    if(button.innerHTML === helpName) {
        myButton = button;
        break;
    }
}
console.log(myButton) // the button with Key Partners as the text


问:
Can we use Perl 'inotify2.pm' perl module for monitoring file on the shared directories having different machines?
my intention is to monitor for newly created files in a directory and the same directory is shared among many computers and below is the script for your reference and once i run the script which identifies the files which are created from the machine xyz (on which i am running notifier script)and it does not recognizes the files from machine abc! Is there anything i need to consider for monitoring newly created files under the given directory ?. irrespective of the machine from which the files are created.

Is there any way to track the file created on different machines using 'inotify2.pm' ?

```<code>use Linux::Inotify2;
my $inotify;
$inotify = new Linux::Inotify2 ;
my $dir="/home/vikas/";
opendir(DIR, $dir);

while(readdir DIR)
{
   print "$dir/$_\n";
  -d $_ and $inotify->watch($_,IN_CREATE, \&watch_new);
}
close DIR;
sub watch_new
{
  my $e = shift;
  my $name = $e->fullname;
  print "File was created! $name\n";
}
while(1)
{
  $inotify->poll;
}
</code>```

答:
No, you can't. NFS doesn't work this way.

inotify is a kernel hook, that lets the kernel notify 'watchers' when 'something else' changes the file.

However the kernel isn't made aware of every change on a remote filesystem, because that'd get a bit insane, fast. So it can only 'notify' for changes that go through the kernel, and practically speaking that means only stuff that happens locally. (Which can, in some cases, be remote filesystems, but the notification doesn't propagate)

If you need to do this, then the answer is really - don't use a filesystem as a semaphore mechanism. It's optimised for 'at rest' data, not real time synchronisation between distributed processes. Use a message passing system instead. I've used Redis with Publish/Subscribe for this sort of IPC, and it works very nicely, for example.

Body:
my intention is to monitor for newly created files in a directory and the same directory is shared among many computers and below is the script for your reference and once i run the script which identifies the files which are created from the machine xyz (on which i am running notifier script)and it does not recognizes the files from machine abc! Is there anything i need to consider for monitoring newly created files under the given directory ?. irrespective of the machine from which the files are created.

Is there any way to track the file created on different machines using 'inotify2.pm' ?

use Linux::Inotify2;
my $inotify;
$inotify = new Linux::Inotify2 ;
my $dir="/home/vikas/";
opendir(DIR, $dir);

while(readdir DIR)
{
   print "$dir/$_\n";
  -d $_ and $inotify->watch($_,IN_CREATE, \&watch_new);
}
close DIR;
sub watch_new
{
  my $e = shift;
  my $name = $e->fullname;
  print "File was created! $name\n";
}
while(1)
{
  $inotify->poll;
}


问:
How to compare if any of the elements in a row is same
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

```<code>DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA
</code>```

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

```<code> > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)
</code>```

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

答:
Here is a base R solution using intersect:

```<code>res <- c(0, sapply(2:nrow(DT), function(i)
  length(intersect( na.omit(as.character(DT[i,])), na.omit(as.character(DT[i-1,])) ) )>0))

cbind(DT, D=res)
   # A  B  C D
# 1: a  a  a 0
# 2: a  b  b 1
# 3: b  c  c 1
# 4: d  c  b 1
# 5: e  f  g 0
# 6: f  g  h 1
# 7: h NA NA 1
# 8: i  j NA 0
# 9: j NA NA 1
</code>```

Body:
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

 > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

Body:
Here is a base R solution using intersect:

res <- c(0, sapply(2:nrow(DT), function(i)
  length(intersect( na.omit(as.character(DT[i,])), na.omit(as.character(DT[i-1,])) ) )>0))

cbind(DT, D=res)
   # A  B  C D
# 1: a  a  a 0
# 2: a  b  b 1
# 3: b  c  c 1
# 4: d  c  b 1
# 5: e  f  g 0
# 6: f  g  h 1
# 7: h NA NA 1
# 8: i  j NA 0
# 9: j NA NA 1


问:
Android - how to make a scrollable constraintlayout?
I want to make a layout that lets me scroll down using constraint layout, but I don't know how to go about it. Should the ScrollView be the parent of the ConstraintLayout like this?

```<code><?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

<android.support.constraint.ConstraintLayout
    android:id="@+id/Constraint"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</code>```

Or the other way around? Maybe someone can point me to a good tutorial on this or give an example, I can't seem to find one.

Also, I don't know if this is a bug or some configuration that I don't have set up but I've seen images like this one :

where there are some components outside the blueprint "blue rectangle" yet they are visible, while on my side if I place a component on the "white space" I can't see it or move it anywhere, and it appears on the component tree.

UPDATE :

I found a way to make the constraint layout scrollable in the design tool, using a horizontal guideline to push down the constraint layout border and extend it beyond the device, after that, you can use the guideline as the new bottom of the constraint layout to anchor the components.

答:
TO make a scrollable layout, the layout is correct. It will not be scrollable until there is reason to scroll(just like in any other layout). So add enough content and it will be scrollable, just like with any layout(Linear, Relative, etc). However, you cannot scroll properly in Blueprint or design-mode when designing with ConstraintLayout and ScrollView.

Meaning:

You can make a scrollable ConstraintLayout, but it will not scroll properly in the editor due to a bug/scenario that wasn't considered. But even though scrolling doesn't work in the editor, it works on devices. (I have made several scrolling COnstraintLayouts, so I have tested it)

Note

Regarding your code. The ScrollView is missing a closing tag, I don't know if it is the case in the file or if it is a copy-paste miss, but you may want to look at it.

ContentLicense: CC BY-SA 4.0

Body:
I want to make a layout that lets me scroll down using constraint layout, but I don't know how to go about it. Should the ScrollView be the parent of the ConstraintLayout like this?

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

<android.support.constraint.ConstraintLayout
    android:id="@+id/Constraint"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Or the other way around? Maybe someone can point me to a good tutorial on this or give an example, I can't seem to find one.

Also, I don't know if this is a bug or some configuration that I don't have set up but I've seen images like this one :

where there are some components outside the blueprint "blue rectangle" yet they are visible, while on my side if I place a component on the "white space" I can't see it or move it anywhere, and it appears on the component tree.

UPDATE :

I found a way to make the constraint layout scrollable in the design tool, using a horizontal guideline to push down the constraint layout border and extend it beyond the device, after that, you can use the guideline as the new bottom of the constraint layout to anchor the components.


问:
why is ng-model not checking default radio button?
Below is the fiddle i am working:

http://jsfiddle.net/3c0dxf4d/

The ng-model has an object and the ng-value maps to object, why is my default value {"id":1,"name":"Bill"}
 not getting selected by default.

答:
Change

```<code><input type="radio" ng-model="$parent.currentCustomer" name="foo" ng-value="theCustomer" id="{{theCustomer.id}}">
</code>```

To

```<code><input type="radio" ng-model="$parent.currentCustomer.id" name="foo" ng-value="theCustomer.id" id="{{theCustomer.id}}">{{theCustomer.name}}</td>
</code>```

From ng-value docs

It is mainly used on input[radio] and option elements, so that when
  the element is selected, the ngModel of that element (or its select
  parent element) is set to the bound value.

Body:
Change

<input type="radio" ng-model="$parent.currentCustomer" name="foo" ng-value="theCustomer" id="{{theCustomer.id}}">

To

<input type="radio" ng-model="$parent.currentCustomer.id" name="foo" ng-value="theCustomer.id" id="{{theCustomer.id}}">{{theCustomer.name}}</td>

From ng-value docs

It is mainly used on input[radio] and option elements, so that when
  the element is selected, the ngModel of that element (or its select
  parent element) is set to the bound value.


问:
How to create like %keyword% query in MongoDB using Nodejs
I am working on a MEAN application and want to implement a search filter. I am passing the search keyword in below route as follows

```<code>router.route("/places/search/:keyword")
    .get(function (req, res) {

        query = {};
        if (req.params.keyword !== undefined) {
            query = {
                name: { '$regex': new RegExp("^" + req.params.keyword.toLowerCase(), "i") }
            };
        }
        var response = {};
        Place.find(query, function (err, data) {
            if (err) {
                response = { "error": true, "message": "Error fetching data" };
            } else {
                response = { "error": false, "message": data };
            }
            res.json(response);
        });
    });
</code>```

Above code is doing search like keyword% that returns all places having name starting with the passed keyword but I want to fetch all places where name contains keyword either in start, middle or at the end, something like %keyword% in MySQL.

答:
```<code>router.route("/places/search/:keyword")
    .get(function (req, res) {

        query = {};
        if (req.params.keyword !== undefined) {
            query = {
                name: new RegExp(req.params.keyword, 'i')
            };
        }
        var response = {};
        Place.find(query, function (err, data) {
            if (err) {
                response = { "error": true, "message": "Error fetching data" };
            } else {
                response = { "error": false, "message": data };
            }
            res.json(response);
        });
    });
</code>```

Body:
I am working on a MEAN application and want to implement a search filter. I am passing the search keyword in below route as follows

router.route("/places/search/:keyword")
    .get(function (req, res) {

        query = {};
        if (req.params.keyword !== undefined) {
            query = {
                name: { '$regex': new RegExp("^" + req.params.keyword.toLowerCase(), "i") }
            };
        }
        var response = {};
        Place.find(query, function (err, data) {
            if (err) {
                response = { "error": true, "message": "Error fetching data" };
            } else {
                response = { "error": false, "message": data };
            }
            res.json(response);
        });
    });

Above code is doing search like keyword% that returns all places having name starting with the passed keyword but I want to fetch all places where name contains keyword either in start, middle or at the end, something like %keyword% in MySQL.


问:
How to use do-while loop continuously with a new values for the variables involved (re-input by user)?
This code solves for the root of a cubic function. Setting aside any mathematical concepts, SPECIFICALLY I want to do my DO-WHILE LOOP THREE TIMES (for it's cubic). Consequently, the user will input a guess of the root, v THREE TIMES.

Now the problem is after the FIRST DO-WHILE LOOP, the values of the variables v, seemed to be NOT OVERWRITTEN by the re-input of the user for the SECOND and THIRD DO-WHILE LOOP.

Please help guys!

```<code>#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

const double R = 0.082054;

double f(double a,double b,double P,double T,double v);
double f(double a,double b,double P,double T,double v)
{
    double q =P*pow(v,3)-(P*b+R*T)*pow(v,2)+a*v-a*b;
    return q;
}
double fPrime(double a,double b,double P,double T,double v);
double fPrime(double a,double b,double P,double T,double v)
{
    double s =3*P*pow(v,2)-2*(P*b+R*T)*pow(v,1)+a;
    return s;
}

int main()
{
    double a,b,P,T,Tc;
    cin >> a;
    cin >> b;
    cin >> P;
    cin >> T;

    double v,v1=0,fv,fv1,N,e;                                   //FIRST DO-WHILE
    int iteration = 0;
    cout << "\nUse initial guess for molal volume, v: ";
    cin >> v;
    cout << "\nUse maximum number of iterations, N: ";
    cin >> N;
    cout << "\nUse tolerance, e: ";
    cin >> e;
    do
    {
        v = v1;
        fv = f(a,b,P,T,v);
        fv1 = fPrime(a,b,P,T,v);
        if (fv1==0)
        {
           cout << "Math Error";
           break;
        }
        v1 = v-(fv/fv1);
        cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
        iteration++;
    }
    while(iteration<N && abs(v1-v)>e);
    cout << "The approximate root/solution is " << v1 << endl;

    iteration = 0;                                              //SECOND DO-WHILE
    cout << "\nUse initial guess for molal volume, v: ";
    cin >> v;
    cout << "\nUse maximum number of iterations, N: ";
    cin >> N;
    cout << "\nUse tolerance, e: ";
    cin >> e;
    do
    {
        v = v1;
        fv = f(a,b,P,T,v);
        fv1 = fPrime(a,b,P,T,v);
        if (fv1==0)
        {
           cout << "Math Error";
           break;
        }
        v1 = v-(fv/fv1);
        cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
        iteration++;
    }
    while(iteration<N && abs(v1-v)>e);
    cout << "The approximate root/solution is " << v1 << endl;

    iteration = 0;                                              //THIRD DO-WHILE
    cout << "\nUse initial guess for molal volume, v: ";
    cin >> v;
    cout << "\nUse maximum number of iterations, N: ";
    cin >> N;
    cout << "\nUse tolerance, e: ";
    cin >> e;
    do
    {
        v = v1;
        fv = f(a,b,P,T,v);
        fv1 = fPrime(a,b,P,T,v);
        if (fv1==0)
        {
           cout << "Math Error";
           break;
        }
        v1 = v-(fv/fv1);
        cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
        iteration++;
    }
    while(iteration<N && abs(v1-v)>e);
    cout << "The approximate root/solution is " << v1 << endl;

return 0;
}
</code>```

答:
It seems to me that your line 'cin>>v;' is pointless in your code, because every time you are reading v, you immediately afterwards assign the value of v1 to v with 'v=v1' . So your initial guess is lost.
Moreover, since the exit condition for your second do-while is the same as the exit condition for your first do-while, the second do-while should only execute once and the value of v after that execution should equal v1 = v-fv/fv1, so you will never get a new second value for v distinct from the first value.</p>

Body:
This code solves for the root of a cubic function. Setting aside any mathematical concepts, SPECIFICALLY I want to do my DO-WHILE LOOP THREE TIMES (for it's cubic). Consequently, the user will input a guess of the root, v THREE TIMES.

Now the problem is after the FIRST DO-WHILE LOOP, the values of the variables v, seemed to be NOT OVERWRITTEN by the re-input of the user for the SECOND and THIRD DO-WHILE LOOP.

Please help guys!

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

const double R = 0.082054;

double f(double a,double b,double P,double T,double v);
double f(double a,double b,double P,double T,double v)
{
    double q =P*pow(v,3)-(P*b+R*T)*pow(v,2)+a*v-a*b;
    return q;
}
double fPrime(double a,double b,double P,double T,double v);
double fPrime(double a,double b,double P,double T,double v)
{
    double s =3*P*pow(v,2)-2*(P*b+R*T)*pow(v,1)+a;
    return s;
}

int main()
{
    double a,b,P,T,Tc;
    cin >> a;
    cin >> b;
    cin >> P;
    cin >> T;

    double v,v1=0,fv,fv1,N,e;                                   //FIRST DO-WHILE
    int iteration = 0;
    cout << "\nUse initial guess for molal volume, v: ";
    cin >> v;
    cout << "\nUse maximum number of iterations, N: ";
    cin >> N;
    cout << "\nUse tolerance, e: ";
    cin >> e;
    do
    {
        v = v1;
        fv = f(a,b,P,T,v);
        fv1 = fPrime(a,b,P,T,v);
        if (fv1==0)
        {
           cout << "Math Error";
           break;
        }
        v1 = v-(fv/fv1);
        cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
        iteration++;
    }
    while(iteration<N && abs(v1-v)>e);
    cout << "The approximate root/solution is " << v1 << endl;

    iteration = 0;                                              //SECOND DO-WHILE
    cout << "\nUse initial guess for molal volume, v: ";
    cin >> v;
    cout << "\nUse maximum number of iterations, N: ";
    cin >> N;
    cout << "\nUse tolerance, e: ";
    cin >> e;
    do
    {
        v = v1;
        fv = f(a,b,P,T,v);
        fv1 = fPrime(a,b,P,T,v);
        if (fv1==0)
        {
           cout << "Math Error";
           break;
        }
        v1 = v-(fv/fv1);
        cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
        iteration++;
    }
    while(iteration<N && abs(v1-v)>e);
    cout << "The approximate root/solution is " << v1 << endl;

    iteration = 0;                                              //THIRD DO-WHILE
    cout << "\nUse initial guess for molal volume, v: ";
    cin >> v;
    cout << "\nUse maximum number of iterations, N: ";
    cin >> N;
    cout << "\nUse tolerance, e: ";
    cin >> e;
    do
    {
        v = v1;
        fv = f(a,b,P,T,v);
        fv1 = fPrime(a,b,P,T,v);
        if (fv1==0)
        {
           cout << "Math Error";
           break;
        }
        v1 = v-(fv/fv1);
        cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
        iteration++;
    }
    while(iteration<N && abs(v1-v)>e);
    cout << "The approximate root/solution is " << v1 << endl;

return 0;
}


问:
Async functionality is not completing, however I get no error message
Background

Currently creating a web api which will need to talk to another web api which I have created.  This problematic web api is out the box and the only changed I have mad is to enable cores and added two classes to it.

Problem

Currently this web api is executing all the way to my integration point however when it hits  HttpResponseMessage hrm = await hc.GetAsync(requestUrl); it stops and does not give me an error.  I tried putting a try catch on that function however it ignores that try catch aswell.  The following code will show how I am building this web api.

Code

Controller

```<code>    [Route("api/WorkingPaperServices/CreateWorkingPaper")]
    public IHttpActionResult CreateWorkingPaper()
    {
        try
        {
            log4net.Config.XmlConfigurator.Configure();
            bool complete = WorkingPaperCreator.StartWPCreation().Result;
            return Ok("Finished");
        }
        catch(Exception ex)
        {
            log4net.LogManager.GetLogger("EmailLogger").Error(JsonConvert.SerializeObject(ex));
            return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Not Laoded"));
        }
    }
</code>```

WorkingPaperCreator - class

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace CWAppServices.Services
{
    public class WorkingPaperCreator
    {
        public static async Task<bool> StartWPCreation()
        {
            try
            {
                var testing = await IntergrationPoints.GetClientInformation();
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
    }
}
</code>```

IntergrationPoints -  class (Where my problem is)

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;

namespace CWAppServices.Services
{
    public class IntergrationPoints
    {
        public static async Task<bool> GetClientInformation()
        {
            List<string> uniqueID = new List<string>();
            try
            {
                string requestUrl = "http://appdev.tenant.com/caseware32/api/DataServices/GetAllClients";

                var action = new HttpMethod("GET");

                HttpClient hc = new HttpClient();

                HttpResponseMessage hrm = await hc.GetAsync(requestUrl);

                if (hrm.IsSuccessStatusCode)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                // TODO Log
                return false;
            }
        }
    }
}
</code>```

答:
This blocking call leads to the problems:
bool complete = WorkingPaperCreator.StartWPCreation().Result;.
You get dead lock. To avoid it use aync\await everywhere (make your controller async as well) or add .ConfigureAwait(false) to all await calls.

Body:
Background

Currently creating a web api which will need to talk to another web api which I have created.  This problematic web api is out the box and the only changed I have mad is to enable cores and added two classes to it.

Problem

Currently this web api is executing all the way to my integration point however when it hits  HttpResponseMessage hrm = await hc.GetAsync(requestUrl); it stops and does not give me an error.  I tried putting a try catch on that function however it ignores that try catch aswell.  The following code will show how I am building this web api.

Code

Controller

    [Route("api/WorkingPaperServices/CreateWorkingPaper")]
    public IHttpActionResult CreateWorkingPaper()
    {
        try
        {
            log4net.Config.XmlConfigurator.Configure();
            bool complete = WorkingPaperCreator.StartWPCreation().Result;
            return Ok("Finished");
        }
        catch(Exception ex)
        {
            log4net.LogManager.GetLogger("EmailLogger").Error(JsonConvert.SerializeObject(ex));
            return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Not Laoded"));
        }
    }

WorkingPaperCreator - class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace CWAppServices.Services
{
    public class WorkingPaperCreator
    {
        public static async Task<bool> StartWPCreation()
        {
            try
            {
                var testing = await IntergrationPoints.GetClientInformation();
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
    }
}

IntergrationPoints -  class (Where my problem is)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;

namespace CWAppServices.Services
{
    public class IntergrationPoints
    {
        public static async Task<bool> GetClientInformation()
        {
            List<string> uniqueID = new List<string>();
            try
            {
                string requestUrl = "http://appdev.tenant.com/caseware32/api/DataServices/GetAllClients";

                var action = new HttpMethod("GET");

                HttpClient hc = new HttpClient();

                HttpResponseMessage hrm = await hc.GetAsync(requestUrl);

                if (hrm.IsSuccessStatusCode)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                // TODO Log
                return false;
            }
        }
    }
}


答: Since  element is inline by default and div is block, you need to define  element as block either. (block element in inline element is not valid)</p>

Title: <a> link is not working on the div

Body:
STEAK HOUSE
RESTAURANT

Jeddah

      Name:

Steak House Restaurant

 Location:

Jeddah

The  element is the parent of the class "txt" and when I try to make  the parent of the entire "gallery-cell" class it doesn't work!
I want the entire cell to be clickable, not just the text.

If you want, take a look at this website to test it out: http://urbanphenomena.net/