问:
Entity Framework Code-First - Defining relationships with MembershipUser
I'm trying to understand the best way to define my POCO classes to be able to use Entity Framework code-first feature.

I want to define some foreign key relations in my classes, between the user and also between the classes themselves. For example consider the following 3 classes:

```<code>Public class Job
{
    public int JobID {get; set;}
    public string JobTitle {get; set;}
    public virtual ICollection<Resume> Resumes {get; set;} // Is this correct at all? How to access all resumes for a certain job? (many-to-many relationship between Job and Employee)
}

Public class Resume
{
    public int EmployeeID {get; set;} // or should it be: public virtual Employee EmployeePerson?
    public int JobID {get; set;} // or should it be: public virtual Job UserJob?
    public DateTime EmploymentDate {get; set;}
}

public class Employee
{
    public int EmployeeID {get; set;}
    public int UserID{ger; set;} // or should it be: public virtual MembershipUser User?
    public ICollection<Resume> Resumes {get; set;} // Is this correct at all?
}
</code>```

The user is a Membership user which is in System.Web.Security which is being authenticated by FormsAuthentication or ActiveDirectoryAuthentication.  The questions are mentioned in the code (as comments). But for clarification:

Should I define the objects in relations and use .Include every time I need them or is it better to store the ID of the objects and try to get the data from that ID every time I need to? Should I use a different approach when dealing with MembershipUser class instead of my defined classes?

What's other uses of virtual apart from enabling lazy loading? Where should I avoid it and where should I use it?

Thank you.

UPDATE: I have just tested to define Employee with the ublic virtual MembershipUser User definition. The result was 4 added columns in my table:

User_Email,

User_Comment,

User_IsApproved,

User_LastLoginDate,

User_LastActivityDate

Nothing unique to the user (User_Email is defined as nullable). So If you want to have user in you classes, write a wrapper for MembershipUser or just store UserID.

Thank you Ladislav and Sergi.

答:
I would recommend declaring the Foreign Keys as navigation properties, that way you can always access the related property directly without having to retrieve it explicitly from the database yourself (it will be lazy loaded).

So your model would look like:

```<code>public class Resume
{
    public int ID {get; set;}
    // or should it be: public virtual Employee EmployeePerson?
    // --> yep, easier for you, innit?
    public Employee Employee {get; set;}

    // or should it be: public virtual Job UserJob? --> yep :)
    public virtual Job Job {get; set;}

    public DateTime EmploymentDate {get; set;}
}

public class Employee
{
    public int EmployeeID {get; set;}

    // or should it be: public virtual MembershipUser User?
    // --> yes, as an approach, but read on for clarification.
    public virtual MembershipUser User {get; set;}

    // Is this correct at all? ---> needs to be declared as virtual
    public virtual ICollection<Resume> Resumes {get; set;}
}
</code>```

Your Job class is OK as far as I can tell.

To be clear, it will work as well using it as you had it initially, but you'll need to explicitly mark the properties with the ForeignKeyAttribute, which isn't necessary if you're willing to give up a tiny bit of control on how FK's are named in your database.

One remark about the MembershipUser navigation property: I'm afraid you'll need to write a wrapper for the MembershipUser class because as far as I can recall it doesn't have a default contructor and so EF will probably not be able to instantiate it for you on lazy loading.

About the effects of marking a property as virtual, you might want to take a look at this question: What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First?

Body:
I'm trying to understand the best way to define my POCO classes to be able to use Entity Framework code-first feature.

I want to define some foreign key relations in my classes, between the user and also between the classes themselves. For example consider the following 3 classes:

Public class Job
{
    public int JobID {get; set;}
    public string JobTitle {get; set;}
    public virtual ICollection<Resume> Resumes {get; set;} // Is this correct at all? How to access all resumes for a certain job? (many-to-many relationship between Job and Employee)
}

Public class Resume
{
    public int EmployeeID {get; set;} // or should it be: public virtual Employee EmployeePerson?
    public int JobID {get; set;} // or should it be: public virtual Job UserJob?
    public DateTime EmploymentDate {get; set;}
}

public class Employee
{
    public int EmployeeID {get; set;}
    public int UserID{ger; set;} // or should it be: public virtual MembershipUser User?
    public ICollection<Resume> Resumes {get; set;} // Is this correct at all?
}

The user is a Membership user which is in System.Web.Security which is being authenticated by FormsAuthentication or ActiveDirectoryAuthentication.  The questions are mentioned in the code (as comments). But for clarification:

Should I define the objects in relations and use .Include every time I need them or is it better to store the ID of the objects and try to get the data from that ID every time I need to? Should I use a different approach when dealing with MembershipUser class instead of my defined classes?

What's other uses of virtual apart from enabling lazy loading? Where should I avoid it and where should I use it?

Thank you.

UPDATE: I have just tested to define Employee with the ublic virtual MembershipUser User definition. The result was 4 added columns in my table:

User_Email,

User_Comment,

User_IsApproved,

User_LastLoginDate,

User_LastActivityDate

Nothing unique to the user (User_Email is defined as nullable). So If you want to have user in you classes, write a wrapper for MembershipUser or just store UserID.

Thank you Ladislav and Sergi.

Body:
I would recommend declaring the Foreign Keys as navigation properties, that way you can always access the related property directly without having to retrieve it explicitly from the database yourself (it will be lazy loaded).

So your model would look like:

public class Resume
{
    public int ID {get; set;}
    // or should it be: public virtual Employee EmployeePerson?
    // --> yep, easier for you, innit?
    public Employee Employee {get; set;}

    // or should it be: public virtual Job UserJob? --> yep :)
    public virtual Job Job {get; set;}

    public DateTime EmploymentDate {get; set;}
}

public class Employee
{
    public int EmployeeID {get; set;}

    // or should it be: public virtual MembershipUser User?
    // --> yes, as an approach, but read on for clarification.
    public virtual MembershipUser User {get; set;}

    // Is this correct at all? ---> needs to be declared as virtual
    public virtual ICollection<Resume> Resumes {get; set;}
}

Your Job class is OK as far as I can tell.

To be clear, it will work as well using it as you had it initially, but you'll need to explicitly mark the properties with the ForeignKeyAttribute, which isn't necessary if you're willing to give up a tiny bit of control on how FK's are named in your database.

One remark about the MembershipUser navigation property: I'm afraid you'll need to write a wrapper for the MembershipUser class because as far as I can recall it doesn't have a default contructor and so EF will probably not be able to instantiate it for you on lazy loading.

About the effects of marking a property as virtual, you might want to take a look at this question: What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First?


来源: stackexchange

问:
MongoDB track which user mande changes
We're running a microservice architecture with multiple systems having access to shared collections in a MongoDB (yes, questionable design, but we're in the transition to get out of this.)

We're trying to find a way to track which change within the oplog was done by which "user"/service (each microservice is using different credentials) actually made this change. If we find any invalid changes in our DB this would make it super easy to find out which system is bugging out.

Any ideas?

The only ones I came up with so far would always have to change client side code, which I would like to avoid.

答:
If you can maintain a column editors such that every operation would have an { $addToSet: { editors: { by: userId, at: new Date() } } }, then the corresponding oplog entries would have this information that you can cross-check with your access control list.

Note: you might have to change inserts to upserts, or account for another case: .insert({ ..., editors: [{ by: userId, at: new Date() }] })

ContentLicense: CC BY-SA 4.0

Title: MongoDB track which user mande changes


问:
Get FirstName based on Alias Outlook search in vba
I able to do reverse (Get Alias based on Name) by following code: Is it possible to get Name based on Alias ? (I would like to run it in excel spreadsheet)

```<code>Public Sub GetUsers()

Dim olApp As Outlook.Application
    Set olApp = CreateObject("Outlook.Application")
Dim olNameSpace As Outlook.Namespace
    Set olNameSpace = olApp.GetNamespace("MAPI")
Dim olAddrList As Outlook.AddressList
    Set olAddrList = olNameSpace.AddressLists("Global Address List")
Dim oGal As Outlook.AddressEntries
    Set oGal = olAddrList.AddressEntries

Dim myAddrEntry As Outlook.AddressEntry
    Set myAddrEntry = olAddrList.AddressEntries("UserA")
Dim exchUser As Outlook.ExchangeUser
    Set exchUser = myAddrEntry.GetExchangeUser

MsgBox exchUser.Alias

End Sub
</code>```

Based on @Dmitry Streblechenko suggestion. Now problem resolved by following code:

```<code>Sub GetStaffName()

Dim str As String
    str = Sheets("Form").Range("StaffID").Value
Dim olApp As Outlook.Application
    Set olApp = CreateObject("Outlook.Application")
Dim olNameSpace As Outlook.Namespace
    Set olNameSpace = olApp.GetNamespace("MAPI")
Dim olRecipient As Outlook.Recipient
    Set olRecipient = olNameSpace.CreateRecipient(str)
Dim oEU As Outlook.ExchangeUser
Dim oEDL As Outlook.ExchangeDistributionList

olRecipient.Resolve
If olRecipient.Resolved Then
    Select Case olRecipient.AddressEntry.AddressEntryUserType
        Case OlAddressEntryUserType.olExchangeUserAddressEntry
            Set oEU = olRecipient.AddressEntry.GetExchangeUser
                If Not (oEU Is Nothing) Then
                    Debug.Print oEU.PrimarySmtpAddress
                End If
            Case OlAddressEntryUserType.olExchangeDistributionListAddressEntry
                Set oEDL = olRecipient.AddressEntry.GetExchangeDistributionList
                    If Not (oEDL Is Nothing) Then
                        Debug.Print oEDL.PrimarySmtpAddress
                    End If
        End Select

    Sheets("Form").Range("StaffName").Value = oEU

End If

End Sub
</code>```

