问:
Adding data from multiple check boxes to cell
I've seen some similar posts to this one but I'm not 100% sure how to make it work for my existing UserForm.  What I have is 5 check boxes that if checked will enter data to the cell, including if multiple boxes are checked.  So if HU and OS are checked it will read something like HU,OS.

The form right now adds information to a new line and I would like for it to continue doing that. I've tried some of the other methods I've seen but they don't seem to work with my very basic coding here.   Below are screenshots of the form and the coding.

Coding:

```<code>Private Sub CommandButton1_Click()

Dim emptyRow As Long

'Make Sheet1 active
Sheet1.Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Transfer information
Cells(emptyRow, 1).Value = Position.Value
Cells(emptyRow, 2).Value = Time.Value
Cells(emptyRow, 3).Value = Callpriority.Value

If CellCB.Value = True Then Cells(emptyRow, 4).Value = Cells(emptyRow, 4).Value & "Yes"

Cells(emptyRow, 5).Value = Calltype.Value
Cells(emptyRow, 6).Value = Transferto.Value

If HUCB.Value = True Then Cells(emptyRow, 7).Value = HUCB.Caption

If OSCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & OSCB.Caption

If CBCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & CBCB.Caption

If SCCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & SCCB.Caption

If TestCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & TestCB.Caption

Cells(emptyRow, 8).Value = Code.Value
Cells(emptyRow, 9).Value = Phonenumber.Value
Cells(emptyRow, 10).Value = Comments.Value

ActiveWorkbook.Save

End Sub

Private Sub CommandButton2_Click()

Application.ScreenUpdating = False
Unload Me
Testlog.Show
Application.ScreenUpdating = True

End Sub

Private Sub CommandButton3_Click()

Unload Me

End Sub

Private Sub UserForm_Initialize()

'Fill Position
With Position
    .AddItem "Police A"
    .AddItem "Police B"
    .AddItem "Fire A"
    .AddItem "Fire B"
    .AddItem "Trainer"
    .AddItem "Supervisor"
End With

'Empty Time
Time.Value = ""

'Fill Callpriority
With Callpriority
    .AddItem "Non-Emergency"
    .AddItem "Emergency"
    .AddItem "Unknown"
End With

'Fill Calltype
With Calltype
    .AddItem "Police"
    .AddItem "Fire"
    .AddItem "Medical"
End With

'Empty Transferto
Transferto.Value = ""

'Uncheck DataCheckBoxes
HUCB.Value = False
OSCB.Value = False
CBCB.Value = False
SCCB.Value = False
TestCB.Value = False
CellCB.Value = False

'Fill Code
With Code
    .AddItem "1"
    .AddItem "2"
    .AddItem "3"
    .AddItem "4"
    .AddItem "5"
    .AddItem "6"
    .AddItem "7"
    .AddItem "8"
    .AddItem "9"
    .AddItem "10"
End With

'Empty Phonenumber
Phonenumber.Value = ""

'Empty Comments
Comments.Value = ""

End Sub
</code>```

Log and Form

Form

答:
Simply add a String variable and add text to it as needed.</p>

```<code>Dim sDisposition As String

' ... Your other codes ...

sDisposition = ""
If HUCB.Value = True Then
    If Len(sDisposition) > 0 Then sDisposition = sDisposition & " "
    sDisposition = sDisposition & HUCB.Caption
End If
If OSCB.Value = True Then
    If Len(sDisposition) > 0 Then sDisposition = sDisposition & " "
    sDisposition = sDisposition & OSCB.Caption
End If
If CBCB.Value = True Then
    If Len(sDisposition) > 0 Then sDisposition = sDisposition & " "
    sDisposition = sDisposition & CBCB.Caption
End If
If SCCB.Value = True Then
    If Len(sDisposition) > 0 Then sDisposition = sDisposition & " "
    sDisposition = sDisposition & SCCB.Caption
End If
If TestCB.Value = True Then
    If Len(sDisposition) > 0 Then sDisposition = sDisposition & " "
    sDisposition = sDisposition & TestCB.Caption
End If
Cells(emptyRow, 7).Value = sDisposition ' typo here earlier...

' ... Your other codes ...
</code>```

Body:
I've seen some similar posts to this one but I'm not 100% sure how to make it work for my existing UserForm.  What I have is 5 check boxes that if checked will enter data to the cell, including if multiple boxes are checked.  So if HU and OS are checked it will read something like HU,OS.

The form right now adds information to a new line and I would like for it to continue doing that. I've tried some of the other methods I've seen but they don't seem to work with my very basic coding here.   Below are screenshots of the form and the coding.

Coding:

Private Sub CommandButton1_Click()

Dim emptyRow As Long

'Make Sheet1 active
Sheet1.Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Transfer information
Cells(emptyRow, 1).Value = Position.Value
Cells(emptyRow, 2).Value = Time.Value
Cells(emptyRow, 3).Value = Callpriority.Value

If CellCB.Value = True Then Cells(emptyRow, 4).Value = Cells(emptyRow, 4).Value & "Yes"

Cells(emptyRow, 5).Value = Calltype.Value
Cells(emptyRow, 6).Value = Transferto.Value

If HUCB.Value = True Then Cells(emptyRow, 7).Value = HUCB.Caption

If OSCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & OSCB.Caption

If CBCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & CBCB.Caption

If SCCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & SCCB.Caption

If TestCB.Value = True Then Cells(emptyRow, 7).Value = Cells(emptyRow, 7).Value & " " & TestCB.Caption

Cells(emptyRow, 8).Value = Code.Value
Cells(emptyRow, 9).Value = Phonenumber.Value
Cells(emptyRow, 10).Value = Comments.Value

ActiveWorkbook.Save

End Sub

Private Sub CommandButton2_Click()

Application.ScreenUpdating = False
Unload Me
Testlog.Show
Application.ScreenUpdating = True

End Sub

Private Sub CommandButton3_Click()

Unload Me

End Sub

Private Sub UserForm_Initialize()

'Fill Position
With Position
    .AddItem "Police A"
    .AddItem "Police B"
    .AddItem "Fire A"
    .AddItem "Fire B"
    .AddItem "Trainer"
    .AddItem "Supervisor"
End With

'Empty Time
Time.Value = ""

'Fill Callpriority
With Callpriority
    .AddItem "Non-Emergency"
    .AddItem "Emergency"
    .AddItem "Unknown"
End With

'Fill Calltype
With Calltype
    .AddItem "Police"
    .AddItem "Fire"
    .AddItem "Medical"
End With

'Empty Transferto
Transferto.Value = ""

'Uncheck DataCheckBoxes
HUCB.Value = False
OSCB.Value = False
CBCB.Value = False
SCCB.Value = False
TestCB.Value = False
CellCB.Value = False

'Fill Code
With Code
    .AddItem "1"
    .AddItem "2"
    .AddItem "3"
    .AddItem "4"
    .AddItem "5"
    .AddItem "6"
    .AddItem "7"
    .AddItem "8"
    .AddItem "9"
    .AddItem "10"
End With

'Empty Phonenumber
Phonenumber.Value = ""

'Empty Comments
Comments.Value = ""

End Sub

Log and Form

Form

Body:
Simply add a String variable and add text to it as needed.

Dim sDisposition As String

' ... Your other codes ...

sDisposition = ""
If HUCB.Value = True Then
    If Len(sDisposition) > 0 Then sDisposition = sDisposition & " "
    sDisposition = sDisposition & HUCB.Caption
End If
If OSCB.Value = True Then
    If Len(sDisposition) > 0 Then sDisposition = sDisposition & " "
    sDisposition = sDisposition & OSCB.Caption
End If
If CBCB.Value = True Then
    If Len(sDisposition) > 0 Then sDisposition = sDisposition & " "
    sDisposition = sDisposition & CBCB.Caption
End If
If SCCB.Value = True Then
    If Len(sDisposition) > 0 Then sDisposition = sDisposition & " "
    sDisposition = sDisposition & SCCB.Caption
End If
If TestCB.Value = True Then
    If Len(sDisposition) > 0 Then sDisposition = sDisposition & " "
    sDisposition = sDisposition & TestCB.Caption
End If
Cells(emptyRow, 7).Value = sDisposition ' typo here earlier...

' ... Your other codes ...


来源: stackexchange

问:
I changed the SelectedItem via a Binding. Now how do I move it into view without code-behind?
I've got a DataGrid with a Two-Way Binding on SelectedItem.  I can change the SelectedItem in my ViewModel, but the DataGrid won't ScrollIntoView automatically.

Is there a way to do this without using a code-behind event handler that calls ScrollIntoView(SelectedItem), or should I just give in and use a little code-behind?

ContentLicense: CC BY-SA 2.5

Body: Check http://www.codeproject.com/Tips/125583/ScrollIntoView-for-a-DataGrid-when-using-MVVM.aspx


问:
CSRF token and XSS vulnerability
Let's say that we use a CSRF token in our forms, but it happens that there is an unnoticed XSS hole on our site.

From what I uderstand, CSRF token protection is completely void in this case, because attacker can retreive it with XMLHttpRequest through XSS.

In such case, is there a way to enchant the CSRF protection in a way that it would survive the attack or should our site first have a secure anti-XSS protection before doing any king of CSRF at all?

Setting a new token upon every page request instead of token on login would deal with it? This brings up the problem of having more forms open at once and I don't like it.

答:
Short Answer: Origin header check is the only csrf protection mechanism which will hold it's ground even when there is XSS vulnerability.

These are the techniques that we use to prevent CSRF

Synchronizer Token

With the Synchronizer Token approach, the server embeds a dynamic hidden variable in an input form (Pay close attention, server has to have absolute control on the form generation so that it can generate a random string and embed in the form) and keep it in the session on server side --> verify on the form submit and invalidate it from the session as soon as it is used once. This will not work with Restful services powering a totally detached SPA(Single page applications) as Microservices has no access to the SPAs' form generation mechanism. When the form is submitted, the server can check and make sure that the hidden variable is present and that it is the correct value. See, this is being sent in the body (If we set this new token to cookie instead of form body, it defeats the whole thing, there will be no difference between this and sessionID).

If mybank.com is not sanitizing the form inputs (or in other words, if mybank.com is vulnerable to xss) hackers can overcome this csrf prevention method. https://rileykidd.com/2013/09/09/using-xss-to-csrf/

Double Submit Cookie

With the Double Submit Cookie approach, two cookies are sent back to the browser. One is the session id and the other is a random value (similar to the synchronizer token) Lets say sessionid and csrfid are those cookies.

There are 2 things to put this mechanism to work.

1) A feature built into the browser called the Same Origin Policy. This permits the script code to interact with other server endpoints only if those endpoints have the same origin (base URI) as the endpoint that delivered said script code. You might be wondering, “Whoa ! If one cookie isn’t secure on its own, how are two cookies going to be more secure?” Hang on, The key is in the next point

