问:
Can I use a parameter I get from another controller to the current initializable?
I have two different controllers, but by getting a certain value at one of them I want to use it at the second controller's initializable.

This is the part where the first controller sends the region parameter to the other controler

```<code>    public void enterlevel(String x) throws IOException{

    FXMLLoader Loader=new FXMLLoader();

    Loader.setLocation(getClass().getResource(x));

    Loader.load();

    regionalController reg=Loader.getController();
    reg.getRegion(region);

    //System.out.println(region);

    Parent root = Loader.getRoot();

    Stage primaryStage = new Stage();
    Scene scene = new Scene(root);

    primaryStage.setTitle("Ziga Ziga");
    primaryStage.setScene(scene);
    primaryStage.setMaximized(true);
    primaryStage.setResizable(false);
    primaryStage.show();

    Stage stage = (Stage) loginButton.getScene().getWindow();
    stage.close();

}
</code>```

This is where the second controller gets it

```<code>    public void getRegion(String region) {
    System.out.println(region+" UO UO UO ");
    regi=region;
    }
</code>```

And this is the initializable where I can't use the value as it starts

```<code>public void initialize(URL arg0, ResourceBundle arg1) {
    System.out.println(regi);
    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bimbima","root","");
        Statement stmt=con.createStatement();
        ResultSet rs=stmt.executeQuery("SELECT * FROM  `file` WHERE Region = '"+regi+"'");
        while(rs.next())  {
        filename=rs.getString("filename");
        nameofSup=rs.getString("Name of Supervisor");
        System.out.println(filename);
        }
        con.close();
        }catch(Exception e){ System.out.println(e);}
}
</code>```

答:
Aside: surely your getRegion(...) method should be called setRegion(...), since it changes the value of a property, and doesn't return anything.

Just change the code in the second controller so that you only retrieve the values from the database when you know the region:

```<code>public void initialize(URL arg0, ResourceBundle arg1) {
}

public void setRegion(String region) {
    regi=region;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bimbima","root","");
        Statement stmt=con.createStatement();
        ResultSet rs=stmt.executeQuery("SELECT * FROM  `file` WHERE Region = '"+regi+"'");
        while(rs.next())  {
        filename=rs.getString("filename");
        nameofSup=rs.getString("Name of Supervisor");
        System.out.println(filename);
        }
        con.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
}
</code>```

Body:
I have two different controllers, but by getting a certain value at one of them I want to use it at the second controller's initializable.

This is the part where the first controller sends the region parameter to the other controler

    public void enterlevel(String x) throws IOException{

    FXMLLoader Loader=new FXMLLoader();

    Loader.setLocation(getClass().getResource(x));

    Loader.load();

    regionalController reg=Loader.getController();
    reg.getRegion(region);

    //System.out.println(region);

    Parent root = Loader.getRoot();

    Stage primaryStage = new Stage();
    Scene scene = new Scene(root);

    primaryStage.setTitle("Ziga Ziga");
    primaryStage.setScene(scene);
    primaryStage.setMaximized(true);
    primaryStage.setResizable(false);
    primaryStage.show();

    Stage stage = (Stage) loginButton.getScene().getWindow();
    stage.close();

}

This is where the second controller gets it

    public void getRegion(String region) {
    System.out.println(region+" UO UO UO ");
    regi=region;
    }

And this is the initializable where I can't use the value as it starts

public void initialize(URL arg0, ResourceBundle arg1) {
    System.out.println(regi);
    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bimbima","root","");
        Statement stmt=con.createStatement();
        ResultSet rs=stmt.executeQuery("SELECT * FROM  `file` WHERE Region = '"+regi+"'");
        while(rs.next())  {
        filename=rs.getString("filename");
        nameofSup=rs.getString("Name of Supervisor");
        System.out.println(filename);
        }
        con.close();
        }catch(Exception e){ System.out.println(e);}
}

Body:
Aside: surely your getRegion(...) method should be called setRegion(...), since it changes the value of a property, and doesn't return anything.

Just change the code in the second controller so that you only retrieve the values from the database when you know the region:

public void initialize(URL arg0, ResourceBundle arg1) {
}

public void setRegion(String region) {
    regi=region;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bimbima","root","");
        Statement stmt=con.createStatement();
        ResultSet rs=stmt.executeQuery("SELECT * FROM  `file` WHERE Region = '"+regi+"'");
        while(rs.next())  {
        filename=rs.getString("filename");
        nameofSup=rs.getString("Name of Supervisor");
        System.out.println(filename);
        }
        con.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
}


来源: stackexchange

问:
Using AndroidStudio + gradle + NDK to build Library for Android and Linux
I want to build a shared library with different variants / versions that I can use on Android and in Linux applications.

Therefor, I set up an Android Project consisting of an app module and a (native C/C++) library module as outlined in the official Android Studio documentation*, so that my complete build tool chain for the library consists of**:

Android Studio

gradle / build.gradle

cmake / CMakeLists.txt

ninja

clang

My code is actually portable, e.g. I used #ifdef __ANDROID__ around Android specific code paths, and I can compile a working Linux shared object by hand, that is, by invoking the compiler from the command line.

Is there a nice way to use the above tool chain to create both the .so files for Android and Linux, without maintaining two redundant sets of build configuration files?

* I followed the documentation from May 2017, which is almost identical to this archive.org snapshot from February 2017.

** I do not use Android.mk and ndk-build, so that this related question does not apply for me, even though the purpose is the same.

答: I searched for a similar solution, but I think there is currently no way to do it. There is no Android-Studio plugin to do native c/c++ compilation. Java is possible, but not an option for me.</p>

ContentLicense: CC BY-SA 3.0


问:
How get the Value of DropDown in TypeScript
I have a drop down list in my MVC view as :

```<code> <select id="organization" class="create-user-select-half"></select>
</code>```

I try to get the value of dropdown in Type Script like this:

```<code> var e = (<HTMLInputElement>document.getElementById("organization")).value;
</code>```

but it return empty, this is how I get the textbox value and it is working. Also I tired this code but options and selectedIndex are undefined.

```<code> var value = e.options[e.selectedIndex].value;
 var text = e.options[e.selectedIndex].text;
</code>```

答:
You need to use the HTMLSelectElement instead, but this can be tricky

```<code>    var e = (document.getElementById("organization")) as HTMLSelectElement;
    var sel = e.selectedIndex;
    var opt = e.options[sel];
    var CurValue = (<HTMLSelectElement>opt).value;
    var CurText = (<HTMLSelectElement>opt).text;
</code>```

You will need to define the value or text though if you want anything back

```<code>    '<select id="organization" value="ThisIsMyValue">This is my text</select>
</code>```

Output

CurValue = "ThisIsMyValue"

CurText = "This is my text"

Body:
I have a drop down list in my MVC view as :

 <select id="organization" class="create-user-select-half"></select>

I try to get the value of dropdown in Type Script like this:

 var e = (<HTMLInputElement>document.getElementById("organization")).value;

but it return empty, this is how I get the textbox value and it is working. Also I tired this code but options and selectedIndex are undefined.

 var value = e.options[e.selectedIndex].value;
 var text = e.options[e.selectedIndex].text;

Body:
You need to use the HTMLSelectElement instead, but this can be tricky

    var e = (document.getElementById("organization")) as HTMLSelectElement;
    var sel = e.selectedIndex;
    var opt = e.options[sel];
    var CurValue = (<HTMLSelectElement>opt).value;
    var CurText = (<HTMLSelectElement>opt).text;

You will need to define the value or text though if you want anything back

    '<select id="organization" value="ThisIsMyValue">This is my text</select>

Output

CurValue = "ThisIsMyValue"

CurText = "This is my text"