答:
```<code>Public Function GetNameFromAlias2(sAlias As String) As String

    Dim oAddressEntry As Outlook.AddressEntry

    On Error Resume Next

    With New Outlook.Application
     For Each oAddressEntry In .Session.AddressLists("Global Address List").AddressEntries
      If oAddressEntry.Class = Outlook.OlObjectClass.olAddressEntry Then
       If oAddressEntry.GetExchangeUser.Alias = sAlias Then
        GetNameFromAlias2 = oAddressEntry.GetExchangeUser.Alias
        Exit For
       End If
      End If
     Next oAddressEntry
    End With

End Function
</code>```

<p>@Bas Verlaat, the first function works smoothly, but the second is exactly what I need. However, it's not giving the correct result, I get: 01_New Requests
on every cell.</p>

ContentLicense: CC BY-SA 3.0

Body:
I able to do reverse (Get Alias based on Name) by following code: Is it possible to get Name based on Alias ? (I would like to run it in excel spreadsheet)

Public Sub GetUsers()

Dim olApp As Outlook.Application
    Set olApp = CreateObject("Outlook.Application")
Dim olNameSpace As Outlook.Namespace
    Set olNameSpace = olApp.GetNamespace("MAPI")
Dim olAddrList As Outlook.AddressList
    Set olAddrList = olNameSpace.AddressLists("Global Address List")
Dim oGal As Outlook.AddressEntries
    Set oGal = olAddrList.AddressEntries

Dim myAddrEntry As Outlook.AddressEntry
    Set myAddrEntry = olAddrList.AddressEntries("UserA")
Dim exchUser As Outlook.ExchangeUser
    Set exchUser = myAddrEntry.GetExchangeUser

MsgBox exchUser.Alias

End Sub

Based on @Dmitry Streblechenko suggestion. Now problem resolved by following code:

Sub GetStaffName()

Dim str As String
    str = Sheets("Form").Range("StaffID").Value
Dim olApp As Outlook.Application
    Set olApp = CreateObject("Outlook.Application")
Dim olNameSpace As Outlook.Namespace
    Set olNameSpace = olApp.GetNamespace("MAPI")
Dim olRecipient As Outlook.Recipient
    Set olRecipient = olNameSpace.CreateRecipient(str)
Dim oEU As Outlook.ExchangeUser
Dim oEDL As Outlook.ExchangeDistributionList

olRecipient.Resolve
If olRecipient.Resolved Then
    Select Case olRecipient.AddressEntry.AddressEntryUserType
        Case OlAddressEntryUserType.olExchangeUserAddressEntry
            Set oEU = olRecipient.AddressEntry.GetExchangeUser
                If Not (oEU Is Nothing) Then
                    Debug.Print oEU.PrimarySmtpAddress
                End If
            Case OlAddressEntryUserType.olExchangeDistributionListAddressEntry
                Set oEDL = olRecipient.AddressEntry.GetExchangeDistributionList
                    If Not (oEDL Is Nothing) Then
                        Debug.Print oEDL.PrimarySmtpAddress
                    End If
        End Select

    Sheets("Form").Range("StaffName").Value = oEU

End If

End Sub

Body:
Public Function GetNameFromAlias2(sAlias As String) As String

    Dim oAddressEntry As Outlook.AddressEntry

    On Error Resume Next

    With New Outlook.Application
     For Each oAddressEntry In .Session.AddressLists("Global Address List").AddressEntries
      If oAddressEntry.Class = Outlook.OlObjectClass.olAddressEntry Then
       If oAddressEntry.GetExchangeUser.Alias = sAlias Then
        GetNameFromAlias2 = oAddressEntry.GetExchangeUser.Alias
        Exit For
       End If
      End If
     Next oAddressEntry
    End With

End Function

@Bas Verlaat, the first function works smoothly, but the second is exactly what I need. However, it's not giving the correct result, I get: 01_New Requests
on every cell.


问:
Call Django View from D3.js onclick event on Heatmap
Is there a way to invoke a Django view and pass it a parameter(s) from a D3.js onclick event handler associated with a heatmap? For my heatmap, I'm using the code found at the following:

https://www.d3-graph-gallery.com/graph/heatmap_style.html

Any help would be greatly appreciated. Thanks.

答:
This is javascript code, which makes HTTP request when click on rectangle. Use jquery library (I am using here, in this example $.ajax({}) is jQuery's function). You can use Javascript's XMLHttpRequest class also, to make AJAX call. You should just pass correct URL of Django's view. Also, use GET request for testing purposes to avoid CSRF Features of Django.

```<code><script>

        // set the dimensions and margins of the graph
        var margin = {top: 80, right: 25, bottom: 30, left: 40},
          width = 450 - margin.left - margin.right,
          height = 450 - margin.top - margin.bottom;

        // append the svg object to the body of the page
        var svg = d3.select("#my_dataviz")
        .append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
        .append("g")
          .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");

        //Read the data
        d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/heatmap_data.csv", function(data) {

          // Labels of row and columns -> unique identifier of the column called 'group' and 'variable'
          var myGroups = d3.map(data, function(d){return d.group;}).keys()
          var myVars = d3.map(data, function(d){return d.variable;}).keys()

          // Build X scales and axis:
          var x = d3.scaleBand()
            .range([ 0, width ])
            .domain(myGroups)
            .padding(0.05);
          svg.append("g")
            .style("font-size", 15)
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x).tickSize(0))
            .select(".domain").remove()

          // Build Y scales and axis:
          var y = d3.scaleBand()
            .range([ height, 0 ])
            .domain(myVars)
            .padding(0.05);
          svg.append("g")
            .style("font-size", 15)
            .call(d3.axisLeft(y).tickSize(0))
            .select(".domain").remove()

          // Build color scale
          var myColor = d3.scaleSequential()
            .interpolator(d3.interpolateInferno)
            .domain([1,100])

          // create a tooltip
          var tooltip = d3.select("#my_dataviz")
            .append("div")
            .style("opacity", 0)
            .attr("class", "tooltip")
            .style("background-color", "white")
            .style("border", "solid")
            .style("border-width", "2px")
            .style("border-radius", "5px")
            .style("padding", "5px")

          // Three function that change the tooltip when user hover / move / leave a cell
          var mouseover = function(d) {
            tooltip
              .style("opacity", 1)
            d3.select(this)
              .style("stroke", "black")
              .style("opacity", 1)
          }
          var mousemove = function(d) {
            tooltip
              .html("The exact value of<br>this cell is: " + d.value)
              .style("left", (d3.mouse(this)[0]+70) + "px")
              .style("top", (d3.mouse(this)[1]) + "px")
          }
          var mouseleave = function(d) {
            tooltip
              .style("opacity", 0)
            d3.select(this)
              .style("stroke", "none")
              .style("opacity", 0.8)
          }

          // add the squares
          svg.selectAll()
            .data(data, function(d) {return d.group+':'+d.variable;})
            .enter()
            .append("rect")
              .attr("x", function(d) { return x(d.group) })
              .attr("y", function(d) { return y(d.variable) })
              .attr("rx", 4)
              .attr("ry", 4)
              .attr("width", x.bandwidth() )
              .attr("height", y.bandwidth() )
              .style("fill", function(d) { return myColor(d.value)} )
              .style("stroke-width", 4)
              .style("stroke", "none")
              .style("opacity", 0.8)
            .on("mouseover", mouseover)
            .on("mousemove", mousemove)
            .on("mouseleave", mouseleave)
            .on("click", function(arg1, arg2, arg3) {
                console.log('clicked !!!');
                // make AJAX call now !
                $.ajax({
                    type: 'GET',
                    url: '<DJANGO_VIEW_URL_HERE>',
                    data: {'key1': 'val1', 'key2': 'val2'},
                    success: function(data) {
                        console.log('server returned status code 200');
                    },
                    error: function() {
                        console.log('problem on server during processing');
                    }
                });
            })
        })

        // Add title to graph
        svg.append("text")
                .attr("x", 0)
                .attr("y", -50)
                .attr("text-anchor", "left")
                .style("font-size", "22px")
                .text("A d3.js heatmap");

        // Add subtitle to graph
        svg.append("text")
                .attr("x", 0)
                .attr("y", -20)
                .attr("text-anchor", "left")
                .style("font-size", "14px")
                .style("fill", "grey")
                .style("max-width", 400)
                .text("A short description of the take-away message of this chart.");
        </script>
</code>```

Good luck.

Body:
This is javascript code, which makes HTTP request when click on rectangle. Use jquery library (I am using here, in this example $.ajax({}) is jQuery's function). You can use Javascript's XMLHttpRequest class also, to make AJAX call. You should just pass correct URL of Django's view. Also, use GET request for testing purposes to avoid CSRF Features of Django.

<script>

        // set the dimensions and margins of the graph
        var margin = {top: 80, right: 25, bottom: 30, left: 40},
          width = 450 - margin.left - margin.right,
          height = 450 - margin.top - margin.bottom;

        // append the svg object to the body of the page
        var svg = d3.select("#my_dataviz")
        .append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
        .append("g")
          .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");

        //Read the data
        d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/heatmap_data.csv", function(data) {

          // Labels of row and columns -> unique identifier of the column called 'group' and 'variable'
          var myGroups = d3.map(data, function(d){return d.group;}).keys()
          var myVars = d3.map(data, function(d){return d.variable;}).keys()

          // Build X scales and axis:
          var x = d3.scaleBand()
            .range([ 0, width ])
            .domain(myGroups)
            .padding(0.05);
          svg.append("g")
            .style("font-size", 15)
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x).tickSize(0))
            .select(".domain").remove()

          // Build Y scales and axis:
          var y = d3.scaleBand()
            .range([ height, 0 ])
            .domain(myVars)
            .padding(0.05);
          svg.append("g")
            .style("font-size", 15)
            .call(d3.axisLeft(y).tickSize(0))
            .select(".domain").remove()

          // Build color scale
          var myColor = d3.scaleSequential()
            .interpolator(d3.interpolateInferno)
            .domain([1,100])

          // create a tooltip
          var tooltip = d3.select("#my_dataviz")
            .append("div")
            .style("opacity", 0)
            .attr("class", "tooltip")
            .style("background-color", "white")
            .style("border", "solid")
            .style("border-width", "2px")
            .style("border-radius", "5px")
            .style("padding", "5px")

          // Three function that change the tooltip when user hover / move / leave a cell
          var mouseover = function(d) {
            tooltip
              .style("opacity", 1)
            d3.select(this)
              .style("stroke", "black")
              .style("opacity", 1)
          }
          var mousemove = function(d) {
            tooltip
              .html("The exact value of<br>this cell is: " + d.value)
              .style("left", (d3.mouse(this)[0]+70) + "px")
              .style("top", (d3.mouse(this)[1]) + "px")
          }
          var mouseleave = function(d) {
            tooltip
              .style("opacity", 0)
            d3.select(this)
              .style("stroke", "none")
              .style("opacity", 0.8)
          }

          // add the squares
          svg.selectAll()
            .data(data, function(d) {return d.group+':'+d.variable;})
            .enter()
            .append("rect")
              .attr("x", function(d) { return x(d.group) })
              .attr("y", function(d) { return y(d.variable) })
              .attr("rx", 4)
              .attr("ry", 4)
              .attr("width", x.bandwidth() )
              .attr("height", y.bandwidth() )
              .style("fill", function(d) { return myColor(d.value)} )
              .style("stroke-width", 4)
              .style("stroke", "none")
              .style("opacity", 0.8)
            .on("mouseover", mouseover)
            .on("mousemove", mousemove)
            .on("mouseleave", mouseleave)
            .on("click", function(arg1, arg2, arg3) {
                console.log('clicked !!!');
                // make AJAX call now !
                $.ajax({
                    type: 'GET',
                    url: '<DJANGO_VIEW_URL_HERE>',
                    data: {'key1': 'val1', 'key2': 'val2'},
                    success: function(data) {
                        console.log('server returned status code 200');
                    },
                    error: function() {
                        console.log('problem on server during processing');
                    }
                });
            })
        })

        // Add title to graph
        svg.append("text")
                .attr("x", 0)
                .attr("y", -50)
                .attr("text-anchor", "left")
                .style("font-size", "22px")
                .text("A d3.js heatmap");

        // Add subtitle to graph
        svg.append("text")
                .attr("x", 0)
                .attr("y", -20)
                .attr("text-anchor", "left")
                .style("font-size", "14px")
                .style("fill", "grey")
                .style("max-width", 400)
                .text("A short description of the take-away message of this chart.");
        </script>

