问:
Export Excel data to fixed-width text file - field locations
Let me begin by saying I'm kind of new to working with delimited files. I am trying to emulate how a piece of software lays out a text file using Excel.

Here is the code I'm using to create a text file from the worksheet:

```<code>Sub Export_Selection_As_Fixed_Length_File()
     ' Dimension all  variables.
    Dim DestinationFile, CellValue, Filler_Char_To_Replace_Blanks As String
    Dim FileNum, ColumnCount, RowCount, FieldWidth As Integer
    Dim sht As Worksheet

    'Below are options incase you want to change the folder where VBA stores the .txt file
    'We use ActiveWorkbook.Path in this example
    'ActiveWorkbook.Path 'the activeworkbook
    'ThisWorkbook.Path  'the workbook with the code
    'CurDir  'the current directory (when you hit File|open)

    'If a cell is blank, what character should be used instead
    Filler_Char_To_Replace_Blanks = " "

        'Check if the user has made any selection at all
        If Selection.Cells.Count < 2 Then
            MsgBox "Nothing selected to export"
            Selection.Activate
            End
        End If

    'This is the destination file name.
    DestinationFile = ActiveWorkbook.Path & "/textfile.txt"
    'Obtain next free file handle number.
    FileNum = FreeFile()

     ' Turn  error checking off.
    On Error Resume Next

     ' Attempt to open destination file for output.
    Open DestinationFile For Output As #FileNum

     ' If an error occurs report it and end.
    If Err <> 0 Then
         MsgBox "Cannot open filename " & DestinationFile
         Selection.Activate
        End
    End If

     ' Turn error checking on.
    On Error GoTo 0

     '  Loop for each row in selection.
    For RowCount = 1 To Selection.Rows.Count
                For ColumnCount = 1 To Selection.Columns.Count
                    CellValue = Selection.Cells(RowCount, ColumnCount).Text
                    If (IsNull(CellValue) Or CellValue = "") Then CellValue = Filler_Char_To_Replace_Blanks
                    FieldWidth = Cells(1, ColumnCount).Value
                    If (ColumnCount = Selection.Columns.Count) Then
                            Print #FileNum, Format$(CellValue, "!" & String(FieldWidth, "@")) & vbCrLf;
                    Else: Print #FileNum, Format$(CellValue, "!" & String(FieldWidth, "@"));
                    End If
                Next ColumnCount
         ' Start next iteration of RowCount loop.
    Next RowCount
     ' Close destination file.
    Close #FileNum
    Selection.Activate
    Workbooks.OpenText Filename:=DestinationFile
End Sub
</code>```

The software I'm trying to emulate has "data locations" and "field sizes." For example, one field has a data location of 77, which means it will start as the 77th character on the line in the text file. (I don't know how common this is, so if it's very common, please excuse the useless information.) And the field size is 12.

If that doesn't make sense, here's a screenshot of a text file. The first line shows what my VBA creates, and the second line is how I want it to look. How can I force the values on the worksheet to start at a certain position on the line based on the column it's in?

答:
It looks like your first row in the selection contains the field's width FieldWidth = Cells(1, ColumnCount).Value. In your problem description you mentioned data locations and field sizes.  You need to have this information some where.  You could put it on another sheet in the file, which would let you adjust the output of text file, or you could put those values in your VBA code as constants, or your could create a Class.  Using something like this will enable you can redefine the fields as needed.  The example below uses a simple class and a few private functions in the module

In the example below you'll need to add a sheet named "FieldControl" and place the appropriate values in columns..See the GetFieldControl function.  To test the code I used the following:

You'll need to add the following reference to your macro work book.  In the VBA editor under the Tools menu select References, then when the dialog box appears select Microsoft Scripting Runtime. (Tools->References)

And with all things code related, there are improvements that could be made to this.

Good Luck with your efforts

The Class (Insert->Class) change the default name to clField (you can call it whatever you like but make sure to update the dim statement GetFieldControl function to match the name you gave it.)

```<code>Option Explicit

Public Enum eFieldType
    Number
    Text
End Enum

Public Name As String
Public Size As Long
Public StartPos As Long
Public Value As String
Public FieldType As eFieldType
</code>```

The module with a few updates

```<code>Option Explicit
Option Base 1    'This makes any defined array start a 1 rather than 0

Sub Export_Selection_As_Fixed_Length_File()
     ' Dimension all  variables.
    Dim DestinationFile, CellValue, Filler_Char_To_Replace_Blanks As String
    Dim FileNum, ColumnCount, RowCount, FieldWidth As Integer
    Dim sht As Worksheet

    Dim outputRecord() As String
    'Below are options in case you want to change the folder where VBA stores the .txt file
    'We use ActiveWorkbook.Path in this example
    'ActiveWorkbook.Path 'the activeworkbook
    'ThisWorkbook.Path  'the workbook with the code
    'CurDir  'the current directory (when you hit File|open)

    'If a cell is blank, what character should be used instead
    Filler_Char_To_Replace_Blanks = "+"

    'Check if the user has made any selection at all
    If Selection.Cells.Count < 2 Then
        MsgBox "Nothing selected to export"
        Selection.Activate
        End
    End If

    'This is the destination file name.
    DestinationFile = ActiveWorkbook.Path & "\textfile.txt"  'This was changed to the DOS version of directory separator

    On Error GoTo catchFileOpenError    'Poor man's version of Try/Catch

    'Get a FileSystemObject using the MSFT Scripting Runtime reference
    Dim fd As Scripting.FileSystemObject
    Set fd = New Scripting.FileSystemObject

    Dim outputFile As Object
    Set outputFile = fd.CreateTextFile(DestinationFile, True, False)

    ' Turn error checking on.
    On Error GoTo 0

    Dim record As Scripting.Dictionary
    'Call a private function that gets the filed control information from the
    'Sheet titled FieldControl and the associated range
    Set record = GetFieldControl(ActiveWorkbook.Sheets("FieldControl").Range("A2:D7"))

    'Declare enumerators to loop through the selection
    Dim dataRow As Range
    Dim dataFld As Range

    'Declare the output buffer, 80 characters
    Dim outputBuffer(80) As Byte
    'loop thru the selection row by row
    For Each dataRow In Selection.Rows
        'Initialize buffer to empty value defined by the second parameter
        Call InitOutputBuffer(outputBuffer, Filler_Char_To_Replace_Blanks)
        'Loop thru each field in the row
        For Each dataFld In dataRow.Columns
            'Copy the input value into the output byte array
            Call CopyStringToByteArray(outputBuffer, StrConv(Trim(CStr(dataFld.Value2)), vbFromUnicode), _
                        record(dataFld.Column).StartPos, record(dataFld.Column).FieldType, record(dataFld.Column).Size)
        Next dataFld
        'Write the record to the text file but first convert ASCII Byte to Unicode String
        'Also this method places CR/LF as part of the output to the file
        outputFile.WriteLine StrConv(outputBuffer, vbUnicode)
    Next dataRow

     ' Close destination file.
    outputFile.Close

    Selection.Activate
    Workbooks.OpenText Filename:=DestinationFile
    Exit Sub

catchFileOpenError:     'Catch the error after trying if openning the file fails
    On Error GoTo 0
    MsgBox "Cannot open filename " & DestinationFile
    Selection.Activate
End Sub
'***********************************************************************************
'*
'* PARAMETERS:
'*  outBuf is the updated buffer
'*  inBuf is the input buffer that needs to be copied to the output buffer (buffer)
'*  startCol is the starting column for the field
'*  fldTy is the field type as defined by the class enumerator eFieldType
'*  fldLen is the length of the field as defined on the control sheet
Private Sub CopyStringToByteArray(ByRef outBuf() As Byte, ByRef inBuf() As Byte, _
                ByVal startCol As Long, ByRef fldTy As eFieldType, ByVal fldLen As Long)
    Dim idx As Long
    If fldTy = Text Then       'Left Justified
        For idx = LBound(inBuf) To UBound(inBuf)
            outBuf(startCol) = inBuf(idx)
            startCol = startCol + 1
        Next idx
    Else                        'Right Justified
        Dim revIdx As Long
        revIdx = startCol + fldLen - 1
        For idx = UBound(inBuf) To LBound(inBuf) Step -1
            outBuf(revIdx) = inBuf(idx)
            revIdx = revIdx - 1
        Next idx
    End If
End Sub
'***************************************************************************
'*  InitOutputBuffer
'*      PARAMETERS:
'*          buffer is the buffer to initialize
'*          initVal is a string containing the value used to initialize the buffer
Private Sub InitOutputBuffer(ByRef buffer() As Byte, ByVal initVal As String)
    Dim byInitVal() As Byte 'Byte array to hold the values from the string conversion
    byInitVal = StrConv(initVal, vbFromUnicode) 'convert the string into an ASCII array
    Dim idx As Long
    For idx = LBound(buffer) To UBound(buffer)
        buffer(idx) = byInitVal(0)
    Next idx

    'buffer(81) = Asc(Chr(13)) 'Carriage Return Character
    'buffer(82) = Asc(Chr(10)) 'Line Feed Character

End Sub

'*******************************************************************************
'*
'*  GetFieldControl
'*      PARAMETERS:
'*          ctrlRng is the range on a worksheet where the field control info is
'*              found
'*      REMARKS:
'*          The range needs to have the following columns: Name, Size, Start Postion
'*          and Type.  Type values can be Text or Number
Private Function GetFieldControl(ByRef ctrlRng As Range) As Scripting.Dictionary
    Dim retVal As Scripting.Dictionary
    Set retVal = New Scripting.Dictionary

    'format of control range is : Name, Size, Start Position, Type
    Dim fldInfoRow As Range
    Dim fld As clField  'A class that holds the control values from the work sheet
    Dim colCnt As Long: colCnt = 1  'Becomes the key for the dictionary
    For Each fldInfoRow In ctrlRng.Rows
        Set fld = New clField
        fld.Name = fldInfoRow.Value2(1, 1)      'Name of field in data table
        fld.Size = fldInfoRow.Value2(1, 2)      'Output Size of field
        fld.StartPos = fldInfoRow.Value2(1, 3)  'Output starting position for this field
        Select Case fldInfoRow.Value2(1, 4)     'Controls how the output value is formated
            Case "Text"                         '  Text left justified, Numbers are right justified
                fld.FieldType = Text
            Case "Number"
                fld.FieldType = Number
            Case Default
                fld.FieldType = Text
        End Select
        retVal.Add Key:=colCnt, Item:=fld   'Add the key and the fld object to the dictionary
        colCnt = colCnt + 1                 'This key value is mapped to the column number in the input data table
    Next fldInfoRow

    'Return the scripting Dictionary
    Set GetFieldControl = retVal
End Function
</code>```

