问:
Export Chinese Characters From Excel To ICS
Macro stops as soon as there are Chinese characters like š访问父母 in Summary.
Works fine using English.
With Chinese it shows Run-Time error '5': Invalid procedure call or argument and when going into details the line below is highlighted.
objFile.write "SUMMARY:" & Summary & vbCrLf
Help in how to tackle this would be appreciated.</p>

```<code>Sub Create_ICS()

Dim CSV_Name As String
CSV_Name = ThisWorkbook.Names("CSV_Name").RefersToRange + ".ics"
If CSV_Name = ".ics" Then GoTo No_Filename

Dim Folder_Existence As String
Folder_Existence = ThisWorkbook.Names("Folder_Existence").RefersToRange
If Folder_Existence <> "" Then GoTo No_Such_Folder

Sheets("ICS").Select

' PARAMETERS
Dim Last_Columm As Long
Last_Columm = 21
Dim First_Row As Long
First_Row = 2

Dim ICS_Format As String
ICS_Format = ThisWorkbook.Names("ICS_Format").RefersToRange

Dim Time_Zone_Selected As String
Time_Zone_Selected = ThisWorkbook.Names("Time_Zone_Selected").RefersToRange

Dim Calendar_ID As String
Calendar_ID = ThisWorkbook.Names("Calendar_ID").RefersToRange

Dim CSV_Directory As String
CSV_Directory = ThisWorkbook.Names("CSV_Directory").RefersToRange

Dim Sync_URL As String
Sync_URL = ThisWorkbook.Names("Sync_URL").RefersToRange + CSV_Name

Dim Time_Format As String
Time_Format = ThisWorkbook.Names("Time_Format").RefersToRange
If Time_Format = "Excel Timestamps" Then Application.Run "Excel_Timestamps"

Dim Total_Errors As Long
Application.Calculate
Total_Errors = ThisWorkbook.Names("Total_Errors").RefersToRange
If Total_Errors > 0 Then GoTo Fix_Errors

Start_Export:

Dim CSV_Slash As String
CSV_Slash = Right(CSV_Directory, 1)
Dim Slash As String
If CSV_Slash = "\" Then Slash = ""
If CSV_Slash <> "\" Then Slash = "\"

Dim CSV_Filename As String
CSV_Filename = CSV_Directory + Slash + CSV_Name

Dim rng1 As Range, X, i As Long, v As Long
Dim objFSO, objFile
Dim FilePath As String
FilePath = "D:\test.ics"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(CSV_Filename)

' SET AREA
Set rng1 = Range(Cells(First_Row, 1), Cells(Cells(Rows.Count, "A").End(xlUp).Row, Last_Columm))
X = rng1

'GoTo Details

' CREATE HEADER
objFile.write "BEGIN:VCALENDAR" & vbCrLf
objFile.write "CALSCALE:GREGORIAN" & vbCrLf
objFile.write "VERSION:2.0" & vbCrLf
objFile.write "METHOD:Publish" & vbCrLf
objFile.write "PRODID:-//None" & vbCrLf

Details:
Dim Summary As String
Dim Description As String
Dim DateStart As String
Dim TimeStart As String
Dim DateEnd As String
Dim TimeEnd As String
Dim Location As String
Dim Frequency As String
Dim Interval As String
Dim When As String
Dim ByDay As String
Dim ByMonthDay As String
Dim ByYearDay As String
Dim ByWeekNo As String
Dim ByMonth As String
Dim BySetPos As String
Dim WkSt As String
Dim Color As String
Dim Alarm As String
Dim TzId As String
Dim UID As String

' Create Details

For i = 1 To UBound(X, 1)

Summary = X(i, 1)
Description = X(i, 2)
DateStart = X(i, 3)
TimeStart = X(i, 4)
DateEnd = X(i, 5)
TimeEnd = X(i, 6)
Location = X(i, 7)
Frequency = X(i, 8)
Interval = X(i, 9)
When = X(i, 10)
ByDay = X(i, 11)
ByMonthDay = X(i, 12)
ByYearDay = X(i, 13)
ByWeekNo = X(i, 14)
ByMonth = X(i, 15)
BySetPos = X(i, 16)
WkSt = X(i, 17)
Color = X(i, 18)
Alarm = X(i, 19)
TzId = X(i, 20)
UID = X(i, 21)

'11
ByMonthDay = Right(DateStart, 2) / 1

If BySetPos = "L" Then BySetPos = "-1"

'14
ByMonth = Mid(DateStart, 5, 2) / 1

objFile.write "BEGIN:VEVENT" & vbCrLf

objFile.write "UID:" & UID & vbCrLf

objFile.write "DTSTAMP" & TzId & ":" & DateStart & "T000000" & ICS_Format & vbCrLf

If Description <> "" Then
    objFile.write "DESCRIPTION:" & Description & vbCrLf
End If

If TimeStart = "" Or TimeStart = "0" And TimeEnd = "0" Then
objFile.write "DTEND;VALUE=DATE:" & DateEnd & vbCrLf
Else
If Len(TimeEnd) = 3 Then TimeEnd = "000" + TimeEnd
If Len(TimeEnd) = 4 Then TimeEnd = "00" + TimeEnd
If Len(TimeEnd) = 5 Then TimeEnd = "0" + TimeEnd
objFile.write "DTEND" & TzId & ":" & DateEnd & "T" & TimeEnd & vbCrLf
End If

If Location <> "" Then
objFile.write "LOCATION:" & Location & vbCrLf
End If

objFile.write "SUMMARY:" & Summary & vbCrLf

If TimeStart = "" Or TimeStart = "0" And TimeEnd = "0" Then
objFile.write "DTSTART;VALUE=DATE:" & DateStart & vbCrLf ' All Day
Else
If Len(TimeStart) = 3 Then TimeStart = "000" + TimeStart
If Len(TimeStart) = 4 Then TimeStart = "00" + TimeStart
If Len(TimeStart) = 5 Then TimeStart = "0" + TimeStart
   objFile.write "DTSTART" & TzId & ":" & DateStart & "T" & TimeStart & vbCrLf
End If

If TimeStart = "" Or TimeStart = "0" And TimeEnd = "0" Then
   objFile.write "X-MICROSOFT-CDO-ALLDAYEVENT:TRUE" & vbCrLf
   objFile.write "X-FUNAMBOL-ALLDAY:1" & vbCrLf
End If

If Frequency <> "" And Interval = "" Then Interval = "1"

If Frequency = "DAILY" Then
   objFile.write "RRULE:FREQ=DAILY" & vbCrLf
ElseIf Frequency = "WEEKLY" Then
   objFile.write "RRULE:FREQ=" & Frequency & ";INTERVAL=" & Interval & vbCrLf

' Day X of each Y months
ElseIf Frequency = "MONTHLY" And ByDay = "" Then
    objFile.write "RRULE:FREQ=MONTHLY;INTERVAL=" & Interval & "BYMONTHDAY=" & ByMonthDay & vbCrLf

' Xth WeekDay of each Y months
ElseIf Frequency = "MONTHLY" And ByDay <> "" Then
    objFile.write "RRULE:FREQ=MONTHLY;INTERVAL=" & 1 & ";BYDAY=" & When & ByDay & vbCrLf

ElseIf Frequency = "YEARLY" And ByYearDay <> "" Then
    objFile.write "RRULE:FREQ=YEARLY;INTERVAL=" & Interval & ";BYYEARDAY=" & ByYearDay & vbCrLf

ElseIf Frequency = "YEARLY" And ByYearDay = "" Then
    objFile.write "RRULE:FREQ=YEARLY;INTERVAL=" & Interval & ";BYMONTHDAY=" & ByMonthDay & ";BYMONTH=" & ByMonth & vbCrLf
End If

If Alarm <> "" Then
Dim TRIGGER As String
If Alarm = "0" Then TRIGGER = "+PT0S"
If Alarm = "1440" Then TRIGGER = "-P1DT0S"
If Alarm / 1 > 0 And Alarm / 1 < 60 Then TRIGGER = "-PT0H" & Alarm & "M0S"
If Alarm / 1 > 59 And Alarm / 1 < 1440 Then TRIGGER = "-PT" & Int(Alarm / 60) & "H" & (Alarm / 60 - Int(Alarm / 60)) * 60 & "M0S"

objFile.write "DESCRIPTION:Event Reminder" & vbCrLf
objFile.write "ACTION: DISPLAY" & vbCrLf
objFile.write "End:VALARM" & vbCrLf
End If

If Color <> "" Then
   objFile.write "X-UTILITAP-COLOR: " & Color & vbCrLf
End If

objFile.write "END:VEVENT" & vbCrLf

Skip_Record:
Next i

' Create Footer
objFile.write "END:VCALENDAR"

Sheets("Instructions").Select
MsgBox "File " + CSV_Directory + CSV_Name + " created..."

GoTo Finish

Close_CSV:
MsgBox " The destination file " + CSV_Name + " is open, please close it first..."
GoTo Finish

No_Such_Folder:
MsgBox "Folder '" + CSV_Directory + "' doesn't exist, please fix this first...."
Application.GoTo Reference:="CSV_Directory"
GoTo Finish

No_Filename:
MsgBox "No file name specified, please fix this first...."
Application.GoTo Reference:="CSV_Name"
GoTo Finish

No_ICS_Rows:
MsgBox "Sheet 'ICS' doesn't contain calendar items, nothing to export...."
GoTo Finish

Fix_Errors:
MsgBox "Sheet 'ICS' contains errors, please fix these first...."
Application.Run "Filter_Errors"

GoTo Finish

No_Error_Checks:
    MsgBox "Sheet ICS doesn't contain error checks, this will be fixed now...."
Application.Run "Calendar_Checks"
Application.Calculate
GoTo Finish

Finish:

End Sub
</code>```

答:
The error is here:

```<code> Set objFile = objFSO.CreateTextFile(CSV_Filename)
</code>```

By default that's created as Ascii not UniCode. Replace with

```<code> Set objFile = objFSO.CreateTextFile(filename:=CSV_Filename, Unicode:=true)
</code>```

Body:
Macro stops as soon as there are Chinese characters like š访问父母 in Summary.
Works fine using English.
With Chinese it shows Run-Time error '5': Invalid procedure call or argument and when going into details the line below is highlighted.
objFile.write "SUMMARY:" & Summary & vbCrLf
Help in how to tackle this would be appreciated.

Sub Create_ICS()

Dim CSV_Name As String
CSV_Name = ThisWorkbook.Names("CSV_Name").RefersToRange + ".ics"
If CSV_Name = ".ics" Then GoTo No_Filename

Dim Folder_Existence As String
Folder_Existence = ThisWorkbook.Names("Folder_Existence").RefersToRange
If Folder_Existence <> "" Then GoTo No_Such_Folder

Sheets("ICS").Select

' PARAMETERS
Dim Last_Columm As Long
Last_Columm = 21
Dim First_Row As Long
First_Row = 2

Dim ICS_Format As String
ICS_Format = ThisWorkbook.Names("ICS_Format").RefersToRange

Dim Time_Zone_Selected As String
Time_Zone_Selected = ThisWorkbook.Names("Time_Zone_Selected").RefersToRange

Dim Calendar_ID As String
Calendar_ID = ThisWorkbook.Names("Calendar_ID").RefersToRange