Good luck.


问:
Leaflet map not showing on android
My leaflet map shows on desktop (with Firefox) but not on Android. There only controls and attribution are shown but no map and no marker, only gray.

I searched and read everything with the tags "[leaflet]" and "mobile" on stackoverflow but no suggested solution worked for me.

My code:

```<code><div id="karte_weitra" style="height: 400px; width: 96%; margin: 1em auto 1.2em;"></div>
<script type="text/javascript">
var mymap = L.map('karte_weitra').setView([48.7008, 15.09], 10);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
    maxZoom: 18
}).addTo(mymap);
var markerWeitra = L.marker([48.70071, 14.9038]).addTo(mymap);
markerWeitra.bindPopup("<strong>Jägerfabrik</strong><br />Wilhelm Szabo Str. 230<br />3970 Weitra, Austria", {
    minWidth: 170,
    className: "marker_weitra_popup",
    maxHeight: 60
});
</script>
</code>```

No error messages in konsole.

答:
The culprit was a CSS rule forcing images to 90% width on small displays.

Again thanks for the help especially the hint at MCVE with an useful link to "How to debug small programs".

Title: Leaflet map not showing on android

Body:
My leaflet map shows on desktop (with Firefox) but not on Android. There only controls and attribution are shown but no map and no marker, only gray.

I searched and read everything with the tags "[leaflet]" and "mobile" on stackoverflow but no suggested solution worked for me.

My code:

No error messages in konsole.


问:
Find duplicates in Laravel Eloquent
The following code I have on the controller is below.

public function add(Request $request)
{
    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = new ProjectResearchers();
    $researcherToProject->user_id = $request->userSelected;
    $researcherToProject->project_id = $request->projectSelected;
    $researcherToProject->created_at = Carbon::now();
    $researcherToProject->updated_at = Carbon::now();
    $researcherToProject->save();

    return new ProjectsResearchersResource($researcherToProject);
}
```

Should I make another validation or create a function?

Ex: I create a user id "5" with project id "13" and user id "2" with project id "17". If I try creating again a user id "5" with project id "13" it allows me, so I get two times the same data in the database. How do I avoid duplicate entries?

答:
change the following:

```<code>    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);
</code>```

to

```<code>    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required|unique:ProjectResearchers,project_id,NULL,id,user_id,'.$request->userSelected
    ]);
</code>```

this will work check if the combination of user-project already exists inthe table called ProjectResearchers.
for more information about the unique validation rule visit the Laravel Documentation.

Title: Find duplicates in Laravel Eloquent

Body:
The following code I have on the controller is below.

public function add(Request $request)
{
    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = new ProjectResearchers();
    $researcherToProject->user_id = $request->userSelected;
    $researcherToProject->project_id = $request->projectSelected;
    $researcherToProject->created_at = Carbon::now();
    $researcherToProject->updated_at = Carbon::now();
    $researcherToProject->save();

    return new ProjectsResearchersResource($researcherToProject);
}

Should I make another validation or create a function?

Ex: I create a user id "5" with project id "13" and user id "2" with project id "17". If I try creating again a user id "5" with project id "13" it allows me, so I get two times the same data in the database. How do I avoid duplicate entries?

Body:
change the following:

    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

to

    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required|unique:ProjectResearchers,project_id,NULL,id,user_id,'.$request->userSelected
    ]);

this will work check if the combination of user-project already exists inthe table called ProjectResearchers.
for more information about the unique validation rule visit the Laravel Documentation.


问:
How to update MediaPlayerElement's buffer in realtime?
I'm creating Twitch player using MediaPlayerElement and I want to update MediaPlayerElement's buffer in real-time but I don't know how.

I tried to do it like this:

public sealed partial class MainPage : Page
{
    MemoryStream stream = new MemoryStream(64 * 1024 * 1024);
    BinaryWriter writer;
    BinaryReader reader;

    Task task;

    public MainPage()
    {
        this.InitializeComponent();

        writer = new BinaryWriter(stream);
    }

    async void ReadTask()
    {
        while (true)
        {
            var bytes = reader.ReadBytes(1024 * 1024);

            if (bytes.Length == 0)
            {
                break;
            }

            writer.Write(bytes);

            // Do some delay to see progress of loading
            await Task.Delay(1000);
        }
    }

    private async void Page_Loaded(object sender, RoutedEventArgs e)
    {
        // I'm using file to speed up tests
        StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/output.ts"));

        reader = new BinaryReader(await file.OpenStreamForReadAsync());

        // Write few first bytes
        writer.Write(reader.ReadBytes(1024 * 1024));

        // Start task which will write more bytes soon
        task = new Task(ReadTask);
        task.Start();

        StreamMediaPlayer.AreTransportControlsEnabled = true;
        StreamMediaPlayer.AutoPlay = true;
        StreamMediaPlayer.MediaPlayer.Volume = 0;
        StreamMediaPlayer.Source = MediaSource.CreateFromStream(writer.BaseStream.AsRandomAccessStream(), "video/MP2T");
    }
}
```

<p>This code works but player displays only first 1 MB which I wrote before setting source even if <code>TaskRead()</code> write more bytes while playing video.</p>

<p>I also tried to use method <code>CreateFromStreamReference</code> instead of <code>CreateFromStream</code> like this:</p>

<pre class="lang-cs prettyprint-override"><code>var s = RandomAccessStreamReference.CreateFromStream(writer.BaseStream.AsRandomAccessStream());
StreamMediaPlayer.Source = MediaSource.CreateFromStreamReference(s, "video/MP2T");
</code>```

But this don't work at all.

Here is full project with video: https://drive.google.com/open?id=175Z5HzK3MJ-Dm4ZX84r81lWYtZ0ahSSS

答:
I figured this out.
I have to use MseStreamSource.

First I need to create MseStreamSource with event like this:

streamSource = new MseStreamSource();
streamSource.Opened += (_, __) =>
{
    if (buffer is null)
    {
        // it will create buffer where I can write data
        buffer = streamSource.AddSourceBuffer("video/MP2T");
        buffer.Mode = MseAppendMode.Sequence;
    }
};
```

<p>Then set the source: </p>

<pre class="lang-cs prettyprint-override"><code>StreamMediaPlayer.Source = MediaSource.CreateFromMseStreamSource(streamSource);
</code>```

And if I want to add video I have to do it like this:

buffer.AppendBuffer(reader.ReadBytes(20 * 1024 * 1024).AsBuffer());
```

I have to make sure that buffer is not updating. This information provides IsUpdating property.

Body:
I'm creating Twitch player using MediaPlayerElement and I want to update MediaPlayerElement's buffer in real-time but I don't know how.

I tried to do it like this:

public sealed partial class MainPage : Page
{
    MemoryStream stream = new MemoryStream(64 * 1024 * 1024);
    BinaryWriter writer;
    BinaryReader reader;

    Task task;

    public MainPage()
    {
        this.InitializeComponent();

        writer = new BinaryWriter(stream);
    }

