问:
ReactJs redux : How to call a function from the render function if the prop value change?
I have two react components which are ProgramSearchBox and DualBox which are generic and wrapper components of predefined npm packages AutoSuggest and DualListBox respectively.

My task to achieve is Based on the value from ProgramSearchBox, I have to list the set values in the DualListBox.

So, If user select a Program from ProgramSearchBox, then I will call API by passing the ProgramId and fetch the set of result values and have to bind them in the DualListBox.

I will get the user selected ProgramID from the ProgramSearchBox as a prop in DualBox component render method.
How to dispatch an action (call a function) from render function in DualBox component by passing the ProgramId?

If I call a method from render function in DualBox, that is becoming Infinite loop!

Here is DualBox component:

```<code>  //DualBox.js
   class DualBox extends React.Component {
      constructor() {
        super();

        this.state = { selected: [] };

        this.onChange = this.onChange.bind(this);

        this.options = [ ];

        }

      onChange(selected) {
        selected(selected);

      }

      updateOptions()
      {
        console.log("Update Option method called :" + this.props.traineesList );
        this.options = [{ value: 'luna', label: 'Moon' },   { value: 'phobos', label: 'Phobos' }];
        //this.options = this.props.traineeList.map( (value,id) => )
      }
      render() {

            const {ProgramID} = this.props; // HERE I GET ProgramID AS PROP FROM AN ANOTHER COMPONENT
            const {selected} = this.state;

            if(ProgramID !== "") // BASED ON THIS ProgramID VALUE, I NEED TO DISPATCH AN ACTION.
            {
              {this.updateProgramId(ProgramID)} // THIS IS CAUSING INFINITE LOOP
              {this.updateOptions}
            console.log("Program Id came to dualbox:" +ProgramID);
        return <DualListBox options={this.options} selected={selected} onChange={this.onChange}
            canFilter
                filterCallback={(option, filterInput) => {
                    if (filterInput === '') {
                        return true;
                    }

                    return (new RegExp(filterInput, 'i')).test(option.label);
                }}
                filterPlaceholder="Filter..."
            />;
          }
          else
          {
            console.log("Program Id didn't come to dualbox");
        return <DualListBox options={this.options} selected={selected} onChange={this.onChange}
            canFilter
                filterCallback={(option, filterInput) => {
                    if (filterInput === '') {
                        return true;
                    }

                    return (new RegExp(filterInput, 'i')).test(option.label);
                }}
                filterPlaceholder="Filter..."
            />;
          }

      }
    }

    function mapStateToProps(state, ownProps) {
      return {
        traineesList: state.traineesList
      };
    }

    const mapDispatchToProps = (dispatch, ownProps) => {

      return {
        updateProgramId: bindActionCreators(( {ProgramID}) => dualBoxActions.getTraineesList(ProgramID), dispatch)
      };
    }

    export default connect(mapStateToProps,mapDispatchToProps)(DualBox);
</code>```

Here is the ProgramSearchBox component:

```<code>function renderSuggestion(suggestion) {
      return (
        <ul>
          <li>{suggestion.Program}</li>
        </ul>

      );
    }

    class ProgramSearchBox extends React.Component {
      constructor(props) {
        super(props);

      }

      render() {
        const { value, suggestions, onChange, onSuggestionSelected} = this.props;

        const inputProps = {
          placeholder: "Look Up",
          value,
          onChange: (event, { newValue, method }) => {
              this.setState({
                value: newValue
              });
              console.log("onChange: " + JSON.stringify(newValue) );
              onChange(newValue);

          }

        };

        return (
          <Autosuggest
            suggestions={suggestions}
            onSuggestionsFetchRequested={this.props.onSuggestionsFetchRequested}
            onSuggestionsClearRequested={this.props.onSuggestionsClearRequested}
            onSuggestionSelected={
              (event, { suggestion, suggestionValue, suggestionIndex, sectionIndex, method }) => {

                console.log("onSuggestionSelected: " + JSON.stringify(suggestion) );
                onSuggestionSelected(suggestion);

              }
            }
            getSuggestionValue={(suggestion) => suggestion.Program}
            renderSuggestion={renderSuggestion}
            inputProps={inputProps}
            theme={theme}
          />
        );
      }
    }

    function mapStateToProps(state, ownProps) {
      return {
        suggestions: state.results
      };
    }
    const mapDispatchToProps = (dispatch, ownProps) => {

      return {

        onSuggestionsFetchRequested: bindActionCreators(({ value }) => searchActions.getProgramSuggestions(value), dispatch),
        onSuggestionsClearRequested: bindActionCreators(() => searchActions.clearSuggestions(), dispatch),

      };
    }

    export default connect(mapStateToProps, mapDispatchToProps)(ProgramSearchBox);
</code>```

答:
Don't call other functions in render() method. Render method is responsible only for rendering views, it can be called many times and it should be as pure as possible.

Updated answer (2019-11-21)

Use componentDidUpdate(prevProps) lifecycle function to react to prop changes.
It will look something like this:

```<code>componentDidUpdate(prevProps) {
  if (this.props.ProgramID !== '' && prevProps.ProgramID !== this.props.ProgramID) {
        this.updateProgramId(this.props.ProgramID)
    }
}
</code>```

Old answer

To do actions depending on props changing, use componentWillReceiveProps(nextProps) lifecycle function.

It will look something like this:

```<code>componentWillReceiveProps(nextProps) {
    if (nextProps.ProgramID !== '' && this.props.ProgramID !== nextProps.ProgramID) {
        this.updateProgramId(ProgramID)
    }
}
</code>```

After calling this.updateProgramId(ProgramID) props will update and render method will be called.

More info about ReactJS lifecycle:
https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops

Body:
I have two react components which are ProgramSearchBox and DualBox which are generic and wrapper components of predefined npm packages AutoSuggest and DualListBox respectively.

My task to achieve is Based on the value from ProgramSearchBox, I have to list the set values in the DualListBox.

So, If user select a Program from ProgramSearchBox, then I will call API by passing the ProgramId and fetch the set of result values and have to bind them in the DualListBox.

I will get the user selected ProgramID from the ProgramSearchBox as a prop in DualBox component render method.
How to dispatch an action (call a function) from render function in DualBox component by passing the ProgramId?

If I call a method from render function in DualBox, that is becoming Infinite loop!

Here is DualBox component:

  //DualBox.js
   class DualBox extends React.Component {
      constructor() {
        super();

        this.state = { selected: [] };

        this.onChange = this.onChange.bind(this);

        this.options = [ ];

        }

      onChange(selected) {
        selected(selected);

      }

      updateOptions()
      {
        console.log("Update Option method called :" + this.props.traineesList );
        this.options = [{ value: 'luna', label: 'Moon' },   { value: 'phobos', label: 'Phobos' }];
        //this.options = this.props.traineeList.map( (value,id) => )
      }
      render() {

            const {ProgramID} = this.props; // HERE I GET ProgramID AS PROP FROM AN ANOTHER COMPONENT
            const {selected} = this.state;

            if(ProgramID !== "") // BASED ON THIS ProgramID VALUE, I NEED TO DISPATCH AN ACTION.
            {
              {this.updateProgramId(ProgramID)} // THIS IS CAUSING INFINITE LOOP
              {this.updateOptions}
            console.log("Program Id came to dualbox:" +ProgramID);
        return <DualListBox options={this.options} selected={selected} onChange={this.onChange}
            canFilter
                filterCallback={(option, filterInput) => {
                    if (filterInput === '') {
                        return true;
                    }

                    return (new RegExp(filterInput, 'i')).test(option.label);
                }}
                filterPlaceholder="Filter..."
            />;
          }
          else
          {
            console.log("Program Id didn't come to dualbox");
        return <DualListBox options={this.options} selected={selected} onChange={this.onChange}
            canFilter
                filterCallback={(option, filterInput) => {
                    if (filterInput === '') {
                        return true;
                    }

                    return (new RegExp(filterInput, 'i')).test(option.label);
                }}
                filterPlaceholder="Filter..."
            />;
          }

      }
    }

    function mapStateToProps(state, ownProps) {
      return {
        traineesList: state.traineesList
      };
    }

    const mapDispatchToProps = (dispatch, ownProps) => {

      return {
        updateProgramId: bindActionCreators(( {ProgramID}) => dualBoxActions.getTraineesList(ProgramID), dispatch)
      };
    }

    export default connect(mapStateToProps,mapDispatchToProps)(DualBox);

Here is the ProgramSearchBox component:

function renderSuggestion(suggestion) {
      return (

{suggestion.Program}

      );
    }

    class ProgramSearchBox extends React.Component {
      constructor(props) {
        super(props);

      }

      render() {
        const { value, suggestions, onChange, onSuggestionSelected} = this.props;

        const inputProps = {
          placeholder: "Look Up",
          value,
          onChange: (event, { newValue, method }) => {
              this.setState({
                value: newValue
              });
              console.log("onChange: " + JSON.stringify(newValue) );
              onChange(newValue);

          }

        };

        return (
          <Autosuggest
            suggestions={suggestions}
            onSuggestionsFetchRequested={this.props.onSuggestionsFetchRequested}
            onSuggestionsClearRequested={this.props.onSuggestionsClearRequested}
            onSuggestionSelected={
              (event, { suggestion, suggestionValue, suggestionIndex, sectionIndex, method }) => {

                console.log("onSuggestionSelected: " + JSON.stringify(suggestion) );
                onSuggestionSelected(suggestion);

              }
            }
            getSuggestionValue={(suggestion) => suggestion.Program}
            renderSuggestion={renderSuggestion}
            inputProps={inputProps}
            theme={theme}
          />
        );
      }
    }

    function mapStateToProps(state, ownProps) {
      return {
        suggestions: state.results
      };
    }
    const mapDispatchToProps = (dispatch, ownProps) => {

      return {

        onSuggestionsFetchRequested: bindActionCreators(({ value }) => searchActions.getProgramSuggestions(value), dispatch),
        onSuggestionsClearRequested: bindActionCreators(() => searchActions.clearSuggestions(), dispatch),

      };
    }

    export default connect(mapStateToProps, mapDispatchToProps)(ProgramSearchBox);