问:
Excel VBA error type '13' typemismatch
```<code>Option Explicit

#If VBA7 And Win64 Then
    Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
      Alias "URLDownloadToFileA" ( _
        ByVal pCaller As LongPtr, _
        ByVal szURL As String, _
        ByVal szFileName As String, _
        ByVal dwReserved As LongPtr, _
        ByVal lpfnCB As LongPtr _
      ) As Long
    Private Declare PtrSafe Function DeleteUrlCacheEntry Lib "Wininet.dll" _
      Alias "DeleteUrlCacheEntryA" ( _
        ByVal lpszUrlName As String _
      ) As Long
#Else
    Private Declare Function URLDownloadToFile Lib "urlmon" _
      Alias "URLDownloadToFileA" ( _
        ByVal pCaller As Long, _
        ByVal szURL As String, _
        ByVal szFileName As String, _
        ByVal dwReserved As Long, _
        ByVal lpfnCB As Long _
      ) As Long
    Private Declare Function DeleteUrlCacheEntry Lib "Wininet.dll" _
      Alias "DeleteUrlCacheEntryA" ( _
        ByVal lpszUrlName As String _
      ) As Long
#End If

Public Const ERROR_SUCCESS As Long = 0
Public Const BINDF_GETNEWESTVERSION As Long = &H10
Public Const INTERNET_FLAG_RELOAD As Long = &H80000000

    'Global Variables for passing values b/w subs
    Dim myPath As String
    Dim folderPath As String
    Dim folderLocation As Variant

Sub airtableCleaner()
    Dim argCounter As Integer
    Dim Answer As VbMsgBoxResult

    Dim strProgramName As String
    Dim strArgument As String
    Dim shellCommand As String

    folderPath = Application.ActiveWorkbook.Path 'Example C:/downloads
    myPath = Application.ActiveWorkbook.FullName 'Example C:/downloads/book1.csv

    'Ask user if they want to run macro
    Answer = MsgBox("Run? Airtable - 1: primaryKey, 2: one image attachment", vbYesNo, "Run Macro")
    If Answer = vbYes Then

    folderLocation = Application.InputBox("Give a subfolder name for directory. E.G. Batch1")

    'Creates new folder based on input
    Dim strDir As String
    strDir = folderPath & "\" & folderLocation

    If Dir(strDir, vbDirectory) = "" Then
        MkDir strDir
    Else
        MsgBox "Directory exists."
    End If

    'Cleanup to just amazons3 dl.airtable links
    Columns("B:B").Select
    Selection.Replace What:="* ", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Selection.Replace What:="(", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Selection.Replace What:=")", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

    'Count Cells
    Range("B2").Activate
    Do
        If ActiveCell.Value = "" Then Exit Do
        ActiveCell.Offset(1, 0).Activate
        argCounter = argCounter + 1

    Loop

    'Copy Image Links to new cells to format in Column C
    Columns("B:B").Select
    Selection.Copy
    Columns("C:C").Select
    ActiveSheet.Paste
    Application.CutCopyMode = False

    'Clean up links to only have names in Column C
    Selection.Replace What:="https://dl.airtable.com/", Replacement:="", _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:= _
    False, ReplaceFormat:=False

    'Cleanup Broken images using excelVBA downloader %5B1%5D = B1D
     Columns("C:C").Select
     Range("C40").Activate
     Selection.Replace What:="%5B1%5D", Replacement:="B1D", LookAt:=xlPart, _
     SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
     ReplaceFormat:=False

    'Create Column D batch files
        Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34), " & folderPath & "\" & ", C2,CHAR(34),"" "", CHAR(34), " & _
                      Chr(34) & folderPath & "\" & folderLocation & "\" & Chr(34) & ",A2,"".png"",CHAR(34))"

    Range("D2").Select
    Selection.AutoFill Destination:=Range("D2:D" & argCounter + 1)

    'Delete header row 1 information
    Rows("1:1").Select
    Selection.Delete Shift:=xlUp

    'Repaste values back into column D removing formulas
        Columns("D:D").Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False

    'Image downloader to source folder
    Call dlStaplesImages

    'Make the batch files using row data col D
    Call ExportRangetoBatch

    'Ask user to run bat file now or later
    shellCommand = """" & folderPath & "\" & "newcurl.bat" & """"
    Call Shell(shellCommand, vbNormalFocus)

    End If
End Sub

'https://superuser.com/questions/1045707/create-bat-file-with-excel-data-with-vba    , modified copypasta code

Sub ExportRangetoBatch()

    Dim ColumnNum: ColumnNum = 4   ' Column D
    Dim RowNum: RowNum = 1          ' Row to start on
    Dim objFSO, objFile

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.CreateTextFile(folderPath & "\newcurl.bat")    'Output Path

    Dim OutputString: OutputString = ""

    OutputString = "Timeout 3" & vbNewLine 'useful for error checking

    Do
        OutputString = OutputString & Replace(Cells(RowNum, ColumnNum).Value, Chr(10), vbNewLine) & vbNewLine 'Goes to new line in string, then creates another
        RowNum = RowNum + 1
    Loop Until IsEmpty(Cells(RowNum, ColumnNum))

    OutputString = OutputString & "Timeout 3"   'useful for errorchecking

    objFile.Write (OutputString)

    Set objFile = Nothing
    Set objFSO = Nothing

End Sub

'https://stackoverflow.com/questions/31359682/with-excel-vba-save-web-image-to-disk/31360105#31360105      , modified copypasta code

Sub dlStaplesImages()
    Dim rw As Long, lr As Long, ret As Long, sIMGDIR As String, sWAN As String, sLAN As String

    sIMGDIR = folderPath
    'If Dir(sIMGDIR, vbDirectory) = "" Then MkDir sIMGDIR

    With ActiveSheet    '<-set this worksheet reference properly!
        lr = .Cells(Rows.Count, 1).End(xlUp).Row
        For rw = 1 To lr 'rw to last row, assume first row is not header

            sWAN = .Cells(rw, 2).Value2
            sLAN = sIMGDIR & Chr(92) & Trim(Right(Replace(sWAN, Chr(47), Space(999)), 999))

            Debug.Print sWAN
            Debug.Print sLAN

            If CBool(Len(Dir(sLAN))) Then
                Call DeleteUrlCacheEntry(sLAN)
                Kill sLAN
            End If

            ret = URLDownloadToFile(0&, sWAN, sLAN, BINDF_GETNEWESTVERSION, 0&)

            'Imported code to output success / fail
            If ret = 0 Then
            Range("E" & rw).Value = "File successfully downloaded"
        Else
            Range("E" & rw).Value = "Unable to download the file"
        End If

            '.Cells(rw, 5) = ret
            Next rw
    End With

End Sub
</code>```

I have this set of code. The above code works without any errors. Basically it takes some input data, transforms data, downloads images, and inputs a .batch file to rename many all the images after

The problem I have is when I change this line:

```<code>Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34),C2,CHAR(34),"" "", CHAR(34), " & _
                          Chr(34) & folderPath & "\" & folderLocation & "\" & Chr(34) & ",A2,"".png"",CHAR(34))"
</code>```

to this new line:

```<code>Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34), " & folderPath & "\" & ", C2,CHAR(34),"" "", CHAR(34), " & _
                          Chr(34) & folderPath & "\" & folderLocation & "\" & Chr(34) & ",A2,"".png"",CHAR(34))"
</code>```

I get an error here

Run-time error '13' :Type mismatch

On this line where I run a do loop

```<code>OutputString = OutputString & Replace(Cells(RowNum, ColumnNum).Value, Chr(10), vbNewLine) & vbNewLine 'Goes to new line in string, then creates another
</code>```

Originally, OutputString took iterative values like this:

COPY "foo.png" "C:\batch\foo2.png"

Now I am trying to give it this:

COPY "C:\foo.png" "C:\batch\foo2.png"

The only thing I changed was added a longer string value that outputString would have to be reading. I'm not sure why I have a type 13 error (variable datatypes not matching)

答:
Excel's syntax is really confusing when passing variables to excel-functions in VBA.

What happened was I was verbatim passing the the folderPath variable (e.g. C:\foo) right inside of an excel formula, when I should have been concatenating each result seperately (which was not possible with my previous solution)

So I just rewrote a set of clean code using no built in excel functions

Original code snippet causing Error type 13 code statement:

```<code>Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34), " & folderPath & "\" & ", C2,CHAR(34),"" "", CHAR(34), " & _
                          Chr(34) & folderPath & "\" & folderLocation & "\" & Chr(34) & ",A2,"".png"",CHAR(34))"
</code>```

New Clean and easy-to-read / edit code:

```<code>For row = 2 To argCounter + 1
    A = Cells(row, 1).Value
    C = Cells(row, 3).Value

    A = """" & folderPath & "\" & folderLocation & "\" & A & ".png" & """"
    C = """" & folderPath & "\" & C & """"

    Cells(row, 4).Value = "Copy " & C & " " & A
Next row
</code>```

Title: Excel VBA error type '13' typemismatch

Body:
Option Explicit

#If VBA7 And Win64 Then
    Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
      Alias "URLDownloadToFileA" ( _
        ByVal pCaller As LongPtr, _
        ByVal szURL As String, _
        ByVal szFileName As String, _
        ByVal dwReserved As LongPtr, _
        ByVal lpfnCB As LongPtr _
      ) As Long
    Private Declare PtrSafe Function DeleteUrlCacheEntry Lib "Wininet.dll" _
      Alias "DeleteUrlCacheEntryA" ( _
        ByVal lpszUrlName As String _
      ) As Long
#Else
    Private Declare Function URLDownloadToFile Lib "urlmon" _
      Alias "URLDownloadToFileA" ( _
        ByVal pCaller As Long, _
        ByVal szURL As String, _
        ByVal szFileName As String, _
        ByVal dwReserved As Long, _
        ByVal lpfnCB As Long _
      ) As Long
    Private Declare Function DeleteUrlCacheEntry Lib "Wininet.dll" _
      Alias "DeleteUrlCacheEntryA" ( _
        ByVal lpszUrlName As String _
      ) As Long
#End If

Public Const ERROR_SUCCESS As Long = 0
Public Const BINDF_GETNEWESTVERSION As Long = &H10
Public Const INTERNET_FLAG_RELOAD As Long = &H80000000

    'Global Variables for passing values b/w subs
    Dim myPath As String
    Dim folderPath As String
    Dim folderLocation As Variant

