问:
When using JQuery replaceWith() function, events won't work afterward?
I have a button within some html that calls an ajax request which then replaces the aforementioned html and button with the .replaceWith() JQuery function.  After this 'replacing' happens the button will no longer work.  The event code is completely separate from the html, so I don't see why it won't still enact the event as many times as I need.

Here is the JQuery code:

```<code>$(document).ready(function () {
    $("button.hit").click(function (e) {
        e.preventDefault();
        var thisPlayer = this.id;
        $.post('/home/GetHitHold/', { action: "hit", playerName: this.id },
            function (returnedData) {
                $('div[id~="' + thisPlayer + '"]').replaceWith(returnedData);
            }).fail(function () {
                addTableRow("error");
            });
    });
});
</code>```

Here's the html that is returned from the ajax request which is what is doing the replacing.

```<code><div id="@Model.PlayerName" class="col-md-3" style="display: inline-block; margin: 10px 0px 10px 0px;">
    <div class="card border-warning" style="background-color:#1C5619">
        <div class="card-block">
            <h4 class="card-title text-center text-warning">Player: @Model.PlayerName</h4>
            <h1 class="card-text text-center text-lg-center text-warning">@Model.DisplayHand()</h1>
            <div>
                <button id="@Model.PlayerName" class="hit greenButtons btn btn-warning">Hit</button>
                <button id="@Model.PlayerName" class="hold greenButtons btn btn-warning">Hold</button>
            </div>
            <p class="card-text text-right">
                <small class="text-warning text-center text-warning" style="margin: 10px;">Hand Value: @Model.ParticipantsHighestHand()</small>
            </p>
        </div>
    </div>
</div>
</code>```

So my goal is to be able to replace the html and still have a working 'click' event for the button within that replaced html.

(I'm doing this within ASP.NET Core MVC, though that shouldn't matter)

答:
As I was writing this I found one that worked by a fluke chance.  In the following link at the bottom by the commenter "davids":

Event not get triggered after replacing with JQuery replaceWith()?

He states the following:

Try binding the event like this:

```<code>> $(document).on('click', '#search-main a', function(ev){
>     // your code });
</code>```

Body:
I have a button within some html that calls an ajax request which then replaces the aforementioned html and button with the .replaceWith() JQuery function.  After this 'replacing' happens the button will no longer work.  The event code is completely separate from the html, so I don't see why it won't still enact the event as many times as I need.

Here is the JQuery code:

$(document).ready(function () {
    $("button.hit").click(function (e) {
        e.preventDefault();
        var thisPlayer = this.id;
        $.post('/home/GetHitHold/', { action: "hit", playerName: this.id },
            function (returnedData) {
                $('div[id~="' + thisPlayer + '"]').replaceWith(returnedData);
            }).fail(function () {
                addTableRow("error");
            });
    });
});

Here's the html that is returned from the ajax request which is what is doing the replacing.

Player: @Model.PlayerName

@Model.DisplayHand()

                <button id="@Model.PlayerName" class="hit greenButtons btn btn-warning">Hit</button>
                <button id="@Model.PlayerName" class="hold greenButtons btn btn-warning">Hold</button>

                Hand Value: @Model.ParticipantsHighestHand()

So my goal is to be able to replace the html and still have a working 'click' event for the button within that replaced html.

(I'm doing this within ASP.NET Core MVC, though that shouldn't matter)

Body:
As I was writing this I found one that worked by a fluke chance.  In the following link at the bottom by the commenter "davids":

Event not get triggered after replacing with JQuery replaceWith()?

He states the following:

Try binding the event like this:

> $(document).on('click', '#search-main a', function(ev){
>     // your code });


来源: stackexchange

问:
index out of bound when iterrow() how is this possible?
I got error message:

```<code>5205
(5219, 25)
5221
(5219, 25)
Traceback (most recent call last):
  File "/Users/Chu/Documents/dssg2018/sa4.py", line 44, in <module>
    df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\
IndexError: index 5221 is out of bounds for axis 0 with size 5219
</code>```

when I'm traversing the data frame, the index comes from the iterators. I don't know how is this even possible? idx directly comes from the dataframe

```<code>bt = BallTree(df[['lat','lng']], metric="haversine")
indices = bt.query_radius(df[['lat','lng']],r=(float(10)/40000)*360)

for idx,row in df.iterrows():
    for word in bag_of_words:
        if word in row['caption']:
            print(idx)
            print(df.shape)
            df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\
                             np.max([1,len(df.iloc[indices[idx]][df[word]!=1])])
</code>```

changing iloc to loc gives

```<code>/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/Chu/Documents/dssg2018/sa4.py
(-124.60334244261675, 49.36453144316216, -121.67106179949566, 50.863501888419826)
27
(5219, 25)
/Users/Chu/Documents/dssg2018/sa4.py:42: FutureWarning:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike
  df.loc[idx,word]=len(df.loc[indices[idx]][df[word]==1])/\
/Users/Chu/Documents/dssg2018/sa4.py:42: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
  df.loc[idx,word]=len(df.loc[indices[idx]][df[word]==1])/\
Traceback (most recent call last):
  File "/Users/Chu/Documents/dssg2018/sa4.py", line 42, in <module>
    df.loc[idx,word]=len(df.loc[indices[idx]][df[word]==1])/\
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2133, in __getitem__
    return self._getitem_array(key)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2173, in _getitem_array
    key = check_bool_indexer(self.index, key)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/indexing.py", line 2023, in check_bool_indexer
    raise IndexingError('Unalignable boolean Series provided as '
pandas.core.indexing.IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match
</code>```

答:
Your index is not from 0 to len(df)-1, this will making df.iloc[idx]out of boundary

For example

```<code>df = pd.DataFrame({'a': [0, 1]},index=[1,100])

for idx,row in df.iterrows():
    print(idx)
    print(row)

1
a    0
Name: 1, dtype: int64
100
a    1
Name: 100, dtype: int64
</code>```

Then when you do

```<code>df.iloc[100]
</code>```

IndexError: single positional indexer is out-of-bounds

But when you do .loc you get the expected output.

```<code>df.loc[100]
Out[23]:
a    1
Name: 100, dtype: int64
</code>```

From the file :

.iloc :iloc[] is primarily integer position based

.loc:.loc[] is primarily label based

Solution:

Using .loc  or df=df.reset_index(drop=True)

ContentLicense: CC BY-SA 3.0

Body:
I got error message:

5205
(5219, 25)
5221
(5219, 25)
Traceback (most recent call last):
  File "/Users/Chu/Documents/dssg2018/sa4.py", line 44, in <module>
    df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\
IndexError: index 5221 is out of bounds for axis 0 with size 5219

when I'm traversing the data frame, the index comes from the iterators. I don't know how is this even possible? idx directly comes from the dataframe

bt = BallTree(df[['lat','lng']], metric="haversine")
indices = bt.query_radius(df[['lat','lng']],r=(float(10)/40000)*360)

for idx,row in df.iterrows():
    for word in bag_of_words:
        if word in row['caption']:
            print(idx)
            print(df.shape)
            df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\
                             np.max([1,len(df.iloc[indices[idx]][df[word]!=1])])

changing iloc to loc gives

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/Chu/Documents/dssg2018/sa4.py
(-124.60334244261675, 49.36453144316216, -121.67106179949566, 50.863501888419826)
27
(5219, 25)
/Users/Chu/Documents/dssg2018/sa4.py:42: FutureWarning:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike
  df.loc[idx,word]=len(df.loc[indices[idx]][df[word]==1])/\
/Users/Chu/Documents/dssg2018/sa4.py:42: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
  df.loc[idx,word]=len(df.loc[indices[idx]][df[word]==1])/\
Traceback (most recent call last):
  File "/Users/Chu/Documents/dssg2018/sa4.py", line 42, in <module>
    df.loc[idx,word]=len(df.loc[indices[idx]][df[word]==1])/\
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2133, in __getitem__
    return self._getitem_array(key)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2173, in _getitem_array
    key = check_bool_indexer(self.index, key)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/indexing.py", line 2023, in check_bool_indexer
    raise IndexingError('Unalignable boolean Series provided as '
pandas.core.indexing.IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match

Body:
Your index is not from 0 to len(df)-1, this will making df.iloc[idx]out of boundary

For example

df = pd.DataFrame({'a': [0, 1]},index=[1,100])

for idx,row in df.iterrows():
    print(idx)
    print(row)

1
a    0
Name: 1, dtype: int64
100
a    1
Name: 100, dtype: int64

Then when you do

df.iloc[100]

IndexError: single positional indexer is out-of-bounds

But when you do .loc you get the expected output.

df.loc[100]
Out[23]:
a    1
Name: 100, dtype: int64

From the file :

.iloc :iloc[] is primarily integer position based

.loc:.loc[] is primarily label based

Solution:

Using .loc  or df=df.reset_index(drop=True)


问:
notification channel min API level vs. target API level
In my app i have set min API level to 19 and target level to 26 (Oreo). Now, when I try to create a notification without a notification channel, it does not work because a notification channel is required when target API level is 26. But when I try to create the notification channel the IDE complains that creating a notification channel requires min API level 26.

How should I go about this? I would not want the set the minimum level to 26.

答:
You don't have to set the minimum API level to 26. You can check the API level at runtime to conditionally call createNotificationChannel when the API level is equal to or greater than Android 8.0 (API level 26)

```<code>if (Build.VERSION.SDK_INT >= 26) {
    NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,
        CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
    notificationManager.createNotificationChannel(notificationChannel);
    notification = new Notification.Builder(this, CHANNEL_ID)
        .setContentTitle("title...")
        .setContentText("message...")
        .setSmallIcon(R.drawable.ic_notification)
        .setContentIntent(pendingIntent)
        .build();
}
</code>```

Body:
You don't have to set the minimum API level to 26. You can check the API level at runtime to conditionally call createNotificationChannel when the API level is equal to or greater than Android 8.0 (API level 26)

if (Build.VERSION.SDK_INT >= 26) {
    NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,
        CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
    notificationManager.createNotificationChannel(notificationChannel);
    notification = new Notification.Builder(this, CHANNEL_ID)
        .setContentTitle("title...")
        .setContentText("message...")
        .setSmallIcon(R.drawable.ic_notification)
        .setContentIntent(pendingIntent)
        .build();
}


问:
Select intent not triggered if selection is not immediately followed by carousel
I am facing a problem with listening to User Selection when we show a carousel. We are using askWithCarousel with dialogFlow and listening to click of a carousel item using actions_intent_option event. When a carousel is displayed to user, assistant starts listening to user input using mic, if mic gets a random input from user (which doesn’t match any of our synonyms for the carousel items) and then the user taps on any carousel item or says any of the synonyms, actions_intent_option event is not getting fired. It works fine if this interaction is immediately followed by showing of carousel. Else, it will take carousel title as user input and resolves to a different intent.

Not able to get the id of the carousel item because of this. Is there a way to disable mic or emit actions_intent_option even when the user clicks on carousel item later. Please help with this flow.

答:
Selection events are only emitted, as you've discovered, right after the carousel or list has been sent to the user.

I'd recommend setting up a fallback intent to check for the titles of the list items or prompting the user with a carousel or list again.


问:
values missing while inserting geojson values to postgres table
I am trying to read a geojson file and insert the records into a postgres table - using the below python code.

```<code>import json
import psycopg2
conn = psycopg2.connect(host="<<ip_address>>",database="DB1", user="<<id>>", password="pwd")
cur = conn.cursor()
with open('NTA_shape.json') as f:
Geojson_data = json.load(f)
for feature in Geojson_data['features']:
    type_val=feature['geometry']['type']
    geom=feature['geometry']['coordinates']
    ntaname=feature['properties']['NTAName']
    boroname=feature['properties']['BoroName']
    data = {"type":type_val,"coordinates":geom}
    sql ="""Insert into <<Table_NAME> (geom,ntaname,boroname) VALUES(ST_GeomFromGeoJSON(%s),%s,%s)"""
    nta_boro=(json.dumps(data),ntaname,boroname)
    cur.execute(sql,nta_boro)
    conn.commit()
conn.close()
</code>```

But when I query the table, lot of records are missing.
If I print the json.dumps(data) variable - its showing all records.

I am not sure, what am i missing during table insert
Kindly help.

答:
I was able to fix with below change</p>

```<code>nta_boro=(json.dumps(data,),ntaname,boroname)
</code>```

Body:
I am trying to read a geojson file and insert the records into a postgres table - using the below python code.

import json
import psycopg2
conn = psycopg2.connect(host="<<ip_address>>",database="DB1", user="<<id>>", password="pwd")
cur = conn.cursor()
with open('NTA_shape.json') as f:
Geojson_data = json.load(f)
for feature in Geojson_data['features']:
    type_val=feature['geometry']['type']
    geom=feature['geometry']['coordinates']
    ntaname=feature['properties']['NTAName']
    boroname=feature['properties']['BoroName']
    data = {"type":type_val,"coordinates":geom}
    sql ="""Insert into <<Table_NAME> (geom,ntaname,boroname) VALUES(ST_GeomFromGeoJSON(%s),%s,%s)"""
    nta_boro=(json.dumps(data),ntaname,boroname)
    cur.execute(sql,nta_boro)
    conn.commit()
conn.close()

But when I query the table, lot of records are missing.
If I print the json.dumps(data) variable - its showing all records.

I am not sure, what am i missing during table insert
Kindly help.

Body:
I was able to fix with below change

nta_boro=(json.dumps(data,),ntaname,boroname)


问:
AddClass to match statements
I am trying to allocate tbody into 1 of 2 different class. I can't seem to get the if statement running, perhaps I have not used the syntax correctly?

condition 1: If tbody id = today (yyyymm), then add class "current"

condition 2: If tbody id < today (yyyymm), then add class "past"

condition 3: If tbody id > today (yyyymm), then add do nothing

$(function(){
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + (month<10 ? '0' : '') + month;
var checktbody = $('tbody').attr('id');
//alert(output);

if(checktbody == output) {
$(this).addclass("current");
}

//$("table#ttrate").find("tbody".attr("id") == output).addclass("current");

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table#ttx{margin-left:40px; border-collapse:collapse;}
#ttx th {padding-top: 18px; text-align:left;}
#ttx td {padding-left: 18px;}
#ttx tbody.current {background-color: #FFFF99;}
#ttx tbody.past {color: #B8B8B8;}</code>```

Jan-2018

Buy	23,000

Sell	10,250

Dec-2017

Buy	20,000

Sell	12,500

Nov-2017

Buy	10,000

Sell	8,750

```

答:
First off, grab each tbody on the page and loop through each one using $.each:

```<code>$.each( $("tbody"), function(index, el) { ... });
</code>```

In order to achieve the 3 conditions that you stated, we have to rethink how the application is currently coded. Right now, you are comparing strings to see whether the element's date is current or past.

A better way of doing this would be to use Date objects to facilitate date comparisons.

See the code below. We use regular expressions to extract year and month from the id of each tbody and we use that to create a Date object, which we then compare to today's Date object:

$(function(){

  var now = new Date(); // today's date
  var nowYear = now.getFullYear();
  var nowMonth = now.getMonth();

  var today = new Date(nowYear, nowMonth);
  var todayTime = today.getTime(); // get today in milliseconds so we can run comparisons

  $.each( $("tbody"), function(index, el) {

    var $el = $(el);
    var id = $el.attr('id');

    // Get year, month, day using regex
    var rxArr = id.match(/(\d{4})(\d{2})/);
    var year = rxArr[1];
    var month = parseInt(rxArr[2]) - 1; // we need month - 1 to pass to Date object

    var elDate = new Date(year, month);
    var elDateTime = elDate.getTime(); // returns milliseconds so we run comparisons

    if(elDateTime === todayTime) {
      $el.addClass("current");
    } else if(elDateTime < todayTime) {
      $el.addClass("past");
    }

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table#ttx{margin-left:40px; border-collapse:collapse;}
#ttx th {padding-top: 18px; text-align:left;}
#ttx td {padding-left: 18px;}
#ttx tbody.current {background-color: #FFFF99;}
#ttx tbody.past {color: #B8B8B8;}</code>```

Jan-2018

Buy	23,000

Sell	10,250

Dec-2017

Buy	20,000

Sell	12,500

Nov-2017

Buy	10,000

Sell	8,750

```

Title: AddClass to match statements

Body:
I am trying to allocate tbody into 1 of 2 different class. I can't seem to get the if statement running, perhaps I have not used the syntax correctly?

condition 1: If tbody id = today (yyyymm), then add class "current"

condition 2: If tbody id < today (yyyymm), then add class "past"

condition 3: If tbody id > today (yyyymm), then add do nothing

$(function(){
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + (month<10 ? '0' : '') + month;
var checktbody = $('tbody').attr('id');
//alert(output);

if(checktbody == output) {
$(this).addclass("current");
}

//$("table#ttrate").find("tbody".attr("id") == output).addclass("current");

});

table#ttx{margin-left:40px; border-collapse:collapse;}
#ttx th {padding-top: 18px; text-align:left;}
#ttx td {padding-left: 18px;}
#ttx tbody.current {background-color: #FFFF99;}
#ttx tbody.past {color: #B8B8B8;}

Jan-2018

Buy	23,000

Sell	10,250

Dec-2017

Buy	20,000

Sell	12,500

Nov-2017

Buy	10,000

Sell	8,750

Body:
First off, grab each tbody on the page and loop through each one using $.each:

$.each( $("tbody"), function(index, el) { ... });

In order to achieve the 3 conditions that you stated, we have to rethink how the application is currently coded. Right now, you are comparing strings to see whether the element's date is current or past.

A better way of doing this would be to use Date objects to facilitate date comparisons.

See the code below. We use regular expressions to extract year and month from the id of each tbody and we use that to create a Date object, which we then compare to today's Date object:

$(function(){

  var now = new Date(); // today's date
  var nowYear = now.getFullYear();
  var nowMonth = now.getMonth();

  var today = new Date(nowYear, nowMonth);
  var todayTime = today.getTime(); // get today in milliseconds so we can run comparisons

  $.each( $("tbody"), function(index, el) {

    var $el = $(el);
    var id = $el.attr('id');

    // Get year, month, day using regex
    var rxArr = id.match(/(\d{4})(\d{2})/);
    var year = rxArr[1];
    var month = parseInt(rxArr[2]) - 1; // we need month - 1 to pass to Date object

    var elDate = new Date(year, month);
    var elDateTime = elDate.getTime(); // returns milliseconds so we run comparisons

    if(elDateTime === todayTime) {
      $el.addClass("current");
    } else if(elDateTime < todayTime) {
      $el.addClass("past");
    }

  });
});

table#ttx{margin-left:40px; border-collapse:collapse;}
#ttx th {padding-top: 18px; text-align:left;}
#ttx td {padding-left: 18px;}
#ttx tbody.current {background-color: #FFFF99;}
#ttx tbody.past {color: #B8B8B8;}

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<table id="ttx">
  <tbody id="201801">
  <tr><th colspan="2">Jan-2018</th></tr>
  <tr><td>Buy</td><td>23,000</td></tr>
  <tr><td>Sell</td><td>10,250</td></tr>
</tbody>

<tbody id="201712">
  <tr><th colspan="2">Dec-2017</th></tr>
  <tr><td>Buy</td><td>20,000</td></tr>
  <tr><td>Sell</td><td>12,500</td></tr>
</tbody>

<tbody id="201711">
  <tr><th colspan="2">Nov-2017</th></tr>
  <tr><td>Buy</td><td>10,000</td></tr>
  <tr><td>Sell</td><td>8,750</td></tr>
</tbody>

</table>


问:
Child Components are not being re-rendered
I'm new to React. As a learning exercise I'm building an chess application

I want to change the DOM of child based on state in parent. Currently there is no change in child components on change of state in parent.

Parent Component

```<code>class Game extends Component{
    constructor(){
        super();
        this.state = {
            game :{
                board_position = { 'One' : ''}
            }
        }

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(){
        let p = this.state.game.board_position;

        // some computations on p
        p = { board_position : { 'One' : Math.random() } }

        this.setState({
            game : p
        })

        //this.forceUpdate(); // Just trying different methods to make it work
    }

    render(){
        return(
            <div onClick={(e) => this.handleClick(e) }>
                <Piece {...this.state.game.board_position} />
            </div>
        )
    }
}
</code>```

Child Component

```<code>Class Piece extends Component{

    constructor(){
        super(props);
        this.state = {
            clr : ''
        }
    }

    componentWillMount(){
        let c;

        // some computations that change value of c based on props
        if( typeof ( this.props.game.one) == number ){
            c = 'Red'
        } else {
            c = 'Blue'
        }

        this.setState({
            clr : c
        })

    }

    render(){
        return(
            <span>{this.state.clr}</span>
        )
    }
}
</code>```

On call of handle click method, there is a change in state of the game. However, subsequent changes in Child are not seen.

Can anyone please help me out? Where am I going wrong?

I'm not sure how to implement ref as suggested over here. However, I don't think that is a good solution. Probably I'm having some conceptual misunderstanding.

PS: Please ignore any syntax error. This code is a strip down of real code.
If you want to take a look at full code - go over here

答:
componentWillMount in your Piece component will only fire once.

Are you updating your state each time the props change as well ? For example using componentWillReceiveProps

Also you could just display the props directly in your render function

```<code>render(){
    return(
        <span>{use the props directly here}</span>
    )
}
</code>```

Try to avoid using state whenever possible, and stick with just rendering your component based on props.

Body:
I'm new to React. As a learning exercise I'm building an chess application

I want to change the DOM of child based on state in parent. Currently there is no change in child components on change of state in parent.

Parent Component

class Game extends Component{
    constructor(){
        super();
        this.state = {
            game :{
                board_position = { 'One' : ''}
            }
        }

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(){
        let p = this.state.game.board_position;

        // some computations on p
        p = { board_position : { 'One' : Math.random() } }

        this.setState({
            game : p
        })

        //this.forceUpdate(); // Just trying different methods to make it work
    }

    render(){
        return(

 this.handleClick(e) }>
                <Piece {...this.state.game.board_position} />

        )
    }
}

Child Component

Class Piece extends Component{

    constructor(){
        super(props);
        this.state = {
            clr : ''
        }
    }

    componentWillMount(){
        let c;

        // some computations that change value of c based on props
        if( typeof ( this.props.game.one) == number ){
            c = 'Red'
        } else {
            c = 'Blue'
        }

        this.setState({
            clr : c
        })

    }

    render(){
        return(
            {this.state.clr}
        )
    }
}

On call of handle click method, there is a change in state of the game. However, subsequent changes in Child are not seen.

Can anyone please help me out? Where am I going wrong?

I'm not sure how to implement ref as suggested over here. However, I don't think that is a good solution. Probably I'm having some conceptual misunderstanding.

PS: Please ignore any syntax error. This code is a strip down of real code.
If you want to take a look at full code - go over here

Body:
componentWillMount in your Piece component will only fire once.

Are you updating your state each time the props change as well ? For example using componentWillReceiveProps

Also you could just display the props directly in your render function

render(){
    return(
        <span>{use the props directly here}</span>
    )
}

Try to avoid using state whenever possible, and stick with just rendering your component based on props.


问:
Where to find Azure Mobile Apps Push API Documentation?
I can't find any documentation for the  push/installations/ REST API. Is there any ?

For example in my code I use that statement to register my Azure Mobile Apps Client on the Push Notification Hub.

```<code>// Register with NotificationHub
            DeviceInstallation deviceInstallation = await client.InvokeApiAsync<DeviceInstallation, DeviceInstallation>(
                $"/push/installations/{client.InstallationId}",
                installation,
                HttpMethod.Put,
                new Dictionary<string, string>());
</code>```

But I want to know how to DELETE a previous registration but don't know how.

Thanks for any help.

Eric

答:
But I want to know how to DELETE a previous registration but don't know how.

For deleting the Installation, you could send a request as follows:

```<code>DELETE /push/installations/{InstallationId}
</code>```

For more details, you could check the method DeleteInstallationAsync and CreateOrUpdateInstallationAsync under PushHttpClient.cs.

Moreover, for creating/deleting a installation, you could just use the following build-in methods:

```<code>client.GetPush().RegisterAsync
client.GetPush().UnregisterAsync
</code>```

Details you could just follow Add push notifications to Xamarin.Forms app.

Body:
I can't find any documentation for the  push/installations/ REST API. Is there any ?

For example in my code I use that statement to register my Azure Mobile Apps Client on the Push Notification Hub.

// Register with NotificationHub
            DeviceInstallation deviceInstallation = await client.InvokeApiAsync<DeviceInstallation, DeviceInstallation>(
                $"/push/installations/{client.InstallationId}",
                installation,
                HttpMethod.Put,
                new Dictionary<string, string>());

But I want to know how to DELETE a previous registration but don't know how.

Thanks for any help.

Eric

Body:
But I want to know how to DELETE a previous registration but don't know how.

For deleting the Installation, you could send a request as follows:

DELETE /push/installations/{InstallationId}

For more details, you could check the method DeleteInstallationAsync and CreateOrUpdateInstallationAsync under PushHttpClient.cs.

Moreover, for creating/deleting a installation, you could just use the following build-in methods:

client.GetPush().RegisterAsync
client.GetPush().UnregisterAsync

Details you could just follow Add push notifications to Xamarin.Forms app.


问:
Sending a structure through a socket in c
I want to send a data structure through a socket in a tcp server/client program written in C. However when i try to print the sent data it doesn't print anything. I've realized by now that sending structures this way is a bad idea, the posts i've seen aren't being very helpful in finding a way to actually make this work. Here's the data structure in question:

```<code>#define BUFFSIZE 1024
#define USERLEN 32
#define OPTLEN 16

struct  message{
  char option[OPTLEN];
  char user[USERLEN];
  char buff[BUFFSIZE];
  char target[USERLEN];
  int sockid;
};
</code>```

thanks in advance.

答:
For the same machines and compilers you can do as follows:

```<code>// define your structure:
#define BUFFSIZE 1024
#define USERLEN 32
#define OPTLEN 16

typedef struct message{
  char option[OPTLEN];
  char user[USERLEN];
  char buff[BUFFSIZE];
  char target[USERLEN];
  int sockid;
}my_message;

// now you can use it in your program

my_message m;

// initialize m
...
strcpy(m.user,"1234");
...
m.sockid = sockfd;

// send it over

if ((nbytes = write(sockfd, &m, sizeof(my_message)) != sizeof(my_message))
{
  printf("error writing my message");
}

// read the message on the other side:
...
my_message received_message;
int size;

if( (size = recv ( sockfd, (void*)&received_message, sizeof(my_message), 0)) >= 0)
{
     // check the size
}

// It would work for same machines 32/64 bits and same compilers.
</code>```

If you need better portability try protobuf-c , nanopb, binary serialization binn or tpl.

Body:
I want to send a data structure through a socket in a tcp server/client program written in C. However when i try to print the sent data it doesn't print anything. I've realized by now that sending structures this way is a bad idea, the posts i've seen aren't being very helpful in finding a way to actually make this work. Here's the data structure in question:

#define BUFFSIZE 1024
#define USERLEN 32
#define OPTLEN 16

struct  message{
  char option[OPTLEN];
  char user[USERLEN];
  char buff[BUFFSIZE];
  char target[USERLEN];
  int sockid;
};

thanks in advance.

Body:
For the same machines and compilers you can do as follows:

// define your structure:
#define BUFFSIZE 1024
#define USERLEN 32
#define OPTLEN 16

typedef struct message{
  char option[OPTLEN];
  char user[USERLEN];
  char buff[BUFFSIZE];
  char target[USERLEN];
  int sockid;
}my_message;

// now you can use it in your program

my_message m;

// initialize m
...
strcpy(m.user,"1234");
...
m.sockid = sockfd;

// send it over

if ((nbytes = write(sockfd, &m, sizeof(my_message)) != sizeof(my_message))
{
  printf("error writing my message");
}

// read the message on the other side:
...
my_message received_message;
int size;

if( (size = recv ( sockfd, (void*)&received_message, sizeof(my_message), 0)) >= 0)
{
     // check the size
}

// It would work for same machines 32/64 bits and same compilers.

If you need better portability try protobuf-c , nanopb, binary serialization binn or tpl.


问:
Best serialization library for .net with ability to deserialize inheritance correctly
I need a serialization library for .net with better features than the default xml serializer.
The problem is that it  is not polymorphic - say you have class B : A { }, and have serialized an type B, you should be able to call A myBaseType = Deserialize(xml) on it and be returned an instance of type B in the myBaseType variable.

I have an implementation at http://refactormycode.com/codes/710-polymorphic-xml-serializer with unit tests that the serialization library should be able to deal with. This implementation will not work if an object to be serialized has a child type which is also a polymorphic serialized type, so I need something better.

thanks!

答: protobuf-net supports most inheritance routes (even though the spec doesn't). There is one known glitch (I'm working on it ;-p) - but it covers most options.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Marc Gravell


问:
How to make a repeating generator in Python
How do you make a repeating generator, like xrange, in Python? For instance, if I do:

```<code>>>> m = xrange(5)
>>> print list(m)
>>> print list(m)
</code>```

I get the same result both times — the numbers 0..4. However, if I try the same with yield:

```<code>>>> def myxrange(n):
...   i = 0
...   while i < n:
...     yield i
...     i += 1
>>> m = myxrange(5)
>>> print list(m)
>>> print list(m)
</code>```

The second time I try to iterate over m, I get nothing back — an empty list.

Is there a simple way to create a repeating generator like xrange with yield, or generator comprehensions? I found a workaround on a Python tracker issue, which uses a decorator to transform a generator into an iterator. This restarts every time you start using it, even if you didn't use all the values last time through, just like xrange. I also came up with my own decorator, based on the same idea, which actually returns a generator, but one which can restart after throwing a StopIteration exception:

```<code>@decorator.decorator
def eternal(genfunc, *args, **kwargs):
  class _iterable:
    iter = None
    def __iter__(self): return self
    def next(self, *nargs, **nkwargs):
      self.iter = self.iter or genfunc(*args, **kwargs):
      try:
        return self.iter.next(*nargs, **nkwargs)
      except StopIteration:
        self.iter = None
        raise
  return _iterable()
</code>```

Is there a better way to solve the problem, using only yield and/or generator comprehensions? Or something built into Python? So I don't need to roll my own classes and decorators?

Update

The comment by u0b34a0f6ae nailed the source of my misunderstanding:

xrange(5) does not return an iterator, it creates an xrange object. xrange objects can be iterated, just like dictionaries, more than once.

My "eternal" function was barking up the wrong tree entirely, by acting like an iterator/generator (__iter__ returns self) rather than like a collection/xrange (__iter__ returns a new iterator).

答:
You can reset iterators with more_itertools.seekable, a third-party tool.

Install via > pip install more_itertools.

```<code>import more_itertools as mit

def myxrange(n):
    """Yield integers."""
    i = 0
    while i < n:
        yield i
        i += 1

m = mit.seekable(myxrange(5))
print(list(m))
m.seek(0)                                              # reset iterator
print(list(m))
# [0, 1, 2, 3, 4]
# [0, 1, 2, 3, 4]
</code>```

Note: memory consumption grows while advancing an iterator, so be wary wrapping large iterables.

Body:
How do you make a repeating generator, like xrange, in Python? For instance, if I do:

>>> m = xrange(5)
>>> print list(m)
>>> print list(m)

I get the same result both times — the numbers 0..4. However, if I try the same with yield:

>>> def myxrange(n):
...   i = 0
...   while i < n:
...     yield i
...     i += 1
>>> m = myxrange(5)
>>> print list(m)
>>> print list(m)

The second time I try to iterate over m, I get nothing back — an empty list.

Is there a simple way to create a repeating generator like xrange with yield, or generator comprehensions? I found a workaround on a Python tracker issue, which uses a decorator to transform a generator into an iterator. This restarts every time you start using it, even if you didn't use all the values last time through, just like xrange. I also came up with my own decorator, based on the same idea, which actually returns a generator, but one which can restart after throwing a StopIteration exception:

@decorator.decorator
def eternal(genfunc, *args, **kwargs):
  class _iterable:
    iter = None
    def __iter__(self): return self
    def next(self, *nargs, **nkwargs):
      self.iter = self.iter or genfunc(*args, **kwargs):
      try:
        return self.iter.next(*nargs, **nkwargs)
      except StopIteration:
        self.iter = None
        raise
  return _iterable()

Is there a better way to solve the problem, using only yield and/or generator comprehensions? Or something built into Python? So I don't need to roll my own classes and decorators?

Update

The comment by u0b34a0f6ae nailed the source of my misunderstanding:

xrange(5) does not return an iterator, it creates an xrange object. xrange objects can be iterated, just like dictionaries, more than once.

My "eternal" function was barking up the wrong tree entirely, by acting like an iterator/generator (__iter__ returns self) rather than like a collection/xrange (__iter__ returns a new iterator).

Body:
You can reset iterators with more_itertools.seekable, a third-party tool.

Install via > pip install more_itertools.

import more_itertools as mit

def myxrange(n):
    """Yield integers."""
    i = 0
    while i < n:
        yield i
        i += 1

m = mit.seekable(myxrange(5))
print(list(m))
m.seek(0)                                              # reset iterator
print(list(m))
# [0, 1, 2, 3, 4]
# [0, 1, 2, 3, 4]

Note: memory consumption grows while advancing an iterator, so be wary wrapping large iterables.


问:
Replace multiple %in% statements with a single line of dplyr code

I would like to create a flag that is 1 if any one of 13 columns contains any one of a large number of codes and is 0 otherwise. I need to use dplyr because my data is in database. I can accomplish what I'm after using many %in% statements. I am wondering if there is a more concise way to write this code. Is there a version of %in% that allows multiple variables on the left hand side?

The following code gives the correct result. I've included only 5 columns and 2 rows for brevity.

```<code>library(dplyr)

match_dx <- c(paste0("C0", 0:9), paste0("C", 10:20))

df <- tibble(dx1 = c("C00", "G01"),
   dx2 = c("C50", "Z11"),
   dx3 = c("D20", "D22"),
   dx4 = c("A40", "C21"),
   dx13 = c("G20", "C30"))

df %>%
 mutate(flag = case_when(
      dx1 %in% match_dx ~ 1,
      dx2 %in% match_dx ~ 1,
      dx3 %in% match_dx ~ 1,
      dx4 %in% match_dx ~ 1,
      dx13 %in% match_dx ~ 1,
      T ~ 0
 ))
</code>```

I would like to know if there is something like

```<code>df %>%
 mutate(flag = case_when(
      any(vars(dx1:dx13) %in% match_dx) ~ 1,
      T ~ 0
 ))
</code>```

This does work but perhaps there is something similar or another way to accomplish this without needing one line per variable.

Thanks!

答:
Yet another alternative using purrr:

library(dplyr)
library(purrr)

df %>% mutate(flag = map_int(transpose(.), ~ any(. %in% match_dx)))
#> # A tibble: 2 x 6
#>     dx1   dx2   dx3   dx4  dx13  flag
#>   <chr> <chr> <chr> <chr> <chr> <int>
#> 1   C00   C50   D20   A40   G20     1
#> 2   G01   Z11   D22   C21   C30     0
```

Body:
I would like to create a flag that is 1 if any one of 13 columns contains any one of a large number of codes and is 0 otherwise. I need to use dplyr because my data is in database. I can accomplish what I'm after using many %in% statements. I am wondering if there is a more concise way to write this code. Is there a version of %in% that allows multiple variables on the left hand side?

The following code gives the correct result. I've included only 5 columns and 2 rows for brevity.

library(dplyr)

match_dx <- c(paste0("C0", 0:9), paste0("C", 10:20))

df <- tibble(dx1 = c("C00", "G01"),
   dx2 = c("C50", "Z11"),
   dx3 = c("D20", "D22"),
   dx4 = c("A40", "C21"),
   dx13 = c("G20", "C30"))

df %>%
 mutate(flag = case_when(
      dx1 %in% match_dx ~ 1,
      dx2 %in% match_dx ~ 1,
      dx3 %in% match_dx ~ 1,
      dx4 %in% match_dx ~ 1,
      dx13 %in% match_dx ~ 1,
      T ~ 0
 ))

I would like to know if there is something like

df %>%
 mutate(flag = case_when(
      any(vars(dx1:dx13) %in% match_dx) ~ 1,
      T ~ 0
 ))

This does work but perhaps there is something similar or another way to accomplish this without needing one line per variable.

Thanks!


问:
How can I prove irreflexivity of an inductively defined relation in Isabelle?
Consider as an example the following definition of inequality of natural numbers in Isabelle:

```<code>inductive unequal :: "nat ⇒ nat ⇒ bool" where
  zero_suc: "unequal 0 (Suc _)" |
  suc_zero: "unequal (Suc _) 0" |
  suc_suc:  "unequal n m ⟹ unequal (Suc n) (Suc m)"
</code>```

I want to prove irreflexivity of unequal, that is, ¬ unequal n n. For illustration purposes let me first prove the contrived lemma ¬ unequal (n + m) (n + m):

```<code>lemma "¬ unequal (n + m) (n + m)"
proof
  assume "unequal (n + m) (n + m)"
  then show False
  proof (induction "n + m" "n + m" arbitrary: n m)
    case zero_suc
    then show False by simp
  next
    case suc_zero
    then show False by simp
  next
    case suc_suc
    then show False by presburger
  qed
qed
</code>```

In the first two cases, False must be deduced from the assumptions 0 = n + m and Suc _ = n + m, which is trivial.

I would expect that the proof of ¬ unequal n n can be done in an analogous way, that is, according to the following pattern:

```<code>lemma "¬ unequal n n"
proof
  assume "unequal n n"
  then show False
  proof (induction n n arbitrary: n)
    case zero_suc
    then show False sorry
  next
    case suc_zero
    then show False sorry
  next
    case suc_suc
    then show False sorry
  qed
qed
</code>```

In particular, I would expect that in the first two cases, I get the assumptions 0 = n and Suc _ = n. However, I get no assumptions at all, meaning that I am asked to prove False from nothing. Why is this and how can I conduct the proof of inequality?

答:
You are inducting over unequal. Instead, you should induct over n, like this:

```<code>lemma "¬ (unequal n n)"
proof (induct n)
  case 0
  then show ?case sorry
next
  case (Suc n)
  then show ?case sorry
qed
</code>```

Then we can use Sledgehammer on each of the subgoals marked with sorry. Sledgehammer (with CVC4) recommends us to complete the proof as follows:

```<code>lemma "¬ (unequal n n)"
proof (induct n)
  case 0
  then show ?case using unequal.cases by blast
next
  case (Suc n)
  then show ?case using unequal.cases by blast
qed
</code>```

Body:
Consider as an example the following definition of inequality of natural numbers in Isabelle:

inductive unequal :: "nat ⇒ nat ⇒ bool" where
  zero_suc: "unequal 0 (Suc _)" |
  suc_zero: "unequal (Suc _) 0" |
  suc_suc:  "unequal n m ⟹ unequal (Suc n) (Suc m)"

I want to prove irreflexivity of unequal, that is, ¬ unequal n n. For illustration purposes let me first prove the contrived lemma ¬ unequal (n + m) (n + m):

lemma "¬ unequal (n + m) (n + m)"
proof
  assume "unequal (n + m) (n + m)"
  then show False
  proof (induction "n + m" "n + m" arbitrary: n m)
    case zero_suc
    then show False by simp
  next
    case suc_zero
    then show False by simp
  next
    case suc_suc
    then show False by presburger
  qed
qed

In the first two cases, False must be deduced from the assumptions 0 = n + m and Suc _ = n + m, which is trivial.

I would expect that the proof of ¬ unequal n n can be done in an analogous way, that is, according to the following pattern:

lemma "¬ unequal n n"
proof
  assume "unequal n n"
  then show False
  proof (induction n n arbitrary: n)
    case zero_suc
    then show False sorry
  next
    case suc_zero
    then show False sorry
  next
    case suc_suc
    then show False sorry
  qed
qed

In particular, I would expect that in the first two cases, I get the assumptions 0 = n and Suc _ = n. However, I get no assumptions at all, meaning that I am asked to prove False from nothing. Why is this and how can I conduct the proof of inequality?

Body:
You are inducting over unequal. Instead, you should induct over n, like this:

lemma "¬ (unequal n n)"
proof (induct n)
  case 0
  then show ?case sorry
next
  case (Suc n)
  then show ?case sorry
qed

Then we can use Sledgehammer on each of the subgoals marked with sorry. Sledgehammer (with CVC4) recommends us to complete the proof as follows:

lemma "¬ (unequal n n)"
proof (induct n)
  case 0
  then show ?case using unequal.cases by blast
next
  case (Suc n)
  then show ?case using unequal.cases by blast
qed


问:
How to reference parent names in JSON response (with Groovy)
I have the following JSON response in SoapUI

```<code>{
   "formatted":    {
      "line1": "14/8 QUAY STREET",
      "line2": "14/8 QUAY STREET"

   },
   "structure":    {
      "level": null
   },
   "location":    {
      "nzX": 1758749.75300025
   },
   "references":    {
      "aid": "A1003467096"
   }
 }
</code>```

I want the following as the output

formatted, structure, location and references.

I am using Json slurper but i am not able to get all the parent element names.

How do i do it using JSON slurper in groovy.

答:
Assuming the JSON is in a string s, consider the following which illustrates getting the top level keys:

```<code>import groovy.json.*

def json = new JsonSlurper().parseText(s)

def parentNames = json.keySet()

parentNames.each { println it }
</code>```

Body:
I have the following JSON response in SoapUI

{
   "formatted":    {
      "line1": "14/8 QUAY STREET",
      "line2": "14/8 QUAY STREET"

   },
   "structure":    {
      "level": null
   },
   "location":    {
      "nzX": 1758749.75300025
   },
   "references":    {
      "aid": "A1003467096"
   }
 }

I want the following as the output

formatted, structure, location and references.

I am using Json slurper but i am not able to get all the parent element names.

How do i do it using JSON slurper in groovy.

Body:
Assuming the JSON is in a string s, consider the following which illustrates getting the top level keys:

import groovy.json.*

def json = new JsonSlurper().parseText(s)

def parentNames = json.keySet()

parentNames.each { println it }


问:
How can I limit the number of records to load in view???
This code shows all the records of CommunityTopic that belongs to current Community.
How can I limit the numbers to 10 records to display here?</p>

```<code><ul>
  <% @community.community_topics.each do |topic| %>
    <li>
    <%= link_to topic.title, community_topic_path(@community, topic) %>
    <%= link_to topic.user.user_profile.nickname, community_topic_path(@community, topic) %>
    </li>
  <% end %>
</ul>
</code>```

答:
Use 8.3 reorder

The reorder method overrides the default scope order. For example:

```<code>@categories = Category.includes(:subcategories).where(active: true).references(:subcategories).order(name: :asc).reorder('categories.name ASC', 'subcategories.name ASC')
</code>```

http://guides.rubyonrails.org/active_record_querying.html

Body:
This code shows all the records of CommunityTopic that belongs to current Community.
How can I limit the numbers to 10 records to display here?

  <% @community.community_topics.each do |topic| %>

    <%= link_to topic.title, community_topic_path(@community, topic) %>
    <%= link_to topic.user.user_profile.nickname, community_topic_path(@community, topic) %>

  <% end %>

Body:
Use 8.3 reorder

The reorder method overrides the default scope order. For example:

@categories = Category.includes(:subcategories).where(active: true).references(:subcategories).order(name: :asc).reorder('categories.name ASC', 'subcategories.name ASC')

http://guides.rubyonrails.org/active_record_querying.html


问:
Does the implementation of an abstract method in Java needs throws someException declaration if the abstract method has it?
In the superclass I have:

```<code>abstract someMethod() throws someException;
</code>```

In the subclass I have:

```<code>someMethod(){/*do something*/}
</code>```

Is it ok to do this without a throws someException declaration? Is it that the throws someException declaration is there by default without adding it explicitly?

答: Your implementation doesn’t have to throw any exceptions. However, it can only throw checked exceptions specified in the abstract class.

Body:
In the superclass I have:

abstract someMethod() throws someException;

In the subclass I have:

someMethod(){/*do something*/}

Is it ok to do this without a throws someException declaration? Is it that the throws someException declaration is there by default without adding it explicitly?


问:
Licensing checker longevity of the "activated" status. How frequent is too much for the user?
My app is a kind of a pocket guide with some data for the whole year. I'm assuming users will use the program at least once with Internet access to activate the license. Or at least that's my understanding of how the Android licensing system works. I'm using ServerManagedPolicy.

Does it check periodically for the license? Is there any way that I can control this? I don't want my users to be in the middle of nowhere, with an app already and previously activated and suddenly after 1 week, 1 month, 1 year etc. the app starts limiting the usability of the app itself because the license couldn't be verified again. My app is going to be used in remote places with erratic net access (can't be taken for granted all the time) by people who will live there for weeks, maybe months.

I feel I should at least warn them that they will be asked every X weeks to do that. Is the license system even that draconian?

I know I can handle the errors with the ERROR_CONTACTING_SERVER flag, on the applicationError void of LicenseCheckerCallback. Is the "VT" response always the same (can't test this on a test account/my account)? I was just curious about how you guys treat this situation on your own real life apps. Am I missing something here? For some reason I'm feeling I am. Is there any "catch"?

// EDITED:

Here is the code I'm trying right now:

```<code>// ServerManagedPolicy.java
private void setValidityTimestamp(String validityTimestamp) {
    Long lValidityTimestamp;
    try {
        lValidityTimestamp = Long.parseLong(validityTimestamp);
    } catch (NumberFormatException e) {
        // No response or not parsable, expire in one minute.
        Log.w(TAG, "License validity timestamp (VT) missing, caching for a minute");
        lValidityTimestamp = System.currentTimeMillis() + MILLIS_PER_MINUTE;
        validityTimestamp = Long.toString(lValidityTimestamp);
    }
    // added by me--->

    private static long maxLicense = 1000 * 3600 * 24 * 30; // ~ roughly 30 days
    private static long minLicense = 1000 * 3600 * 24 * 3;  // ~ roughly 3 days

    long lMax = System.currentTimeMillis() + maxLicense;
    long lMin = System.currentTimeMillis() + minLicense;
    if ((lValidityTimestamp > lMin) && (lValidityTimestamp < lMax)) {
        validityTimestamp = Long.toString(lMax);
    }

    // <--- added by me

    mValidityTimestamp = lValidityTimestamp;
    mPreferences.putString(PREF_VALIDITY_TIMESTAMP, validityTimestamp);
}
</code>```

答: I got the answer to this very simply.  Connect a real device via USB to your computer.  Edit your LVL library source code in ServerManagedPolicy.java and add in a log statement for the lValidityTimestamp variable using DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM).  Then uninstall your application to clear out any previous license cache timestamp, reinstall, and run your app.  This contacts the server and then your logging statement reveals the answer.  In my testing, the VT comes back to be exactly 1 day from now (when the license is checkes).</p>

Body:
My app is a kind of a pocket guide with some data for the whole year. I'm assuming users will use the program at least once with Internet access to activate the license. Or at least that's my understanding of how the Android licensing system works. I'm using ServerManagedPolicy.

Does it check periodically for the license? Is there any way that I can control this? I don't want my users to be in the middle of nowhere, with an app already and previously activated and suddenly after 1 week, 1 month, 1 year etc. the app starts limiting the usability of the app itself because the license couldn't be verified again. My app is going to be used in remote places with erratic net access (can't be taken for granted all the time) by people who will live there for weeks, maybe months.

I feel I should at least warn them that they will be asked every X weeks to do that. Is the license system even that draconian?

I know I can handle the errors with the ERROR_CONTACTING_SERVER flag, on the applicationError void of LicenseCheckerCallback. Is the "VT" response always the same (can't test this on a test account/my account)? I was just curious about how you guys treat this situation on your own real life apps. Am I missing something here? For some reason I'm feeling I am. Is there any "catch"?

// EDITED:

Here is the code I'm trying right now:

// ServerManagedPolicy.java
private void setValidityTimestamp(String validityTimestamp) {
    Long lValidityTimestamp;
    try {
        lValidityTimestamp = Long.parseLong(validityTimestamp);
    } catch (NumberFormatException e) {
        // No response or not parsable, expire in one minute.
        Log.w(TAG, "License validity timestamp (VT) missing, caching for a minute");
        lValidityTimestamp = System.currentTimeMillis() + MILLIS_PER_MINUTE;
        validityTimestamp = Long.toString(lValidityTimestamp);
    }
    // added by me--->

    private static long maxLicense = 1000 * 3600 * 24 * 30; // ~ roughly 30 days
    private static long minLicense = 1000 * 3600 * 24 * 3;  // ~ roughly 3 days

    long lMax = System.currentTimeMillis() + maxLicense;
    long lMin = System.currentTimeMillis() + minLicense;
    if ((lValidityTimestamp > lMin) && (lValidityTimestamp < lMax)) {
        validityTimestamp = Long.toString(lMax);
    }

    // <--- added by me

    mValidityTimestamp = lValidityTimestamp;
    mPreferences.putString(PREF_VALIDITY_TIMESTAMP, validityTimestamp);
}


问:
Having trouble finding the start of a sentence inside string array
I have a text file from which I read the text in lines. Also from all that text I need to find the longest sentence and find in which line it begins. I have no trouble finding the longest sentence but the problem arises when I need to find where it begins.

The contents of the text file is:

V. M. Putinas

  Margi sakalai

  Lydėdami gęstančią žarą vėlai

  Pakilo į dangų;;, margi sakalai.

  Paniekinę žemės vylingus sapnus,

  Padangėje ištiesė,,; savo sparnus.

  Ir tarė margieji: negrįšim į žemę,

  Kol josios kalnai ir pakalnės aptemę.

My code:

```<code>static void Sakiniai (string fv, string skyrikliai)
{
    char[] skyrikliaiSak = { '.', '!', '?' };
    string naujas = "";
    string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));

    foreach (string line in lines)
    {
        // Add lines into a string so I can separate them into sentences
        naujas += line;
    }

    // Separating into sentences
    string[] sakiniai = naujas.Split(skyrikliaiSak);

    // This method finds the longest sentence
    string ilgiausiasSak = RastiIlgiausiaSakini(sakiniai);
}
</code>```

From the text file the longest sentence is: "Margi sakalai Lydėdami gęstančią žarą vėlai Pakilo į dangų;;, margi sakalai"

How can I find the exact line where the sentence begins?

答:
First find the start index of the longest sentence in the whole content

```<code>int startIdx = naujas.IndexOf(ilgiausiasSak);
</code>```

then loop the lines to find out which line the startIdx falls in

```<code>int i = 0;
while (i < lines.Length && startIdx >= 0)
{
    startIdx -= lines[i].Length;
    i++;
}
// do stuff with i
</code>```

i is where the longest sentence starts at. e.g. i=2 means it start from the second line

Body:
I have a text file from which I read the text in lines. Also from all that text I need to find the longest sentence and find in which line it begins. I have no trouble finding the longest sentence but the problem arises when I need to find where it begins.

The contents of the text file is:

V. M. Putinas

  Margi sakalai

  Lydėdami gęstančią žarą vėlai

  Pakilo į dangų;;, margi sakalai.

  Paniekinę žemės vylingus sapnus,

  Padangėje ištiesė,,; savo sparnus.

  Ir tarė margieji: negrįšim į žemę,

  Kol josios kalnai ir pakalnės aptemę.

My code:

static void Sakiniai (string fv, string skyrikliai)
{
    char[] skyrikliaiSak = { '.', '!', '?' };
    string naujas = "";
    string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));

    foreach (string line in lines)
    {
        // Add lines into a string so I can separate them into sentences
        naujas += line;
    }

    // Separating into sentences
    string[] sakiniai = naujas.Split(skyrikliaiSak);

    // This method finds the longest sentence
    string ilgiausiasSak = RastiIlgiausiaSakini(sakiniai);
}

From the text file the longest sentence is: "Margi sakalai Lydėdami gęstančią žarą vėlai Pakilo į dangų;;, margi sakalai"

How can I find the exact line where the sentence begins?

Body:
First find the start index of the longest sentence in the whole content

int startIdx = naujas.IndexOf(ilgiausiasSak);

then loop the lines to find out which line the startIdx falls in

int i = 0;
while (i < lines.Length && startIdx >= 0)
{
    startIdx -= lines[i].Length;
    i++;
}
// do stuff with i

i is where the longest sentence starts at. e.g. i=2 means it start from the second line


问:
Slicing Dataframe: 2400 rows into 100 columns each of 24 rows
I am new to pandas. I was wondering if anyone new a quick way to slice a dataframe such that. Input every 24 rows as a new column. The data I have is just one long stream of rows. </p>

答:
We using numpy.reshape

```<code>pd.DataFrame(np.reshape(df.values, (24, 100)))
</code>```

Body:
We using numpy.reshape

pd.DataFrame(np.reshape(df.values, (24, 100)))


问:
CodeIgniter & CSRF
When a user is logged in, he can perform a search with a small form. This is an AJAX request to a controller. I can perform this action multiple times. However,  when I try to reload the page, the user is logged out and needs to be logged in again.

This is my JS:

```<code>var CFG = {
        url: '<?php echo $this->config->item('base_url'); ?>',
        token: '<?php echo $this->security->get_csrf_hash(); ?>'
};

$(function()
{

    $('#personen_search_result').hide();
    $('#search_alert').hide();

    $.ajaxSetup(
    {
        data:
        {
            token:CFG.token
        }
    });

    $(document).ajaxSuccess(function(e,x)
    {
        var result = $.parseJSON(x.responseText);
        $('input:hidden[name="token"]').val(result.token);
        $.ajaxSetup(
        {
            data:
            {
                token: result.token
            }
        });
    });

    $( "#submit_personen" ).click(function(event)
    {

        event.preventDefault();

        var namelast        = $('#namelast').val();
        var dateofbirth     = $('#dateofbirth').val();
        var rijksregisternr = $('#rijksregisternr').val();
        var email           = $('#email').val();
        var hosid           = <?php echo $this->session->hosid; ?>;

        $.ajaxSetup(
        {
            data:
            {
                nameLast: namelast,
                dateofBirth: dateofbirth,
                rijksregisterNr: rijksregisternr,
                email: email,
                hosid: hosid
            }
        });

        $('#table_personen').html("");
        $('#search_alert').html("").hide();

        $.post(CFG.url + 'persoon/js_retrieve', function(data)
        {

            if(data['status']   == 200)
            {
                var personenrows        = data['html'];
                $('#table_personen').append (personenrows);

                if (!$('#personen_search_result').is(':visible'))
                    $('#personen_search_result').slideToggle();
            }
            else if (data['status'] == 400)
            {
                var message         = data['html'];
                $('#search_alert').append(message);

                if (!$('#search_alert').is(':visible'))
                    $('#search_alert').slideToggle();
            }
        }, 'json');

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

And this is my controller:

```<code>public function js_retrieve()
{

    // Data preperations

    // Query Builder

    if ($result->num_rows() == 0)
    {

        // No result: error message
        $data['html']       = '<span class="alert">Geen personen gevonden.</span>';
        $data['status']     = 400;
    }
    else
    {

        // Good result, show list in table
        // table header
        $html               = '<thead class="thead-light"><tr><th>Naam</th>th>Voornaam</th><th>Geboortedatum</th><th>Rijksregister</th><th>status</th></tr><tbody>';

        // create rows
        foreach ($result->result_array() as $row)
        {
            $html           .=
                '<tr>/\n<td><a href="'. base_url( 'persoon/detail/' .$row['id']  ) .'">' . $row['NameLast'] .', '. $row['NameFirst'] . '</a></td>/\n<td>' . $row['DateofBirth'] . '</td>/\n<td>' . $row['RijksRegisterNumber'] . '</td>/\n<td>' . $row['Status'] . '</td></tr>';
        }

        // close body
        $data['html']       = $html . '</tbody>';

        // status
        $data['status']     = 200;
    }

    // Set CSRF token hash & headers
    $data['oldtoken']       = $this->input->post('token');
    $data['token']          = $this->security->get_csrf_hash();

    if (!headers_sent())
    {
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: ' . date('r'));
        header('Content-type: application/json');
    }

    // return result
    exit( json_encode($data , JSON_FORCE_OBJECT) );
}
</code>```

Anyone that can give me some guidance?

PS: These are my configs:

```<code>$config['csrf_token_name'] = 'token';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = FALSE;
$config['csrf_exclude_uris'] = array();
</code>```

答:
This is not so much of an answer as it is a troubleshooting test too long for a comment. Try this:</p>

```<code>$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data, JSON_FORCE_OBJECT));
$this->output->_display();
exit;
</code>```

Title: CodeIgniter & CSRF

Body:
When a user is logged in, he can perform a search with a small form. This is an AJAX request to a controller. I can perform this action multiple times. However,  when I try to reload the page, the user is logged out and needs to be logged in again.

This is my JS:

var CFG = {
        url: '<?php echo $this->config->item('base_url'); ?>',
        token: '<?php echo $this->security->get_csrf_hash(); ?>'
};

$(function()
{

    $('#personen_search_result').hide();
    $('#search_alert').hide();

    $.ajaxSetup(
    {
        data:
        {
            token:CFG.token
        }
    });

    $(document).ajaxSuccess(function(e,x)
    {
        var result = $.parseJSON(x.responseText);
        $('input:hidden[name="token"]').val(result.token);
        $.ajaxSetup(
        {
            data:
            {
                token: result.token
            }
        });
    });

    $( "#submit_personen" ).click(function(event)
    {

        event.preventDefault();

        var namelast        = $('#namelast').val();
        var dateofbirth     = $('#dateofbirth').val();
        var rijksregisternr = $('#rijksregisternr').val();
        var email           = $('#email').val();
        var hosid           = <?php echo $this->session->hosid; ?>;

        $.ajaxSetup(
        {
            data:
            {
                nameLast: namelast,
                dateofBirth: dateofbirth,
                rijksregisterNr: rijksregisternr,
                email: email,
                hosid: hosid
            }
        });

        $('#table_personen').html("");
        $('#search_alert').html("").hide();

        $.post(CFG.url + 'persoon/js_retrieve', function(data)
        {

            if(data['status']   == 200)
            {
                var personenrows        = data['html'];
                $('#table_personen').append (personenrows);

                if (!$('#personen_search_result').is(':visible'))
                    $('#personen_search_result').slideToggle();
            }
            else if (data['status'] == 400)
            {
                var message         = data['html'];
                $('#search_alert').append(message);

                if (!$('#search_alert').is(':visible'))
                    $('#search_alert').slideToggle();
            }
        }, 'json');

    });
});

And this is my controller:

public function js_retrieve()
{

    // Data preperations

    // Query Builder

    if ($result->num_rows() == 0)
    {

        // No result: error message
        $data['html']       = 'Geen personen gevonden.';
        $data['status']     = 400;
    }
    else
    {

        // Good result, show list in table
        // table header
        $html               = '

Naam	th>Voornaam	Geboortedatum	Rijksregister	status

';

        // create rows
        foreach ($result->result_array() as $row)
        {
            $html           .=
                '
/\n' . $row['NameLast'] .', '. $row['NameFirst'] . '	/\n' . $row['DateofBirth'] . '	/\n' . $row['RijksRegisterNumber'] . '	/\n' . $row['Status'] . '
';
        }

        // close body
        $data['html']       = $html . '
';

        // status
        $data['status']     = 200;
    }

    // Set CSRF token hash & headers
    $data['oldtoken']       = $this->input->post('token');
    $data['token']          = $this->security->get_csrf_hash();

    if (!headers_sent())
    {
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: ' . date('r'));
        header('Content-type: application/json');
    }

    // return result
    exit( json_encode($data , JSON_FORCE_OBJECT) );
}

Anyone that can give me some guidance?

PS: These are my configs:

$config['csrf_token_name'] = 'token';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = FALSE;
$config['csrf_exclude_uris'] = array();

Body:
This is not so much of an answer as it is a troubleshooting test too long for a comment. Try this:

$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data, JSON_FORCE_OBJECT));
$this->output->_display();
exit;


问:
Extract a value from within a nested key python
I need to extract out a specific value from within a nested key in python
for example from the below I want to extract out the Start from the key Params

```<code>{'Key': 'Params', 'Value': `'{"Shut":false,"Remove":false,"SnapshotRequired":false,"Start":"Never","End":"Never"}'}
</code>```

This is as far as I have got

```<code>            for tag in i["Tags"]:
            if 'Params' in tag['Key']:
</code>```

then I can get the value but this is the whole string.

答:
Ok after fixing an issue in the string, an extra '`' you can simply make dict(string) to make it a valid python dict, which then accepts nested dicts as values.
also have in mine that "false" is not a valid python type, so you would have to make it a string or convert to python format which is False with the capital F

and finally do:
variable['Value']['Start']

```<code>test = dict({'Key': 'Params', 'Value': {"Shut":False,"Remove":False,"SnapshotRequired":False,"Start":"Never","End":"Never"}})
test['Value']['Start']
</code>```

Body:
I need to extract out a specific value from within a nested key in python
for example from the below I want to extract out the Start from the key Params

{'Key': 'Params', 'Value': `'{"Shut":false,"Remove":false,"SnapshotRequired":false,"Start":"Never","End":"Never"}'}

This is as far as I have got

            for tag in i["Tags"]:
            if 'Params' in tag['Key']:

then I can get the value but this is the whole string.

Body:
Ok after fixing an issue in the string, an extra '`' you can simply make dict(string) to make it a valid python dict, which then accepts nested dicts as values.
also have in mine that "false" is not a valid python type, so you would have to make it a string or convert to python format which is False with the capital F

and finally do:
variable['Value']['Start']

test = dict({'Key': 'Params', 'Value': {"Shut":False,"Remove":False,"SnapshotRequired":False,"Start":"Never","End":"Never"}})
test['Value']['Start']


问:
How to sort comma separated values in bash?
I have some numbers like

7, 15, 6, 2, -9

I want to sort it like this in bash(from command line or either a script file)

-9, 2, 6, 7, 15

How can I do this? I am unable to get this using sort command.

答:
```<code>echo "7, 15, 6, 2, -9" | sed -e $'s/,/\\\n/g' | sort -n | tr '\n' ',' | sed 's/.$//'
</code>```

sed -e $'s/,/\\\n/g': For splitting string into lines by comma.

sort -n: Then you can use sort by number

tr '\n' ',': Covert newline separator back to comma.

sed 's/.$//': Removing tailing comma.

Not elegant enough, but it should work :p

Body:
echo "7, 15, 6, 2, -9" | sed -e $'s/,/\\\n/g' | sort -n | tr '\n' ',' | sed 's/.$//'

sed -e $'s/,/\\\n/g': For splitting string into lines by comma.

sort -n: Then you can use sort by number

tr '\n' ',': Covert newline separator back to comma.

sed 's/.$//': Removing tailing comma.

Not elegant enough, but it should work :p


问:
MS BotFramework: collecting users credentials
Apologies for the lack of code or detail but I honestly don't know where to start!

I am building a bot to run a couple of reports and update a bunch of stuff in SharePoint (currently 2013 but moving to Online later in 2017).

I don't want to store them in plain text within the folder structure of my bot but I don't want them visible when you type them into the chat bot either.

Is there a way to asterisk out the password as the user types it in?

Cheers!

答:
Per my understanding, you want to mask the password input for your users. If any misunderstanding, please feel free to let me know.

So it seems that there is a similar question in GitHub at [Question] Masking Password field in Adaptive Card?

Password masking is not currently a feature. We recommend using the Sign-in Card workflow.

Using Sign-in card:

```<code>Activity replyToConversation = message.CreateReply("Should go to conversation");
replyToConversation.Attachments = new List<Attachment>();

List<CardAction> cardButtons = new List<CardAction>();

CardAction plButton = new CardAction()
{
    Value = $"https://<OAuthSignInURL",
    Type = "signin",
    Title = "Connect"
};

cardButtons.Add(plButton);

SigninCard plCard = new SigninCard(title: "You need to authorize me", button: plButton);

Attachment plAttachment = plCard.ToAttachment();
replyToConversation.Attachments.Add(plAttachment);

var reply = await connector.Conversations.SendToConversationAsync(replyToConversation);
</code>```

Then leverage https://github.com/MicrosoftDX/AuthBot in your bot for authentication.

Body:
Per my understanding, you want to mask the password input for your users. If any misunderstanding, please feel free to let me know.

So it seems that there is a similar question in GitHub at [Question] Masking Password field in Adaptive Card?

Password masking is not currently a feature. We recommend using the Sign-in Card workflow.

Using Sign-in card:

Activity replyToConversation = message.CreateReply("Should go to conversation");
replyToConversation.Attachments = new List<Attachment>();

List<CardAction> cardButtons = new List<CardAction>();

CardAction plButton = new CardAction()
{
    Value = $"https://<OAuthSignInURL",
    Type = "signin",
    Title = "Connect"
};

cardButtons.Add(plButton);

SigninCard plCard = new SigninCard(title: "You need to authorize me", button: plButton);

Attachment plAttachment = plCard.ToAttachment();
replyToConversation.Attachments.Add(plAttachment);

var reply = await connector.Conversations.SendToConversationAsync(replyToConversation);

Then leverage https://github.com/MicrosoftDX/AuthBot in your bot for authentication.


问:
List index out of range error on simple python for loop
Can someone explain to me why this for loop doesn't work. I'm trying to use something like this in another program to loop through a list using this N as a parameter.

```<code>    N = [20,40,60,80]

    for j in N:
        print(j)
        for i in range(0,N[j]):
            print(i)
</code>```

Thanks in advance!

答:
You're out of range, because j is taking the values of the elements of the N array, not the index. So, j is not 0, 1, 2, 3 but rather 20, 40, 60, 80.
So, when you get to for i in range((0, N[j]), you're asking for N[20], which is well beyond the length of the N list.

You could do:

```<code>N = [20,40,60,80]

for j in range(len(N)):
#        ^^^^^^^^^^^^^
    print(j)
    for i in range(0,N[j]):
        print(i)
</code>```

Body:
Can someone explain to me why this for loop doesn't work. I'm trying to use something like this in another program to loop through a list using this N as a parameter.

    N = [20,40,60,80]

    for j in N:
        print(j)
        for i in range(0,N[j]):
            print(i)

Thanks in advance!

Body:
You're out of range, because j is taking the values of the elements of the N array, not the index. So, j is not 0, 1, 2, 3 but rather 20, 40, 60, 80.
So, when you get to for i in range((0, N[j]), you're asking for N[20], which is well beyond the length of the N list.

You could do:

N = [20,40,60,80]

for j in range(len(N)):
#        ^^^^^^^^^^^^^
    print(j)
    for i in range(0,N[j]):
        print(i)


答:
What about a nested for loop? If two sentences are the same length, this just finds the first one.

```<code>var lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));
var terminators = new HashSet<char> { '.', '?', '!' };
var currentLength = 0;
var currentSentence = new StringBuilder();
var maxLength = 0;
var maxLine = default(int?);
var maxSentence = "";

for (var currentLine = 0; currentLine < lines.Count(); currentLine++)
{
    foreach (var character in lines[currentLine])
    {
        if (terminators.Contains(character))
        {
            if (currentLength > maxLength)
            {
                maxLength = currentLength;
                maxLine = currentLine;
                maxSentence = currentSentence.ToString();
            }

            currentLength = 0;
            currentSentence.Clear();
        }
        else
        {
            currentLength++;
            currentSentence.Append(character);
        }
    }
}
</code>```

Title: Having trouble finding the start of a sentence inside string array

Body:
What about a nested for loop? If two sentences are the same length, this just finds the first one.

var lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));
var terminators = new HashSet<char> { '.', '?', '!' };
var currentLength = 0;
var currentSentence = new StringBuilder();
var maxLength = 0;
var maxLine = default(int?);
var maxSentence = "";

for (var currentLine = 0; currentLine < lines.Count(); currentLine++)
{
    foreach (var character in lines[currentLine])
    {
        if (terminators.Contains(character))
        {
            if (currentLength > maxLength)
            {
                maxLength = currentLength;
                maxLine = currentLine;
                maxSentence = currentSentence.ToString();
            }

            currentLength = 0;
            currentSentence.Clear();
        }
        else
        {
            currentLength++;
            currentSentence.Append(character);
        }
    }
}


问:
PHP: Is timezone data somehow embeded into Timestamps?
```<code>date_default_timezone_set("Asia/Singapore"); // UTC +8
$dt = new DateTime();
$dt->setTimestamp(DateTime::createFromFormat('u', gmdate('u'))->getTimestamp());
echo $dt->getTimezone()->getName(); // Asia/Singapore
echo $dt->format('d M Y H:i:s'); // Correct local time

$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->format('d M Y H:i:s'); // Correct UTC Time
die;
</code>```

I am wondering if timestamps contain timezone data. On line 3 you see that I used gmdate() which should give me UTC/GMT time. But when I get the timezone & formatted datetime, they are in localtime. I didn't set timezones in my DateTime object yet, gave it a UTC timestamp. It somehow knew to convert to localtime. Which makes me wonder if Timezone data are included in timestamps

答:
Timestamps are interpreted according to the interpreters timezone.

So no, they are standard and do not contain timezone data within themselves.

your example proves it, as you change the timezone, so does your result.

If the timezone data was embedded, the result would not change.

Body:
date_default_timezone_set("Asia/Singapore"); // UTC +8
$dt = new DateTime();
$dt->setTimestamp(DateTime::createFromFormat('u', gmdate('u'))->getTimestamp());
echo $dt->getTimezone()->getName(); // Asia/Singapore
echo $dt->format('d M Y H:i:s'); // Correct local time

$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->format('d M Y H:i:s'); // Correct UTC Time
die;

I am wondering if timestamps contain timezone data. On line 3 you see that I used gmdate() which should give me UTC/GMT time. But when I get the timezone & formatted datetime, they are in localtime. I didn't set timezones in my DateTime object yet, gave it a UTC timestamp. It somehow knew to convert to localtime. Which makes me wonder if Timezone data are included in timestamps


问:
Laravel 5.5 - login explained?
My problem, or rather question is regarding the actual Login function of the builtin Authenthication feature by Laravel (v5.5).

I simply do not understand where the magic happens regarding logging the user into the system.

Here the login method within the LoginController

```<code>public function login(Request $request)
    {
        $this->validateLogin($request);

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }
</code>```

and here the attemptedLogin method butthis one still does not give me any closure.

```<code>protected function attemptLogin(Request $request)
{
    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}
</code>```

Can ANYONE explain to me where exactly in laravel a user gets logged in into the application? i cant read it out of the documentation either.
Either i'm too blind or stupid but i really do not see it.

Thanks in advance!

答:
I have spent the last few days trying to find the answer to almost the same question, so maybe I will be able to somehow clarify it a bit :)

How the user is authenticated depends on which guard you're using for a given model.

Just as you already know, the attemptLogin method is called on the result of the guard() method:

```<code>protected function attemptLogin(Request $request)
{
    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}
</code>```

If you use the default 'session' guard, this method returns an instance of Illuminate\Auth\SessionGuard.php class.

This class, in turn, defines attempt method, which calls the login method if the user credentials are valid. This seems to be the final place, where the user is actually authenticated.

Title: Laravel 5.5 - login explained?

Body:
My problem, or rather question is regarding the actual Login function of the builtin Authenthication feature by Laravel (v5.5).

I simply do not understand where the magic happens regarding logging the user into the system.

Here the login method within the LoginController

public function login(Request $request)
    {
        $this->validateLogin($request);

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

and here the attemptedLogin method butthis one still does not give me any closure.

protected function attemptLogin(Request $request)
{
    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}

Can ANYONE explain to me where exactly in laravel a user gets logged in into the application? i cant read it out of the documentation either.
Either i'm too blind or stupid but i really do not see it.

Thanks in advance!

Body:
I have spent the last few days trying to find the answer to almost the same question, so maybe I will be able to somehow clarify it a bit :)

How the user is authenticated depends on which guard you're using for a given model.

Just as you already know, the attemptLogin method is called on the result of the guard() method:

protected function attemptLogin(Request $request)
{
    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}

If you use the default 'session' guard, this method returns an instance of Illuminate\Auth\SessionGuard.php class.

This class, in turn, defines attempt method, which calls the login method if the user credentials are valid. This seems to be the final place, where the user is actually authenticated.


问:
how to use the client_authenticated_user custom grant type on light-oauth2 token endpoint
I am trying to use the custom grant type client_authenticated_user of light-oauth2 token service. The reason I cannot use standard grant types is due to my client need to talk to both legacy soap API and new restful API built on top of light-rest-4j. Today the client(webserver) does the authentication for users and we want to generate a token similar with authorization code grant type by passing the user profile to light-oauth2 token service. We have both client and light-oauth2 deployed on the same organization and the client is set up trusted client type on light-oauth2 client registration.

The question is how can I access token server to get JWT token using this custom grant type as this is not a standard flow. Do you have any examples or curl commands?

答:
As this is not a standard grant type in OAuth 2.0 specification, a lot of users are confused. To clarify this, I have created a tutorial and provide several curl command for the happy path.

https://doc.networknt.com/tutorial/oauth/custom/


问:
Force a branch naming convention in Azure DevOps Git
We use Git hosted in Azure DevOps for all of our source code. So far we have used Git Hooks to ensure that team members follow a branch naming convention {branchtype}/{username}/{friendlyname}/{workitemtype}{workitemid}.

Examples:

dev/dparkar/addauth/ta123456

hf/jsmith/memoryleak/bu11111

The branch naming convention allow us to clearly understand whether it's a regular development branch or a hotfix branch and which work item it is associated with, among other things.

To setup Git Hooks locally, team members were required to run a script locally before starting to contribute. This was fine as the script was doing additional setup besides just setting up Git Hooks. But we don't need that additional setup anymore and therefore we are looking to remove the script completely.

Is there a way to force branch naming conventions on the server side?

I noticed there is documentation for Pull Request Status Server, but was wondering if there is something OOTB which just needs to be configured in Azure DevOps.

答:
There are two kinds of git hooks:

Client-side hooks, works for the local git repo.

Server-side hooks, works for the remote repo (VSTS git repo as you used).

More details about git hooks, you can refer Customizing Git - Git Hooks in git book.

For now, only client-side hooks (such as pre-push hook, pre-commit hook etc) are supported for VSTS git repo.

The Server-side hooks is not available for now (but already in our backlog) for VSTS git repo, you can also find it in this user voice. Once server-side hooks are available in future, such as you can use pre-receive hook (or post-receive hook) to check and force convert branch name in remote repo.

Besides, the link in your question is using VSTS web hook which is quite different from git hooks. And of course you can check and force convert branch name by web hook, but you additional website to receive information and convert branch name. Detail steps as below:

Add a web hook in VSTS service Hooks Tab -> Trigger by code push event -> input your own website url -> Test -> make sure it can connect successful -> Finish.

Once new changes are pushed to VSTS git repo, the web hook will be triggered, and send information to your website. Then you can check and convert branch name in your website and push again.

ContentLicense: CC BY-SA 4.0


问:
how to run query on dataset?
i have Dataset that contain any database.

how to run any query on this dataset ?

答:
Hi I believe you can use Linq To Objects to query this dataset:

```<code>var results = (from r in mydatasetvar.AsQuarieable() .. )
</code>```

See this for more info

Alternatively, you can loop through the tables, rows and columns of the dataset.

Title: how to run query on dataset?

Body:
Hi I believe you can use Linq To Objects to query this dataset:

var results = (from r in mydatasetvar.AsQuarieable() .. )

See this for more info

Alternatively, you can loop through the tables, rows and columns of the dataset.


问:
Model filters based on the currently authenticated user
I am working on an app, in which each user is assigned a particular region. For example, user 1 belongs to a region 'Phoenix', user 2 to 'Scottsdale', and user 3 to 'Tempe'. The region of each user is defined in the region_id column.

The app has 3 separate guards for 3 different user models (it's a marketplace with regional managers, providers, and customers). Virtually every model in the app has a region_id column, identifying to which region the resource belongs to.

I would like to simplify how the resources are queried. Currently, I am filtering each model/resource directly in the controller, e.g.:

```<code>$customers = Customer::where('region_id', Auth::user()->region_id);
</code>```

I would like to set such filters at the global level, to make sure that each authenticated user can see records only from their own region. It is important particularly for displaying the list of records in the current region, not checking whether the user can access/edit a particular single record.

I have looked into Query Scopes, but I am not able to access the currently authenticated user withing them. The only case when I can access the current user is when the global scope is defined in a closure, but this defeats the purpose of not having to define the same logic in each model (i.e. I cannot extract the filtering logic to a query scope class).

What would be a good alternative approach to consider? How can I set the global model filters based on a property of a currently authenticated user?

答:
How about make a RegionalModel and extend all your Models with a region_id field? Then, in your RegionalModel create a scope like forUser(User $user) to apply your filter.

```<code>class RegionalModel extends Model {

    public function scopeForUser($query, User $user) {
        // Apply filter here
    }

}
</code>```

Then your Customer model might look like this

```<code>class Customer extends RegionalModel {

    // Code here

}
</code>```

Then when you want to get a list of customers

```<code>$user = Auth::user();
$customers = Customer::forUser($user)->get();
</code>```

Body:
I am working on an app, in which each user is assigned a particular region. For example, user 1 belongs to a region 'Phoenix', user 2 to 'Scottsdale', and user 3 to 'Tempe'. The region of each user is defined in the region_id column.

The app has 3 separate guards for 3 different user models (it's a marketplace with regional managers, providers, and customers). Virtually every model in the app has a region_id column, identifying to which region the resource belongs to.

I would like to simplify how the resources are queried. Currently, I am filtering each model/resource directly in the controller, e.g.:

$customers = Customer::where('region_id', Auth::user()->region_id);

I would like to set such filters at the global level, to make sure that each authenticated user can see records only from their own region. It is important particularly for displaying the list of records in the current region, not checking whether the user can access/edit a particular single record.

I have looked into Query Scopes, but I am not able to access the currently authenticated user withing them. The only case when I can access the current user is when the global scope is defined in a closure, but this defeats the purpose of not having to define the same logic in each model (i.e. I cannot extract the filtering logic to a query scope class).

What would be a good alternative approach to consider? How can I set the global model filters based on a property of a currently authenticated user?

Body:
How about make a RegionalModel and extend all your Models with a region_id field? Then, in your RegionalModel create a scope like forUser(User $user) to apply your filter.

class RegionalModel extends Model {

    public function scopeForUser($query, User $user) {
        // Apply filter here
    }

}

Then your Customer model might look like this

class Customer extends RegionalModel {

    // Code here

}

Then when you want to get a list of customers

$user = Auth::user();
$customers = Customer::forUser($user)->get();


问:
express js api end point does not work on azure web app
I just tried creating a test api app using Express js. i embraced many ways available on internet to deploy and run node js api app. But nothing is working in my case. Please help me.

Other wise i will have to leave either azure or node js.

I am attaching all the files below:
1.index.js

var express = require('express');
var app = express();

router.get('/things', function(req, res) {
    res.json('GET route on things.');
});
router.post('/things', function(req, res) {
    res.json('POST route on things.');
});

app.get('/hello', function(req, res) {
    res.json("Hello World!");
});

app.post('/hello', function(req, res) {
    res.json("You just called the post method at '/hello'!\n");
});

const port = process.env.PORT || 1337;
app.listen(port);```
</div>
</div>

2.package-lock.json</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
    "name": "testabc",
    "version": "1.0.0",
    "description": "test api",
    "main": "index.js",
    "engines": {
        "node": "^7.10.0"
    },
    "scripts": {
        "test": "test",
        "start": "node index.js",
        "prestart": "npm install"
    },
    "repository": {
        "type": "git",
        "url": "none"
    },
    "keywords": [
        "test"
    ],
    "author": "rakesh",
    "license": "ISC",
    "dependencies": {
        "express": "^4.16.2"
    }
}</code>```

3.package.json

{
    "name": "testabc",
    "version": "1.0.0",
    "description": "test api",
    "main": "index.js",
    "engines": {
        "node": "^7.10.0"
    },
    "scripts": {
        "test": "test",
        "start": "node index.js",
        "prestart": "npm install"
    },
    "repository": {
        "type": "git",
        "url": "none"
    },
    "keywords": [
        "test"
    ],
    "author": "rakesh",
    "license": "ISC",
    "dependencies": {
        "express": "^4.16.2"
    }
}```
</div>
</div>
</p>

<p>4.web.config</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
        </handlers>
        <rewrite>
      <rules>
        <rule name="myapp">
          <match url="/*" />
          <action type="Rewrite" url="index.js" />
        </rule>
      </rules>
    </rewrite>
    </system.webServer>
</configuration></code>```

答:
This would work if you change it to:

```<code>var express = require('express');
var app = express();

//****************************************
app.route('/things')
    .get(function (req, res) {
        res.json('GET route on things.');
    })
    .post(function (req, res) {
        res.json('POST route on things.');
    })
//****************************************
// or
//****************************************
var router = express.Router();
router.get('/', function (req, res) {
    res.json('GET route on things.');
});
router.post('/', function (req, res) {
    res.json('POST route on things.');
});
app.use('/things', router);
//****************************************

app.get('/hello', function (req, res) {
    res.json("Hello World!");
});

app.post('/hello', function (req, res) {
    res.json("You just called the post method at '/hello'!\n");
});

const port = process.env.PORT || 1337;
app.listen(port);
</code>```

The app will now be able to handle requests to:

GET /things

POST /things

GET /hello

POST /hello

Reference: https://expressjs.com/en/guide/routing.html

Body:
I just tried creating a test api app using Express js. i embraced many ways available on internet to deploy and run node js api app. But nothing is working in my case. Please help me.

Other wise i will have to leave either azure or node js.

I am attaching all the files below:
1.index.js

var express = require('express');
var app = express();

router.get('/things', function(req, res) {
    res.json('GET route on things.');
});
router.post('/things', function(req, res) {
    res.json('POST route on things.');
});

app.get('/hello', function(req, res) {
    res.json("Hello World!");
});

app.post('/hello', function(req, res) {
    res.json("You just called the post method at '/hello'!\n");
});

const port = process.env.PORT || 1337;
app.listen(port);

2.package-lock.json

{
    "name": "testabc",
    "version": "1.0.0",
    "description": "test api",
    "main": "index.js",
    "engines": {
        "node": "^7.10.0"
    },
    "scripts": {
        "test": "test",
        "start": "node index.js",
        "prestart": "npm install"
    },
    "repository": {
        "type": "git",
        "url": "none"
    },
    "keywords": [
        "test"
    ],
    "author": "rakesh",
    "license": "ISC",
    "dependencies": {
        "express": "^4.16.2"
    }
}

3.package.json

{
    "name": "testabc",
    "version": "1.0.0",
    "description": "test api",
    "main": "index.js",
    "engines": {
        "node": "^7.10.0"
    },
    "scripts": {
        "test": "test",
        "start": "node index.js",
        "prestart": "npm install"
    },
    "repository": {
        "type": "git",
        "url": "none"
    },
    "keywords": [
        "test"
    ],
    "author": "rakesh",
    "license": "ISC",
    "dependencies": {
        "express": "^4.16.2"
    }
}

4.web.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
        </handlers>
        <rewrite>
      <rules>
        <rule name="myapp">
          <match url="/*" />
          <action type="Rewrite" url="index.js" />
        </rule>
      </rules>
    </rewrite>
    </system.webServer>
</configuration>

Body:
This would work if you change it to:

var express = require('express');
var app = express();

//****************************************
app.route('/things')
    .get(function (req, res) {
        res.json('GET route on things.');
    })
    .post(function (req, res) {
        res.json('POST route on things.');
    })
//****************************************
// or
//****************************************
var router = express.Router();
router.get('/', function (req, res) {
    res.json('GET route on things.');
});
router.post('/', function (req, res) {
    res.json('POST route on things.');
});
app.use('/things', router);
//****************************************

app.get('/hello', function (req, res) {
    res.json("Hello World!");
});

app.post('/hello', function (req, res) {
    res.json("You just called the post method at '/hello'!\n");
});

const port = process.env.PORT || 1337;
app.listen(port);

The app will now be able to handle requests to:

GET /things

POST /things

GET /hello

POST /hello

Reference: https://expressjs.com/en/guide/routing.html