问:
Looping through dynamic ranges on another sheet for rows with specific text in VBA
I have a macro that does a lot of things to build a report. Its a template named "Report" that has a user add another sheet, via GetOpenFile, with data to parse. The intent is to have the user open the book, push the button, select a file and generate a full report.

The data sheet, imported and renamed "Source" contains a row of headers and a variably long list of work orders. Each row contains a reference to a product code and and multiple references to order status. I have part of the macro pulling the product codes from Source column O and sorting alphabetically without duplicates.

```<code>    Sub ReportBuilder()

    'Variables for opening and copying the Sourcesheet, building and formatting the report.
    Dim sImportFile As String, sFile As String, cellName As String
    Dim sThisBk As Workbook, wbBk As Workbook
    Dim wSheet As Worksheet, sSheet As Worksheet, keepThis As Worksheet
    Dim nameRange As Range, orderRange As Range
    Dim rowCounterW As Integer, rowCounterS As Integer, pediCounter As Integer, adhoCounter As Integer, workCounter As Integer, holdCounter As Integer

    'Turns off display of screen updates and alerts.
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    'Removes all but the summary sheet "Report".
    For Each keepThis In Application.ActiveWorkbook.Worksheets
        If keepThis.Name <> "Report" Then
            keepThis.Delete
        End If
    Next

    'Displays an open file dialog box for selecting the target Source file.
    Set sThisBk = ActiveWorkbook
    sImportFile = Application.GetOpenFilename( _
    FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Select a file saved from Source")

    'Handles no sheet selection.
    If sImportFile = "False" Then
        MsgBox "No File Selected!"
        Exit Sub

    'Opens the targeted file and copies the sheet.
    Else
        sFile = Dir(sImportFile)
        Application.Workbooks.Open fileName:=sImportFile
        Set wbBk = Workbooks(sFile)
        With wbBk
            Set wSheet = .Sheets("Sheet1")
            wSheet.Copy after:=sThisBk.Sheets("PBUS Report")
            ActiveSheet.Name = "Source"
            Sheets("PBUS Report").Activate
            wbBk.Close SaveChanges:=False
        End With
    End If

    'Clears everything below the headers.
    Worksheets("Report").Rows(7 & ":" & Worksheets("Report").Rows.Count).Delete

    'Inserts the list of unique PRODICT CODEs from the Source sheet.
    Set wSheet = Worksheets("Report")
    Set sSheet = Worksheets("Source")
    sSheet.Activate
    sSheet.Range("O2", Cells(Rows.Count, "O").End(xlUp)).Copy
    wSheet.Activate
    wSheet.Range("B7").PasteSpecial

    'Sorts and adjusts after paste, also captures the range of PRODUCT CODEs.
    Selection.Interior.Color = xlNone
    Selection.Font.Bold = False
    wSheet.Columns("B:B").EntireColumn.AutoFit
    Application.Selection.RemoveDuplicates Columns:=1, Header:=xlNo
    Set nameRange = wSheet.Range("B7", Cells(Rows.Count, "B").End(xlUp))
    nameRange.Sort key1:=ActiveCell, order1:=xlAscending
</code>```

This part works great, I get a unique and alphabetized list of product codes from Source column O starting at row 2 in Report column B starting at row 7.

I'm stuck with the loop that counts rows on the Source sheet. For every unique product code in Report (column B starting at 7), I need to count the number of rows in Source (column O starting at 2) where the code matches AND another column contains a status description. Descriptions being either "Plant" or "Storage" in Source column Z, or "Working" or "Holding" in Source column C. There are more descriptions in either but I only track those 4 per product code.

```<code>    'Loop through the range of PRODUCT CODEs to build report.
    Set orderRange = sSheet.Range("O2", sSheet.Cells(Rows.Count, "O").End(xlUp))
    rowCounterW = 7 'Starting offset for populating the report.
    For Each c In nameRange.Rows
        pediCounter = 0 'Counter for pedigree column.
        adhoCounter = 0 'Counter for ad-hoc column.
        workCounter = 0 'Counter for working column.
        holdCounter = 0 'Counter for hold column.
        cellName = c.Value

        For Each d In orderRange.Rows
             rowCounterS = orderRange.Row + 1
             If sSheet.Cells(rowCounterS, "O") = cellName Then 'If the program name matches on both sheets.
                If sSheet.Cells(rowCounterS, "Z") = "Plant" Then
                    pediCounter = pediCounter + 1 'Counts for pedigree column.
                End If
                If sSheet.Cells(rowCounterS, "Z") = "Storage" Then
                    adhoCounter = adhoCounter + 1 'Counts for ad-hoc column.
                End If
                If sSheet.Cells(rowCounterS, "C") = "Working" Then
                    workCounter = workCounter + 1 'Counts for working column.
                End If
                If sSheet.Cells(rowCounterS, "C") = "Holding" Then
                    holdCounter = holdCounter + 1 'Counts for hold column.
                End If
            End If

        Next d
        wSheet.Cells(rowCounterW, "C") = pediCounter
        wSheet.Cells(rowCounterW, "D") = adhoCounter
        wSheet.Cells(rowCounterW, "E") = wSheet.Cells(rowCounterW, "C") + wSheet.Cells(rowCounterW, "D")
        wSheet.Cells(rowCounterW, "F") = workCounter
        wSheet.Cells(rowCounterW, "G") = holdCounter
        wSheet.Cells(rowCounterW, "H") = wSheet.Cells(rowCounterW, "E") + wSheet.Cells(rowCounterW, "F") + wSheet.Cells(rowCounterW, "G")
        rowCounterW = rowCounter + 1
    Next c
</code>```

This iteration does not count or populate correctly, but it does compile. It only populates the row of B7 with 0s and gives up. I am trying to accomplish:

```<code>    For Each "product code" in "range of product codes" on Report
        For Each row on Source starting at 2
            If "that row" contains a matching "product code" from Report
                And If "that row" also contains "desired status1"
                    Add 1 to counter for "desired status1"
                And If "that row" also contains "desired status2"
                    Add 1 to a counter for "desired status2"
                etc...
    Populate Report column C with status 1 from the counter
    Populate Report column D with status 2 from the counter
    etc...
    Next "product code"
</code>```

How did I mess this up? Trying all day with variations on that syntax once got all the fields to populate with status numbers, but they were all 0s like the first row. Currently only getting top row populating 0s. I don't understand why the dynamic range worked once to get the unique product code list once but not in the next step to loop.

EDIT: Caught a typo with rowCounterW at the bottom that stopped it from looping more than once. Also replaces some variables to count rows on the Source sheet better. Working as follows:

```<code>    'Loop through the range of PRODUCT CODEs to build report.
    rowCounterW = 7 'Starting offset for populating the report.
    For Each c In nameRange
        pediCounter = 0 'Counter for pedigree column.
        adhoCounter = 0 'Counter for ad-hoc column.
        workCounter = 0 'Counter for working column.
        holdCounter = 0 'Counter for hold column.
        cellName = c.Value

        For i = 2 To sSheet.Cells(Rows.Count, 2).End(xlUp).Row
            If sSheet.Cells(i, "O") = cellName Then 'If the program name matches on both sheets.
                If sSheet.Cells(i, "Z") = "Plant" Then
                    pediCounter = pediCounter + 1 'Counts for pedigree column.
                End If
                If sSheet.Cells(i, "Z") = "Storage" Then
                    adhoCounter = adhoCounter + 1 'Counts for ad-hoc column.
                End If
                If sSheet.Cells(i, "C") = "Working" Then
                    workCounter = workCounter + 1 'Counts for working column.
                End If
                If sSheet.Cells(i, "C") = "Holding" Then
                    holdCounter = holdCounter + 1 'Counts for hold column.
                End If
            End If
        Next i
        'Populates the report after parsing every row.
        wSheet.Cells(rowCounterW, "C") = pediCounter
        wSheet.Cells(rowCounterW, "D") = adhoCounter
        wSheet.Cells(rowCounterW, "E") = wSheet.Cells(rowCounterW, "C") + wSheet.Cells(rowCounterW, "D")
        wSheet.Cells(rowCounterW, "F") = workCounter
        wSheet.Cells(rowCounterW, "G") = holdCounter
        wSheet.Cells(rowCounterW, "H") = wSheet.Cells(rowCounterW, "E") + wSheet.Cells(rowCounterW, "F") + wSheet.Cells(rowCounterW, "G")
        rowCounterW = rowCounterW + 1
    Next c
</code>```

答:
Sorry I didn't take the time to match your variables, but I don't have time to fix it up (mine deals with Projects/People/Hours)...

I'd start by defining a few data structures:

```<code>Type ZCOType
    WBS As String
    ActivityType As String
    EmployeeName As String
    ProductionOrder As String
    Hours As Double
End Type

Type WeeklyManpower
    StartDate As Date
    EndDate As Date
    Hours As Double
    People As Long
    Data() As ZCOType
    DataCount As Long
End Type

Public g_ManpowerData() As WeeklyManpower, g_ManpowerCount As Long
</code>```

...Read the data into a variant array (for speed)

```<code>Dim vData
vData = sSheet.Range("O2", Cells(Rows.Count, "O").End(xlUp))
</code>```

...Loop through the vData array more of less like it's the same as looping through rows & columns and assigning the values to the Data Structure

