问:
Invoking a method of an anonymous class without reflection in java
I want to do something like this

```<code>static <T> T mine()
{
    return  new Object(){void hello(){}};
}
</code>```

so that I can do this

```<code>mine().hello();
</code>```

the intend is to do something like this

```<code>mine.hello().hi().bye();
</code>```

so either I declare classes each with 1 method hello,hi,bye and than return there instances or somehow I could return an anonymous class(with newly defined method) form each method like above. so that I dont have to write lot of classes.

Like it I can do

```<code>static <T> T tunnel(T t)
    {
        return t;
    }

tunnel(new Object()
        {
            void hello()
            {
                System.out.println("hello");

            }
        }).hello();
</code>```

but its of no use, I want to return anonymous object(created in tunnel itself) from tunnel , instead of returning passed argument

答:
You probably want a fluent class. Something like

```<code>public class MyFluentClass {

   public MyFluentClass methodOne() {
     // do something
     return this;
   }

   public MyFluentClass methodTwo() {
     // do something
     return this;
   }
}
</code>```

And then in your main method:

```<code>MyFluentClass myFuent = new MyFluentClass();
myFluent.methodOne().methodTwo();
</code>```

Body:
I want to do something like this

static <T> T mine()
{
    return  new Object(){void hello(){}};
}

so that I can do this

mine().hello();

the intend is to do something like this

mine.hello().hi().bye();

so either I declare classes each with 1 method hello,hi,bye and than return there instances or somehow I could return an anonymous class(with newly defined method) form each method like above. so that I dont have to write lot of classes.

Like it I can do

static <T> T tunnel(T t)
    {
        return t;
    }

tunnel(new Object()
        {
            void hello()
            {
                System.out.println("hello");

            }
        }).hello();

but its of no use, I want to return anonymous object(created in tunnel itself) from tunnel , instead of returning passed argument

Body:
You probably want a fluent class. Something like

public class MyFluentClass {

   public MyFluentClass methodOne() {
     // do something
     return this;
   }

   public MyFluentClass methodTwo() {
     // do something
     return this;
   }
}

And then in your main method:

MyFluentClass myFuent = new MyFluentClass();
myFluent.methodOne().methodTwo();


来源: stackexchange

问:
Valgrind - Open Windows memory dump
I have a memory leak on a service installed on a Windows productive server where I can't stop service or install programs. I used the task manager to extract a dump of the memory to a file.

This memory dump make more that 1GB, but when I use tools like DotMemory, they see only 2MB of memory. I think that the leak is in unmanaged memory and want to open the dump with Valgrind to find the leak, but I could not find how to open a dump using Valgrind.

Please notice that it's almost the first time that I use Valgrind, I'm really not familiar with this program. I don't know if it is possible or if it even make sense.

Thanks in advance.

答:
Valgrind is not available on Windows, except for some old ports that I don't believe are maintained. Additionally, I'm not aware of it having any memory dump analysis features.

I'm not too familiar with Windows tools. The nearest equivalent to Valgrind is IBM Rational PurifyPlus, but I believe that there are others like BoundsChecker and Insure++. These are likely to require an instrumentation step, which wouldn't be compatible with your live server requirement.

ContentLicense: CC BY-SA 3.0

Title: Valgrind - Open Windows memory dump


问:
Sort by date with comparison, returns wrong order in React
I get the data from firebase

```<code>componentWillMount() {
  let athleteRef = fire.database()
    .ref("athlete")
    .orderByChild("email")
    .equalTo(this.state.email)

  athleteRef
    .once("value")
    .then((snapshot) => {
      snapshot.forEach((data) => {

        let workload: number = data.val().minutes * data.val().intensity;
        let datas = data.val();

        let workouts = {
          key: data.key,
          date: datas.dateCreated,
          athleteData: data.val(),
          workload: workload,
        };
        this.setState({ workouts: [workouts].concat(this.state.workouts) });
    })
  });
}
</code>```

I made this sort function

```<code>sortByDate(arr) {
  if(this.state.sortedByDate === true) {
    let sorted = arr.sort((a,b) => {
      new Date(a.date).getTime() - new Date(b.date).getTime());
    }
    this.setState({
      workouts: sorted,
      sortedByDate: false,
    });
  } else {
    let sorted = arr.sort((a,b) => {
      new Date(b.date).getTime() - new Date(a.date).getTime());
    }
    this.setState({
      workouts: sorted,
      sortedByDate: true,
    });
  }
}
</code>```

The array looks like this after being sorted desc (notice year 2016):

```<code>Array (11)
{key: "-KyocQLyhpwVHCpKJOBv", date: "13/11/2017", athleteData: Object, workload: 1}
{key: "-KyR0ovLXga6zlHX4J40", date: "08/11/2017", athleteData: Object, workload: 30}
{key: "-KyPny-m5OjAdK0C133e", date: "08/11/2017", athleteData: Object, workload: 80}
{key: "-KvRKjbTmbvajvcijYl2", date: "02/10/2017", athleteData: Object, workload: 72}
{key: "-KvOv-2gZ1U46btx62Lg", date: "01/09/2017", athleteData: Object, workload: 120}
{key: "-KyR0rqVt34A-_TYdpH9", date: "01/01/2017", athleteData: Object, workload: 60006}
{key: "-KyR0qf78bi7S1xE7QyE", date: "01/01/2017", athleteData: Object, workload: 100000}
{key: "-KvXHVN6MsfQS-j6aAx9", date: "01/01/2017", athleteData: Object, workload: 100000}
{key: "-KyR0kW7WWE9N5SIM9hz", date: "01/01/2016", athleteData: Object, workload: 5000000000}
{key: "-KvMBqOTfcQpf1nJsY-V", date: "21/09/2017", athleteData: Object, workload: 80}
{key: "-KvMBbaNmbeg9h66YNoj", date: "01/10/2017", athleteData: Object, workload: 100}
</code>```

After i run the asc part of the function I get:

```<code>{key: "-KyocQLyhpwVHCpKJOBv", date: "13/11/2017", athleteData: Object, workload: 1}
{key: "-KyR0kW7WWE9N5SIM9hz", date: "01/01/2016", athleteData: Object, workload: 5000000000}
{key: "-KyR0rqVt34A-_TYdpH9", date: "01/01/2017", athleteData: Object, workload: 60006}
{key: "-KyR0qf78bi7S1xE7QyE", date: "01/01/2017", athleteData: Object, workload: 100000}
{key: "-KvXHVN6MsfQS-j6aAx9", date: "01/01/2017", athleteData: Object, workload: 100000}
{key: "-KvOv-2gZ1U46btx62Lg", date: "01/09/2017", athleteData: Object, workload: 120}
{key: "-KvRKjbTmbvajvcijYl2", date: "02/10/2017", athleteData: Object, workload: 72}
{key: "-KyR0ovLXga6zlHX4J40", date: "08/11/2017", athleteData: Object, workload: 30}
{key: "-KyPny-m5OjAdK0C133e", date: "08/11/2017", athleteData: Object, workload: 80}
{key: "-KvMBqOTfcQpf1nJsY-V", date: "21/09/2017", athleteData: Object, workload: 80}
{key: "-KvMBbaNmbeg9h66YNoj", date: "01/10/2017", athleteData: Object, workload: 100}
</code>```

So... yeah it's almost right, but a few records all out of place :)

I also tried making the dates with

```<code>moment().format("YYYY-MM-DD")
</code>```

but that gives the same output... Any suggestions as to why?
Thanks!

答:
Passing string into Date constructor is discouraged see date MDN page for more. The correct way to sort it would be to use Moment and pass it format and convert it into timestamp used for sorting.

For readability, I moved it to a separate function and generalized data (make sure you access date poperty in your case):

```<code>const data = [//this is your data]
const dateFormat = 'DD/MM/YYYY'
const sorted = data.sort(
 (a, b) =>
 moment(a, dateFormat).unix() - moment(b, dateFormat).unix()
)
</code>```

Another thing is that setting setState in React is async because it may be batched or deferred until later. The correct way to set state based on the previous one would be to use callback passed to setState. Simplified code for your example would be:

```<code>this.setState(state => {
  return {
    sortedByDate: !state.sortedByDate,
    sorted: // do sorting here :)
  }
})
</code>```

Body:
I get the data from firebase

componentWillMount() {
  let athleteRef = fire.database()
    .ref("athlete")
    .orderByChild("email")
    .equalTo(this.state.email)

  athleteRef
    .once("value")
    .then((snapshot) => {
      snapshot.forEach((data) => {

        let workload: number = data.val().minutes * data.val().intensity;
        let datas = data.val();

        let workouts = {
          key: data.key,
          date: datas.dateCreated,
          athleteData: data.val(),
          workload: workload,
        };
        this.setState({ workouts: [workouts].concat(this.state.workouts) });
    })
  });
}

I made this sort function

sortByDate(arr) {
  if(this.state.sortedByDate === true) {
    let sorted = arr.sort((a,b) => {
      new Date(a.date).getTime() - new Date(b.date).getTime());
    }
    this.setState({
      workouts: sorted,
      sortedByDate: false,
    });
  } else {
    let sorted = arr.sort((a,b) => {
      new Date(b.date).getTime() - new Date(a.date).getTime());
    }
    this.setState({
      workouts: sorted,
      sortedByDate: true,
    });
  }
}

The array looks like this after being sorted desc (notice year 2016):