Body:
Let me begin by saying I'm kind of new to working with delimited files. I am trying to emulate how a piece of software lays out a text file using Excel.

Here is the code I'm using to create a text file from the worksheet:

Sub Export_Selection_As_Fixed_Length_File()
     ' Dimension all  variables.
    Dim DestinationFile, CellValue, Filler_Char_To_Replace_Blanks As String
    Dim FileNum, ColumnCount, RowCount, FieldWidth As Integer
    Dim sht As Worksheet

    'Below are options incase you want to change the folder where VBA stores the .txt file
    'We use ActiveWorkbook.Path in this example
    'ActiveWorkbook.Path 'the activeworkbook
    'ThisWorkbook.Path  'the workbook with the code
    'CurDir  'the current directory (when you hit File|open)

    'If a cell is blank, what character should be used instead
    Filler_Char_To_Replace_Blanks = " "

        'Check if the user has made any selection at all
        If Selection.Cells.Count < 2 Then
            MsgBox "Nothing selected to export"
            Selection.Activate
            End
        End If

    'This is the destination file name.
    DestinationFile = ActiveWorkbook.Path & "/textfile.txt"
    'Obtain next free file handle number.
    FileNum = FreeFile()

     ' Turn  error checking off.
    On Error Resume Next

     ' Attempt to open destination file for output.
    Open DestinationFile For Output As #FileNum

     ' If an error occurs report it and end.
    If Err <> 0 Then
         MsgBox "Cannot open filename " & DestinationFile
         Selection.Activate
        End
    End If

     ' Turn error checking on.
    On Error GoTo 0

     '  Loop for each row in selection.
    For RowCount = 1 To Selection.Rows.Count
                For ColumnCount = 1 To Selection.Columns.Count
                    CellValue = Selection.Cells(RowCount, ColumnCount).Text
                    If (IsNull(CellValue) Or CellValue = "") Then CellValue = Filler_Char_To_Replace_Blanks
                    FieldWidth = Cells(1, ColumnCount).Value
                    If (ColumnCount = Selection.Columns.Count) Then
                            Print #FileNum, Format$(CellValue, "!" & String(FieldWidth, "@")) & vbCrLf;
                    Else: Print #FileNum, Format$(CellValue, "!" & String(FieldWidth, "@"));
                    End If
                Next ColumnCount
         ' Start next iteration of RowCount loop.
    Next RowCount
     ' Close destination file.
    Close #FileNum
    Selection.Activate
    Workbooks.OpenText Filename:=DestinationFile
End Sub

The software I'm trying to emulate has "data locations" and "field sizes." For example, one field has a data location of 77, which means it will start as the 77th character on the line in the text file. (I don't know how common this is, so if it's very common, please excuse the useless information.) And the field size is 12.

If that doesn't make sense, here's a screenshot of a text file. The first line shows what my VBA creates, and the second line is how I want it to look. How can I force the values on the worksheet to start at a certain position on the line based on the column it's in?

Body:
It looks like your first row in the selection contains the field's width FieldWidth = Cells(1, ColumnCount).Value. In your problem description you mentioned data locations and field sizes.  You need to have this information some where.  You could put it on another sheet in the file, which would let you adjust the output of text file, or you could put those values in your VBA code as constants, or your could create a Class.  Using something like this will enable you can redefine the fields as needed.  The example below uses a simple class and a few private functions in the module

In the example below you'll need to add a sheet named "FieldControl" and place the appropriate values in columns..See the GetFieldControl function.  To test the code I used the following:

You'll need to add the following reference to your macro work book.  In the VBA editor under the Tools menu select References, then when the dialog box appears select Microsoft Scripting Runtime. (Tools->References)

And with all things code related, there are improvements that could be made to this.

Good Luck with your efforts

The Class (Insert->Class) change the default name to clField (you can call it whatever you like but make sure to update the dim statement GetFieldControl function to match the name you gave it.)

Option Explicit

Public Enum eFieldType
    Number
    Text
End Enum

Public Name As String
Public Size As Long
Public StartPos As Long
Public Value As String
Public FieldType As eFieldType

The module with a few updates

Option Explicit
Option Base 1    'This makes any defined array start a 1 rather than 0

Sub Export_Selection_As_Fixed_Length_File()
     ' Dimension all  variables.
    Dim DestinationFile, CellValue, Filler_Char_To_Replace_Blanks As String
    Dim FileNum, ColumnCount, RowCount, FieldWidth As Integer
    Dim sht As Worksheet

    Dim outputRecord() As String
    'Below are options in case you want to change the folder where VBA stores the .txt file
    'We use ActiveWorkbook.Path in this example
    'ActiveWorkbook.Path 'the activeworkbook
    'ThisWorkbook.Path  'the workbook with the code
    'CurDir  'the current directory (when you hit File|open)

    'If a cell is blank, what character should be used instead
    Filler_Char_To_Replace_Blanks = "+"

    'Check if the user has made any selection at all
    If Selection.Cells.Count < 2 Then
        MsgBox "Nothing selected to export"
        Selection.Activate
        End
    End If

    'This is the destination file name.
    DestinationFile = ActiveWorkbook.Path & "\textfile.txt"  'This was changed to the DOS version of directory separator

    On Error GoTo catchFileOpenError    'Poor man's version of Try/Catch

    'Get a FileSystemObject using the MSFT Scripting Runtime reference
    Dim fd As Scripting.FileSystemObject
    Set fd = New Scripting.FileSystemObject

    Dim outputFile As Object
    Set outputFile = fd.CreateTextFile(DestinationFile, True, False)

    ' Turn error checking on.
    On Error GoTo 0

    Dim record As Scripting.Dictionary
    'Call a private function that gets the filed control information from the
    'Sheet titled FieldControl and the associated range
    Set record = GetFieldControl(ActiveWorkbook.Sheets("FieldControl").Range("A2:D7"))

    'Declare enumerators to loop through the selection
    Dim dataRow As Range
    Dim dataFld As Range

    'Declare the output buffer, 80 characters
    Dim outputBuffer(80) As Byte
    'loop thru the selection row by row
    For Each dataRow In Selection.Rows
        'Initialize buffer to empty value defined by the second parameter
        Call InitOutputBuffer(outputBuffer, Filler_Char_To_Replace_Blanks)
        'Loop thru each field in the row
        For Each dataFld In dataRow.Columns
            'Copy the input value into the output byte array
            Call CopyStringToByteArray(outputBuffer, StrConv(Trim(CStr(dataFld.Value2)), vbFromUnicode), _
                        record(dataFld.Column).StartPos, record(dataFld.Column).FieldType, record(dataFld.Column).Size)
        Next dataFld
        'Write the record to the text file but first convert ASCII Byte to Unicode String
        'Also this method places CR/LF as part of the output to the file
        outputFile.WriteLine StrConv(outputBuffer, vbUnicode)
    Next dataRow

     ' Close destination file.
    outputFile.Close

    Selection.Activate
    Workbooks.OpenText Filename:=DestinationFile
    Exit Sub

catchFileOpenError:     'Catch the error after trying if openning the file fails
    On Error GoTo 0
    MsgBox "Cannot open filename " & DestinationFile
    Selection.Activate
End Sub
'***********************************************************************************
'*
'* PARAMETERS:
'*  outBuf is the updated buffer
'*  inBuf is the input buffer that needs to be copied to the output buffer (buffer)
'*  startCol is the starting column for the field
'*  fldTy is the field type as defined by the class enumerator eFieldType
'*  fldLen is the length of the field as defined on the control sheet
Private Sub CopyStringToByteArray(ByRef outBuf() As Byte, ByRef inBuf() As Byte, _
                ByVal startCol As Long, ByRef fldTy As eFieldType, ByVal fldLen As Long)
    Dim idx As Long
    If fldTy = Text Then       'Left Justified
        For idx = LBound(inBuf) To UBound(inBuf)
            outBuf(startCol) = inBuf(idx)
            startCol = startCol + 1
        Next idx
    Else                        'Right Justified
        Dim revIdx As Long
        revIdx = startCol + fldLen - 1
        For idx = UBound(inBuf) To LBound(inBuf) Step -1
            outBuf(revIdx) = inBuf(idx)
            revIdx = revIdx - 1
        Next idx
    End If
End Sub
'***************************************************************************
'*  InitOutputBuffer
'*      PARAMETERS:
'*          buffer is the buffer to initialize
'*          initVal is a string containing the value used to initialize the buffer
Private Sub InitOutputBuffer(ByRef buffer() As Byte, ByVal initVal As String)
    Dim byInitVal() As Byte 'Byte array to hold the values from the string conversion
    byInitVal = StrConv(initVal, vbFromUnicode) 'convert the string into an ASCII array
    Dim idx As Long
    For idx = LBound(buffer) To UBound(buffer)
        buffer(idx) = byInitVal(0)
    Next idx

    'buffer(81) = Asc(Chr(13)) 'Carriage Return Character
    'buffer(82) = Asc(Chr(10)) 'Line Feed Character

End Sub