Sub airtableCleaner()
    Dim argCounter As Integer
    Dim Answer As VbMsgBoxResult

    Dim strProgramName As String
    Dim strArgument As String
    Dim shellCommand As String

    folderPath = Application.ActiveWorkbook.Path 'Example C:/downloads
    myPath = Application.ActiveWorkbook.FullName 'Example C:/downloads/book1.csv

    'Ask user if they want to run macro
    Answer = MsgBox("Run? Airtable - 1: primaryKey, 2: one image attachment", vbYesNo, "Run Macro")
    If Answer = vbYes Then

    folderLocation = Application.InputBox("Give a subfolder name for directory. E.G. Batch1")

    'Creates new folder based on input
    Dim strDir As String
    strDir = folderPath & "\" & folderLocation

    If Dir(strDir, vbDirectory) = "" Then
        MkDir strDir
    Else
        MsgBox "Directory exists."
    End If

    'Cleanup to just amazons3 dl.airtable links
    Columns("B:B").Select
    Selection.Replace What:="* ", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Selection.Replace What:="(", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Selection.Replace What:=")", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

    'Count Cells
    Range("B2").Activate
    Do
        If ActiveCell.Value = "" Then Exit Do
        ActiveCell.Offset(1, 0).Activate
        argCounter = argCounter + 1

    Loop

    'Copy Image Links to new cells to format in Column C
    Columns("B:B").Select
    Selection.Copy
    Columns("C:C").Select
    ActiveSheet.Paste
    Application.CutCopyMode = False

    'Clean up links to only have names in Column C
    Selection.Replace What:="https://dl.airtable.com/", Replacement:="", _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:= _
    False, ReplaceFormat:=False

    'Cleanup Broken images using excelVBA downloader %5B1%5D = B1D
     Columns("C:C").Select
     Range("C40").Activate
     Selection.Replace What:="%5B1%5D", Replacement:="B1D", LookAt:=xlPart, _
     SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
     ReplaceFormat:=False

    'Create Column D batch files
        Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34), " & folderPath & "\" & ", C2,CHAR(34),"" "", CHAR(34), " & _
                      Chr(34) & folderPath & "\" & folderLocation & "\" & Chr(34) & ",A2,"".png"",CHAR(34))"

    Range("D2").Select
    Selection.AutoFill Destination:=Range("D2:D" & argCounter + 1)

    'Delete header row 1 information
    Rows("1:1").Select
    Selection.Delete Shift:=xlUp

    'Repaste values back into column D removing formulas
        Columns("D:D").Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False

    'Image downloader to source folder
    Call dlStaplesImages

    'Make the batch files using row data col D
    Call ExportRangetoBatch

    'Ask user to run bat file now or later
    shellCommand = """" & folderPath & "\" & "newcurl.bat" & """"
    Call Shell(shellCommand, vbNormalFocus)

    End If
End Sub

'https://superuser.com/questions/1045707/create-bat-file-with-excel-data-with-vba    , modified copypasta code

Sub ExportRangetoBatch()

    Dim ColumnNum: ColumnNum = 4   ' Column D
    Dim RowNum: RowNum = 1          ' Row to start on
    Dim objFSO, objFile

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.CreateTextFile(folderPath & "\newcurl.bat")    'Output Path

    Dim OutputString: OutputString = ""

    OutputString = "Timeout 3" & vbNewLine 'useful for error checking

    Do
        OutputString = OutputString & Replace(Cells(RowNum, ColumnNum).Value, Chr(10), vbNewLine) & vbNewLine 'Goes to new line in string, then creates another
        RowNum = RowNum + 1
    Loop Until IsEmpty(Cells(RowNum, ColumnNum))

    OutputString = OutputString & "Timeout 3"   'useful for errorchecking

    objFile.Write (OutputString)

    Set objFile = Nothing
    Set objFSO = Nothing

End Sub

'https://stackoverflow.com/questions/31359682/with-excel-vba-save-web-image-to-disk/31360105#31360105      , modified copypasta code

Sub dlStaplesImages()
    Dim rw As Long, lr As Long, ret As Long, sIMGDIR As String, sWAN As String, sLAN As String

    sIMGDIR = folderPath
    'If Dir(sIMGDIR, vbDirectory) = "" Then MkDir sIMGDIR

    With ActiveSheet    '<-set this worksheet reference properly!
        lr = .Cells(Rows.Count, 1).End(xlUp).Row
        For rw = 1 To lr 'rw to last row, assume first row is not header

            sWAN = .Cells(rw, 2).Value2
            sLAN = sIMGDIR & Chr(92) & Trim(Right(Replace(sWAN, Chr(47), Space(999)), 999))

            Debug.Print sWAN
            Debug.Print sLAN

            If CBool(Len(Dir(sLAN))) Then
                Call DeleteUrlCacheEntry(sLAN)
                Kill sLAN
            End If

            ret = URLDownloadToFile(0&, sWAN, sLAN, BINDF_GETNEWESTVERSION, 0&)

            'Imported code to output success / fail
            If ret = 0 Then
            Range("E" & rw).Value = "File successfully downloaded"
        Else
            Range("E" & rw).Value = "Unable to download the file"
        End If

            '.Cells(rw, 5) = ret
            Next rw
    End With

End Sub

I have this set of code. The above code works without any errors. Basically it takes some input data, transforms data, downloads images, and inputs a .batch file to rename many all the images after

The problem I have is when I change this line:

Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34),C2,CHAR(34),"" "", CHAR(34), " & _
                          Chr(34) & folderPath & "\" & folderLocation & "\" & Chr(34) & ",A2,"".png"",CHAR(34))"

to this new line:

Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34), " & folderPath & "\" & ", C2,CHAR(34),"" "", CHAR(34), " & _
                          Chr(34) & folderPath & "\" & folderLocation & "\" & Chr(34) & ",A2,"".png"",CHAR(34))"

I get an error here

Run-time error '13' :Type mismatch

On this line where I run a do loop

OutputString = OutputString & Replace(Cells(RowNum, ColumnNum).Value, Chr(10), vbNewLine) & vbNewLine 'Goes to new line in string, then creates another

Originally, OutputString took iterative values like this:

COPY "foo.png" "C:\batch\foo2.png"

Now I am trying to give it this:

COPY "C:\foo.png" "C:\batch\foo2.png"

The only thing I changed was added a longer string value that outputString would have to be reading. I'm not sure why I have a type 13 error (variable datatypes not matching)

Body:
Excel's syntax is really confusing when passing variables to excel-functions in VBA.

What happened was I was verbatim passing the the folderPath variable (e.g. C:\foo) right inside of an excel formula, when I should have been concatenating each result seperately (which was not possible with my previous solution)

So I just rewrote a set of clean code using no built in excel functions

Original code snippet causing Error type 13 code statement:

Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34), " & folderPath & "\" & ", C2,CHAR(34),"" "", CHAR(34), " & _
                          Chr(34) & folderPath & "\" & folderLocation & "\" & Chr(34) & ",A2,"".png"",CHAR(34))"

New Clean and easy-to-read / edit code:

For row = 2 To argCounter + 1
    A = Cells(row, 1).Value
    C = Cells(row, 3).Value

    A = """" & folderPath & "\" & folderLocation & "\" & A & ".png" & """"
    C = """" & folderPath & "\" & C & """"

    Cells(row, 4).Value = "Copy " & C & " " & A
Next row


问:
Extracting corresponding other values in mutate when group_by is applied
I have a data frame with patient data and measurements of different variables over time.

The data frame looks a bit like this but more lab-values variables:

```<code>df <- data.frame(id=c(1,1,1,1,2,2,2,2,2),
                 time=c(0,3,7,35,0,7,14,28,42),
                 labvalue1=c(4.04,NA,2.93,NA,NA,3.78,3.66,NA,2.54),
                 labvalue2=c(NA,63.8,62.8,61.2,78.1,NA,77.6,75.3,NA))

> df2
  id time labvalue1 labvalue2
1  1    0      4.04        NA
2  1    3        NA      63.8
3  1    7      2.93      62.8
4  1   35        NA      61.2
5  2    0        NA      78.1
6  2    7      3.78        NA
7  2   14      3.66      77.6
8  2   28        NA      75.3
9  2   42      2.54        NA
</code>```

I want to calculate for each patient (with unique ID) the decrease or slope per day for the first and last measurement. To compare the slopes between patients. Time is in days. So, eventually I want a new variable, e.g. diff_labvalues - for each value, that gives me for labvalue1:

For patient 1: (2.93-4.04)/ (7-0)  and for patient 2: (2.54-3.78)/(42-7) (for now ignoring the measurements in between, just last-first); etc for labvalue2, and so forth.

So far I have used dplyr, created the first1 and last1 functions, because first() and last() did not work with the NA values.
Thereafter, I have grouped_by 'id', used mutate_all (because there are more lab-values in the original df) calculated the difference between the last1() and first1() lab-values for that patient.

But cannot find HOW to extract the values of the corresponding time values (the delta-time value) which I need to calculate the slope of the decline.

Eventually I want something like this (last line):

```<code>first1 <- function(x) {
  first(na.omit(x))
}

last1 <- function(x) {
  last(na.omit(x))
}
df2 = df %>%
  group_by(id) %>%
  mutate_all(funs(diff=(last1(.)-first1(.)) / #it works until here
  (time[position of last1(.)]-time[position of first1(.)]))) #something like this
</code>```

Not sure if tidyverse even has a solution for this, so any help would be appreciated. :)

ContentLicense: CC BY-SA 4.0

Body:
I have a data frame with patient data and measurements of different variables over time.

The data frame looks a bit like this but more lab-values variables:

df <- data.frame(id=c(1,1,1,1,2,2,2,2,2),
                 time=c(0,3,7,35,0,7,14,28,42),
                 labvalue1=c(4.04,NA,2.93,NA,NA,3.78,3.66,NA,2.54),
                 labvalue2=c(NA,63.8,62.8,61.2,78.1,NA,77.6,75.3,NA))

> df2
  id time labvalue1 labvalue2
1  1    0      4.04        NA
2  1    3        NA      63.8
3  1    7      2.93      62.8
4  1   35        NA      61.2
5  2    0        NA      78.1
6  2    7      3.78        NA
7  2   14      3.66      77.6
8  2   28        NA      75.3
9  2   42      2.54        NA

I want to calculate for each patient (with unique ID) the decrease or slope per day for the first and last measurement. To compare the slopes between patients. Time is in days. So, eventually I want a new variable, e.g. diff_labvalues - for each value, that gives me for labvalue1:

For patient 1: (2.93-4.04)/ (7-0)  and for patient 2: (2.54-3.78)/(42-7) (for now ignoring the measurements in between, just last-first); etc for labvalue2, and so forth.

So far I have used dplyr, created the first1 and last1 functions, because first() and last() did not work with the NA values.
Thereafter, I have grouped_by 'id', used mutate_all (because there are more lab-values in the original df) calculated the difference between the last1() and first1() lab-values for that patient.

But cannot find HOW to extract the values of the corresponding time values (the delta-time value) which I need to calculate the slope of the decline.

Eventually I want something like this (last line):

first1 <- function(x) {
  first(na.omit(x))
}

last1 <- function(x) {
  last(na.omit(x))
}
df2 = df %>%
  group_by(id) %>%
  mutate_all(funs(diff=(last1(.)-first1(.)) / #it works until here
  (time[position of last1(.)]-time[position of first1(.)]))) #something like this

Not sure if tidyverse even has a solution for this, so any help would be appreciated. :)

Body:
We can try

df %>%
   group_by(id) %>%
   filter(!is.na(labs)) %>%
   summarise(diff_labs = (last(labs) - first(labs))/(last(time) - first(time)))
# A tibble: 2 x 2
#     id   diff_labs
#   <dbl>       <dbl>
#1     1 -0.15857143
#2     2 -0.03542857

and

> (2.93-4.04)/ (7-0)
#[1] -0.1585714
> (2.54-3.78)/(42-7)
#[1] -0.03542857

Or another option is data.table

library(data.table)
setDT(df)[!is.na(labs), .(diff_labs = (labs[.N] - labs[1])/(time[.N] - time[1])) , id]
#   id   diff_labs
#1:  1 -0.15857143
#2:  2 -0.03542857


问:
Ionic.Zip.Unity.dll ZlibException on iOS
I'm developing a mobile game for Android and iOS using Unity.
In my game I need to download a compressed file and extract it.

In order to manage compression and decompression, I'm using Ionic.Zip.Unity (you can found that library at https://github.com/r2d2rigo/dotnetzip-for-unity).
Ionic.Zip is a stripped down version of DotNetZip library, that should work with Android and iOS.

So, my code is:

```<code>string fileStr = "*************";
byte[] fileData = Convert.FromBase64String(fileStr);

MemoryStream fileStream = new MemoryStream(fileData);

ZipFile zipFile = ZipFile.Read(fileStream);
foreach (ZipEntry zipEntry in zipFile)
{
     MemoryStream memoryStream = new MemoryStream();

     zipEntry.Extract(memoryStream);

     memoryStream.position = 0;
     StreamReader streamReader = new StreamReader(memoryStream);
     string str = streamReader.ReadToEnd();

     Debug.Log("String decoded: " + str);
}
</code>```

*fileStr contains the encrypted string.

This code works fine on Editor with all platforms (Android, PC, iOS).
If I build the apk for Android, it works.
The problem is with the iOS build. The code compile but runtime I have this exception:

ZlibException
inflating: rc=323508496 msg=

I have tried to remove .dll and add the source code to the project and it works. How is it possibile?

I really need help cause I finish my ideas.

Thank you all.

答: I had similar issue with new xcode 8.3.x, the problem is with new Xcode and the way how LLVM stripping the unused code. It could be a bug from xcode or the new way how it does it. One thing you can try is to set Dead Code Stripping flag in Build Setting to NO</p>

Body:
I'm developing a mobile game for Android and iOS using Unity.
In my game I need to download a compressed file and extract it.

In order to manage compression and decompression, I'm using Ionic.Zip.Unity (you can found that library at https://github.com/r2d2rigo/dotnetzip-for-unity).
Ionic.Zip is a stripped down version of DotNetZip library, that should work with Android and iOS.

So, my code is:

string fileStr = "*************";
byte[] fileData = Convert.FromBase64String(fileStr);

MemoryStream fileStream = new MemoryStream(fileData);

ZipFile zipFile = ZipFile.Read(fileStream);
foreach (ZipEntry zipEntry in zipFile)
{
     MemoryStream memoryStream = new MemoryStream();

     zipEntry.Extract(memoryStream);

     memoryStream.position = 0;
     StreamReader streamReader = new StreamReader(memoryStream);
     string str = streamReader.ReadToEnd();

     Debug.Log("String decoded: " + str);
}

*fileStr contains the encrypted string.

This code works fine on Editor with all platforms (Android, PC, iOS).
If I build the apk for Android, it works.
The problem is with the iOS build. The code compile but runtime I have this exception:

ZlibException
inflating: rc=323508496 msg=

I have tried to remove .dll and add the source code to the project and it works. How is it possibile?

I really need help cause I finish my ideas.

Thank you all.


问:
Where are the English pluralization rules for ActiveSupport defined?
I found the ActiveSupport inflector class. Where can I find the code that initializes the inflector for English?</p>

答:
The ActiveSupport inflector.rb file includes all the inflection libraries and modules.

If you want to customize it, there's a file called inflections.rb in your Rails config/initializers path.

By default it contains

```<code># Be sure to restart your server when you modify this file.

# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
#   inflect.plural /^(ox)$/i, '\1en'
#   inflect.singular /^(ox)en/i, '\1'
#   inflect.irregular 'person', 'people'
#   inflect.uncountable %w( fish sheep )
# end
</code>```

You can edit it to customize the Inflector behavior.

Body:
The ActiveSupport inflector.rb file includes all the inflection libraries and modules.

If you want to customize it, there's a file called inflections.rb in your Rails config/initializers path.

By default it contains

# Be sure to restart your server when you modify this file.

# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
#   inflect.plural /^(ox)$/i, '\1en'
#   inflect.singular /^(ox)en/i, '\1'
#   inflect.irregular 'person', 'people'
#   inflect.uncountable %w( fish sheep )
# end

You can edit it to customize the Inflector behavior.

ContentLicense: CC BY-SA 2.5


问:
Parallel run with jenkins
I have several (few hundreds) of files to run test on (each test takes few minutes).

Running sequentially is not acceptable and neither all together. So I am looking for something like a producer-consumer.

I tried pipeline jobs and parallel command the following way:

def files = findFiles glob: 'test_files/*'
def branches = [:]

files.each{
    def test_command = "./test ${it}"
    branches["${it}"] = { sh "${test_command} ${it}"}
}

stage name:'run', concurrency:2
parallel branches
```

Problem:

All the tasks are launch at the same time (OOM and all the fun)

答:
Doesn't have the same introspection as the Jenkins parallel step, but since it seems not to support a fixed pool you can use xargs to achieve the same result:

```<code>def files = findFiles glob: 'test_files/*'
def branches = [:]

// there's probably a more efficient way to generate the list of commands
files.each{
    sh "echo './test ${it}' >> tests.txt"
}

sh 'cat tests.txt | xargs -L 1 -I {} -P 2 bash -c "{}"'
</code>```

The -P argument is the one that specifies a fixed number of 2 (or N) processes should always be running. Other tools like GNU Parallel offer even more tuning on how many processes should be used.

You can also try to use the lock step from the Lockable Resources plugin, the node step targeting a fixed number of executors. However this seems too much overhead to me unless your single tests are already taking tens of second each.

Title: Parallel run with jenkins

Body:
I have several (few hundreds) of files to run test on (each test takes few minutes).

Running sequentially is not acceptable and neither all together. So I am looking for something like a producer-consumer.

I tried pipeline jobs and parallel command the following way:

def files = findFiles glob: 'test_files/*'
def branches = [:]

files.each{
    def test_command = "./test ${it}"
    branches["${it}"] = { sh "${test_command} ${it}"}
}

stage name:'run', concurrency:2
parallel branches

Problem:

All the tasks are launch at the same time (OOM and all the fun)

Body:
Doesn't have the same introspection as the Jenkins parallel step, but since it seems not to support a fixed pool you can use xargs to achieve the same result:

def files = findFiles glob: 'test_files/*'
def branches = [:]

// there's probably a more efficient way to generate the list of commands
files.each{
    sh "echo './test ${it}' >> tests.txt"
}

sh 'cat tests.txt | xargs -L 1 -I {} -P 2 bash -c "{}"'

The -P argument is the one that specifies a fixed number of 2 (or N) processes should always be running. Other tools like GNU Parallel offer even more tuning on how many processes should be used.

You can also try to use the lock step from the Lockable Resources plugin, the node step targeting a fixed number of executors. However this seems too much overhead to me unless your single tests are already taking tens of second each.


问:
onLocationChanged not being called within the IndoorAtlas location manager
When testing I am able to receive updates from the onStatusChanged within the IALocationListener, but the onLocationChanged is not being called. Any ideas as to why this is?

I have followed the instructions from IndoorAtlas (http://docs.indooratlas.com/android/dev-guide/getting-user-location.html) as well as a video from YouTube (https://www.youtube.com/watch?v=2EXkV4xL5rg) but was still not able to get the location.

Do I have to be in the area that I have mapped or should it read the location no matter where I am?

```<code>package com.bignerdranch.android.indoormapping;

import android.Manifest;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.util.Log;

import com.indooratlas.android.sdk.IALocation;
import com.indooratlas.android.sdk.IALocationListener;
import com.indooratlas.android.sdk.IALocationManager;
import com.indooratlas.android.sdk.IALocationRequest;

public class MappingActivity extends FragmentActivity {