Body:
Don't call other functions in render() method. Render method is responsible only for rendering views, it can be called many times and it should be as pure as possible.

Updated answer (2019-11-21)

Use componentDidUpdate(prevProps) lifecycle function to react to prop changes.
It will look something like this:

componentDidUpdate(prevProps) {
  if (this.props.ProgramID !== '' && prevProps.ProgramID !== this.props.ProgramID) {
        this.updateProgramId(this.props.ProgramID)
    }
}

Old answer

To do actions depending on props changing, use componentWillReceiveProps(nextProps) lifecycle function.

It will look something like this:

componentWillReceiveProps(nextProps) {
    if (nextProps.ProgramID !== '' && this.props.ProgramID !== nextProps.ProgramID) {
        this.updateProgramId(ProgramID)
    }
}

After calling this.updateProgramId(ProgramID) props will update and render method will be called.

More info about ReactJS lifecycle:
https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops


来源: stackexchange

问:
Copy and Pasting excel data from unopened excel sheet to destination excel sheet to the last row
I am trying to copy and paste data from one excel sheet to another sheet into the last available row. My current code is overwriting the previous data. I would like to add data to last available row. Please help.

Sub CopyToExcel()

Application.ScreenUpdating = False

Application.EnableEvents = False

```<code>WB_1 = ThisWorkbook.Name
WB_2 = "Analysis.xls"
b_file = "C:\\" & WB_2

On Error Resume Next
    Workbooks.Open (b_file)
If Err.Number <> 0 Then
    MsgBox ("Cannot find " & WB_2 & "-file!")
    Application.EnableEvents = True
    Application.ScreenUpdating = True
    Exit Sub
End If

t_max = Workbooks(WB_2).Sheets("Page 1").Cells(Rows.Count, 1).End(xlUp).Row
Workbooks(WB_2).Sheets("Page 1").Range("A1:R" & 100).Copy Destination:=Workbooks(WB_1).Sheets("DB2").Range("C1")
Workbooks(WB_2).Close SaveChanges:=False
Workbooks(WB_1).Activate

Application.EnableEvents = True
Application.ScreenUpdating = True
ActiveWorkbook.Save
</code>```

End Sub

答:
I don't see you finding the last row in WB_1 nor can I see you using that?. My suggestion: Work with objects. It becomes easier to understand what you are doing and you have a better control over the code.

Is this what you are trying? (Untested)

```<code>Sub CopyToExcel()
    Dim wbDest As Workbook, wbSource As Workbook
    Dim wsDest As Worksheet, wsSource As Worksheet
    Dim lRowDest As Long, lRowSource As Long

    '~~> This is the workbook where you want to copy
    Set wbDest = ThisWorkbook
    '~~> This is the worksheet where you want to copy
    Set wsDest = wbDest.Sheets("DB2")
    '~~> This is the last row where the data will be copied
    lRowDest = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).Row + 1

    '~~> This is the workbook FROM where you want to copy
    Set wbSource = Workbooks.Open("C:\Analysis.xls")
    '~~> This is the worksheet FROM where you want to copy
    Set wsSource = wbSource.Sheets("Page 1")

    With wsSource
        '~~> This is the last row till where the data will be copied from
        lRowSource = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Do the final Copy
        .Range("A1:R" & lRowSource).Copy wsDest.Range("C" & lRowDest)
    End With

    wbSource.Close (False)
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to copy and paste data from one excel sheet to another sheet into the last available row. My current code is overwriting the previous data. I would like to add data to last available row. Please help.

Sub CopyToExcel()

Application.ScreenUpdating = False

Application.EnableEvents = False

WB_1 = ThisWorkbook.Name
WB_2 = "Analysis.xls"
b_file = "C:\\" & WB_2

On Error Resume Next
    Workbooks.Open (b_file)
If Err.Number <> 0 Then
    MsgBox ("Cannot find " & WB_2 & "-file!")
    Application.EnableEvents = True
    Application.ScreenUpdating = True
    Exit Sub
End If

t_max = Workbooks(WB_2).Sheets("Page 1").Cells(Rows.Count, 1).End(xlUp).Row
Workbooks(WB_2).Sheets("Page 1").Range("A1:R" & 100).Copy Destination:=Workbooks(WB_1).Sheets("DB2").Range("C1")
Workbooks(WB_2).Close SaveChanges:=False
Workbooks(WB_1).Activate

Application.EnableEvents = True
Application.ScreenUpdating = True
ActiveWorkbook.Save

End Sub

Body:
I don't see you finding the last row in WB_1 nor can I see you using that?. My suggestion: Work with objects. It becomes easier to understand what you are doing and you have a better control over the code.

Is this what you are trying? (Untested)

Sub CopyToExcel()
    Dim wbDest As Workbook, wbSource As Workbook
    Dim wsDest As Worksheet, wsSource As Worksheet
    Dim lRowDest As Long, lRowSource As Long

    '~~> This is the workbook where you want to copy
    Set wbDest = ThisWorkbook
    '~~> This is the worksheet where you want to copy
    Set wsDest = wbDest.Sheets("DB2")
    '~~> This is the last row where the data will be copied
    lRowDest = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).Row + 1

    '~~> This is the workbook FROM where you want to copy
    Set wbSource = Workbooks.Open("C:\Analysis.xls")
    '~~> This is the worksheet FROM where you want to copy
    Set wsSource = wbSource.Sheets("Page 1")

    With wsSource
        '~~> This is the last row till where the data will be copied from
        lRowSource = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Do the final Copy
        .Range("A1:R" & lRowSource).Copy wsDest.Range("C" & lRowDest)
    End With

    wbSource.Close (False)
End Sub


问:
Ionic 2: login with keycloak
I have MyApp - Ionic 2 app and I would like to implement login via Keycloak as you can see here here.

MyApp is runnig on http://localhost:8100/

Keycloak server on http://localhost:8080/

Have following scenario:

User Access MyApp and press login button.

User is redirect to Keycloak page, fills the credentials and press the login.

User is redirected back to MyApp:

Here is the issue:  The MyApp will not store the cookies from Keycloak response (see here). So I was thinking about catching the redirect from Keycloak, extracting the cookies and storing them into LocalStorage. I don't know how in Angular 2 catch such redirect.

Thanks for any advice!

答:
In the Keycloak there is a Javascript Adapter - keycloak.js, it already knows how to work with a Cordova application.

Your another question already has an answer, how to work with this js adapter Ionic 2: login via keycloak won't store keycloak cookies

Title: Ionic 2: login with keycloak


问:
Measuring function execution time in R
Is there a standardized way in R of measuring execution time of function?

Obviously I can take system.time before and after execution and then take the difference of those, but I would like to know if there is some standardized way or function (would like to not invent the wheel).

I seem to remember that I have once used something like below:

```<code>somesysfunction("myfunction(with,arguments)")
> Start time : 2001-01-01 00:00:00  # output of somesysfunction
> "Result" "of" "myfunction"        # output of myfunction
> End time : 2001-01-01 00:00:10    # output of somesysfunction
> Total Execution time : 10 seconds # output of somesysfunction
</code>```

答:
microbenchmark is a lightweight (~50kB) package and more-or-less a standard way in R for benchmarking multiple expressions and functions:

```<code>microbenchmark(myfunction(with,arguments))
</code>```

For example:

```<code>> microbenchmark::microbenchmark(log10(5), log(5)/log(10), times = 10000)
Unit: nanoseconds
           expr min lq    mean median uq   max neval cld
       log10(5)   0  0 25.5738      0  1 10265 10000   a
 log(5)/log(10)   0  0 28.1838      0  1 10265 10000
</code>```

Here both the expressions were evaluated 10000 times, with mean execution time being around 25-30 ns.

Title: Measuring function execution time in R

Body:
Is there a standardized way in R of measuring execution time of function?

Obviously I can take system.time before and after execution and then take the difference of those, but I would like to know if there is some standardized way or function (would like to not invent the wheel).

I seem to remember that I have once used something like below:

somesysfunction("myfunction(with,arguments)")
> Start time : 2001-01-01 00:00:00  # output of somesysfunction
> "Result" "of" "myfunction"        # output of myfunction
> End time : 2001-01-01 00:00:10    # output of somesysfunction
> Total Execution time : 10 seconds # output of somesysfunction

Body:
microbenchmark is a lightweight (~50kB) package and more-or-less a standard way in R for benchmarking multiple expressions and functions:

microbenchmark(myfunction(with,arguments))

For example:

> microbenchmark::microbenchmark(log10(5), log(5)/log(10), times = 10000)
Unit: nanoseconds
           expr min lq    mean median uq   max neval cld
       log10(5)   0  0 25.5738      0  1 10265 10000   a
 log(5)/log(10)   0  0 28.1838      0  1 10265 10000

Here both the expressions were evaluated 10000 times, with mean execution time being around 25-30 ns.


问:
Angular 2: how to update service variable in a module's component so that the variable in lazy module updates automatically?
Below is a link to project on Plunker. where there are two components eager and lazy, also there is shared service which is used on both components.

How to update service variable in a module's component so that the variable in lazy module updates automatically?

```<code>[Plunker example][1]
[1]: https://plnkr.co/edit/L2ypUQZiltSPXnLlxBoa?p=preview
</code>```

答:
You can achieve this by using an Observable. This observable is stored in your service and other can subscribe to this observable. Below is an example in which I have removed the standard Angular stuff to improve readability:

service.ts

```<code>@Injectable()
export class MyService {
    // BehaviorSubject sends last known value when someone subscribes.
    public isAuthenticated$ = new BehaviorSubject<boolean>(false);