'*******************************************************************************
'*
'*  GetFieldControl
'*      PARAMETERS:
'*          ctrlRng is the range on a worksheet where the field control info is
'*              found
'*      REMARKS:
'*          The range needs to have the following columns: Name, Size, Start Postion
'*          and Type.  Type values can be Text or Number
Private Function GetFieldControl(ByRef ctrlRng As Range) As Scripting.Dictionary
    Dim retVal As Scripting.Dictionary
    Set retVal = New Scripting.Dictionary

    'format of control range is : Name, Size, Start Position, Type
    Dim fldInfoRow As Range
    Dim fld As clField  'A class that holds the control values from the work sheet
    Dim colCnt As Long: colCnt = 1  'Becomes the key for the dictionary
    For Each fldInfoRow In ctrlRng.Rows
        Set fld = New clField
        fld.Name = fldInfoRow.Value2(1, 1)      'Name of field in data table
        fld.Size = fldInfoRow.Value2(1, 2)      'Output Size of field
        fld.StartPos = fldInfoRow.Value2(1, 3)  'Output starting position for this field
        Select Case fldInfoRow.Value2(1, 4)     'Controls how the output value is formated
            Case "Text"                         '  Text left justified, Numbers are right justified
                fld.FieldType = Text
            Case "Number"
                fld.FieldType = Number
            Case Default
                fld.FieldType = Text
        End Select
        retVal.Add Key:=colCnt, Item:=fld   'Add the key and the fld object to the dictionary
        colCnt = colCnt + 1                 'This key value is mapped to the column number in the input data table
    Next fldInfoRow

    'Return the scripting Dictionary
    Set GetFieldControl = retVal
End Function


来源: stackexchange

问:
When building apk in Android Studio, APK size increased by big margin i.e. from 3 mb to 20mb

APK size increased after building, apk size increased from 3 mb to 20mb.
its due to lib as seen in circle.
How to remove these lib files??

https://i.stack.imgur.com/6ZCp5.png

```<code>apply plugin: 'com.android.application'

    android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "csdevbin.dua"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 6
        versionName "4.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            debuggable false
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            debuggable true
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
</code>```

My dependencies

```<code>implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'
implementation 'com.google.android.gms:play-services-ads:11.0.2'
implementation 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
testCompile 'junit:junit:4.12'
implementation 'com.google.firebase:firebase-core:11.0.2'
implementation 'com.startapp:inapp-sdk:3.6.7'
implementation 'com.github.barteksc:android-pdf-viewer:2.8.1'
implementation 'com.android.support:cardview-v7:27.0.2'
</code>```