```<code>For iRow = 2 To iLastRow
    ' Search for an data entry, with the same Start Date
    For Index = 0 to g_ManpowerCount -1
        If StartDate = vData(iRow,1) then exit for
    Next Index
    ' If not found, create a new Record
    if Index >= g_ManpowerCount then
        ReDim Preserve g_ManpowerData(g_ManpowerCount)
        g_ManpowerData(Index).StartDate  = vData(irow,1)
        g_ManpowerCount = g_ManpowerCount + 1
    end if
    '
    With g_ManpowerData(Index)
        ReDim Preserve .Data(.DataCount)
        With .Data(.DataCount)
            .EmployeeName  = vData(irow,5)
            '....
        End With
        .DataCount=.DataCount+1
    End With
Next
</code>```

Use a custom sort function to sort the list:

```<code>Public Sub QuickSortManpower(ManpowerData() As WeeklyManpower, intBottom As Integer, intTop As Integer)
</code>```

Get ready to dump the data back into the spreadsheet by putting it into a Variant array:

```<code>Dim vProjectedData
ReDim vProjectedData(g_ManpowerCount,7)
For i = 0 To g_ManpowerCount
    vProjectedData(i, 1) = ManpowerData(i).StartDate
    vProjectedData(i, 2) = ManpowerData(i).EndDate
    vProjectedData(i, 3) = ManpowerData(i).Hours
    '...
Next
</code>```

And finally, dump the values onto the sheet

```<code>Sheet.Cells(2, 1).Resize(Rows + 1, 8) = vProjectedData
</code>```

Add headers/formatting as needed...

Body:
I have a macro that does a lot of things to build a report. Its a template named "Report" that has a user add another sheet, via GetOpenFile, with data to parse. The intent is to have the user open the book, push the button, select a file and generate a full report.

The data sheet, imported and renamed "Source" contains a row of headers and a variably long list of work orders. Each row contains a reference to a product code and and multiple references to order status. I have part of the macro pulling the product codes from Source column O and sorting alphabetically without duplicates.

    Sub ReportBuilder()

    'Variables for opening and copying the Sourcesheet, building and formatting the report.
    Dim sImportFile As String, sFile As String, cellName As String
    Dim sThisBk As Workbook, wbBk As Workbook
    Dim wSheet As Worksheet, sSheet As Worksheet, keepThis As Worksheet
    Dim nameRange As Range, orderRange As Range
    Dim rowCounterW As Integer, rowCounterS As Integer, pediCounter As Integer, adhoCounter As Integer, workCounter As Integer, holdCounter As Integer

    'Turns off display of screen updates and alerts.
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    'Removes all but the summary sheet "Report".
    For Each keepThis In Application.ActiveWorkbook.Worksheets
        If keepThis.Name <> "Report" Then
            keepThis.Delete
        End If
    Next

    'Displays an open file dialog box for selecting the target Source file.
    Set sThisBk = ActiveWorkbook
    sImportFile = Application.GetOpenFilename( _
    FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Select a file saved from Source")

    'Handles no sheet selection.
    If sImportFile = "False" Then
        MsgBox "No File Selected!"
        Exit Sub

    'Opens the targeted file and copies the sheet.
    Else
        sFile = Dir(sImportFile)
        Application.Workbooks.Open fileName:=sImportFile
        Set wbBk = Workbooks(sFile)
        With wbBk
            Set wSheet = .Sheets("Sheet1")
            wSheet.Copy after:=sThisBk.Sheets("PBUS Report")
            ActiveSheet.Name = "Source"
            Sheets("PBUS Report").Activate
            wbBk.Close SaveChanges:=False
        End With
    End If

    'Clears everything below the headers.
    Worksheets("Report").Rows(7 & ":" & Worksheets("Report").Rows.Count).Delete

    'Inserts the list of unique PRODICT CODEs from the Source sheet.
    Set wSheet = Worksheets("Report")
    Set sSheet = Worksheets("Source")
    sSheet.Activate
    sSheet.Range("O2", Cells(Rows.Count, "O").End(xlUp)).Copy
    wSheet.Activate
    wSheet.Range("B7").PasteSpecial

    'Sorts and adjusts after paste, also captures the range of PRODUCT CODEs.
    Selection.Interior.Color = xlNone
    Selection.Font.Bold = False
    wSheet.Columns("B:B").EntireColumn.AutoFit
    Application.Selection.RemoveDuplicates Columns:=1, Header:=xlNo
    Set nameRange = wSheet.Range("B7", Cells(Rows.Count, "B").End(xlUp))
    nameRange.Sort key1:=ActiveCell, order1:=xlAscending

This part works great, I get a unique and alphabetized list of product codes from Source column O starting at row 2 in Report column B starting at row 7.

I'm stuck with the loop that counts rows on the Source sheet. For every unique product code in Report (column B starting at 7), I need to count the number of rows in Source (column O starting at 2) where the code matches AND another column contains a status description. Descriptions being either "Plant" or "Storage" in Source column Z, or "Working" or "Holding" in Source column C. There are more descriptions in either but I only track those 4 per product code.

    'Loop through the range of PRODUCT CODEs to build report.
    Set orderRange = sSheet.Range("O2", sSheet.Cells(Rows.Count, "O").End(xlUp))
    rowCounterW = 7 'Starting offset for populating the report.
    For Each c In nameRange.Rows
        pediCounter = 0 'Counter for pedigree column.
        adhoCounter = 0 'Counter for ad-hoc column.
        workCounter = 0 'Counter for working column.
        holdCounter = 0 'Counter for hold column.
        cellName = c.Value

        For Each d In orderRange.Rows
             rowCounterS = orderRange.Row + 1
             If sSheet.Cells(rowCounterS, "O") = cellName Then 'If the program name matches on both sheets.
                If sSheet.Cells(rowCounterS, "Z") = "Plant" Then
                    pediCounter = pediCounter + 1 'Counts for pedigree column.
                End If
                If sSheet.Cells(rowCounterS, "Z") = "Storage" Then
                    adhoCounter = adhoCounter + 1 'Counts for ad-hoc column.
                End If
                If sSheet.Cells(rowCounterS, "C") = "Working" Then
                    workCounter = workCounter + 1 'Counts for working column.
                End If
                If sSheet.Cells(rowCounterS, "C") = "Holding" Then
                    holdCounter = holdCounter + 1 'Counts for hold column.
                End If
            End If

        Next d
        wSheet.Cells(rowCounterW, "C") = pediCounter
        wSheet.Cells(rowCounterW, "D") = adhoCounter
        wSheet.Cells(rowCounterW, "E") = wSheet.Cells(rowCounterW, "C") + wSheet.Cells(rowCounterW, "D")
        wSheet.Cells(rowCounterW, "F") = workCounter
        wSheet.Cells(rowCounterW, "G") = holdCounter
        wSheet.Cells(rowCounterW, "H") = wSheet.Cells(rowCounterW, "E") + wSheet.Cells(rowCounterW, "F") + wSheet.Cells(rowCounterW, "G")
        rowCounterW = rowCounter + 1
    Next c

This iteration does not count or populate correctly, but it does compile. It only populates the row of B7 with 0s and gives up. I am trying to accomplish:

    For Each "product code" in "range of product codes" on Report
        For Each row on Source starting at 2
            If "that row" contains a matching "product code" from Report
                And If "that row" also contains "desired status1"
                    Add 1 to counter for "desired status1"
                And If "that row" also contains "desired status2"
                    Add 1 to a counter for "desired status2"
                etc...
    Populate Report column C with status 1 from the counter
    Populate Report column D with status 2 from the counter
    etc...
    Next "product code"

How did I mess this up? Trying all day with variations on that syntax once got all the fields to populate with status numbers, but they were all 0s like the first row. Currently only getting top row populating 0s. I don't understand why the dynamic range worked once to get the unique product code list once but not in the next step to loop.

EDIT: Caught a typo with rowCounterW at the bottom that stopped it from looping more than once. Also replaces some variables to count rows on the Source sheet better. Working as follows:

    'Loop through the range of PRODUCT CODEs to build report.
    rowCounterW = 7 'Starting offset for populating the report.
    For Each c In nameRange
        pediCounter = 0 'Counter for pedigree column.
        adhoCounter = 0 'Counter for ad-hoc column.
        workCounter = 0 'Counter for working column.
        holdCounter = 0 'Counter for hold column.
        cellName = c.Value

        For i = 2 To sSheet.Cells(Rows.Count, 2).End(xlUp).Row
            If sSheet.Cells(i, "O") = cellName Then 'If the program name matches on both sheets.
                If sSheet.Cells(i, "Z") = "Plant" Then
                    pediCounter = pediCounter + 1 'Counts for pedigree column.
                End If
                If sSheet.Cells(i, "Z") = "Storage" Then
                    adhoCounter = adhoCounter + 1 'Counts for ad-hoc column.
                End If
                If sSheet.Cells(i, "C") = "Working" Then
                    workCounter = workCounter + 1 'Counts for working column.
                End If
                If sSheet.Cells(i, "C") = "Holding" Then
                    holdCounter = holdCounter + 1 'Counts for hold column.
                End If
            End If
        Next i
        'Populates the report after parsing every row.
        wSheet.Cells(rowCounterW, "C") = pediCounter
        wSheet.Cells(rowCounterW, "D") = adhoCounter
        wSheet.Cells(rowCounterW, "E") = wSheet.Cells(rowCounterW, "C") + wSheet.Cells(rowCounterW, "D")
        wSheet.Cells(rowCounterW, "F") = workCounter
        wSheet.Cells(rowCounterW, "G") = holdCounter
        wSheet.Cells(rowCounterW, "H") = wSheet.Cells(rowCounterW, "E") + wSheet.Cells(rowCounterW, "F") + wSheet.Cells(rowCounterW, "G")
        rowCounterW = rowCounterW + 1
    Next c

Body:
Sorry I didn't take the time to match your variables, but I don't have time to fix it up (mine deals with Projects/People/Hours)...

I'd start by defining a few data structures:

Type ZCOType
    WBS As String
    ActivityType As String
    EmployeeName As String
    ProductionOrder As String
    Hours As Double
End Type

Type WeeklyManpower
    StartDate As Date
    EndDate As Date
    Hours As Double
    People As Long
    Data() As ZCOType
    DataCount As Long
End Type

Public g_ManpowerData() As WeeklyManpower, g_ManpowerCount As Long

...Read the data into a variant array (for speed)

Dim vData
vData = sSheet.Range("O2", Cells(Rows.Count, "O").End(xlUp))

...Loop through the vData array more of less like it's the same as looping through rows & columns and assigning the values to the Data Structure

For iRow = 2 To iLastRow
    ' Search for an data entry, with the same Start Date
    For Index = 0 to g_ManpowerCount -1
        If StartDate = vData(iRow,1) then exit for
    Next Index
    ' If not found, create a new Record
    if Index >= g_ManpowerCount then
        ReDim Preserve g_ManpowerData(g_ManpowerCount)
        g_ManpowerData(Index).StartDate  = vData(irow,1)
        g_ManpowerCount = g_ManpowerCount + 1
    end if
    '
    With g_ManpowerData(Index)
        ReDim Preserve .Data(.DataCount)
        With .Data(.DataCount)
            .EmployeeName  = vData(irow,5)
            '....
        End With
        .DataCount=.DataCount+1
    End With
Next

Use a custom sort function to sort the list:

Public Sub QuickSortManpower(ManpowerData() As WeeklyManpower, intBottom As Integer, intTop As Integer)

Get ready to dump the data back into the spreadsheet by putting it into a Variant array:

Dim vProjectedData
ReDim vProjectedData(g_ManpowerCount,7)
For i = 0 To g_ManpowerCount
    vProjectedData(i, 1) = ManpowerData(i).StartDate
    vProjectedData(i, 2) = ManpowerData(i).EndDate
    vProjectedData(i, 3) = ManpowerData(i).Hours
    '...
Next

And finally, dump the values onto the sheet

Sheet.Cells(2, 1).Resize(Rows + 1, 8) = vProjectedData

Add headers/formatting as needed...


来源: stackexchange

问:
How to get Pinterest Total Share Count Using Javascript?
What i require? I need to get a total share count using javascript.

Using this link: https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=http://google.com

I can get the result:
receiveCount({"url":"http://google.com","count":11278})

My code which is not working, i'm not sure which part of the code is wrong. Below:

#pin-div {
  color: red
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>

<div id="pin-div">0</div>

<script type="text/javascript">
  $(function() {
    var url = "http://facebook.com";
    var apiUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;

    $.ajax({
      url: apiUrl,
      success: function(result) {
        $.each(result, function(key, val) {
          console.log(key + " - " + val["receiveCount"]["count"]);
          var shareCount = val["receiveCount"]["count"];
          $("#pin-div").html(shareCount);
        });
      }
    });
  });
</script></code>```

答:
Your data is jsonp: receiveCount({"url":"http://google.com","count":11278}). Where the receiveCount function must be created in the window context to hold the data.

You need to add: dataType: "jsonp" in your $.ajax code.

You can try with this version of your code:

#pin-div {
  color: red
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>

<div id="pin-div">0</div>

<script type="text/javascript">
  $(function() {
    var url = "http://facebook.com";
    var apiUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;

    $.ajax({
      url: apiUrl,
      dataType: "jsonp",
      success: function(result) {
        receiveCount(result);
      }
    });
  });

  function receiveCount(data) {
    $("#pin-div").html(data.count);
  }
</script></code>```

ContentLicense: CC BY-SA 3.0

Body:
What i require? I need to get a total share count using javascript.

Using this link: https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=http://google.com

I can get the result:
receiveCount({"url":"http://google.com","count":11278})

My code which is not working, i'm not sure which part of the code is wrong. Below:

#pin-div {
  color: red
}