    changeAuthenticated() {
       // broadcast true to all subscribers
       this.isAuthenticated$.next(true);
    }

}
</code>```

component.ts

```<code>myService.isAuthenticated$.subscribe(authenticated => {

    if (authenticated) {
        // do stuff
    }

});
</code>```

So when isAuthenticated$ inside MyService is changed it fires to all subscribers. Please not it doesn't fire if there are no subscribers.

More info about Observables: https://angular-2-training-book.rangle.io/handout/observables/using_observables.html

Body:
Below is a link to project on Plunker. where there are two components eager and lazy, also there is shared service which is used on both components.

How to update service variable in a module's component so that the variable in lazy module updates automatically?

[Plunker example][1]
[1]: https://plnkr.co/edit/L2ypUQZiltSPXnLlxBoa?p=preview

Body:
You can achieve this by using an Observable. This observable is stored in your service and other can subscribe to this observable. Below is an example in which I have removed the standard Angular stuff to improve readability:

service.ts

@Injectable()
export class MyService {
    // BehaviorSubject sends last known value when someone subscribes.
    public isAuthenticated$ = new BehaviorSubject<boolean>(false);

    changeAuthenticated() {
       // broadcast true to all subscribers
       this.isAuthenticated$.next(true);
    }

}

component.ts

myService.isAuthenticated$.subscribe(authenticated => {

    if (authenticated) {
        // do stuff
    }

});

So when isAuthenticated$ inside MyService is changed it fires to all subscribers. Please not it doesn't fire if there are no subscribers.

More info about Observables: https://angular-2-training-book.rangle.io/handout/observables/using_observables.html


问:
text-overflow in span element not cutting texta outside element width
I'm trying to make a div with 3 spans inside where the middle one should "compress", ie cut the extra text when the size of the div is small.

The result I'm looking for is

```<code>A Very lon... A
          ^ here it should get cut with "text-overflow: ellipsis;"
</code>```

Somehow the text-overflow: ellipsis; is not being applied to the span.

Any idea what I am missing?

Tried with width, display, overflow and nothing seems to work... tested both Chrome and Firefox.

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>A</span>
  <span id="long-text">Very long text here....</span>
  <span>A</span>
</div></code>```

答:
change your padding to margin.

margin gives spaces outside your object while padding gives you spaces inside. text overflow will not consider it outside if it is still inside that padding

Body:
I'm trying to make a div with 3 spans inside where the middle one should "compress", ie cut the extra text when the size of the div is small.

The result I'm looking for is

A Very lon... A
          ^ here it should get cut with "text-overflow: ellipsis;"

Somehow the text-overflow: ellipsis; is not being applied to the span.

Any idea what I am missing?

Tried with width, display, overflow and nothing seems to work... tested both Chrome and Firefox.

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}

  A
  Very long text here....
  A


问:
How to match with new RegExp exactly
I have this string:

```<code>var str = "https://www.mysite.se/this-match?ba=11"
</code>```

I need to match it exactly (between / and ?), so only this-match matches, not this-ma or anything (shorter) that is contained in this-match.
I.e:

```<code>var myre = new RegExp('\/this-ma\?');
</code>```

Still matches:

```<code>myre.exec(str)[0]
"/this-ma"
</code>```

How can I avoid that a shorter string contained in this-match does give a match?

答:
The definition of your regex is wrong. You'd think that \? would match literal ? character, instead of being non-greedy modifier. Not true. Quite the opposite, in fact.

```<code>var myre = new RegExp('\/this-ma\?');
> /\/this-ma?/
</code>```

The backslash here works within the string literal, and outputs single ? to regex, which becomes non-greedy modifier. Use the regex literal.

```<code>var myre = /\/this-ma\?/
</code>```

Title: How to match with new RegExp exactly

Body:
I have this string:

var str = "https://www.mysite.se/this-match?ba=11"

I need to match it exactly (between / and ?), so only this-match matches, not this-ma or anything (shorter) that is contained in this-match.
I.e:

var myre = new RegExp('\/this-ma\?');

Still matches:

myre.exec(str)[0]
"/this-ma"

How can I avoid that a shorter string contained in this-match does give a match?

Body:
The definition of your regex is wrong. You'd think that \? would match literal ? character, instead of being non-greedy modifier. Not true. Quite the opposite, in fact.

var myre = new RegExp('\/this-ma\?');
> /\/this-ma?/

The backslash here works within the string literal, and outputs single ? to regex, which becomes non-greedy modifier. Use the regex literal.

var myre = /\/this-ma\?/


问:
C# WebApi Json Posting
I have below C# code for WEB API When I post below JSON the Account object is always null. Please, anyone can guide on below code.

```<code>public class Account
{
    public string id { get; set; }
    public string number { get; set; }
}

public object Post([FromBody] Account account)
{
    Message msg = new Message();
    msg.status = "Status";
    return Request.CreateResponse(msg);
}
</code>```

JSON

```<code>{
  "Accounts": {
    "id": "13456454",
    "number": "222",
  }
}
</code>```

答:
Your json:

```<code>{
  "Accounts": {
    "id": "13456454",
    "number": "222",
  }
}
</code>```

It can be parsed to object with property Accounts which has id and number properties

If you want to post only one Account your json should be:

```<code>{
    "id": "13456454",
    "number": "222"
}
</code>```

Title: C# WebApi Json Posting

Body:
I have below C# code for WEB API When I post below JSON the Account object is always null. Please, anyone can guide on below code.

public class Account
{
    public string id { get; set; }
    public string number { get; set; }
}

public object Post([FromBody] Account account)
{
    Message msg = new Message();
    msg.status = "Status";
    return Request.CreateResponse(msg);
}

JSON

{
  "Accounts": {
    "id": "13456454",
    "number": "222",
  }
}

Body:
Your json:

{
  "Accounts": {
    "id": "13456454",
    "number": "222",
  }
}

It can be parsed to object with property Accounts which has id and number properties

If you want to post only one Account your json should be:

{
    "id": "13456454",
    "number": "222"
}


问:
Repository Pattern - Validating Object and Return Message
I'm working on a website, and just trying to get my head around the general structure. I have a database in the background that I'm accessing using the "Repository Pattern". I have the below code in my UserRepository class:

```<code>public bool IsValid(User user)
{
  if (_context.Users.Any(c => c.EmailAddress == user.EmailAddress))
  {
    Message = "Email address already in use";
    return false;
  }

  return true;
}
</code>```

And that is implemented here

```<code>[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(User user)
{
  if (ModelState.IsValid)
  {
    var context = new Context("DatabaseContext");
    var userRepo = new UserRepository(context);

    if (userRepo.IsValid(user))
    {
      userRepo.Add(user);
      // return to different view
    }
    else
    {
      // display userRepo.Message on page
      return View(user);
    }
  }

  return View(user);
}
</code>```

My problem is I don't think I'm going around the "message" bit correctly, but I can't find anything online to help me out (specifically around repository). I think I should be changing the return type of IsValid to something like a result (as I've seen with dialog boxes), but again, I'm not sure.

Any help would be much appreciated.

Thanks.

答:
One way to achieve this is exactly like you have suggested - change the return type of IsValid.

In the past I have had similar validation methods in my "business layer" that return a collection of ValidationResult, where each returned record accounts for a validation error within the model and an empty collection would be interpreted as a valid model.

For example:

```<code>public class ValidationResult
{
    public string FieldName { get; set; }
    public string Message { get; set; }
}

public interface IValidator<T>
{
    IEnumerable<ValidationResult> IsValid(T model);
}

//...in your implementation
public IEnumerable<ValidationResult> IsValid(User user)
{
    //Return a new ValidationResult per validation error
    if (_context.Users.Any(c => c.EmailAddress == user.EmailAddress))
    {
        yield return new ValidationResult
        {
            Message = "Email address already in use",
            FieldName = nameof(user.EmailAddress)
        };
    }
}
</code>```

This could then be interpreted by your presentation layer to feedback to the user.

Body:
I'm working on a website, and just trying to get my head around the general structure. I have a database in the background that I'm accessing using the "Repository Pattern". I have the below code in my UserRepository class:

public bool IsValid(User user)
{
  if (_context.Users.Any(c => c.EmailAddress == user.EmailAddress))
  {
    Message = "Email address already in use";
    return false;
  }

  return true;
}

And that is implemented here

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(User user)
{
  if (ModelState.IsValid)
  {
    var context = new Context("DatabaseContext");
    var userRepo = new UserRepository(context);

    if (userRepo.IsValid(user))
    {
      userRepo.Add(user);
      // return to different view
    }
    else
    {
      // display userRepo.Message on page
      return View(user);
    }
  }

  return View(user);
}

My problem is I don't think I'm going around the "message" bit correctly, but I can't find anything online to help me out (specifically around repository). I think I should be changing the return type of IsValid to something like a result (as I've seen with dialog boxes), but again, I'm not sure.

Any help would be much appreciated.

Thanks.

Body:
One way to achieve this is exactly like you have suggested - change the return type of IsValid.

In the past I have had similar validation methods in my "business layer" that return a collection of ValidationResult, where each returned record accounts for a validation error within the model and an empty collection would be interpreted as a valid model.

For example:

public class ValidationResult
{
    public string FieldName { get; set; }
    public string Message { get; set; }
}

public interface IValidator<T>
{
    IEnumerable<ValidationResult> IsValid(T model);
}

//...in your implementation
public IEnumerable<ValidationResult> IsValid(User user)
{
    //Return a new ValidationResult per validation error
    if (_context.Users.Any(c => c.EmailAddress == user.EmailAddress))
    {
        yield return new ValidationResult
        {
            Message = "Email address already in use",
            FieldName = nameof(user.EmailAddress)
        };
    }
}

This could then be interpreted by your presentation layer to feedback to the user.


问:
PostgreSQL get date
I have the following query which returns the date as dd/mm/yyyy hh:mm:ss, but I would like to extract the time and date as separate columns, how can I do this please?  I am new to PostgreSQL

Thanks
Kath

```<code>select
    up.mis_id,
    up.name,
    up.surname,
    es.created as "signed in",
    es1.created as "signed out",
    bb.name as "location"

from users_person as up

join users_role as ur on ur.id = up.role_id
join events_event as ee on ee.user_id = up.id
join events_swipe as es on es.id = ee.sign_in_id
join events_swipe as es1 on es1.id = ee.sign_out_id
join buildings_building as bb on bb.id = es.location_id
</code>```

答:
Use to_char. See Postgres documentation

```<code>select to_char(current_timestamp, 'HH12:MI:SS') as time,
       to_char(current_timestamp, 'mm/dd/yyyy') as date;
       time   |    date
    ----------+------------
     04:43:13 | 06/06/2017
    (1 row)
</code>```

Title: PostgreSQL get date

Body:
I have the following query which returns the date as dd/mm/yyyy hh:mm:ss, but I would like to extract the time and date as separate columns, how can I do this please?  I am new to PostgreSQL

Thanks
Kath

select
    up.mis_id,
    up.name,
    up.surname,
    es.created as "signed in",
    es1.created as "signed out",
    bb.name as "location"

from users_person as up

join users_role as ur on ur.id = up.role_id
join events_event as ee on ee.user_id = up.id
join events_swipe as es on es.id = ee.sign_in_id
join events_swipe as es1 on es1.id = ee.sign_out_id
join buildings_building as bb on bb.id = es.location_id

Body:
Use to_char. See Postgres documentation

select to_char(current_timestamp, 'HH12:MI:SS') as time,
       to_char(current_timestamp, 'mm/dd/yyyy') as date;
       time   |    date
    ----------+------------
     04:43:13 | 06/06/2017
    (1 row)


问:
XmlSerializer - Same Element with different Attributes
Expected XML Output:

```<code><add>
 <doc>
  <field name="id">1</field>
  <field name="Myname">MyName1</field1>
 </doc>
 <doc>
  <field name="id">2</field>
  <field name="Myname">MyName2</field>
 </doc>
 <doc>
  <field name="id">3</field>
  <field name="Myname">MyName3</field>
 </doc>
</add>
</code>```

To get the above XML document, I designed the following class

```<code>public class doc
{
    [XmlElement("field")]
    public ID Id
    {
        get;
        set;
    }
    [XmlElement("field2")]
    public Name Myname
    {
        get;
        set;
    }
}
</code>```

Name class will be

```<code> public class Name
{
    [XmlText]
    public string Namevalue
    {
        get;
        set;
    }
    [XmlAttribute("name")]
    public string Myname
    {
        get;
        set;
    }
}
</code>```

XmlSerializer Code:

```<code>XmlSerializer serializer = new XmlSerializer(typeof(List<doc>), new XmlRootAttribute("add"));
</code>```

This give me the following output

```<code><add>
 <doc>
  <field name="id">1</field>
  <field2 name="Myname">MyName1</field2>
 </doc>
 <doc>
  <field name="id">2</field>
  <field2 name="Myname">MyName2</field2>
 </doc>
 <doc>
  <field name="id">3</field>
  <field2 name="Myname">MyName3</field2>
 </doc>
</add>
</code>```

Here the field2 should be field I know I need to change the field2 as field in doc class but that results in error.

How should I design my class to get the expected output?

Edit: ID class will also look like Name class with its own attributes

答:
Something like:

```<code>[XmlType("add"), XmlRoot("add")]
public class WhateverAddIs {
    private readonly List<Document> docs = new List<Document>();
    [XmlElement("doc")]
    public List<Document> Documents { get { return docs; } }
}
public class Document {
    private readonly List<Field> fields = new List<Field>();
    [XmlElement("field")]
    public List<Field> Fields { get { return fields; } }
}
public class Field {
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlText]
    public string Value { get; set; }
}
</code>```

Then:

```<code>class Program {
    static void Main() {
        var add = new WhateverAddIs {
            Documents = {
                new Document {
                    Fields = {
                        new Field { Name="id", Value ="1"},
                        new Field { Name="Myname", Value ="Myname1"},
                    }
                }, new Document {
                    Fields = {
                        new Field { Name="id", Value ="2"},
                        new Field { Name="Myname", Value ="Myname2"},
                    }
                }, new Document {
                    Fields = {
                        new Field { Name="id", Value ="3"},
                        new Field { Name="Myname", Value ="Myname3"},
                    }
                }
            }
        };
        var ser = new XmlSerializer(add.GetType());
        ser.Serialize(Console.Out, add);
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Expected XML Output:

<add>
 <doc>
  <field name="id">1</field>
  <field name="Myname">MyName1</field1>
 </doc>
 <doc>
  <field name="id">2</field>
  <field name="Myname">MyName2</field>
 </doc>
 <doc>
  <field name="id">3</field>
  <field name="Myname">MyName3</field>
 </doc>
</add>

To get the above XML document, I designed the following class

public class doc
{
    [XmlElement("field")]
    public ID Id
    {
        get;
        set;
    }
    [XmlElement("field2")]
    public Name Myname
    {
        get;
        set;
    }
}

Name class will be

 public class Name
{
    [XmlText]
    public string Namevalue
    {
        get;
        set;
    }
    [XmlAttribute("name")]
    public string Myname
    {
        get;
        set;
    }
}

XmlSerializer Code:

XmlSerializer serializer = new XmlSerializer(typeof(List<doc>), new XmlRootAttribute("add"));

This give me the following output

<add>
 <doc>
  <field name="id">1</field>
  <field2 name="Myname">MyName1</field2>
 </doc>
 <doc>
  <field name="id">2</field>
  <field2 name="Myname">MyName2</field2>
 </doc>
 <doc>
  <field name="id">3</field>
  <field2 name="Myname">MyName3</field2>
 </doc>
</add>

Here the field2 should be field I know I need to change the field2 as field in doc class but that results in error.

How should I design my class to get the expected output?

Edit: ID class will also look like Name class with its own attributes

Body:
Something like:

[XmlType("add"), XmlRoot("add")]
public class WhateverAddIs {
    private readonly List<Document> docs = new List<Document>();
    [XmlElement("doc")]
    public List<Document> Documents { get { return docs; } }
}
public class Document {
    private readonly List<Field> fields = new List<Field>();
    [XmlElement("field")]
    public List<Field> Fields { get { return fields; } }
}
public class Field {
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlText]
    public string Value { get; set; }
}

Then:

class Program {
    static void Main() {
        var add = new WhateverAddIs {
            Documents = {
                new Document {
                    Fields = {
                        new Field { Name="id", Value ="1"},
                        new Field { Name="Myname", Value ="Myname1"},
                    }
                }, new Document {
                    Fields = {
                        new Field { Name="id", Value ="2"},
                        new Field { Name="Myname", Value ="Myname2"},
                    }
                }, new Document {
                    Fields = {
                        new Field { Name="id", Value ="3"},
                        new Field { Name="Myname", Value ="Myname3"},
                    }
                }
            }
        };
        var ser = new XmlSerializer(add.GetType());
        ser.Serialize(Console.Out, add);
    }
}


问:
open new activity with button
here is the code of my xml.

```<code><Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn2"
            android:layout_gravity="center_horizontal"
            android:text="Make New Account"
            android:onClick="new"
            android:textColor="#E74C3C"
            android:textStyle="bold"
            android:paddingTop="20dp"/>
</code>```

and here is my code of java.

```<code> public Button btn2;
public void onClick(){
    btn2=(Button)findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });

}
</code>```

my button is not working yet, even an message will appear after clicking on button that unfortunately application has stopped... what is the reason??

答:
The thing is you are calling the onClick function when you have declared the onClick of button as new

Try this :

```<code><Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn2"
        android:layout_gravity="center_horizontal"
        android:text="Make New Account"
        android:onClick="submit"
        android:textColor="#E74C3C"
        android:textStyle="bold"
        android:paddingTop="20dp"/>