Dim CSV_Directory As String
CSV_Directory = ThisWorkbook.Names("CSV_Directory").RefersToRange

Dim Sync_URL As String
Sync_URL = ThisWorkbook.Names("Sync_URL").RefersToRange + CSV_Name

Dim Time_Format As String
Time_Format = ThisWorkbook.Names("Time_Format").RefersToRange
If Time_Format = "Excel Timestamps" Then Application.Run "Excel_Timestamps"

Dim Total_Errors As Long
Application.Calculate
Total_Errors = ThisWorkbook.Names("Total_Errors").RefersToRange
If Total_Errors > 0 Then GoTo Fix_Errors

Start_Export:

Dim CSV_Slash As String
CSV_Slash = Right(CSV_Directory, 1)
Dim Slash As String
If CSV_Slash = "\" Then Slash = ""
If CSV_Slash <> "\" Then Slash = "\"

Dim CSV_Filename As String
CSV_Filename = CSV_Directory + Slash + CSV_Name

Dim rng1 As Range, X, i As Long, v As Long
Dim objFSO, objFile
Dim FilePath As String
FilePath = "D:\test.ics"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(CSV_Filename)

' SET AREA
Set rng1 = Range(Cells(First_Row, 1), Cells(Cells(Rows.Count, "A").End(xlUp).Row, Last_Columm))
X = rng1

'GoTo Details

' CREATE HEADER
objFile.write "BEGIN:VCALENDAR" & vbCrLf
objFile.write "CALSCALE:GREGORIAN" & vbCrLf
objFile.write "VERSION:2.0" & vbCrLf
objFile.write "METHOD:Publish" & vbCrLf
objFile.write "PRODID:-//None" & vbCrLf

Details:
Dim Summary As String
Dim Description As String
Dim DateStart As String
Dim TimeStart As String
Dim DateEnd As String
Dim TimeEnd As String
Dim Location As String
Dim Frequency As String
Dim Interval As String
Dim When As String
Dim ByDay As String
Dim ByMonthDay As String
Dim ByYearDay As String
Dim ByWeekNo As String
Dim ByMonth As String
Dim BySetPos As String
Dim WkSt As String
Dim Color As String
Dim Alarm As String
Dim TzId As String
Dim UID As String

' Create Details

For i = 1 To UBound(X, 1)

Summary = X(i, 1)
Description = X(i, 2)
DateStart = X(i, 3)
TimeStart = X(i, 4)
DateEnd = X(i, 5)
TimeEnd = X(i, 6)
Location = X(i, 7)
Frequency = X(i, 8)
Interval = X(i, 9)
When = X(i, 10)
ByDay = X(i, 11)
ByMonthDay = X(i, 12)
ByYearDay = X(i, 13)
ByWeekNo = X(i, 14)
ByMonth = X(i, 15)
BySetPos = X(i, 16)
WkSt = X(i, 17)
Color = X(i, 18)
Alarm = X(i, 19)
TzId = X(i, 20)
UID = X(i, 21)

'11
ByMonthDay = Right(DateStart, 2) / 1

If BySetPos = "L" Then BySetPos = "-1"

'14
ByMonth = Mid(DateStart, 5, 2) / 1

objFile.write "BEGIN:VEVENT" & vbCrLf

objFile.write "UID:" & UID & vbCrLf

objFile.write "DTSTAMP" & TzId & ":" & DateStart & "T000000" & ICS_Format & vbCrLf

If Description <> "" Then
    objFile.write "DESCRIPTION:" & Description & vbCrLf
End If

If TimeStart = "" Or TimeStart = "0" And TimeEnd = "0" Then
objFile.write "DTEND;VALUE=DATE:" & DateEnd & vbCrLf
Else
If Len(TimeEnd) = 3 Then TimeEnd = "000" + TimeEnd
If Len(TimeEnd) = 4 Then TimeEnd = "00" + TimeEnd
If Len(TimeEnd) = 5 Then TimeEnd = "0" + TimeEnd
objFile.write "DTEND" & TzId & ":" & DateEnd & "T" & TimeEnd & vbCrLf
End If

If Location <> "" Then
objFile.write "LOCATION:" & Location & vbCrLf
End If

objFile.write "SUMMARY:" & Summary & vbCrLf

If TimeStart = "" Or TimeStart = "0" And TimeEnd = "0" Then
objFile.write "DTSTART;VALUE=DATE:" & DateStart & vbCrLf ' All Day
Else
If Len(TimeStart) = 3 Then TimeStart = "000" + TimeStart
If Len(TimeStart) = 4 Then TimeStart = "00" + TimeStart
If Len(TimeStart) = 5 Then TimeStart = "0" + TimeStart
   objFile.write "DTSTART" & TzId & ":" & DateStart & "T" & TimeStart & vbCrLf
End If

If TimeStart = "" Or TimeStart = "0" And TimeEnd = "0" Then
   objFile.write "X-MICROSOFT-CDO-ALLDAYEVENT:TRUE" & vbCrLf
   objFile.write "X-FUNAMBOL-ALLDAY:1" & vbCrLf
End If

If Frequency <> "" And Interval = "" Then Interval = "1"

If Frequency = "DAILY" Then
   objFile.write "RRULE:FREQ=DAILY" & vbCrLf
ElseIf Frequency = "WEEKLY" Then
   objFile.write "RRULE:FREQ=" & Frequency & ";INTERVAL=" & Interval & vbCrLf

' Day X of each Y months
ElseIf Frequency = "MONTHLY" And ByDay = "" Then
    objFile.write "RRULE:FREQ=MONTHLY;INTERVAL=" & Interval & "BYMONTHDAY=" & ByMonthDay & vbCrLf

' Xth WeekDay of each Y months
ElseIf Frequency = "MONTHLY" And ByDay <> "" Then
    objFile.write "RRULE:FREQ=MONTHLY;INTERVAL=" & 1 & ";BYDAY=" & When & ByDay & vbCrLf

ElseIf Frequency = "YEARLY" And ByYearDay <> "" Then
    objFile.write "RRULE:FREQ=YEARLY;INTERVAL=" & Interval & ";BYYEARDAY=" & ByYearDay & vbCrLf

ElseIf Frequency = "YEARLY" And ByYearDay = "" Then
    objFile.write "RRULE:FREQ=YEARLY;INTERVAL=" & Interval & ";BYMONTHDAY=" & ByMonthDay & ";BYMONTH=" & ByMonth & vbCrLf
End If

If Alarm <> "" Then
Dim TRIGGER As String
If Alarm = "0" Then TRIGGER = "+PT0S"
If Alarm = "1440" Then TRIGGER = "-P1DT0S"
If Alarm / 1 > 0 And Alarm / 1 < 60 Then TRIGGER = "-PT0H" & Alarm & "M0S"
If Alarm / 1 > 59 And Alarm / 1 < 1440 Then TRIGGER = "-PT" & Int(Alarm / 60) & "H" & (Alarm / 60 - Int(Alarm / 60)) * 60 & "M0S"

objFile.write "DESCRIPTION:Event Reminder" & vbCrLf
objFile.write "ACTION: DISPLAY" & vbCrLf
objFile.write "End:VALARM" & vbCrLf
End If

If Color <> "" Then
   objFile.write "X-UTILITAP-COLOR: " & Color & vbCrLf
End If

objFile.write "END:VEVENT" & vbCrLf

Skip_Record:
Next i

' Create Footer
objFile.write "END:VCALENDAR"

Sheets("Instructions").Select
MsgBox "File " + CSV_Directory + CSV_Name + " created..."

GoTo Finish

Close_CSV:
MsgBox " The destination file " + CSV_Name + " is open, please close it first..."
GoTo Finish

No_Such_Folder:
MsgBox "Folder '" + CSV_Directory + "' doesn't exist, please fix this first...."
Application.GoTo Reference:="CSV_Directory"
GoTo Finish

No_Filename:
MsgBox "No file name specified, please fix this first...."
Application.GoTo Reference:="CSV_Name"
GoTo Finish

No_ICS_Rows:
MsgBox "Sheet 'ICS' doesn't contain calendar items, nothing to export...."
GoTo Finish

Fix_Errors:
MsgBox "Sheet 'ICS' contains errors, please fix these first...."
Application.Run "Filter_Errors"

GoTo Finish

No_Error_Checks:
    MsgBox "Sheet ICS doesn't contain error checks, this will be fixed now...."
Application.Run "Calendar_Checks"
Application.Calculate
GoTo Finish

Finish:

End Sub

Body:
The error is here:

 Set objFile = objFSO.CreateTextFile(CSV_Filename)

By default that's created as Ascii not UniCode. Replace with

 Set objFile = objFSO.CreateTextFile(filename:=CSV_Filename, Unicode:=true)


来源: stackexchange

问:
How to automatically populate a 5x3x2 array with natural numbers from zero to the array's full size?
I need to populate a 3D array automatically, using natural positive numbers (0,1,2,3,4...), up to the array's full dimension. In this case, a 5x3x2 array stores 30 elements. Is there any algorithm, where for-loops could be employed to dynamically populate such array? For example: if I had a 5x3 2D array, I certainly could use the following code, to automatically generate its elements:

```<code>var ray = new Array(5);
for (var make2D = 0; make2D < ray.length; make2D++) {
    ray[make2D] = new Array(3);
}
for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
        array[i][j] = i * array[i].length + j;
    }
}
</code>```

The above code would first create a 5 x 3 array and populate this 2D array with elements from 0 to 14.
But, I have struggled to find a 'formula' to populate a 3D array likewise

Like explicit: array[ i ] [ j ] [ z ]= '.....code.....'  using length property values and for-loops?

答:
If any of the dimensions are fixed, it's faster to hard code them:

for (var a = [], n = 0, i = 0, j, k; i < 5; i++)
  for (j = 0, a[i] = []; j < 3; j++)
    for (k = 0, a[i][j] = []; k < 2; k++)
      a[i][j][k] = n++

console.log(JSON.stringify(a))

// faster
for (var a = [], n = 0, i = 0, j; i < 5; i++)
  for (j = 0, a[i] = []; j < 3; j++)
      a[i][j] = [n++, n++]

console.log(JSON.stringify(a))

// even faster
for (var a = [], i = 0, n = 0; i < 5; i++)
    a[i] = [[n++, n++], [n++, n++], [n++, n++]]

console.log(JSON.stringify(a))