2) Having the second cookie (csrfid) included in subsequent requests in a custom header (let's say, X-XSRF-Token). It is up to your client script code to ensure that this is setup properly.

When you request the login page, two cookies are sent back by the server. The second cookie is used in a custom header for subsequent requests from the browser. The server checks for the existence of the custom header and checks the value against what was sent for that page.

Similar to the Synchronizer Token approach, an external site trying to spoof a page and trick you into submitting data to an active session, would fail as it would not be able to set the custom header for a site at a different URL.

Main actions

Server have to generate a random value csrftoken cookie and send it to browser when the session is established.

Client needs to access the cookie and set into custom header for every subsequent request

Server needs to verify the CUSTOM HEADER (just ignore csrfid (or whatever name you gave) cookie. Since it's a cookie, it will be there with every request anyway, just ignore it )

This technique is effective because all browsers implement the same origin policy. Only code from the website on which cookies are set can read the cookies from that site and set custom headers on requests to that site.

Open questions (did not get a chance to test this out yet): What about the httpOnly on second (csrf-token) cookie.. do we need to set it or not? .. If we set it, will Javascript be able to access it to set to each subsequent request. On the other hand, if Javascript is able to access it, then together with un-sanitized-form-negligence XSS vulnerability, XSS attack can expose the user's csrf-token. Then, if evil-guy is be able to fool users into visiting evil-site-which-has-a-csrf-form.com while having an active session in mybank.com, csrf attack can take place. Agreed, there are too many "if"s for the attack to take place, but still it's not secure.

By far, these methods are not that effective if there is XSS vulnerability. Let's take a look at the 3rd option

Origin header check

All browsers, including Internet Explorer 9 and later, send an Origin header in their requests. This header is not allowed to be set by Javascript, which gives you a high degree of confidence that the browser has the right information in that header. The server can then explicitly check that header and verify that the base URI matches the server’s. If the server is set to reject browser requests where the base URI in the Origin header does not match the expected value, then a third-party site trying to spoof the look of your page would be foiled as the Origin set in the browser would be different than what was expected.

This will not fail even if mybank.com has a XSS vulnerability. Catch Nada! If your users are using (very) older versions of browsers you might have other problems to solve anyway :)

Reference:
https://stormpath.com/blog/secure-single-page-app-problem

ContentLicense: CC BY-SA 3.0

Title: CSRF token and XSS vulnerability


问:
d3.nest return sum of values for each row
I have a csv like that:

```<code>name,na,profile,one,two,three,four,
uni1,eng,impact,4,5,3,1
uni1,eng,overall,10,5,3,1
uni1,fr,impact,4,5,7,1
uni1,fr,overall,20,5,7,1
uni1,ger,impact,4,5,3,1
uni1,ger,overall,18,5,18,1
uni1,eng,impact,4,5,3,1
uni2,eng,overall,4,5,3,1
uni2,fr,impact,4,5,3,30
uni2,fr,overall,4,5,3,1
uni2,ger,impact,4,5,3,1
uni2,ger,overall,4,21,3,1
uni2,spain,impact,4,5,3,1
uni2,spain,overall,4,5,3,1
uni2,spain,impact,4,20,3,1
uni2,lat,overall,4,19,3,1
uni2,lat,impact,4,5,17,1
</code>```

I would like to compute a d3 nest that will returned me for each uni and na the sum of the the one two three four value when profile === overall.

I woul like to have an array of object like :

```<code>array[object0{uni1{
                  eng{
                  value:230}]
</code>```

I succed to get all the line with the overall value but  I do not know how to return such things...

```<code>var nestedData = d3.nest()
            .key(function(d){return (d.profile=== "Overall").forEach(d.name);})
            //.rollup(function (v) { return d3.sum(v,function(d){return (d.four*4,d.three*3,d.two*2,d.one)/100 });})
            .sortKeys(d3.ascending)
            .entries(filteredData());

        console.log("Ranked :data",nestedData);

        return nestedData;
</code>```

答:
Your desired outcome is not exactly clear because you didn't show us how do you want to position the inner array for different eng in the same uni.

Therefore, here is an solution (out of many), check the console to see the array's structure:

var csv = `name,na,profile,one,two,three,four,
uni1,eng,impact,4,5,3,1
uni1,eng,overall,10,5,3,1
uni1,fr,impact,4,5,7,1
uni1,fr,overall,20,5,7,1
uni1,ger,impact,4,5,3,1
uni1,ger,overall,18,5,18,1
uni1,eng,impact,4,5,3,1
uni2,eng,overall,4,5,3,1
uni2,fr,impact,4,5,3,30
uni2,fr,overall,4,5,3,1
uni2,ger,impact,4,5,3,1
uni2,ger,overall,4,21,3,1
uni2,spain,impact,4,5,3,1
uni2,spain,overall,4,5,3,1
uni2,spain,impact,4,20,3,1
uni2,lat,overall,4,19,3,1
uni2,lat,impact,4,5,17,1`;

var data = d3.csvParse(csv, function(d) {
  d.one = +d.one;
  d.two = +d.two;
  d.three = +d.three;
  d.four = +d.four;
  return d;
});

var filteredData = data.filter(function(d) {
  return d.profile === "overall"
});

var nestedData = d3.nest()
  .key(function(d) {
    return d.name;
  })
  .sortKeys(d3.ascending)
  .key(function(d) {
    return d.na
  })
  .rollup(function(v) {
    return v[0].one + v[0].two + v[0].three + v[0].four
  })
  .entries(filteredData);

console.log(nestedData)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

PS: I know it's just me, but I was never a great fan of d3.nest(). I prefer to manipulate the data array the way I want with plain JavaScript functions... it's more versatile and you can structure the outcome exactly as you need.

EDIT: answering the Friday-challenge, this is the vanilla JavaScript to create the outcome described by OP (almost, because the inner objects have to be inside an array):

```<code>var finalArray = [];

[...new Set(filteredData.map(function(d) {
    return d.name
}))].forEach(function(d) {
    var tempObj = {
        [d]: []
    };
    filteredData.filter(function(e) {
        return e.name === d;
    }).forEach(function(e) {
        tempObj[d].push({
            [e.na]: e.one + e.two + e.three + e.four
        })
    });
    finalArray.push(tempObj)
});
</code>```

Here is the demo:

var csv = `name,na,profile,one,two,three,four,
uni1,eng,impact,4,5,3,1
uni1,eng,overall,10,5,3,1
uni1,fr,impact,4,5,7,1
uni1,fr,overall,20,5,7,1
uni1,ger,impact,4,5,3,1
uni1,ger,overall,18,5,18,1
uni1,eng,impact,4,5,3,1
uni2,eng,overall,4,5,3,1
uni2,fr,impact,4,5,3,30
uni2,fr,overall,4,5,3,1
uni2,ger,impact,4,5,3,1
uni2,ger,overall,4,21,3,1
uni2,spain,impact,4,5,3,1
uni2,spain,overall,4,5,3,1
uni2,spain,impact,4,20,3,1
uni2,lat,overall,4,19,3,1
uni2,lat,impact,4,5,17,1`;

var data = d3.csvParse(csv, function(d) {
  d.one = +d.one;
  d.two = +d.two;
  d.three = +d.three;
  d.four = +d.four;
  return d;
});

var filteredData = data.filter(function(d) {
  return d.profile === "overall"
});

var finalArray = [];

[...new Set(filteredData.map(function(d) {
  return d.name
}))].forEach(function(d) {
  var tempObj = {
    [d]: []
  };
  filteredData.filter(function(e) {
    return e.name === d;
  }).forEach(function(e) {
    tempObj[d].push({
      [e.na]: e.one + e.two + e.three + e.four
    })
  });
  finalArray.push(tempObj)
});

console.log(finalArray)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

Body:
I have a csv like that:

name,na,profile,one,two,three,four,
uni1,eng,impact,4,5,3,1
uni1,eng,overall,10,5,3,1
uni1,fr,impact,4,5,7,1
uni1,fr,overall,20,5,7,1
uni1,ger,impact,4,5,3,1
uni1,ger,overall,18,5,18,1
uni1,eng,impact,4,5,3,1
uni2,eng,overall,4,5,3,1
uni2,fr,impact,4,5,3,30
uni2,fr,overall,4,5,3,1
uni2,ger,impact,4,5,3,1
uni2,ger,overall,4,21,3,1
uni2,spain,impact,4,5,3,1
uni2,spain,overall,4,5,3,1
uni2,spain,impact,4,20,3,1
uni2,lat,overall,4,19,3,1
uni2,lat,impact,4,5,17,1

I would like to compute a d3 nest that will returned me for each uni and na the sum of the the one two three four value when profile === overall.

I woul like to have an array of object like :

array[object0{uni1{
                  eng{
                  value:230}]

I succed to get all the line with the overall value but  I do not know how to return such things...

var nestedData = d3.nest()
            .key(function(d){return (d.profile=== "Overall").forEach(d.name);})
            //.rollup(function (v) { return d3.sum(v,function(d){return (d.four*4,d.three*3,d.two*2,d.one)/100 });})
            .sortKeys(d3.ascending)
            .entries(filteredData());

        console.log("Ranked :data",nestedData);

        return nestedData;

Body:
Your desired outcome is not exactly clear because you didn't show us how do you want to position the inner array for different eng in the same uni.

Therefore, here is an solution (out of many), check the console to see the array's structure:

var csv = `name,na,profile,one,two,three,four,
uni1,eng,impact,4,5,3,1
uni1,eng,overall,10,5,3,1
uni1,fr,impact,4,5,7,1
uni1,fr,overall,20,5,7,1
uni1,ger,impact,4,5,3,1
uni1,ger,overall,18,5,18,1
uni1,eng,impact,4,5,3,1
uni2,eng,overall,4,5,3,1
uni2,fr,impact,4,5,3,30
uni2,fr,overall,4,5,3,1
uni2,ger,impact,4,5,3,1
uni2,ger,overall,4,21,3,1
uni2,spain,impact,4,5,3,1
uni2,spain,overall,4,5,3,1
uni2,spain,impact,4,20,3,1
uni2,lat,overall,4,19,3,1
uni2,lat,impact,4,5,17,1`;

var data = d3.csvParse(csv, function(d) {
  d.one = +d.one;
  d.two = +d.two;
  d.three = +d.three;
  d.four = +d.four;
  return d;
});

var filteredData = data.filter(function(d) {
  return d.profile === "overall"
});

var nestedData = d3.nest()
  .key(function(d) {
    return d.name;
  })
  .sortKeys(d3.ascending)
  .key(function(d) {
    return d.na
  })
  .rollup(function(v) {
    return v[0].one + v[0].two + v[0].three + v[0].four
  })
  .entries(filteredData);

console.log(nestedData)

<script src="https://d3js.org/d3.v4.min.js"></script>

PS: I know it's just me, but I was never a great fan of d3.nest(). I prefer to manipulate the data array the way I want with plain JavaScript functions... it's more versatile and you can structure the outcome exactly as you need.

EDIT: answering the Friday-challenge, this is the vanilla JavaScript to create the outcome described by OP (almost, because the inner objects have to be inside an array):

var finalArray = [];

[...new Set(filteredData.map(function(d) {
    return d.name
}))].forEach(function(d) {
    var tempObj = {
        [d]: []
    };
    filteredData.filter(function(e) {
        return e.name === d;
    }).forEach(function(e) {
        tempObj[d].push({
            [e.na]: e.one + e.two + e.three + e.four
        })
    });
    finalArray.push(tempObj)
});

Here is the demo:

var csv = `name,na,profile,one,two,three,four,
uni1,eng,impact,4,5,3,1
uni1,eng,overall,10,5,3,1
uni1,fr,impact,4,5,7,1
uni1,fr,overall,20,5,7,1
uni1,ger,impact,4,5,3,1
uni1,ger,overall,18,5,18,1
uni1,eng,impact,4,5,3,1
uni2,eng,overall,4,5,3,1
uni2,fr,impact,4,5,3,30
uni2,fr,overall,4,5,3,1
uni2,ger,impact,4,5,3,1
uni2,ger,overall,4,21,3,1
uni2,spain,impact,4,5,3,1
uni2,spain,overall,4,5,3,1
uni2,spain,impact,4,20,3,1
uni2,lat,overall,4,19,3,1
uni2,lat,impact,4,5,17,1`;

var data = d3.csvParse(csv, function(d) {
  d.one = +d.one;
  d.two = +d.two;
  d.three = +d.three;
  d.four = +d.four;
  return d;
});

var filteredData = data.filter(function(d) {
  return d.profile === "overall"
});

var finalArray = [];

[...new Set(filteredData.map(function(d) {
  return d.name
}))].forEach(function(d) {
  var tempObj = {
    [d]: []
  };
  filteredData.filter(function(e) {
    return e.name === d;
  }).forEach(function(e) {
    tempObj[d].push({
      [e.na]: e.one + e.two + e.three + e.four
    })
  });
  finalArray.push(tempObj)
});

console.log(finalArray)

<script src="https://d3js.org/d3.v4.min.js"></script>


问:
Compiler vs Interpreter vs Transpiler
During a ReactJS session that I was attending, the presenter used a term transpiler for some code conversion/porting happening. In the past, I have heard the terms compiler and interpreter. I've used in the context of converting a user written language code to a runnable form on a computer system. Transpiler is new to me. How is a transpiler different from a compiler or an interpreter and why is it needed?

答:
Compiler - compiles code to a lower level code.

Example:

"Developer code" -> "Machine code"

PHP -> C

Java -> bytecode

Transpiler - compiles code to same level of code/abstraction.

Example:

"Developer code" -> "Another developer code or version"

JavaScript ES2015+ -> JavaScript ES5

Interpreter - interprets code, not really in the same class/league/context with the two above.

Example: php.exe

"Your PHP code/scripts inside index.php" -> "Results to html or just like pure index.html"

ContentLicense: CC BY-SA 4.0

Title: Compiler vs Interpreter vs Transpiler


问:
How to use HoTT path induction in Coq?
In Coq I have

```<code>Definition f (s:Unit) : tt=tt := match s with tt => idpath end.
Definition g (p:tt=tt) : Unit := match p with idpath => tt end.
</code>```

and I would like to prove forall (p:tt=tt), (f o g) p = p.

I want to do it using the path induction described in 1.12.1 in HoTT's book.

It is clear that for the case in which p is idpath, we can prove

```<code>assert( (f o g) idpath = idpath).
simpl.
reflexivity.
</code>```

But how do I use path induction in Coq to package together the whole proof?

The whole proof until now: (What to put instead of admit?)

```<code>Require Import HoTT.
Definition f (s:Unit) : tt=tt := match s with tt => idpath end.
Definition g (p:tt=tt) : Unit := match p with idpath => tt end.
Theorem myTheorem : forall (p:tt=tt), (f o g) p = p.
  assert( (f o g) idpath = idpath).
  simpl.
  reflexivity.
admit.
</code>```

答:
The analog of path induction in Coq is the match construct.  Here is how we can use it to define (based) path induction as described in the HoTT book.

```<code>Set Implicit Arguments.

Definition J {A} {x : A} (P : forall y, x = y -> Type)
                 (H : P x eq_refl) : forall y p, P y p :=
  fun y p => match p with eq_refl => H end.
</code>```

The type of this definition says that, whenever we want to prove P y p, where

y : A,

p : x = y, and

P : forall y, x = y -> Type,

it suffices to show that P x eq_refl holds.  We can use J to show that  your g function is constant. (I have rephrased the definitions to match the ones given by the Coq standard library.)

```<code>Definition f (s : unit) : tt = tt := match s with tt => eq_refl end.
Definition g (p : tt = tt) : unit := match p return unit with eq_refl => tt end.

Definition g_tt p : g p = tt :=
  J (fun y q => match q return unit with eq_refl => tt end = tt)
    eq_refl p.
</code>```

The tricky part of this proof is finding out what the P parameter of J should be, which is also the case of other proofs that proceed by path induction.  Here, I had to unfold the definition of g, because it requires an argument of type tt = tt, whereas the q used above has type tt = y.  In any case, you can see that P tt p is definitionally equal to g p = tt, which is what we want to prove.

We can play trick to show that p = eq_refl for any p : tt = tt.  Combined with the previous result, it will give exactly what you want.

```<code>Definition result (p : tt = tt) : p = eq_refl :=
  J (fun y q =>
       unit_rect (fun z => tt = z -> Prop)
                 (fun u => u = eq_refl)
                 y q)
    eq_refl p.
</code>```

Once again, the crux is the P parameter.  We make use of the induction principle for unit, which says that we can define something of type T x (for T : unit -> Type and x : tt) whenever we can find an element of T tt. Recall that the result of this application of J should have type

```<code>P tt p
</code>```

which in this case is just

```<code>unit_rect (fun z => tt = z -> Prop)
          (fun u => u = eq_refl)
          tt p
= (p = eq_refl)
</code>```

by the computation rules for unit_rect.

Unfortunately, this sort of proof is difficult to replicate with Coq's tactic language, because it often has trouble inferring what P should be.  It is often easier to figure out what this value should be yourself and write down the proof term explicitly.

I don't quite understand why, but Coq is also much better at figuring out this annotation if you write down the proof term with match.  Compare:

```<code>Definition result' (p : tt = tt) : p = eq_refl :=
  match p with eq_refl => eq_refl end.
</code>```

Although this looks much simpler, you will see that the actual term inferred by Coq is much more complicated when you try to print it. Try it!

Edit

Ah, I just realized that you were trying to use the HoTT version of Coq.  I don't have that version installed, but I think it shouldn't be too hard to adapt my solution to it.

Title: How to use HoTT path induction in Coq?

Body:
In Coq I have

Definition f (s:Unit) : tt=tt := match s with tt => idpath end.
Definition g (p:tt=tt) : Unit := match p with idpath => tt end.

and I would like to prove forall (p:tt=tt), (f o g) p = p.

I want to do it using the path induction described in 1.12.1 in HoTT's book.

It is clear that for the case in which p is idpath, we can prove

assert( (f o g) idpath = idpath).
simpl.
reflexivity.

But how do I use path induction in Coq to package together the whole proof?

The whole proof until now: (What to put instead of admit?)

Require Import HoTT.
Definition f (s:Unit) : tt=tt := match s with tt => idpath end.
Definition g (p:tt=tt) : Unit := match p with idpath => tt end.
Theorem myTheorem : forall (p:tt=tt), (f o g) p = p.
  assert( (f o g) idpath = idpath).
  simpl.
  reflexivity.
admit.

Body:
The analog of path induction in Coq is the match construct.  Here is how we can use it to define (based) path induction as described in the HoTT book.

Set Implicit Arguments.

Definition J {A} {x : A} (P : forall y, x = y -> Type)
                 (H : P x eq_refl) : forall y p, P y p :=
  fun y p => match p with eq_refl => H end.

The type of this definition says that, whenever we want to prove P y p, where

y : A,

p : x = y, and

P : forall y, x = y -> Type,

it suffices to show that P x eq_refl holds.  We can use J to show that  your g function is constant. (I have rephrased the definitions to match the ones given by the Coq standard library.)

Definition f (s : unit) : tt = tt := match s with tt => eq_refl end.
Definition g (p : tt = tt) : unit := match p return unit with eq_refl => tt end.

Definition g_tt p : g p = tt :=
  J (fun y q => match q return unit with eq_refl => tt end = tt)
    eq_refl p.

The tricky part of this proof is finding out what the P parameter of J should be, which is also the case of other proofs that proceed by path induction.  Here, I had to unfold the definition of g, because it requires an argument of type tt = tt, whereas the q used above has type tt = y.  In any case, you can see that P tt p is definitionally equal to g p = tt, which is what we want to prove.

We can play trick to show that p = eq_refl for any p : tt = tt.  Combined with the previous result, it will give exactly what you want.

Definition result (p : tt = tt) : p = eq_refl :=
  J (fun y q =>
       unit_rect (fun z => tt = z -> Prop)
                 (fun u => u = eq_refl)
                 y q)
    eq_refl p.

Once again, the crux is the P parameter.  We make use of the induction principle for unit, which says that we can define something of type T x (for T : unit -> Type and x : tt) whenever we can find an element of T tt. Recall that the result of this application of J should have type

P tt p

which in this case is just

unit_rect (fun z => tt = z -> Prop)
          (fun u => u = eq_refl)
          tt p
= (p = eq_refl)

by the computation rules for unit_rect.

Unfortunately, this sort of proof is difficult to replicate with Coq's tactic language, because it often has trouble inferring what P should be.  It is often easier to figure out what this value should be yourself and write down the proof term explicitly.

I don't quite understand why, but Coq is also much better at figuring out this annotation if you write down the proof term with match.  Compare:

Definition result' (p : tt = tt) : p = eq_refl :=
  match p with eq_refl => eq_refl end.

Although this looks much simpler, you will see that the actual term inferred by Coq is much more complicated when you try to print it. Try it!

Edit

Ah, I just realized that you were trying to use the HoTT version of Coq.  I don't have that version installed, but I think it shouldn't be too hard to adapt my solution to it.


问:
How to Save, Separate, and Write Data from File to Multiple TextBoxes
I need to save a bunch (around 600) of TextBox content to a (Preferably) single file, then be able to write that data back to their respective TextBoxes on file open. Essentially I'm making a D&D stat sheet, and I want to save what each player has entered as the [character's name].txt. I already got simple saving and writing down by using a single control and the code:

```<code>Dim SaveCharacter As StreamWriter
        If txtName.Text = "" Then
            MessageBox.Show("In order to save, you must enter a name for your character.", "Error: No Name Entered")
        Else
            Try
                SaveCharacter = File.AppendText("H:\Visual Basic Projects\DAndD-2.5\DAndD-2.5\Saves\" & txtName.Text & ".txt")
                SaveCharacter.WriteLine(frmNotes.rtxNotes.Text)
                SaveCharacter.Close()
            Catch
                MessageBox.Show("Error")
            End Try
        End If

 'Next event handler
            Dim OpenCharacter As StreamReader
            OpenCharacter = File.OpenText("H:\Visual Basic Projects\DAndD-2.5\DAndD-2.5\Saves\Jared.txt")
            Do Until OpenCharacter.EndOfStream
                frmNotes.rtxNotes.Text = OpenCharacter.ReadToEnd.ToString()
                For Each strLine As String In frmNotes.rtxNotes.Text.Split(vbNewLine)
                Next
            Loop
</code>```

Is there an easy(ish) way to do what I need, especially in mass (few lines of code) without having to save each TextBox as a different .txt file?

Thanks for the help!

答:
This will write the contents of all your TextBoxes to a file, one line per control:

```<code>IO.File.WriteAllLines(filePath, Me.Controls.OfType(Of TextBox).Select(Function(tb) tb.Text))
</code>```

This will read a file back into those TextBoxes:

```<code>Dim textBoxes = Me.Controls.OfType(Of TextBox).ToArray()
Dim lines = IO.File.ReadAllLines(filePath)

For i = 0 To lines.GetUpperBound(0)
    textBoxes(i).Text = lines(i)
Next
</code>```

That assumes that no TextBoxes are multi-line and it also does not validate the file on reading, so you might want to check that the number of lines and TextBoxes matches.

Body:
I need to save a bunch (around 600) of TextBox content to a (Preferably) single file, then be able to write that data back to their respective TextBoxes on file open. Essentially I'm making a D&D stat sheet, and I want to save what each player has entered as the [character's name].txt. I already got simple saving and writing down by using a single control and the code:

Dim SaveCharacter As StreamWriter
        If txtName.Text = "" Then
            MessageBox.Show("In order to save, you must enter a name for your character.", "Error: No Name Entered")
        Else
            Try
                SaveCharacter = File.AppendText("H:\Visual Basic Projects\DAndD-2.5\DAndD-2.5\Saves\" & txtName.Text & ".txt")
                SaveCharacter.WriteLine(frmNotes.rtxNotes.Text)
                SaveCharacter.Close()
            Catch
                MessageBox.Show("Error")
            End Try
        End If

 'Next event handler
            Dim OpenCharacter As StreamReader
            OpenCharacter = File.OpenText("H:\Visual Basic Projects\DAndD-2.5\DAndD-2.5\Saves\Jared.txt")
            Do Until OpenCharacter.EndOfStream
                frmNotes.rtxNotes.Text = OpenCharacter.ReadToEnd.ToString()
                For Each strLine As String In frmNotes.rtxNotes.Text.Split(vbNewLine)
                Next
            Loop

Is there an easy(ish) way to do what I need, especially in mass (few lines of code) without having to save each TextBox as a different .txt file?

Thanks for the help!

Body:
This will write the contents of all your TextBoxes to a file, one line per control:

IO.File.WriteAllLines(filePath, Me.Controls.OfType(Of TextBox).Select(Function(tb) tb.Text))

This will read a file back into those TextBoxes:

Dim textBoxes = Me.Controls.OfType(Of TextBox).ToArray()
Dim lines = IO.File.ReadAllLines(filePath)

For i = 0 To lines.GetUpperBound(0)
    textBoxes(i).Text = lines(i)
Next

That assumes that no TextBoxes are multi-line and it also does not validate the file on reading, so you might want to check that the number of lines and TextBoxes matches.


问:
How to avoid writing ugly code while dealing with object properties in javascript
I find that when I write javascript I encounter a situation where I am forced to write ugly code. This is due to my inability to reconcile the following two criteria:

1) Define data using shorthand, e.g. var data = { a: 1, b: { c: 2, d: 3 ... } }

2) Use a primitive operator to check for property existence