0

Body:
Your data is jsonp: receiveCount({"url":"http://google.com","count":11278}). Where the receiveCount function must be created in the window context to hold the data.

You need to add: dataType: "jsonp" in your $.ajax code.

You can try with this version of your code:

#pin-div {
  color: red
}

<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>

<div id="pin-div">0</div>

<script type="text/javascript">
  $(function() {
    var url = "http://facebook.com";
    var apiUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;

    $.ajax({
      url: apiUrl,
      dataType: "jsonp",
      success: function(result) {
        receiveCount(result);
      }
    });
  });

  function receiveCount(data) {
    $("#pin-div").html(data.count);
  }
</script>


问:
Blocks types with image (important, warning, ...)
I would like to have blocks with a image on the left.  I start using the package in RStudio, but even if I use the type tag it does not work.

I think the style that comes with the package does not provide this feature. Is that right?

答:
try to copy the custom blocks

you can use google chrome to open the page press Ctrl+Shift+I

choose source and navigate to the style.css

you can also download the same pictures here easily

Style.css

```<code>.rmdcaution, .rmdimportant, .rmdnote, .rmdtip, .rmdwarning {
  padding: 1em 1em 1em 4em;
  margin-bottom: 10px;
  background: #f5f5f5 5px center/3em no-repeat;
}
.rmdcaution {
  background-image: url("../images/caution.png");
}
.rmdimportant {
  background-image: url("../images/important.png");
}
.rmdnote {
  background-image: url("../images/note.png");
}
.rmdtip {
  background-image: url("../images/tip.png");
}
.rmdwarning {
  background-image: url("../images/warning.png");
}
p.caption {
  color: #777;
  margin-top: 10px;
}
p code {
  white-space: inherit;
}
pre {
  word-break: normal;
  word-wrap: normal;
}
pre code {
  white-space: inherit;
}
p.flushright {
  text-align: right;
}
blockquote > p:last-child {
  text-align: right;
}
blockquote > p:first-child {
  text-align: inherit;
}
.header-section-number {
  padding-right: .2em;
  font-weight: 500;
}
.level1 .header-section-number {
  display: inline-block;
  border-bottom: 3px solid;
}
.level1 h1 {
  border-bottom: 1px solid;
}
h1, h2, h3, h4, h5, h6 {
  font-weight: normal;
}
h1.title {
  font-weight: 700;
}
.book .book-body .page-wrapper .page-inner section.normal strong {
  font-weight: 500;
}
</code>```

Body:
try to copy the custom blocks

you can use google chrome to open the page press Ctrl+Shift+I

choose source and navigate to the style.css

you can also download the same pictures here easily

Style.css

.rmdcaution, .rmdimportant, .rmdnote, .rmdtip, .rmdwarning {
  padding: 1em 1em 1em 4em;
  margin-bottom: 10px;
  background: #f5f5f5 5px center/3em no-repeat;
}
.rmdcaution {
  background-image: url("../images/caution.png");
}
.rmdimportant {
  background-image: url("../images/important.png");
}
.rmdnote {
  background-image: url("../images/note.png");
}
.rmdtip {
  background-image: url("../images/tip.png");
}
.rmdwarning {
  background-image: url("../images/warning.png");
}
p.caption {
  color: #777;
  margin-top: 10px;
}
p code {
  white-space: inherit;
}
pre {
  word-break: normal;
  word-wrap: normal;
}
pre code {
  white-space: inherit;
}
p.flushright {
  text-align: right;
}
blockquote > p:last-child {
  text-align: right;
}
blockquote > p:first-child {
  text-align: inherit;
}
.header-section-number {
  padding-right: .2em;
  font-weight: 500;
}
.level1 .header-section-number {
  display: inline-block;
  border-bottom: 3px solid;
}
.level1 h1 {
  border-bottom: 1px solid;
}
h1, h2, h3, h4, h5, h6 {
  font-weight: normal;
}
h1.title {
  font-weight: 700;
}
.book .book-body .page-wrapper .page-inner section.normal strong {
  font-weight: 500;
}


问:
ng-repeat with ng-selected
I am trying to figure out how to generate list of option elements using ng-repeat, but one of them to be marked as the selected option on load.