</code>```

And then in your activity class declare this function:

```<code>public void submit(View view){
Intent intent = new Intent(MainActivity.this,submit.class);
        startActivity(intent);
}
</code>```

That's it. Hope this helps.

Title: open new activity with button

Body:
here is the code of my xml.

<Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn2"
            android:layout_gravity="center_horizontal"
            android:text="Make New Account"
            android:onClick="new"
            android:textColor="#E74C3C"
            android:textStyle="bold"
            android:paddingTop="20dp"/>

and here is my code of java.

 public Button btn2;
public void onClick(){
    btn2=(Button)findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });

}

my button is not working yet, even an message will appear after clicking on button that unfortunately application has stopped... what is the reason??

Body:
The thing is you are calling the onClick function when you have declared the onClick of button as new

Try this :

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn2"
        android:layout_gravity="center_horizontal"
        android:text="Make New Account"
        android:onClick="submit"
        android:textColor="#E74C3C"
        android:textStyle="bold"
        android:paddingTop="20dp"/>

And then in your activity class declare this function:

public void submit(View view){
Intent intent = new Intent(MainActivity.this,submit.class);
        startActivity(intent);
}

That's it. Hope this helps.


问:
Project refresh failed, Failed to open zip file
I recently updated android studio version from 2.2.3 to 2.3 and My Working project starts throwing error below.

Error : Failed to open zip file.

Gradle's dependency cache may be corrupt (this sometimes occurs after
a network connection timeout.)

Re-download dependencies and sync project (requires network)

Re-download dependencies and sync project (requires network)

I searched a lot and find many solutions but no one suitable to solve my error

答:
This usually happens when something goes wrong in Android Studio's first launch (eg. system crash, connection loss or whatever).

To resolve this issue close the Android Studio and delete the following directory's content, necessary files will be downloaded on IDE's next launch.

macOS: ~/.gradle/wrapper/dists

Windows: C:\Users\your-username.gradle\wrapper\dists

While downloading Gradle manually works, I recommend letting Android Studio itself to do it.


问:
Unpacking argument in print statements
I would like to know if there is a way to unpack values in a print statement, the same way it is possible to unpack arguments in a function f

This works:

```<code>import numpy
er = numpy.array([0.36666667, 0.46666667, 0.43333333, numpy.nan])
l = 0.8
print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (er[0], er[1], er[2], er[3], l))
# 0.367 | 0.467 | 0.433 | nan | 0.8
</code>```

However, I would like to avoid multiple er[x] and instead use something like *er as in:

```<code>def f(a,b,c,d):
    return True
print(f(*er))
# True
</code>```

I tried:

```<code>#print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (*(er, numpy.array([l]))))
</code>```

But this last line generates "SyntaxError: invalid syntax" error.

Any ideas?

答:
You do't want to unpack anything because you want a tuple after %.

```<code>print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (tuple(er) + (1,)))
0.367 | 0.467 | 0.433 | nan | 1.0
</code>```

But you'd better use str.format. Unpacking makes sense here because you want to pass every array item as an argument to the function.

```<code>print('{:0.3f} | {:0.3f} | {:0.3f} | {:0.3f} | {:0.1f}'.format(*er, 1))
0.367 | 0.467 | 0.433 | nan | 1.0
</code>```

Title: Unpacking argument in print statements

Body:
I would like to know if there is a way to unpack values in a print statement, the same way it is possible to unpack arguments in a function f

This works:

import numpy
er = numpy.array([0.36666667, 0.46666667, 0.43333333, numpy.nan])
l = 0.8
print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (er[0], er[1], er[2], er[3], l))
# 0.367 | 0.467 | 0.433 | nan | 0.8

However, I would like to avoid multiple er[x] and instead use something like *er as in:

def f(a,b,c,d):
    return True
print(f(*er))
# True

I tried:

#print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (*(er, numpy.array([l]))))

But this last line generates "SyntaxError: invalid syntax" error.

Any ideas?

Body:
You do't want to unpack anything because you want a tuple after %.

print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (tuple(er) + (1,)))
0.367 | 0.467 | 0.433 | nan | 1.0

But you'd better use str.format. Unpacking makes sense here because you want to pass every array item as an argument to the function.

print('{:0.3f} | {:0.3f} | {:0.3f} | {:0.3f} | {:0.1f}'.format(*er, 1))
0.367 | 0.467 | 0.433 | nan | 1.0


问:
Kotlin generics and wrong type inference
Consider a general class Item and specific class Event which inherits it:

```<code>open class Item<T> {
    fun copyFrom(item: T) {
        if (this is Event && item is Event) {
            owner = item.owner
            value = item.value
        }
    }
}

class Event : Item<Event> {
    open var owner = ""
    open var value = 0
}
</code>```

Thanks to type inference we don't have to cast Item to Event and we can directly access the owner and value. However it says the item is of type T and cannot be cast to Event in the item is Event clause. I believe this should not happen as this clause is correct in Java?

EDIT:

I am aware of the fact that the copyFrom implementation should be done in Event, but this is just to demonstrate the type inference issue.

答:
Even when you sort out the syntactical problems: do not do this.

You are creating a generic container, which explicitly checks if a distinct subclass comes in. To then do a downcast and access fields in the subclass.

This is like the absolute opposite of a good OO design. You base class should know nothing about any subclass!

Body:
Consider a general class Item and specific class Event which inherits it:

open class Item<T> {
    fun copyFrom(item: T) {
        if (this is Event && item is Event) {
            owner = item.owner
            value = item.value
        }
    }
}

class Event : Item<Event> {
    open var owner = ""
    open var value = 0
}

Thanks to type inference we don't have to cast Item to Event and we can directly access the owner and value. However it says the item is of type T and cannot be cast to Event in the item is Event clause. I believe this should not happen as this clause is correct in Java?

EDIT:

I am aware of the fact that the copyFrom implementation should be done in Event, but this is just to demonstrate the type inference issue.


问:
using groupby attribute in pandas
I have a DataFrame with 3 columns (A,B,C) and a large number of rows. There are different types of elements in each of these columns: A1,A2... B1,B2... and C1, C2... respectively.

I want to find the number of times a particular combination (say (A1,B2,C2)) occurs in a row. Then I want to generate a (summary) list of all combinations whose frequency-counts exceed a fixed threshold. Example: combinations number of counts (A1,B2,C2) 5 (A2,B2,C2) 7 .... if the fixed value is 6.

I am new to pandas and numpy. Can this be done efficiently using pandas, and if so how?

答:
```<code>df = pd.DataFrame({'A':['A1','A1','A2','A3'],
                   'B':[4,4,6,4],
                   'C':[7,7,9,7]})

print (df)
    A   B  C