For example consider a function which returns the intersection of two Object instances' keys as an Array of the intersecting keys:

```<code>var intersection = function(obj1, obj2) {
    var result = [];
    for (var k in obj1) if (k in obj2) result.push(k);
    return result;
};
</code>```

That code looks quite nice. But unfortunately, it doesn't always work as expected! This is due to the inconsistency between for (x in y), and if (x in y): Using for (x in y) will only iterate over "own" properties (properties which return true for hasOwnProperty), while if (x in y) while apply for "own" and "non-own" properties!

If I call intersection like so:

```<code>var obj1 = { toString: 'hahaha' };
var obj2 = {};
var intersectingKeys = intersection(obj1, obj2);
</code>```

I will wind up with intersectingKeys === [ 'toString' ]; Obviously this is not correct: an intersection operation involving an empty set (as obj2 appears to be) must return an empty set. While {} is clearly intended to be "empty", our problem is that ('toString' in {}) === true. This also applies to terms such as 'constructor', 'valueOf', as well as any new properties that are introduced to Object.prototype in the future.

In my opinion, if a native operator can provide iteration over keys, a native operator should be able to verify whether a key will appear in an iteration. It feels inconsistent and ugly, to me, to use a native operator for one, but a function call for the other. For that reason I dislike this fix:

```<code>var safeIntersection = function(obj1, obj2) {
    var result = [];
    for (var k in obj1) if (obj2.hasOwnProperty(k)) result.push(k);
    return result;
};
</code>```

If if (x in y) must be used, I only see one other possible solution: Ensure that the parameters passed to intersection have no properties at all, apart from properties explicitly defined by our code. In other words, ensure that we only work with prototype-less objects:

```<code>var obj1 = Object.create(null, {
    toString: {
        configurable: true,
        enumerable: true,
        writable: true,
        value: 'hahaha'
    }
});
var obj2 = Object.create(null, {});
var intersectingKeys = intersection(obj1, obj2);
</code>```

Note that this code uses intersection, not safeIntersection, and still works because obj1 and obj2 are prototype-less. But the problem is, now data definition is really, really clunky! Look at how much code it takes to define an object with a single "toString" property. This approach prevents us from using javascript's beautiful object-shorthand. Even if we write a utility function to encompass prototype-less object creation, the definition of nested objects is still incredibly clunky:

```<code>// Utility function for prototype-less object definition
var obj = function(props) {
    return Object.create(null, props.map(function(v) {
        return {
            writable: true,
            configurable: true,
            enumerable: true,
            value: v
        };
    }));
};

// Now defining `obj1` looks ok...
var obj1 = obj({ toString: 'hahaha' });

// But for large, nested object definitions it's sooper ugly:
var big = obj({
    a: 'a value',
    b: 'b value',
    moreProps: obj({
        wheee: 'yay',
        evenMoreProps: obj({
            prop: 'propMeUp'
            /* ... */
        })
        /* ... */
    })
});
</code>```

Javascript's object-definition shorthand is a huge perk of the language, and throwing it away by being forced to wrap all { ... } instances in a function call seems like a tremendous pity.

My ideal solution to this problem would involve converting the shorthand object constructor to produce prototype-less objects. Perhaps a global setting:

```<code>// Perhaps along with other global settings such as:
'use strict';
Error.stackTraceLimit = Infinity;

// We could also have:
Object.shorthandIncludesPrototype = false;
</code>```

Although even if this solutions were available it would break tons and tons of pre-existing libraries. :(

How do I reconcile the following criteria???:

1) Write code that works

2) Use the primitive in operator to check for property existence

3) Define objects using typical shorthand

Perhaps it's impossible to meet all these criteria simultaneously. In that case, what are some of the next-best approaches for keeping code clean in these cases?

答:
I have 2 extra solutions that are probably worth mentioning here:

1) Recursive obj function

As I mentioned in the question, having an obj method which creates an un-prototyped value from a regular Object defined via shorthand gets really ugly when it needs to be applied all throughout a nested shorthand structure - but this problem can be somewhat solved if the obj method is recursive, so that it only needs to be applied to the root Object and not explicitly to every inner child property:

var obj = function(val) {
  if (val.constructor === Object) {
    var ret = Object.create(null);
    for (var k in val) ret[k] = obj(val[k]);
  } else if (val.constructor === Array) {
    var ret = [];
    for (var i = 0; i < val.length; i++) ret.push(obj(val[i]));
  } else {
    var ret = val;
  }

  return ret;
};

var thing = obj({
  prop1: 'hello',
  prop2: 'hi',
  prop3: [
    { num: 1, val: 'lalala' },
    { num: 2, val: 'heehee' },
    { num: 3, val: 'hoho' },
  ],
  really: {
    deep: {
      property: {
        over: {
          here: { val: 'soooo deep' }
        }
      }
    }
  }
});

console.log('toString' in thing);
console.log('toString' in thing.prop3[1]);
console.log('toString' in thing.really.deep.property.over.here);```
</div>
</div>
</p>

<p>Now it's important that all shorthand objects are wrapped in <code>obj</code>.</p>

<h1>2) Clear out <code>Object.prototype</code></h1>

<p>I've found that chrome and node (v0.12.0) will allow me to delete all properties from <code>Object.prototype</code>. The prototype can even be restored at any point in the future if these removed properties are kept in memory:</p>

```var savedPrototype = {};
var removePrototype = function() {
  savedPrototype = {};
  var props = Object.getOwnPropertyNames(Object.prototype);
  for (var i = 0; i < props.length; i++) {
    savedPrototype[props[i]] = Object.prototype[props[i]];
    delete Object.prototype[props[i]];
  }
};
var restorePrototype = function() {
  for (var k in savedPrototype) {
    Object.prototype[k] = savedPrototype[k];
  }
};