Array (11)
{key: "-KyocQLyhpwVHCpKJOBv", date: "13/11/2017", athleteData: Object, workload: 1}
{key: "-KyR0ovLXga6zlHX4J40", date: "08/11/2017", athleteData: Object, workload: 30}
{key: "-KyPny-m5OjAdK0C133e", date: "08/11/2017", athleteData: Object, workload: 80}
{key: "-KvRKjbTmbvajvcijYl2", date: "02/10/2017", athleteData: Object, workload: 72}
{key: "-KvOv-2gZ1U46btx62Lg", date: "01/09/2017", athleteData: Object, workload: 120}
{key: "-KyR0rqVt34A-_TYdpH9", date: "01/01/2017", athleteData: Object, workload: 60006}
{key: "-KyR0qf78bi7S1xE7QyE", date: "01/01/2017", athleteData: Object, workload: 100000}
{key: "-KvXHVN6MsfQS-j6aAx9", date: "01/01/2017", athleteData: Object, workload: 100000}
{key: "-KyR0kW7WWE9N5SIM9hz", date: "01/01/2016", athleteData: Object, workload: 5000000000}
{key: "-KvMBqOTfcQpf1nJsY-V", date: "21/09/2017", athleteData: Object, workload: 80}
{key: "-KvMBbaNmbeg9h66YNoj", date: "01/10/2017", athleteData: Object, workload: 100}

After i run the asc part of the function I get:

{key: "-KyocQLyhpwVHCpKJOBv", date: "13/11/2017", athleteData: Object, workload: 1}
{key: "-KyR0kW7WWE9N5SIM9hz", date: "01/01/2016", athleteData: Object, workload: 5000000000}
{key: "-KyR0rqVt34A-_TYdpH9", date: "01/01/2017", athleteData: Object, workload: 60006}
{key: "-KyR0qf78bi7S1xE7QyE", date: "01/01/2017", athleteData: Object, workload: 100000}
{key: "-KvXHVN6MsfQS-j6aAx9", date: "01/01/2017", athleteData: Object, workload: 100000}
{key: "-KvOv-2gZ1U46btx62Lg", date: "01/09/2017", athleteData: Object, workload: 120}
{key: "-KvRKjbTmbvajvcijYl2", date: "02/10/2017", athleteData: Object, workload: 72}
{key: "-KyR0ovLXga6zlHX4J40", date: "08/11/2017", athleteData: Object, workload: 30}
{key: "-KyPny-m5OjAdK0C133e", date: "08/11/2017", athleteData: Object, workload: 80}
{key: "-KvMBqOTfcQpf1nJsY-V", date: "21/09/2017", athleteData: Object, workload: 80}
{key: "-KvMBbaNmbeg9h66YNoj", date: "01/10/2017", athleteData: Object, workload: 100}

So... yeah it's almost right, but a few records all out of place :)

I also tried making the dates with

moment().format("YYYY-MM-DD")

but that gives the same output... Any suggestions as to why?
Thanks!

Body:
Passing string into Date constructor is discouraged see date MDN page for more. The correct way to sort it would be to use Moment and pass it format and convert it into timestamp used for sorting.

For readability, I moved it to a separate function and generalized data (make sure you access date poperty in your case):