0   4   7  C1
1   4   7  C1
2   6   9  C2
3   4   7  C3
</code>```

For count of all combination use groupby + size:

```<code>s = df.groupby(["A", "B","C"]).size()
print (s)
A   B   C
A1  4   7     2
A2  6   9     1
A3  4   7     1
dtype: int64
</code>```

For filtered list by value add boolean indexing:

```<code>L = s.index[s > 1].tolist()
print (L)
[('A1', 4, 7)]
</code>```

Title: using groupby attribute in pandas

Body:
df = pd.DataFrame({'A':['A1','A1','A2','A3'],
                   'B':[4,4,6,4],
                   'C':[7,7,9,7]})

print (df)
    A   B  C
0   4   7  C1
1   4   7  C1
2   6   9  C2
3   4   7  C3

For count of all combination use groupby + size:

s = df.groupby(["A", "B","C"]).size()
print (s)
A   B   C
A1  4   7     2
A2  6   9     1
A3  4   7     1
dtype: int64

For filtered list by value add boolean indexing:

L = s.index[s > 1].tolist()
print (L)
[('A1', 4, 7)]


问:
BLE device re-connects after cancelPeripheralConnection (How to forget a BLE device?)
I have a BLE device that connects to an iOS device after it has been chosen through a fairly standard user interface (tap on the device entry shown in a UITableView).

The connection is simple enough- some internal processing followed by calling the CBCentralManager's connectPeripheral(peripheral: options:).

There is a requirement to 'forget' the device (so that the iPhone won't connect to it automatically again). I call the cancelPeripheralConnection(peripheral:), however the device still connects back to the phone automatically.

How can I stop the BLE device from automatically re-connecting after the cancelPeripheralConnection(peripheral:) method is called?

答:
There is no way to forget a device using code. You have to manually go to the settings and forget the device.

The system will automatically connect to a paired device when the bluetooth is turned on or if the device initiates a connection. Are you calling connect after the cancelPeripheralConnection call?


问:
Java generics name clash after type erasure
I am working through "Java Generics and Collections" book, and came across this piece of code, which is supposed to compile and run without errors

```<code>class Overloaded {
    public static Integer sum(List<Integer> ints) {
        int sum = 0;
        for (int i : ints) sum += i;
        return sum;
    }
    public static String sum(List<String> strings) {
        StringBuffer sum = new StringBuffer();
        for (String s : strings) sum.append(s);
        return sum.toString();
    }
}
</code>```

However, this example fails to compile with error

Error:(16, 26) java: name clash: sum(java.util.List)
  and sum(java.util.List) have the same erasure

I can understand why this is an error. However, the book specifically mentions that this is allowed, as compiler can distinguish the 2 methods based on return type.

I then found this thread
Type Erasure and Overloading in Java: Why does this work?

It also suggests that this example should compile. Any idea what's causing the compile to fail?

I am using JDK 1.8. Is this recently changed with Java 1.8? In case this is relevant, I am using latest IntelliJ IDEA as IDE.

答:
As we know, In the Runtime, Java will erasure generic type, so:

```<code>Integer sum(List<Integer> ints)
String sum(List<String> strings)
</code>```

will be translated to in Runtime:

```<code>Integer sum(List ints)
String sum(List strings)
</code>```

so this compiler error should be throwed.

It compiles without throwing error in JDK6 it's a bug. this bug has been fixed in JDK7, so compile with JDK8 will throw this compile error.

Reference:

Generic class compiles in Java 6, but not Java 7

Body:
I am working through "Java Generics and Collections" book, and came across this piece of code, which is supposed to compile and run without errors

class Overloaded {
    public static Integer sum(List<Integer> ints) {
        int sum = 0;
        for (int i : ints) sum += i;
        return sum;
    }
    public static String sum(List<String> strings) {
        StringBuffer sum = new StringBuffer();
        for (String s : strings) sum.append(s);
        return sum.toString();
    }
}

However, this example fails to compile with error

Error:(16, 26) java: name clash: sum(java.util.List)
  and sum(java.util.List) have the same erasure

I can understand why this is an error. However, the book specifically mentions that this is allowed, as compiler can distinguish the 2 methods based on return type.

I then found this thread
Type Erasure and Overloading in Java: Why does this work?

It also suggests that this example should compile. Any idea what's causing the compile to fail?

I am using JDK 1.8. Is this recently changed with Java 1.8? In case this is relevant, I am using latest IntelliJ IDEA as IDE.

Body:
As we know, In the Runtime, Java will erasure generic type, so:

Integer sum(List<Integer> ints)
String sum(List<String> strings)

will be translated to in Runtime:

Integer sum(List ints)
String sum(List strings)

so this compiler error should be throwed.

It compiles without throwing error in JDK6 it's a bug. this bug has been fixed in JDK7, so compile with JDK8 will throw this compile error.

Reference:

Generic class compiles in Java 6, but not Java 7


问:
XML in C++ Builder 6
How can I use XML as a simple data storage in Borland C++ Builder 6?

Is there an internal class, which I could use?

Thank's for help

答:
use NativeXML

```<code>xmlDoc = new TNativeXml("test");
xmlDoc->EncodingString = "GB2312" ;
xmlDoc->XmlFormat = xfReadable;
xmlNode = xmlDoc->Root->NodeNew("report") ;
xmlNode->WriteString("date","2008-6-8") ;
xmlNode->WriteString("road0","10") ;
xmlNode->WriteString("road1","8") ;
xmlNode = xmlDoc->Root->NodeNew("ctrParm") ;
xmlNode->WriteString("parm0","0") ;
xmlNode->WriteString("parm1","1") ;
xmlNode->WriteString("parm2","2") ;
xmlDoc->SaveToFile("test.xml") ;
delete xmlDoc ;
</code>```

Title: XML in C++ Builder 6

Body:
use NativeXML

xmlDoc = new TNativeXml("test");
xmlDoc->EncodingString = "GB2312" ;
xmlDoc->XmlFormat = xfReadable;
xmlNode = xmlDoc->Root->NodeNew("report") ;
xmlNode->WriteString("date","2008-6-8") ;
xmlNode->WriteString("road0","10") ;
xmlNode->WriteString("road1","8") ;
xmlNode = xmlDoc->Root->NodeNew("ctrParm") ;
xmlNode->WriteString("parm0","0") ;
xmlNode->WriteString("parm1","1") ;
xmlNode->WriteString("parm2","2") ;
xmlDoc->SaveToFile("test.xml") ;
delete xmlDoc ;


问:
sgen TypeLoadException in Visual Studio for Mac when trying to build Xamarin.iOS app
When compiling our app on MacOS in Visual Studio (version 7.0.1 build 24), I'm presented with the error:

```<code>/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(5,5): Error MSB6006: "sgen.exe" exited with code 1. (MSB6006) (SyncWebClientLight)
</code>```

If I start a build in Visual Studio 2015 Pro (with VS2015 connecting to the Mac and compiling it there), then I can debug etc. This would be great, except that I can't generate an archive for submission into the App Store from VS2015 (for whatever reason, the "Archive" menu option is greyed out)

Is there a way to disable sgen.exe in Visual Studio for Mac (some msbuild switch or something?) Might that help?

Update 1:

VS 2015 gives the following error:

```<code>Could not load file or assembly 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0x8013141A)   SyncWebClientLight  C:\projects\mWORKSPACE\trunk\Source\SyncWebClientLight\SGEN
</code>```

So that's a little more information, at least.

Update 2:

```<code>Target GenerateSerializationAssemblies:
    /Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.5/sgen.exe /assembly:/Users/mj/Documents/projects/mWORKSPACE/Source/SyncWebClientLight/obj/iPhoneSimulator/Release/SBW.SyncWebClientLight.dll /proxytypes /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/mscorlib.dll /reference:/Users/mj/Documents/projects/mWORKSPACE/Release/SBW.Sync.dll /reference:/Users/mj/Documents/projects/mWORKSPACE/Debug/SBW.SystemBase.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/System.Core.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/System.Data.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/System.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/System.Web.Services.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/System.Xml.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/Xamarin.iOS.dll

    Unhandled Exception:
    System.TypeLoadException: Could not load type of field 'SyncWebClientLight.ClientPackageController:_syncDef' (2) due to: Could not load file or assembly 'SBW.Sync, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. assembly:SBW.Sync, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null type:<unknown type> member:<none>
      at (wrapper managed-to-native) System.RuntimeType:GetConstructors_native (System.RuntimeType,System.Reflection.BindingFlags)
      at System.RuntimeType.GetConstructors_internal (System.Reflection.BindingFlags bindingAttr, System.RuntimeType reflectedType) [0x00008] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.RuntimeType.GetConstructorCandidates (System.String name, System.Reflection.BindingFlags bindingAttr, System.Reflection.CallingConventions callConv, System.Type[] types, System.Boolean allowPrefixLookup) [0x00034] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.RuntimeType.GetConstructorImpl (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) [0x00000] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.Type.GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) [0x00032] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.Xml.Serialization.TypeScope.GetConstructorFlags (System.Type type, System.Exception& exception) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.ImportTypeDesc (System.Type type, System.Reflection.MemberInfo memberInfo, System.Boolean directReference) [0x00444] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.GetTypeDesc (System.Type type, System.Reflection.MemberInfo source, System.Boolean directReference, System.Boolean throwOnError) [0x00050] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.GetTypeDesc (System.Type type, System.Reflection.MemberInfo source, System.Boolean directReference) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.ModelScope.GetTypeModel (System.Type type, System.Boolean directReference) [0x00017] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.ModelScope.GetTypeModel (System.Type type) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping (System.Type type, System.Xml.Serialization.XmlRootAttribute root, System.String defaultNamespace) [0x00014] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping (System.Type type) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at Driver.Run (System.String[] args) [0x00110] in <eeaf85d64a8c4c2eb792db70e13a9f1e>:0
      at Driver.Main (System.String[] args) [0x00005] in <eeaf85d64a8c4c2eb792db70e13a9f1e>:0
    [ERROR] FATAL UNHANDLED EXCEPTION: System.TypeLoadException: Could not load type of field 'SyncWebClientLight.ClientPackageController:_syncDef' (2) due to: Could not load file or assembly 'SBW.Sync, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. assembly:SBW.Sync, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null type:<unknown type> member:<none>
      at (wrapper managed-to-native) System.RuntimeType:GetConstructors_native (System.RuntimeType,System.Reflection.BindingFlags)
      at System.RuntimeType.GetConstructors_internal (System.Reflection.BindingFlags bindingAttr, System.RuntimeType reflectedType) [0x00008] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.RuntimeType.GetConstructorCandidates (System.String name, System.Reflection.BindingFlags bindingAttr, System.Reflection.CallingConventions callConv, System.Type[] types, System.Boolean allowPrefixLookup) [0x00034] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.RuntimeType.GetConstructorImpl (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) [0x00000] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.Type.GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) [0x00032] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.Xml.Serialization.TypeScope.GetConstructorFlags (System.Type type, System.Exception& exception) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.ImportTypeDesc (System.Type type, System.Reflection.MemberInfo memberInfo, System.Boolean directReference) [0x00444] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.GetTypeDesc (System.Type type, System.Reflection.MemberInfo source, System.Boolean directReference, System.Boolean throwOnError) [0x00050] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.GetTypeDesc (System.Type type, System.Reflection.MemberInfo source, System.Boolean directReference) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.ModelScope.GetTypeModel (System.Type type, System.Boolean directReference) [0x00017] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.ModelScope.GetTypeModel (System.Type type) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping (System.Type type, System.Xml.Serialization.XmlRootAttribute root, System.String defaultNamespace) [0x00014] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping (System.Type type) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at Driver.Run (System.String[] args) [0x00110] in <eeaf85d64a8c4c2eb792db70e13a9f1e>:0
      at Driver.Main (System.String[] args) [0x00005] in <eeaf85d64a8c4c2eb792db70e13a9f1e>:0
    /Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(3366,5): error MSB6006: "sgen.exe" exited with code 1.