After googling, what I found is this base, which I modified by adding the selected property to the data objects
https://plnkr.co/edit/7g4MeAQnG4PzpnrebBGc?p=preview
However, it seems that ng-selected="option.selected == true" has no effect :(

Why? I also have the more complex example here: http://jsfiddle.net/ej5fx3kr/14/ which works, although I am not sure what is the difference, or what is the model here used for (note: changing the model name from "program" to anything, it still works... so not sure what is the purpose).

Bonus points: How do I debug code in AngularJS in directives? Like experiment in debug mode line by line to actually see what are the variable values in that particular scope, what is available to use, etc...

My ultimate goal in this question, is to load list of values via ajax on page load in the controller, IF there is a routeParam in the URL, find it in the list of loaded values, and add selected attribute, then set selected=true in the generated HTML on page load, otherwise not pre-select anything in the populated select box on the page load, so this is why its important for me to understand this on the simplest example before trying to plug this in.

Thanks!

答:
The "Angular Way" to handle this is to use ng-options instead of ng-repeat, and then simply set the model equal to the default value on controller load.

For example:

```<code><select ng-options="option.name for option in data.availableOptions"
        ng-model="selectedItem"></select>

$scope.selectedItem=$scope.data.availableOptions[2];
</code>```

For a more advanced case, where your ng-model might not be the object in the array, but a single property, you can use a modified version of ng-options:

```<code><select ng-options="option.id as option.name for option in data.availableOptions"
        ng-model="selectedId"></select>

$scope.selectedId = '2';
</code>```

Here is a modified version of your plunker showing these different possibilities:  https://plnkr.co/edit/xzYmXf8C3WuZaelwj5hO?p=preview

Title: ng-repeat with ng-selected

Body:
The "Angular Way" to handle this is to use ng-options instead of ng-repeat, and then simply set the model equal to the default value on controller load.

For example:

<select ng-options="option.name for option in data.availableOptions"
        ng-model="selectedItem"></select>

$scope.selectedItem=$scope.data.availableOptions[2];

For a more advanced case, where your ng-model might not be the object in the array, but a single property, you can use a modified version of ng-options:

<select ng-options="option.id as option.name for option in data.availableOptions"
        ng-model="selectedId"></select>

$scope.selectedId = '2';

Here is a modified version of your plunker showing these different possibilities:  https://plnkr.co/edit/xzYmXf8C3WuZaelwj5hO?p=preview


问:
Is there a way to use Postgres' UUID generation with Hibernate's IDENTITY ID generation strategy?
I'm using Spring Boot 1.4.1, which includes Hibernate 5, with Postgres 9.6, and I'm trying to create an entity with a UUID ID but using Postgres' UUID generation instead of Hibernate's. Many similar questions say to set the column type as pg-uuid. That seems to work for non-database-generated ID columns, but when I try to use it for the ID column I get

org.hibernate.id.IdentifierGenerationException: unrecognized id type : pg-uuid -> java.util.UUID

So it looks like Hibernate is applying the type correctly, but not converting it.

Here is how the ID column of my entity is setup:

```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@org.hibernate.annotations.Type(type="pg-uuid")
private UUID id;
</code>```

And the table is setup similar to as follows (uuid-ossp is installed)

```<code>create table example (
    id UUID NOT NULL DEFAULT uuid_generate_v1mc(),
    ...
);
</code>```

I would prefer to have the database generate the UUIDs and don't want to use Hibernate's generation strategies. Is there a way to get this to work?

答:
You can use strategy: AUTO

```<code>@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
</code>```

Here is a working example

Body:
I'm using Spring Boot 1.4.1, which includes Hibernate 5, with Postgres 9.6, and I'm trying to create an entity with a UUID ID but using Postgres' UUID generation instead of Hibernate's. Many similar questions say to set the column type as pg-uuid. That seems to work for non-database-generated ID columns, but when I try to use it for the ID column I get

org.hibernate.id.IdentifierGenerationException: unrecognized id type : pg-uuid -> java.util.UUID

So it looks like Hibernate is applying the type correctly, but not converting it.

Here is how the ID column of my entity is setup:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@org.hibernate.annotations.Type(type="pg-uuid")
private UUID id;

And the table is setup similar to as follows (uuid-ossp is installed)

create table example (
    id UUID NOT NULL DEFAULT uuid_generate_v1mc(),
    ...
);

I would prefer to have the database generate the UUIDs and don't want to use Hibernate's generation strategies. Is there a way to get this to work?

Body:
You can use strategy: AUTO

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;

Here is a working example

ContentLicense: CC BY-SA 4.0


问:
Concatenation with FILTER clause
This question follows this one.

I now have this code:

```<code>select
    min(purchaseDate) filter (where fruitType = 'apple') as appleFirstPurchaseDate,
    min(purchaseDate) filter (where fruitType = 'orange') as orangeFirstPurchaseDate,
    customer
from fruitPurchases
group by customer
</code>```

Which gives the following output:

```<code>appleFirstPurchaseDate  orangeFirstPurchaseDate
----------------------  -----------------------
       2017-05-03              2016-11-25
</code>```

You should also know that each piece of fruit has an ID. With this ID, I'd like to create two keys: one that concatenates the fruit ID with the appleFirstPurchaseDate and the other one that concatenates the fruit ID with the orangeFirstPurchaseDate

Therefore I tried this:

```<code>select
    fruitId || '-' || min(purchaseDate) filter (where fruitType = 'apple') as appleKey,
    min(purchaseDate) filter (where fruitType = 'apple') as apple,
    fruitId || '-' || min(purchaseDate) filter (where fruitType = 'orange') as orangeKey,
    min(purchaseDate) filter (where fruitType = 'orange') as orange,
    customer
from fruitPurchases
group by customer, fruitId
</code>```

But when a customer has already bought apples as well as oranges, it unfortunately gives me this:

```<code>  appleKey        appleFirstPurchaseDate    orangeKey    orangeFirstPurchaseDate
  --------        ----------------------    ---------    -----------------------
283-2017-05-03          2017-05-03           [NULL]             [NULL]
   [NULL]                 [NULL]          322-2016-11-25      2016-11-25
</code>```

While I would like this:

```<code>  appleKey        appleFirstPurchaseDate    orangeKey    orangeFirstPurchaseDate
  --------        ----------------------    ---------    -----------------------
283-2017-05-03          2017-05-03       322-2016-11-25        2016-11-25
</code>```

Last piece of information: an earlier FirstPurchaseDate does not imply a lower fruitID.

答:
You might find this easier with window functions:

```<code>select distinct customer,
       first_value(fruitId || '-' purchaseDate) filter (where fruittype = 'apple') over (partition by customer order by purchaseDate) as appleKey,
       first_value(fruitId || '-' purchaseDate) filter (where fruittype = 'orange') over (partition by customer order by purchaseDate) as orangeKey
from fruitPurchases;
</code>```

You can also write this as:

```<code>select distinct customer,
       first_value(case when fruittype = 'apple' then fruitId || '-' || purchaseDate end) over (partition by customer order by (fruittype = 'apple')::int desc, purchaseDate) as appleKey,
       first_value(case when fruittype = 'orange' then fruitId || '-' || purchaseDate end) over (partition by customer order by (fruittype = 'orange')::int desc, purchaseDate) as orangeKey
from fruitPurchases;
</code>```

Here is a SQL Fiddle.

Title: Concatenation with FILTER clause

Body:
This question follows this one.

I now have this code:

select
    min(purchaseDate) filter (where fruitType = 'apple') as appleFirstPurchaseDate,
    min(purchaseDate) filter (where fruitType = 'orange') as orangeFirstPurchaseDate,
    customer
from fruitPurchases
group by customer

Which gives the following output:

appleFirstPurchaseDate  orangeFirstPurchaseDate
----------------------  -----------------------
       2017-05-03              2016-11-25

You should also know that each piece of fruit has an ID. With this ID, I'd like to create two keys: one that concatenates the fruit ID with the appleFirstPurchaseDate and the other one that concatenates the fruit ID with the orangeFirstPurchaseDate

Therefore I tried this:

select
    fruitId || '-' || min(purchaseDate) filter (where fruitType = 'apple') as appleKey,
    min(purchaseDate) filter (where fruitType = 'apple') as apple,
    fruitId || '-' || min(purchaseDate) filter (where fruitType = 'orange') as orangeKey,
    min(purchaseDate) filter (where fruitType = 'orange') as orange,
    customer
from fruitPurchases
group by customer, fruitId

But when a customer has already bought apples as well as oranges, it unfortunately gives me this:

  appleKey        appleFirstPurchaseDate    orangeKey    orangeFirstPurchaseDate
  --------        ----------------------    ---------    -----------------------
283-2017-05-03          2017-05-03           [NULL]             [NULL]
   [NULL]                 [NULL]          322-2016-11-25      2016-11-25

While I would like this:

  appleKey        appleFirstPurchaseDate    orangeKey    orangeFirstPurchaseDate
  --------        ----------------------    ---------    -----------------------
283-2017-05-03          2017-05-03       322-2016-11-25        2016-11-25

Last piece of information: an earlier FirstPurchaseDate does not imply a lower fruitID.

Body:
You might find this easier with window functions:

select distinct customer,
       first_value(fruitId || '-' purchaseDate) filter (where fruittype = 'apple') over (partition by customer order by purchaseDate) as appleKey,
       first_value(fruitId || '-' purchaseDate) filter (where fruittype = 'orange') over (partition by customer order by purchaseDate) as orangeKey
from fruitPurchases;

You can also write this as:

select distinct customer,
       first_value(case when fruittype = 'apple' then fruitId || '-' || purchaseDate end) over (partition by customer order by (fruittype = 'apple')::int desc, purchaseDate) as appleKey,
       first_value(case when fruittype = 'orange' then fruitId || '-' || purchaseDate end) over (partition by customer order by (fruittype = 'orange')::int desc, purchaseDate) as orangeKey
from fruitPurchases;

Here is a SQL Fiddle.


问:
Sending images or buttons on facebook messenger via ibm watson configuered via botkit
I have made a wotson chat bot, deployed on facebbok messenger the broker is a node app just like in this github example. I'm recieving text responses perfectly but how do I configure the bot to send images or buttons to the fb messenger. I have tried Respond with JSON option in watson dialog.
JSON:

```<code>{
  "output": {

  },
"context":{
"facebook":{
  "message":{
    "attachment":{
        "type":"image",
        "payload":{
            "url":"https://petersapparel.com/img/shirt.png"
        }
    }
  }
}
}
}
</code>```

I Think there is some problem with my JSON.

答:
To send buttons define message with template_type generic and buttons with type postback

```<code>controller.hears('test', 'message_received', function(bot, message) {

    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'generic',
            'elements':[
                {
                    'title':'Chocolate Cookie',
                    'image_url':'http://cookies.com/cookie.png',
                    'subtitle':'A delicious chocolate cookie',
                    'buttons':[
                        {
                        'type':'postback',
                        'title':'Eat Cookie',
                        'payload':'chocolate'
                        }
                    ]
                },
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

});
</code>```

To send attachment define attachment message with resource url and call upload method.

```<code>controller.hears('test', 'message_received', function(bot, message) {

var attachment = {
        "type":"image",
        "payload":{
            "url":"https://pbs.twimg.com/profile_images/803642201653858305/IAW1DBPw_400x400.png",
            "is_reusable": true
        }
    };

    controller.api.attachment_upload.upload(attachment, function (err, attachmentId) {
        if(err) {
            // Error
        } else {
            var image = {
                "attachment":{
                    "type":"image",
                    "payload": {
                        "attachment_id": attachmentId
                    }
                }
            };
            bot.reply(message, image);
        }
    });
}
</code>```

Check Botkit Messenger documentation.

Body:
I have made a wotson chat bot, deployed on facebbok messenger the broker is a node app just like in this github example. I'm recieving text responses perfectly but how do I configure the bot to send images or buttons to the fb messenger. I have tried Respond with JSON option in watson dialog.
JSON:

{
  "output": {

  },
"context":{
"facebook":{
  "message":{
    "attachment":{
        "type":"image",
        "payload":{
            "url":"https://petersapparel.com/img/shirt.png"
        }
    }
  }
}
}
}

I Think there is some problem with my JSON.

Body:
To send buttons define message with template_type generic and buttons with type postback

controller.hears('test', 'message_received', function(bot, message) {

    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'generic',
            'elements':[
                {
                    'title':'Chocolate Cookie',
                    'image_url':'http://cookies.com/cookie.png',
                    'subtitle':'A delicious chocolate cookie',
                    'buttons':[
                        {
                        'type':'postback',
                        'title':'Eat Cookie',
                        'payload':'chocolate'
                        }
                    ]
                },
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

});

To send attachment define attachment message with resource url and call upload method.

controller.hears('test', 'message_received', function(bot, message) {

var attachment = {
        "type":"image",
        "payload":{
            "url":"https://pbs.twimg.com/profile_images/803642201653858305/IAW1DBPw_400x400.png",
            "is_reusable": true
        }
    };

    controller.api.attachment_upload.upload(attachment, function (err, attachmentId) {
        if(err) {
            // Error
        } else {
            var image = {
                "attachment":{
                    "type":"image",
                    "payload": {
                        "attachment_id": attachmentId
                    }
                }
            };
            bot.reply(message, image);
        }
    });
}

Check Botkit Messenger documentation.


问:
Access - how to derive a field upon entry of a record
I have an Access database for a media rental company which includes the following tables, among others;

LOAN:
customer_id (pk),
loan_datetimeLeant (pk),
loan_dateReturned (pk)

LOAN_ITEMS:
customer_id (pk),
loan_datetimeLeant (pk),
item_id (pk),
loanItem_cost

ITEM:
item_id (pk),
product_id,
item_availability

PRODUCT:
product_id (pk),
product_name,
product_type

MEDIA_COST:
product_type (pk),
product_cost

So basically the 'product type' (DVD, VHS etc) determines the cost. The 'product id' determines what movie, platform etc each item is.

My question is:
When creating a form for the Loan_Items table, how can I populate the loanItem_cost field (so it is stored) whenever a new Loan_Item record is added? I need to store it as the cost of the item (product_cost) may change over time and I'd like to record what the customer paid at the time the loan was made.

Thanks in advance

答: You can create an update query to update your loan item cost from the current product cost.  Then to perform the update, just execute the query.

ContentLicense: CC BY-SA 2.5


问:
Hibernate Caching and lazy loaded associations
I got a typical entity association of order and items. To make it possible to read only orders, the items set is default FetchType.LAZY. 2nd level and query cache is enabled. To read an order with associated items, I'm using a JPQL query. The query and the entities are cached by EHCache. But on the second call when accessing items, a LazyInitializationException was thrown, because items are not initialized (not restored from cache). Why? What's the best way to implement this requirement?

Order:

```<code>@Entity
@Cacheable
@NamedQueries({
  @NamedQuery(name = Order.NQ_FIND_BY_ID_FETCH_ITEMS, query = "SELECT DISTINCT o FROM Order o JOIN FETCH o.items WHERE o.id = :id")
})
@Table(...)
public class Order extends ... {
  ...
  @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
  // @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
  private Set<Item> items = new HashSet<Item>();
  ...
}
</code>```

Item:

```<code>@Entity
@Cacheable
@Table(...)
public class Item extends ... {
  @ManyToOne
  @JoinColumn(name = "order_id", nullable = false)
  private Order order;
  ...
}
</code>```

DAO:

```<code>public class OrderDaoJpaImpl extends ... {

  @Override
  public Catalog findByIdFetchItems(Long id) {
    TypedQuery<Order> query = entityManager.createNamedQuery(Order.NQ_FIND_BY_ID_FETCH_ITEMS, Order.class);
    query.setParameter("id", id);
    // query.setHint(QueryHints.HINT_CACHEABLE, Boolean.TRUE);
    Order order = JPAUtil.singleResultOrNull(query);
    return order;
}
</code>```

Service:

```<code>@Service("orderService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class OrderServiceImpl implements OrderService {

  @Override
  public Order getOrderWithItems(Long orderId) {
    return orderDao.findByIdFetchItems(orderId);
  }
}
</code>```

persistence.xml:

```<code><persistence ...>
  <persistence-unit name="shop-persistence" transaction-type="RESOURCE_LOCAL">
    <jar-file>shop-persistence.jar</jar-file>
    <!-- Enable JPA 2 second level cache -->
    <shared-cache-mode>ALL</shared-cache-mode>
    <properties>
      ...
      <property name="hibernate.cache.use_second_level_cache" value="true" />
      <property name="hibernate.cache.use_query_cache" value="true" />
      <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
    </properties>
  </persistence-unit>
</persistence>
</code>```

Spring Framework 4.3.7.RELEASE and Hibernate 5.2.9.Final.

As you can see, I've tried to use Hibernate entity annotations and cache hints instead of JPA caching. I've also tried JPA entity graphs instead of JOIN FETCH. Always the same: Items are not initialized/restored on the second call of the order query.

答:
I think the @Cacheable is not Hibernate cache, but Spring cache.
@Cache annotation is for Hibernate cache.
Besides of this, when I have troubles with this stuff, to get the JOIN FETCH result also usable with cache, I had to add Hibernate.initialize(...) to the Dao method to avoid LazyInitializationException.</p>

Body:
I got a typical entity association of order and items. To make it possible to read only orders, the items set is default FetchType.LAZY. 2nd level and query cache is enabled. To read an order with associated items, I'm using a JPQL query. The query and the entities are cached by EHCache. But on the second call when accessing items, a LazyInitializationException was thrown, because items are not initialized (not restored from cache). Why? What's the best way to implement this requirement?

Order:

@Entity
@Cacheable
@NamedQueries({
  @NamedQuery(name = Order.NQ_FIND_BY_ID_FETCH_ITEMS, query = "SELECT DISTINCT o FROM Order o JOIN FETCH o.items WHERE o.id = :id")
})
@Table(...)
public class Order extends ... {
  ...
  @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
  // @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
  private Set<Item> items = new HashSet<Item>();
  ...
}

Item:

@Entity
@Cacheable
@Table(...)
public class Item extends ... {
  @ManyToOne
  @JoinColumn(name = "order_id", nullable = false)
  private Order order;
  ...
}

DAO:

public class OrderDaoJpaImpl extends ... {

  @Override
  public Catalog findByIdFetchItems(Long id) {
    TypedQuery<Order> query = entityManager.createNamedQuery(Order.NQ_FIND_BY_ID_FETCH_ITEMS, Order.class);
    query.setParameter("id", id);
    // query.setHint(QueryHints.HINT_CACHEABLE, Boolean.TRUE);
    Order order = JPAUtil.singleResultOrNull(query);
    return order;
}

Service:

@Service("orderService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class OrderServiceImpl implements OrderService {

  @Override
  public Order getOrderWithItems(Long orderId) {
    return orderDao.findByIdFetchItems(orderId);
  }
}

persistence.xml:

<persistence ...>
  <persistence-unit name="shop-persistence" transaction-type="RESOURCE_LOCAL">
    <jar-file>shop-persistence.jar</jar-file>

    <shared-cache-mode>ALL</shared-cache-mode>
    <properties>
      ...
      <property name="hibernate.cache.use_second_level_cache" value="true" />
      <property name="hibernate.cache.use_query_cache" value="true" />
      <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
    </properties>
  </persistence-unit>
</persistence>

Spring Framework 4.3.7.RELEASE and Hibernate 5.2.9.Final.

As you can see, I've tried to use Hibernate entity annotations and cache hints instead of JPA caching. I've also tried JPA entity graphs instead of JOIN FETCH. Always the same: Items are not initialized/restored on the second call of the order query.


问:
ajax returns page source, not the message
All the answers I saw here or elsewhere on Google were with jquery. This is not jquery.

I send an ajax string to a php file.

The php, among other things, formulates a message string which I echo
back to the client.

The returned string is put up in the client as an alert.

The form is then reset.

The problem is that when I do this it puts up as much of the page source that the alert can handle. If I open developer tools to look at the return, it puts the message up correctly, not the page source. Here is the return snippet in my ajax:

```<code>ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
        alert(ajaxRequest.responseText);
        document.getElementById("thisForm").reset();
    }
}
</code>```

The php file does a simple echo of a text string.

What is it about developer tools that makes this run correctly and why doesn't it print out the message in the alert when developer tools is not there?

When I run the backend php by itself, with or without developer tools, it displays the message properly.

Does anyone have any ideas?

More information: I tried to replace the alert and reset with a
display.innerHTML=ajaxRequest.responseText   where display is a javascript object formed from getElementById("ajaxReturn") of a "div id="ajaxReturn". It didn't work. When I tried developer tools, it showed the network response text as being the page source.

I also added    && this.status == 200  to the if statement.  No change.

答: The problem is solved.  I am not deleting this because it might help some other poster who runs into the same problem.  I launched the AJAX with an onclick to a javascript function called ajaxFunction().  The html entity containing the onclick had an href="#" in it. Removing that href solved the problem.</p>

Body:
All the answers I saw here or elsewhere on Google were with jquery. This is not jquery.

I send an ajax string to a php file.

The php, among other things, formulates a message string which I echo
back to the client.

The returned string is put up in the client as an alert.

The form is then reset.

The problem is that when I do this it puts up as much of the page source that the alert can handle. If I open developer tools to look at the return, it puts the message up correctly, not the page source. Here is the return snippet in my ajax:

ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
        alert(ajaxRequest.responseText);
        document.getElementById("thisForm").reset();
    }
}

The php file does a simple echo of a text string.

What is it about developer tools that makes this run correctly and why doesn't it print out the message in the alert when developer tools is not there?

When I run the backend php by itself, with or without developer tools, it displays the message properly.

Does anyone have any ideas?

More information: I tried to replace the alert and reset with a
display.innerHTML=ajaxRequest.responseText   where display is a javascript object formed from getElementById("ajaxReturn") of a "div id="ajaxReturn". It didn't work. When I tried developer tools, it showed the network response text as being the page source.

I also added    && this.status == 200  to the if statement.  No change.


问:
Pass by value Linked list
I am trying to rearrange a Singly linked list. The initial list will be 1,2,3,4,5
and they have to be sorted in 1,5,2,4,3. I have the code and I am trying to understand how it works. Basically I am stuck at the concept of pass by value in java.

The complete code

```<code>public class Test {
public static void main(String[] args) {

    LinkedLists linkedList = new LinkedLists();
    linkedList.append(1);
    linkedList.append(2);
    linkedList.append(3);
    linkedList.append(4);
    linkedList.append(5);
    linkedList.reorderList();

}}

class Node {
int data;
Node next;

public Node(int data) {
    this.data = data;
}}
</code>```

class LinkedLists {

```<code>Node head;

public void reorderList() {
    if (head == null) {
        System.out.println(head);
        return;
    }
    Node slowPointer = head;
    Node fastPointer = head.next;
    System.out.println(slowPointer.hashCode());
    System.out.println(head.hashCode());
    while (fastPointer != null && fastPointer.next != null) {
        fastPointer = fastPointer.next.next;
        slowPointer = slowPointer.next;// why head value did not change
    }

    Node head2 = slowPointer.next;
    slowPointer.next = null;// why did the head value change here
    LinkedList<Node> queue = new LinkedList<Node>();
    while (head2 != null) {
        Node temp = head2;
        head2 = head2.next;
        temp.next = null;
        queue.push(temp);
    }
    while (!queue.isEmpty()) {
        Node temp = queue.pop();
        temp.next = head.next;
        head.next = temp;
        head = temp.next;
    }

}

public void append(int data) {
    if (head == null) {
        head = new Node(data);
        return;
    }
    Node current = head;
    while (current.next != null) {
        current = current.next;
    }
    current.next = new Node(data);
}}
</code>```

The value of head does not get changed at line

```<code>slowPointer = slowPointer.next;// why head value did not change
</code>```

But at line

```<code>slowPointer.next = null;// why did the head value change here
</code>```

Why does it change here. Thanks.

答:
Because in the first case you are assigning the object pointed by next to the slowPointer.

But in second case you are modifying the value of 'next' of the object being pointed by the reference slowPointer. So the head object is directly modified.

Title: Pass by value Linked list

Body:
I am trying to rearrange a Singly linked list. The initial list will be 1,2,3,4,5
and they have to be sorted in 1,5,2,4,3. I have the code and I am trying to understand how it works. Basically I am stuck at the concept of pass by value in java.

The complete code

public class Test {
public static void main(String[] args) {

    LinkedLists linkedList = new LinkedLists();
    linkedList.append(1);
    linkedList.append(2);
    linkedList.append(3);
    linkedList.append(4);
    linkedList.append(5);
    linkedList.reorderList();

}}

class Node {
int data;
Node next;

public Node(int data) {
    this.data = data;
}}

class LinkedLists {

Node head;

public void reorderList() {
    if (head == null) {
        System.out.println(head);
        return;
    }
    Node slowPointer = head;
    Node fastPointer = head.next;
    System.out.println(slowPointer.hashCode());
    System.out.println(head.hashCode());
    while (fastPointer != null && fastPointer.next != null) {
        fastPointer = fastPointer.next.next;
        slowPointer = slowPointer.next;// why head value did not change
    }

    Node head2 = slowPointer.next;
    slowPointer.next = null;// why did the head value change here
    LinkedList<Node> queue = new LinkedList<Node>();
    while (head2 != null) {
        Node temp = head2;
        head2 = head2.next;
        temp.next = null;
        queue.push(temp);
    }
    while (!queue.isEmpty()) {
        Node temp = queue.pop();
        temp.next = head.next;
        head.next = temp;
        head = temp.next;
    }

}

public void append(int data) {
    if (head == null) {
        head = new Node(data);
        return;
    }
    Node current = head;
    while (current.next != null) {
        current = current.next;
    }
    current.next = new Node(data);
}}

The value of head does not get changed at line

slowPointer = slowPointer.next;// why head value did not change

But at line

slowPointer.next = null;// why did the head value change here

Why does it change here. Thanks.


问:
What would be the software architecture of a videogame?
I'm developing a videogame under Unity. I've been asked to describe the software architecture of my project. My videogame won't be using databases nor it will be connected to a server, it is a platform adventure kind of game with one player.

I have heard of other architectures like client-server, peer-to-peer, service-oriented, but can't find the one that truly fits a videogame.

答:
Without further informations nobody can help you. You need to tell us more about your game.

But I guess you program a multiplayer.

Client-Server

In short every player (client) will connect to a server and this server will mostly do all the work what happens in your game.

Peer-to-Peer (P2P)

Here, there will be only one host (server) and every client will connect on it. Because of this, there will be some problems if the host is far away from the clients and more. Basically if you are the host it is much easier to cheat because you are the server.


问:
Abaqus Surface getSequenceFromMask
I am writing script in Abaqus, where I crush circle and square with cut circle (like cheese). I need to put Contact between parts so I need Surface.

macro manager generates:

```<code>s1 = a.instances['kolo-1'].edges
side1Edges1 = s1.getSequenceFromMask(mask=('[#1 ]', ), )
a.Surface(side1Edges=side1Edges1 , name='kolkoSurf')
</code>```

The problem is: getSequenceFromMask(mask=('[#1 ]', ), )
How to get this #1? Can I replace it? I searched little and there were some ideas to use: 'find', 'face', 'COORDS' but I cannot manage it.
Please help me. I dream to get an simple example how to extract this Surface using X, Y or anyway.

BR,
Wonman

答:
You recorded the above journal using the macro manager with default journal options. Therefore, the variable side1Edges1 is defined in your journal using the getSequenceFromMask()-method. This method is the recording of the selection you performed by clicking the GUI during the recording. This means you clicked the GUI to select an edge and the result is the getSequenceFromMask()-method acting on s1 which is a set of all edges of the instance 'kolo-1'.

According to Abaqus Scripting Reference Guide 6.14 - 7.2.2 the method getSequenceFromMask() is highly efficient when a large number of objects are involved. However, this is not very helpful if your trying to customize your journal file to select another geometry element to work with. There are two solutions:

Solution: Paste the command

```<code>session.journalOptions.setValues(replayGeometry=COORDINATE, recoverGeometry=COORDINATE)
</code>```

into the Abaqus command line at the bottom of Abaqus CAE to set the members replayGeometry and recoverGeometry of your JournalOptions object to COORDINATE and repeat the recording of your journal.
You can, most of the time, omit clicking the GUI again by executing your old journal after issuing the command above.
You can then save your project, preferably with a new name, and use the newly created journal.
In the new journal the command getSequenceFromMask(mask=('[#1 ]', ), ) will by replaced by a selection based on coordinates to represent your recorded GUI-click.
You can then modify the coordinates in order to customize your journal file and to select the edge you like to use in subsequent modeling steps.

Solution: Define side1Edges1 using variables you defined from Scratch in the preceding lines of your python script. I recommend using the journal file as a blueprint in which all click-events have to be replaced using well known variables, defined by yourself. For example, define a list of points myPoints = [(0,0), (0,1) ] using your own logic and then use these points as arguments of the methods e.g. myLine = mySketch.Line(point1=myPoints[0], point2=myPoints[1]), constructing new variables like myLine for the usage in subsequent modeling steps.

To get a basic understanding of the modeling workflow using the Abaqus Python API, i can recommend
Puri, G. M., 2011. Python scripts for Abaqus : learn by example, 1st Edition, also it is hardly available in most universities.

Looking at the Abaqus Benchmark Guide can be helpful, as some newer Benchmarks contain Python scripts (e.g. Fracture Mechanics).

Title: Abaqus Surface getSequenceFromMask

Body:
I am writing script in Abaqus, where I crush circle and square with cut circle (like cheese). I need to put Contact between parts so I need Surface.

macro manager generates:

s1 = a.instances['kolo-1'].edges
side1Edges1 = s1.getSequenceFromMask(mask=('[#1 ]', ), )
a.Surface(side1Edges=side1Edges1 , name='kolkoSurf')

The problem is: getSequenceFromMask(mask=('[#1 ]', ), )
How to get this #1? Can I replace it? I searched little and there were some ideas to use: 'find', 'face', 'COORDS' but I cannot manage it.
Please help me. I dream to get an simple example how to extract this Surface using X, Y or anyway.

BR,
Wonman

Body:
You recorded the above journal using the macro manager with default journal options. Therefore, the variable side1Edges1 is defined in your journal using the getSequenceFromMask()-method. This method is the recording of the selection you performed by clicking the GUI during the recording. This means you clicked the GUI to select an edge and the result is the getSequenceFromMask()-method acting on s1 which is a set of all edges of the instance 'kolo-1'.

According to Abaqus Scripting Reference Guide 6.14 - 7.2.2 the method getSequenceFromMask() is highly efficient when a large number of objects are involved. However, this is not very helpful if your trying to customize your journal file to select another geometry element to work with. There are two solutions:

Solution: Paste the command

session.journalOptions.setValues(replayGeometry=COORDINATE, recoverGeometry=COORDINATE)

into the Abaqus command line at the bottom of Abaqus CAE to set the members replayGeometry and recoverGeometry of your JournalOptions object to COORDINATE and repeat the recording of your journal.
You can, most of the time, omit clicking the GUI again by executing your old journal after issuing the command above.
You can then save your project, preferably with a new name, and use the newly created journal.
In the new journal the command getSequenceFromMask(mask=('[#1 ]', ), ) will by replaced by a selection based on coordinates to represent your recorded GUI-click.
You can then modify the coordinates in order to customize your journal file and to select the edge you like to use in subsequent modeling steps.

Solution: Define side1Edges1 using variables you defined from Scratch in the preceding lines of your python script. I recommend using the journal file as a blueprint in which all click-events have to be replaced using well known variables, defined by yourself. For example, define a list of points myPoints = [(0,0), (0,1) ] using your own logic and then use these points as arguments of the methods e.g. myLine = mySketch.Line(point1=myPoints[0], point2=myPoints[1]), constructing new variables like myLine for the usage in subsequent modeling steps.

To get a basic understanding of the modeling workflow using the Abaqus Python API, i can recommend
Puri, G. M., 2011. Python scripts for Abaqus : learn by example, 1st Edition, also it is hardly available in most universities.

Looking at the Abaqus Benchmark Guide can be helpful, as some newer Benchmarks contain Python scripts (e.g. Fracture Mechanics).


问:
Make spring security add the return to url in the query string for the login page
Earlier I asked if it was possible to get the original request url in the form login page in Spring Security 2. Turns out that actually won't help me, what I need is for the redirect to the form-login page to have that embedded in it as a request parameter. So if I have:

<form-login login-page="/login.html" />
```

and try to access /secure.html I want to end up in /login.html?return_to=/secure.html.

答:
The redirect to the login form is performed by the AuthenticationEntryPoint. For Spring Security 3.0+ this will usually be an instance of LoginUrlAuthenticationEntryPoint. In 2.0 the corresponding class is AuthenticationProcessingFilterEntryPoint.

The entry point is invoked by the ExceptionTranslationFilter which is also responsible for caching the request. You can therefore write a custom AuthenticationEntryPoint which redirects to the login page URL with the additional parameter appended (containing the current request URI). The code should be almost identical to the standard implementation.

You can inject a custom AuthenticationEntryPoint into the namespace configuration using the entry-point-ref attribute on the http namespace element. If you are using plain beans, you would inject it into the ExceptionTranslationFilter.

Body:
Earlier I asked if it was possible to get the original request url in the form login page in Spring Security 2. Turns out that actually won't help me, what I need is for the redirect to the form-login page to have that embedded in it as a request parameter. So if I have:

<form-login login-page="/login.html" />

and try to access /secure.html I want to end up in /login.html?return_to=/secure.html.


问:
Replace special character in data frame
I have a dataframe which contains in different cells a special character which I know which is. An example of the structure:

```<code>df = data.frame(col_1 = c("21 myspec^ch2 12",NA),
                col_2 = c("1 myspec^ch2 4","4 myspec^ch2 212"))
</code>```

The character is this  myspec^ch2 and I would like to replace with -. An example of expected output:

```<code>df = data.frame(col_1 = c("21-12",NA),
                col_2 = c("1-4","4-212"))
</code>```

I tried this but it is not working:

```<code>df [ df == " myspec^ch2 " ] <- "-"
</code>```

答:
You really want to do a regex-style substitution here. However, in regex, ^ is seen as the beginning of the line (rather than a literal caret). So you can do something like this (using the stringr package):

```<code>library(dplyr)
library(stringr)

fixed_df  <- df %>%
    mutate_all(funs(str_replace_all( . , " myspec\\^ch2 ", "-"))
</code>```

Note the double backslashes in front of the caret--that escapes the caret and tells R to interpret it literally, rather than as the beginning of the line.

Title: Replace special character in data frame

Body:
I have a dataframe which contains in different cells a special character which I know which is. An example of the structure:

df = data.frame(col_1 = c("21 myspec^ch2 12",NA),
                col_2 = c("1 myspec^ch2 4","4 myspec^ch2 212"))

The character is this  myspec^ch2 and I would like to replace with -. An example of expected output:

df = data.frame(col_1 = c("21-12",NA),
                col_2 = c("1-4","4-212"))

I tried this but it is not working:

df [ df == " myspec^ch2 " ] <- "-"

Body:
You really want to do a regex-style substitution here. However, in regex, ^ is seen as the beginning of the line (rather than a literal caret). So you can do something like this (using the stringr package):

library(dplyr)
library(stringr)

fixed_df  <- df %>%
    mutate_all(funs(str_replace_all( . , " myspec\\^ch2 ", "-"))

Note the double backslashes in front of the caret--that escapes the caret and tells R to interpret it literally, rather than as the beginning of the line.


问:
how to replace an rx java expression with lambda?
I keep getting expression can be replaced with a lambda for Java 8. How do I go about that? Here's one of the expressions I get that message on:

```<code>Observable.create(new ObservableOnSubscribe<Pair>() {
            @Override
            public void subscribe(@io.reactivex.annotations.NonNull ObservableEmitter<Pair> observableEmitter) throws Exception { ...
</code>```

any idea?

答:
Due to the fact that any interface which has a SAM is by nature a functional interface, we can, therefore, do something like this:

```<code>Observable.create(e -> { /* do logic */ });
</code>```

Note, that the above approach does not bubble up exceptions if any occur within the scope of create. To accomplish such behavior with lambdas (anonymous functions) you can create a wrapper method and perform the logic there i.e:

```<code>public void subscribeWrapper(ObservableEmitter<Pair> e) throws java.lang.Exception {
    // do logic
}
</code>```

then you'd do:

```<code>Observable.create(e -> subscribeWrapper(e));
</code>```

On the other hand, you could ignore creating the said method and use a try/catch within the lambda statement block and rethrow the exception from there.

Body:
I keep getting expression can be replaced with a lambda for Java 8. How do I go about that? Here's one of the expressions I get that message on:

Observable.create(new ObservableOnSubscribe<Pair>() {
            @Override
            public void subscribe(@io.reactivex.annotations.NonNull ObservableEmitter<Pair> observableEmitter) throws Exception { ...

any idea?

Body:
Due to the fact that any interface which has a SAM is by nature a functional interface, we can, therefore, do something like this:

Observable.create(e -> { /* do logic */ });

Note, that the above approach does not bubble up exceptions if any occur within the scope of create. To accomplish such behavior with lambdas (anonymous functions) you can create a wrapper method and perform the logic there i.e:

public void subscribeWrapper(ObservableEmitter<Pair> e) throws java.lang.Exception {
    // do logic
}

then you'd do:

Observable.create(e -> subscribeWrapper(e));

On the other hand, you could ignore creating the said method and use a try/catch within the lambda statement block and rethrow the exception from there.


问:
Timertask not stopping
Hi I have been creating an app that would check if the phone is using wifi or mobile data, using timerTask to inform the user and broadcast Receivers to check if WIFI or MOBILE DATA is open.

Even after I cancel the timerTask it goes to an Error notification and then the wifi notification runs again.

I have been stuck with this problem for hours now and I decided to ask for some help.

This is my MainActivity Class:

```<code>public class MainActivity extends AppCompatActivity {

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

}

public String getConnectivityStatus(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

    String status = null;

    if (null != activeNetwork) {
        if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
            status = "WIFI";
        if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
            status = "DATA";
    }
    else{
        status = "ERROR";
    }
    return status;
}
</code>```

And this is my NetworkChangeReceiver Class:

```<code>public class NetworkChangeReceiver extends BroadcastReceiver {

 //WIFI TIMER
public void startWIFITimer() {
    wifiTimer = new Timer();
    initializeWIFITimer();
    wifiTimer.schedule(wifiTimerTask, 1000, 5000);
}
public void stopWIFITimer() {
    if (wifiTimer != null) {
        wifiTimer.cancel();
        wifiTimer = null;
    }
}
public void initializeWIFITimer() {
    wifiTimerTask = new TimerTask() {
        public void run() {
            wifiHandler.post(new Runnable() {
                public void run() {displayNotificationWIFI();
                }
            });
        }
    };
}

    @Override
public void onReceive(Context context, final Intent intent) {

    contexts = context.getApplicationContext();

    String status = main.getConnectivityStatus(context);

    if (status.contains("WIFI")){
        startWIFITimer();
    }
    else if (status.contains("DATA")){]
    }
    else if (status.contains("ERROR")){
            displayNotificationERROR();
            stopWIFITimer();
        }
    }
</code>```

And if someone decides to downvote, it would be nice to get a reason why. Thanks again in advance for any help! :D

答:
Each time you receive a broadcast message, a new instance of the BroadcastReceiver is created. So when you call stopWIFITimer() you are actually trying to stop a never started timer, because the started timer is an object of another instance of the BroadcastReceiver.
So, you should move your timer somewhere else.

Title: Timertask not stopping

Body:
Hi I have been creating an app that would check if the phone is using wifi or mobile data, using timerTask to inform the user and broadcast Receivers to check if WIFI or MOBILE DATA is open.

Even after I cancel the timerTask it goes to an Error notification and then the wifi notification runs again.

I have been stuck with this problem for hours now and I decided to ask for some help.

This is my MainActivity Class:

public class MainActivity extends AppCompatActivity {

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

}

public String getConnectivityStatus(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

    String status = null;

    if (null != activeNetwork) {
        if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
            status = "WIFI";
        if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
            status = "DATA";
    }
    else{
        status = "ERROR";
    }
    return status;
}

And this is my NetworkChangeReceiver Class:

public class NetworkChangeReceiver extends BroadcastReceiver {

 //WIFI TIMER
public void startWIFITimer() {
    wifiTimer = new Timer();
    initializeWIFITimer();
    wifiTimer.schedule(wifiTimerTask, 1000, 5000);
}
public void stopWIFITimer() {
    if (wifiTimer != null) {
        wifiTimer.cancel();
        wifiTimer = null;
    }
}
public void initializeWIFITimer() {
    wifiTimerTask = new TimerTask() {
        public void run() {
            wifiHandler.post(new Runnable() {
                public void run() {displayNotificationWIFI();
                }
            });
        }
    };
}

    @Override
public void onReceive(Context context, final Intent intent) {

    contexts = context.getApplicationContext();

    String status = main.getConnectivityStatus(context);

    if (status.contains("WIFI")){
        startWIFITimer();
    }
    else if (status.contains("DATA")){]
    }
    else if (status.contains("ERROR")){
            displayNotificationERROR();
            stopWIFITimer();
        }
    }

And if someone decides to downvote, it would be nice to get a reason why. Thanks again in advance for any help! :D


问:
Use special characters (Umlaut) in Express Response
I'm using Express to deliver a file download like this:

```<code>const fileStream = Storage.getFileStream(path);
res.setHeader('Content-disposition', `attachment; filename="${filename}"`);
res.setHeader('Content-type', contentType);
res.setHeader('Content-length', size);
fileStream.pipe(res);
</code>```

When filename contains special characters (Ä, Ü, è, ...) an error is thrown, saying I'm using characters that are not allowed.

I found a solution in using unidecode. But is there a solution that keeps an "Ä" instead of converting it to "A"

I search this issue but I got very confused how to handle this the right way, so forgive me if this question is a duplicate...

Solution (added later): I found this solution that works for me and keeps all special characters in the filename:

```<code>const filename = encodeURI(file.filename);
res.setHeader('Content-disposition', `attachment; filename*=UTF-8''${filename}; filename=${filename}`);
res.setHeader('Content-type', contentType);
res.setHeader('Content-length', size);
</code>```

答:
You may Try Normalizing the string with one of the great library
JavaScript Unicode 8.0 Normalization - NFC, NFD, NFKC, NFKD.
Which can be availed using :-

npm install unorm

An example Code -

```<code>var unorm = require('unorm');

var text =
  'The \u212B symbol invented by A. J. \u00C5ngstr\u00F6m ' +
  '(1814, L\u00F6gd\u00F6, \u2013 1874) denotes the length ' +
  '10\u207B\u00B9\u2070 m.';

var combining = /[\u0300-\u036F]/g; // Use XRegExp('\\p{M}', 'g'); see
example.js.

console.log('Regular:  ' + text);
console.log('NFC:      ' + unorm.nfc(text));
console.log('NFD:      ' + unorm.nfd(text));
console.log('NFKC:     ' + unorm.nfkc(text));
console.log('NFKD: *   ' + unorm.nfkd(text).replace(combining, ''));
console.log(' * = Combining characters removed from decomposed form.');
</code>```

Source: https://github.com/walling/unorm
I hope It works.

Body:
I'm using Express to deliver a file download like this:

const fileStream = Storage.getFileStream(path);
res.setHeader('Content-disposition', `attachment; filename="${filename}"`);
res.setHeader('Content-type', contentType);
res.setHeader('Content-length', size);
fileStream.pipe(res);

When filename contains special characters (Ä, Ü, è, ...) an error is thrown, saying I'm using characters that are not allowed.

I found a solution in using unidecode. But is there a solution that keeps an "Ä" instead of converting it to "A"

I search this issue but I got very confused how to handle this the right way, so forgive me if this question is a duplicate...

Solution (added later): I found this solution that works for me and keeps all special characters in the filename:

const filename = encodeURI(file.filename);
res.setHeader('Content-disposition', `attachment; filename*=UTF-8''${filename}; filename=${filename}`);
res.setHeader('Content-type', contentType);
res.setHeader('Content-length', size);

Body:
You may Try Normalizing the string with one of the great library
JavaScript Unicode 8.0 Normalization - NFC, NFD, NFKC, NFKD.
Which can be availed using :-

npm install unorm

An example Code -

var unorm = require('unorm');

var text =
  'The \u212B symbol invented by A. J. \u00C5ngstr\u00F6m ' +
  '(1814, L\u00F6gd\u00F6, \u2013 1874) denotes the length ' +
  '10\u207B\u00B9\u2070 m.';

var combining = /[\u0300-\u036F]/g; // Use XRegExp('\\p{M}', 'g'); see
example.js.

console.log('Regular:  ' + text);
console.log('NFC:      ' + unorm.nfc(text));
console.log('NFD:      ' + unorm.nfd(text));
console.log('NFKC:     ' + unorm.nfkc(text));
console.log('NFKD: *   ' + unorm.nfkd(text).replace(combining, ''));
console.log(' * = Combining characters removed from decomposed form.');

Source: https://github.com/walling/unorm
I hope It works.


问:
Django REST Framework POST nested objects
I'm facing a little problem right now with Django Rest Framework. I'm trying to post an object with nested objects in it.

Here are my serializers.py:

```<code>class ClassSerializer(serializers.ModelSerializer):
    class Meta:
        model = Class
        fields = ('number', 'letter')

class SubjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Subject
        fields = ('title',)

class ExamSerializer(serializers.ModelSerializer):
    subject = SubjectSerializer()
    clazz = ClassSerializer()

    class Meta:
        model = Exam
        fields = ('id', 'subject', 'clazz', 'topic', 'date', 'details')
        depth = 1

    def create(self, validated_data):
        return Exam.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.__dict__.update(**validated_data)
        instance.save()

        return instance
</code>```

And create() from views.py:

```<code>def create(self, request):
    serializer = self.serializer_class(data=request.data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)

    return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
</code>```

And here it is the response from Postman:

I've read some posts here about this problem but I'm still stuck with it. I've tried to fix it in several ways but it is still returning "This field is required.".

答:
I had the same issue when trying to post a nested JSON object to DRF (Django Rest Framework).

Once you've properly set up writing nested serializers (see the docs on writable nested serializers), you can test that it works by using the browsable API and posting/putting data there. If that works, and you're still getting "This field is required" errors on your nested models when posting/putting JSON objects, you may have to set the content-type of your request.

This answer provided the solution I needed, and it's summarised below.

```<code>$.ajax ({
  // Other parameters e.g. url, type
  data: JSON.stringify(data),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
});
</code>```

I needed to set the "contentType" as well as "stringify" my js object.

Body:
I'm facing a little problem right now with Django Rest Framework. I'm trying to post an object with nested objects in it.

Here are my serializers.py:

class ClassSerializer(serializers.ModelSerializer):
    class Meta:
        model = Class
        fields = ('number', 'letter')

class SubjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Subject
        fields = ('title',)

class ExamSerializer(serializers.ModelSerializer):
    subject = SubjectSerializer()
    clazz = ClassSerializer()

    class Meta:
        model = Exam
        fields = ('id', 'subject', 'clazz', 'topic', 'date', 'details')
        depth = 1

    def create(self, validated_data):
        return Exam.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.__dict__.update(**validated_data)
        instance.save()

        return instance

And create() from views.py:

def create(self, request):
    serializer = self.serializer_class(data=request.data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)

    return Response(serializer.validated_data, status=status.HTTP_201_CREATED)

And here it is the response from Postman:

I've read some posts here about this problem but I'm still stuck with it. I've tried to fix it in several ways but it is still returning "This field is required.".

Body:
I had the same issue when trying to post a nested JSON object to DRF (Django Rest Framework).

Once you've properly set up writing nested serializers (see the docs on writable nested serializers), you can test that it works by using the browsable API and posting/putting data there. If that works, and you're still getting "This field is required" errors on your nested models when posting/putting JSON objects, you may have to set the content-type of your request.

This answer provided the solution I needed, and it's summarised below.

$.ajax ({
  // Other parameters e.g. url, type
  data: JSON.stringify(data),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
});

I needed to set the "contentType" as well as "stringify" my js object.