    async void ReadTask()
    {
        while (true)
        {
            var bytes = reader.ReadBytes(1024 * 1024);

            if (bytes.Length == 0)
            {
                break;
            }

            writer.Write(bytes);

            // Do some delay to see progress of loading
            await Task.Delay(1000);
        }
    }

    private async void Page_Loaded(object sender, RoutedEventArgs e)
    {
        // I'm using file to speed up tests
        StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/output.ts"));

        reader = new BinaryReader(await file.OpenStreamForReadAsync());

        // Write few first bytes
        writer.Write(reader.ReadBytes(1024 * 1024));

        // Start task which will write more bytes soon
        task = new Task(ReadTask);
        task.Start();

        StreamMediaPlayer.AreTransportControlsEnabled = true;
        StreamMediaPlayer.AutoPlay = true;
        StreamMediaPlayer.MediaPlayer.Volume = 0;
        StreamMediaPlayer.Source = MediaSource.CreateFromStream(writer.BaseStream.AsRandomAccessStream(), "video/MP2T");
    }
}

This code works but player displays only first 1 MB which I wrote before setting source even if TaskRead() write more bytes while playing video.

I also tried to use method CreateFromStreamReference instead of CreateFromStream like this:

var s = RandomAccessStreamReference.CreateFromStream(writer.BaseStream.AsRandomAccessStream());
StreamMediaPlayer.Source = MediaSource.CreateFromStreamReference(s, "video/MP2T");

But this don't work at all.

Here is full project with video: https://drive.google.com/open?id=175Z5HzK3MJ-Dm4ZX84r81lWYtZ0ahSSS

Body:
I figured this out.
I have to use MseStreamSource.

First I need to create MseStreamSource with event like this:

streamSource = new MseStreamSource();
streamSource.Opened += (_, __) =>
{
    if (buffer is null)
    {
        // it will create buffer where I can write data
        buffer = streamSource.AddSourceBuffer("video/MP2T");
        buffer.Mode = MseAppendMode.Sequence;
    }
};

Then set the source:

StreamMediaPlayer.Source = MediaSource.CreateFromMseStreamSource(streamSource);

And if I want to add video I have to do it like this:

buffer.AppendBuffer(reader.ReadBytes(20 * 1024 * 1024).AsBuffer());

I have to make sure that buffer is not updating. This information provides IsUpdating property.


问:
C# laziness question
What's the common approach to design applications, which strongly rely on lazy evaluation in C# (LINQ, IEnumerable, IQueryable, ...)?

Right now I usually attempt to make every query as lazy as possible, using yield return and LINQ queries, but in runtime this could usually lead to "too lazy" behavior, when every query gets builts from it's beginning obviously resulting in severe visual performance degradation.

What I usually do means putting ToList() projection operators somewhere to cache the data, but I suspect this approach might be incorrect.

What's the appropriate / common ways to design this sort of applications from the very beginning?

答:
I would suggest doing a ToList in your DAL before returning the DTO

```<code>public IList<UserDTO> GetUsers()
{
  using (var db = new DbContext())
  {
    return (from u in db.tblUsers
           select new UserDTO()
           {
               Name = u.Name
           }).ToList();
  }
}
</code>```

In the example above you have to do a ToList() before the DbContext scope ends.

Title: C# laziness question

Body:
I would suggest doing a ToList in your DAL before returning the DTO

public IList<UserDTO> GetUsers()
{
  using (var db = new DbContext())
  {
    return (from u in db.tblUsers
           select new UserDTO()
           {
               Name = u.Name
           }).ToList();
  }
}

In the example above you have to do a ToList() before the DbContext scope ends.


问:
Cannot decrypt given cyphertext twice with same AES Object
I am using an AES object (aesDecryptObj ) to decrypt a cyphertext that was encrypted using a seperate AES object (aesEncryptObj ).

def aesInit():
    global aesEncryptObj
    global aesDecryptObj
    aesKey = <my key>
    aesEncryptObj = AES.new(aesKey, AES.MODE_CBC, iv=<My Init Vector>)
    aesDecryptObj = AES.new(aesKey, AES.MODE_CBC, iv=<My Init Vector>)

def aesEncrypt(clearStr):
    global aesEncryptObj
    padded_data = pad(str(clearStr).encode("utf-8"), aesEncryptObj.block_size)
    e = aesEncryptObj.encrypt(padded_data)
    eb64 = base64.b64encode(e)
    d = eb64.decode('ascii')
    return(d)

def aesDecrypt(encryptedStr):
    global aesDecryptObj
    e = base64.b64decode(encryptedStr)
    b = aesDecryptObj.decrypt(e)
    b = unpad(b, aesDecryptObj.block_size)
    clearStr = b.decode('utf-8')
    return(clearStr)

aesInit()

cypherText = aesEncrypt('test') #this line will render the same result no matter how many times it is repeated

print(aesDecrypt(cypherText)) #this line executes fine
print(aesDecrypt(cypherText)) #this line throws the "padding is incorrect" error
```

<p>Using aesEncryptObj sequentially any number of times produces successful results, however, when I use aesDecryptObj to decrypt a given cyphertext two or more times in a row I receive the following error:  </p>

```File "/usr/lib64/python3.6/site-packages/Cryptodome/Util/Padding.py", line 90, in unpad
    raise ValueError("Padding is incorrect.")
ValueError: Padding is incorrect.
```

Should it be the case that, given the same ciphertext, aesDecryptObj would produce the same results as it did the first time it decrypted the value?

答:
AES objects have a state (at least with AES.MODE_CBC). You initialize that state with iv=<My Init Vector>. As you decrypt ciphertext the state changes. You need to reinitialize your object before you call decrypt again.

You probably want something like:

```<code>def aesDecrypt(encryptedStr):
    aesKey = <my key>
    aesDecryptObj = AES.new(aesKey, AES.MODE_CBC, iv=<My Init Vector>)
    e = base64.b64decode(encryptedStr)
    b = aesDecryptObj.decrypt(e)
    b = unpad(b, aesDecryptObj.block_size)
    clearStr = b.decode('utf-8')
    return(clearStr)
</code>```

Or you can simply call aesInit() again after decrypting the first ciphertext.

Body:
I am using an AES object (aesDecryptObj ) to decrypt a cyphertext that was encrypted using a seperate AES object (aesEncryptObj ).

def aesInit():
    global aesEncryptObj
    global aesDecryptObj
    aesKey = <my key>
    aesEncryptObj = AES.new(aesKey, AES.MODE_CBC, iv=<My Init Vector>)
    aesDecryptObj = AES.new(aesKey, AES.MODE_CBC, iv=<My Init Vector>)

def aesEncrypt(clearStr):
    global aesEncryptObj
    padded_data = pad(str(clearStr).encode("utf-8"), aesEncryptObj.block_size)
    e = aesEncryptObj.encrypt(padded_data)
    eb64 = base64.b64encode(e)
    d = eb64.decode('ascii')
    return(d)

def aesDecrypt(encryptedStr):
    global aesDecryptObj
    e = base64.b64decode(encryptedStr)
    b = aesDecryptObj.decrypt(e)
    b = unpad(b, aesDecryptObj.block_size)
    clearStr = b.decode('utf-8')
    return(clearStr)

aesInit()

cypherText = aesEncrypt('test') #this line will render the same result no matter how many times it is repeated

print(aesDecrypt(cypherText)) #this line executes fine
print(aesDecrypt(cypherText)) #this line throws the "padding is incorrect" error

Using aesEncryptObj sequentially any number of times produces successful results, however, when I use aesDecryptObj to decrypt a given cyphertext two or more times in a row I receive the following error:

File "/usr/lib64/python3.6/site-packages/Cryptodome/Util/Padding.py", line 90, in unpad
    raise ValueError("Padding is incorrect.")
ValueError: Padding is incorrect.

Should it be the case that, given the same ciphertext, aesDecryptObj would produce the same results as it did the first time it decrypted the value?

Body:
AES objects have a state (at least with AES.MODE_CBC). You initialize that state with iv=<My Init Vector>. As you decrypt ciphertext the state changes. You need to reinitialize your object before you call decrypt again.

You probably want something like:

def aesDecrypt(encryptedStr):
    aesKey = <my key>
    aesDecryptObj = AES.new(aesKey, AES.MODE_CBC, iv=<My Init Vector>)
    e = base64.b64decode(encryptedStr)
    b = aesDecryptObj.decrypt(e)
    b = unpad(b, aesDecryptObj.block_size)
    clearStr = b.decode('utf-8')
    return(clearStr)

Or you can simply call aesInit() again after decrypting the first ciphertext.


问:
Is it possible to duplicate a row based on a column value, and change another column value?
I have a table with an INT column of time in seconds, another column with the type of that record, and a foreign ID.

I want to select the same row repeated everytime it's seconds row is greater than X, and in the first row it keeps X seconds with type 1, and in the second row it shows the seconds left (seconds - X, up to X) with type 2. The same with Y. No more than 3 rows. So row 1 is up to x, row 2 up to Y and row 3 is Y+1 and beyond

Eg:

X is 5. Y is 9.
I want this:

```<code>| id | type | seconds |
|----|------|---------|
|  1 |  10  |   19    |
|  2 |  10  |   12    |
|  3 |  10  |    7    |
</code>```

to become this:

```<code>| id | type | seconds |
|----|------|---------|
|  1 |   1  |    5    |
|  1 |   2  |    4    |
|  1 |   3  |   10    |
|  2 |   1  |    5    |
|  2 |   2  |    4    |
|  2 |   3  |    3    |
|  3 |   1  |    5    |
|  3 |   2  |    2    |
</code>```

Is that possible?

I've seen solutions to this (syntax-) exclusively for oracle.
But how do I do this in SQL Server?

Edit: Only for this type id (10 in the example), letting others unchanged.

答:
This is not very pretty, but does the trick. To duplicate rows, we use tally tables. In this case I used a hard coded one with only 3 rows. Then made the calculations based on it. There might be a simpler way to code it, but I'm not on my best today.</p>

```<code>--Creating sample data
CREATE TABLE SampleData(
    id      int,
    [type]  int,
    seconds int
);