答:
i have used { com.github.barteksc:android-pdf-viewer:2.8.1' }

That library uses native code to render PDFs. The library's documentation has a FAQ with a question specifically about your concern.

ContentLicense: CC BY-SA 4.0

Body:
APK size increased after building, apk size increased from 3 mb to 20mb.
its due to lib as seen in circle.
How to remove these lib files??

https://i.stack.imgur.com/6ZCp5.png

apply plugin: 'com.android.application'

    android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "csdevbin.dua"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 6
        versionName "4.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            debuggable false
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            debuggable true
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

My dependencies

implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'
implementation 'com.google.android.gms:play-services-ads:11.0.2'
implementation 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
testCompile 'junit:junit:4.12'
implementation 'com.google.firebase:firebase-core:11.0.2'
implementation 'com.startapp:inapp-sdk:3.6.7'
implementation 'com.github.barteksc:android-pdf-viewer:2.8.1'
implementation 'com.android.support:cardview-v7:27.0.2'

ContentLicense: CC BY-SA 3.0


问:
Speed up recursive method by converting into iterative
I'm writing a dynamic programming algorithm in Python which seems to be working perfectly for smaller inputs but it times out for large inputs probably because of the recursive calls. I read this article online which says that most modern programming languages don't deal with recursion well and it's a better idea to convert them into an iterative method.

My algorithm is as follows:

```<code>def get_val(x,y,g,i,xlast,ylast):
    # checks if array over
    if(i>(len(x)-1)):
        return 0
    # else returns the max of the two values
    # dist returns the euclidian distance between the two points
    # the max condition just decides if it's profitable to move to the
    # next x and y coordinate or if it would be better to skip this particular (x, y)
    return max(g[i]-dist(x[i],y[i],xlast,ylast) + get_val(x,y,g,i+1,x[i],y[i]),get_val(x,y,g,i+1,xlast,ylast))
</code>```

I have been trying to improve its performance but I'm not really sure about the steps I should take to ensure that it doesn't time out on large inputs.

答:
If i figured out what you arr trying to accomplish, you could use a generator to go to the next step. See these generator tricks:

http://linuxgazette.net/100/pramode.html

Or visit

https://wiki.python.org/moin/Generators

Body:
I'm writing a dynamic programming algorithm in Python which seems to be working perfectly for smaller inputs but it times out for large inputs probably because of the recursive calls. I read this article online which says that most modern programming languages don't deal with recursion well and it's a better idea to convert them into an iterative method.

My algorithm is as follows:

def get_val(x,y,g,i,xlast,ylast):
    # checks if array over
    if(i>(len(x)-1)):
        return 0
    # else returns the max of the two values
    # dist returns the euclidian distance between the two points
    # the max condition just decides if it's profitable to move to the
    # next x and y coordinate or if it would be better to skip this particular (x, y)
    return max(g[i]-dist(x[i],y[i],xlast,ylast) + get_val(x,y,g,i+1,x[i],y[i]),get_val(x,y,g,i+1,xlast,ylast))

I have been trying to improve its performance but I'm not really sure about the steps I should take to ensure that it doesn't time out on large inputs.


问:
Xcode 9 - iOS 11 Device Log Private
I am having problems installing an app I have written via an MDM.

The only error shown on screen is:
"Unable to download app"

Connecting my device to my Mac and looking at the Device Log while installing gives me the following lines:

```<code>Nov 30 15:08:29 Thomass-iPhone appstored[152] <Error>: !B18:com.MyCompany.MyApp,J:-7184901782002726309,I:5931121481553874548#[<private>]: Failed to install application at path: <private> error: <private>
Nov 30 15:08:29 Thomass-iPhone appstored[152] <Notice>: !B18:com.MyCompany.MyApp,J:-7184901782002726309,I:5931121481553874548#[<private>]: Install failed after error: <private>
</code>```

Is it possible to change the log so that instead of displaying "private", it will display the actual error?

How can I find out why my app won't install?

答: Build the IPA file with distribution provision profile, and generate a downloadable link from diawi.com . Try downloading from the link. If it works fine then there might be issue with MDM configuration. If not then check the distribution provision profile.</p>

Title: Xcode 9 - iOS 11 Device Log Private

Body:
I am having problems installing an app I have written via an MDM.

The only error shown on screen is:
"Unable to download app"

Connecting my device to my Mac and looking at the Device Log while installing gives me the following lines:

Nov 30 15:08:29 Thomass-iPhone appstored[152] <Error>: !B18:com.MyCompany.MyApp,J:-7184901782002726309,I:5931121481553874548#[<private>]: Failed to install application at path: <private> error: <private>
Nov 30 15:08:29 Thomass-iPhone appstored[152] <Notice>: !B18:com.MyCompany.MyApp,J:-7184901782002726309,I:5931121481553874548#[<private>]: Install failed after error: <private>

Is it possible to change the log so that instead of displaying "private", it will display the actual error?

How can I find out why my app won't install?


问:
Is memmem available on mac?
Can I safely use memmem() if I want it to also run on Mac?

I know it requires:

```<code>#define _GNU_SOURCE
#include <string.h>
</code>```

答:
Yes,  memmem is available on MacOS.  See the man page for details.

You don't however need to #define _GNU_SOURCE.  That is specific to Linux.

Title: Is memmem available on mac?

Body:
Can I safely use memmem() if I want it to also run on Mac?

I know it requires:

#define _GNU_SOURCE
#include <string.h>


问:
How to use a variable inside IN operator
I'm trying to write an application in C# that will pass a variable that contains multiple value separated by a comma, to a stored procedure

```<code>string state = "AZ, CA, VA"
</code>```

I want my stored procedure to return all data for each state in the variable

```<code>CREATE PROCEDURE usp_GetStateInfo
@state varchar(2)

SELECT * FROM StateTable WHERE state IN (@state)
</code>```

But when I do the code above I get an error saying 'Incorrect syntax'
What am I doing wrong and how can I fix this?

Thank you

答:
You cannot use multiple inputs as parameter for IN statement. You will have to split those comma separated values in SQL to create a table variable and join with that table variable.

You can create a function for splitting input string :-

```<code>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[udf_PutStringtoTableUnique]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[udf_PutStringtoTableUnique]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE function [dbo].[udf_PutStringtoTableUnique]
(
      @inputStr as varchar(max),
      @delim nchar(1) = N','
)
returns @tbl table(ID int primary key)
as
BEGIN

if @inputStr = '' or @inputStr is null
return

declare @tags nchar(2)
set @tags = @delim + @delim;

with tbl_for_csv as
(
select left(@inputStr + @tags,charindex(@delim,@inputStr + @tags) -1)as Col,
right(@inputStr + @tags,len(@inputStr + @tags) - charindex(@delim,@inputStr + @tags)) as Str
union all
select left(Str,charindex(@delim,Str) - 1)as Col,
right(Str,len(Str) - charindex(@delim,Str)) from tbl_for_csv
where len(right(Str,len(Str) - charindex(@delim,Str))) > 0
)
insert into @tbl
select distinct Col from tbl_for_csv
option (maxrecursion 0)

return
END

GO

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
</code>```

And Then write something like this in procedure :-

```<code>DECLARE @TempStates Table (StateName Varchar(2))

INSERT INTO @TempStates
Select id from [dbo].[udf_PutStringtoTableUnique](@state, ',')

    SELECT * FROM StateTable
    INNER JOIN @TempStates temp ON state = temp.StateName
</code>```

Body:
I'm trying to write an application in C# that will pass a variable that contains multiple value separated by a comma, to a stored procedure

string state = "AZ, CA, VA"

I want my stored procedure to return all data for each state in the variable

CREATE PROCEDURE usp_GetStateInfo
@state varchar(2)

SELECT * FROM StateTable WHERE state IN (@state)

But when I do the code above I get an error saying 'Incorrect syntax'
What am I doing wrong and how can I fix this?

Thank you

Body:
You cannot use multiple inputs as parameter for IN statement. You will have to split those comma separated values in SQL to create a table variable and join with that table variable.

You can create a function for splitting input string :-

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[udf_PutStringtoTableUnique]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[udf_PutStringtoTableUnique]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE function [dbo].[udf_PutStringtoTableUnique]
(
      @inputStr as varchar(max),
      @delim nchar(1) = N','
)
returns @tbl table(ID int primary key)
as
BEGIN

if @inputStr = '' or @inputStr is null
return

declare @tags nchar(2)
set @tags = @delim + @delim;

with tbl_for_csv as
(
select left(@inputStr + @tags,charindex(@delim,@inputStr + @tags) -1)as Col,
right(@inputStr + @tags,len(@inputStr + @tags) - charindex(@delim,@inputStr + @tags)) as Str
union all
select left(Str,charindex(@delim,Str) - 1)as Col,
right(Str,len(Str) - charindex(@delim,Str)) from tbl_for_csv
where len(right(Str,len(Str) - charindex(@delim,Str))) > 0
)
insert into @tbl
select distinct Col from tbl_for_csv
option (maxrecursion 0)

return
END

GO

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

And Then write something like this in procedure :-

DECLARE @TempStates Table (StateName Varchar(2))

INSERT INTO @TempStates
Select id from [dbo].[udf_PutStringtoTableUnique](@state, ',')

    SELECT * FROM StateTable
    INNER JOIN @TempStates temp ON state = temp.StateName


问:
Using Struts2 Tags in Enterprise Application
I have created an enterprise application with an EJB module. But I haven't created a Web war yet.

Then I created a Struts2 web, and add it into the enterprise application.

It's ok. If I use the HTML Tag, but when I use Struts2 tag it throw an exception:

Here:

"HTTP Status 500 - Internal Server Error

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException:

The Struts dispatcher cannot be found.

This is usually caused by using Struts tags without the associated filter.

Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. - [unknown location]
root cause

The Struts dispatcher cannot be found.  This is usually caused by using Struts tags without the associated filter.

Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag.

[unknown location]
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.0 logs.HTTP Status 500 - Internal Server Error

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException:

The Struts dispatcher cannot be found.

This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. - [unknown location]
root cause

The Struts dispatcher cannot be found.  This is usually caused by using Struts tags without the associated filter.

Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag.

[unknown location]
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.0 logs."

答:
I had the same issue and this is how I solved it :

1 - Make sure your welcome file in the web.xml isn't the one that has the struts tags.

So create a page index.jsp, add it to web.xml as follow :

```<code>  <welcome-file-list>
     <welcome-file>/vues/index.jsp</welcome-file>
  </welcome-file-list>
</code>```

And the index.jsp should only have a code to redirect the user to your actual index page that has the struts tags.

```<code><%
     response.sendRedirect(response.encodeRedirectURL(request.getContextPath()) + "/index.action");
%>
</code>```

index.action is an action without a class, its result is to direct you to you actual index page, so in struts.xml you'll have the following :

```<code>    <action name="index">
        <result>jspPages/index-logged-out.jsp</result>
    </action>
</code>```

Body:
I had the same issue and this is how I solved it :

1 - Make sure your welcome file in the web.xml isn't the one that has the struts tags.

So create a page index.jsp, add it to web.xml as follow :

  <welcome-file-list>
     <welcome-file>/vues/index.jsp</welcome-file>
  </welcome-file-list>

And the index.jsp should only have a code to redirect the user to your actual index page that has the struts tags.

<%
     response.sendRedirect(response.encodeRedirectURL(request.getContextPath()) + "/index.action");
%>

index.action is an action without a class, its result is to direct you to you actual index page, so in struts.xml you'll have the following :

    <action name="index">
        <result>jspPages/index-logged-out.jsp</result>
    </action>


问:
How do I use getch from curses without clearing the screen?
I'm learning to program in C and want to be able to type characters into the terminal while my code is running without pressing return. My program works, however when I call initscr(), the screen is cleared - even after calling filter(). The documentation for filter suggests it should disable clearing - however this is not the case for me.

```<code>#include <stdio.h>
#include <curses.h>
#include <term.h>

int main(void) {

    int ch;

    filter();
    initscr();
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    while((ch = getch()) != EOF);

    endwin();

    return 0;
}
</code>```

Why does the above code still clearr the screen, and what could be done to fix it?

I'm using Debian Lenny (stable) and gnome-terminal if that helps.

答: Use newterm() instead of initscr(), you should be fine then. And don't forget about delscreen() if you follow this advice.

Body:
I'm learning to program in C and want to be able to type characters into the terminal while my code is running without pressing return. My program works, however when I call initscr(), the screen is cleared - even after calling filter(). The documentation for filter suggests it should disable clearing - however this is not the case for me.

#include <stdio.h>
#include <curses.h>
#include <term.h>

int main(void) {

    int ch;

    filter();
    initscr();
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    while((ch = getch()) != EOF);

    endwin();

    return 0;
}

Why does the above code still clearr the screen, and what could be done to fix it?

I'm using Debian Lenny (stable) and gnome-terminal if that helps.

ContentLicense: CC BY-SA 2.5


问:
SWI Prolog - Recursion with lists
I am new to ProLog and I am having some troubles understanding recursion over lists.

I am stuck on this exercise. Basically given the vocabulary I need to convert a list of Italian numbers to English numbers.

This is my KB.

```<code>tran(uno, one).
tran(due, two).
tran(tre, three).
tran(quattro, four).
tran(cinque, five).
tran(sei, six).
tran(sette, seven).
tran(otto, eight).
tran(nove, nine).

listran(L,[]).
listran(L,[H|T]) :- tran(H,E), listran([E|L],T).
</code>```

This program should give the translated list (in reverse order). However, it only outputs true when I pass:

```<code>?- listran(X, [uno, due, tre]).
</code>```

I've tried to trace it and seems that at the end removes?? all elements from my translated list. This is the trace output.

```<code>[trace]  ?- listran(X,[uno,due,tre]).
   Call: (8) listran(_5566, [uno, due, tre]) ? creep
   Call: (9) tran(uno, _5820) ? creep
   Exit: (9) tran(uno, one) ? creep
   Call: (9) listran([one|_5566], [due, tre]) ? creep
   Call: (10) tran(due, _5826) ? creep
   Exit: (10) tran(due, two) ? creep
   Call: (10) listran([two, one|_5566], [tre]) ? creep
   Call: (11) tran(tre, _5832) ? creep
   Exit: (11) tran(tre, three) ? creep
   Call: (11) listran([three, two, one|_5566], []) ? creep
   Exit: (11) listran([three, two, one|_5566], []) ? creep
   Exit: (10) listran([two, one|_5566], [tre]) ? creep
   Exit: (9) listran([one|_5566], [due, tre]) ? creep
   Exit: (8) listran(_5566, [uno, due, tre]) ? creep
true.
</code>```

Can someone help me understanding this little problem?

Thank you in advance.

答:
The problem is in both clauses:

```<code>listran(L,[]).
listran(L,[H|T]) :- tran(H,E), listran([E|L],T).
</code>```

here you state that: translate H and place it to head of L and continue, this holds for every L, you need explicitly state that the current head of L is E not add E:

```<code>listran([],[]).
listran([E|T1],[H|T]) :- tran(H,E), listran(T1,T).
</code>```

Here you say the head of first list is E and continue with rest until base case where both lists are empty.

Title: SWI Prolog - Recursion with lists

Body:
I am new to ProLog and I am having some troubles understanding recursion over lists.

I am stuck on this exercise. Basically given the vocabulary I need to convert a list of Italian numbers to English numbers.

This is my KB.

tran(uno, one).
tran(due, two).
tran(tre, three).
tran(quattro, four).
tran(cinque, five).
tran(sei, six).
tran(sette, seven).
tran(otto, eight).
tran(nove, nine).

listran(L,[]).
listran(L,[H|T]) :- tran(H,E), listran([E|L],T).

This program should give the translated list (in reverse order). However, it only outputs true when I pass:

?- listran(X, [uno, due, tre]).

I've tried to trace it and seems that at the end removes?? all elements from my translated list. This is the trace output.

[trace]  ?- listran(X,[uno,due,tre]).
   Call: (8) listran(_5566, [uno, due, tre]) ? creep
   Call: (9) tran(uno, _5820) ? creep
   Exit: (9) tran(uno, one) ? creep
   Call: (9) listran([one|_5566], [due, tre]) ? creep
   Call: (10) tran(due, _5826) ? creep
   Exit: (10) tran(due, two) ? creep
   Call: (10) listran([two, one|_5566], [tre]) ? creep
   Call: (11) tran(tre, _5832) ? creep
   Exit: (11) tran(tre, three) ? creep
   Call: (11) listran([three, two, one|_5566], []) ? creep
   Exit: (11) listran([three, two, one|_5566], []) ? creep
   Exit: (10) listran([two, one|_5566], [tre]) ? creep
   Exit: (9) listran([one|_5566], [due, tre]) ? creep
   Exit: (8) listran(_5566, [uno, due, tre]) ? creep
true.

Can someone help me understanding this little problem?

Thank you in advance.

Body:
The problem is in both clauses:

listran(L,[]).
listran(L,[H|T]) :- tran(H,E), listran([E|L],T).

here you state that: translate H and place it to head of L and continue, this holds for every L, you need explicitly state that the current head of L is E not add E:

listran([],[]).
listran([E|T1],[H|T]) :- tran(H,E), listran(T1,T).

Here you say the head of first list is E and continue with rest until base case where both lists are empty.


问:
CSS Positioning on keyDown
I'm making an airplane game. To shoot missiles I'm using JavaScript functions that create divs with the class of missile and use the position of my airplane to position the missile.

The problem is with my top positioning.

Here is my keyDown function...

```<code>    document.onkeydown = function(e) {
        (e.keyCode === 37) ? player.left-= 10
        : (e.keyCode === 38) ? player.top-= 10
        : (e.keyCode === 39) ? player.left += 10
        : (e.keyCode === 40) ? player.top += 10
        : (e.keyCode === 32) ? missiles.push({top: player.top - 8, left: player.left + 34})
        : player = player;
        drawMissiles();

        (player.top <= 400) ? player.top = 400
        : player = player;

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

This adds an object to an empty missiles array with the properties of "top" and "left."

I'm then using a JavaScript function to add that div to my HTML with the top and bottom properties being used as my CSS style, like so..

```<code>function drawMissiles() {
            let content = "";
            missiles.map(function(missile) {
                content+= "<div class='missile' style='left:"+missile.left+"px;, top:"+missile.top+"px;'></div>"
                    document.getElementById("missiles").innerHTML = content;
                })
            }
        drawMissiles();
</code>```

My "left" property is working, but my "top" is not. My missiles are ending up at the top of my page.

答: Looks like a typo. You have a comma after the first semicolon in your style tag.</p>

Title: CSS Positioning on keyDown

Body:
I'm making an airplane game. To shoot missiles I'm using JavaScript functions that create divs with the class of missile and use the position of my airplane to position the missile.

The problem is with my top positioning.

Here is my keyDown function...

    document.onkeydown = function(e) {
        (e.keyCode === 37) ? player.left-= 10
        : (e.keyCode === 38) ? player.top-= 10
        : (e.keyCode === 39) ? player.left += 10
        : (e.keyCode === 40) ? player.top += 10
        : (e.keyCode === 32) ? missiles.push({top: player.top - 8, left: player.left + 34})
        : player = player;
        drawMissiles();

        (player.top <= 400) ? player.top = 400
        : player = player;

        drawPlayer();
}

This adds an object to an empty missiles array with the properties of "top" and "left."

I'm then using a JavaScript function to add that div to my HTML with the top and bottom properties being used as my CSS style, like so..

function drawMissiles() {
            let content = "";
            missiles.map(function(missile) {
                content+= "

"
                    document.getElementById("missiles").innerHTML = content;
                })
            }
        drawMissiles();

My "left" property is working, but my "top" is not. My missiles are ending up at the top of my page.


问:
Get key name from the property of javascript object
How can I get the key name "email" inside the function ? Is there a special context variable to do this ?

Thanks for help.

var user = {
  "email": function() {
    // How can I get the name of the key (email) inside the function ?
  }
}```

答:
I will answer this by asking a question. Consider this scenario:

```<code>let myFunc = function(){ /* somehow returns the name */ };

let a = {
    funcA: myFunc
};

let b = {
    funcB: myFunc
};
</code>```

Now, consider this:

```<code>a.funcA();
b.funcB();
</code>```

What should they return? myFunc, funcA, or funcB? The answer is "it doesn't make sense".

This is why what you are trying to do is impossible. The function can be "owned" by different objects.

Body:
I will answer this by asking a question. Consider this scenario:

let myFunc = function(){ /* somehow returns the name */ };

let a = {
    funcA: myFunc
};

let b = {
    funcB: myFunc
};

Now, consider this:

a.funcA();
b.funcB();

What should they return? myFunc, funcA, or funcB? The answer is "it doesn't make sense".

This is why what you are trying to do is impossible. The function can be "owned" by different objects.


问:
VBA: need to default control value if only 1 possible result or show list if more than possible result
I'm trying to write a bit of code, in VBA, that would restrict the possible values in a select list if certain criteria are met or, if only one possible value, default the value in the control to that one possible value or return a null list if no possible values.

To be more specific, in a form, I have an EventDate and ProtocolID. The protocols have a BeginImplementationDate and EndImplmentationDate. If the EventDate falls between the BeginImplementationDate and EndImplementationDate (which can be null, if the protocol is still active) of more than 1 protocol, I need to show all the ProtocolIDs for those protocols in the drop-down list. If only 1 protocol meets that criteria, the field needs to default to the ProtocolID that qualifies. If zero protocols meet the criteria, the drop-down list will be empty.

答:
The following is what I did to resolve the problem. </p>

```<code>Private Sub txtEventDate_AfterUpdate()
    Dim intProtocolCount As Integer
    Dim intProtocolID As Integer

    intProtocolCount = DCount("ID", "lu_Protocol", "BeginImplementationDate<=#" & Me.EventDate & "# and Nz([EndImplementationDate],Date())>=#" & Me.EventDate & "#")

    If intProtocolCount = 1 Then
        intProtocolID = DLookup("ID", "lu_Protocol", "BeginImplementationDate<=#" & Me.EventDate & "# and Nz([EndImplementationDate],Date())>=#" & Me.EventDate & "#")
        Me.cmbProtocol = intProtocolID
        Me.cmbProtocol.Requery
    ElseIf intProtocolCount = 0 Then
        MsgBox ("No Protocol is active for this Event Date. If Event Date is correct, please contact the Data Manager to update the Protocol list in the database.")
        Me.cmbProtocol.Requery
    Else
        Me.cmbProtocol.Requery
    End If
End Sub
</code>```

Body:
The following is what I did to resolve the problem.

Private Sub txtEventDate_AfterUpdate()
    Dim intProtocolCount As Integer
    Dim intProtocolID As Integer

    intProtocolCount = DCount("ID", "lu_Protocol", "BeginImplementationDate<=#" & Me.EventDate & "# and Nz([EndImplementationDate],Date())>=#" & Me.EventDate & "#")

    If intProtocolCount = 1 Then
        intProtocolID = DLookup("ID", "lu_Protocol", "BeginImplementationDate<=#" & Me.EventDate & "# and Nz([EndImplementationDate],Date())>=#" & Me.EventDate & "#")
        Me.cmbProtocol = intProtocolID
        Me.cmbProtocol.Requery
    ElseIf intProtocolCount = 0 Then
        MsgBox ("No Protocol is active for this Event Date. If Event Date is correct, please contact the Data Manager to update the Protocol list in the database.")
        Me.cmbProtocol.Requery
    Else
        Me.cmbProtocol.Requery
    End If
End Sub


问:
Replacing keyword argument in pytest
I am doing some testing and I would like to mock one argument of a function.

For example I got function like:

```<code>def foo(arg1, arg2):
    'do something'
</code>```

and call of that function:

```<code>foo(1, 2)
</code>```

I would like to monkeypatch it somehow to use 3 instead of 2. Is that possible?

tried something like:

```<code>monkeypatch.setattr('foo', partial(foo, arg2= 3))
</code>```

But I got type error: foo() got multiple values for keyword argument 'arg2'

Any idea how to solve this?

答:
You can simply alias the function:</p>

```<code>old_foo = monkeypatch.foo
def foo(arg1, arg2):
    return old_foo(arg1, 3)

monkeypatch.foo = foo
</code>```

Title: Replacing keyword argument in pytest

Body:
I am doing some testing and I would like to mock one argument of a function.

For example I got function like:

def foo(arg1, arg2):
    'do something'

and call of that function:

foo(1, 2)

I would like to monkeypatch it somehow to use 3 instead of 2. Is that possible?

tried something like:

monkeypatch.setattr('foo', partial(foo, arg2= 3))

But I got type error: foo() got multiple values for keyword argument 'arg2'

Any idea how to solve this?

Body:
You can simply alias the function:

old_foo = monkeypatch.foo
def foo(arg1, arg2):
    return old_foo(arg1, 3)

monkeypatch.foo = foo


问:
Is it possible to know the geographic location where my GitHub commits come from?
I am working on a big project (solo project) and committing to my GitHub repository almost every day. The thing is, I usually travel and my commits come from different cities/countries! Is it possible to know which geographic locations the commits came from? or at least the geographic location where the repo was created? Hope this question makes sense.</p>

答:
No, it is not.

Commits do not track the IP from which the commit happened.  Even if they did, IP-to-geographic translations are fraught with errors.


问:
how to use pdf.js without defining pdf.worker location
I meet a problem when using pdf.js to view pdf. The problem comes from the
PDFJS.workerSrc setting. Is that possible to include the pdf.worker.js in
header, like

```<code><script type="text/javascript" src="./../jsfiles/pdf.worker.js"></script>
</code>```

and not using

```<code>PDFJS.workerSrc = './../jsfiles/pdf.worker.js';
</code>```

is that possible for that? Thanks a lot.

答:
From the documentation:

In order to bundle all src/ files into two production scripts and build the generic viewer, run:

```<code>$ gulp generic
</code>```

This will generate pdf.js and pdf.worker.js in the build/generic/build/ directory. Both scripts are needed but only pdf.js needs to be included since pdf.worker.js will be loaded by pdf.js. The PDF.js files are large and should be minified for production.

This means that you only need to add the following code:

```<code><script type="text/javascript" src="pdf.js"></script>
</code>```

Remember that all files generated should located in the same directory as pdf.js

Body:
I meet a problem when using pdf.js to view pdf. The problem comes from the
PDFJS.workerSrc setting. Is that possible to include the pdf.worker.js in
header, like

and not using

PDFJS.workerSrc = './../jsfiles/pdf.worker.js';

is that possible for that? Thanks a lot.

Body:
From the documentation:

In order to bundle all src/ files into two production scripts and build the generic viewer, run:

$ gulp generic

This will generate pdf.js and pdf.worker.js in the build/generic/build/ directory. Both scripts are needed but only pdf.js needs to be included since pdf.worker.js will be loaded by pdf.js. The PDF.js files are large and should be minified for production.

This means that you only need to add the following code:

<script type="text/javascript" src="pdf.js"></script>

Remember that all files generated should located in the same directory as pdf.js


问:
CloudWatch to delete old backups
I am currently using AWS CloudWatch to create backups of a particular EBS volume every 12 hours and would like to delete old snapshots every so often so I don't end up with a crazy amount of backups. Based on the simpler route I'd like to either replace the existing backup with a new one every time rule triggers OR delete backups older than 2 days. Any idea how to accomplish this?

I tried search Target actions in the CloudWatchAWS console for something like "EC2 DeleteSnapshot API call" or similar with no success.

答: You could create a Lambda function that does this and then invoke that Lambda from a scheduled CloudWatch Event. Beware the maximum execution time of Lamda though. Alternatively you could run an instance and cron a script that does this too. Whichever way you go, you’ll need to script it.</p>

Title: CloudWatch to delete old backups


问:
Regex to match "maybe valid month"
Basically I want to match the following:

```<code>const regex = /(?=.*[0-1])(?=.*[^0{2}])|(0[1-9]|1[012])$/
console.log('0, should be True: ', regex.test('0'))
console.log('1, should be True: ', regex.test('1'))
console.log('00, should be False: ', regex.test('00'))
console.log('01, should be True: ', regex.test('01'))
console.log('12, should be True: ', regex.test('12'))
console.log('99, should be False: ', regex.test('99'))
</code>```

Valid: 0, 1, 01-09, 10-12
Invalid: 00, >12

Anyone know how to do this?

答:
You can do something like this.

```<code>var regex = /^\d?$|^0[1-9]?$|^1(=?[0-2])$/;
</code>```

or:

```<code>var regex = /^\d?$|^0[1-9]?$|^1[0-2]$/;
</code>```

or:

```<code>var regex = /^(\d?|^0[1-9]?|^1[0-2])$/;
</code>```

there are many possible way you can achieve the same results.

Title: Regex to match "maybe valid month"

Body:
Basically I want to match the following:

const regex = /(?=.*[0-1])(?=.*[^0{2}])|(0[1-9]|1[012])$/
console.log('0, should be True: ', regex.test('0'))
console.log('1, should be True: ', regex.test('1'))
console.log('00, should be False: ', regex.test('00'))
console.log('01, should be True: ', regex.test('01'))
console.log('12, should be True: ', regex.test('12'))
console.log('99, should be False: ', regex.test('99'))

Valid: 0, 1, 01-09, 10-12
Invalid: 00, >12

Anyone know how to do this?

Body:
You can do something like this.

var regex = /^\d?$|^0[1-9]?$|^1(=?[0-2])$/;

or:

var regex = /^\d?$|^0[1-9]?$|^1[0-2]$/;

or:

var regex = /^(\d?|^0[1-9]?|^1[0-2])$/;

there are many possible way you can achieve the same results.


问:
exception ToString(): debug versus release mode
regarding th stack trace depth in debug and release mode. I have come to the following conclusion (calling exception.ToString()):

at debug mode you get the complete stack trace with line numbers (several frames) at release mode instead complete stack trace you get only the throwing method in try block (single frame) with line numbers

-is that true ?
-is there any way to get the complete stack tracve on release mode ?

答:
Compiling in debug mode will include Debug statements as well as generate a *.pdb file, which actually "holds debugging and project state information that allows incremental linking of a debug configuration of your program".  The depth of linking is dependent upon the depth of pdb files generated.

http://msdn.microsoft.com/en-us/library/ms241903.aspx


问:
How to redirect *after* dropping a facebook tracking pixel (or similar)
Trying to figure out how to redirect to a new page after dropping a Facebook retargeting pixel.

We already have everything else setup but want to add this functionality (the same as https://meteor.link/)

We currently use window.location.replace('https://thelinkgoeshere.com'); but I think the Facebook is async so we can't just add the pixel code above it.

Thanks for any help you can provide!

答:
You can modify the facebook pixel script you put on the page</p>

```<code>  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');
  fbq('init', '111......1');
  fbq('track', 'PageView');

  //add your redirect here
  window.location.replace('https://thelinkgoeshere.com');
</code>```

Body:
You can modify the facebook pixel script you put on the page

  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');
  fbq('init', '111......1');
  fbq('track', 'PageView');

  //add your redirect here
  window.location.replace('https://thelinkgoeshere.com');


问:
Specifying python files for jupyter notebook on a Spark cluster
I am running a jupyter-notebook on a Spark cluster (with yarn). I am using the "findspark" package to set up the notebook and it works perfectly fine (I connect to the cluster master through a SSH tunnel).
When I write a "self-contained" notebook, it works perfectly, e.g. the following code runs with no problem:

```<code>import findspark
findspark.init()

import pyspark

sc = pyspark.SparkContext(appName='myApp')
a = sc.range(1000,numSlices=10)
a.take(10)
sc.stop()
</code>```

The Spark job is perfectly distributed on the workers. However, when I want to use a python package that I wrote, the files are missing on the workers.

When I am not using Jupyter-notebook and when I use spark-submit --master yarn --py-files myPackageSrcFiles.zip, my Spark job works fine, e.g. the following code runs correctly:

main.py

```<code>import pyspark
from myPackage import myFunc

sc = pyspark.SparkContext(appName='myApp')
a = sc.range(1000,numSlices=10)
b = a.map(lambda x: myFunc(x))
b.take(10)
sc.stop()
</code>```

Then

```<code>spark-submit --master yarn --py-files myPackageSrcFiles.zip main.py
</code>```

The question is: How to run main.py from a jupyter notebook? I tried specifying the .zip package in the SparkContext with the pyfiles keyword but I got an error...

答:
I tried specifying the .zip package in the SparkContext with the pyfiles keyword but I got an error

It is camel case:

```<code>sc = pyspark.SparkContext(appName='myApp', pyFiles=["myPackageSrcFiles.zip"])
</code>```

Or you can addPyFile

```<code>sc.addPyFile("myPackageSrcFiles.zip")
</code>```

Body:
I am running a jupyter-notebook on a Spark cluster (with yarn). I am using the "findspark" package to set up the notebook and it works perfectly fine (I connect to the cluster master through a SSH tunnel).
When I write a "self-contained" notebook, it works perfectly, e.g. the following code runs with no problem:

import findspark
findspark.init()

import pyspark

sc = pyspark.SparkContext(appName='myApp')
a = sc.range(1000,numSlices=10)
a.take(10)
sc.stop()

The Spark job is perfectly distributed on the workers. However, when I want to use a python package that I wrote, the files are missing on the workers.

When I am not using Jupyter-notebook and when I use spark-submit --master yarn --py-files myPackageSrcFiles.zip, my Spark job works fine, e.g. the following code runs correctly:

main.py

import pyspark
from myPackage import myFunc

sc = pyspark.SparkContext(appName='myApp')
a = sc.range(1000,numSlices=10)
b = a.map(lambda x: myFunc(x))
b.take(10)
sc.stop()

Then

spark-submit --master yarn --py-files myPackageSrcFiles.zip main.py

The question is: How to run main.py from a jupyter notebook? I tried specifying the .zip package in the SparkContext with the pyfiles keyword but I got an error...

Body:
I tried specifying the .zip package in the SparkContext with the pyfiles keyword but I got an error

It is camel case:

sc = pyspark.SparkContext(appName='myApp', pyFiles=["myPackageSrcFiles.zip"])

Or you can addPyFile

sc.addPyFile("myPackageSrcFiles.zip")


问:
How to access JS variable of one razor page in other razor page?
How do i access variable "DataToBind" of One.cshtml page in Two.cshtml page?

One.cshtml

```<code><script>
var DataToBind;

    $.ajax({
            url: "/Home/getDetails",
            type: "POST",
            dataType: "json",
            data: JSON.stringify({ agencyID: agencyID, salesID: saleID, DebtorID: debtorID, AccountNo: accountNO }),
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                DataToBind = response[0];

                window.location.href = "Two";
            }, error: function () {

                console.log("new error");
            }
        });
</script>
</code>```

Two.cshtml

I get this error : Uncaught ReferenceError: DataToBind is not defined
when i use "DataToBind" variable in this page.

答:
As I understand you are trying to get some value and use it in another page.
This is a bit unusual scenario, but you best shot is

```<code><script>
var DataToBind;

$.ajax({
        url: "/Home/getDetails",
        type: "POST",
        dataType: "json",
        data: JSON.stringify({ agencyID: agencyID, salesID: saleID, DebtorID: debtorID, AccountNo: accountNO }),
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            c= response[0];

            window.location.href = "Two?data=" + DataToBind;
        }, error: function () {

            console.log("new error");
        }
    });

</script>
</code>```

and in your page Two access this data

```<code><script>
        var DataToBind =  @(Request.QueryString["data"])
        ...
     </script>
</code>```

or another way

```<code><script>
var DataToBind = @HttpContext.Current.Request.QueryString["data"]
...
</script>
</code>```

and then you can use your DataToBind  on Two.cshtml

Body:
How do i access variable "DataToBind" of One.cshtml page in Two.cshtml page?

One.cshtml

Two.cshtml

I get this error : Uncaught ReferenceError: DataToBind is not defined
when i use "DataToBind" variable in this page.

Body:
As I understand you are trying to get some value and use it in another page.
This is a bit unusual scenario, but you best shot is

<script>
var DataToBind;

$.ajax({
        url: "/Home/getDetails",
        type: "POST",
        dataType: "json",
        data: JSON.stringify({ agencyID: agencyID, salesID: saleID, DebtorID: debtorID, AccountNo: accountNO }),
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            c= response[0];

            window.location.href = "Two?data=" + DataToBind;
        }, error: function () {

            console.log("new error");
        }
    });

</script>

and in your page Two access this data

<script>
        var DataToBind =  @(Request.QueryString["data"])
        ...
     </script>

or another way

<script>
var DataToBind = @HttpContext.Current.Request.QueryString["data"]
...
</script>

and then you can use your DataToBind  on Two.cshtml


问:
Conceptual issue with coding Otsu's method - skimage.filters.thresholding.threshold_otsu
Otsu's method performs binary image thresholding and consists of maximising the variance between the two subclasses (foreground/background) created by splitting the image at a given threshold.  Mathematically, this is expressed as:

variance12 = weight1 * (mean1 - meanT)**2 + weight2 * (mean2 - meanT)**2

(meanT is the overal mean of the image histogram).  However, I'm having trouble with understanding how this is implemented in the threshold_otsu function in scikit-image which writes this as:

variance12 = weight1 * weight2 * (mean1 - mean2)**2.

Though the definitions of the weights and means are slightly different in this function, I can't see how these two formulations are the same - even though they give the same answers.  Would someone care to clarify?

Thank you for your help.

答:
You can prove the two formulations are the same by using the definitions of the weights and meanT.

```<code>meanT = weight1*mean1 + weight2*mean2  (1)
weight1 + weight2 = 1                  (2)
</code>```

If you insert (1) into your first formula, you end up with something like this

```<code>[(mean1-mean2)**2]*[weight1*weight2**2] + [(mean1-mean2)**2]*[weight2*weight1**2]
</code>```

If you factor that and use (2), you'll get your result.

The complete proof is below, and the definitions can be checked in Otsu's original paper here.

Hope this helps.

Body:
You can prove the two formulations are the same by using the definitions of the weights and meanT.

meanT = weight1*mean1 + weight2*mean2  (1)
weight1 + weight2 = 1                  (2)

If you insert (1) into your first formula, you end up with something like this

[(mean1-mean2)**2]*[weight1*weight2**2] + [(mean1-mean2)**2]*[weight2*weight1**2]

If you factor that and use (2), you'll get your result.

The complete proof is below, and the definitions can be checked in Otsu's original paper here.

Hope this helps.


问:
IPython startup script: Check if QtConsole
For my IPython QtConsole, I have a startup script in my profile_default/startup folder, which contains the following lines:

```<code>ipy = get_ipython()

try:
    plot
except NameError:  #  not loaded yet
    ipy.run_line_magic("pylab", "inline")
</code>```

This works fine in the QtConsole and Notebook, but if I now run ipython with no subcommand, i.e. in the Windows command line, it prints an error that the 'inline' GUI is invalid.

Is there any way I can check for the subcommand (qtconsole, notebook or "None") inside the startup script, so I can avoid that message?

(IPython QtConsole 3.2.0, WinPython-64bit-3.4.3.4)

答:
I'm going to assume that ipy is the result of get_ipython().

Warning: You should not try to have code that behave differently on various frontend. It will break at some point, and lead to hard to debug issues that don't make sens. Nasal demons will be on a the lookout for the smallest misstep to haunt you.

That being say, in the pure, classical terminal IPython  you can can verify that:

```<code>In [1]: type(get_ipython())
Out[1]: IPython.terminal.interactiveshell.TerminalInteractiveShell
</code>```

Which is not true for Notebook and QtConsole (which are ZMQInteractiveShell). In both case IPython.terminal.interactiveshell.TerminalInteractiveShell should be importable, and you can check with issubclass in which case you are.

Now, you can also create your own aliases on windows (not sure how), that pass extra command line arguments to IPython, in order for notebook and qtconsole to not have the same startup sequence.

Body:
For my IPython QtConsole, I have a startup script in my profile_default/startup folder, which contains the following lines:

ipy = get_ipython()

try:
    plot
except NameError:  #  not loaded yet
    ipy.run_line_magic("pylab", "inline")

This works fine in the QtConsole and Notebook, but if I now run ipython with no subcommand, i.e. in the Windows command line, it prints an error that the 'inline' GUI is invalid.

Is there any way I can check for the subcommand (qtconsole, notebook or "None") inside the startup script, so I can avoid that message?

(IPython QtConsole 3.2.0, WinPython-64bit-3.4.3.4)

Body:
I'm going to assume that ipy is the result of get_ipython().

Warning: You should not try to have code that behave differently on various frontend. It will break at some point, and lead to hard to debug issues that don't make sens. Nasal demons will be on a the lookout for the smallest misstep to haunt you.

That being say, in the pure, classical terminal IPython  you can can verify that:

In [1]: type(get_ipython())
Out[1]: IPython.terminal.interactiveshell.TerminalInteractiveShell

Which is not true for Notebook and QtConsole (which are ZMQInteractiveShell). In both case IPython.terminal.interactiveshell.TerminalInteractiveShell should be importable, and you can check with issubclass in which case you are.

Now, you can also create your own aliases on windows (not sure how), that pass extra command line arguments to IPython, in order for notebook and qtconsole to not have the same startup sequence.


问:
Why my application crash on applicationDidEnterBackground?
I have a static method called writeToServer that is called when application enter in background mode.

in my AppDelegate.m:

```<code>- (void)applicationDidEnterBackground:(UIApplication *) application {
    [LogZone writeToServer];
    NSLog(@"Log sended to server. Done.");
}
</code>```

in my LogZone.m:

```<code>+ (void) writeToServer {
    NSString *qStr = [[NSString alloc]
        initWithFormat:@"%@?ip=%@&uid=%@&platform=%@&model=%@&lat=%@&lon=%@",
            LOG_SERVER_URL,
            _LOG_IP, _LOG_UID, _LOG_PLAT, _LOG_MOD, _LOG_LAT, _LOG_LON];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:qStr]];
    [request setHTTPMethod: @"POST"];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
</code>```

Uppercase vars are static strings created in this way:

.h

```<code>extern NSString* _LOG_UID;
</code>```

.m

```<code>NSString* _LOG_UID = @"-1";
</code>```

When I enter in background mode it crash with this "classic" error:

* -[CFString respondsToSelector:]: message sent to deallocated instance
  0x6a4c800

But why?

I don't release anything!=!

What's wrong?

答:
But why?
  I don't release anything!

Sure, but do you retain the right objects?

Retaining at the right time is every bit as important as not releasing at the wrong time...

Body:
I have a static method called writeToServer that is called when application enter in background mode.

in my AppDelegate.m:

- (void)applicationDidEnterBackground:(UIApplication *) application {
    [LogZone writeToServer];
    NSLog(@"Log sended to server. Done.");
}

in my LogZone.m:

+ (void) writeToServer {
    NSString *qStr = [[NSString alloc]
        initWithFormat:@"%@?ip=%@&uid=%@&platform=%@&model=%@&lat=%@&lon=%@",
            LOG_SERVER_URL,
            _LOG_IP, _LOG_UID, _LOG_PLAT, _LOG_MOD, _LOG_LAT, _LOG_LON];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:qStr]];
    [request setHTTPMethod: @"POST"];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