removePrototype();
var obj = { val: 'haha' };
console.log('toString' in obj); // false
restorePrototype();
console.log('toString' in obj); // true
```

Body:
I find that when I write javascript I encounter a situation where I am forced to write ugly code. This is due to my inability to reconcile the following two criteria:

1) Define data using shorthand, e.g. var data = { a: 1, b: { c: 2, d: 3 ... } }

2) Use a primitive operator to check for property existence

For example consider a function which returns the intersection of two Object instances' keys as an Array of the intersecting keys:

var intersection = function(obj1, obj2) {
    var result = [];
    for (var k in obj1) if (k in obj2) result.push(k);
    return result;
};

That code looks quite nice. But unfortunately, it doesn't always work as expected! This is due to the inconsistency between for (x in y), and if (x in y): Using for (x in y) will only iterate over "own" properties (properties which return true for hasOwnProperty), while if (x in y) while apply for "own" and "non-own" properties!

If I call intersection like so:

var obj1 = { toString: 'hahaha' };
var obj2 = {};
var intersectingKeys = intersection(obj1, obj2);

I will wind up with intersectingKeys === [ 'toString' ]; Obviously this is not correct: an intersection operation involving an empty set (as obj2 appears to be) must return an empty set. While {} is clearly intended to be "empty", our problem is that ('toString' in {}) === true. This also applies to terms such as 'constructor', 'valueOf', as well as any new properties that are introduced to Object.prototype in the future.

In my opinion, if a native operator can provide iteration over keys, a native operator should be able to verify whether a key will appear in an iteration. It feels inconsistent and ugly, to me, to use a native operator for one, but a function call for the other. For that reason I dislike this fix:

var safeIntersection = function(obj1, obj2) {
    var result = [];
    for (var k in obj1) if (obj2.hasOwnProperty(k)) result.push(k);
    return result;
};

If if (x in y) must be used, I only see one other possible solution: Ensure that the parameters passed to intersection have no properties at all, apart from properties explicitly defined by our code. In other words, ensure that we only work with prototype-less objects:

var obj1 = Object.create(null, {
    toString: {
        configurable: true,
        enumerable: true,
        writable: true,
        value: 'hahaha'
    }
});
var obj2 = Object.create(null, {});
var intersectingKeys = intersection(obj1, obj2);

Note that this code uses intersection, not safeIntersection, and still works because obj1 and obj2 are prototype-less. But the problem is, now data definition is really, really clunky! Look at how much code it takes to define an object with a single "toString" property. This approach prevents us from using javascript's beautiful object-shorthand. Even if we write a utility function to encompass prototype-less object creation, the definition of nested objects is still incredibly clunky:

// Utility function for prototype-less object definition
var obj = function(props) {
    return Object.create(null, props.map(function(v) {
        return {
            writable: true,
            configurable: true,
            enumerable: true,
            value: v
        };
    }));
};

// Now defining `obj1` looks ok...
var obj1 = obj({ toString: 'hahaha' });

// But for large, nested object definitions it's sooper ugly:
var big = obj({
    a: 'a value',
    b: 'b value',
    moreProps: obj({
        wheee: 'yay',
        evenMoreProps: obj({
            prop: 'propMeUp'
            /* ... */
        })
        /* ... */
    })
});

Javascript's object-definition shorthand is a huge perk of the language, and throwing it away by being forced to wrap all { ... } instances in a function call seems like a tremendous pity.

My ideal solution to this problem would involve converting the shorthand object constructor to produce prototype-less objects. Perhaps a global setting:

// Perhaps along with other global settings such as:
'use strict';
Error.stackTraceLimit = Infinity;

// We could also have:
Object.shorthandIncludesPrototype = false;

Although even if this solutions were available it would break tons and tons of pre-existing libraries. :(

How do I reconcile the following criteria???:

1) Write code that works

2) Use the primitive in operator to check for property existence

3) Define objects using typical shorthand

Perhaps it's impossible to meet all these criteria simultaneously. In that case, what are some of the next-best approaches for keeping code clean in these cases?

Body:
I have 2 extra solutions that are probably worth mentioning here:

1) Recursive obj function

As I mentioned in the question, having an obj method which creates an un-prototyped value from a regular Object defined via shorthand gets really ugly when it needs to be applied all throughout a nested shorthand structure - but this problem can be somewhat solved if the obj method is recursive, so that it only needs to be applied to the root Object and not explicitly to every inner child property:

var obj = function(val) {
  if (val.constructor === Object) {
    var ret = Object.create(null);
    for (var k in val) ret[k] = obj(val[k]);
  } else if (val.constructor === Array) {
    var ret = [];
    for (var i = 0; i < val.length; i++) ret.push(obj(val[i]));
  } else {
    var ret = val;
  }

  return ret;
};

var thing = obj({
  prop1: 'hello',
  prop2: 'hi',
  prop3: [
    { num: 1, val: 'lalala' },
    { num: 2, val: 'heehee' },
    { num: 3, val: 'hoho' },
  ],
  really: {
    deep: {
      property: {
        over: {
          here: { val: 'soooo deep' }
        }
      }
    }
  }
});

console.log('toString' in thing);
console.log('toString' in thing.prop3[1]);
console.log('toString' in thing.really.deep.property.over.here);

Now it's important that all shorthand objects are wrapped in obj.

2) Clear out Object.prototype

I've found that chrome and node (v0.12.0) will allow me to delete all properties from Object.prototype. The prototype can even be restored at any point in the future if these removed properties are kept in memory:

var savedPrototype = {};
var removePrototype = function() {
  savedPrototype = {};
  var props = Object.getOwnPropertyNames(Object.prototype);
  for (var i = 0; i < props.length; i++) {
    savedPrototype[props[i]] = Object.prototype[props[i]];
    delete Object.prototype[props[i]];
  }
};
var restorePrototype = function() {
  for (var k in savedPrototype) {
    Object.prototype[k] = savedPrototype[k];
  }
};

removePrototype();
var obj = { val: 'haha' };
console.log('toString' in obj); // false
restorePrototype();
console.log('toString' in obj); // true


问:
Angular2 - Importing angular modules
Modules are imported in app.module.ts, by adding an entry below,

```<code>@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    DirectoryComponent,
    FilterPipe,
    LoggingService
  ],
  imports: [
    FormsModule,
    BrowserModule,
    HttpClientModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})
</code>```

but RouterModule is directly used in ../src/app/app.routes.ts, as shown below,

```<code>import {Routes, RouterModule} from "@angular/router";
export const routes:Routes = [
    /* Each route will be an object {}*/
    {path: 'directory', component: DirectoryComponent},
    {path: '',          component: HomeComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
</code>```

There is no entry of RouterModule in @NgModule(imports: [..]).

1)
Are there different ways to import an angular module?

2)
Is import of angular module different from import of typescript module?

答:
There is an entry, you just named it routing as a const.
so in your case routing is actually RouterModule.forRoot(routes); which means it's the RouterModule.

I think angular team explains it nicely here https://angular.io/guide/router

And there is no typescript module. Only angular module. In your case you assigned the angular module to a const referenced with name routing and you exported it.

Title: Angular2 - Importing angular modules

Body:
Modules are imported in app.module.ts, by adding an entry below,

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    DirectoryComponent,
    FilterPipe,
    LoggingService
  ],
  imports: [
    FormsModule,
    BrowserModule,
    HttpClientModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})

but RouterModule is directly used in ../src/app/app.routes.ts, as shown below,

import {Routes, RouterModule} from "@angular/router";
export const routes:Routes = [
    /* Each route will be an object {}*/
    {path: 'directory', component: DirectoryComponent},
    {path: '',          component: HomeComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

There is no entry of RouterModule in @NgModule(imports: [..]).

1)
Are there different ways to import an angular module?

2)
Is import of angular module different from import of typescript module?


问:
Drop duplicate rows from a pandas DataFrame whose timestamps are within a specified range or duration
I have a DataFrame like this:

```<code>Subject Verb    Object  Date
---------------------------------
Bill    Ate     Food    7/11/2015
Steve   Painted House   8/12/2011
Bill    Ate     Food    7/13/2015
Steve   Painted House   8/25/2011
</code>```

I would like to drop all duplicates, where a duplicate is defined as having the same Subject, Verb, Object, and falls within an X day range (in my example: 5 days).

```<code>Subject Verb    Object  Date
---------------------------------
Bill    Ate     Food    7/11/2015
Steve   Painted House   8/12/2011
Steve   Painted House   8/25/2011
</code>```

Neither instance of "Steve - Painted - House" is removed because they are outside of a 5 day window.

I know I can do this using some data structures and the iterrows method of the DataFrame, but is there a way to do this using Pandas drop_duplicates?

答:
Use duplicated + diff in conjunction with groupby to figure out what rows you want to remove.

```<code>c = ['Subject', 'Verb', 'Object']

def f(x):
    return x[c].duplicated() & x.Date.diff().dt.days.lt(5)

df = df.sort_values(c)
df[~df.groupby(c).apply(f).values]

  Subject     Verb Object       Date
0    Bill      Ate   Food 2015-07-11
1   Steve  Painted  House 2011-08-12
3   Steve  Painted  House 2011-08-25
</code>```

Body:
I have a DataFrame like this:

Subject Verb    Object  Date
---------------------------------
Bill    Ate     Food    7/11/2015
Steve   Painted House   8/12/2011
Bill    Ate     Food    7/13/2015
Steve   Painted House   8/25/2011

I would like to drop all duplicates, where a duplicate is defined as having the same Subject, Verb, Object, and falls within an X day range (in my example: 5 days).

Subject Verb    Object  Date
---------------------------------
Bill    Ate     Food    7/11/2015
Steve   Painted House   8/12/2011
Steve   Painted House   8/25/2011

Neither instance of "Steve - Painted - House" is removed because they are outside of a 5 day window.

I know I can do this using some data structures and the iterrows method of the DataFrame, but is there a way to do this using Pandas drop_duplicates?

Body:
Use duplicated + diff in conjunction with groupby to figure out what rows you want to remove.

c = ['Subject', 'Verb', 'Object']

def f(x):
    return x[c].duplicated() & x.Date.diff().dt.days.lt(5)

df = df.sort_values(c)
df[~df.groupby(c).apply(f).values]

  Subject     Verb Object       Date
0    Bill      Ate   Food 2015-07-11
1   Steve  Painted  House 2011-08-12
3   Steve  Painted  House 2011-08-25


问:
Why would PayPal's IPN return the status as 'Completed' when it's on hold?
I'm using Express Checkout, and the response from DoExpressCheckout returns the following parameters:

```<code>PAYMENTINFO_0_PAYMENTTYPE = INSTANT
PAYMENTINFO_0_PAYMENTSTATUS = COMPLETED_FUNDS_HELD
PENDINGREASON = NONE
REASONCODE = NONE
HOLDDECISION = PAYMENTHOLD
</code>```

However, the IPN that's sent along doesn't make any reference to the funds being held. The payment_status is set as Completed and there's no mention of a parameter that might signify an issue in the documentation for the IPN values.

How can I ensure that I only react once the payment has been taken out of review, and is no longer being held?

(Note: I need to resolve how to handle this in the IPN, not the underlying problem with the account, as this is a historical issue that I need to prevent from happening again for any reason)

答:
IPN are showing the transaction status during the time it was happen, in your case, the payment are done, completed which means, the money was initiated from the buyer account into your account, but due to some issues/reasons the transfer of the said money was pending. Some security check has caused the transaction funds being held

In IPN payment status, it was showing that COMPLETED_FUNDS_HELD which means there is a money come into your account but then it was held due to some reason where only PayPal knows.

This payment will be release in a few days, and until that time, if you handling the payment carefully from your website dashboard order, it shouldn't be any issue because normally PayPal only hold it for a few days.

Until this time, I written this, PayPal hasn't got any solution for this type of held because it was an account related issue where IPN are not feed to the get the update.

Body:
I'm using Express Checkout, and the response from DoExpressCheckout returns the following parameters:

PAYMENTINFO_0_PAYMENTTYPE = INSTANT
PAYMENTINFO_0_PAYMENTSTATUS = COMPLETED_FUNDS_HELD
PENDINGREASON = NONE
REASONCODE = NONE
HOLDDECISION = PAYMENTHOLD

However, the IPN that's sent along doesn't make any reference to the funds being held. The payment_status is set as Completed and there's no mention of a parameter that might signify an issue in the documentation for the IPN values.

How can I ensure that I only react once the payment has been taken out of review, and is no longer being held?

(Note: I need to resolve how to handle this in the IPN, not the underlying problem with the account, as this is a historical issue that I need to prevent from happening again for any reason)


问:
How can I disable a task in build.gradle
I want to skip some tasks when I run gradle build. I know that it can be done from command line with -x:

gradle build -x unwantedTask
```

My question is how can the same result be achieved in the build.gradle?

答:
Because I need to disable a bunch of tasks, so I use the following codes before apply plugin: in my build.gradle file:

```<code>tasks.whenTaskAdded {task ->
    if(task.name.contains("unwantedTask")) {
        task.enabled = false
    }
}
</code>```

Body:
I want to skip some tasks when I run gradle build. I know that it can be done from command line with -x:

gradle build -x unwantedTask

My question is how can the same result be achieved in the build.gradle?

Body:
Because I need to disable a bunch of tasks, so I use the following codes before apply plugin: in my build.gradle file:

tasks.whenTaskAdded {task ->
    if(task.name.contains("unwantedTask")) {
        task.enabled = false
    }
}


问:
Audio cable controlling MediaPlayer Service
I have programmed an usual MediaPlayer like APP. Now I have a pair of headphones with inline remote controls for Controlling the volume, pause and Play Songs.
My idea is to Control my MediaPlayer Service with this. But I cant find anything on the web concerning my Problem. Can somebody might give me a hint to this?</p>

答:
I dont know why I get downvoted with my question, but I will answer it for others facing the same Problem.

```<code>public class MediaService extends Service implements
    MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
    MediaPlayer.OnCompletionListener {

private IntentFilter intentFilterMediaButton = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
private MediaButtonIntentReceiver mMediaButtonReceiver = new MediaButtonIntentReceiver();

@Override
public void onPrepared(MediaPlayer mediaPlayer) {
    registerReceiver(this.mMediaButtonReceiver, this.intentFilterMediaButton);
    player.start();
}
public static class MediaButtonIntentReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String intentAction = intent.getAction();
        if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
            return;
        }
        KeyEvent event =   (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        if (event == null) {
            return;
        }
        int action = event.getAction();
        if (action == KeyEvent.ACTION_DOWN) {
            switch (action){
                case 0: // Button down
                    // do something
                    Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
        abortBroadcast();
    }
}
</code>```

Called this in the main activity.onCreate()

```<code>    AudioManager manager = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (manager != null) {
        manager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), MediaService.MediaButtonIntentReceiver.class.getName()));
    }
</code>```

And put this into the Manifest

```<code>    <receiver android:name="MediaService$MediaButtonIntentReceiver" android:enabled="true">
        <intent-filter android:priority="1000000000">
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </receiver>
</code>```

Body:
I dont know why I get downvoted with my question, but I will answer it for others facing the same Problem.

public class MediaService extends Service implements
    MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
    MediaPlayer.OnCompletionListener {

private IntentFilter intentFilterMediaButton = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
private MediaButtonIntentReceiver mMediaButtonReceiver = new MediaButtonIntentReceiver();

@Override
public void onPrepared(MediaPlayer mediaPlayer) {
    registerReceiver(this.mMediaButtonReceiver, this.intentFilterMediaButton);
    player.start();
}
public static class MediaButtonIntentReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String intentAction = intent.getAction();
        if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
            return;
        }
        KeyEvent event =   (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        if (event == null) {
            return;
        }
        int action = event.getAction();
        if (action == KeyEvent.ACTION_DOWN) {
            switch (action){
                case 0: // Button down
                    // do something
                    Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
        abortBroadcast();
    }
}

Called this in the main activity.onCreate()

    AudioManager manager = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (manager != null) {
        manager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), MediaService.MediaButtonIntentReceiver.class.getName()));
    }