INSERT INTO SampleData
VALUES
( 1, 10, 19),
( 2, 10, 12),
( 3, 10,  7),
( 4, 10, 5),
( 5, 10,  3);
GO

--Actual solution
DECLARE @X int = 5;

WITH CTE AS(
    SELECT id,
        CASE WHEN [type] =  10 THEN n ELSE [type] END AS [type],
        CASE WHEN [type] <> 10 THEN seconds
             WHEN n = 1 AND seconds > @X THEN @X
             WHEN n = 1 AND seconds <= @X THEN seconds
             WHEN n = 2 AND seconds - @X >= @X THEN @X-1
             WHEN n = 2 AND seconds - @X > 0 THEN seconds - @X
             WHEN n = 3 AND seconds > @X*2-1 THEN seconds - (@X*2-1)
             END AS seconds
    FROM SampleData
    CROSS JOIN( VALUES(1),(2),(3))AS x(n)
    WHERE [type] = 10 OR n = 1
)
SELECT *
FROM CTE
WHERE seconds IS NOT NULL;
</code>```

Body:
I have a table with an INT column of time in seconds, another column with the type of that record, and a foreign ID.

I want to select the same row repeated everytime it's seconds row is greater than X, and in the first row it keeps X seconds with type 1, and in the second row it shows the seconds left (seconds - X, up to X) with type 2. The same with Y. No more than 3 rows. So row 1 is up to x, row 2 up to Y and row 3 is Y+1 and beyond

Eg:

X is 5. Y is 9.
I want this:

| id | type | seconds |
|----|------|---------|
|  1 |  10  |   19    |
|  2 |  10  |   12    |
|  3 |  10  |    7    |

to become this:

| id | type | seconds |
|----|------|---------|
|  1 |   1  |    5    |
|  1 |   2  |    4    |
|  1 |   3  |   10    |
|  2 |   1  |    5    |
|  2 |   2  |    4    |
|  2 |   3  |    3    |
|  3 |   1  |    5    |
|  3 |   2  |    2    |

Is that possible?

I've seen solutions to this (syntax-) exclusively for oracle.
But how do I do this in SQL Server?

Edit: Only for this type id (10 in the example), letting others unchanged.

Body:
This is not very pretty, but does the trick. To duplicate rows, we use tally tables. In this case I used a hard coded one with only 3 rows. Then made the calculations based on it. There might be a simpler way to code it, but I'm not on my best today.

--Creating sample data
CREATE TABLE SampleData(
    id      int,
    [type]  int,
    seconds int
);

INSERT INTO SampleData
VALUES
( 1, 10, 19),
( 2, 10, 12),
( 3, 10,  7),
( 4, 10, 5),
( 5, 10,  3);
GO

--Actual solution
DECLARE @X int = 5;

WITH CTE AS(
    SELECT id,
        CASE WHEN [type] =  10 THEN n ELSE [type] END AS [type],
        CASE WHEN [type] <> 10 THEN seconds
             WHEN n = 1 AND seconds > @X THEN @X
             WHEN n = 1 AND seconds <= @X THEN seconds
             WHEN n = 2 AND seconds - @X >= @X THEN @X-1
             WHEN n = 2 AND seconds - @X > 0 THEN seconds - @X
             WHEN n = 3 AND seconds > @X*2-1 THEN seconds - (@X*2-1)
             END AS seconds
    FROM SampleData
    CROSS JOIN( VALUES(1),(2),(3))AS x(n)
    WHERE [type] = 10 OR n = 1
)
SELECT *
FROM CTE
WHERE seconds IS NOT NULL;


问:
How to access Node Express server using proxy once deployed to Heroku?
How do I tell my app that when it is in production, and paypal triggers the 'return_url' it should look for '/success' on the server side rather than in the client?

I have set up an express server to handle PayPal payment requests. When a post request is served to 'localhost:5000/pay' on express I handle the logic and am redirected to PayPal where the user enters their details. They are then redirected to 'localhost:5000/success' where the payment is executed using the token returned by paypal. This works fine locally, but not on heroku. The issue is the return to the '/success' page.

As you can see from the code below, paypal asks me to reference a return_url (the url served for a successful transaction). In heroku the server is not running on 'locahost:5000' so it just throws an error. Alternatively serving the actual url followed by '/success' doesn't trigger the proxy I have set up in react and so it tries to find '/success' in my client side - which of course isn't there and triggers a 404.

The code to create payment:

```<code>    const create_payment_json = {

            "intent": "sale",
            "payer": {
                "payment_method": "paypal"
            },
            "redirect_urls": {
                "return_url": `http://localhost:5000/success`,
                "cancel_url": `http://localhost:5000/cancel`
            },
            "transactions": [{
                "item_list": {
                    "items": content
                },
                "amount": {
                    "currency": "USD",
                    "total": productSelectTotal,
                    "details":{
                        "subtotal":productSubTotal,
                        "shipping":shipping
                    }
                },
                "description": "first tea added to the store"
            }]
        }
</code>```

execution of payment once redirected to server/success

```<code>    app.get('/success', (req, res)=> {
            const payerId = req.query.PayerID
            const paymentId = req.query.paymentId

            const execute_payment_json = {
                "payer_id": payerId,
                "transactions": [{
                    "item_list": {
                    "items": content
                },
                    "amount": {
                        "currency":"USD",
                        "total": productSelectTotal,
                        "details":{
                            "subtotal":productSubTotal,
                            "shipping":shipping
                        }
                    }
                }]
            }

            paypal.payment.execute(paymentId, execute_payment_json, function (error, payment) {
                if (error) {
                    console.log(error.response);
                    throw error;
                } else {
                    console.log(JSON.stringify(payment));
                    res.send('Payment Successful')
                }
            });

        })
</code>```

答: I ended up solving the issue by adding a routes/api/... folder in my node server. When rect made the call, it made it to api/paypal/success instead and there was no confusion. </p>

Body:
How do I tell my app that when it is in production, and paypal triggers the 'return_url' it should look for '/success' on the server side rather than in the client?

I have set up an express server to handle PayPal payment requests. When a post request is served to 'localhost:5000/pay' on express I handle the logic and am redirected to PayPal where the user enters their details. They are then redirected to 'localhost:5000/success' where the payment is executed using the token returned by paypal. This works fine locally, but not on heroku. The issue is the return to the '/success' page.

As you can see from the code below, paypal asks me to reference a return_url (the url served for a successful transaction). In heroku the server is not running on 'locahost:5000' so it just throws an error. Alternatively serving the actual url followed by '/success' doesn't trigger the proxy I have set up in react and so it tries to find '/success' in my client side - which of course isn't there and triggers a 404.

The code to create payment:

    const create_payment_json = {

            "intent": "sale",
            "payer": {
                "payment_method": "paypal"
            },
            "redirect_urls": {
                "return_url": `http://localhost:5000/success`,
                "cancel_url": `http://localhost:5000/cancel`
            },
            "transactions": [{
                "item_list": {
                    "items": content
                },
                "amount": {
                    "currency": "USD",
                    "total": productSelectTotal,
                    "details":{
                        "subtotal":productSubTotal,
                        "shipping":shipping
                    }
                },
                "description": "first tea added to the store"
            }]
        }

execution of payment once redirected to server/success

    app.get('/success', (req, res)=> {
            const payerId = req.query.PayerID
            const paymentId = req.query.paymentId

            const execute_payment_json = {
                "payer_id": payerId,
                "transactions": [{
                    "item_list": {
                    "items": content
                },
                    "amount": {
                        "currency":"USD",
                        "total": productSelectTotal,
                        "details":{
                            "subtotal":productSubTotal,
                            "shipping":shipping
                        }
                    }
                }]
            }

            paypal.payment.execute(paymentId, execute_payment_json, function (error, payment) {
                if (error) {
                    console.log(error.response);
                    throw error;
                } else {
                    console.log(JSON.stringify(payment));
                    res.send('Payment Successful')
                }
            });

        })


问:
Escaping slashes and left square brackets when using sed replace
I have to write short script to replace line in file. Some of the lines contains slashes and left square brackets (probably right also).

I know that another delimiter should be used to replace line with slashes.

My code:

```<code>sed -i -e "s|${oldLine}|${newLine}|g"
</code>```