// fastest
var a = [[[0,1],[2,3],[4,5]],[[6,7],[8,9],[10,11]],[[12,13],[14,15],[16,17]],[[18,19],[20,21],[22,23]],[[24,25],[26,27],[28,29]]]```
</div>
</div>
</p>

<p>Otherwise, there are many shorter and slower ES6 alternatives (don't work in IE):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// nested:
var n = 0, a = [...Array(5)].map(v => [...Array(3)].map(v => [...Array(2)].map(v => n++)))
console.log(JSON.stringify(a))

var n = 0, r = c => [...Array(c)], a = r(5).map(v => r(3).map(v => r(2).map(v => n++)))
console.log(JSON.stringify(a))

var n = 0, r = (c, f) => [...Array(c)].map(f), a = r(5, v => r(3, v => r(2, v => n++)))
console.log(JSON.stringify(a))

// recursive:
var n = 0, r = (c, ...a) => [...Array(c)].map(v => a[0] ? r(...a) : n++), a = r(5, 3, 2)
console.log(JSON.stringify(a))

var n = 0, r = a => [...Array(a[0])].map(v => a[1] ? r(a.slice(1)) : n++), a = r([5, 3, 2])
console.log(JSON.stringify(a))

// recursive without having to declare n outside of the function:
var r = (a, n = [0]) => [...Array(a[0])].map(v => a[1] ? r(a.slice(1), n) : n[0]++), a = r([5, 3, 2])
console.log(JSON.stringify(a))</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to populate a 3D array automatically, using natural positive numbers (0,1,2,3,4...), up to the array's full dimension. In this case, a 5x3x2 array stores 30 elements. Is there any algorithm, where for-loops could be employed to dynamically populate such array? For example: if I had a 5x3 2D array, I certainly could use the following code, to automatically generate its elements:

var ray = new Array(5);
for (var make2D = 0; make2D < ray.length; make2D++) {
    ray[make2D] = new Array(3);
}
for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
        array[i][j] = i * array[i].length + j;
    }
}

The above code would first create a 5 x 3 array and populate this 2D array with elements from 0 to 14.
But, I have struggled to find a 'formula' to populate a 3D array likewise

Like explicit: array[ i ] [ j ] [ z ]= '.....code.....'  using length property values and for-loops?

Body:
If any of the dimensions are fixed, it's faster to hard code them:

for (var a = [], n = 0, i = 0, j, k; i < 5; i++)
  for (j = 0, a[i] = []; j < 3; j++)
    for (k = 0, a[i][j] = []; k < 2; k++)
      a[i][j][k] = n++

console.log(JSON.stringify(a))

// faster
for (var a = [], n = 0, i = 0, j; i < 5; i++)
  for (j = 0, a[i] = []; j < 3; j++)
      a[i][j] = [n++, n++]

console.log(JSON.stringify(a))

// even faster
for (var a = [], i = 0, n = 0; i < 5; i++)
    a[i] = [[n++, n++], [n++, n++], [n++, n++]]

console.log(JSON.stringify(a))

// fastest
var a = [[[0,1],[2,3],[4,5]],[[6,7],[8,9],[10,11]],[[12,13],[14,15],[16,17]],[[18,19],[20,21],[22,23]],[[24,25],[26,27],[28,29]]]

Otherwise, there are many shorter and slower ES6 alternatives (don't work in IE):

// nested:
var n = 0, a = [...Array(5)].map(v => [...Array(3)].map(v => [...Array(2)].map(v => n++)))
console.log(JSON.stringify(a))

var n = 0, r = c => [...Array(c)], a = r(5).map(v => r(3).map(v => r(2).map(v => n++)))
console.log(JSON.stringify(a))

var n = 0, r = (c, f) => [...Array(c)].map(f), a = r(5, v => r(3, v => r(2, v => n++)))
console.log(JSON.stringify(a))

// recursive:
var n = 0, r = (c, ...a) => [...Array(c)].map(v => a[0] ? r(...a) : n++), a = r(5, 3, 2)
console.log(JSON.stringify(a))

var n = 0, r = a => [...Array(a[0])].map(v => a[1] ? r(a.slice(1)) : n++), a = r([5, 3, 2])
console.log(JSON.stringify(a))

// recursive without having to declare n outside of the function:
var r = (a, n = [0]) => [...Array(a[0])].map(v => a[1] ? r(a.slice(1), n) : n[0]++), a = r([5, 3, 2])
console.log(JSON.stringify(a))


问:
OpenGL - glDrawElements only draws half polygon
I have a problem right now when implementing indices in opengl for Android. I think I am almost there - but the problem is that only half of the polygon is drawn. What could be the reason for this and how to solve it?

1
create and bind buffers, one FloatBuffer for positions and uvcoords, one ShortBuffer for indices

```<code>    public int createVBO(ArrayList <SpriteDataHolder> spriteDataList) {

    final int BYTES_PER_FLOAT = 4;
    final int BYTES_PER_SHORT = 2;
    final int N_SPRITES = spriteDataList.size();
    final int N_VERTICES_SPRITE = spriteDataList.get(0).getSpriteVertices().length; //godtyckligt indexvärde - alla lika
    final int N_UVS_SPRITE = spriteDataList.get(0).getUvsSprites().length;
    final int N_INDICES_SPRITE = 6;
    final int totalDataLength = N_SPRITES * (N_VERTICES_SPRITE + N_UVS_SPRITE);
    final int totalDataLengthShort = N_SPRITES * N_INDICES_SPRITE;

    final int POSITION_DATA_SIZE = 3; // antal floats per punktcoordinat
    final int TEXTURE_COORDINATE_DATA_SIZE = 2; // antal floats per uvcoordinat
    final int INDEX_DATA_SIZE = 1; // antal shorts per indexvärde

    final FloatBuffer spriteBuffer = ByteBuffer.allocateDirect(totalDataLength * BYTES_PER_FLOAT)
            .order(ByteOrder.nativeOrder()).asFloatBuffer();

    final ShortBuffer indexBuffer = ByteBuffer.allocateDirect(totalDataLengthShort * BYTES_PER_SHORT)
            .order(ByteOrder.nativeOrder()).asShortBuffer();

    int spritePositionOffset = 0;
    int spriteTextureOffset = 0;
    int spriteIndexOffset = 0;

    for (int i = 0; i < N_SPRITES; i++) {
        for (int v = 0; v < 6; v++) { // 6 punkter per polygon

            spriteBuffer.put(spriteDataList.get(i).getSpriteVertices(), spritePositionOffset, POSITION_DATA_SIZE); // vertices x y z för sprite i
            spritePositionOffset += POSITION_DATA_SIZE;

            spriteBuffer.put(spriteDataList.get(i).getUvsSprites(), spriteTextureOffset, TEXTURE_COORDINATE_DATA_SIZE);
            spriteTextureOffset += TEXTURE_COORDINATE_DATA_SIZE;

            indexBuffer.put(spriteDataList.get(i).getIndices(), spriteIndexOffset, INDEX_DATA_SIZE);
            spriteIndexOffset += INDEX_DATA_SIZE;
        }
        spritePositionOffset = 0;
        spriteTextureOffset = 0;
        spriteIndexOffset = 0;
    }

    spriteBuffer.position(0);
    indexBuffer.position(0);

    // skicka flyttalsbufferten till GPU'N
    final int buffers[] = new int[1];
    GLES20.glGenBuffers(1, buffers, 0);

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, buffers[0]);
    GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, spriteBuffer.capacity() * BYTES_PER_FLOAT, spriteBuffer, GLES20.GL_STATIC_DRAW);

    final int[] indexbuffers = new int[1];
    GLES20.glGenBuffers(1, indexbuffers, 0);

    GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexbuffers[0]);
    GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBuffer.capacity() * BYTES_PER_SHORT, indexBuffer, GLES20.GL_STATIC_DRAW);

    return buffers[0];
}
</code>```

2 // and the created indices for all sprites

```<code>    private void createVBOindices(short[][] indices, int nSprites) {

    int last = 0;
    for (int i = 0; i < nSprites; i++) {

        indices[i][0] = (short)(last + 0);
        indices[i][1] = (short)(last + 1);
        indices[i][2] = (short)(last + 2);
        indices[i][3] = (short)(last + 1);
        indices[i][4] = (short)(last + 3);
        indices[i][5] = (short)(last + 2);

        last = last + 4;
    }
}
</code>```

I have this order since this is the order that follows the vertices that is ...

```<code> TRIANGLE 1

  0     2
  x x x x
  x    x
  x  x
  x
  1

 TRIANGLE 2

        2
        x
      x x
    x   x
  x x x x
  1     3
</code>```

so for the first triangle it draws from 0 to 1 and then to 2 and for the second triangle it draws from 1 to 3 and then to 2.

I thougt the problem could be found here that is the drawingorder of the second triangle but a have tried several combinations but the second triangle will not be drawed.

Heres  the drawcall in the drawmethod

```<code> GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_SHORT, 0);
</code>```

答:
Not sure if the comment from Columbo fixed this one, but the winding of your triangles is different so if you have GL_CULL_FACE enabled then it's possible that your second triangle is classified as back-facing.

Either disable the facing test, or change the index order in the second triangle so both are facial the same way.

Body:
I have a problem right now when implementing indices in opengl for Android. I think I am almost there - but the problem is that only half of the polygon is drawn. What could be the reason for this and how to solve it?

1
create and bind buffers, one FloatBuffer for positions and uvcoords, one ShortBuffer for indices

    public int createVBO(ArrayList <SpriteDataHolder> spriteDataList) {

    final int BYTES_PER_FLOAT = 4;
    final int BYTES_PER_SHORT = 2;
    final int N_SPRITES = spriteDataList.size();
    final int N_VERTICES_SPRITE = spriteDataList.get(0).getSpriteVertices().length; //godtyckligt indexvärde - alla lika
    final int N_UVS_SPRITE = spriteDataList.get(0).getUvsSprites().length;
    final int N_INDICES_SPRITE = 6;
    final int totalDataLength = N_SPRITES * (N_VERTICES_SPRITE + N_UVS_SPRITE);
    final int totalDataLengthShort = N_SPRITES * N_INDICES_SPRITE;

    final int POSITION_DATA_SIZE = 3; // antal floats per punktcoordinat
    final int TEXTURE_COORDINATE_DATA_SIZE = 2; // antal floats per uvcoordinat
    final int INDEX_DATA_SIZE = 1; // antal shorts per indexvärde

    final FloatBuffer spriteBuffer = ByteBuffer.allocateDirect(totalDataLength * BYTES_PER_FLOAT)
            .order(ByteOrder.nativeOrder()).asFloatBuffer();

    final ShortBuffer indexBuffer = ByteBuffer.allocateDirect(totalDataLengthShort * BYTES_PER_SHORT)
            .order(ByteOrder.nativeOrder()).asShortBuffer();

    int spritePositionOffset = 0;
    int spriteTextureOffset = 0;
    int spriteIndexOffset = 0;

    for (int i = 0; i < N_SPRITES; i++) {
        for (int v = 0; v < 6; v++) { // 6 punkter per polygon

            spriteBuffer.put(spriteDataList.get(i).getSpriteVertices(), spritePositionOffset, POSITION_DATA_SIZE); // vertices x y z för sprite i
            spritePositionOffset += POSITION_DATA_SIZE;

            spriteBuffer.put(spriteDataList.get(i).getUvsSprites(), spriteTextureOffset, TEXTURE_COORDINATE_DATA_SIZE);
            spriteTextureOffset += TEXTURE_COORDINATE_DATA_SIZE;

            indexBuffer.put(spriteDataList.get(i).getIndices(), spriteIndexOffset, INDEX_DATA_SIZE);
            spriteIndexOffset += INDEX_DATA_SIZE;
        }
        spritePositionOffset = 0;
        spriteTextureOffset = 0;
        spriteIndexOffset = 0;
    }

    spriteBuffer.position(0);
    indexBuffer.position(0);

    // skicka flyttalsbufferten till GPU'N
    final int buffers[] = new int[1];
    GLES20.glGenBuffers(1, buffers, 0);

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, buffers[0]);
    GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, spriteBuffer.capacity() * BYTES_PER_FLOAT, spriteBuffer, GLES20.GL_STATIC_DRAW);

    final int[] indexbuffers = new int[1];
    GLES20.glGenBuffers(1, indexbuffers, 0);

    GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexbuffers[0]);
    GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBuffer.capacity() * BYTES_PER_SHORT, indexBuffer, GLES20.GL_STATIC_DRAW);

    return buffers[0];
}

2 // and the created indices for all sprites

    private void createVBOindices(short[][] indices, int nSprites) {

    int last = 0;
    for (int i = 0; i < nSprites; i++) {

        indices[i][0] = (short)(last + 0);
        indices[i][1] = (short)(last + 1);
        indices[i][2] = (short)(last + 2);
        indices[i][3] = (short)(last + 1);
        indices[i][4] = (short)(last + 3);
        indices[i][5] = (short)(last + 2);

        last = last + 4;
    }
}

I have this order since this is the order that follows the vertices that is ...

 TRIANGLE 1

  0     2
  x x x x
  x    x
  x  x
  x
  1

 TRIANGLE 2

        2
        x
      x x
    x   x
  x x x x
  1     3

so for the first triangle it draws from 0 to 1 and then to 2 and for the second triangle it draws from 1 to 3 and then to 2.

I thougt the problem could be found here that is the drawingorder of the second triangle but a have tried several combinations but the second triangle will not be drawed.

Heres  the drawcall in the drawmethod

 GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_SHORT, 0);


问:
gulp does not serve css files (if is in sub folder)
Having a problem with gulp (or html file, I really don't know).

Below see the code and my project structure.

After running gulp everything works fine. All the files are where needed and compiled. BUT the links to CSS files do not work. I tested them without using gulp (I can just open index.html in browser) and they seem to be right - the library and custom file work right.

And this problem only occurs when the server directory is in the subfolder - when I put it to templates. For example, if the index.html is in the app folder (without putting it to templates) it works correctly (just need to change links in html from '../' to '/')

gulpfile.js:

```<code>var gulp        = require('gulp');
var browserSync = require('browser-sync').create();
var sass        = require('gulp-sass');

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
    return gulp.src(['node_modules/bootstrap/scss/bootstrap.scss', 'app/static/assets/scss/*.scss'])
        .pipe(sass())
        .pipe(gulp.dest("app/static/css"))
        .pipe(browserSync.stream());
});