Done building target "GenerateSerializationAssemblies" in project "SyncWebClientLight.csproj" -- FAILED.
</code>```

The Type is there though: I can drill down to its reference in VS4mac, the project SBW.Sync compiles fine, SyncWebClientLight is referencing the correct assembly.

It would be nice if I knew where it was loading the assembly from (is there a fuslogvw.exe in mono?)

答:
So, it seems that Visual Studio for Mac doesn't understand the csproj/msbuild flag:

```<code><GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</code>```

And sgen is the thing that won't let me get on with my work day. So let's replace sgen with our own version that does nothing!

sgen is located on my Mac at:

```<code>/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.5
</code>```

I made a simple .NET console app in VS4mac that does nothing, and copied it to that dir, replacing the original sgen.exe

I can now compile my assembly, resulting in a warm feeling of bliss marred only slightly by the worry that I've done something I probably shouldn't have.

If anyone knows how to fix this properly, I'd be much obliged.

Body:
When compiling our app on MacOS in Visual Studio (version 7.0.1 build 24), I'm presented with the error:

/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(5,5): Error MSB6006: "sgen.exe" exited with code 1. (MSB6006) (SyncWebClientLight)

If I start a build in Visual Studio 2015 Pro (with VS2015 connecting to the Mac and compiling it there), then I can debug etc. This would be great, except that I can't generate an archive for submission into the App Store from VS2015 (for whatever reason, the "Archive" menu option is greyed out)

Is there a way to disable sgen.exe in Visual Studio for Mac (some msbuild switch or something?) Might that help?

Update 1:

VS 2015 gives the following error:

Could not load file or assembly 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0x8013141A)   SyncWebClientLight  C:\projects\mWORKSPACE\trunk\Source\SyncWebClientLight\SGEN

So that's a little more information, at least.

Update 2:

Target GenerateSerializationAssemblies:
    /Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.5/sgen.exe /assembly:/Users/mj/Documents/projects/mWORKSPACE/Source/SyncWebClientLight/obj/iPhoneSimulator/Release/SBW.SyncWebClientLight.dll /proxytypes /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/mscorlib.dll /reference:/Users/mj/Documents/projects/mWORKSPACE/Release/SBW.Sync.dll /reference:/Users/mj/Documents/projects/mWORKSPACE/Debug/SBW.SystemBase.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/System.Core.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/System.Data.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/System.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/System.Web.Services.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/System.Xml.dll /reference:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/Xamarin.iOS.dll

    Unhandled Exception:
    System.TypeLoadException: Could not load type of field 'SyncWebClientLight.ClientPackageController:_syncDef' (2) due to: Could not load file or assembly 'SBW.Sync, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. assembly:SBW.Sync, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null type:<unknown type> member:<none>
      at (wrapper managed-to-native) System.RuntimeType:GetConstructors_native (System.RuntimeType,System.Reflection.BindingFlags)
      at System.RuntimeType.GetConstructors_internal (System.Reflection.BindingFlags bindingAttr, System.RuntimeType reflectedType) [0x00008] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.RuntimeType.GetConstructorCandidates (System.String name, System.Reflection.BindingFlags bindingAttr, System.Reflection.CallingConventions callConv, System.Type[] types, System.Boolean allowPrefixLookup) [0x00034] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.RuntimeType.GetConstructorImpl (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) [0x00000] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.Type.GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) [0x00032] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.Xml.Serialization.TypeScope.GetConstructorFlags (System.Type type, System.Exception& exception) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.ImportTypeDesc (System.Type type, System.Reflection.MemberInfo memberInfo, System.Boolean directReference) [0x00444] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.GetTypeDesc (System.Type type, System.Reflection.MemberInfo source, System.Boolean directReference, System.Boolean throwOnError) [0x00050] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.GetTypeDesc (System.Type type, System.Reflection.MemberInfo source, System.Boolean directReference) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.ModelScope.GetTypeModel (System.Type type, System.Boolean directReference) [0x00017] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.ModelScope.GetTypeModel (System.Type type) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping (System.Type type, System.Xml.Serialization.XmlRootAttribute root, System.String defaultNamespace) [0x00014] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping (System.Type type) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at Driver.Run (System.String[] args) [0x00110] in <eeaf85d64a8c4c2eb792db70e13a9f1e>:0
      at Driver.Main (System.String[] args) [0x00005] in <eeaf85d64a8c4c2eb792db70e13a9f1e>:0
    [ERROR] FATAL UNHANDLED EXCEPTION: System.TypeLoadException: Could not load type of field 'SyncWebClientLight.ClientPackageController:_syncDef' (2) due to: Could not load file or assembly 'SBW.Sync, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. assembly:SBW.Sync, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null type:<unknown type> member:<none>
      at (wrapper managed-to-native) System.RuntimeType:GetConstructors_native (System.RuntimeType,System.Reflection.BindingFlags)
      at System.RuntimeType.GetConstructors_internal (System.Reflection.BindingFlags bindingAttr, System.RuntimeType reflectedType) [0x00008] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.RuntimeType.GetConstructorCandidates (System.String name, System.Reflection.BindingFlags bindingAttr, System.Reflection.CallingConventions callConv, System.Type[] types, System.Boolean allowPrefixLookup) [0x00034] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.RuntimeType.GetConstructorImpl (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) [0x00000] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.Type.GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) [0x00032] in <ffb99659fc1c47faa4d5f883014d08aa>:0
      at System.Xml.Serialization.TypeScope.GetConstructorFlags (System.Type type, System.Exception& exception) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.ImportTypeDesc (System.Type type, System.Reflection.MemberInfo memberInfo, System.Boolean directReference) [0x00444] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.GetTypeDesc (System.Type type, System.Reflection.MemberInfo source, System.Boolean directReference, System.Boolean throwOnError) [0x00050] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.TypeScope.GetTypeDesc (System.Type type, System.Reflection.MemberInfo source, System.Boolean directReference) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.ModelScope.GetTypeModel (System.Type type, System.Boolean directReference) [0x00017] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.ModelScope.GetTypeModel (System.Type type) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping (System.Type type, System.Xml.Serialization.XmlRootAttribute root, System.String defaultNamespace) [0x00014] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping (System.Type type) [0x00000] in <3a4ce9be61fd46ab845a4d68f2905e06>:0
      at Driver.Run (System.String[] args) [0x00110] in <eeaf85d64a8c4c2eb792db70e13a9f1e>:0
      at Driver.Main (System.String[] args) [0x00005] in <eeaf85d64a8c4c2eb792db70e13a9f1e>:0
    /Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(3366,5): error MSB6006: "sgen.exe" exited with code 1.
Done building target "GenerateSerializationAssemblies" in project "SyncWebClientLight.csproj" -- FAILED.

The Type is there though: I can drill down to its reference in VS4mac, the project SBW.Sync compiles fine, SyncWebClientLight is referencing the correct assembly.

It would be nice if I knew where it was loading the assembly from (is there a fuslogvw.exe in mono?)

Body:
So, it seems that Visual Studio for Mac doesn't understand the csproj/msbuild flag:

<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>

And sgen is the thing that won't let me get on with my work day. So let's replace sgen with our own version that does nothing!

sgen is located on my Mac at:

/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/4.5

I made a simple .NET console app in VS4mac that does nothing, and copied it to that dir, replacing the original sgen.exe

I can now compile my assembly, resulting in a warm feeling of bliss marred only slightly by the worry that I've done something I probably shouldn't have.

If anyone knows how to fix this properly, I'd be much obliged.


答:
You only need to post id and number in following format:

```<code> {
     "id": "13456454",
     "number": "222",
 }
</code>```

This will wok for you.

Title: C# WebApi Json Posting

Body:
I have below C# code for WEB API When I post below JSON the Account object is always null. Please, anyone can guide on below code.

public class Account
{
    public string id { get; set; }
    public string number { get; set; }
}

public object Post([FromBody] Account account)
{
    Message msg = new Message();
    msg.status = "Status";
    return Request.CreateResponse(msg);
}

JSON

{
  "Accounts": {
    "id": "13456454",
    "number": "222",
  }
}

Body:
You only need to post id and number in following format:

 {
     "id": "13456454",
     "number": "222",
 }

This will wok for you.


问:
div grid tab not in content
I use a php function to put my page content in the index.php, but when I use a grid (tab) in the content it goes out of the content borders.

I put a little bit of the code underneath, you can see the site here: (link deleted > problem solved)

答:
You put your .clearfix  in the beginning of the .content .

If you place it after the tabs, the border will display correctly.

Title: div grid tab not in content


问:
NavigationDrawer height collapses to that of the Toolbar after onPause on some devices
I have a fairly simple application that has a custom Toolbar with a NavigationDrawer. Apart from these items I have a GLSurfaceView that fills the entire screen. In my NavigationDrawer I have a list of cases that can be selected and then data is fetched and rendered in the GLSurfaceView.

Everything is working fine, except one thing: When the application is paused and then resumed, the height of the NavigationView collapses to that of the Toolbar. The NavigationView can still be scrolled in that small height and when a case is selected at that point, the NavigationView's height is refreshed and everything goes back to normal. This therefore also happens on rotation of the device.

Note that if the NavigationView is visible when rotating/pausing the app, the issue does not occur.

This issue does not happen on all devices though. Here is a list I have tested on:

Issue appears on:

Samsung Galaxy S2 Tab: Android 6.0.1

Samsung Galaxy S7 Edge: Android 6.0.1

HTC One A9s: Android 6.0

Samsung Galaxy Note 10.1: Android 5.11

The issue does not appear on:

Sony Xperia XZ: Android 6.0.1

Huawei Honor 7: Android 5.0.2

Huawei Nexus P6: Android 7.0

I have tried invalidating all the views in onPause, but nothing helps and I cannot figure out where I am doing something wrong.

Other notes:

compileSdkVersion = 25

targetSdkVersion = 25

Support library version: 25.2.0

Build tools version: 25.0.2

Gradle plugin version: 2.3.0 / Android Studio 2.3

styles.xml

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

    <!-- This style is set in AndroidManifest.xml -->
    <style name="DemoTheme" parent="Theme.AppCompat.Light.DarkActionBar">

        <!-- To be able to use a custom Toolbar. -->
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>

        <item name="colorPrimary">@color/demo_color_main_brand</item>
        <item name="colorPrimaryDark">@color/demo_color_extras_darkblue</item>
        <item name="colorAccent">@color/demo_color_extras_lightgreen</item>

    </style>

    <style name="DemoActionBarStyle" parent="@style/Widget.AppCompat.ActionBar">
        <item name="android:theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
        <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:background">@color/demo_color_main_brand</item>
        <item name="android:minHeight">?attr/actionBarSize</item>
    </style>

   ...

</resources>
</code>```