Uppercase vars are static strings created in this way:

.h

extern NSString* _LOG_UID;

.m

NSString* _LOG_UID = @"-1";

When I enter in background mode it crash with this "classic" error:

* -[CFString respondsToSelector:]: message sent to deallocated instance
  0x6a4c800

But why?

I don't release anything!=!

What's wrong?


问:
KStream: Error Reading and Writing Avro records
I’m trying to write avro record that I read from a topic into another topic, intentions it to augment it with transformation after I get this routing working. I have used the KStream with avro code from one of the example with some modifications to connect to Schema Registry for retrieving the avro schema.

```<code>streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "mysql-stream-processing");
streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
streamsConfiguration.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl);
final Serde<GenericRecord> keySerde = new GenericAvroSerde(
        new CachedSchemaRegistryClient(schemaRegistryUrl, 100),
        Collections.singletonMap(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
                schemaRegistryUrl));
final Serde<GenericRecord> valueSerde = new GenericAvroSerde(
        new CachedSchemaRegistryClient(schemaRegistryUrl, 100),
        Collections.singletonMap(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
                schemaRegistryUrl));
streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
streamsConfiguration.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 10 * 1000);

final KStreamBuilder builder = new KStreamBuilder();

final KStream<GenericRecord, GenericRecord> record = builder.stream("dbserver1.employees.employees");

record.print(keySerde, valueSerde);

record.to(keySerde, valueSerde, "newtopic");

record.foreach((key, val) -> System.out.println(key.toString()+"  "+val.toString()));
final KafkaStreams streams = new KafkaStreams(builder, streamsConfiguration);

streams.cleanUp();
streams.start();
</code>```