const data = [//this is your data]
const dateFormat = 'DD/MM/YYYY'
const sorted = data.sort(
 (a, b) =>
 moment(a, dateFormat).unix() - moment(b, dateFormat).unix()
)

Another thing is that setting setState in React is async because it may be batched or deferred until later. The correct way to set state based on the previous one would be to use callback passed to setState. Simplified code for your example would be:

this.setState(state => {
  return {
    sortedByDate: !state.sortedByDate,
    sorted: // do sorting here :)
  }
})


问:
Smart Table Angularjs external search box
Good morning, i have a smart table on my angualrJS spa but i need to place the search fields outside the table for ui design purposes. Can it be done? Here a sample code of my table

```<code><table st-table="displayedCollection" st-safe-src="rowCollection" class="table table-striped">
  <thead>
    <tr>
      <th>Tipo</th>
      <th>Da</th>
      <th>A</th>
      <th>Data</th>
      <th>Durata</th>
      <th>Costo</th>
    </tr>
    <tr>
      <th></th>
      <th></th>
      <th><input st-search="'destination'" /></th>
      <th><input st-search="'answerTime'" /></th>
      <th><input st-search="'duration'" /></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in displayedCollection">
      <td></td>
      <td></td>
      <td>{{row.destination}}</td>
      <td>{{row.answerTime | date : 'short'}}</td>
      <td>{{row.duration | number}}</td>
      <td>{{row.cost | currency : '€'}}</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="5" class="text-center">
        <div st-pagination="" st-items-by-page="itemsByPage" st-displayed-pages="5"></div>
      </td>
    </tr>
  </tfoot>
</table>
</code>```

i need to place the st-search field (or something similar) outside the  tags.

here the sample, on top default, and on bottom desired

http://imgur.com/C24pk0K

答:
You may try to wrap the table in a wrapper like this:

```<code><div st-table="displayedCollection" st-safe-src="rowCollection">

   <input st-search="'destination'" />
   <input st-search="'answerTime'" />
   <input st-search="'duration'" />

   <table class="table table-striped">
      <thead>
         <tr>
            <th>Tipo</th>
            <th>Da</th>
            <th>A</th>
            <th>Data</th>
            <th>Durata</th>
            <th>Costo</th>
         </tr>
      </thead>
      <tbody>
         <tr ng-repeat="row in displayedCollection">
            <td></td>
            <td></td>
            <td>{{row.destination}}</td>
            <td>{{row.answerTime | date : 'short'}}</td>
            <td>{{row.duration | number}}</td>
            <td>{{row.cost | currency : '€'}}</td>
          </tr>
      </tbody>
    </table>
 </div>
</code>```

For me, this worked perfect.

Body:
Good morning, i have a smart table on my angualrJS spa but i need to place the search fields outside the table for ui design purposes. Can it be done? Here a sample code of my table

      Tipo
      Da
      A
      Data
      Durata
      Costo

      <input st-search="'destination'" />
      <input st-search="'answerTime'" />
      <input st-search="'duration'" />

      {{row.destination}}
      {{row.answerTime | date : 'short'}}
      {{row.duration | number}}
      {{row.cost | currency : '€'}}

i need to place the st-search field (or something similar) outside the  tags.

here the sample, on top default, and on bottom desired

http://imgur.com/C24pk0K

Body:
You may try to wrap the table in a wrapper like this:

<div st-table="displayedCollection" st-safe-src="rowCollection">

   <input st-search="'destination'" />
   <input st-search="'answerTime'" />
   <input st-search="'duration'" />

   <table class="table table-striped">
      <thead>
         <tr>
            <th>Tipo</th>
            <th>Da</th>
            <th>A</th>
            <th>Data</th>
            <th>Durata</th>
            <th>Costo</th>
         </tr>
      </thead>
      <tbody>
         <tr ng-repeat="row in displayedCollection">
            <td></td>
            <td></td>
            <td>{{row.destination}}</td>
            <td>{{row.answerTime | date : 'short'}}</td>
            <td>{{row.duration | number}}</td>
            <td>{{row.cost | currency : '€'}}</td>
          </tr>
      </tbody>
    </table>
 </div>

For me, this worked perfect.


问:
Adding items to a navigation toolbar
I have a navigation toolbar in which I am adding toolbar items programatically, as below.  The toolbar displays properly, and the toolbar style is set to black opaque. but the button on the toolbar does not display.  Why?  </p>

```<code>    //Set up the toolbar
 [[[self navigationController] toolbar] setBarStyle:UIBarStyleBlackOpaque];
 UIBarButtonItem *myButtonItem =
 [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(handleMyButton)];
 NSArray *myItems = [NSArray arrayWithObjects: myButtonItem,nil];
 [[self navigationController] setToolbarItems:myItems animated:NO];
 [myButtonItem release];
</code>```

答: Show the toolbar by setting the toolbarHidden property of the navigation controller object to NO.</p>

ContentLicense: CC BY-SA 2.5

Title: Adding items to a navigation toolbar

Body:
I have a navigation toolbar in which I am adding toolbar items programatically, as below.  The toolbar displays properly, and the toolbar style is set to black opaque. but the button on the toolbar does not display.  Why?

    //Set up the toolbar
 [[[self navigationController] toolbar] setBarStyle:UIBarStyleBlackOpaque];
 UIBarButtonItem *myButtonItem =
 [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(handleMyButton)];
 NSArray *myItems = [NSArray arrayWithObjects: myButtonItem,nil];
 [[self navigationController] setToolbarItems:myItems animated:NO];
 [myButtonItem release];


问:
Can you tell me how to make use of XQuery here?
```<code>let $db := xdmp:databases()[1]
let $db-name := xdmp:database-name($db)
let $db-forests := xdmp:database-forests($db, fn:false())
let $forests-name := xdmp:forest-name($db-forests)
let $forests-name := for $f in xdmp:forest-name($db-forests)
                        order by $f ascending
                      return $f
let $forest-status := xdmp:forest-status($db-forests)
let $map := map:map()
let $_ := for $f in $forests-name
            let $host-id := $forest-status/f:host-id/text() where ($forest-status/f:forest-name[. = $f] and ($forest-status/f:availablility/text() eq "online"))
            let $_ := if(map:contains(xdmp:host-name($host-id))) then() else()
          return $host-id
return $forest-status
</code>```

I am getting error as I'm not using Xquery correctly. Please guide me.

答:
A FLWOR statement is not just the name - it is the order in which things need to be done.  you have let-where-let in your FLWOR statement. Re-arrange it. It is upset about the second let statement because it comes after the where statement..

Second - from a visual inspection, you seem to have no namespace binding for the prefix 'f'.

Third - a visual inspection suggests that your map statement will fail because:

1 the map never seems to have values

2 the map:contains function does not have enough parameters..

Body:
let $db := xdmp:databases()[1]
let $db-name := xdmp:database-name($db)
let $db-forests := xdmp:database-forests($db, fn:false())
let $forests-name := xdmp:forest-name($db-forests)
let $forests-name := for $f in xdmp:forest-name($db-forests)
                        order by $f ascending
                      return $f
let $forest-status := xdmp:forest-status($db-forests)
let $map := map:map()
let $_ := for $f in $forests-name
            let $host-id := $forest-status/f:host-id/text() where ($forest-status/f:forest-name[. = $f] and ($forest-status/f:availablility/text() eq "online"))
            let $_ := if(map:contains(xdmp:host-name($host-id))) then() else()
          return $host-id
return $forest-status

I am getting error as I'm not using Xquery correctly. Please guide me.


问:
jQuery $.each or $.map to append
 to dynamically added tables
I am using an a jQuery AJAX response to dynamically build a bootstrap table within a panel.

I can get it to create the panel and add a table to the panel but I've got a problem looping through the AJAX response to create the table rows and cells.

```<code>$.ajax({
    ...
    ...
    ...
    ...
    success: function(response) {
        $('#groups').append(
            $('<div/>', {'class': 'panel panel-default'}).append(
                $('<div/>', {'class': 'panel-heading'}).append(
                    $('<span/>', {text: 'TEST'})
                )
            ).append(
                $('<div/>', {'class': 'panel-body'}).append(
                    $('<div/>', {class: 'table-responsive'}).append(
                        $('<table/>', {class: 'table table-bordered'}).append(

                        )
                    )
                )
            )
        );
    }
});
</code>```

The expected output is:

```<code><div class="panel panel-default">
    <div class="panel-heading">
         TEST
    </div>
    <div class="panel-body">
        <div class="table-responsive">
            <table class="table">
                <tr>
                    <td></td>
                </tr>
                <tr>
                    <td></td>
                </tr>
            </table>
        </div>
    </div>
</div>
</code>```

but at the moment I get this:

```<code><div class="panel panel-default">
    <div class="panel-heading">
         TEST
    </div>
    <div class="panel-body">
        <div class="table-responsive">
            <table class="table">

            </table>
        </div>
    </div>
</div>
</code>```

How do I loop through the response to create a
 for each row?

答:
try this</p>

```<code>$('#groups').append(
            $('<div/>', {'class': 'panel panel-default'}).append(
                $('<div/>', {'class': 'panel-heading'}).append(
                    $('<span/>', {text: $('#productgroup option:selected').text() + '/' + $('#productline option:selected').text() + '/' + $('#producttype option:selected').text()})
                )
            ).append(
                $('<div/>', {'class': 'panel-body'}).append(
                    $('<div/>', {class: 'table-responsive'}).append(
                        $('<table/>', {class: 'table table-bordered table-striped'}).append(
                            $.map(response, function (k, v) {
                                return $('<tr/>').append(
                                    $('<td>', {text: 'some text'})
                                ).append(
                                    $('<td>', {text: 'some more text'})
                                );
                            })
                        )
                    )
                )
            )
        );
</code>```

Title: jQuery $.each or $.map to append <tr> to dynamically added tables

Body:
I am using an a jQuery AJAX response to dynamically build a bootstrap table within a panel.

I can get it to create the panel and add a table to the panel but I've got a problem looping through the AJAX response to create the table rows and cells.

$.ajax({
    ...
    ...
    ...
    ...
    success: function(response) {
        $('#groups').append(
            $('
', {'class': 'panel panel-default'}).append(
                $('
', {'class': 'panel-heading'}).append(
                    $('', {text: 'TEST'})
                )
            ).append(
                $('
', {'class': 'panel-body'}).append(
                    $('
', {class: 'table-responsive'}).append(
                        $('
', {class: 'table table-bordered'}).append(

                        )
                    )
                )
            )
        );
    }
});

The expected output is:

         TEST

but at the moment I get this:

         TEST

How do I loop through the response to create a
 for each row?

Body:
try this

$('#groups').append(
            $('<div/>', {'class': 'panel panel-default'}).append(
                $('<div/>', {'class': 'panel-heading'}).append(
                    $('<span/>', {text: $('#productgroup option:selected').text() + '/' + $('#productline option:selected').text() + '/' + $('#producttype option:selected').text()})
                )
            ).append(
                $('<div/>', {'class': 'panel-body'}).append(
                    $('<div/>', {class: 'table-responsive'}).append(
                        $('<table/>', {class: 'table table-bordered table-striped'}).append(
                            $.map(response, function (k, v) {
                                return $('<tr/>').append(
                                    $('<td>', {text: 'some text'})
                                ).append(
                                    $('<td>', {text: 'some more text'})
                                );
                            })
                        )
                    )
                )
            )
        );


问:
c# Deep Copy reflection GetMembers
I am trying to deep copy a complex object

```<code>public class Team
{
    public string id { get; set; }
    public Driver driver{ get; set;}
    public Driver codriver{ get; set;}
}

public class Driver
{
    public Team parentTeam{ get; set;}
    public string driverId { get; set; }
}

var modifiedTeams = new List<Team>
{
    new Team {id = "T1", driver = new Driver { driverId = "D2" }, codriver = new Driver { driverId = "C1"} },
    new Team {id = "T2", driver = new Driver { driverId = "D1"} }
};
</code>```

//Note: Parent Team holds reference to the Team the driver or codriver is in

I want to deep copy the modified lists. Below is the utility that I am using.

```<code>    /// <summary>
/// Utility
/// </summary>
public static class DeepCopyUtility
{
    private static string[] _excludedPropertyNames = null;
    private static BindingFlags _memberAccess = (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

    /// <summary>
    /// Copies the data of one object to another. The target object gets properties of the first.
    /// Any matching properties (by name) are written to the target.
    /// </summary>
    /// <param name="source">The source object to copy from</param>
    /// <param name="target">The target object to copy to public</param>
    /// <param name="propertyNames">     </param>
    public static void DeepCopy<T>(T source, T target, string[] propertyNames = null)
    {
        if (source == null)
        {
            throw new ArgumentNullException("Object is null");
        }
        if (propertyNames != null)
        {
            _excludedPropertyNames = propertyNames;
        }
        CopyObjectData(source, target, new Dictionary<object, object>());
    }

    /// <summary>
    /// Copies the data of one object to another. The target object gets properties of the first.
    /// Any matching properties (by name) are written to the target.
    /// </summary>
    /// <param name="source">The source object to copy from</param>
    /// <param name="target">The target object to copy to</param>
    /// <param name="excludedProperties">A comma delimited list of properties that should not be copied</param>
    public static void CopyObjectData(object source, object target, Dictionary<object, object> cloned)
    {
        Type type = source.GetType();
        if (target == null && type.IsValueType == false && type != typeof(string))
        {
            if (source.GetType().IsArray)
            {
                target = Activator.CreateInstance(source.GetType().GetElementType());
            }
            else if (source.GetType().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
            {
                if (typeof(IList).IsAssignableFrom(type))
                {
                    target = (IList)Activator.CreateInstance(type);
                }
                else if (type.IsGenericType)
                {
                    var objectType = type.GetGenericArguments().Single();
                    if (typeof(IList<>).MakeGenericType(objectType).IsAssignableFrom(type) || typeof(ISet<>).MakeGenericType(objectType).IsAssignableFrom(type))
                    {
                        target = Activator.CreateInstance(type);
                    }
                }
            }
            else
            {
                target = Activator.CreateInstance(source.GetType());
            }
        }

        MemberInfo[] miT = target.GetType().GetMembers(_memberAccess);
        foreach (MemberInfo field in miT)
        {
            string name = field.Name;

            // Skip over excluded properties
            if (_excludedPropertyNames != null && _excludedPropertyNames.Contains(name))
            {
                continue;
            }

            object clone;
            if (cloned.TryGetValue(source, out clone))
            {
                // this object has been cloned earlier, return reference to that clone
                continue;
            }

            if (field.MemberType == MemberTypes.Field)
            {
                FieldInfo sourcefield = source.GetType().GetField(name);
                if (sourcefield == null)
                {
                    continue;
                }

                object sourceValue = sourcefield.GetValue(source);
                ((FieldInfo)field).SetValue(target, sourceValue);
                cloned[target] = sourceValue;
            }
            else if (field.MemberType == MemberTypes.Property)
            {
                PropertyInfo piTarget = field as PropertyInfo;
                PropertyInfo sourceField = source.GetType().GetProperty(name, _memberAccess);
                if (sourceField == null)
                {
                    continue;
                }

                if (piTarget.CanWrite && sourceField.CanRead)
                {

                    if (sourceField.PropertyType.IsArray && piTarget.PropertyType.IsArray)
                    {
                        CopyArray(source, target, piTarget, sourceField, cloned);
                    }
                    else if ((sourceField.PropertyType.IsGenericType && sourceField.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
                             && (piTarget.PropertyType.IsGenericType && piTarget.PropertyType.GetGenericTypeDefinition() == typeof(List<>)))
                    {
                        CopyList(source, target, piTarget, sourceField, cloned);
                    }
                    else
                    {
                        CopySingleData(source, target, piTarget, sourceField, cloned);
                    }
                }
            }
        }
    }

    private static void CopySingleData(object source, object target, PropertyInfo piTarget, PropertyInfo sourceField, Dictionary<object, object> cloned)
    {
        object sourceValue = sourceField.GetValue(source, null);
        object targetValue = piTarget.GetValue(target, null);
        if (sourceValue == null) { return; }

        //instantiate target if needed
        if (targetValue == null && piTarget.PropertyType.IsValueType == false && piTarget.PropertyType != typeof(string))
        {
            if (piTarget.PropertyType.IsArray)
            {
                targetValue = Activator.CreateInstance(piTarget.PropertyType.GetElementType());
            }
            else
            {
                targetValue = Activator.CreateInstance(piTarget.PropertyType);
            }
        }

        if (piTarget.PropertyType.IsValueType == false && piTarget.PropertyType != typeof(string))
        {
            CopyObjectData(sourceValue, targetValue, cloned);
            piTarget.SetValue(target, targetValue, null);
        }
        else
        {
            if (piTarget.PropertyType.FullName == sourceField.PropertyType.FullName)
            {
                object tempSourceValue = sourceField.GetValue(source, null);
                piTarget.SetValue(target, tempSourceValue, null);
                cloned[target] = tempSourceValue;
            }
            else
            {
                CopyObjectData(piTarget, target, cloned);
            }
        }
    }

    private static void CopyArray(object source, object target, PropertyInfo piTarget, PropertyInfo sourceField, Dictionary<object, object> cloned)
    {
        object sourceValue = sourceField.GetValue(source, null);
        if (sourceValue == null) { return; }

        int sourceLength = (int)sourceValue.GetType().InvokeMember("Length", BindingFlags.GetProperty, null, sourceValue, null);
        Array targetArray = Array.CreateInstance(piTarget.PropertyType.GetElementType(), sourceLength);
        Array array = (Array)sourceField.GetValue(source, null);

        for (int i = 0; i < array.Length; i++)
        {
            object o = array.GetValue(i);
            object tempTarget = Activator.CreateInstance(piTarget.PropertyType.GetElementType());
            CopyObjectData(o, tempTarget, cloned);
            targetArray.SetValue(tempTarget, i);
        }
        piTarget.SetValue(target, targetArray, null);
        cloned[target] = targetArray;
    }

    private static void CopyList(object source, object target, PropertyInfo piTarget, PropertyInfo sourceField, Dictionary<object, object> cloned)
    {
        var sourceValue = ((IEnumerable)sourceField.GetValue(source, null)).Cast<object>().ToList();
        if (!sourceValue.Any()) { return; }

        int sourceLength = (int)sourceValue.GetType().GetProperty("Count").GetValue(sourceValue);
        var listType = typeof(List<>);
        Type[] genericArgs = sourceField.PropertyType.GetGenericArguments();
        var concreteType = listType.MakeGenericType(genericArgs);
        var newList = (IList)Activator.CreateInstance(concreteType);

        var obj = (IList)sourceField.GetValue(source, null);
        for (int i = 0; i < sourceLength; i++)
        {
            object[] ind = { i };
            object o = obj[i];
            object tempTarget = Activator.CreateInstance(piTarget.PropertyType.GetGenericArguments()[0]);
            CopyObjectData(o, tempTarget, cloned);
            newList.Insert(i, tempTarget);
        }
        piTarget.SetValue(target, newList, null);
        cloned[target] = newList;
    }
</code>```

On execution I am getting "System.Reflection.TargetParameterCountException : Parameter count mismatch.". This is mainly because it is trying to get Team value from a list of teams. Can someone help me with how I could fix this.

Note: This utility code is referred from below links:-
https://ddkonline.blogspot.com/2010/04/net-deep-copy-between-2-different.html?_sm_au_=iVV8TZZ5L71MRvZf

https://stackoverflow.com/a/2266441/4583547

答:
You mentioned that you are open to other forms of cloning, so here's a suggestion.

If you can use Json.NET then you can leverage its serialization to perform a clone operation like so:

```<code>public static class Cloner
{
    public static T Clone<T>(T source)
    {
        if (ReferenceEquals(source, null))
            return default(T);

        var settings = new JsonSerializerSettings { ContractResolver = new ContractResolver() };

        return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source, settings), settings);
    }

    class ContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                .Select(p => base.CreateProperty(p, memberSerialization))
                .Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                    .Select(f => base.CreateProperty(f, memberSerialization)))
                .ToList();
            props.ForEach(p => { p.Writable = true; p.Readable = true; });
            return props;
        }
    }
}
</code>```

Test project (console app):

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Demo
{
    public class Team
    {
        public string id { get; set; }
        public Driver driver { get; set; }
        public Driver codriver { get; set; }
    }

    public class Driver
    {
        public Team parentTeam { get; set; }
        public string driverId { get; set; }
    }

    class Program
    {
        static void Main()
        {
            var original = new List<Team>
            {
                new Team {id = "T1", driver = new Driver { driverId = "D2" }, codriver = new Driver { driverId = "C1"} },
                new Team {id = "T2", driver = new Driver { driverId = "D1"} }
            };

            var cloned = Cloner.Clone(original);

            // Change original to prove that clone is not referencing it.

            original[0].codriver.driverId = "changed";

            Console.WriteLine(cloned[0].codriver.driverId); // Should be C1
        }
    }

    public static class Cloner
    {
        public static T Clone<T>(T source)
        {
            if (ReferenceEquals(source, null))
                return default(T);

            var settings = new JsonSerializerSettings { ContractResolver = new ContractResolver() };

            return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source, settings), settings);
        }

        class ContractResolver : DefaultContractResolver
        {
            protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
            {
                var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                    .Select(p => base.CreateProperty(p, memberSerialization))
                    .Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                        .Select(f => base.CreateProperty(f, memberSerialization)))
                    .ToList();
                props.ForEach(p => { p.Writable = true; p.Readable = true; });
                return props;
            }
        }
    }
}
</code>```

NOTE

See this answer for the original source of the cloning code above.

Title: c# Deep Copy reflection GetMembers

Body:
I am trying to deep copy a complex object

public class Team
{
    public string id { get; set; }
    public Driver driver{ get; set;}
    public Driver codriver{ get; set;}
}

public class Driver
{
    public Team parentTeam{ get; set;}
    public string driverId { get; set; }
}

var modifiedTeams = new List<Team>
{
    new Team {id = "T1", driver = new Driver { driverId = "D2" }, codriver = new Driver { driverId = "C1"} },
    new Team {id = "T2", driver = new Driver { driverId = "D1"} }
};

//Note: Parent Team holds reference to the Team the driver or codriver is in

I want to deep copy the modified lists. Below is the utility that I am using.

    ///
/// Utility
///
public static class DeepCopyUtility
{
    private static string[] _excludedPropertyNames = null;
    private static BindingFlags _memberAccess = (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

    ///
    /// Copies the data of one object to another. The target object gets properties of the first.
    /// Any matching properties (by name) are written to the target.
    ///
    /// <param name="source">The source object to copy from</param>
    /// <param name="target">The target object to copy to public</param>
    /// <param name="propertyNames">     </param>
    public static void DeepCopy<T>(T source, T target, string[] propertyNames = null)
    {
        if (source == null)
        {
            throw new ArgumentNullException("Object is null");
        }
        if (propertyNames != null)
        {
            _excludedPropertyNames = propertyNames;
        }
        CopyObjectData(source, target, new Dictionary<object, object>());
    }

    ///
    /// Copies the data of one object to another. The target object gets properties of the first.
    /// Any matching properties (by name) are written to the target.
    ///
    /// <param name="source">The source object to copy from</param>
    /// <param name="target">The target object to copy to</param>
    /// <param name="excludedProperties">A comma delimited list of properties that should not be copied</param>
    public static void CopyObjectData(object source, object target, Dictionary<object, object> cloned)
    {
        Type type = source.GetType();
        if (target == null && type.IsValueType == false && type != typeof(string))
        {
            if (source.GetType().IsArray)
            {
                target = Activator.CreateInstance(source.GetType().GetElementType());
            }
            else if (source.GetType().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
            {
                if (typeof(IList).IsAssignableFrom(type))
                {
                    target = (IList)Activator.CreateInstance(type);
                }
                else if (type.IsGenericType)
                {
                    var objectType = type.GetGenericArguments().Single();
                    if (typeof(IList<>).MakeGenericType(objectType).IsAssignableFrom(type) || typeof(ISet<>).MakeGenericType(objectType).IsAssignableFrom(type))
                    {
                        target = Activator.CreateInstance(type);
                    }
                }
            }
            else
            {
                target = Activator.CreateInstance(source.GetType());
            }
        }

        MemberInfo[] miT = target.GetType().GetMembers(_memberAccess);
        foreach (MemberInfo field in miT)
        {
            string name = field.Name;

            // Skip over excluded properties
            if (_excludedPropertyNames != null && _excludedPropertyNames.Contains(name))
            {
                continue;
            }

            object clone;
            if (cloned.TryGetValue(source, out clone))
            {
                // this object has been cloned earlier, return reference to that clone
                continue;
            }

            if (field.MemberType == MemberTypes.Field)
            {
                FieldInfo sourcefield = source.GetType().GetField(name);
                if (sourcefield == null)
                {
                    continue;
                }

                object sourceValue = sourcefield.GetValue(source);
                ((FieldInfo)field).SetValue(target, sourceValue);
                cloned[target] = sourceValue;
            }
            else if (field.MemberType == MemberTypes.Property)
            {
                PropertyInfo piTarget = field as PropertyInfo;
                PropertyInfo sourceField = source.GetType().GetProperty(name, _memberAccess);
                if (sourceField == null)
                {
                    continue;
                }

                if (piTarget.CanWrite && sourceField.CanRead)
                {

                    if (sourceField.PropertyType.IsArray && piTarget.PropertyType.IsArray)
                    {
                        CopyArray(source, target, piTarget, sourceField, cloned);
                    }
                    else if ((sourceField.PropertyType.IsGenericType && sourceField.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
                             && (piTarget.PropertyType.IsGenericType && piTarget.PropertyType.GetGenericTypeDefinition() == typeof(List<>)))
                    {
                        CopyList(source, target, piTarget, sourceField, cloned);
                    }
                    else
                    {
                        CopySingleData(source, target, piTarget, sourceField, cloned);
                    }
                }
            }
        }
    }

    private static void CopySingleData(object source, object target, PropertyInfo piTarget, PropertyInfo sourceField, Dictionary<object, object> cloned)
    {
        object sourceValue = sourceField.GetValue(source, null);
        object targetValue = piTarget.GetValue(target, null);
        if (sourceValue == null) { return; }

        //instantiate target if needed
        if (targetValue == null && piTarget.PropertyType.IsValueType == false && piTarget.PropertyType != typeof(string))
        {
            if (piTarget.PropertyType.IsArray)
            {
                targetValue = Activator.CreateInstance(piTarget.PropertyType.GetElementType());
            }
            else
            {
                targetValue = Activator.CreateInstance(piTarget.PropertyType);
            }
        }

        if (piTarget.PropertyType.IsValueType == false && piTarget.PropertyType != typeof(string))
        {
            CopyObjectData(sourceValue, targetValue, cloned);
            piTarget.SetValue(target, targetValue, null);
        }
        else
        {
            if (piTarget.PropertyType.FullName == sourceField.PropertyType.FullName)
            {
                object tempSourceValue = sourceField.GetValue(source, null);
                piTarget.SetValue(target, tempSourceValue, null);
                cloned[target] = tempSourceValue;
            }
            else
            {
                CopyObjectData(piTarget, target, cloned);
            }
        }
    }

    private static void CopyArray(object source, object target, PropertyInfo piTarget, PropertyInfo sourceField, Dictionary<object, object> cloned)
    {
        object sourceValue = sourceField.GetValue(source, null);
        if (sourceValue == null) { return; }

        int sourceLength = (int)sourceValue.GetType().InvokeMember("Length", BindingFlags.GetProperty, null, sourceValue, null);
        Array targetArray = Array.CreateInstance(piTarget.PropertyType.GetElementType(), sourceLength);
        Array array = (Array)sourceField.GetValue(source, null);

        for (int i = 0; i < array.Length; i++)
        {
            object o = array.GetValue(i);
            object tempTarget = Activator.CreateInstance(piTarget.PropertyType.GetElementType());
            CopyObjectData(o, tempTarget, cloned);
            targetArray.SetValue(tempTarget, i);
        }
        piTarget.SetValue(target, targetArray, null);
        cloned[target] = targetArray;
    }

    private static void CopyList(object source, object target, PropertyInfo piTarget, PropertyInfo sourceField, Dictionary<object, object> cloned)
    {
        var sourceValue = ((IEnumerable)sourceField.GetValue(source, null)).Cast<object>().ToList();
        if (!sourceValue.Any()) { return; }

        int sourceLength = (int)sourceValue.GetType().GetProperty("Count").GetValue(sourceValue);
        var listType = typeof(List<>);
        Type[] genericArgs = sourceField.PropertyType.GetGenericArguments();
        var concreteType = listType.MakeGenericType(genericArgs);
        var newList = (IList)Activator.CreateInstance(concreteType);

        var obj = (IList)sourceField.GetValue(source, null);
        for (int i = 0; i < sourceLength; i++)
        {
            object[] ind = { i };
            object o = obj[i];
            object tempTarget = Activator.CreateInstance(piTarget.PropertyType.GetGenericArguments()[0]);
            CopyObjectData(o, tempTarget, cloned);
            newList.Insert(i, tempTarget);
        }
        piTarget.SetValue(target, newList, null);
        cloned[target] = newList;
    }

On execution I am getting "System.Reflection.TargetParameterCountException : Parameter count mismatch.". This is mainly because it is trying to get Team value from a list of teams. Can someone help me with how I could fix this.

Note: This utility code is referred from below links:-
https://ddkonline.blogspot.com/2010/04/net-deep-copy-between-2-different.html?_sm_au_=iVV8TZZ5L71MRvZf

https://stackoverflow.com/a/2266441/4583547

Body:
You mentioned that you are open to other forms of cloning, so here's a suggestion.

If you can use Json.NET then you can leverage its serialization to perform a clone operation like so:

public static class Cloner
{
    public static T Clone<T>(T source)
    {
        if (ReferenceEquals(source, null))
            return default(T);

        var settings = new JsonSerializerSettings { ContractResolver = new ContractResolver() };

        return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source, settings), settings);
    }

    class ContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                .Select(p => base.CreateProperty(p, memberSerialization))
                .Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                    .Select(f => base.CreateProperty(f, memberSerialization)))
                .ToList();
            props.ForEach(p => { p.Writable = true; p.Readable = true; });
            return props;
        }
    }
}

Test project (console app):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Demo
{
    public class Team
    {
        public string id { get; set; }
        public Driver driver { get; set; }
        public Driver codriver { get; set; }
    }

    public class Driver
    {
        public Team parentTeam { get; set; }
        public string driverId { get; set; }
    }

    class Program
    {
        static void Main()
        {
            var original = new List<Team>
            {
                new Team {id = "T1", driver = new Driver { driverId = "D2" }, codriver = new Driver { driverId = "C1"} },
                new Team {id = "T2", driver = new Driver { driverId = "D1"} }
            };

            var cloned = Cloner.Clone(original);

            // Change original to prove that clone is not referencing it.

            original[0].codriver.driverId = "changed";

            Console.WriteLine(cloned[0].codriver.driverId); // Should be C1
        }
    }

    public static class Cloner
    {
        public static T Clone<T>(T source)
        {
            if (ReferenceEquals(source, null))
                return default(T);

            var settings = new JsonSerializerSettings { ContractResolver = new ContractResolver() };

            return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source, settings), settings);
        }

        class ContractResolver : DefaultContractResolver
        {
            protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
            {
                var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                    .Select(p => base.CreateProperty(p, memberSerialization))
                    .Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                        .Select(f => base.CreateProperty(f, memberSerialization)))
                    .ToList();
                props.ForEach(p => { p.Writable = true; p.Readable = true; });
                return props;
            }
        }
    }
}

NOTE

See this answer for the original source of the cloning code above.


问:
app.UseDefaultFiles in Kestrel not doing anything?
I have this in a Startup.cs file for a small project for a webserver hosting static files with Kestrel:

```<code>public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new RequireHttpsAttribute());
        });
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        var configBuilder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json");
        var config = configBuilder.Build();

        var options = new RewriteOptions()
           .AddRedirectToHttps();

        app.UseRewriter(options);

        DefaultFilesOptions defoptions = new DefaultFilesOptions();
        defoptions.DefaultFileNames.Clear();
        defoptions.DefaultFileNames.Add("index.html");
        app.UseDefaultFiles(defoptions);

        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions()
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"static")),
            RequestPath = new PathString("")
        });

        loggerFactory.AddConsole(config.GetSection(key: "Logging"));
    }
}
</code>```

However, it doesn't try to load an index.html or anything. If I access it manually, it does indeed work.

Any ideas?

Thanks

答:
Ideally your index.html should be under the web root path (wwwroot), however, if your file is under ContentRootPath\static (as it appears to be), you will need to change your code to specify the DefaultFilesOptions.FileProvider as follows:

```<code>PhysicalFileProvider fileProvider = new PhysicalFileProvider(
    Path.Combine(Directory.GetCurrentDirectory(), @"static"));