And put this into the Manifest

    <receiver android:name="MediaService$MediaButtonIntentReceiver" android:enabled="true">
        <intent-filter android:priority="1000000000">
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </receiver>


问:
C++ template class inheritance
I have been porting some C++ code, which was written long time ago, and is normally compiled with Visual C++ (Visual Studio 7.1 version) and Intel C++ Compiler 11.0, the target platform is Linux (Suse x86-64), with GCC 4.3.2 and Intel C++ Compiler 11.1

The problem is that code like this

FileA.h

```<code>template<typename T, int dim>
class A
{
 public:
  A(){};
  ~A(){};
 protected:
  void foo1(){};
}
</code>```

FileB.h

```<code>#include "FileA.h"
template<typename T>
class B : public A<T, 2>
{
 public:
  B(){};
  ~B(){};
  void foo(){ foo1(); }
}
</code>```

main.cpp

```<code>#include "FileB.h"
int main()
{
 B<float> b = B<float>();
}
</code>```

does not compile on Linux (Intel C++ 11.1, GCC 4.3.2), but perfectly compiles on Windows (Visual C++ 7.1, Intel C++ 11.0), althow it surely must not depend on platform.
GCC tells that if I change foo1() to foo1(T a) it will work (and it does), but I can not change the code, and have to use Intel C++ for final release.

I would be glad if anyone could help with any advice.

答: This is a well-known problem with templates. It is explained in the C++ FAQ</p>

Title: C++ template class inheritance

Body:
I have been porting some C++ code, which was written long time ago, and is normally compiled with Visual C++ (Visual Studio 7.1 version) and Intel C++ Compiler 11.0, the target platform is Linux (Suse x86-64), with GCC 4.3.2 and Intel C++ Compiler 11.1

The problem is that code like this

FileA.h

template<typename T, int dim>
class A
{
 public:
  A(){};
  ~A(){};
 protected:
  void foo1(){};
}

FileB.h

#include "FileA.h"
template<typename T>
class B : public A<T, 2>
{
 public:
  B(){};
  ~B(){};
  void foo(){ foo1(); }
}

main.cpp

#include "FileB.h"
int main()
{
 B<float> b = B<float>();
}

does not compile on Linux (Intel C++ 11.1, GCC 4.3.2), but perfectly compiles on Windows (Visual C++ 7.1, Intel C++ 11.0), althow it surely must not depend on platform.
GCC tells that if I change foo1() to foo1(T a) it will work (and it does), but I can not change the code, and have to use Intel C++ for final release.

I would be glad if anyone could help with any advice.


问:
How to publish my Android app on Tencent or 360 mobile?
I have a fully working APK of an Android application I have developed. The app only have ads and some basic functions, not any Google Admob ads or any Google in-app purchases.

I wish to market this app to China, but the Google Play store is inaccessible at mainland China. So, how can I publish my app to a Chinese app market store like Tencent or 360 mobile? I can't read or write a single word in Chinese.

答:
On 360's English site, there is a form http://developer.360.cn/distribution that can allow developers to submit their apps.

Same for Tencent's English official site. http://open.qq.com/eng/reg

You can simply follow instructions on their website to submit your application.


问:
Given a lat/long, find the nearest lat/long pair from a list of lat/long in c#
From a List of lat/long pairs, I am trying to find  nearest lat/long pair w.r.t to a given Lat/Long .  For ex- List of {42_-72,42,-75,43,-76} and a given point 42,-71

The Point 42,-72 is the nearest to 42,-71, hence output => 42,-72.

答:
I would start by creating a method that can get the distance between two points. If we consider that in any right triangle, a^2 + b^2 = c^2, and the distance from point P1 to point P2 is c, then we can use this formula to get the distance between two points since we know their X and Y coordinates. The distance a is the difference between P2.X and P1.X, and the distance b is the difference between P2.Y and P1.Y:

```<code>private static double GetDistance(Point a, Point b)
{
    return Math.Sqrt(Math.Pow(b.X - a.X, 2) + Math.Pow(b.Y - a.Y, 2));
}
</code>```

Then we can create a method that takes in a target point and a list of candidate points and returns the candidate which is the shortest distance from the target:

```<code>private static Point GetClosestPoint(Point target, List<Point> candidates)
{
    if (candidates == null) throw new ArgumentNullException(nameof(candidates));
    if (!candidates.Any()) throw new ArgumentException("The candidates list is empty.");

    var minDistance = double.MaxValue;
    var closestPoint = new Point();

    foreach (var candidate in candidates)
    {
        var distance = GetDistance(target, candidate);
        if (distance > minDistance) continue;
        minDistance = distance;
        closestPoint = candidate;
    }

    return closestPoint;
}
</code>```

Body:
I would start by creating a method that can get the distance between two points. If we consider that in any right triangle, a^2 + b^2 = c^2, and the distance from point P1 to point P2 is c, then we can use this formula to get the distance between two points since we know their X and Y coordinates. The distance a is the difference between P2.X and P1.X, and the distance b is the difference between P2.Y and P1.Y:

private static double GetDistance(Point a, Point b)
{
    return Math.Sqrt(Math.Pow(b.X - a.X, 2) + Math.Pow(b.Y - a.Y, 2));
}

Then we can create a method that takes in a target point and a list of candidate points and returns the candidate which is the shortest distance from the target:

private static Point GetClosestPoint(Point target, List<Point> candidates)
{
    if (candidates == null) throw new ArgumentNullException(nameof(candidates));
    if (!candidates.Any()) throw new ArgumentException("The candidates list is empty.");

    var minDistance = double.MaxValue;
    var closestPoint = new Point();

    foreach (var candidate in candidates)
    {
        var distance = GetDistance(target, candidate);
        if (distance > minDistance) continue;
        minDistance = distance;
        closestPoint = candidate;
    }

    return closestPoint;
}


问:
C++ linkedList head returns NULL even though list is not empty
I am trying to implement the pop function of a linked list in C++. My Node and Linked List classes look like this:

```<code>//Node class
template <class T>
class Node{
    public:
        T data;
        Node<T> *next;

        Node(T data, Node<T> *next);
        ~Node();
};

template <class T>
Node<T>::Node(T data, Node<T> *next){
    this->next = next;
    this->data = data;
}

template <class T>
Node<T>::~Node(){
    delete this;
}

//LinkedList class
template <class T>
class  LinkedList{
    public:
        //fields
        Node<T> *head;
        int size;

        //methods
        LinkedList();
        void push(T data);
        T pop();
        void printList();

};

template <class T>
LinkedList<T>::LinkedList(){
    this->head = NULL;
    this->size = 0;
}

template <class T>
void LinkedList<T>::printList(){
    int i = 1;
    while(head){
        std::cout<<i<<": "<<head->data<<std::endl;
        head = head->next;
        i++;
    }
}

int main(){
    LinkedList<int> list;

    for (int i = 1; i < 6; ++i)
        list.push(i);

    list.printList();

    for (int j = 0; j < 3; ++j){
        int output=list.pop();
        printf("popped: %d\n", output);
    }

    list.printList();
    return 0;
}
</code>```

Below is my pop function. The problem is that this->head is returning NULL. hence I cannot change its value or access its data field. I used print statements to find out that this->head is returning NULL. How can I resolve this issue?