When run print() works as I can see the record in the console, but Im unable to get the record written to the “newtopic”, failing with the below error

```<code>Exception in thread "StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Exception caught in process. taskId=0_0, processor=KSTREAM-SOURCE-0000000000, topic=dbserver1.employees.employees, partition=0, offset=0
        at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:217)
        at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:627)
        at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:361)
Caused by: org.apache.kafka.streams.errors.StreamsException: A serializer (key: io.confluent.examples.streams.utils.GenericAvroSerializer / value: io.confluent.examples.streams.utils.GenericAvroSerializer) is not compatible to the actual key or value type (key type: [B / value type: [B). Change the default Serdes in StreamConfig or provide correct Serdes via method parameters.
        at org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:81)
        at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:83)
        at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:70)
        at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:198)
        ... 2 more
Caused by: java.lang.ClassCastException: [B cannot be cast to org.apache.avro.generic.GenericRecord
        at io.confluent.examples.streams.utils.GenericAvroSerializer.serialize(GenericAvroSerializer.java:25)
        at org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:77)
        at org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:79)
        ... 5 more
</code>```

答:
I guess you need to configure the correct Serdes:

https://docs.confluent.io/current/streams/developer-guide/config-streams.html#default-key-serde

https://docs.confluent.io/current/streams/developer-guide/dsl-api.html