DefaultFilesOptions defoptions = new DefaultFilesOptions();
defoptions.DefaultFileNames.Clear();
defoptions.FileProvider = fileProvider;
defoptions.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(defoptions);

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = fileProvider,
    RequestPath = new PathString("")
});
</code>```

Note: you are probably better off using IHostingEnvironment.ContentRootPath (env.ContentRootPath) rather than Directory.GetCurrentDirectory() on the first line (just in case you want to change the content root in your WebHostBuilder at some point).

Body:
I have this in a Startup.cs file for a small project for a webserver hosting static files with Kestrel:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new RequireHttpsAttribute());
        });
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        var configBuilder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json");
        var config = configBuilder.Build();

        var options = new RewriteOptions()
           .AddRedirectToHttps();

        app.UseRewriter(options);

        DefaultFilesOptions defoptions = new DefaultFilesOptions();
        defoptions.DefaultFileNames.Clear();
        defoptions.DefaultFileNames.Add("index.html");
        app.UseDefaultFiles(defoptions);

        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions()
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"static")),
            RequestPath = new PathString("")
        });

        loggerFactory.AddConsole(config.GetSection(key: "Logging"));
    }
}

However, it doesn't try to load an index.html or anything. If I access it manually, it does indeed work.

Any ideas?

Thanks

Body:
Ideally your index.html should be under the web root path (wwwroot), however, if your file is under ContentRootPath\static (as it appears to be), you will need to change your code to specify the DefaultFilesOptions.FileProvider as follows:

PhysicalFileProvider fileProvider = new PhysicalFileProvider(
    Path.Combine(Directory.GetCurrentDirectory(), @"static"));
DefaultFilesOptions defoptions = new DefaultFilesOptions();
defoptions.DefaultFileNames.Clear();
defoptions.FileProvider = fileProvider;
defoptions.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(defoptions);

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = fileProvider,
    RequestPath = new PathString("")
});

Note: you are probably better off using IHostingEnvironment.ContentRootPath (env.ContentRootPath) rather than Directory.GetCurrentDirectory() on the first line (just in case you want to change the content root in your WebHostBuilder at some point).


问:
How to know which header declare the specified function by Visual Studio?
Such I have such code

```<code>#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main() {
    vector<int> values = { 5,3,4,6 };
    sort(values.begin(), values.end(), less<>());
    for_each(values.begin(), values.end(), [](int i) {cout << i <<endl; });
    return 0;
    }