```<code>template <class T>
T LinkedList<T>::pop(){
    Node<T> *h = this->head;

    //if list is empty
    if (this->size==0){
        return 0;
    }

    //if list has only one node
    if (this->size==1){
        T ret = h->data;
        this->head = NULL;
        this->size --;
        return ret;
    }

    //if list has multiple nodes
    else{
        T ret = this->head->data;
        this -> head = h->next;
        return ret;
    }

    h.~Node<T>();

}
</code>```

Below if my push function. I have tested this function and it works fine, but please let me know if it is not handling node pointers properly.

```<code>template <class T>
void LinkedList<T>::push(T data){
    Node<T> *n = new Node<T>(data, this->head);
    this->head = n;
    this->size++;
}
</code>```

答:
```<code>template <class T>
Node<T>::~Node(){
    delete this;
}
</code>```

This is so very very wrong. You need to get rid of it completely.

More importantly, printList() is modifying head when it shouldn't be. That is why head is NULL when pop() is called. Use a local Node* variable to iterate the list:

```<code>template <class T>
void LinkedList<T>::printList(){
    int i = 1;
    Node<T> *n = head; // <-- here
    while(n){
        std::cout << i << ": " << n->data << std::endl;
        n = n->next;
        i++;
    }
}
</code>```

Also, pop() is not freeing nodes correctly (if at all), and not always decrementing size.  It should look more like this instead:

```<code>template <class T>
T LinkedList<T>::pop(){
    Node<T> *h = this->head;

    //if list is empty
    if (this->size==0){
        return T(); // <-- not 0! or throw an exception instead...
    }

    //if list has only one node
    if (this->size==1){
        T ret = h->data;
        this->head = NULL;
        this->size--;
        delete h; // <-- add this!
        return ret;
    }

    //if list has multiple nodes

    T ret = this->head->data;
    this->head = h->next;
    this->size--; // <-- add this!

    delete h; // <-- not h.~Node<T>()!

    return ret; // <-- moved down here!
}
</code>```

Or simpler, this (no need to handle the size==1 case separately):

```<code>template <class T>
T LinkedList<T>::pop(){
    Node<T> *h = this->head;

    //if list is empty
    if (!h){
        return T();
    }

    //if list has any nodes

    T ret = h->data;
    this->head = h->next;
    this->size--;
    delete h;

    return ret;
}
</code>```

Body:
I am trying to implement the pop function of a linked list in C++. My Node and Linked List classes look like this:

//Node class
template <class T>
class Node{
    public:
        T data;
        Node<T> *next;

        Node(T data, Node<T> *next);
        ~Node();
};

template <class T>
Node<T>::Node(T data, Node<T> *next){
    this->next = next;
    this->data = data;
}

template <class T>
Node<T>::~Node(){
    delete this;
}

//LinkedList class
template <class T>
class  LinkedList{
    public:
        //fields
        Node<T> *head;
        int size;

        //methods
        LinkedList();
        void push(T data);
        T pop();
        void printList();

};

template <class T>
LinkedList<T>::LinkedList(){
    this->head = NULL;
    this->size = 0;
}

template <class T>
void LinkedList<T>::printList(){
    int i = 1;
    while(head){
        std::cout<<i<<": "<data<<std::endl;
        head = head->next;
        i++;
    }
}

int main(){
    LinkedList<int> list;

    for (int i = 1; i < 6; ++i)
        list.push(i);

    list.printList();

    for (int j = 0; j < 3; ++j){
        int output=list.pop();
        printf("popped: %d\n", output);
    }

    list.printList();
    return 0;
}

Below is my pop function. The problem is that this->head is returning NULL. hence I cannot change its value or access its data field. I used print statements to find out that this->head is returning NULL. How can I resolve this issue?

template <class T>
T LinkedList<T>::pop(){
    Node<T> *h = this->head;

    //if list is empty
    if (this->size==0){
        return 0;
    }

    //if list has only one node
    if (this->size==1){
        T ret = h->data;
        this->head = NULL;
        this->size --;
        return ret;
    }

    //if list has multiple nodes
    else{
        T ret = this->head->data;
        this -> head = h->next;
        return ret;
    }

    h.~Node<T>();

}

Below if my push function. I have tested this function and it works fine, but please let me know if it is not handling node pointers properly.

template <class T>
void LinkedList<T>::push(T data){
    Node<T> *n = new Node<T>(data, this->head);
    this->head = n;
    this->size++;
}

Body:
template <class T>
Node<T>::~Node(){
    delete this;
}

This is so very very wrong. You need to get rid of it completely.

More importantly, printList() is modifying head when it shouldn't be. That is why head is NULL when pop() is called. Use a local Node* variable to iterate the list:

template <class T>
void LinkedList<T>::printList(){
    int i = 1;
    Node<T> *n = head; // <-- here
    while(n){
        std::cout << i << ": " << n->data << std::endl;
        n = n->next;
        i++;
    }
}

Also, pop() is not freeing nodes correctly (if at all), and not always decrementing size.  It should look more like this instead:

template <class T>
T LinkedList<T>::pop(){
    Node<T> *h = this->head;

    //if list is empty
    if (this->size==0){
        return T(); // <-- not 0! or throw an exception instead...
    }

    //if list has only one node
    if (this->size==1){
        T ret = h->data;
        this->head = NULL;
        this->size--;
        delete h; // <-- add this!
        return ret;
    }

    //if list has multiple nodes

    T ret = this->head->data;
    this->head = h->next;
    this->size--; // <-- add this!

    delete h; // <-- not h.~Node<T>()!

    return ret; // <-- moved down here!
}

Or simpler, this (no need to handle the size==1 case separately):

template <class T>
T LinkedList<T>::pop(){
    Node<T> *h = this->head;

    //if list is empty
    if (!h){
        return T();
    }

    //if list has any nodes

    T ret = h->data;
    this->head = h->next;
    this->size--;
    delete h;

    return ret;
}


问:
Programming in Swift on Linux
I would like to prepare the environment for working with Swift on Ubuntu 16.04.

I installed Swift and Atom editor.
I installed the Script package, which allows me to run code from the Atom editor.

Generally it is nice when I compile and run one file (Ctrl+Shift+B shortcut).
The problem is when I would like to build a project composed of several files.
Classes defined in the other files (not the one I compile) are not visible (compilation error).

Is it possible to configure the editor to compile and run the entire project?
How to import external library, eg ObjectMapper ?

答:
For dependencies, you should use Swift Package Manager.

You can check how Vapor is built - it is prepared for build apps for Ubuntu too.

Also, Vapor toolbox would help you with other projects
https://docs.vapor.codes/2.0/getting-started/install-on-ubuntu/

Title: Programming in Swift on Linux


问:
Find and extract a number from a string
I have a requirement to find and extract a number contained within a string.

For example, from these strings:

```<code>string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
</code>```

How can I do this?

答:
go through the string and use Char.IsDigit

```<code>string a = "str123";
string b = string.Empty;
int val;

for (int i=0; i< a.Length; i++)
{
    if (Char.IsDigit(a[i]))
        b += a[i];
}

if (b.Length>0)
    val = int.Parse(b);
</code>```

Title: Find and extract a number from a string

Body:
I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"

How can I do this?

Body:
go through the string and use Char.IsDigit

string a = "str123";
string b = string.Empty;
int val;

for (int i=0; i< a.Length; i++)
{
    if (Char.IsDigit(a[i]))
        b += a[i];
}

if (b.Length>0)
    val = int.Parse(b);


问:
Generate random numbers from exponential distribution and model using python
My goal is to create a dataset of random points whose histogram looks like an exponential decay function and then plot an exponential decay function through those points.

First I tried to create a series of random numbers (but did not do so successfully since these should be points, not numbers) from an exponential distribution.

```<code>from pylab import *
from scipy.optimize import curve_fit
import random
import numpy as np
import pandas as pd

testx = pd.DataFrame(range(10)).astype(float)
testx = testx[0]

for i in range(1,11):
   x = random.expovariate(15) # rate = 15 arrivals per second
   data[i] = [x]

testy = pd.DataFrame(data).T.astype(float)
testy = testy[0]; testy

plot(testx, testy, 'ko')
</code>```

The result could look something like this.

And then I define a function to draw a line through my points:

```<code>def func(x, a, e):
return a*np.exp(-a*x)+e

popt, pcov = curve_fit(f=func, xdata=testx, ydata=testy, p0 = None, sigma = None)

print popt # parameters
print pcov # covariance

plot(testx, testy, 'ko')

xx = np.linspace(0, 15, 1000)
plot(xx, func(xx,*popt))

plt.show()
</code>```

What I'm looking for is: (1) a more elegant way to create an array of random numbers from an exponential (decay) distribution and (2) how to test that my function is indeed going through the data points.

答:
I think you are actually asking about a regression problem, which is what Praveen was suggesting.

You have a bog standard exponential decay that arrives at the y-axis at about y=0.27. Its equation is therefore y = 0.27*exp(-0.27*x). I can model gaussian error around the values of this function and plot the result using the following code.

```<code>import matplotlib.pyplot as plt
from math import exp
from scipy.stats import norm

x = range(0, 16)
Y = [0.27*exp(-0.27*_) for _ in x]
error = norm.rvs(0, scale=0.05, size=9)
simulated_data = [max(0, y+e) for (y,e) in zip(Y[:9],error)]

plt.plot(x, Y, 'b-')
plt.plot(x[:9], simulated_data, 'r.')
plt.show()

print (x[:9])
print (simulated_data)
</code>```

Here's the plot. Notice that I save the output values for subsequent use.

Now I can calculate the nonlinear regression of the exponential decay values, contaminated with noise, on the independent variable, which is what curve_fit does.

```<code>from math import exp
from scipy.optimize import curve_fit
import numpy as np

def model(x, p):
    return p*np.exp(-p*x)

x = list(range(9))
Y = [0.22219001972988275, 0.15537454187341937, 0.15864069451825827, 0.056411162886672819, 0.037398831058143338, 0.10278251869912845, 0.03984605649260467, 0.0035360087611421981, 0.075855255999424692]

popt, pcov = curve_fit(model, x, Y)
print (popt[0])
print (pcov)
</code>```

The bonus is that, not only does curve_fit calculate an estimate for the parameter — 0.207962159793 — it also offers an estimate for this estimate's variance — 0.00086071 — as an element of pcov. This would appear to be a fairly small value, given the small sample size.

Here's how to calculate the residuals. Notice that each residual is the difference between the data value and the value estimated from x using the parameter estimate.

```<code>residuals = [y-model(_, popt[0]) for (y, _) in zip(Y, x)]
print (residuals)
</code>```

If you wanted to further 'test that my function is indeed going through the data points' then I would suggest looking for patterns in the residuals. But discussions like this might be beyond what's welcomed on stackoverflow: Q-Q and P-P plots, plots of residuals vs y or x, and so on.