    private final int CODE_PERMISSIONS = 0;
    private IALocationManager mIALocationManager;
    private static final String TAG = "LocateActivity";

    private IALocationListener mIALocationListener = new IALocationListener() {
        @Override
        public void onLocationChanged(IALocation iaLocation) {
            Log.d(TAG, "Latitude: " + iaLocation.getLatitude());
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }
    };

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

        mIALocationManager = IALocationManager.create(this);

        // request permissions for coarse location and Wifi
        String[] neededPermissions = {
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION
        };
        ActivityCompat.requestPermissions( this, neededPermissions, CODE_PERMISSIONS );

        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.fragment_cont);

        if(fragment == null) {
            fragment = new MappingFragment();
            fm.beginTransaction()
                    .add(R.id.fragment_cont, fragment)
                    .commit();
        }
    }

    // handle any permissions that are denied
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onResume() {
        super.onResume();
        mIALocationManager.requestLocationUpdates(IALocationRequest.create(), mIALocationListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        mIALocationManager.removeLocationUpdates(mIALocationListener);
    }
}
</code>```

答: Here IndoorAtlas has given some code examples of their SDK. You should be able to find the issue.</p>

Body:
When testing I am able to receive updates from the onStatusChanged within the IALocationListener, but the onLocationChanged is not being called. Any ideas as to why this is?

I have followed the instructions from IndoorAtlas (http://docs.indooratlas.com/android/dev-guide/getting-user-location.html) as well as a video from YouTube (https://www.youtube.com/watch?v=2EXkV4xL5rg) but was still not able to get the location.

Do I have to be in the area that I have mapped or should it read the location no matter where I am?

package com.bignerdranch.android.indoormapping;

import android.Manifest;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.util.Log;

import com.indooratlas.android.sdk.IALocation;
import com.indooratlas.android.sdk.IALocationListener;
import com.indooratlas.android.sdk.IALocationManager;
import com.indooratlas.android.sdk.IALocationRequest;

public class MappingActivity extends FragmentActivity {

    private final int CODE_PERMISSIONS = 0;
    private IALocationManager mIALocationManager;
    private static final String TAG = "LocateActivity";

    private IALocationListener mIALocationListener = new IALocationListener() {
        @Override
        public void onLocationChanged(IALocation iaLocation) {
            Log.d(TAG, "Latitude: " + iaLocation.getLatitude());
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }
    };

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

        mIALocationManager = IALocationManager.create(this);

        // request permissions for coarse location and Wifi
        String[] neededPermissions = {
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION
        };
        ActivityCompat.requestPermissions( this, neededPermissions, CODE_PERMISSIONS );

        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.fragment_cont);

        if(fragment == null) {
            fragment = new MappingFragment();
            fm.beginTransaction()
                    .add(R.id.fragment_cont, fragment)
                    .commit();
        }
    }

    // handle any permissions that are denied
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onResume() {
        super.onResume();
        mIALocationManager.requestLocationUpdates(IALocationRequest.create(), mIALocationListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        mIALocationManager.removeLocationUpdates(mIALocationListener);
    }
}


问:
Can't submit form without reloading page
I build a link shortener,just for fun!
Everything works, but everytime I create a link and submit the form, the page reloads! I wanted to prevent that with onclick="return false;"but it didnt work.

```<code><input class="submit" type="submit" value="Create!"  />

$('#contactForm').submit(function () {
    sendContactForm();
    return false;
});
</code>```

But nothing works, the file is just stuck and doesn't do anything! What am I doing from ? This is the problem page https://viid.su
PHP

```<code>   require("db_config.php");
       $uid = 1;
      $flink = $_POST['url'];
      if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
        $html = "Error: invalid URL";
      } else {

        $db = mysqli_connect($host, $username, $password);
        $conn = new mysqli($host, $username, $password, $database);

          $id = substr(md5(time().$flink), 0, 5);
          if($conn->query("INSERT INTO `".$database."`.`link` (`id`, `flink`,`adonly`,`userid`) VALUES ('".$id."', '".$flink."','true','".$uid."');")) {
            $html = 'Your short URL is <a class="test" href="https://viid.su/'.$id.'">https://viid.su/'.$id.'</a>';
          } else {
            $html = "Error: cannot find database";
          }
        mysqli_close($db);
      }
</code>```

答:
Just change the <input type="submit" /> into something like <button onclick="return false;" id="shortenLinkButton">Send</button>

Then with jQuery you can catch the even like this:

```<code>// This code will be usable after the page has fully loaded
$(document).ready(function(){
  // Catch the onclick event
  $('#shortenLinkButton').on('click', function() {
    // do something
    alert('clicked the button, do your ajax stuff here after retrieving the data from the input');
  });
});
</code>```

Body:
I build a link shortener,just for fun!
Everything works, but everytime I create a link and submit the form, the page reloads! I wanted to prevent that with onclick="return false;"but it didnt work.

<input class="submit" type="submit" value="Create!"  />

$('#contactForm').submit(function () {
    sendContactForm();
    return false;
});

But nothing works, the file is just stuck and doesn't do anything! What am I doing from ? This is the problem page https://viid.su
PHP

   require("db_config.php");
       $uid = 1;
      $flink = $_POST['url'];
      if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
        $html = "Error: invalid URL";
      } else {

        $db = mysqli_connect($host, $username, $password);
        $conn = new mysqli($host, $username, $password, $database);

          $id = substr(md5(time().$flink), 0, 5);
          if($conn->query("INSERT INTO `".$database."`.`link` (`id`, `flink`,`adonly`,`userid`) VALUES ('".$id."', '".$flink."','true','".$uid."');")) {
            $html = 'Your short URL is https://viid.su/'.$id.'';
          } else {
            $html = "Error: cannot find database";
          }
        mysqli_close($db);
      }

Body:
Just change the <input type="submit" /> into something like <button onclick="return false;" id="shortenLinkButton">Send</button>

Then with jQuery you can catch the even like this:

// This code will be usable after the page has fully loaded
$(document).ready(function(){
  // Catch the onclick event
  $('#shortenLinkButton').on('click', function() {
    // do something
    alert('clicked the button, do your ajax stuff here after retrieving the data from the input');
  });
});


问:
PBKDF2 - What happens when generating 1024 bits key length with SHA512?
I have this code snippet to generate key with PBKDF2.

```<code>SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterations, length);
        SecretKey key = skf.generateSecret(spec);
        byte[] res = key.getEncoded();
</code>```

I am wondering how generating works when a key lengthis longer than specified SHA digest algorithm type?

For example - what happens when I set a key length of 1024 bits and use PBKDF2WithHmacSHA512 algorithm? Where are 512 bits generated?

答:
Per PBKDF2

```<code>dkLen is the desired length of the derived key
DK is the generated derived key
</code>```

Each hLen-bit block Ti of derived key DK, is computed as follows:

```<code>DK = T1 || T2 || ... || Tdklen/hlen
</code>```

The derived byte array can be an arbitrary length not based on the hash algorithm.

Body:
I have this code snippet to generate key with PBKDF2.

SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterations, length);
        SecretKey key = skf.generateSecret(spec);
        byte[] res = key.getEncoded();

I am wondering how generating works when a key lengthis longer than specified SHA digest algorithm type?

For example - what happens when I set a key length of 1024 bits and use PBKDF2WithHmacSHA512 algorithm? Where are 512 bits generated?

Body:
Per PBKDF2

dkLen is the desired length of the derived key
DK is the generated derived key

Each hLen-bit block Ti of derived key DK, is computed as follows:

DK = T1 || T2 || ... || Tdklen/hlen

The derived byte array can be an arbitrary length not based on the hash algorithm.


问:
Query on SQL Server stored procedure takes longer for specific data than for all data
I have a query in a stored procedure that is retrieving data from several tables of my SQL Server database. From my application I call this stored procedure with some parameters to filter the data.

The strange thing is that, for all data returned for "X" week of year (about 2600 records) it takes about 30 seconds to retrieve the data. But if I add a specific "center" filter for the same week of year (about 1800 records), it takes about 3 minutes to get the data!

If I run just the query, it works well (30 seconds for all data and about 22 seconds for filtered data). The issue is when I run the query through the stored procedure!

How is this possible? Why does filtered data is taking about x6 times than getting all data? Why am I missing? Am I writing the stored procedure correctly? How can I do this in a more efficient way?

My stored procedure code is something like this:

```<code>ALTER PROCEDURE EventMonitoring
    @EventType AS CHAR(1),
    @Year AS INT,
    @Week AS INT,
    @CenterID AS CHAR(2),
    @AreaID AS INT