This throws an error because line contains [.

Example String in line to change (oldLine variable):

```<code>// List exampleList = [
</code>```

Example how like should look after change:

```<code>List exampleList = [
</code>```

How to make it works when there are some chars like [

To reproduce:

```<code>sed -i -e 's|// List exampleList = [|List exampleList = [|g' test.txt
</code>```

答:
You need to escape the "bad" characters in $oldline and $newline. The command

```<code>sed -e 's/\\/\\\\/g; s/\([[&()/\]]\)/\\\1/g'
</code>```

will replace \,[,&,(,),/,] with \\,\[, etc. So the combined command

```<code>sed -e "s/$(echo $oldline | sed -e 's/\\/\\\\/g; s/\([[&()/\]]\)/\\\1/g')/$(echo $newline | sed -e 's/\\/\\\\/g; s/\([[&()/\]]\)/\\\1/g')/g"
</code>```

will do what you want.

Body:
I have to write short script to replace line in file. Some of the lines contains slashes and left square brackets (probably right also).

I know that another delimiter should be used to replace line with slashes.

My code:

sed -i -e "s|${oldLine}|${newLine}|g"

This throws an error because line contains [.

Example String in line to change (oldLine variable):

// List exampleList = [

Example how like should look after change:

List exampleList = [

How to make it works when there are some chars like [

To reproduce:

sed -i -e 's|// List exampleList = [|List exampleList = [|g' test.txt

Body:
You need to escape the "bad" characters in $oldline and $newline. The command

sed -e 's/\\/\\\\/g; s/\([[&()/\]]\)/\\\1/g'

will replace \,[,&,(,),/,] with \\,\[, etc. So the combined command

sed -e "s/$(echo $oldline | sed -e 's/\\/\\\\/g; s/\([[&()/\]]\)/\\\1/g')/$(echo $newline | sed -e 's/\\/\\\\/g; s/\([[&()/\]]\)/\\\1/g')/g"

will do what you want.


问:
Understanding esModuleInterop in tsconfig file
I was checking out someone .tsconfig file and there I spotted --esModuleInterop

This is his .tsconfig file

```<code>{
  "compilerOptions": {
    "moduleResolution": "node",
    "target": "es6",
    "module": "commonjs",
    "lib": ["esnext"],
    "strict": true,
    "sourceMap": true,
    "declaration": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "declarationDir": "./dist",
    "outDir": "./dist",
    "typeRoots": ["node_modules/@types"]
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modues"]
}
</code>```

Here, My primary question is what is    "esModuleInterop": true, and
"allowSyntheticDefaultImports": true,. I know they are sort of dependent on the  "module": "commonjs", . Can someone try to explain it in the best human language possible?

The official docs for allowSyntheticDefaultImports states

Allow default imports from modules with no default export. This does
not affect code emit, just typechecking.

What does that mean? If there isn't any export default then I think the only use case of the import default would be to initialize something? Like a singleton?

The following question/answer does not make sense as well
Is there a way to use --esModuleInterop in tsconfig as opposed to it being a flag?

And --esModuleInterop definition on the compiler page

Emit __importStar and __importDefault helpers for runtime babel
ecosystem compatibility and enable --allowSyntheticDefaultImports for
typesystem compatibility.

Also seemed difficult for me to understand/comprehend

答:
Problem statement

Problem occurs when we want to import CommonJS module into ES6 module codebase.

Before these flags we had to import CommonJS modules with star (* as something) import:

```<code>// node_modules/moment/index.js
exports = moment
</code>```
```<code>// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec

// transpiled js (simplified):
const moment = require("moment");
moment();
</code>```

We can see that * was somehow equivalent to exports variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment in our case) can be only a plain object, not callable (moment() is not allowed).

Solution

With flag esModuleInterop we can import CommonJS modules in compliance with es6 modules spec. Now our import code looks like this:

```<code>// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec

// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();
</code>```

It works and it's perfectly valid with es6 modules spec, because moment is not namespace from star import, it's default import.

But how does it work? As you can see, because we did a default import, we called the default property on a moment object. But we didn't declare a default property on the exports object in the moment library. The key is the __importDefault function. It assigns module (exports) to the default property for CommonJS modules:

```<code>var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
</code>```

As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default key. This makes it possible to import defaults on CommonJS modules.

__importStar does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default property:

```<code>// index.ts file in our app
import * as moment from 'moment'

// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
</code>```
```<code>var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
</code>```

Synthetic imports

And what about allowSyntheticDefaultImports - what is it for? Now the docs should be clear:

Allow default imports from modules with no default export. This does not affect code emit, just typechecking.

In moment typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop on. So allowSyntheticDefaultImports will not report an error if we want to import default from a third-party module which doesn't have a default export.

Body:
I was checking out someone .tsconfig file and there I spotted --esModuleInterop

This is his .tsconfig file

{
  "compilerOptions": {
    "moduleResolution": "node",
    "target": "es6",
    "module": "commonjs",
    "lib": ["esnext"],
    "strict": true,
    "sourceMap": true,
    "declaration": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "declarationDir": "./dist",
    "outDir": "./dist",
    "typeRoots": ["node_modules/@types"]
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modues"]
}

Here, My primary question is what is    "esModuleInterop": true, and
"allowSyntheticDefaultImports": true,. I know they are sort of dependent on the  "module": "commonjs", . Can someone try to explain it in the best human language possible?

The official docs for allowSyntheticDefaultImports states

Allow default imports from modules with no default export. This does
not affect code emit, just typechecking.

What does that mean? If there isn't any export default then I think the only use case of the import default would be to initialize something? Like a singleton?

The following question/answer does not make sense as well
Is there a way to use --esModuleInterop in tsconfig as opposed to it being a flag?

And --esModuleInterop definition on the compiler page

Emit __importStar and __importDefault helpers for runtime babel
ecosystem compatibility and enable --allowSyntheticDefaultImports for
typesystem compatibility.

Also seemed difficult for me to understand/comprehend

Body:
Problem statement

Problem occurs when we want to import CommonJS module into ES6 module codebase.

Before these flags we had to import CommonJS modules with star (* as something) import:

// node_modules/moment/index.js
exports = moment

// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec

// transpiled js (simplified):
const moment = require("moment");
moment();

We can see that * was somehow equivalent to exports variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment in our case) can be only a plain object, not callable (moment() is not allowed).

Solution

With flag esModuleInterop we can import CommonJS modules in compliance with es6 modules spec. Now our import code looks like this:

// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec

// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();

It works and it's perfectly valid with es6 modules spec, because moment is not namespace from star import, it's default import.

But how does it work? As you can see, because we did a default import, we called the default property on a moment object. But we didn't declare a default property on the exports object in the moment library. The key is the __importDefault function. It assigns module (exports) to the default property for CommonJS modules:

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};

As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default key. This makes it possible to import defaults on CommonJS modules.

__importStar does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default property:

// index.ts file in our app
import * as moment from 'moment'

// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};

Synthetic imports

And what about allowSyntheticDefaultImports - what is it for? Now the docs should be clear:

Allow default imports from modules with no default export. This does not affect code emit, just typechecking.

In moment typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop on. So allowSyntheticDefaultImports will not report an error if we want to import default from a third-party module which doesn't have a default export.


问:
How to copy between two existing objects in javascript
I have two objects that are the same type and I want to copy the content of one of them to the other.

```<code>const Invoice1 = new InvoiceModel();

const Invoice2 = new InvoiceModel();
</code>```

now in order to have something like : Invoice2 = Invoice1

After reading :

How do I correctly clone a JavaScript object?

I tried to use any of below commands but all of them say that invoice2 is not defined at runtime:

```<code> Invoice2 = { ...Invoice1 };  //OR

 Invoice2 = Object.assign({}, Invoice1);  //OR

 Invoice2 = JSON.parse(JSON.stringify(Invoice1));
</code>```

finally I used this function to copy the content of objects by reading this article (https://medium.com/@Farzad_YZ/3-ways-to-clone-objects-in-javascript-f752d148054d):

```<code>function CopyObject(src, target) {
  for (let prop in src) {
    if (src.hasOwnProperty(prop)) {
      target[prop] = src[prop];
    }
  }
  return target;
}
</code>```

I wonder is there any cleaner way to do that except using above function?

I have read many post regarding this issue but all of them create a new object.

答:
I recommend creating a method in the prototype in InvoiceModel that does this automatically for you.

class InvoiceModel {
  constructor(num) {
    this.num = num
  }
  duplicate() {
    return Object.assign(Object.create(this), this)
  }
}

const obj1 = new InvoiceModel(10)
console.log(obj1.num)
const obj1Copy = obj1.duplicate()
console.log(obj1Copy.num)
console.log(obj1Copy === obj1)```

Body:
I have two objects that are the same type and I want to copy the content of one of them to the other.

const Invoice1 = new InvoiceModel();

const Invoice2 = new InvoiceModel();

now in order to have something like : Invoice2 = Invoice1

After reading :

How do I correctly clone a JavaScript object?

I tried to use any of below commands but all of them say that invoice2 is not defined at runtime:

 Invoice2 = { ...Invoice1 };  //OR

 Invoice2 = Object.assign({}, Invoice1);  //OR

 Invoice2 = JSON.parse(JSON.stringify(Invoice1));

finally I used this function to copy the content of objects by reading this article (https://medium.com/@Farzad_YZ/3-ways-to-clone-objects-in-javascript-f752d148054d):

function CopyObject(src, target) {
  for (let prop in src) {
    if (src.hasOwnProperty(prop)) {
      target[prop] = src[prop];
    }
  }
  return target;
}

I wonder is there any cleaner way to do that except using above function?

I have read many post regarding this issue but all of them create a new object.


问:
Calling functions and returning values
I am a beginner in C++.I have a function which returns some parameters that i need ,to use in  the rest of my program.I am trying to access that function within another class.I am confused with the way i can do it...Can anyone please help me..?

Following is my code :

```<code> void SampleProgram :: myFunction()
   {
         string sInput;
         GetInfo  getInfo(sInput);  //creating instance of the class containing the function

            string sSw="";
       string sName="ram";
       string sList="list";

           getInfo.getRequiredInfo(sSw,sName,sList); //calling the function

    }
</code>```

How can i access the output parameters of getRequiredInfo() ..?and save it if the ouput parameters are as following :string name,int status
Please help me...

答:
It sounds as though getRequiredInfo has the behaviour of both reading from and writing to some of the parameters you've passed in.

In C++, unlike in C#, there's no way to specify that a function should, or must, change the value of a given parameter. Indeed, if you have defined your function like this:

```<code>void GetInfo::getRequiredInfo(string a, string b, string c);
</code>```

then all three parameters will be passed by value meaning any changes made to them inside the function will be changing copies of those objects, rather than the objects themselves.

As other contributors have suggested, if you really want to change the parameters you passed in, you could either do so by passing references:

```<code>void GetInfo::getRequiredInfo(string a, string& b, string& c);
</code>```

or (more typically) by passing pointers:

```<code>void GetInfo::getRequiredInfo(string a, string* b, string* c);
</code>```

However, if you want your function to simply read the parameters and return a value (which is the more accepted term for what you're calling 'output parameters') then you have to express your tuple of "name + status" as a single value.

You could use the built in pair template as someone else just suggested:

```<code>pair<string,int> getRequiredInfo(string a, string b, string c);
</code>```

Or you could define your own struct to do it, like someone else suggested:

```<code>struct NameAndStatus
{
    string name;
    int status;
};

NameAndStatus getRequiredInfo(string a, string b, string c);
</code>```

Title: Calling functions and returning values

Body:
I am a beginner in C++.I have a function which returns some parameters that i need ,to use in  the rest of my program.I am trying to access that function within another class.I am confused with the way i can do it...Can anyone please help me..?

Following is my code :

 void SampleProgram :: myFunction()
   {
         string sInput;
         GetInfo  getInfo(sInput);  //creating instance of the class containing the function

            string sSw="";
       string sName="ram";
       string sList="list";

           getInfo.getRequiredInfo(sSw,sName,sList); //calling the function

    }

How can i access the output parameters of getRequiredInfo() ..?and save it if the ouput parameters are as following :string name,int status
Please help me...

Body:
It sounds as though getRequiredInfo has the behaviour of both reading from and writing to some of the parameters you've passed in.

In C++, unlike in C#, there's no way to specify that a function should, or must, change the value of a given parameter. Indeed, if you have defined your function like this:

void GetInfo::getRequiredInfo(string a, string b, string c);

then all three parameters will be passed by value meaning any changes made to them inside the function will be changing copies of those objects, rather than the objects themselves.

As other contributors have suggested, if you really want to change the parameters you passed in, you could either do so by passing references:

void GetInfo::getRequiredInfo(string a, string& b, string& c);

or (more typically) by passing pointers:

void GetInfo::getRequiredInfo(string a, string* b, string* c);

However, if you want your function to simply read the parameters and return a value (which is the more accepted term for what you're calling 'output parameters') then you have to express your tuple of "name + status" as a single value.

You could use the built in pair template as someone else just suggested:

pair<string,int> getRequiredInfo(string a, string b, string c);

Or you could define your own struct to do it, like someone else suggested:

struct NameAndStatus
{
    string name;
    int status;
};

NameAndStatus getRequiredInfo(string a, string b, string c);


答:
If the objects are just plain old data objects - with no methods or private state - you can just use a deep object clone method as specified here.

However, by the looks of things you are using classes with constructors, which implies you have methods and state. This is more tricky, because it suggests you may be relying on the constructor being re-run, e.g. to store private state in a closure, to allocate other resources, or rely on some kind of side effects. In that case you will need some kind of Invoice.prototype.clone method, that knows how to inject state into a new instance, and reruns the constructor function for the class - as per @andrew's answer.

I would avoid cloning objects with the syntax target = {...src}, which one commenter suggested. This will cause you trouble as soon as you have non-scalar reference members like sub-objects or arrays (as you will be copying pointers to the originals, not cloning their values). The same flaw applies to that CopyObject function you have picked up.

Title: How to copy between two existing objects in javascript


问:
UnsatisfiedLinkError when enabling JProfiler on armhf
I am trying to start a JProfiler agent in a docker container running on a Raspberry PI 3. Here is the complete Dockerfile.

```<code>FROM balenalib/raspberrypi3-openjdk

RUN ["cross-build-start"]
RUN curl -SL http://download-keycdn.ej-technologies.com/jprofiler/jprofiler_linux_11_0.tar.gz | tar -xz -C /usr/local && \
  echo 'sudo -u root /usr/local/jprofiler11.0/bin/jpenable -g -p 8849' > /jprofile.sh && \
  chmod +x /jprofile.sh
RUN [ "cross-build-end" ]

ENV JPAGENT_PATH="-agentpath:/usr/local/jprofiler11.0/bin/linux-armhf/libjprofilerti.so=nowait"
ENV JAVA_OPTS=""
EXPOSE 8849

ADD build/libs/myproject-0.0.1-SNAPSHOT.jar /app.jar

ENTRYPOINT exec java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar
</code>```

For profiling, run:

```<code>docker exec -it mycontainer /bin/bash -c "/jprofile.sh"
</code>```

Here is the complete output:

```<code>Connecting to app.jar [1] ... ERROR: The agent could not be loaded: Exception in thread "main" java.lang.UnsatisfiedLinkError: sun.tools.attach.LinuxVirtualMachine.isLinuxThreads()Z
        at sun.tools.attach.LinuxVirtualMachine.isLinuxThreads(Native Method)
        at sun.tools.attach.LinuxVirtualMachine.<clinit>(LinuxVirtualMachine.java:343)
        at sun.tools.attach.LinuxAttachProvider.attachVirtualMachine(LinuxAttachProvider.java:63)
        at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:195)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at com.jprofiler.attach.proxy.a.e$b.invoke(ejt:110)
        at com.sun.proxy.$Proxy0.attach(Unknown Source)
        at com.jprofiler.attach.a.main(ejt:119)
</code>```

It seems like the native library loads fine when I call System.loadLibrary("attach") from jshell. Any ideas what could be causing this exception?

答:
Solved via support@ej-technologies.com - if you place the correct file in lib/libattach.so, you can add the following snippet to the Dockerfile to make it work.

Offical support for armhf is scheduled to release with 11.0.1.

```<code># ...
# Add ARMHF remote attach library (acquired via EJ Technologies support)
# See https://stackoverflow.com/questions/56307915/unsatisfiedlinkerror-when-enabling-jprofiler-on-armhf
ADD lib/libattach.so /usr/local/jprofiler11.0/bin/linux-armhf/
RUN chmod a+x /usr/local/jprofiler11.0/bin/linux-armhf/libattach.so

RUN [ "cross-build-end" ]
</code>```

Special thanks to Ingo Kegel!

Body:
I am trying to start a JProfiler agent in a docker container running on a Raspberry PI 3. Here is the complete Dockerfile.

FROM balenalib/raspberrypi3-openjdk

RUN ["cross-build-start"]
RUN curl -SL http://download-keycdn.ej-technologies.com/jprofiler/jprofiler_linux_11_0.tar.gz | tar -xz -C /usr/local && \
  echo 'sudo -u root /usr/local/jprofiler11.0/bin/jpenable -g -p 8849' > /jprofile.sh && \
  chmod +x /jprofile.sh
RUN [ "cross-build-end" ]

ENV JPAGENT_PATH="-agentpath:/usr/local/jprofiler11.0/bin/linux-armhf/libjprofilerti.so=nowait"
ENV JAVA_OPTS=""
EXPOSE 8849

ADD build/libs/myproject-0.0.1-SNAPSHOT.jar /app.jar

ENTRYPOINT exec java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar

For profiling, run:

docker exec -it mycontainer /bin/bash -c "/jprofile.sh"

Here is the complete output:

Connecting to app.jar [1] ... ERROR: The agent could not be loaded: Exception in thread "main" java.lang.UnsatisfiedLinkError: sun.tools.attach.LinuxVirtualMachine.isLinuxThreads()Z
        at sun.tools.attach.LinuxVirtualMachine.isLinuxThreads(Native Method)
        at sun.tools.attach.LinuxVirtualMachine.<clinit>(LinuxVirtualMachine.java:343)
        at sun.tools.attach.LinuxAttachProvider.attachVirtualMachine(LinuxAttachProvider.java:63)
        at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:195)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at com.jprofiler.attach.proxy.a.e$b.invoke(ejt:110)
        at com.sun.proxy.$Proxy0.attach(Unknown Source)
        at com.jprofiler.attach.a.main(ejt:119)

It seems like the native library loads fine when I call System.loadLibrary("attach") from jshell. Any ideas what could be causing this exception?

Body:
Solved via support@ej-technologies.com - if you place the correct file in lib/libattach.so, you can add the following snippet to the Dockerfile to make it work.

Offical support for armhf is scheduled to release with 11.0.1.

# ...
# Add ARMHF remote attach library (acquired via EJ Technologies support)
# See https://stackoverflow.com/questions/56307915/unsatisfiedlinkerror-when-enabling-jprofiler-on-armhf
ADD lib/libattach.so /usr/local/jprofiler11.0/bin/linux-armhf/
RUN chmod a+x /usr/local/jprofiler11.0/bin/linux-armhf/libattach.so

RUN [ "cross-build-end" ]

Special thanks to Ingo Kegel!


问:
Behaviour of redis client-output-buffer-limit during resynchronization
I'm assuming that during replica resynchronisation (full or partial), the master will attempt to send data as fast as possible to the replica. Wouldn't this mean the replica output buffer on the master would rapidly fill up since the speed the master can write is likely to be faster than the throughput of the network? If I have client-output-buffer-limit set for replicas, wouldn't the master end up closing the connection before the resynchronisation can complete?

答:
Yes, Redis Master will close the connection and the synchronization will be started from beginning again. But, please find some details below:

Do you need to touch this configuration parameter and what is the purpose/benefit/cost of it?

There is a zero (almost) chance it will happen with default configuration and pretty much moderate modern hardware.

"By default normal clients are not limited because they don't receive data
without asking (in a push way), but just after a request, so only asynchronous clients may create a scenario where data is requested faster than it can read." - the chunk from documentation .

Even if that happens, the replication will be started from beginning but it may lead up to infinite loop when slaves will continuously ask for synchronization over and over. Redis Master will need to fork whole memory snapshot (perform BGSAVE) and use up to 3 times of RAM from initial snapshot size each time during synchronization. That will be causing higher CPU utilization, memory spikes network utilization (if any) and IO.

General recommendations to avoid production issues tweaking this configuration parameter:

Don't decrease this buffer and before increasing the size of the buffer make sure you have enough memory on your box.

Please consider total amount of RAM as snapshot memory size (doubled for copy-on-write BGSAVE process) plus the size of any other buffers configured plus some extra capacity.

Please find more details here


问:
Spring boot: disable security auto configuration
I have multipart web project. Web Admin part contains:

```<code>compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-jetty")
compile("org.springframework.boot:spring-boot-starter-actuator")
</code>```

Main project build file contains:

```<code>compile group: 'org.springframework', name: "spring-webmvc", version: springVersion
compile(group: 'org.springframework.security', name: "spring-security-web", version: springSecurityVersion) { exclude(module: 'spring-jdbc') }
</code>```

Spring Boot application file:

```<code>@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class WebAdminApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebAdminApplication.class, args);
    }
}
</code>```

But when I'm doing http request to my admin part I'm getting user and password in my AuthenticationProvider:

```<code>auth.getPrincipal() -> user
auth.getCredentials() -> caeebd3a-307b-4edf-8f2f-833fad9ebc00
</code>```

How I can disable auto security?

答:
Even I was facing the same issue. So, I added below code.

Case 1: If you have NOT activated 'ACTUATOR':
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })

Case 2: If you have activated 'ACTUATOR':
@SpringBootApplication(exclude = {      org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class,        org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration.class})

Body:
I have multipart web project. Web Admin part contains:

compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-jetty")
compile("org.springframework.boot:spring-boot-starter-actuator")

Main project build file contains:

compile group: 'org.springframework', name: "spring-webmvc", version: springVersion
compile(group: 'org.springframework.security', name: "spring-security-web", version: springSecurityVersion) { exclude(module: 'spring-jdbc') }

Spring Boot application file:

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class WebAdminApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebAdminApplication.class, args);
    }
}

But when I'm doing http request to my admin part I'm getting user and password in my AuthenticationProvider:

auth.getPrincipal() -> user
auth.getCredentials() -> caeebd3a-307b-4edf-8f2f-833fad9ebc00

How I can disable auto security?


问:
Trouble with appending row to csv file
I am trying to add a row to an existing CSV file. for some reason, it won't add any rows for a blank CSV...

the weird thing is that if I run over the CSV using w the code runs perfectly, but if I try to append to an existing CSV using a the process finish with no errors but I get a blank CSV.

even weirder is that if I run with w then run another time with a it works both times...

I tried this:

```<code>csvfile = open(r'file path', 'a', newline='')
obj = csv.writer(csvfile)
</code>```

now I got a for loop with some condition doesn't really matter for this case.

```<code>for stock_symbol in mystocks:
    obj.writerow([ddate,bmo_amc,stock_symbol,company_name])
</code>```

```<code>print(ddate,bmo_amc,stock_symbol,company_name)
</code>```

```2019-05-23 00:00:00 Before The Open WMS Advanced Drainage Systems
2019-05-23 00:00:00 Before The Open BBY Best Buy
2019-05-23 00:00:00 Before The Open BJ BJ's Wholesale
2019-05-23 00:00:00 Before The Open BRC Brady
2019-05-23 00:00:00 Before The Open HRL Hormel Foods```

```<code>obj.writerow([ddate,bmo_amc,stock_symbol,company_name])
</code>```

csvfile.close()

now when I rewrite the CSV file like this

csvfile = open(r'file path', 'w', newline='')

it works fine but I need to append some rows and not to rewrite them...

答:
from the doc:

A row must be an iterable of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects.

This worked for me:

csv file look like this:

add 'alex' with height 180 to the file

```<code> with open('./example.csv', 'a', newline='') as csvfile:
        newPerson = csv.writer(csvfile, delimiter=',')
        newPerson.writerow(['alex', 180])
</code>```

output:

edit:

I tried to infer the data structures in your updated post, and it generated a csv file with no problem using 'a' in open(). When use with open() as, no need to put csvfile.close() there, it auto closes for you. and are the ddate, bmo_amc, and company_name iterators as well?

```<code>import csv

mystocks = ['WMS', 'BBY', 'BJ', 'BRC', 'HRL']
ddate = ['2019-05-23 00:00:00']*len(mystocks)
bmo_amc = ['Before']*len(mystocks)
company_name = ['Advanced Drainage Systems', 'Besty Buy', 'BJ\'s whole food', 'Brady', 'Hormel Foods']

with open(r'./stocks.csv', 'a', newline='') as csvfile:
    obj = csv.writer(csvfile, delimiter=',')
    for index, stock_symbol in enumerate(mystocks):
        obj.writerow([ddate[index], bmo_amc[index], stock_symbol, company_name[index]])
</code>```

Title: Trouble with appending row to csv file

Body:
I am trying to add a row to an existing CSV file. for some reason, it won't add any rows for a blank CSV...

the weird thing is that if I run over the CSV using w the code runs perfectly, but if I try to append to an existing CSV using a the process finish with no errors but I get a blank CSV.

even weirder is that if I run with w then run another time with a it works both times...

I tried this:

csvfile = open(r'file path', 'a', newline='')
obj = csv.writer(csvfile)

now I got a for loop with some condition doesn't really matter for this case.

for stock_symbol in mystocks:
    obj.writerow([ddate,bmo_amc,stock_symbol,company_name])

print(ddate,bmo_amc,stock_symbol,company_name)

2019-05-23 00:00:00 Before The Open WMS Advanced Drainage Systems
2019-05-23 00:00:00 Before The Open BBY Best Buy
2019-05-23 00:00:00 Before The Open BJ BJ's Wholesale
2019-05-23 00:00:00 Before The Open BRC Brady
2019-05-23 00:00:00 Before The Open HRL Hormel Foods

obj.writerow([ddate,bmo_amc,stock_symbol,company_name])

csvfile.close()

now when I rewrite the CSV file like this

csvfile = open(r'file path', 'w', newline='')

it works fine but I need to append some rows and not to rewrite them...

Body:
from the doc:

A row must be an iterable of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects.

This worked for me:

csv file look like this:

add 'alex' with height 180 to the file

 with open('./example.csv', 'a', newline='') as csvfile:
        newPerson = csv.writer(csvfile, delimiter=',')
        newPerson.writerow(['alex', 180])

output:

edit:

I tried to infer the data structures in your updated post, and it generated a csv file with no problem using 'a' in open(). When use with open() as, no need to put csvfile.close() there, it auto closes for you. and are the ddate, bmo_amc, and company_name iterators as well?

import csv

mystocks = ['WMS', 'BBY', 'BJ', 'BRC', 'HRL']
ddate = ['2019-05-23 00:00:00']*len(mystocks)
bmo_amc = ['Before']*len(mystocks)
company_name = ['Advanced Drainage Systems', 'Besty Buy', 'BJ\'s whole food', 'Brady', 'Hormel Foods']

with open(r'./stocks.csv', 'a', newline='') as csvfile:
    obj = csv.writer(csvfile, delimiter=',')
    for index, stock_symbol in enumerate(mystocks):
        obj.writerow([ddate[index], bmo_amc[index], stock_symbol, company_name[index]])


问:
how to display xml formatted jsp
I have XML as a string in JSP. But this XML is in a single line. I want to display this XML string formatted in JSP.

For example:

```<code><?xml version="1.0"?><catalog><book id="bk101"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price>...(is going on)
</code>```

I want to display this as follows in JSP:

```<code><?xml version="1.0"?>
<catalog>
    <book id="bk101">
        <author>Gambardella, Matthew</author>
        <title>XML Developer's Guide</title>
        <genre>Computer</genre>
        <price>44.95</price>...(going on)
</code>```

How can I do this?

答:
do xsl transformation and specify option

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="xml" indent="yes"/>
 <xsl:strip-space elements="*"/>
 <xsl:template match="/">
  <xsl:copy-of select="."/>
 </xsl:template>
</code>```

see this example and after this use your xml

Title: how to display xml formatted jsp

Body:
I have XML as a string in JSP. But this XML is in a single line. I want to display this XML string formatted in JSP.

For example:

<?xml version="1.0"?><catalog><book id="bk101"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price>...(is going on)

I want to display this as follows in JSP:

<?xml version="1.0"?>
<catalog>
    <book id="bk101">
        <author>Gambardella, Matthew</author>
        <title>XML Developer's Guide</title>
        <genre>Computer</genre>
        <price>44.95</price>...(going on)

How can I do this?

Body:
do xsl transformation and specify option

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="xml" indent="yes"/>
 <xsl:strip-space elements="*"/>
 <xsl:template match="/">
  <xsl:copy-of select="."/>
 </xsl:template>

see this example and after this use your xml


问:
Library for face recognition
How to install face_recognition package on python3.

I tried it by using,

```<code>pip install face_recognition
</code>```

but not working when compiling .
On statement.

```<code>import face_recognition
</code>```

The error is

no module named face_recognition

答:
Hi before installing face_recognition in python3 you have to install

    dblib,     numpy,     opencv

packages you can find it at,

```<code>https://github.com/ageitgey/face_recognition/issues/175#issue-257710508

https://pypi.org/project/opencv-python/

https://pypi.org/project/numpy/
</code>```

Hope you got the answer.

Title: Library for face recognition

Body:
How to install face_recognition package on python3.

I tried it by using,

pip install face_recognition

but not working when compiling .
On statement.

import face_recognition

The error is

no module named face_recognition

Body:
Hi before installing face_recognition in python3 you have to install

    dblib,     numpy,     opencv

packages you can find it at,

https://github.com/ageitgey/face_recognition/issues/175#issue-257710508

https://pypi.org/project/opencv-python/

https://pypi.org/project/numpy/

Hope you got the answer.