</code>```

I want to know which header included by me(iostream, vector or algorithm) have declared the function less. Of course, we can use Google to search it. But I mean, I want to know this information just by Visual Studio . It is possible? I don't know how to do. And I can button the F12 to know less is in header xstddef, but I don't know which header(iostream, vector or algorithm) include xstddef still. Can anybody can tell me something?

ps: Actually I know the less in the header of <functional>. But note my code have not #include<functional>. But it also can run normally. I think must one of this three header include it already. But I don't know which it is

答:
Your first job is to remove using namespace std;. Then the use of the C++ Standard Library function std::less is obvious at the point of use.

You can then consult your favourite C++ Standard reference manual for the required #includes. Using std::less requires you to #include <functional>.

The fact that you haven't included that file means that you are relying on other headers to include it. Strictly speaking that means you have not written portable C++.

In Visual Studio you can hunt down functions on a right click. But be prepared to wait for a while, and also note that they might not appear where the C++ standard says they should be: so long as you can reach std::less by including <functional>, an implementation can put the function pretty much wherever it wants.

Reference: http://en.cppreference.com/w/cpp/utility/functional/less

Body:
Such I have such code

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main() {
    vector<int> values = { 5,3,4,6 };
    sort(values.begin(), values.end(), less<>());
    for_each(values.begin(), values.end(), [](int i) {cout << i <<endl; });
    return 0;
    }

I want to know which header included by me(iostream, vector or algorithm) have declared the function less. Of course, we can use Google to search it. But I mean, I want to know this information just by Visual Studio . It is possible? I don't know how to do. And I can button the F12 to know less is in header xstddef, but I don't know which header(iostream, vector or algorithm) include xstddef still. Can anybody can tell me something?

ps: Actually I know the less in the header of <functional>. But note my code have not #include<functional>. But it also can run normally. I think must one of this three header include it already. But I don't know which it is


问:
Unable to render component when using a reducer
I am using React-Redux to make a calendar app that stores gardening tasks by month. When I make use of a reducer to store 'task' objects, I am unable to render them out to the calendar, despite not getting any console errors. When I pass in the name of the task using a string, they render correctly.

I have mostly been debugging by console logging at every point to check that the data being passed around is not undefined and is the correct data type. Everything about my app is as I would expect it to be, and nothing seems wrong with it, except that it will not render.

This does not render tasks to the calendar, but produces no errors:

```<code>  render() {
    return (
      <ul className="task-container">
          { this.props.taskTypes.map(task => task.name).forEach(taskName => this.renderTask(taskName)) }
      </ul>
    );
  };