AS
    DECLARE @SQLCommand AS VARCHAR(MAX)
    DECLARE @MessageError AS VARCHAR(MAX)

    SET @SQLCommand = ' SELECT ....
                   ....
                   ....
                   ....
                   FROM   Event E
                   INNER JOIN ...
                   INNER JOIN ...
                   INNER JOIN ...
                   WHERE E.EventYear = ' + CAST(@Year AS VARCHAR) +
                   ' And E.EventWeek = ' + CAST(@Week AS VARCHAR) +
                   ' And E.EventType = ' + CAST(@EventType AS VARCHAR)

    IF @Centro <> '-' --If application sends - as the parameter, it gets all centers
    BEGIN
        @SQLCommand = @SQLCommand + ' AND E.CenterID = ''' + @CenterID + ''''
    END

    IF @Area <> 0 --If application sends 0 as the parameter, it gets all  areas
    BEGIN
        @SQLCommand = @SQLCommand + ' AND E.AreaID = ' + CAST(@AreaID AS VARCHAR)
    END

    SET @SQLCommand = @SQLCommand + 'GROUP BY ....'

    BEGIN TRY
        EXEC(@SQLCommand)
    END TRY
    BEGIN CATCH
        ....
    END CATCH
</code>```

答:
No matter how this shakes out, I bet this can be solved by adding an additional column (CenterId) to an index.

When the difference comes down to 'when I add an additional column to the where clause, the query takes a whole lot longer', that indicates that the additional column is not covered by the index the query is able to use without that clause.

To fix that, find the existing index that query uses without the additional clause and add the additional column to the include() of that index, or make a new index (seems wasteful to make a whole new index to add one more int column though).

Find the index that is being used for Event with the fast query, and see if it includes CenterId. If you do not know how to find it, you basically need to check the execution plans. If you still can not find it, you can share your execution plans and we will help you find it. Share your execution plans using Paste The Plan @ brentozar.com here are the instructions: How to Use Paste the Plan.

I can only guess (vaguely) what the index is going to look like without knowing more about how Event joins to the rest of your query, but the index might look something like this, only missing CenterId:

```<code>create nonclustered index ix_Event_cover
  on dbo.Event(EventYear,EventWeek,EventType)
    include (CenterId, AreaID, [JoinColumns], [SelectedColumns])
</code>```

Body:
I have a query in a stored procedure that is retrieving data from several tables of my SQL Server database. From my application I call this stored procedure with some parameters to filter the data.

The strange thing is that, for all data returned for "X" week of year (about 2600 records) it takes about 30 seconds to retrieve the data. But if I add a specific "center" filter for the same week of year (about 1800 records), it takes about 3 minutes to get the data!

If I run just the query, it works well (30 seconds for all data and about 22 seconds for filtered data). The issue is when I run the query through the stored procedure!

How is this possible? Why does filtered data is taking about x6 times than getting all data? Why am I missing? Am I writing the stored procedure correctly? How can I do this in a more efficient way?

My stored procedure code is something like this:

ALTER PROCEDURE EventMonitoring
    @EventType AS CHAR(1),
    @Year AS INT,
    @Week AS INT,
    @CenterID AS CHAR(2),
    @AreaID AS INT
AS
    DECLARE @SQLCommand AS VARCHAR(MAX)
    DECLARE @MessageError AS VARCHAR(MAX)

    SET @SQLCommand = ' SELECT ....
                   ....
                   ....
                   ....
                   FROM   Event E
                   INNER JOIN ...
                   INNER JOIN ...
                   INNER JOIN ...
                   WHERE E.EventYear = ' + CAST(@Year AS VARCHAR) +
                   ' And E.EventWeek = ' + CAST(@Week AS VARCHAR) +
                   ' And E.EventType = ' + CAST(@EventType AS VARCHAR)

    IF @Centro <> '-' --If application sends - as the parameter, it gets all centers
    BEGIN
        @SQLCommand = @SQLCommand + ' AND E.CenterID = ''' + @CenterID + ''''
    END

    IF @Area <> 0 --If application sends 0 as the parameter, it gets all  areas
    BEGIN
        @SQLCommand = @SQLCommand + ' AND E.AreaID = ' + CAST(@AreaID AS VARCHAR)
    END

    SET @SQLCommand = @SQLCommand + 'GROUP BY ....'

    BEGIN TRY
        EXEC(@SQLCommand)
    END TRY
    BEGIN CATCH
        ....
    END CATCH

Body:
No matter how this shakes out, I bet this can be solved by adding an additional column (CenterId) to an index.

When the difference comes down to 'when I add an additional column to the where clause, the query takes a whole lot longer', that indicates that the additional column is not covered by the index the query is able to use without that clause.

To fix that, find the existing index that query uses without the additional clause and add the additional column to the include() of that index, or make a new index (seems wasteful to make a whole new index to add one more int column though).

Find the index that is being used for Event with the fast query, and see if it includes CenterId. If you do not know how to find it, you basically need to check the execution plans. If you still can not find it, you can share your execution plans and we will help you find it. Share your execution plans using Paste The Plan @ brentozar.com here are the instructions: How to Use Paste the Plan.

I can only guess (vaguely) what the index is going to look like without knowing more about how Event joins to the rest of your query, but the index might look something like this, only missing CenterId:

create nonclustered index ix_Event_cover
  on dbo.Event(EventYear,EventWeek,EventType)
    include (CenterId, AreaID, [JoinColumns], [SelectedColumns])


问:
"Unwind" to specific view controller from an arbitrary point in app
I want to shunt the user back to the initial "splash screen" of the app (the first view controller), so that the app can effectively "reset" and operate in offline mode.

Normally I'd use an unwind segue to push the user back to a specific view controller, but an unwind segue (if I understand correctly) needs to be explicitly created from storyboards. I need to effectively do an unwind from any point in the application, and I don't want to be adding unwind segues to all of my dozens of view controllers.

Is there a way to do this programmatically? Can you create an unwind segue on the fly?

My first attempt was to recursively call dismiss on the application's "top" UIViewController. It technically works but it feels like a kludge, doesn't look very good on the screen, and creates a variety of issues regarding the calling of viewDidAppear on each successive view controller that's popped to. Here's the code for it.

```<code>extension UIApplication {

    var topController: UIViewController? {
        var topController = keyWindow?.rootViewController
        while topController?.presentedViewController != nil {
            topController = topController?.presentedViewController
        }
        return topController
    }

    // Recursively dismiss until some condition is met
    func dismiss(until: @escaping ((UIViewController?)->Bool), completion: (()->Void)?) {
        var proxy: (()->Void) = { }
        let doDismiss: (()->Void) = {
            if !until(self.topController) {
                DispatchQueue.main.async {
                    self.topController?.dismiss(animated: false, completion: proxy)
                }
            } else {
                completion?()
            }
        }
        proxy = doDismiss
        doDismiss()
    }
}
</code>```

And it's called like:

```<code>UIApplication.shared.dismiss(until: { (topController) -> Bool in
    return topController is SplashScreenViewController
}, completion: nil)
</code>```

Is there a simpler solution?

答:
Sorry you can't create any kind of segue in the code itself they have to be setup in the storyboard.

How you achieve what you want and return to the initial view controller depends on how you have setup your controller hierarchy.  For example if you are using a UINavigationController and all the view controllers have been pushed onto it then you can just you can just use popToRootViewController(animated: Bool).  Anything other than that will depend but you will probably have to handle it manually.

You might need to rethink the structure of your view controller hierarchy.

Body:
I want to shunt the user back to the initial "splash screen" of the app (the first view controller), so that the app can effectively "reset" and operate in offline mode.

Normally I'd use an unwind segue to push the user back to a specific view controller, but an unwind segue (if I understand correctly) needs to be explicitly created from storyboards. I need to effectively do an unwind from any point in the application, and I don't want to be adding unwind segues to all of my dozens of view controllers.

Is there a way to do this programmatically? Can you create an unwind segue on the fly?

My first attempt was to recursively call dismiss on the application's "top" UIViewController. It technically works but it feels like a kludge, doesn't look very good on the screen, and creates a variety of issues regarding the calling of viewDidAppear on each successive view controller that's popped to. Here's the code for it.

extension UIApplication {

    var topController: UIViewController? {
        var topController = keyWindow?.rootViewController
        while topController?.presentedViewController != nil {
            topController = topController?.presentedViewController
        }
        return topController
    }

    // Recursively dismiss until some condition is met
    func dismiss(until: @escaping ((UIViewController?)->Bool), completion: (()->Void)?) {
        var proxy: (()->Void) = { }
        let doDismiss: (()->Void) = {
            if !until(self.topController) {
                DispatchQueue.main.async {
                    self.topController?.dismiss(animated: false, completion: proxy)
                }
            } else {
                completion?()
            }
        }
        proxy = doDismiss
        doDismiss()
    }
}

And it's called like:

UIApplication.shared.dismiss(until: { (topController) -> Bool in
    return topController is SplashScreenViewController
}, completion: nil)

Is there a simpler solution?


问:
Generic method to register/unregister event handler
I try to figure out a way to keep my event registration and un-registration in sync from my initialization and cleanup.
What I want is to be able to call a generic method to register or unregister an event and only pass a Boolean to give the operation.

I don't want to use with Window, but that was the for an easy sample.

```<code>class EventSample
{
    private Window myWindow;

    public EventSample(Window window)
    {
        myWindow = window;
        InitEvent(true);
    }

    ~EventSample()
    {
        InitEvent(false);
    }

    private void InitEvent(bool register)
    {
        // I want a generic similar to that
        RegisterEvent(register, myWindow.Activated, MyWindow_Activated);
        RegisterEvent(register,myWindow.Closed , MyWindow_Closed);
        RegisterEvent(register, myWindow.Closing ,MyWindow_Closing);
    }

    private void MyWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {

    }

    private void MyWindow_Closed(object sender, EventArgs e)
    {
    }

    private void MyWindow_Activated(object sender, EventArgs e)
    {

    }
}
</code>```

答:
I have faced similar problems with cleanup methods. I have solved this by keeping a list of actions to execute when disposing the window or control.

Something like this:

```<code>this.RegisterEvent
    ( () => this.Event += handler
    , () => this.Event -= handler
    );
</code>```

The RegisterEvent executes (delayed in my case) the event attachment:

```<code>private List<Action> unregisterEvents = new List<Action>();

private void RegisterEvent(Action registerAction, Action unregisterAction)
{
    registerAction.Invoke();

    unregisterEvents.Add(unregisterAction);
}
</code>```

On dispose, just walk over the unregister events:

```<code>foreach (Action a in unregisterEvents)
{
    a.Invoke();
}
</code>```

Body:
I try to figure out a way to keep my event registration and un-registration in sync from my initialization and cleanup.
What I want is to be able to call a generic method to register or unregister an event and only pass a Boolean to give the operation.

I don't want to use with Window, but that was the for an easy sample.

class EventSample
{
    private Window myWindow;

    public EventSample(Window window)
    {
        myWindow = window;
        InitEvent(true);
    }

    ~EventSample()
    {
        InitEvent(false);
    }

    private void InitEvent(bool register)
    {
        // I want a generic similar to that
        RegisterEvent(register, myWindow.Activated, MyWindow_Activated);
        RegisterEvent(register,myWindow.Closed , MyWindow_Closed);
        RegisterEvent(register, myWindow.Closing ,MyWindow_Closing);
    }

    private void MyWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {

    }

    private void MyWindow_Closed(object sender, EventArgs e)
    {
    }

    private void MyWindow_Activated(object sender, EventArgs e)
    {

    }
}

Body:
I have faced similar problems with cleanup methods. I have solved this by keeping a list of actions to execute when disposing the window or control.

Something like this:

this.RegisterEvent
    ( () => this.Event += handler
    , () => this.Event -= handler
    );

The RegisterEvent executes (delayed in my case) the event attachment:

private List<Action> unregisterEvents = new List<Action>();

private void RegisterEvent(Action registerAction, Action unregisterAction)
{
    registerAction.Invoke();

    unregisterEvents.Add(unregisterAction);
}

On dispose, just walk over the unregister events:

foreach (Action a in unregisterEvents)
{
    a.Invoke();
}


问:
How to limit a container's width to X when it contains a wider (>X) image?
I need my div element to be as wide as the screen even when its child image element is wider than that. Is that possible? I tried overflow: hidden on the div to no avail.

```<code><div>
    <img src="image.jpg">
</div>
</code>```

答:
I don't know your html so this answer might not be the only/best way.

Having overflow: hidden merely makes your div hide whatever content "spills out" of its box. However, by default a div will have it's width: auto, and that makes the div stretch to accommodate whatever children element it holds.

Simply by adding max-width: 100%, you force the div to stop growing beyond the width of its parent. This way the div will try to stretch for the sake of its children, but not far enough as to go against its parent.

In your case the image is trying to stretch the div more than it should, so overflow: hidden comes into play and hides the part of the image that surpasses the div's width.


问:
Building complex regex pattern using simple patterns
I am trying to use regex to extract some texts from textual data. Since some of the regex patterns are getting complex, I wanted to keep things simple for readability of code. Here is an example of what I did.

```<code>pattern3 = re.compile("[D|d]escription(:)?(\n)+(=*)(\n)+")
pattern4 = re.compile("[D|d]esired [A|a]ction(:)?((\n)+)(=*)| [R|r]equired [A|a]ction(:)?((\n)+)(=*)")

pattern = re.compile(pattern3 | pattern4)
</code>```

But I am getting error. How do I build complex pattern from these small patterns. I am using python's regex module. In fact, I wanted to break up pattern4 as well. But again, it didn't work.

答:
First guess: combine the strings, not the patterns</p>

```<code>import re

pattern3_str = "[D|d]escription(:)?(\n)+(=*)(\n)+"
pattern3 = re.compile(pattern3_str)
pattern4_str = "[D|d]esired [A|a]ction(:)?((\n)+)(=*)| [R|r]equired [A|a]ction(:)?((\n)+)(=*)"
pattern4 = re.compile(pattern4_str)

pattern = re.compile(pattern3_str + "|" + pattern4_str)
</code>```

Body:
I am trying to use regex to extract some texts from textual data. Since some of the regex patterns are getting complex, I wanted to keep things simple for readability of code. Here is an example of what I did.

pattern3 = re.compile("[D|d]escription(:)?(\n)+(=*)(\n)+")
pattern4 = re.compile("[D|d]esired [A|a]ction(:)?((\n)+)(=*)| [R|r]equired [A|a]ction(:)?((\n)+)(=*)")

pattern = re.compile(pattern3 | pattern4)

But I am getting error. How do I build complex pattern from these small patterns. I am using python's regex module. In fact, I wanted to break up pattern4 as well. But again, it didn't work.

Body:
First guess: combine the strings, not the patterns

import re

pattern3_str = "[D|d]escription(:)?(\n)+(=*)(\n)+"
pattern3 = re.compile(pattern3_str)
pattern4_str = "[D|d]esired [A|a]ction(:)?((\n)+)(=*)| [R|r]equired [A|a]ction(:)?((\n)+)(=*)"
pattern4 = re.compile(pattern4_str)

pattern = re.compile(pattern3_str + "|" + pattern4_str)


问:
Why does D3's focus on an input work only the first time?
It's possible to focus on an input field using D3, without even the need to go through setTimeout (I don't know why, but I'm not complaining).

But this only works the first time. After the second press on Set (i.e.: Set, Reset, Set), the input field does not receive focus. Why?

Setting a callback to focus after the transition is complete gives me an error.

```<code><!DOCTYPE HTML>
<head>
    <style>
        div { width: 300px; }
        div#outerdiv  { height: 500px; background-color: #ccc; }
        div#topdiv    { height: 400px; background-color: #dff; }
        div#bottomdiv { height: 0px;   background-color: #ffd; display: 'none' }
        input:focus { background-color: pink; }
    </style>
</head>
<body>
    <div id="outerdiv">
        <div id="topdiv">
            <button onclick=open_form();>Set</button>
            <button onclick=close_form();>Reset</button>
        </div>

        <div id="bottomdiv">
            <form action="javascript:close_form()">
                Name:
                <input type="text" id="myTextField" name="name">
                <input type="submit" name="submit" value="Submit">
            </form>
        </div>
    </div>

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

    <script>
        function open_form() {
            d3.select('#topdiv').transition().duration(500)
              .style('height', '100px');
            d3.select('#bottomdiv').transition().duration(500)
              .style('height', '300px').style('display', 'inline-block');

            d3.select("#myTextField").node().focus();
        }
        function close_form() {
            d3.select('#topdiv').transition().duration(500)
              .style('height', '390px');
            d3.select('#bottomdiv').transition().duration(500)
              .style('height', '10px').style('display', 'none');
        }
    </script>
</body>
</code>```

答:
It wasn't able to find #myTextField because it was mid-transition. You can fix this by removing the transition for display: inline-block, as seen below.</p>

```<code>function open_form() {
    d3.select('#topdiv').transition().duration(500)
      .style('height', '100px');
    d3.select('#bottomdiv').style('display', 'inline-block');
    d3.select('#bottomdiv').transition().duration(500)
      .style('height', '300px');
    d3.select("#myTextField").node().focus();
}
</code>```

Body:
It's possible to focus on an input field using D3, without even the need to go through setTimeout (I don't know why, but I'm not complaining).

But this only works the first time. After the second press on Set (i.e.: Set, Reset, Set), the input field does not receive focus. Why?

Setting a callback to focus after the transition is complete gives me an error.

<!DOCTYPE HTML>

            <button onclick=open_form();>Set</button>
            <button onclick=close_form();>Reset</button>

            <form action="javascript:close_form()">
                Name:
                <input type="text" id="myTextField" name="name">
                <input type="submit" name="submit" value="Submit">
            </form>

Body:
It wasn't able to find #myTextField because it was mid-transition. You can fix this by removing the transition for display: inline-block, as seen below.

function open_form() {
    d3.select('#topdiv').transition().duration(500)
      .style('height', '100px');
    d3.select('#bottomdiv').style('display', 'inline-block');
    d3.select('#bottomdiv').transition().duration(500)
      .style('height', '300px');
    d3.select("#myTextField").node().focus();
}


问:
How do I know when multiple background workers are finished?
So right now I have a method that calls a different method three times.

```<code>List<BackgroundWorker> bgws = new List<BackgroundWorker>();
AutoResetEvent _workerCompleted = new AutoResetEvent(false);

void methodA () {
    methodB(); //bw1
    methodB(); //bw2
    methodB(); //bw3

    //wait for the background workers that were kicked off above to finish
    _workerCompleted.WaitOne();

    Console.Writeline("hey");
}

void methodB() {
    BackgroundWorker bw = new BackgroundWorker();
    bw.WorkerReportsProgress = true;
    bw.WorkerSupportsCancellation = true;
    bgws.Add(bw);

    bw.DoWork += (sender, DoWorkEventArgs) => { bwWork(sender, DoWorkEventArgs, info); };
    bw.ProgressChanged += (sender, ProgressChangedEventArgs) => { bwProgressChanged(sender, ProgressChangedEventArgs, info); };
    bw.RunWorkerCompleted += (sender, RunWorkerCompletedEventArgs) => { bwCompleted(sender, RunWorkerCompletedEventArgs, info); };

    bw.RunWorkerAsync();

}
</code>```

The bwWork and bwProgressChanged events shouldn't matter too much. The former is just processing a file, the latter is updating a progress bar and label.

```<code>private void bwCompleted(object senderr,
System.ComponentModel.RunWorkerCompletedEventArgs e, SenderInfo info)
{
    BackgroundWorker bw = (BackgroundWorker)senderr;

    Console.WriteLine(Path.GetFileName(info.path) + " : Finished.");

    bgws.Remove(bw); //remove the bw from the list
    //remove events from bw
    bw.DoWork -= (sender, DoWorkEventArgs) => { bwWork(sender, DoWorkEventArgs, info); };
    bw.ProgressChanged -= (sender, ProgressChangedEventArgs) => { bwProgressChanged(sender, ProgressChangedEventArgs, info); };
    bw.RunWorkerCompleted -= (sender, RunWorkerCompletedEventArgs) => { bwCompleted(sender, RunWorkerCompletedEventArgs, info); };
    //dispose bw
    bw.Dispose();
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
    if (bgws.Count == 0) //if there are no more bw's, we're good to go
    {
        MessageBox.Show("Done.");
        bgws.Clear();
        _workerCompleted.Set();
    }

}
</code>```

So in the end, I want all of the background workers to finish what they're doing before "hey" is printed out. I tried using the AutoResetEvent and ManualResetEvent, yet nothing seemed to happen when they were present. What I mean is that none of the background workers even ran when I included them.

I would invoke a thread, but I'm a little reluctant because I was told background workers were the thing to use when doing background work and updating UI. Is there any way that I can wait on the three background workers so that I can continue on with my program?

答: Simple you don't use BackgroundWorker and switch to Tasks. Task.Run(() => Your work ); And after you do that you can use Task.WaitAll(task1,task2); You can switch any EAP to Tasks. And with async you can make this with ease.

Body:
So right now I have a method that calls a different method three times.

List<BackgroundWorker> bgws = new List<BackgroundWorker>();
AutoResetEvent _workerCompleted = new AutoResetEvent(false);

void methodA () {
    methodB(); //bw1
    methodB(); //bw2
    methodB(); //bw3

    //wait for the background workers that were kicked off above to finish
    _workerCompleted.WaitOne();

    Console.Writeline("hey");
}

void methodB() {
    BackgroundWorker bw = new BackgroundWorker();
    bw.WorkerReportsProgress = true;
    bw.WorkerSupportsCancellation = true;
    bgws.Add(bw);

    bw.DoWork += (sender, DoWorkEventArgs) => { bwWork(sender, DoWorkEventArgs, info); };
    bw.ProgressChanged += (sender, ProgressChangedEventArgs) => { bwProgressChanged(sender, ProgressChangedEventArgs, info); };
    bw.RunWorkerCompleted += (sender, RunWorkerCompletedEventArgs) => { bwCompleted(sender, RunWorkerCompletedEventArgs, info); };

    bw.RunWorkerAsync();

}

The bwWork and bwProgressChanged events shouldn't matter too much. The former is just processing a file, the latter is updating a progress bar and label.

private void bwCompleted(object senderr,
System.ComponentModel.RunWorkerCompletedEventArgs e, SenderInfo info)
{
    BackgroundWorker bw = (BackgroundWorker)senderr;

    Console.WriteLine(Path.GetFileName(info.path) + " : Finished.");

    bgws.Remove(bw); //remove the bw from the list
    //remove events from bw
    bw.DoWork -= (sender, DoWorkEventArgs) => { bwWork(sender, DoWorkEventArgs, info); };
    bw.ProgressChanged -= (sender, ProgressChangedEventArgs) => { bwProgressChanged(sender, ProgressChangedEventArgs, info); };
    bw.RunWorkerCompleted -= (sender, RunWorkerCompletedEventArgs) => { bwCompleted(sender, RunWorkerCompletedEventArgs, info); };
    //dispose bw
    bw.Dispose();
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
    if (bgws.Count == 0) //if there are no more bw's, we're good to go
    {
        MessageBox.Show("Done.");
        bgws.Clear();
        _workerCompleted.Set();
    }

}

So in the end, I want all of the background workers to finish what they're doing before "hey" is printed out. I tried using the AutoResetEvent and ManualResetEvent, yet nothing seemed to happen when they were present. What I mean is that none of the background workers even ran when I included them.

I would invoke a thread, but I'm a little reluctant because I was told background workers were the thing to use when doing background work and updating UI. Is there any way that I can wait on the three background workers so that I can continue on with my program?


问:
Angular 4 image not found in templateURL but works in template string
I'm using the Angular 4 universal starter https://github.com/ng-seed/universal

I'm having an issue with the templateURL finding images even though they render fine just using:

```<code>template: '<img src="assets/img/twitter.png" />
</code>```

When I put the same code in the templateURL: './home.component.html' I get:

```<code>Module not found: Error: Can't resolve './assets/img/twitter.png'
</code>```

Not sure how to troubleshoot this one.  The template renders all other HTML fine, but can't locate any images.  Any idea how to solve would be great.  thanks.

答:
Angular points to src/assets folder</p>

```<code>'<img src="/assets/img/twitter.png" />
</code>```

Body:
I'm using the Angular 4 universal starter https://github.com/ng-seed/universal

I'm having an issue with the templateURL finding images even though they render fine just using:

template: '

When I put the same code in the templateURL: './home.component.html' I get:

Module not found: Error: Can't resolve './assets/img/twitter.png'

Not sure how to troubleshoot this one.  The template renders all other HTML fine, but can't locate any images.  Any idea how to solve would be great.  thanks.

Body:
Angular points to src/assets folder

'<img src="/assets/img/twitter.png" />


问:
silent push notifications for opted out users
I would like to send a silent notification to my app users, to refresh the content.

I have read various articles on sending silent notification to opted out users. But, how do we do it? Most opted out users don't have device push tokens. How do you ping a device to send the silent push payload?

We currently use push tokens for opted in users to send a remote notification. But if iOS 8 and beyond allows to send silent notification to all the app users even if they are opted out, how do I send them without a token?

答: There are no possibility to send remote notifications to devices that are not registered with a device token. Also you can not send any notification if user doesnt allow the app to receive remote notifications.</p>


问:
How can I send unknown list of arguments to a python decorator -- when the decorator is a method of a different class?
This question is related to another question I just asked.

I have created a python decorator as shown below. I want this decorator to accept an unknown list of arguments. But there is an added wrinkle. The decorator is an instance method of another class:

```<code>#!/usr/bin/env python
from functools import wraps

class A:

    def my_decorator(self, func=None, **kwargs):

        def inner_function(decorated_function):

            def wrapped_func(*fargs, **fkwargs):
                print kwargs
                return decorated_function(*fargs, **fkwargs)
            return wrapped_func

        if func:
            return inner_function(func)
        else:
            return inner_function

class B:
    my_a = A()

    @my_a.my_decorator(arg_1="Yolo", arg2="Bolo")
    def my_func():
         print "Woo Hoo!"

my_B = B()
B.my_func()
</code>```

But this code below doesn't work:

```<code>Traceback (most recent call last):
  File "./decorator_test.py", line 30, in <module>
    B.my_func()
TypeError: unbound method wrapped_func() must be called with B instance as first argument (got nothing instead)
</code>```

How to fix it?

答:
Here's my approach to coding your decorator:

```<code>class A:
    def __init__(self, func=None, **kargs):
        self.args  = func
        self.kargs = kargs
    def __call__(self, decorated_function):
        def wrapper_func(*args, **kargs):
            print kargs
            return decorated_function(*args, **kwargs)
        if self.func:
            #..do something..
            return wrapper_func
        elif 'xyz' in self.kargs:
            #...do something else here..
            return wrapper_func
        else:
            ...

class B:
    @A(arg_1="Yolo", arg2="Bolo")              # A(...)(my_func)
    def my_func():
        print "Woo Hoo!"
</code>```

This is a typical way of coding decorators. Class A returns a callable object when called. The callable object of class A will be called automatically for decoration. When the callable object is called, its __call__ method gets triggered and its __call__ operator overloading method returns the wrapper function after performing some customization. The wrapper function is the function that wraps logic around your original function.

Body:
This question is related to another question I just asked.

I have created a python decorator as shown below. I want this decorator to accept an unknown list of arguments. But there is an added wrinkle. The decorator is an instance method of another class:

#!/usr/bin/env python
from functools import wraps

class A:

    def my_decorator(self, func=None, **kwargs):

        def inner_function(decorated_function):

            def wrapped_func(*fargs, **fkwargs):
                print kwargs
                return decorated_function(*fargs, **fkwargs)
            return wrapped_func

        if func:
            return inner_function(func)
        else:
            return inner_function

class B:
    my_a = A()

    @my_a.my_decorator(arg_1="Yolo", arg2="Bolo")
    def my_func():
         print "Woo Hoo!"

my_B = B()
B.my_func()

But this code below doesn't work:

Traceback (most recent call last):
  File "./decorator_test.py", line 30, in <module>
    B.my_func()
TypeError: unbound method wrapped_func() must be called with B instance as first argument (got nothing instead)

How to fix it?

Body:
Here's my approach to coding your decorator:

class A:
    def __init__(self, func=None, **kargs):
        self.args  = func
        self.kargs = kargs
    def __call__(self, decorated_function):
        def wrapper_func(*args, **kargs):
            print kargs
            return decorated_function(*args, **kwargs)
        if self.func:
            #..do something..
            return wrapper_func
        elif 'xyz' in self.kargs:
            #...do something else here..
            return wrapper_func
        else:
            ...

class B:
    @A(arg_1="Yolo", arg2="Bolo")              # A(...)(my_func)
    def my_func():
        print "Woo Hoo!"

This is a typical way of coding decorators. Class A returns a callable object when called. The callable object of class A will be called automatically for decoration. When the callable object is called, its __call__ method gets triggered and its __call__ operator overloading method returns the wrapper function after performing some customization. The wrapper function is the function that wraps logic around your original function.