// Move the javascript files into our /static/js folder
gulp.task('js', function() {
    return gulp.src(['node_modules/bootstrap/dist/js/bootstrap.min.js', 'node_modules/jquery/dist/jquery.min.js', 'node_modules/popper.js/dist/popper.min.js'])
        .pipe(gulp.dest("app/static/js"))
        .pipe(browserSync.stream());
});

// Static Server + watching scss/html files
gulp.task('serve', ['sass'], function() {

        browserSync.init({
            server: "./app/templates"
        });

        gulp.watch(['node_modules/bootstrap/scss/bootstrap.scss', 'app/static/assets/scss/*.scss'], ['sass']);
        gulp.watch("app/*.html").on('change', browserSync.reload);
    });

    gulp.task('default', ['js','serve']);
</code>```

And the html file (index.html) I won't use all the body, just refs you need:

```<code><!DOCTYPE html>
<html class="no-js" lang="en">
    <head>
        <title>2.1 ///</title>
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:400,800">
        <link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="../static/css/bootstrap.css">
        <link rel="stylesheet" href="../static/css/custom.css">
    </head>

    <body>
        <script src="../static/js/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
        <script src="../static/js/bootstrap.min.js"></script>
    </body>
</code>```

And the project structure:

```<code>/myapplication
    /node_modules
        /bootstrap
        /...
    /app
        /static
            /assets
                /scss
                    custom.scss
            /css
                custom.css
                bootstrap.css
            /js
                /...
        /templates
            index.html
    gulpfile.js
    ...
</code>```

Ok, really long question. I've tried to find the same problem, but didn't. I will appreciate any help, txh

答:
app/static/assets/scss/*.scss -> app/static/assets/scss/**/*.scss

See Globbing in Node: https://css-tricks.com/gulp-for-beginners/#article-header-id-7

Body:
Having a problem with gulp (or html file, I really don't know).

Below see the code and my project structure.

After running gulp everything works fine. All the files are where needed and compiled. BUT the links to CSS files do not work. I tested them without using gulp (I can just open index.html in browser) and they seem to be right - the library and custom file work right.

And this problem only occurs when the server directory is in the subfolder - when I put it to templates. For example, if the index.html is in the app folder (without putting it to templates) it works correctly (just need to change links in html from '../' to '/')

gulpfile.js:

var gulp        = require('gulp');
var browserSync = require('browser-sync').create();
var sass        = require('gulp-sass');

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
    return gulp.src(['node_modules/bootstrap/scss/bootstrap.scss', 'app/static/assets/scss/*.scss'])
        .pipe(sass())
        .pipe(gulp.dest("app/static/css"))
        .pipe(browserSync.stream());
});

// Move the javascript files into our /static/js folder
gulp.task('js', function() {
    return gulp.src(['node_modules/bootstrap/dist/js/bootstrap.min.js', 'node_modules/jquery/dist/jquery.min.js', 'node_modules/popper.js/dist/popper.min.js'])
        .pipe(gulp.dest("app/static/js"))
        .pipe(browserSync.stream());
});

// Static Server + watching scss/html files
gulp.task('serve', ['sass'], function() {

        browserSync.init({
            server: "./app/templates"
        });

        gulp.watch(['node_modules/bootstrap/scss/bootstrap.scss', 'app/static/assets/scss/*.scss'], ['sass']);
        gulp.watch("app/*.html").on('change', browserSync.reload);
    });

    gulp.task('default', ['js','serve']);

And the html file (index.html) I won't use all the body, just refs you need:

<!DOCTYPE html>

        <title>2.1 ///</title>
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:400,800">
        <link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="../static/css/bootstrap.css">
        <link rel="stylesheet" href="../static/css/custom.css">

And the project structure:

/myapplication
    /node_modules
        /bootstrap
        /...
    /app
        /static
            /assets
                /scss
                    custom.scss
            /css
                custom.css
                bootstrap.css
            /js
                /...
        /templates
            index.html
    gulpfile.js
    ...

Ok, really long question. I've tried to find the same problem, but didn't. I will appreciate any help, txh


问:
Bad output - array(1) { ["description"]=> string(0) "" }
how can i get good output of this script:
Source JSON: https://ufile.io/sn0hu

I need get values into array and in the next step take into variables.
Values is result->data->tab->unified_content->item (type->text if header = title and if text = description)

Script:

```<code>function getContent($data) {
    $tabs = $data->result->data->tab;
    foreach($tabs as $tab){
        $content = [];
        if(isset($tab->unified_content->item)) {
            foreach($tab->unified_content->item as $item) {
                if($item->type->name == 'header') {
                    $arr = [];
                    $arr['title'] = $item->text;
                } else {
                    $arr['description'] = $item->text;
                    $content[] = $arr;
                }
            }
            return $content;
        }
    }
}

$test = getContent($data);
foreach ($test as $lol) {
    var_dump($lol);
}
</code>```

Now is output this: array(1) { ["description"]=> string(0) "" }

答:
You need to initialize $content before the foreach loop, and return it after. Otherwise, you're only returning the contents from the first tab where unified_content->item exists. That tab contains just one item, with no header and empty text.:

```<code>    "item": [{
        "id": 17229,
        "text": "",
        "align": "l",
        "type": {
            "id": 3,
            "name": "image"
        },
        "width": "l",
        "shape": "s",
        "swajp": 0,
        "icon": 273,
        "margin": 1,
        "image": [{
            "id": 10482,
            "src": "image.php?id=18432&app_id=5786&key=a1bd33754a582bc1094e5f1b170adbb4747b7bdb",
            "title": "V ned\u011bli 12.11. od 14:00 hrajeme v Bra\u0161kov\u011b",
            "width": 1920,
            "height": 1345
        }, {
            "id": 10480,
            "src": "image.php?id=18430&app_id=5786&key=62d75ca8ea4c16fdd6a4bec8c48848f692b843bf",
            "title": "Dom\u00e1c\u00ed prohra na penalty s Jedom\u011blicemi 2:3 (1:2) Pen: 2:4",
            "width": 1920,
            "height": 1218
        }, {
            "id": 10483,
            "src": "image.php?id=18433&app_id=5786&key=1e1479dcf8de55f57e29e1a16f428f4414c76032",
            "title": "Unho\u0161\u0165 spadla na 11. m\u00edsto v tabulce",
            "width": 1920,
            "height": 1280
        }, {
            "id": 49465,
            "src": "image.php?id=90502&app_id=5786&key=3103a185854b771cdad784950d343bb3e143bec6",
            "title": "\u00dasp\u011b\u0161n\u00fd fotbalov\u00fd kemp",
            "width": 1000,
            "height": 750
        }]
    }]
</code>```

You should also initialize $arr before the inner loop, not in the if, in case there's no header object.

```<code>function getContent($data) {
    $tabs = $data->result->data->tab;
    $content = [];
    foreach($tabs as $tab){
        if(isset($tab->unified_content->item)) {
            $arr = [];
            foreach($tab->unified_content->item as $item) {
                if($item->type->name == 'header') {
                    $arr['title'] = $item->text;
                } else {
                    $arr['description'] = $item->text;
                    $content[] = $arr;
                }
            }
        }
    }
    return $content;
}
</code>```

Body:
how can i get good output of this script:
Source JSON: https://ufile.io/sn0hu

I need get values into array and in the next step take into variables.
Values is result->data->tab->unified_content->item (type->text if header = title and if text = description)

Script:

function getContent($data) {
    $tabs = $data->result->data->tab;
    foreach($tabs as $tab){
        $content = [];
        if(isset($tab->unified_content->item)) {
            foreach($tab->unified_content->item as $item) {
                if($item->type->name == 'header') {
                    $arr = [];
                    $arr['title'] = $item->text;
                } else {
                    $arr['description'] = $item->text;
                    $content[] = $arr;
                }
            }
            return $content;
        }
    }
}

$test = getContent($data);
foreach ($test as $lol) {
    var_dump($lol);
}

Now is output this: array(1) { ["description"]=> string(0) "" }

Body:
You need to initialize $content before the foreach loop, and return it after. Otherwise, you're only returning the contents from the first tab where unified_content->item exists. That tab contains just one item, with no header and empty text.:

    "item": [{
        "id": 17229,
        "text": "",
        "align": "l",
        "type": {
            "id": 3,
            "name": "image"
        },
        "width": "l",
        "shape": "s",
        "swajp": 0,
        "icon": 273,
        "margin": 1,
        "image": [{
            "id": 10482,
            "src": "image.php?id=18432&app_id=5786&key=a1bd33754a582bc1094e5f1b170adbb4747b7bdb",
            "title": "V ned\u011bli 12.11. od 14:00 hrajeme v Bra\u0161kov\u011b",
            "width": 1920,
            "height": 1345
        }, {
            "id": 10480,
            "src": "image.php?id=18430&app_id=5786&key=62d75ca8ea4c16fdd6a4bec8c48848f692b843bf",
            "title": "Dom\u00e1c\u00ed prohra na penalty s Jedom\u011blicemi 2:3 (1:2) Pen: 2:4",
            "width": 1920,
            "height": 1218
        }, {
            "id": 10483,
            "src": "image.php?id=18433&app_id=5786&key=1e1479dcf8de55f57e29e1a16f428f4414c76032",
            "title": "Unho\u0161\u0165 spadla na 11. m\u00edsto v tabulce",
            "width": 1920,
            "height": 1280
        }, {
            "id": 49465,
            "src": "image.php?id=90502&app_id=5786&key=3103a185854b771cdad784950d343bb3e143bec6",
            "title": "\u00dasp\u011b\u0161n\u00fd fotbalov\u00fd kemp",
            "width": 1000,
            "height": 750
        }]
    }]

You should also initialize $arr before the inner loop, not in the if, in case there's no header object.

function getContent($data) {
    $tabs = $data->result->data->tab;
    $content = [];
    foreach($tabs as $tab){
        if(isset($tab->unified_content->item)) {
            $arr = [];
            foreach($tab->unified_content->item as $item) {
                if($item->type->name == 'header') {
                    $arr['title'] = $item->text;
                } else {
                    $arr['description'] = $item->text;
                    $content[] = $arr;
                }
            }
        }
    }
    return $content;
}


问:
UDF in Spark works very slow
I have a UDF in spark (running on EMR), written in scala that parses device from user agent using uaparser library for scala (uap-scala). When working on small sets it works fine (5000 rows) but when running on larger sets (2M) it works very slow.
I tried collecting the Dataframe to list and looping over it on the driver, and that was also very slow, what makes me believe that the UDF runs on the driver and not the workers

How can I establish this? does anyone have another theory?

if that is the case, why can this happen?

This is the udf code:

```<code>def calcDevice(userAgent: String): String = {

val userAgentVal = Option(userAgent).getOrElse("")
Parser.get.parse(userAgentVal).device.family
}