</code>```

This code works (the tasks render to the calendar as expected):

```<code>  render() {
    return (
      <ul className="task-container">
        { this.renderTask("Harvest") }
      </ul>
    );
  };
</code>```

This is my reducer file (task-types.js):

```<code>export default function() {
  return [
    { name: 'Sow Indoors' },
    { name: 'Sow Outside' },
    { name: 'Plant Outside' },
    { name: 'Harvest' },
  ];
}
</code>```

This is the container file in full (TaskGroup.js):

```<code>class TaskGroup extends Component {
  constructor(props) {
    super(props);
    this.checkAgainstMonthAndType = this.checkAgainstMonthAndType.bind(this);
    this.taskTypeIsUsed = this.taskTypeIsUsed.bind(this);
    this.taskHasItems = this.taskHasItems.bind(this);
    this.renderTaskGroup = this.renderTaskGroup.bind(this);
    this.renderTask = this.renderTask.bind(this);
    this.renderTaskItems = this.renderTaskItems.bind(this);
  }

  checkAgainstMonthAndType(list, givenMonth, givenType) {
    return list.some(item => item.month === givenMonth && item.type === givenType);
  }

  taskTypeIsUsed(list, givenMonth, givenType) {
    return list.some(item => this.checkAgainstMonthAndType(item.tasks, givenMonth, givenType));
  };

  taskHasItems(list, givenMonth, givenType) {
    return this.checkAgainstMonthAndType(list, givenMonth, givenType);
  };

  renderTask(taskType) {
    const taskClass = taskType.toLowerCase().replace(" ", "-"); // Sow Indoors -> sow-indoors

    if( this.taskTypeIsUsed(this.props.data, this.props.thisMonth, taskType) ) {
      return (
        <li key={`key-${taskClass}`} className={`task task--${taskClass}`}>
          <h3 className={`task__title task__title--${taskClass}`}>{taskType}</h3>
          <ul className="task__item-list">
            {this.renderTaskItems(taskType)}
          </ul>
        </li>
      );
    }
  };

  renderTaskItems(taskType) {
    return this.props.data
      .filter(item => this.taskHasItems(item.tasks, this.props.thisMonth, taskType))
      .map(item =>
        <Task key={`task-${item.name}`} variety={item.variety} name={item.name} />
      );
  };

  render() {
    return (
      <ul className="task-container">
        {this.renderTask("Sow Indoors")}
      </ul>
    );
  };

}

function mapStateToProps(state) {
  return {
    taskTypes: state.taskTypes,
    data: state.data
  }
}

TaskGroup.propTypes = {
  thisMonth: PropTypes.string.isRequired,
  taskTypes: PropTypes.array.isRequired,
  data: PropTypes.array.isRequired,
};

export default connect(mapStateToProps)(TaskGroup);
</code>```

The calendar app reads API data whereby each plant is an object in this format:

```<code>{
      "id": 0,
      "name": "Peas",
      "variety": "Sugarsnap",
      "tasks": [
        {
          "type": "Sow Indoors",
          "month": "Feb"
        },
        {
          "type": "Plant Outside",
          "month": "Apr"
        },
        {
          "type": "Harvest",
          "month": "May"
        }
      ]
    }