activity_demo.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/demo_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Wrap Toolbar in AppBarLayout to add shadow below the Toolbar. -->
        <android.support.design.widget.AppBarLayout
            android:id="@+id/demo_appbarlayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <android.support.v7.widget.Toolbar
                android:id="@+id/demo_toolbar"
                style="@style/DemoActionBarStyle" />

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

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/demo_appbarlayout" >

            <android.support.design.widget.CoordinatorLayout
                android:id="@+id/fv_coordinatorlayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".activities.DemoActivity" >

                <com.my.company.demo.views.DemoGLSurfaceView
                    android:id="@+id/demo_glsurfaceview"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:visibility="visible" />

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

        </FrameLayout>

    </RelativeLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/demo_navigationview"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/demo_navigationview_header"
        app:menu="@menu/demo_navigationview_menu"
        app:itemIconTint="@drawable/demo_colors_navigationview"
        app:itemTextColor="@drawable/demo_colors_navigationview" />

</android.support.v4.widget.DrawerLayout>
</code>```

onCreate in DemoActivity:

```<code>@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_demo);

    // Setup Toolbar.
    Toolbar toolbar = (Toolbar) findViewById(R.id.demo_toolbar);
    setSupportActionBar(toolbar);

    // Setup NavigationView.
    NavigationView navigationView = (NavigationView) findViewById(R.id.demo_navigationview);
    navigationView.setNavigationItemSelectedListener(this);

    // Setup DrawerLayout.
    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.demo_drawer_layout);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
            this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
    drawerLayout.addDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();

    // Load demo cases.
    mModuleConfiguration = new ModuleConfiguration(getString(R.string.module_config_url), this);
}
</code>```

Before rotation:

After rotation:

答:
I found a similar issue that helped med fix my problem here. The gist of it is to implement an extra DrawerLayout.DrawerListener in the Activity and do

```<code>@Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
    mDrawerLayout.bringChildToFront(drawerView);
    mDrawerLayout.requestLayout();
}
</code>```

to ensure that the drawer is drawn above the GLSurfaceView.

Steps to fix:

Implement DrawerLayout.DrawerListener in the Activity.

Add both an ActionBarDrawerToggle and the Activity as listeners for the DrawerLayout.

Implement the above onDrawerSlide() method from the DrawerLayout.DrawerListener interface (mDrawerLayout is simply a local reference to the DrawerLayout).

Body:
I have a fairly simple application that has a custom Toolbar with a NavigationDrawer. Apart from these items I have a GLSurfaceView that fills the entire screen. In my NavigationDrawer I have a list of cases that can be selected and then data is fetched and rendered in the GLSurfaceView.

Everything is working fine, except one thing: When the application is paused and then resumed, the height of the NavigationView collapses to that of the Toolbar. The NavigationView can still be scrolled in that small height and when a case is selected at that point, the NavigationView's height is refreshed and everything goes back to normal. This therefore also happens on rotation of the device.

Note that if the NavigationView is visible when rotating/pausing the app, the issue does not occur.

This issue does not happen on all devices though. Here is a list I have tested on:

Issue appears on:

Samsung Galaxy S2 Tab: Android 6.0.1

Samsung Galaxy S7 Edge: Android 6.0.1

HTC One A9s: Android 6.0

Samsung Galaxy Note 10.1: Android 5.11

The issue does not appear on:

Sony Xperia XZ: Android 6.0.1

Huawei Honor 7: Android 5.0.2

Huawei Nexus P6: Android 7.0

I have tried invalidating all the views in onPause, but nothing helps and I cannot figure out where I am doing something wrong.

Other notes:

compileSdkVersion = 25

targetSdkVersion = 25

Support library version: 25.2.0

Build tools version: 25.0.2

Gradle plugin version: 2.3.0 / Android Studio 2.3

styles.xml

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

   ...

</resources>

activity_demo.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/demo_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/demo_appbarlayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <android.support.v7.widget.Toolbar
                android:id="@+id/demo_toolbar"
                style="@style/DemoActionBarStyle" />

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

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/demo_appbarlayout" >

            <android.support.design.widget.CoordinatorLayout
                android:id="@+id/fv_coordinatorlayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".activities.DemoActivity" >

                <com.my.company.demo.views.DemoGLSurfaceView
                    android:id="@+id/demo_glsurfaceview"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:visibility="visible" />

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

        </FrameLayout>

    </RelativeLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/demo_navigationview"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/demo_navigationview_header"
        app:menu="@menu/demo_navigationview_menu"
        app:itemIconTint="@drawable/demo_colors_navigationview"
        app:itemTextColor="@drawable/demo_colors_navigationview" />

</android.support.v4.widget.DrawerLayout>

onCreate in DemoActivity:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_demo);

    // Setup Toolbar.
    Toolbar toolbar = (Toolbar) findViewById(R.id.demo_toolbar);
    setSupportActionBar(toolbar);

    // Setup NavigationView.
    NavigationView navigationView = (NavigationView) findViewById(R.id.demo_navigationview);
    navigationView.setNavigationItemSelectedListener(this);

    // Setup DrawerLayout.
    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.demo_drawer_layout);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
            this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
    drawerLayout.addDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();

    // Load demo cases.
    mModuleConfiguration = new ModuleConfiguration(getString(R.string.module_config_url), this);
}

Before rotation:

After rotation:

Body:
I found a similar issue that helped med fix my problem here. The gist of it is to implement an extra DrawerLayout.DrawerListener in the Activity and do

@Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
    mDrawerLayout.bringChildToFront(drawerView);
    mDrawerLayout.requestLayout();
}

to ensure that the drawer is drawn above the GLSurfaceView.

Steps to fix:

Implement DrawerLayout.DrawerListener in the Activity.

Add both an ActionBarDrawerToggle and the Activity as listeners for the DrawerLayout.

Implement the above onDrawerSlide() method from the DrawerLayout.DrawerListener interface (mDrawerLayout is simply a local reference to the DrawerLayout).


问:
Continously getting WhiteLabel Error Page - Spring boot
Hey i have a problem with viewing a jsp file in a simple spring boot app.

Here are my project files:

pom.xml

```<code> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<groupId>com.sample</groupId>
<artifactId>boot-sample</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.5.3.RELEASE</version>
        </plugin>
    </plugins>
</build>
</code>```

HomeController.java

```<code>package com.sample;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {

    @RequestMapping("/home")
    public String home(){
        return "home";
    }
}
</code>```

home.jsp

```<code><%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<html lang="en">

<head>
    <h1>Title</h1>
</head>

<body>
    <h2>text</h2>
</body>

</html>
</code>```

application.properties

```<code>spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
</code>```

file structure

I figured out that it may be something with file structure or prefix path in application.properties, still haven't found an answer though.

答:
From Spring boot Documentation:

JSPs should be avoided if possible, there are several known
  limitations when using them with embedded servlet containers.

You can take further reading here:

http://docs.spring.io/spring-boot/docs/1.5.3.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-template-engines

Body:
Hey i have a problem with viewing a jsp file in a simple spring boot app.

Here are my project files:

pom.xml

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<groupId>com.sample</groupId>
<artifactId>boot-sample</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.5.3.RELEASE</version>
        </plugin>
    </plugins>
</build>

HomeController.java

package com.sample;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {

    @RequestMapping("/home")
    public String home(){
        return "home";
    }
}

home.jsp

<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>

Title

text

application.properties

spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

file structure

I figured out that it may be something with file structure or prefix path in application.properties, still haven't found an answer though.


问:
RestAssured Response is overriden
I am trying to Get multiple URI's using RestAPI programming.
All the GET Requests need Basic Authorization

I have used a BaseClass where I define RequestSpecification as shown below (To avoid Authorization code every time a Test is Run)

BaseClass.java :

```<code> RequestSpecification basicAuth=RestAssured.given().accept("text/html").auth().preemptive().basic("username","password");
</code>```

Inherited above Class and used "basicAuth" parameter in the class with my Test methods.

```<code>  public class Tests extends BaseClass
    {
        @Test(priority=1)
        public void test01() throws IOException
        {
           response=basicAuth.when().get("URL1");
           Assert.assertEquals(200,response.getStatusCode());
        }

          @Test(priority=2)
            public void test02() throws IOException
            {
             response=basicAuth.when().get("URL2");
               Assert.assertEquals(200,response.getStatusCode());
          }}
</code>```

Problem here is both the tests return same Response (test01's response) though the URI's are different .
Running  test02 alone skipping test01 gives Expected Response.

Workaround is to define two RequestSpecification parameters and Send requests.
Is there a way where I can clear previous GET Response and send Request again using basicAuth parameter.

答:
You need to break your call into 2 calls:
1. Add a beforeMethod() function call in which you should call your auth function which is in BaseClass.java and this should return you an object(client) which later you can use in your test class.
2. In each test class, use the client object and make a call to a specific URL. Since each time a before method will be called there is a new client object will be created.
So, ideally your second call will make a call using the auth client and passing the URL object as a parameter.  </p>

Title: RestAssured Response is overriden

Body:
I am trying to Get multiple URI's using RestAPI programming.
All the GET Requests need Basic Authorization

I have used a BaseClass where I define RequestSpecification as shown below (To avoid Authorization code every time a Test is Run)

BaseClass.java :

 RequestSpecification basicAuth=RestAssured.given().accept("text/html").auth().preemptive().basic("username","password");

Inherited above Class and used "basicAuth" parameter in the class with my Test methods.

  public class Tests extends BaseClass
    {
        @Test(priority=1)
        public void test01() throws IOException
        {
           response=basicAuth.when().get("URL1");
           Assert.assertEquals(200,response.getStatusCode());
        }

          @Test(priority=2)
            public void test02() throws IOException
            {
             response=basicAuth.when().get("URL2");
               Assert.assertEquals(200,response.getStatusCode());
          }}

Problem here is both the tests return same Response (test01's response) though the URI's are different .
Running  test02 alone skipping test01 gives Expected Response.

Workaround is to define two RequestSpecification parameters and Send requests.
Is there a way where I can clear previous GET Response and send Request again using basicAuth parameter.