Body:
My goal is to create a dataset of random points whose histogram looks like an exponential decay function and then plot an exponential decay function through those points.

First I tried to create a series of random numbers (but did not do so successfully since these should be points, not numbers) from an exponential distribution.

from pylab import *
from scipy.optimize import curve_fit
import random
import numpy as np
import pandas as pd

testx = pd.DataFrame(range(10)).astype(float)
testx = testx[0]

for i in range(1,11):
   x = random.expovariate(15) # rate = 15 arrivals per second
   data[i] = [x]

testy = pd.DataFrame(data).T.astype(float)
testy = testy[0]; testy

plot(testx, testy, 'ko')

The result could look something like this.

And then I define a function to draw a line through my points:

def func(x, a, e):
return a*np.exp(-a*x)+e

popt, pcov = curve_fit(f=func, xdata=testx, ydata=testy, p0 = None, sigma = None)

print popt # parameters
print pcov # covariance

plot(testx, testy, 'ko')

xx = np.linspace(0, 15, 1000)
plot(xx, func(xx,*popt))

plt.show()

What I'm looking for is: (1) a more elegant way to create an array of random numbers from an exponential (decay) distribution and (2) how to test that my function is indeed going through the data points.

Body:
I think you are actually asking about a regression problem, which is what Praveen was suggesting.

You have a bog standard exponential decay that arrives at the y-axis at about y=0.27. Its equation is therefore y = 0.27*exp(-0.27*x). I can model gaussian error around the values of this function and plot the result using the following code.

import matplotlib.pyplot as plt
from math import exp
from scipy.stats import norm

x = range(0, 16)
Y = [0.27*exp(-0.27*_) for _ in x]
error = norm.rvs(0, scale=0.05, size=9)
simulated_data = [max(0, y+e) for (y,e) in zip(Y[:9],error)]

plt.plot(x, Y, 'b-')
plt.plot(x[:9], simulated_data, 'r.')
plt.show()

print (x[:9])
print (simulated_data)

Here's the plot. Notice that I save the output values for subsequent use.

Now I can calculate the nonlinear regression of the exponential decay values, contaminated with noise, on the independent variable, which is what curve_fit does.

from math import exp
from scipy.optimize import curve_fit
import numpy as np

def model(x, p):
    return p*np.exp(-p*x)

x = list(range(9))
Y = [0.22219001972988275, 0.15537454187341937, 0.15864069451825827, 0.056411162886672819, 0.037398831058143338, 0.10278251869912845, 0.03984605649260467, 0.0035360087611421981, 0.075855255999424692]

popt, pcov = curve_fit(model, x, Y)
print (popt[0])
print (pcov)

The bonus is that, not only does curve_fit calculate an estimate for the parameter — 0.207962159793 — it also offers an estimate for this estimate's variance — 0.00086071 — as an element of pcov. This would appear to be a fairly small value, given the small sample size.

Here's how to calculate the residuals. Notice that each residual is the difference between the data value and the value estimated from x using the parameter estimate.

residuals = [y-model(_, popt[0]) for (y, _) in zip(Y, x)]
print (residuals)

If you wanted to further 'test that my function is indeed going through the data points' then I would suggest looking for patterns in the residuals. But discussions like this might be beyond what's welcomed on stackoverflow: Q-Q and P-P plots, plots of residuals vs y or x, and so on.


问:
Inputting as a Char Array
I am trying to get input as a character array and manipulate it. For example this is what I have. But I just started arrays and I am confused getting confused on how I should be storing the char array.

```<code>   void getMessage(char message[CHARACTERS])
   {
        int i = 0;
        cout << "Enter message: ";
        for (i = 0; i < CHARACTERS; i++)
        {
            cin >> message[i];
            if (message[i] == NULL)
                break;
        }
            cout << "The message you entered was:" << endl << message[i] << endl;
   }
</code>```

Characters is equal to the constant 100 since I do not know the size of the array, it is based off of user input. When I try to get the array to output it doesn't.

答:
So putting all that together, the obvious Modern C++ way to do what you want is:</p>

```<code>#include <cstddef>
#include <iostream>
#include <memory>

using std::cout;
using std::flush;
using std::endl;
using std::cin;
using std::size_t;

template <size_t CHARACTERS>
void getMessage(char(& message)[CHARACTERS]) {
  int i = 0;
  cout << "Enter message: " << flush;

  for (i = 0; i < CHARACTERS; i++) {
    if (!cin.get(message[i])
      || message[i] == '\0'
      || message[i] == '\r'
      || message[i] == '\n') {
      message[i] = '\0';
      break;
    }
  }
  cout << "The message you entered was:" << endl << message << endl;
}

int main() {
  char message[200];
  getMessage(message);
  return EXIT_SUCCESS;
}
</code>```

Title: Inputting as a Char Array

Body:
I am trying to get input as a character array and manipulate it. For example this is what I have. But I just started arrays and I am confused getting confused on how I should be storing the char array.

   void getMessage(char message[CHARACTERS])
   {
        int i = 0;
        cout << "Enter message: ";
        for (i = 0; i < CHARACTERS; i++)
        {
            cin >> message[i];
            if (message[i] == NULL)
                break;
        }
            cout << "The message you entered was:" << endl << message[i] << endl;
   }

Characters is equal to the constant 100 since I do not know the size of the array, it is based off of user input. When I try to get the array to output it doesn't.

Body:
So putting all that together, the obvious Modern C++ way to do what you want is:

#include <cstddef>
#include <iostream>
#include <memory>

using std::cout;
using std::flush;
using std::endl;
using std::cin;
using std::size_t;

template <size_t CHARACTERS>
void getMessage(char(& message)[CHARACTERS]) {
  int i = 0;
  cout << "Enter message: " << flush;

  for (i = 0; i < CHARACTERS; i++) {
    if (!cin.get(message[i])
      || message[i] == '\0'
      || message[i] == '\r'
      || message[i] == '\n') {
      message[i] = '\0';
      break;
    }
  }
  cout << "The message you entered was:" << endl << message << endl;
}

int main() {
  char message[200];
  getMessage(message);
  return EXIT_SUCCESS;
}


问:
S3 upload fails in production (Python)
I'm trying to upload an XML file to S3 in my Django app.

I have tried tinys3, boto3, and boto original flavor.

tinys3 worked like a charm in localhost, but if I'm even importing the file when I load it with Elastic Beanstalk I get an error much like what I get from boto3 when I do the same (except boto3 lets me get as far as launching the server and initiating the xml upload from the client):

```<code>invalid syntax (_base.py, line 381)
</code>```

With the tinys3 imported, I get this error (again, only on elastic beanstalk):

```<code>[Fri Nov 17 00:51:28.918531 2017] [:error] [pid 32767]   File "/opt/python/current/app/user_package/views.py", line 22, in <module>
[Fri Nov 17 00:51:28.918533 2017] [:error] [pid 32767]     import tinys3
[Fri Nov 17 00:51:28.918534 2017] [:error] [pid 32767]   File "/opt/python/run/venv/lib/python3.4/site-packages/tinys3/__init__.py", line 4, in <module>
[Fri Nov 17 00:51:28.918536 2017] [:error] [pid 32767]     from .pool import Pool
[Fri Nov 17 00:51:28.918537 2017] [:error] [pid 32767]   File "/opt/python/run/venv/lib/python3.4/site-packages/tinys3/pool.py", line 4, in <module>
[Fri Nov 17 00:51:28.918539 2017] [:error] [pid 32767]     from concurrent.futures import ThreadPoolExecutor, as_completed
[Fri Nov 17 00:51:28.918540 2017] [:error] [pid 32767]   File "/opt/python/run/venv/lib/python3.4/site-packages/concurrent/futures/__init__.py", line 8, in <module>
[Fri Nov 17 00:51:28.918542 2017] [:error] [pid 32767]     from concurrent.futures._base import (FIRST_COMPLETED,
[Fri Nov 17 00:51:28.918543 2017] [:error] [pid 32767]   File "/opt/python/run/venv/lib/python3.4/site-packages/concurrent/futures/_base.py", line 381
[Fri Nov 17 00:51:28.918545 2017] [:error] [pid 32767]     raise exception_type, self._exception, self._traceback
[Fri Nov 17 00:51:28.918547 2017] [:error] [pid 32767]                         ^
[Fri Nov 17 00:51:28.918549 2017] [:error] [pid 32767] SyntaxError: invalid syntax
</code>```

Boto original doesn't work at all.

I definitely need the ability to upload XML's dynamically to S3.
No idea why this won't work.

答:
Works for me with AWS Command line tools

aws s3 cp ~/myFiles/file.xml < s3 URI > --recursive

Title: S3 upload fails in production (Python)

Body:
I'm trying to upload an XML file to S3 in my Django app.

I have tried tinys3, boto3, and boto original flavor.

tinys3 worked like a charm in localhost, but if I'm even importing the file when I load it with Elastic Beanstalk I get an error much like what I get from boto3 when I do the same (except boto3 lets me get as far as launching the server and initiating the xml upload from the client):

invalid syntax (_base.py, line 381)

With the tinys3 imported, I get this error (again, only on elastic beanstalk):

[Fri Nov 17 00:51:28.918531 2017] [:error] [pid 32767]   File "/opt/python/current/app/user_package/views.py", line 22, in <module>
[Fri Nov 17 00:51:28.918533 2017] [:error] [pid 32767]     import tinys3
[Fri Nov 17 00:51:28.918534 2017] [:error] [pid 32767]   File "/opt/python/run/venv/lib/python3.4/site-packages/tinys3/__init__.py", line 4, in <module>
[Fri Nov 17 00:51:28.918536 2017] [:error] [pid 32767]     from .pool import Pool
[Fri Nov 17 00:51:28.918537 2017] [:error] [pid 32767]   File "/opt/python/run/venv/lib/python3.4/site-packages/tinys3/pool.py", line 4, in <module>
[Fri Nov 17 00:51:28.918539 2017] [:error] [pid 32767]     from concurrent.futures import ThreadPoolExecutor, as_completed
[Fri Nov 17 00:51:28.918540 2017] [:error] [pid 32767]   File "/opt/python/run/venv/lib/python3.4/site-packages/concurrent/futures/__init__.py", line 8, in <module>
[Fri Nov 17 00:51:28.918542 2017] [:error] [pid 32767]     from concurrent.futures._base import (FIRST_COMPLETED,
[Fri Nov 17 00:51:28.918543 2017] [:error] [pid 32767]   File "/opt/python/run/venv/lib/python3.4/site-packages/concurrent/futures/_base.py", line 381
[Fri Nov 17 00:51:28.918545 2017] [:error] [pid 32767]     raise exception_type, self._exception, self._traceback
[Fri Nov 17 00:51:28.918547 2017] [:error] [pid 32767]                         ^
[Fri Nov 17 00:51:28.918549 2017] [:error] [pid 32767] SyntaxError: invalid syntax

Boto original doesn't work at all.

I definitely need the ability to upload XML's dynamically to S3.
No idea why this won't work.