</code>```

答:
forEach loop doesn't return anything. Use only map instead.

```<code>render() {
  return (
    <ul className="task-container">
      {this.props.taskTypes.map(task => this.renderTask(task.name)}
    </ul>
  )
}
</code>```

Body:
I am using React-Redux to make a calendar app that stores gardening tasks by month. When I make use of a reducer to store 'task' objects, I am unable to render them out to the calendar, despite not getting any console errors. When I pass in the name of the task using a string, they render correctly.

I have mostly been debugging by console logging at every point to check that the data being passed around is not undefined and is the correct data type. Everything about my app is as I would expect it to be, and nothing seems wrong with it, except that it will not render.

This does not render tasks to the calendar, but produces no errors:

  render() {
    return (

          { this.props.taskTypes.map(task => task.name).forEach(taskName => this.renderTask(taskName)) }

    );
  };

This code works (the tasks render to the calendar as expected):

  render() {
    return (

        { this.renderTask("Harvest") }

    );
  };

This is my reducer file (task-types.js):

export default function() {
  return [
    { name: 'Sow Indoors' },
    { name: 'Sow Outside' },
    { name: 'Plant Outside' },
    { name: 'Harvest' },
  ];
}

This is the container file in full (TaskGroup.js):

class TaskGroup extends Component {
  constructor(props) {
    super(props);
    this.checkAgainstMonthAndType = this.checkAgainstMonthAndType.bind(this);
    this.taskTypeIsUsed = this.taskTypeIsUsed.bind(this);
    this.taskHasItems = this.taskHasItems.bind(this);
    this.renderTaskGroup = this.renderTaskGroup.bind(this);
    this.renderTask = this.renderTask.bind(this);
    this.renderTaskItems = this.renderTaskItems.bind(this);
  }

  checkAgainstMonthAndType(list, givenMonth, givenType) {
    return list.some(item => item.month === givenMonth && item.type === givenType);
  }

  taskTypeIsUsed(list, givenMonth, givenType) {
    return list.some(item => this.checkAgainstMonthAndType(item.tasks, givenMonth, givenType));
  };

  taskHasItems(list, givenMonth, givenType) {
    return this.checkAgainstMonthAndType(list, givenMonth, givenType);
  };

  renderTask(taskType) {
    const taskClass = taskType.toLowerCase().replace(" ", "-"); // Sow Indoors -> sow-indoors

    if( this.taskTypeIsUsed(this.props.data, this.props.thisMonth, taskType) ) {
      return (
        <li key={`key-${taskClass}`} className={`task task--${taskClass}`}>
          <h3 className={`task__title task__title--${taskClass}`}>{taskType}

            {this.renderTaskItems(taskType)}

      );
    }
  };

  renderTaskItems(taskType) {
    return this.props.data
      .filter(item => this.taskHasItems(item.tasks, this.props.thisMonth, taskType))
      .map(item =>
        <Task key={`task-${item.name}`} variety={item.variety} name={item.name} />
      );
  };

  render() {
    return (

        {this.renderTask("Sow Indoors")}

    );
  };

}

function mapStateToProps(state) {
  return {
    taskTypes: state.taskTypes,
    data: state.data
  }
}

TaskGroup.propTypes = {
  thisMonth: PropTypes.string.isRequired,
  taskTypes: PropTypes.array.isRequired,
  data: PropTypes.array.isRequired,
};

export default connect(mapStateToProps)(TaskGroup);

The calendar app reads API data whereby each plant is an object in this format:

{
      "id": 0,
      "name": "Peas",
      "variety": "Sugarsnap",
      "tasks": [
        {
          "type": "Sow Indoors",
          "month": "Feb"
        },
        {
          "type": "Plant Outside",
          "month": "Apr"
        },
        {
          "type": "Harvest",
          "month": "May"
        }
      ]
    }

Body:
forEach loop doesn't return anything. Use only map instead.

render() {
  return (
    <ul className="task-container">
      {this.props.taskTypes.map(task => this.renderTask(task.name)}
    </ul>
  )
}


问:
Where i can find the systemjs.config.js in angular 4 Application?
I created the angular application via angular cli, I want to use the angular material in that application.

In the angular material document, they said to add some code in systemjs file.but I can't figure out where that file?

答:
Angular CLI no longer creates Angular boilerplates with systemJS config - it creates Angular with integrated Webpack.

Step 1-5 in the documentation Angular Material you install the dependencies through NPM packages, and then you import what you need. So for importing the style for example, add this line to your styles.css

```<code>@import "~@angular/material/prebuilt-themes/indigo-pink.css";
</code>```

In step 6, "Appendix: Configuring SystemJS", is only for older versions of Angular Projects still using SystemJS. As you use an up to date version, you dont need this step, and just need the steps wihtin 1-5

Body:
Angular CLI no longer creates Angular boilerplates with systemJS config - it creates Angular with integrated Webpack.

Step 1-5 in the documentation Angular Material you install the dependencies through NPM packages, and then you import what you need. So for importing the style for example, add this line to your styles.css

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

In step 6, "Appendix: Configuring SystemJS", is only for older versions of Angular Projects still using SystemJS. As you use an up to date version, you dont need this step, and just need the steps wihtin 1-5


问:
PrimeFaces Error StateHelper
What can I do to solve this mistake? This mistake occurs when I run my web application with primefaces, the application recognizes the library and the tags but something happens. If you can solve, please help me.
This my error
  java.lang.NoSuchMethodError: org.primefaces.component.spinner.Spinner.getStateHelper()Ljavax/faces/component/StateHelper;
 at org.primefaces.component.spinner.Spinner.getStepFactor(Spinner.java:68)
 at org.primefaces.component.spinner.SpinnerRenderer.calculateFractionDigits(SpinnerRenderer.java:72)
 at org.primefaces.component.spinner.SpinnerRenderer.encodeScript(SpinnerRenderer.java:52)
 at org.primefaces.component.spinner.SpinnerRenderer.encodeEnd(SpinnerRenderer.java:45)
 at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:649)
 at javax.faces.component.UIComponent.encodeAll(UIComponent.java:261)
 at javax.faces.component.UIComponent.encodeAll(UIComponent.java:257)
 at org.apache.myfaces.application.jsp.JspViewHandlerImpl.actuallyRenderView(JspViewHandlerImpl.java:427)
 at org.apache.myfaces.application.jsp.JspViewHandlerImpl.renderView(JspViewHandlerImpl.java:383)
 at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:41)
 at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:140)
 at org.apache.myfaces.custom.ppr.PPRLifecycleWrapper.render(PPRLifecycleWrapper.java:84)
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:187)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:341)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
 at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:861)
 at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
 at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1584)
 at java.lang.Thread.run(Thread.java:619)

This my web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>Resource Servlet</servlet-name>
        <servlet-class>org.primefaces.resource.ResourceServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Resource Servlet</servlet-name>
        <url-pattern>/primefaces_resource/*</url-pattern>
    </servlet-mapping>
    <context-param>
        <description>Comma separated list of URIs of (additional) faces config files.
            (e.g. /WEB-INF/my-config.xml)
            See JSF 1.0 PRD2, 10.3.2
            Attention: You do not need to put /WEB-INF/faces-config.xml in here.
    </description>
        <param-name>javax.faces.CONFIG_FILES</param-name>
        <param-value>/WEB-INF/faces-config.xml</param-value>
    </context-param>
    <context-param>
        <description>State saving method: "client" or "server" (= default)
            See JSF Specification 2.5.3</description>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>
    <context-param>
        <description>Only applicable if state saving method is "server" (= default).
            Defines the amount (default = 20) of the latest views are stored in session.</description>
        <param-name>org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION</param-name>
        <param-value>20</param-value>
    </context-param>
    <context-param>
        <description>Only applicable if state saving method is "server" (= default).
            If true (default) the state will be serialized to a byte stream before it
            is written to the session.
            If false the state will not be serialized to a byte stream.</description>
        <param-name>org.apache.myfaces.SERIALIZE_STATE_IN_SESSION</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>Only applicable if state saving method is "server" (= default) and if
            org.apache.myfaces.SERIALIZE_STATE_IN_SESSION is true (= default)
            If true (default) the serialized state will be compressed before it
            is written to the session. If false the state will not be compressed.</description>
        <param-name>org.apache.myfaces.COMPRESS_STATE_IN_SESSION</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>This parameter tells MyFaces if javascript code should be allowed in the
            rendered HTML output.
            If javascript is allowed, command_link anchors will have javascript code
            that submits the corresponding form.
            If javascript is not allowed, the state saving info and nested parameters
            will be added as url parameters.
            Default: "true"</description>
        <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
        <param-value>false</param-value>
    </context-param>
    <context-param>
        <description>If true, rendered HTML code will be formatted, so that it is "human readable".
            i.e. additional line separators and whitespace will be written, that do not
            influence the HTML code.
            Default: "true"</description>
        <param-name>org.apache.myfaces.PRETTY_HTML</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>If true, a javascript function will be rendered that is able to restore the
            former vertical scroll on every request. Convenient feature if you have pages
            with long lists and you do not want the browser page to always jump to the top
            if you trigger a link or button action that stays on the same page.
            Default: "false"</description>
        <param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description> Used for encrypting view state.  Only relevant for client side
      state saving.  See MyFaces wiki/web site documentation for instructions
      on how to configure an application for diffenent encryption strengths.
     </description>
        <param-name>org.apache.myfaces.SECRET</param-name>
        <param-value>NzY1NDMyMTA=</param-value>
    </context-param>
    <context-param>
        <description>
     Validate managed beans, navigation rules and ensure that forms are not nested.
    </description>
        <param-name>org.apache.myfaces.VALIDATE</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>A class implementing the
      org.apache.myfaces.shared.renderkit.html.util.AddResource
      interface. It is responsible to
      place scripts and css on the right position in your HTML document.
            Default: "org.apache.myfaces.shared.renderkit.html.util.DefaultAddResource"
            Follow the description on the MyFaces-Wiki-Performance page to enable
            StreamingAddResource instead of DefaultAddResource if you want to
            gain performance.
    </description>
        <param-name>org.apache.myfaces.ADD_RESOURCE_CLASS</param-name>
        <param-value>org.apache.myfaces.renderkit.html.util.DefaultAddResource</param-value>
        <!--param-value>org.apache.myfaces.component.html.util.StreamingAddResource</param-value-->
    </context-param>
    <context-param>
        <description>
        A very common problem in configuring MyFaces-web-applications
        is that the Extensions-Filter is not configured at all
        or improperly configured. This parameter will check for a properly
        configured Extensions-Filter if it is needed by the web-app.
        In most cases this check will work just fine, there might be cases
        where an internal forward will bypass the Extensions-Filter and the check
        will not work. If this is the case, you can disable the check by setting
        this parameter to false.
    </description>
        <param-name>org.apache.myfaces.CHECK_EXTENSIONS_FILTER</param-name>
        <param-value>true</param-value>
    </context-param>
    <filter>
        <filter-name>extensionsFilter</filter-name>
        <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
        <init-param>
            <description>Set the size limit for uploaded files.
                Format: 10 - 10 bytes
                        10k - 10 KB
                        10m - 10 MB
                        1g - 1 GB</description>
            <param-name>uploadMaxFileSize</param-name>
            <param-value>100m</param-value>
        </init-param>
        <init-param>
            <description>Set the threshold size - files
                    below this limit are stored in memory, files above
                    this limit are stored on disk.

                Format: 10 - 10 bytes
                        10k - 10 KB
                        10m - 10 MB
                        1g - 1 GB</description>
            <param-name>uploadThresholdSize</param-name>
            <param-value>100k</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>extensionsFilter</filter-name>
        <url-pattern>*.jsf</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>extensionsFilter</filter-name>
        <url-pattern>/faces/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
        <servlet-name>SourceCodeServlet</servlet-name>
        <servlet-class>org.apache.myfaces.shared_tomahawk.util.servlet.SourceCodeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SourceCodeServlet</servlet-name>
        <url-pattern>*.source</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
</code>```

I am using primefaces 2.0.0 Rc

答: I'd assume version mismatch between primefaces and JSF. For Primefaces 2.0 I think you need JSF 2.0</p>

Title: PrimeFaces Error StateHelper

Body:
What can I do to solve this mistake? This mistake occurs when I run my web application with primefaces, the application recognizes the library and the tags but something happens. If you can solve, please help me.
This my error
  java.lang.NoSuchMethodError: org.primefaces.component.spinner.Spinner.getStateHelper()Ljavax/faces/component/StateHelper;
 at org.primefaces.component.spinner.Spinner.getStepFactor(Spinner.java:68)
 at org.primefaces.component.spinner.SpinnerRenderer.calculateFractionDigits(SpinnerRenderer.java:72)
 at org.primefaces.component.spinner.SpinnerRenderer.encodeScript(SpinnerRenderer.java:52)
 at org.primefaces.component.spinner.SpinnerRenderer.encodeEnd(SpinnerRenderer.java:45)
 at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:649)
 at javax.faces.component.UIComponent.encodeAll(UIComponent.java:261)
 at javax.faces.component.UIComponent.encodeAll(UIComponent.java:257)
 at org.apache.myfaces.application.jsp.JspViewHandlerImpl.actuallyRenderView(JspViewHandlerImpl.java:427)
 at org.apache.myfaces.application.jsp.JspViewHandlerImpl.renderView(JspViewHandlerImpl.java:383)
 at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:41)
 at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:140)
 at org.apache.myfaces.custom.ppr.PPRLifecycleWrapper.render(PPRLifecycleWrapper.java:84)
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:187)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:341)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
 at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:861)
 at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
 at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1584)
 at java.lang.Thread.run(Thread.java:619)