Either set correct global Serdes, or specify Serdes for each operator. If an operator needs a Serde, than it has a corresponding overload taking Serdes are parameters.

Body:
I’m trying to write avro record that I read from a topic into another topic, intentions it to augment it with transformation after I get this routing working. I have used the KStream with avro code from one of the example with some modifications to connect to Schema Registry for retrieving the avro schema.

streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "mysql-stream-processing");
streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
streamsConfiguration.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl);
final Serde<GenericRecord> keySerde = new GenericAvroSerde(
        new CachedSchemaRegistryClient(schemaRegistryUrl, 100),
        Collections.singletonMap(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
                schemaRegistryUrl));
final Serde<GenericRecord> valueSerde = new GenericAvroSerde(
        new CachedSchemaRegistryClient(schemaRegistryUrl, 100),
        Collections.singletonMap(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
                schemaRegistryUrl));
streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
streamsConfiguration.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 10 * 1000);

final KStreamBuilder builder = new KStreamBuilder();

final KStream<GenericRecord, GenericRecord> record = builder.stream("dbserver1.employees.employees");

record.print(keySerde, valueSerde);

record.to(keySerde, valueSerde, "newtopic");

record.foreach((key, val) -> System.out.println(key.toString()+"  "+val.toString()));
final KafkaStreams streams = new KafkaStreams(builder, streamsConfiguration);

streams.cleanUp();
streams.start();

When run print() works as I can see the record in the console, but Im unable to get the record written to the “newtopic”, failing with the below error

Exception in thread "StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Exception caught in process. taskId=0_0, processor=KSTREAM-SOURCE-0000000000, topic=dbserver1.employees.employees, partition=0, offset=0
        at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:217)
        at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:627)
        at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:361)
Caused by: org.apache.kafka.streams.errors.StreamsException: A serializer (key: io.confluent.examples.streams.utils.GenericAvroSerializer / value: io.confluent.examples.streams.utils.GenericAvroSerializer) is not compatible to the actual key or value type (key type: [B / value type: [B). Change the default Serdes in StreamConfig or provide correct Serdes via method parameters.
        at org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:81)
        at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:83)
        at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:70)
        at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:198)
        ... 2 more
Caused by: java.lang.ClassCastException: [B cannot be cast to org.apache.avro.generic.GenericRecord
        at io.confluent.examples.streams.utils.GenericAvroSerializer.serialize(GenericAvroSerializer.java:25)
        at org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:77)
        at org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:79)
        ... 5 more


问:
Get URL origin and parameter
How can I easily extract the origin and a specific parameter from the tab from where I called the extension?