val calcDeviceValUDF: UserDefinedFunction = udf(calcDevice _)
</code>```

usage:

```<code>.withColumn("agentDevice", udfDefinitions.calcDeviceValUDF($"userAgent"))
</code>```

Thanks
Nir

答:
Problem was with instantiating the builder within the UDF itelf. The solution is to create the object outside the udf and use it at row level:</p>

```<code>val userAgentAnalyzerUAParser = Parser.get

def calcDevice(userAgent: String): String = {

val userAgentVal = Option(userAgent).getOrElse("")
userAgentAnalyzerUAParser.parse(userAgentVal).device.family
}

val calcDeviceValUDF: UserDefinedFunction = udf(calcDevice _)
</code>```

Title: UDF in Spark works very slow

Body:
I have a UDF in spark (running on EMR), written in scala that parses device from user agent using uaparser library for scala (uap-scala). When working on small sets it works fine (5000 rows) but when running on larger sets (2M) it works very slow.
I tried collecting the Dataframe to list and looping over it on the driver, and that was also very slow, what makes me believe that the UDF runs on the driver and not the workers

How can I establish this? does anyone have another theory?

if that is the case, why can this happen?

This is the udf code:

def calcDevice(userAgent: String): String = {

val userAgentVal = Option(userAgent).getOrElse("")
Parser.get.parse(userAgentVal).device.family
}

val calcDeviceValUDF: UserDefinedFunction = udf(calcDevice _)

usage:

.withColumn("agentDevice", udfDefinitions.calcDeviceValUDF($"userAgent"))

Thanks
Nir

Body:
Problem was with instantiating the builder within the UDF itelf. The solution is to create the object outside the udf and use it at row level:

val userAgentAnalyzerUAParser = Parser.get

def calcDevice(userAgent: String): String = {

val userAgentVal = Option(userAgent).getOrElse("")
userAgentAnalyzerUAParser.parse(userAgentVal).device.family
}

val calcDeviceValUDF: UserDefinedFunction = udf(calcDevice _)


问:
While Loop to Iterate through Databases
I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns.  this is was I have done so far.  nothing works because i do not know how to make the select statement work through each database with regards to the table that I am querying from each database (dbo.tbldoc)</p>

```<code>DECLARE @Loop int
DECLARE @DBName varchar(300)
DECLARE @SQL varchar(max)
DECLARE @tableName VARCHAR(255)

SET @Loop = 1
SET @DBName = ''

   WHILE @Loop = 1