This my web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>Resource Servlet</servlet-name>
        <servlet-class>org.primefaces.resource.ResourceServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Resource Servlet</servlet-name>
        <url-pattern>/primefaces_resource/*</url-pattern>
    </servlet-mapping>
    <context-param>
        <description>Comma separated list of URIs of (additional) faces config files.
            (e.g. /WEB-INF/my-config.xml)
            See JSF 1.0 PRD2, 10.3.2
            Attention: You do not need to put /WEB-INF/faces-config.xml in here.
    </description>
        <param-name>javax.faces.CONFIG_FILES</param-name>
        <param-value>/WEB-INF/faces-config.xml</param-value>
    </context-param>
    <context-param>
        <description>State saving method: "client" or "server" (= default)
            See JSF Specification 2.5.3</description>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>
    <context-param>
        <description>Only applicable if state saving method is "server" (= default).
            Defines the amount (default = 20) of the latest views are stored in session.</description>
        <param-name>org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION</param-name>
        <param-value>20</param-value>
    </context-param>
    <context-param>
        <description>Only applicable if state saving method is "server" (= default).
            If true (default) the state will be serialized to a byte stream before it
            is written to the session.
            If false the state will not be serialized to a byte stream.</description>
        <param-name>org.apache.myfaces.SERIALIZE_STATE_IN_SESSION</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>Only applicable if state saving method is "server" (= default) and if
            org.apache.myfaces.SERIALIZE_STATE_IN_SESSION is true (= default)
            If true (default) the serialized state will be compressed before it
            is written to the session. If false the state will not be compressed.</description>
        <param-name>org.apache.myfaces.COMPRESS_STATE_IN_SESSION</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>This parameter tells MyFaces if javascript code should be allowed in the
            rendered HTML output.
            If javascript is allowed, command_link anchors will have javascript code
            that submits the corresponding form.
            If javascript is not allowed, the state saving info and nested parameters
            will be added as url parameters.
            Default: "true"</description>
        <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
        <param-value>false</param-value>
    </context-param>
    <context-param>
        <description>If true, rendered HTML code will be formatted, so that it is "human readable".
            i.e. additional line separators and whitespace will be written, that do not
            influence the HTML code.
            Default: "true"</description>
        <param-name>org.apache.myfaces.PRETTY_HTML</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>If true, a javascript function will be rendered that is able to restore the
            former vertical scroll on every request. Convenient feature if you have pages
            with long lists and you do not want the browser page to always jump to the top
            if you trigger a link or button action that stays on the same page.
            Default: "false"</description>
        <param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description> Used for encrypting view state.  Only relevant for client side
      state saving.  See MyFaces wiki/web site documentation for instructions
      on how to configure an application for diffenent encryption strengths.
     </description>
        <param-name>org.apache.myfaces.SECRET</param-name>
        <param-value>NzY1NDMyMTA=</param-value>
    </context-param>
    <context-param>
        <description>
     Validate managed beans, navigation rules and ensure that forms are not nested.
    </description>
        <param-name>org.apache.myfaces.VALIDATE</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>A class implementing the
      org.apache.myfaces.shared.renderkit.html.util.AddResource
      interface. It is responsible to
      place scripts and css on the right position in your HTML document.
            Default: "org.apache.myfaces.shared.renderkit.html.util.DefaultAddResource"
            Follow the description on the MyFaces-Wiki-Performance page to enable
            StreamingAddResource instead of DefaultAddResource if you want to
            gain performance.
    </description>
        <param-name>org.apache.myfaces.ADD_RESOURCE_CLASS</param-name>
        <param-value>org.apache.myfaces.renderkit.html.util.DefaultAddResource</param-value>

    </context-param>
    <context-param>
        <description>
        A very common problem in configuring MyFaces-web-applications
        is that the Extensions-Filter is not configured at all
        or improperly configured. This parameter will check for a properly
        configured Extensions-Filter if it is needed by the web-app.
        In most cases this check will work just fine, there might be cases
        where an internal forward will bypass the Extensions-Filter and the check
        will not work. If this is the case, you can disable the check by setting
        this parameter to false.
    </description>
        <param-name>org.apache.myfaces.CHECK_EXTENSIONS_FILTER</param-name>
        <param-value>true</param-value>
    </context-param>
    <filter>
        <filter-name>extensionsFilter</filter-name>
        <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
        <init-param>
            <description>Set the size limit for uploaded files.
                Format: 10 - 10 bytes
                        10k - 10 KB
                        10m - 10 MB
                        1g - 1 GB</description>
            <param-name>uploadMaxFileSize</param-name>
            <param-value>100m</param-value>
        </init-param>
        <init-param>
            <description>Set the threshold size - files
                    below this limit are stored in memory, files above
                    this limit are stored on disk.

                Format: 10 - 10 bytes
                        10k - 10 KB
                        10m - 10 MB
                        1g - 1 GB</description>
            <param-name>uploadThresholdSize</param-name>
            <param-value>100k</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>extensionsFilter</filter-name>
        <url-pattern>*.jsf</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>extensionsFilter</filter-name>
        <url-pattern>/faces/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
        <servlet-name>SourceCodeServlet</servlet-name>
        <servlet-class>org.apache.myfaces.shared_tomahawk.util.servlet.SourceCodeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SourceCodeServlet</servlet-name>
        <url-pattern>*.source</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

I am using primefaces 2.0.0 Rc


问:
To Compress my jQuery
How can I compress my jQuery useful? I want to add a function to show an element when I hover another one. The function below is exactly what I want, but I want it more dynamic. Maybe with an data attribute?

```<code>var item_first = $('.item_first');
var item_second = $('.item_second');
var item_third = $('.item_third');
var item_fourth = $('.item_fourth');

var image_first = $('.image_first');
var image_second = $('.image_second');
var image_third = $('.image_third');
var image_fourth = $('.image_fourth');

$(document).ready(function () {
    item_first.hover(function () {
        image_first.addClass('active');
    }, function () {
        image_first.removeClass('active');
    });

    item_second.hover(function () {
        image_second.addClass('active');
    }, function () {
        image_second.removeClass('active');
    });
    item_third.hover(function () {
        image_third.addClass('active');
    }, function () {
        image_third.removeClass('active');
    });

    item_fourth.hover(function () {
        image_fourth.addClass('active');
    }, function () {
        image_fourth.removeClass('active');
    });
});
</code>```

https://jsfiddle.net/gt5kw00q/

Sorry for my bad English. I try to write so that you understand it.

答:
Based on your fiddle, try this approach

```<code>$( ".left__item" ).hover( function(){
   $(".right__image").eq( $(this).index() ).addClass( "active" );
}, function(){
   $(".right__image").eq( $(this).index() ).removeClass( "active" );
})
</code>```

Demo

$(document).ready(function() {
  $(".left__item").hover(function() {
    $(".right__image").eq($(this).index()).addClass("active");
  }, function() {
    $(".right__image").eq($(this).index()).removeClass("active");
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.right__image {
  display: none;
}

.right__image.active {
  display: block;
}</code>```

      Werte

      Team

      Arbeitsweise

      Standort

      IMAGE 1 HERE

      IMAGE 2 HERE

      IMAGE 3 HERE

      IMAGE 4 HERE

```

Title: To Compress my jQuery

Body:
How can I compress my jQuery useful? I want to add a function to show an element when I hover another one. The function below is exactly what I want, but I want it more dynamic. Maybe with an data attribute?

var item_first = $('.item_first');
var item_second = $('.item_second');
var item_third = $('.item_third');
var item_fourth = $('.item_fourth');

var image_first = $('.image_first');
var image_second = $('.image_second');
var image_third = $('.image_third');
var image_fourth = $('.image_fourth');

$(document).ready(function () {
    item_first.hover(function () {
        image_first.addClass('active');
    }, function () {
        image_first.removeClass('active');
    });

    item_second.hover(function () {
        image_second.addClass('active');
    }, function () {
        image_second.removeClass('active');
    });
    item_third.hover(function () {
        image_third.addClass('active');
    }, function () {
        image_third.removeClass('active');
    });

    item_fourth.hover(function () {
        image_fourth.addClass('active');
    }, function () {
        image_fourth.removeClass('active');
    });
});

https://jsfiddle.net/gt5kw00q/

Sorry for my bad English. I try to write so that you understand it.

Body:
Based on your fiddle, try this approach

$( ".left__item" ).hover( function(){
   $(".right__image").eq( $(this).index() ).addClass( "active" );
}, function(){
   $(".right__image").eq( $(this).index() ).removeClass( "active" );
})

Demo

$(document).ready(function() {
  $(".left__item").hover(function() {
    $(".right__image").eq($(this).index()).addClass("active");
  }, function() {
    $(".right__image").eq($(this).index()).removeClass("active");
  })
});

.right__image {
  display: none;
}

.right__image.active {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left">
  <ul class="left__inner">
    <li class="left__item item_first active">
      <a href="#" title="Werte" target="_self">Werte</a>
    </li>
    <li class="left__item item_second">
      <a href="#" title="Team" target="_self">Team</a>
    </li>
    <li class="left__item item_third">
      <a href="#" title="Arbeitsweise" target="_self">Arbeitsweise</a>
    </li>
    <li class="left__item item_fourth">
      <a href="#" title="Standort" target="_self">Standort</a>
    </li>
  </ul>
</div>

<div class="right">
  <div class="right__inner">
    <div class="right__image image_first">
      IMAGE 1 HERE
    </div>
    <div class="right__image image_second">
      IMAGE 2 HERE
    </div>
    <div class="right__image image_third">
      IMAGE 3 HERE
    </div>
    <div class="right__image image_fourth">
      IMAGE 4 HERE
    </div>
  </div>
</div>