If the current URL is:

```<code>https://base.com/etc/etc?param1=123
</code>```

I'd want to get two variables
    origin = "https://base.com"
and
    param1 = "123"

Ideally this should still work if there are more parameters, i.e.
if the current URL is
    https://base.com/etc/etc?param1=123&param2=234

I would still get
    origin = "https://base.com"
and
    param1 = "123"

I understand that i could use something like

```<code>chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
</code>```

but i am learning Javascript slooowly. How would this function look like?

答:
The documentation for chrome.tabs.query says that in the callback function (tabs) you'll get an array of Tab. A Tab has a lot of properties, one of them being url. So you could do something like:

```<code>// Get the current active tab in the last focused Chrome window (before the popup showed)
// should return only ONE tab
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
    if (!tabs[0]) { console.log('Could not get current tab'); return; }

    // Now extract the information from the URL
    let url = new URL(tabs[0].url);
    let base = url.protocol + '//' + url.hostname;
    let param1 = url.searchParams.get('param1');

    console.log(base);
    console.log(param1);
})
</code>```

Title: Get URL origin and parameter

Body:
How can I easily extract the origin and a specific parameter from the tab from where I called the extension?

If the current URL is:

https://base.com/etc/etc?param1=123

I'd want to get two variables
    origin = "https://base.com"
and
    param1 = "123"

Ideally this should still work if there are more parameters, i.e.
if the current URL is
    https://base.com/etc/etc?param1=123&param2=234

I would still get
    origin = "https://base.com"
and
    param1 = "123"

I understand that i could use something like

chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {

but i am learning Javascript slooowly. How would this function look like?

Body:
The documentation for chrome.tabs.query says that in the callback function (tabs) you'll get an array of Tab. A Tab has a lot of properties, one of them being url. So you could do something like:

// Get the current active tab in the last focused Chrome window (before the popup showed)
// should return only ONE tab
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
    if (!tabs[0]) { console.log('Could not get current tab'); return; }

    // Now extract the information from the URL
    let url = new URL(tabs[0].url);
    let base = url.protocol + '//' + url.hostname;
    let param1 = url.searchParams.get('param1');

    console.log(base);
    console.log(param1);
})


问:
ImportError in Python library
I am trying the python-upwork library and followed the setup. pip freeze shows required libraries:

```<code>httplib2==0.10.3
httplib2.system-ca-certs-locater==0.1.2
macholib==1.5.1
matplotlib==1.3.1
modulegraph==0.10.4
numpy==1.8.0rc1
oauth2==1.5.211
urllib3==1.10
</code>```

However trying to create client gives

```<code>client = upwork.Client(public_key, secret_key)
  File "/Library/Python/2.7/site-packages/upwork/client.py", line 119, in __init__
    ca_certs=ca_certs_locater.get(),
  File "/Library/Python/2.7/site-packages/ca_certs_locater/__init__.py", line 36, in get
    raise ImportError()
</code>```

I found this link and it sounds like python cannot find the cert to validate upwork.com. I tried following suggestions but still same issue. I'm not sure where to put the cacerts.pem file.

答:
Answering my own question. Here is what worked for me. I am on Mac.

Download the latest pem file from link at bottom of this page. Then force copy to specific location and rename it:

```<code>sudo cp cacert.pem /etc/ssl/certs/ca-certificates.crt
</code>```

Then it works!

Title: ImportError in Python library

Body:
I am trying the python-upwork library and followed the setup. pip freeze shows required libraries:

httplib2==0.10.3
httplib2.system-ca-certs-locater==0.1.2
macholib==1.5.1
matplotlib==1.3.1
modulegraph==0.10.4
numpy==1.8.0rc1
oauth2==1.5.211
urllib3==1.10

However trying to create client gives

client = upwork.Client(public_key, secret_key)
  File "/Library/Python/2.7/site-packages/upwork/client.py", line 119, in __init__
    ca_certs=ca_certs_locater.get(),
  File "/Library/Python/2.7/site-packages/ca_certs_locater/__init__.py", line 36, in get
    raise ImportError()

I found this link and it sounds like python cannot find the cert to validate upwork.com. I tried following suggestions but still same issue. I'm not sure where to put the cacerts.pem file.

Body:
Answering my own question. Here is what worked for me. I am on Mac.

Download the latest pem file from link at bottom of this page. Then force copy to specific location and rename it:

sudo cp cacert.pem /etc/ssl/certs/ca-certificates.crt

Then it works!


问:
SQL comparing a few values in select
so i have 2 tables in SQL, Patients and Patients_Treatments which are connected with patient.id as main key
what i wanna do is take a specific patient and see what treatments he has done so i have this code:

```<code>SELECT (Treatment_code)
FROM Patients_Treatments
Where Patient_ID = '999999999'
</code>```

now what i want do is take all the patients from Patient tabel that have had the same treatments code (or more treatments) just as patient '99999999'

so if patient '9999999' had treatments 111,222,333
and i have a patient that had treatment 111,222,555 - it wont show him
but if had had treatments 111,222,333 or 111,222,333,444 - it will show him

im having problem with how to do a loop so i make sure it check that all the treatments that patient 99999999 has done, also the person im checking has done as well

thanks!

答:
Assume this is the metadata and the examples you provided.

```<code>CREATE TABLE PATIENTS
(PATIENT_ID INTEGER);

CREATE TABLE PATIENTS_TREATMENTS
(PATIENT_ID INTEGER, TREATMENT_CODE INTEGER);

INSERT INTO PATIENTS VALUE (999999999),(1),(2),(3);

INSERT INTO PATIENTS_TREATMENTS VALUE
(999999999, 111),(999999999, 222),(999999999, 333),
(1, 111),(1, 222),(1, 555),
(2, 111),(2, 222),(2, 333),
(3, 111),(3, 222),(3, 333),(3,444);
</code>```

The solution would be as follows

```<code>SELECT
      PATIENTS.PATIENT_ID

   FROM PATIENTS

   INNER JOIN PATIENTS_TREATMENTS MYTREATMENT
   ON PATIENTS.PATIENT_ID              = MYTREATMENT.PATIENT_ID

   LEFT JOIN PATIENTS_TREATMENTS COMPARETREATMENT
   ON  COMPARETREATMENT.TREATMENT_CODE = MYTREATMENT.TREATMENT_CODE
   AND COMPARETREATMENT.PATIENT_ID     = '999999999'

   WHERE PATIENTS.PATIENT_ID <> '999999999'

   GROUP BY PATIENTS.PATIENT_ID
   HAVING COUNT(COMPARETREATMENT.TREATMENT_CODE) = (SELECT COUNT(*) FROM PATIENTS_TREATMENTS WHERE PATIENT_ID = '999999999')
</code>```

Try it on http://sqlfiddle.com/

Title: SQL comparing a few values in select

Body:
so i have 2 tables in SQL, Patients and Patients_Treatments which are connected with patient.id as main key
what i wanna do is take a specific patient and see what treatments he has done so i have this code:

SELECT (Treatment_code)
FROM Patients_Treatments
Where Patient_ID = '999999999'

now what i want do is take all the patients from Patient tabel that have had the same treatments code (or more treatments) just as patient '99999999'

so if patient '9999999' had treatments 111,222,333
and i have a patient that had treatment 111,222,555 - it wont show him
but if had had treatments 111,222,333 or 111,222,333,444 - it will show him

im having problem with how to do a loop so i make sure it check that all the treatments that patient 99999999 has done, also the person im checking has done as well

thanks!

Body:
Assume this is the metadata and the examples you provided.

CREATE TABLE PATIENTS
(PATIENT_ID INTEGER);

CREATE TABLE PATIENTS_TREATMENTS
(PATIENT_ID INTEGER, TREATMENT_CODE INTEGER);

INSERT INTO PATIENTS VALUE (999999999),(1),(2),(3);

INSERT INTO PATIENTS_TREATMENTS VALUE
(999999999, 111),(999999999, 222),(999999999, 333),
(1, 111),(1, 222),(1, 555),
(2, 111),(2, 222),(2, 333),
(3, 111),(3, 222),(3, 333),(3,444);

The solution would be as follows

SELECT
      PATIENTS.PATIENT_ID

   FROM PATIENTS

   INNER JOIN PATIENTS_TREATMENTS MYTREATMENT
   ON PATIENTS.PATIENT_ID              = MYTREATMENT.PATIENT_ID

   LEFT JOIN PATIENTS_TREATMENTS COMPARETREATMENT
   ON  COMPARETREATMENT.TREATMENT_CODE = MYTREATMENT.TREATMENT_CODE
   AND COMPARETREATMENT.PATIENT_ID     = '999999999'

   WHERE PATIENTS.PATIENT_ID <> '999999999'

   GROUP BY PATIENTS.PATIENT_ID
   HAVING COUNT(COMPARETREATMENT.TREATMENT_CODE) = (SELECT COUNT(*) FROM PATIENTS_TREATMENTS WHERE PATIENT_ID = '999999999')

Try it on http://sqlfiddle.com/


问:
Get key name from the property of javascript object
How can I get the key name "email" inside the function ? Is there a special context variable to do this ?

Thanks for help.

var user = {
  "email": function() {
    // How can I get the name of the key (email) inside the function ?
  }
}```

答:
A relatively new feature of JS will assign a name to an anonymous function expression based on the variable or property to which it is initially assigned.

You can access a function's name via arguments.callee.name

var bar = {
  baz: function() {
    console.log(arguments.callee.name);
  }
}

bar.baz();```
</div>
</div>
</p>

<p>Of course, if you copy the function elsewhere, it won't get a new name. The name is given to it at the time it is created.</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>var bar = {
  baz: function() {
    console.log(arguments.callee.name);
  }
}

bar.foo = bar.baz;

bar.foo();</code>```

Body:
A relatively new feature of JS will assign a name to an anonymous function expression based on the variable or property to which it is initially assigned.

You can access a function's name via arguments.callee.name

var bar = {
  baz: function() {
    console.log(arguments.callee.name);
  }
}

bar.baz();

Of course, if you copy the function elsewhere, it won't get a new name. The name is given to it at the time it is created.

var bar = {
  baz: function() {
    console.log(arguments.callee.name);
  }
}

bar.foo = bar.baz;

bar.foo();