BEGIN

   SELECT [name] FROM sys.databases
   WHERE [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
   ORDER BY [name]

      SET @Loop = @@ROWCOUNT

   IF @Loop = 0
      BREAK

   SET @SQL = ('USE ['+ @DBNAME +']')
      IF EXISTS(SELECT [name] FROM sys.tables WHERE name != 'dbo.tbldoc' )
                  BEGIN
               SELECT SUM(PGCOUNT), CREATED FROM **dbo.tbldoc**
            END
            ELSE
            --BEGIN
               PRINT 'ErrorLog'
            END
</code>```

答:
I would consider sp_MSForEachDB which is a lot easier...

Edit:

```<code>EXEC sp_MSForEachDB 'USE [?]; IF DB_NAME() LIKE ''Z%%''
BEGIN

END
'
</code>```

ContentLicense: CC BY-SA 2.5

Title: While Loop to Iterate through Databases

Body:
I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns.  this is was I have done so far.  nothing works because i do not know how to make the select statement work through each database with regards to the table that I am querying from each database (dbo.tbldoc)

DECLARE @Loop int
DECLARE @DBName varchar(300)
DECLARE @SQL varchar(max)
DECLARE @tableName VARCHAR(255)

SET @Loop = 1
SET @DBName = ''

   WHILE @Loop = 1
BEGIN

   SELECT [name] FROM sys.databases
   WHERE [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
   ORDER BY [name]

      SET @Loop = @@ROWCOUNT

   IF @Loop = 0
      BREAK

   SET @SQL = ('USE ['+ @DBNAME +']')
      IF EXISTS(SELECT [name] FROM sys.tables WHERE name != 'dbo.tbldoc' )
                  BEGIN
               SELECT SUM(PGCOUNT), CREATED FROM **dbo.tbldoc**
            END
            ELSE
            --BEGIN
               PRINT 'ErrorLog'
            END

Body:
I would consider sp_MSForEachDB which is a lot easier...

Edit:

EXEC sp_MSForEachDB 'USE [?]; IF DB_NAME() LIKE ''Z%%''
BEGIN

END
'

ContentLicense: CC BY-SA 4.0


问:
AWQL AdWords API : how to retrieve CampaignStatus?
I'm using https://www.awql.me to build request and the first one below works, I'm successfully able to retrieve all campaigns with datas from past 7 days :

```<code>SELECT CampaignId, CampaignName, Clicks, Impressions
FROM CAMPAIGN_PERFORMANCE_REPORT
DURING LAST_7_DAYS
</code>```

But when I try to add CampaignStatus and/or ORDER BY and/or LIMIT, I've got the following error message:

```<code>Underlying errors are
  Type = 'QueryError.LIMIT_CLAUSE_NOT_SUPPORTED', Trigger = '', FieldPath = ''
</code>```

There is below the request that cause the issue (I also tried to just use CampaignStatus,  ORDER BY and LIMIT separately but the same error occured) :

```<code>SELECT CampaignId, CampaignName, Clicks, Impressions
FROM CAMPAIGN_PERFORMANCE_REPORT
WHERE CampaignStatus = 'Enabled'
DURING LAST_7_DAYS
ORDER BY Clicks DESC
LIMIT 0,5
</code>```

I read that it's not possible to use ORDER BY and LIMIT with CAMPAIGN_PERFORMANCE_REPORT, so how do you guys get around this limitation to retrieve formated datas in the response, at a campaigns level ?
Did you find a way to make the status works in your AWQL request ?

Thanks a lot !

答:
The problem with your CampaignStatus filter is that the status value should be ENABLED instead of Enabled.

As for LIMIT and ORDER BY, these are indeed not supported in AWQL. You'll have to process the data on your end.

Body:
I'm using https://www.awql.me to build request and the first one below works, I'm successfully able to retrieve all campaigns with datas from past 7 days :

SELECT CampaignId, CampaignName, Clicks, Impressions
FROM CAMPAIGN_PERFORMANCE_REPORT
DURING LAST_7_DAYS

But when I try to add CampaignStatus and/or ORDER BY and/or LIMIT, I've got the following error message:

Underlying errors are
  Type = 'QueryError.LIMIT_CLAUSE_NOT_SUPPORTED', Trigger = '', FieldPath = ''

There is below the request that cause the issue (I also tried to just use CampaignStatus,  ORDER BY and LIMIT separately but the same error occured) :

SELECT CampaignId, CampaignName, Clicks, Impressions
FROM CAMPAIGN_PERFORMANCE_REPORT
WHERE CampaignStatus = 'Enabled'
DURING LAST_7_DAYS
ORDER BY Clicks DESC
LIMIT 0,5

I read that it's not possible to use ORDER BY and LIMIT with CAMPAIGN_PERFORMANCE_REPORT, so how do you guys get around this limitation to retrieve formated datas in the response, at a campaigns level ?
Did you find a way to make the status works in your AWQL request ?

Thanks a lot !


问:
how to create a singular model and table in laravel
I am an absolute beginner in laravel now I undertsand the concept that laravel creates singular model and plural table name e.g

```<code>php artisan make:model Admin -m

php artisan migrate
</code>```

now this will create a model named Admin and a database named admins now logically I don't have a issue with that but it doesn't look clean if there is only one admin why need to have the table name as admins? Shouldn't it be admin? Is there any workaround for that or do I have to just stick with admins?

答:
This is default behavior. imagine the table as a bag, we have a bag of multiple users, articles or something else. but if you don't feel comfort with laravel standard, you can define your custom table name in your model.</p>

```<code>class Admin extends Model {
protected $table = 'admin';
}
</code>```

Body:
I am an absolute beginner in laravel now I undertsand the concept that laravel creates singular model and plural table name e.g

php artisan make:model Admin -m

php artisan migrate

now this will create a model named Admin and a database named admins now logically I don't have a issue with that but it doesn't look clean if there is only one admin why need to have the table name as admins? Shouldn't it be admin? Is there any workaround for that or do I have to just stick with admins?

Body:
This is default behavior. imagine the table as a bag, we have a bag of multiple users, articles or something else. but if you don't feel comfort with laravel standard, you can define your custom table name in your model.

class Admin extends Model {
protected $table = 'admin';
}


问:
Code for a simple JavaScript countdown timer?
I want to use a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. No milliseconds. How can it be coded?</p>

答:
// Javascript Countdown
// Version 1.01 6/7/07 (1/20/2000)
// by TDavid at http://www.tdscripts.com/
var now = new Date();
var theevent = new Date("Nov 13 2017 22:05:01");
var seconds = (theevent - now) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
ID = window.setTimeout("update();", 1000);

function update() {
  now = new Date();
  seconds = (theevent - now) / 1000;
  seconds = Math.round(seconds);
  minutes = seconds / 60;
  minutes = Math.round(minutes);
  hours = minutes / 60;
  hours = Math.round(hours);
  days = hours / 24;
  days = Math.round(days);
  document.form1.days.value = days;
  document.form1.hours.value = hours;
  document.form1.minutes.value = minutes;
  document.form1.seconds.value = seconds;
  ID = window.setTimeout("update();", 1000);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>
</p>
<form name="form1">
  <p>Days
    <input type="text" name="days" value="0" size="3">Hours
    <input type="text" name="hours" value="0" size="4">Minutes
    <input type="text" name="minutes" value="0" size="7">Seconds
    <input type="text" name="seconds" value="0" size="7">
  </p>
</form></code>```

Body:
// Javascript Countdown
// Version 1.01 6/7/07 (1/20/2000)
// by TDavid at http://www.tdscripts.com/
var now = new Date();
var theevent = new Date("Nov 13 2017 22:05:01");
var seconds = (theevent - now) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
ID = window.setTimeout("update();", 1000);

function update() {
  now = new Date();
  seconds = (theevent - now) / 1000;
  seconds = Math.round(seconds);
  minutes = seconds / 60;
  minutes = Math.round(minutes);
  hours = minutes / 60;
  hours = Math.round(hours);
  days = hours / 24;
  days = Math.round(days);
  document.form1.days.value = days;
  document.form1.hours.value = hours;
  document.form1.minutes.value = minutes;
  document.form1.seconds.value = seconds;
  ID = window.setTimeout("update();", 1000);
}

<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>
</p>
<form name="form1">
  <p>Days
    <input type="text" name="days" value="0" size="3">Hours
    <input type="text" name="hours" value="0" size="4">Minutes
    <input type="text" name="minutes" value="0" size="7">Seconds
    <input type="text" name="seconds" value="0" size="7">
  </p>
</form>


问:
How PHP knows encoding of textual data when parsing POST 'multipart/form-data' input?
I wonder how exactly PHP detects encoding of input data which came from HTTP request.

Imagine API which accepts requests from various clients (mobile apps maybe, not from browsers). The incoming request has header Content-Type: multipart/form-data and by this, no additional encoding information was given.

Let's say that there was a text field within the POST body and I want to apply validation on it. How do I know the encoding I should use?

I found no clear answer in the documentation so please help. I guess, I may look at Mbstring extension which has mb_check_encoding() and it could be used for this purpose. Is it a reliable way?

How client can say which encoding they used when sending multipart/form-data POST request:
As RFC-7578 says (https://www.rfc-editor.org/rfc/rfc7578#section-4.4) each part of multipart/form-data payload can have its own Content-Type information. Which solves a problem of communicating encoding information.

答:
Ok, there are actually two problems:

How to communicate encoding that was used for text creation (in case of transferring it with multibyte/form-data method);

How to detect what real encoding was used for text creation;

The first problem is a problem of communication and can be solved both by reading a documentation as well as providing an additional explicit header for text section within request payload. See RFC-7578 for details.

The second problem has no proper solution. It is hard to detect the actual encoding that was used to assemble the text. Though, you can guess with functions like mb_detect_encoding().


问:
Any url typed on the address bar navigates back to the root url in Angular 4
The routing works perfectly if one click on any of the anchor tags. The problem occurs only if the user manually types the url on the address bar

For example,
If one click on sign in link from the top navigation bar of the web page, then angular is correctly loading the sign in component, but if the user types http://localhost:4200/sign-in, it loads the home component

Specification

Ubuntu 17.10
Node 6.11.4
NPM 5.5.1

The code of the application is below

src/app/app.router.ts

```<code>import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { SignUpComponent } from './sign-up/sign-up.component';
import { SignInComponent } from './sign-in/sign-in.component';
import { HomeComponent } from './home/home.component';
import { Route } from '@angular/router';

export const routes: Route[] = [
  { path: 'sign-up', component: SignUpComponent},
  { path: 'sign-in', component: SignInComponent},
  { path: 'admin', pathMatch: 'full', loadChildren: 'app/admin/admin.module#AdminModule'},
  { path: 'dashboard', loadChildren: 'app/user/user.module#UserModule'},
  { path: '', pathMatch: 'full', component: HomeComponent},
  { path: '**', pathMatch: 'full', component: PageNotFoundComponent}
];
</code>```

src/app/app.component.html

```<code><top-navigation></top-navigation>
<router-outlet></router-outlet>
</code>```

src/app/shared/top-navigation/top-navigation.component.html

```<code><nav class="navbar navbar-expand-lg navbar-light">
  <a class="navbar-brand" href="#">RS</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText"
    aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
  <div class="collapse navbar-collapse" id="navbarText">
    <ul class="navbar-nav mr-auto">
      <li *ngIf="isLoggedIn" class="nav-item">
          <a class="nav-link" [routerLink]="['/dashboard']" >Dashboard</a>
      </li>
    </ul>

    <!-- SIGNED IN USER -->
    <div *ngIf="isLoggedIn" class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        {{currentUser.username}}
      </a>
      <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
        <a class="dropdown-item" routerLink="/me" routerLinkActive="active">Me</a>
        <a class="nav-link disabled" href="#">Disabled</a>
        <a class="nav-link" (click)="authService.logout()">Logout</a>
      </div>
    </div> <!-- [/END] SIGNED IN USER -->

    <!-- NO USER -->
    <div *ngIf="!isLoggedIn" class="nav-item">
      <a class="nav-link" [routerLink]="['/admin']">Sign In</a>
    </div>

  </div>
</nav>
</code>```

src/index.html

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>

  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

</body>
</html>
</code>```

答:
Set the config router to  useHash or make url rewrite.

Following the command to solve this situatoin that rewrite (manage state).

```<code>$ npm install http-server -g
$ npm install -g spa-http-server
$ http-server --push-state
# ↑ it would solve the state flush problem.
</code>```

Another way, use {useHash:true,enableTracing:true} in your RouterModule config.

```<code>config = {useHash:true,enableTracing:true};

imports:[RouterModule.forRoot(routes,config),]
</code>```

Body:
The routing works perfectly if one click on any of the anchor tags. The problem occurs only if the user manually types the url on the address bar

For example,
If one click on sign in link from the top navigation bar of the web page, then angular is correctly loading the sign in component, but if the user types http://localhost:4200/sign-in, it loads the home component

Specification

Ubuntu 17.10
Node 6.11.4
NPM 5.5.1

The code of the application is below

src/app/app.router.ts

import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { SignUpComponent } from './sign-up/sign-up.component';
import { SignInComponent } from './sign-in/sign-in.component';
import { HomeComponent } from './home/home.component';
import { Route } from '@angular/router';

export const routes: Route[] = [
  { path: 'sign-up', component: SignUpComponent},
  { path: 'sign-in', component: SignInComponent},
  { path: 'admin', pathMatch: 'full', loadChildren: 'app/admin/admin.module#AdminModule'},
  { path: 'dashboard', loadChildren: 'app/user/user.module#UserModule'},
  { path: '', pathMatch: 'full', component: HomeComponent},
  { path: '**', pathMatch: 'full', component: PageNotFoundComponent}
];

src/app/app.component.html

<top-navigation></top-navigation>
<router-outlet></router-outlet>

src/app/shared/top-navigation/top-navigation.component.html

  RS
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText"
    aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Dashboard

        {{currentUser.username}}

        Me
        Disabled
        Logout

      Sign In

src/index.html

<!doctype html>

  <meta charset="utf-8">
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

Body:
Set the config router to  useHash or make url rewrite.

Following the command to solve this situatoin that rewrite (manage state).

$ npm install http-server -g
$ npm install -g spa-http-server
$ http-server --push-state
# ↑ it would solve the state flush problem.

Another way, use {useHash:true,enableTracing:true} in your RouterModule config.

config = {useHash:true,enableTracing:true};

imports:[RouterModule.forRoot(routes,config),]


问:
Unity | Which child sprite did I clicked?
I made and empty game object that I use for a container for my sprites, which are my buttons.
I want to know which sprite I just clicked with one script on my container so I can add more buttons later and not have to alter the code.</p>

答:
Many way can doing that.
my solution:

i Create Button Script to handling the OnMouseDown but i don't add it to child because i add it with the Container code.

then in ButtonContainer script get all child and add BoxCollider2D and Button to theme and important part is Adding your listener(DoSomthing method).

Done. :)

create a script Button:

using UnityEngine;
using UnityEngine.Events;

public class Button : MonoBehaviour
{
    private SpriteRenderer sr;
    public MouseDownEvent mouseDown = new MouseDownEvent();

    void Awake(){
        sr = GetComponent<SpriteRenderer>();
    }

    void OnMouseDown(){
        mouseDown.Invoke(sr);
    }
}

[System.Serializable]
public class MouseDownEvent : UnityEvent<SpriteRenderer> { }
```

<p>2.create a script for ButtonCountainer</p>

<pre class="lang-cs prettyprint-override"><code>using UnityEngine;

public class ButtonContainer : MonoBehaviour
{
    private void Awake()
    {
        // get all child
        var childs = GetComponentsInChildren<Transform>();

        // add button class to them
        for (int i = 0; i < childs.Length; i++) {
            // child element
            var go = childs[i].gameObject;
            // add boxcolliser2d. (child must have collider to invoke the OnMouseDown Message)
            go.AddComponent<BoxCollider2D>();
            // add button script to them
            var b = go.AddComponent<Button>();
            // do everything you want with this event
            b.mouseDown.AddListener(DoSomthing);
        }
    }
    // every time this gameObject invoke sr = sprite renderer of the that gameObject
    private void DoSomthing(SpriteRenderer sr)
    {
        Debug.Log(sr.name);
    }
}
</code>```

create GameObject and add ButtonCountainer to that.

now add sprites as child.

end. we have lunch.

Body:
Many way can doing that.
my solution:

i Create Button Script to handling the OnMouseDown but i don't add it to child because i add it with the Container code.

then in ButtonContainer script get all child and add BoxCollider2D and Button to theme and important part is Adding your listener(DoSomthing method).

Done. :)

create a script Button:

using UnityEngine;
using UnityEngine.Events;

public class Button : MonoBehaviour
{
    private SpriteRenderer sr;
    public MouseDownEvent mouseDown = new MouseDownEvent();

    void Awake(){
        sr = GetComponent<SpriteRenderer>();
    }

    void OnMouseDown(){
        mouseDown.Invoke(sr);
    }
}

[System.Serializable]
public class MouseDownEvent : UnityEvent<SpriteRenderer> { }

2.create a script for ButtonCountainer

using UnityEngine;

public class ButtonContainer : MonoBehaviour
{
    private void Awake()
    {
        // get all child
        var childs = GetComponentsInChildren<Transform>();

        // add button class to them
        for (int i = 0; i < childs.Length; i++) {
            // child element
            var go = childs[i].gameObject;
            // add boxcolliser2d. (child must have collider to invoke the OnMouseDown Message)
            go.AddComponent<BoxCollider2D>();
            // add button script to them
            var b = go.AddComponent<Button>();
            // do everything you want with this event
            b.mouseDown.AddListener(DoSomthing);
        }
    }
    // every time this gameObject invoke sr = sprite renderer of the that gameObject
    private void DoSomthing(SpriteRenderer sr)
    {
        Debug.Log(sr.name);
    }
}

create GameObject and add ButtonCountainer to that.

now add sprites as child.

end. we have lunch.


问:
Does the RX0 support the Sony Remote API
I'm hoping to develop custom software that will work with the new Sony RX0. It will require Sony Remote API support. Can anyone confirm if the Remote API supports the RX0?</p>

答: Unfortunately the RX0 does not support the Camera Remote API.</p>


问:
SQL Finding most spoken language in a country
I am trying to get the most spoken language in a country based on percentage. I am joining 2 tables:

```<code>Country(NAME,CODE)
CountryLanguage(Percentage, CountryCode, Language)
</code>```

Joining those 2 gives me

```<code>Aruba           Dutch       5.3
Aruba           English     9.5
Aruba           Papiamento  76.7
Aruba           Spanish     7.4
Afghanistan     Balochi     0.9
Afghanistan     Dari        32.1
Afghanistan     Pashto      52.4
Afghanistan     Turkmenian  1.9
Afghanistan     Uzbek       8.8
</code>```

I tried to get the most spoken language by saying

```<code>SELECT co.Name, cl.language, max(cl.Percentage)
from Country co, CountryLanguage cl
where co.Code = cl.CountryCode
group by co.Name
</code>```

This gives me the right percentage but wrong language, where did I go wrong?

```<code>Afghanistan  Balochi    52.4
Aruba        Dutch      76.7
</code>```

答:
You can use windowing functions to get this answer:

RANK with a PARTITION will do the trick

```<code>With RecordedPercentages AS
(
              Select 'Aruba' Country, 'Dutch' LanguageName, Cast (5.3 as float) Percentage
    Union All Select 'Aruba', 'English', 9.5
    Union All Select 'Aruba', 'Papiamento', 76.7
    Union All Select 'Aruba', 'Spanish', 7.4
    Union All Select 'Afghanistan', 'Balochi', 0.9
    Union All Select 'Afghanistan', 'Dari', 32.1
    Union All Select 'Afghanistan', 'Pashto', 52.4
    Union All Select 'Afghanistan', 'Turkmenian', 1.9
    Union All Select 'Afghanistan', 'Uzbek', 8.8
),
MyRanking As
(
    Select
    Country, LanguageName, Percentage,
    Rank() Over (Partition by Country Order by Percentage Desc) Ranking
    From RecordedPercentages
)
Select *
From MyRanking
Where Ranking = 1
</code>```

Body:
I am trying to get the most spoken language in a country based on percentage. I am joining 2 tables:

Country(NAME,CODE)
CountryLanguage(Percentage, CountryCode, Language)

Joining those 2 gives me

Aruba           Dutch       5.3
Aruba           English     9.5
Aruba           Papiamento  76.7
Aruba           Spanish     7.4
Afghanistan     Balochi     0.9
Afghanistan     Dari        32.1
Afghanistan     Pashto      52.4
Afghanistan     Turkmenian  1.9
Afghanistan     Uzbek       8.8

I tried to get the most spoken language by saying

SELECT co.Name, cl.language, max(cl.Percentage)
from Country co, CountryLanguage cl
where co.Code = cl.CountryCode
group by co.Name

This gives me the right percentage but wrong language, where did I go wrong?

Afghanistan  Balochi    52.4
Aruba        Dutch      76.7

Body:
You can use windowing functions to get this answer:

RANK with a PARTITION will do the trick

With RecordedPercentages AS
(
              Select 'Aruba' Country, 'Dutch' LanguageName, Cast (5.3 as float) Percentage
    Union All Select 'Aruba', 'English', 9.5
    Union All Select 'Aruba', 'Papiamento', 76.7
    Union All Select 'Aruba', 'Spanish', 7.4
    Union All Select 'Afghanistan', 'Balochi', 0.9
    Union All Select 'Afghanistan', 'Dari', 32.1
    Union All Select 'Afghanistan', 'Pashto', 52.4
    Union All Select 'Afghanistan', 'Turkmenian', 1.9
    Union All Select 'Afghanistan', 'Uzbek', 8.8
),
MyRanking As
(
    Select
    Country, LanguageName, Percentage,
    Rank() Over (Partition by Country Order by Percentage Desc) Ranking
    From RecordedPercentages
)
Select *
From MyRanking
Where Ranking = 1


问:
MySQL cache and date functions
I once read in a performance blog that it is better to use PHP's date functions to set dates in a MySQL query instead of using mysql date functions like curdate() because mysql can then cache the query or the result or something like that. Does anyone have any insight into this? Does it hold any water or is it baseless?

example:

```<code>$query = 'SELECT id FROM table WHERE publish_date = \''.date('Y-m-d').'\'';
</code>```

vs

```<code>$query = 'SELECT id FROM table WHERE publish_date = CURDATE()';
</code>```

答:
I personally preffer first way, because it give clear head about server time (time zone), my mysql server happend to be 10h earlier when promissed :)

localtime in your PHP script will apply in SQL

Title: MySQL cache and date functions

Body:
I once read in a performance blog that it is better to use PHP's date functions to set dates in a MySQL query instead of using mysql date functions like curdate() because mysql can then cache the query or the result or something like that. Does anyone have any insight into this? Does it hold any water or is it baseless?

example:

$query = 'SELECT id FROM table WHERE publish_date = \''.date('Y-m-d').'\'';

vs

$query = 'SELECT id FROM table WHERE publish_date = CURDATE()';


问:
MVC Refresh Partial View after Ajax HTTPPost
I am tryng to update a partial view after an Ajax HttpPost.

This is the controller for the Partial view:

```<code>    public PartialViewResult BrtMagazzino(DataMagazzino m)
    {
        if (Session["Data"] != null)
        {
            DateToView dt = (DateToView)Session["Data"];
            ViewBag.comm = dt.commSelected.COMMITTENTE;
            ViewBag.corriere = "Bartolini";
        }
        return PartialView(m);
    }
</code>```

This is the code for the view that include the partial:

```<code><div id="view-Bartolini">
   @{
      Html.RenderAction("BartoliniMagazzino", "Partial", new { m = item });
    }
</div>
</code>```

This is the code for the button:

```<code><input class='btn btn-info btnBordero' type='button' value='Salva Borderò' data-corriere="@ViewBag.corriere" data-magazzino="@Model.NomeMagazzino" data-committente="@ViewBag.comm" />
</code>```

This is the code for the click of this button:

```<code>$(function () {
    $('.btnBordero').on('click', function (event) {
        event.preventDefault();
        _self = $(this);
        var uf = new FormData();
        uf.append('corriere', _self.data('corriere'));
        uf.append('magazzino', _self.data('magazzino'));
        uf.append('committente', _self.data('committente'));
        var url = "/Partial/SaveBordero";
        $.ajax({
            type: "POST",
            url: url,
            contentType: false,
            processData: false,
            data: uf,
            error: function (ts) { alert(ts.responseText)
            },
            success: function (result) {
                $("#view-Bartolini").html(result);
            }
        });
    });
});
</code>```

The SaveBordero function have this code:

```<code>[HttpPost]
public ActionResult SaveBordero(FormCollection form)
{
   DataMagazzino dt = new DataMagazzino();
   // Do something
   return PartialView("BartoliniMagazzino", new { m = dt });
}
</code>```

All works fine but when i call the return PartialView in SaveBordero function the ajax call always go in the error part. I don't know how to go in success and update the partial view

答:
The problem is in this row: return PartialView("BartoliniMagazzino", new { m = dt });

If i call a new m Model this is an anonymus type and the system doesn't reconize it.

I have solved it just writing: return PartialView("BartoliniMagazzino", dt);

Thanks to all

Body:
I am tryng to update a partial view after an Ajax HttpPost.

This is the controller for the Partial view:

    public PartialViewResult BrtMagazzino(DataMagazzino m)
    {
        if (Session["Data"] != null)
        {
            DateToView dt = (DateToView)Session["Data"];
            ViewBag.comm = dt.commSelected.COMMITTENTE;
            ViewBag.corriere = "Bartolini";
        }
        return PartialView(m);
    }

This is the code for the view that include the partial:

   @{
      Html.RenderAction("BartoliniMagazzino", "Partial", new { m = item });
    }

This is the code for the button:

<input class='btn btn-info btnBordero' type='button' value='Salva Borderò' data-corriere="@ViewBag.corriere" data-magazzino="@Model.NomeMagazzino" data-committente="@ViewBag.comm" />

This is the code for the click of this button:

$(function () {
    $('.btnBordero').on('click', function (event) {
        event.preventDefault();
        _self = $(this);
        var uf = new FormData();
        uf.append('corriere', _self.data('corriere'));
        uf.append('magazzino', _self.data('magazzino'));
        uf.append('committente', _self.data('committente'));
        var url = "/Partial/SaveBordero";
        $.ajax({
            type: "POST",
            url: url,
            contentType: false,
            processData: false,
            data: uf,
            error: function (ts) { alert(ts.responseText)
            },
            success: function (result) {
                $("#view-Bartolini").html(result);
            }
        });
    });
});

The SaveBordero function have this code:

[HttpPost]
public ActionResult SaveBordero(FormCollection form)
{
   DataMagazzino dt = new DataMagazzino();
   // Do something
   return PartialView("BartoliniMagazzino", new { m = dt });
}

All works fine but when i call the return PartialView in SaveBordero function the ajax call always go in the error part. I don't know how to go in success and update the partial view


问:
Delete files, directories and buckets in amazon s3 java
I'm wondering how to do this. I looked at the sdk documentation and have some examples, but am confused how the syntax generally goes.

If I want to delete a file, I assume I use deleteObject(path, key). However, what is the "key"?

Also how do you delete a directory? I can't seem to find a method for doing that.

答:
As question is asking about Deleting files, directories and buckets in amazon S3 java, I would like to offer code for deleting a non-empty S3 bucket (AWS Reference):</p>

```<code> public void deleteBucket(final String bucketName) {

        final AmazonS3 s3 = AmazonS3ClientBuilder.defaultClient();

        try {
            ObjectListing objectListing = s3.listObjects(bucketName);
            while (true) {
                for (Iterator<?> iterator = objectListing.getObjectSummaries().iterator(); iterator.hasNext(); ) {
                    S3ObjectSummary summary = (S3ObjectSummary) iterator.next();
                    s3.deleteObject(bucketName, summary.getKey());
                }

                if (objectListing.isTruncated()) {
                    objectListing = s3.listNextBatchOfObjects(objectListing);
                } else {
                    break;
                }
            }

            VersionListing versionListing = s3.listVersions(new ListVersionsRequest().withBucketName(bucketName));
            while (true) {
                for (Iterator<?> iterator = versionListing.getVersionSummaries().iterator(); iterator.hasNext(); ) {
                    S3VersionSummary vs = (S3VersionSummary) iterator.next();
                    s3.deleteVersion(bucketName, vs.getKey(), vs.getVersionId());
                }

                if (versionListing.isTruncated()) {
                    versionListing = s3.listNextBatchOfVersions(versionListing);
                } else {
                    break;
                }
            }

            s3.deleteBucket(bucketName);
        } catch (AmazonServiceException e) {
            System.err.println(e.getErrorMessage());
        }
    }
</code>```

Body:
As question is asking about Deleting files, directories and buckets in amazon S3 java, I would like to offer code for deleting a non-empty S3 bucket (AWS Reference):

 public void deleteBucket(final String bucketName) {

        final AmazonS3 s3 = AmazonS3ClientBuilder.defaultClient();

        try {
            ObjectListing objectListing = s3.listObjects(bucketName);
            while (true) {
                for (Iterator<?> iterator = objectListing.getObjectSummaries().iterator(); iterator.hasNext(); ) {
                    S3ObjectSummary summary = (S3ObjectSummary) iterator.next();
                    s3.deleteObject(bucketName, summary.getKey());
                }

                if (objectListing.isTruncated()) {
                    objectListing = s3.listNextBatchOfObjects(objectListing);
                } else {
                    break;
                }
            }

            VersionListing versionListing = s3.listVersions(new ListVersionsRequest().withBucketName(bucketName));
            while (true) {
                for (Iterator<?> iterator = versionListing.getVersionSummaries().iterator(); iterator.hasNext(); ) {
                    S3VersionSummary vs = (S3VersionSummary) iterator.next();
                    s3.deleteVersion(bucketName, vs.getKey(), vs.getVersionId());
                }

                if (versionListing.isTruncated()) {
                    versionListing = s3.listNextBatchOfVersions(versionListing);
                } else {
                    break;
                }
            }

            s3.deleteBucket(bucketName);
        } catch (AmazonServiceException e) {
            System.err.println(e.getErrorMessage());
        }
    }


问:
Add Check Boxes in Facebook Messenger Chat Room
I want to add check boxes in chat room of facebook messenger. I have been searching but could not find any helpful material! Any suggestions? </p>

答: You can get check boxes via Chat Extensions.</p>


问:
Refresh screen data (START-OF-SELECTION)
I'm developing a report with multiple ALVs.
In START-OF-SELECTION I have:

1) data selection

2) ALV display cl_salv_hierseq_table

The lines can be selected through checkbox. When a button is pressed, some tables in DB are updated. After this processing, I have to return to point 2,
BUT the data on the screen has to be updated (point 1). How I can do this?

Thanks.

答: I think you need to use the REFRESH method of the class.


问:
href in scrollable div-container - link not working jumps to top of container
I got a draggable div container with some dynamically generated content inside.

I call it with this code:

```<code>$( function() {
$( "#dialog-message" ).dialog({
    modal: true,
    height: 400,
    buttons: {
    Fertig: function() {
      $( this ).dialog( "close" );
    }
  }
});
</code>```

CSS:

```<code>div#dialog-message {
background-color:#e8ebf3;
overflow:auto;
</code>```

Inside the div I have other divs with href-links inside.
The links that are shown without scrolling do work fine, but when I scroll down in this container the hrefs does not work and the container scrolls automaticaly to the top when clicking.

The problem is that I use the href with an ID input from my database to toggle visibility of other div-containers like so:

```<code><div href="651">This does not scroll</div>
</code>```

Any ideas, how to combine the answers with this?

The href’s do work in Firefox, when I scroll down and click a link for the first time. But when I click it a second time without refreshing the page, it will scroll to the top.

In Chrome it doesn’t work a single time.

```<code><div id="dialog"  href="651">First time clicking works, second time not.</div>
</code>```

Problem solved:

The problem was that the page was not fully load when I tried to href to an div-Container witch did not exists at this point.

Thanks for all the answers!

答:
You do need to make sure the href is not just #, Use an href like #void or so. Just having an href with # will make the page scroll to the top. An example:

This will scroll to the top

This will not

Body:
I got a draggable div container with some dynamically generated content inside.

I call it with this code:

$( function() {
$( "#dialog-message" ).dialog({
    modal: true,
    height: 400,
    buttons: {
    Fertig: function() {
      $( this ).dialog( "close" );
    }
  }
});

CSS:

div#dialog-message {
background-color:#e8ebf3;
overflow:auto;

Inside the div I have other divs with href-links inside.
The links that are shown without scrolling do work fine, but when I scroll down in this container the hrefs does not work and the container scrolls automaticaly to the top when clicking.

The problem is that I use the href with an ID input from my database to toggle visibility of other div-containers like so:

This does not scroll

Any ideas, how to combine the answers with this?

The href’s do work in Firefox, when I scroll down and click a link for the first time. But when I click it a second time without refreshing the page, it will scroll to the top.

In Chrome it doesn’t work a single time.

First time clicking works, second time not.

Problem solved:

The problem was that the page was not fully load when I tried to href to an div-Container witch did not exists at this point.

Thanks for all the answers!

Body:
You do need to make sure the href is not just #, Use an href like #void or so. Just having an href with # will make the page scroll to the top. An example:

<a href="#">This will scroll to the top</a>

<a href="#void">This will not</a>


问:
Confusion about Keras RNN Input shape requirement
I have read plenty of posts for this point. They are inconsistent with each other and every answer seems to have a different explanation so I thought to ask based on my analyzing of all of them.

As Keras RNN documentation states, the input shape is always in this form (batch_size, timesteps, input_dim). I am a bit confused about that but I guess, not sure though, that input_dim is always 1 while timesteps depends on your problem (could be the data dimension as well). Is that roughly correct?

The reason for this question is that I always get an error when trying to change the value of input_dim to be my dataset dimension (as input_dim sounds like that!!), so I made an assumption that input_dim represent the shape of the input vector to LSTM at a time. Am I wrong again?

```<code>C = C.reshape((C.shape[0], C.shape[1], 1))
tr_C, ts_C, tr_r, ts_r = train_test_split(C, r, train_size=.8)
batch_size = 1000

print('Build model...')
model = Sequential()

model.add(LSTM(8, batch_input_shape=(batch_size, C.shape[1], 1), stateful=True, activation='relu'))
model.add(Dense(1, activation='relu'))

print('Training...')
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(tr_C, tr_r,
          batch_size=batch_size, epochs=1,
          shuffle=True, validation_data=(ts_C, ts_r))
</code>```

Thanks!

答:
Indeed, input_dim is the shape of the input vector at a time. In other words, input_dim is the number of the input features.

It's not necessarily 1, though. If you're working with more than one var, it can be any number.

Suppose you have 10 sequences, each sequence has 200 time steps, and you're measuring just a temperature. Then you have one feature:

input_shape = (200,1) -- notice that the batch size (number of sequences) is ignored here

batch_input_shape = (10,200,1) -- only in specific cases, like stateful = True, you will need a batch input shape.

Now suppose you're measuring not only temperature, but also pressure and volume. Now you've got three input features:

input_shape = (200,3)

batch_input_shape = (10,200,3)

In other words, the first dimension is the number of different sequences. The second is the length of the sequence (how many measures along time). And the last is how many vars at each time.

Body:
I have read plenty of posts for this point. They are inconsistent with each other and every answer seems to have a different explanation so I thought to ask based on my analyzing of all of them.

As Keras RNN documentation states, the input shape is always in this form (batch_size, timesteps, input_dim). I am a bit confused about that but I guess, not sure though, that input_dim is always 1 while timesteps depends on your problem (could be the data dimension as well). Is that roughly correct?

The reason for this question is that I always get an error when trying to change the value of input_dim to be my dataset dimension (as input_dim sounds like that!!), so I made an assumption that input_dim represent the shape of the input vector to LSTM at a time. Am I wrong again?

C = C.reshape((C.shape[0], C.shape[1], 1))
tr_C, ts_C, tr_r, ts_r = train_test_split(C, r, train_size=.8)
batch_size = 1000

print('Build model...')
model = Sequential()

model.add(LSTM(8, batch_input_shape=(batch_size, C.shape[1], 1), stateful=True, activation='relu'))
model.add(Dense(1, activation='relu'))

print('Training...')
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(tr_C, tr_r,
          batch_size=batch_size, epochs=1,
          shuffle=True, validation_data=(ts_C, ts_r))

Thanks!


问:
Maven plugin dependencies are ignored
I created this profile for deploying artifacts on the server via SCP. I know Ant's scp task is optional, therefore I've added the dependencies.

```<code><profiles>
        <profile>
            <id>remote-deploy</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>scp</id>
                                <phase>install</phase>
                                <configuration>
                                    <tasks>
                                        <scp .../>
                                        <sshexec .../>
                                    </tasks>
                                </configuration>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                        <dependencies>
                            <dependency>
                                <groupId>org.apache.ant</groupId>
                                <artifactId>ant-jsch</artifactId>
                                <version>1.7.1</version>
                            </dependency>
                            <dependency>
                                <groupId>com.jcraft</groupId>
                                <artifactId>jsch</artifactId>
                                <version>0.1.42</version>
                            </dependency>
                        </dependencies>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</code>```

However, when I run the profile, I end up with

An Ant BuildException has occured:
  Problem: failed to create task or type
  scp Cause: the class
  org.apache.tools.ant.taskdefs.optional.ssh.Scp
  was not found.
          This looks like one of Ant's optional components. Action: Check
  that the appropriate optional JAR
  exists in
          -ANT_HOME\lib
          -the IDE Ant configuration dialogs

Do not panic, this is a common
  problem. The commonest cause is a
  missing JAR.

This is not a bug; it is a
  configuration problem

Is it possible maven wasn't able to download those dependencies or it just ignores them?

答:
The problem was Maven (2.2.1) didn't download the dependencies. I've found out after I upgraded Maven to version 3. For some reason,the new version downloaded the plugin dependencies and it miraculously started to work.

I have a suspicion the problem was in old version Maven's settings - pluginRepository wasn't configured.

Title: Maven plugin dependencies are ignored

Body:
I created this profile for deploying artifacts on the server via SCP. I know Ant's scp task is optional, therefore I've added the dependencies.

<profiles>
        <profile>
            <id>remote-deploy</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>scp</id>
                                <phase>install</phase>
                                <configuration>
                                    <tasks>
                                        <scp .../>
                                        <sshexec .../>
                                    </tasks>
                                </configuration>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                        <dependencies>
                            <dependency>
                                <groupId>org.apache.ant</groupId>
                                <artifactId>ant-jsch</artifactId>
                                <version>1.7.1</version>
                            </dependency>
                            <dependency>
                                <groupId>com.jcraft</groupId>
                                <artifactId>jsch</artifactId>
                                <version>0.1.42</version>
                            </dependency>
                        </dependencies>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

However, when I run the profile, I end up with

An Ant BuildException has occured:
  Problem: failed to create task or type
  scp Cause: the class
  org.apache.tools.ant.taskdefs.optional.ssh.Scp
  was not found.
          This looks like one of Ant's optional components. Action: Check
  that the appropriate optional JAR
  exists in
          -ANT_HOME\lib
          -the IDE Ant configuration dialogs

Do not panic, this is a common
  problem. The commonest cause is a
  missing JAR.

This is not a bug; it is a
  configuration problem

Is it possible maven wasn't able to download those dependencies or it just ignores them?


问:
How to center text in a row using Bootstrap 4
The problem is that
 and
 are appearing on same line and no matter what I do they can't be centered.

HTML

```<code><div class="container">
  <div class="row" id="appSummary">
    <h1>Why This App Is Awesome</h1>
    <p class="lead">Summary, once again, of your app's awesomeness</p>
  </div>
</div>
</code>```

CSS

```<code>#appSummary{
  text-align:center;
}
</code>```

答:
Use d-flex flex-column : more here    </p>

```<code><div class="container">
        <div class="d-flex flex-column" id="appSummary">
            <h1>Why This App Is Awesome</h1>
            <p class="lead">Summary, once again, of your app's awesomeness</p>

        </div>
 </div>
</code>```

Body:
The problem is that
 and
 are appearing on same line and no matter what I do they can't be centered.

HTML

Why This App Is Awesome

Summary, once again, of your app's awesomeness

CSS

#appSummary{
  text-align:center;
}

Body:
Use d-flex flex-column : more here

<div class="container">
        <div class="d-flex flex-column" id="appSummary">
            <h1>Why This App Is Awesome</h1>
            <p class="lead">Summary, once again, of your app's awesomeness</p>

        </div>
 </div>