问:
jQuery not showing correctly in aspx page
I'm trying to get this function to work in an aspx page but I'm having a rotten time.  Basically it works fine in a regular HTML page but in the aspx page, when click on the button all you can see is a sliver of the top part and on occasion (every 5th+ single button click & every double click) the message shows and fades like it should.  What am I missing?  Could it be getting tied up in the postback?

FIDDLE HERE

Code using in aspx page

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="checkTest.aspx.cs" Inherits="WebApplication2.checkTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#Button1").click(function () {
                    $(".message").stop(true,true).slideToggle().fadeOut(6000);
                });
            });
        </script>
    <style type="text/css">
    .message{height:70px;display:none;}
        .noChangesMessage{width:84px;padding:8px 8px;  background:#535353; -webkit-border-radius:5px; -moz-border-radius:5px; border-radius:5px; color:white;text-align:center;}
        .tipEnd{width:0;height:0;border-left:10px solid transparent;border-right:10px solid transparent;border-top:10px solid #535353;margin:0 auto;}

    </style>
</head>
<body>
    <form id="form1" runat="server">

    <br /><br /><br />
    <div>
    <div style="width:100px">
    <div style="height:70px">
                <div style="margin-bottom:5px;" class="message">
                    <div class="noChangesMessage">No changes were made!</div>
                    <div class="tipEnd"></div>
                </div></div>
            <div style="">
                <asp:Button ID="Button1" runat="server" Text="Save Changes"  />
            </div>
            </div>

    </div>

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

my code via view source for amit_g

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#Button1").click(function () {
                    $(".message").stop(true,true).slideToggle().fadeOut(6000);
                });
            });
        </script>
    <style type="text/css">.
    .message{height:70px;display:none;}
        .noChangesMessage{width:84px;padding:8px 8px;  background:#535353; -webkit-border-radius:5px; -moz-border-radius:5px; border-radius:5px; color:white;text-align:center;}
        .tipEnd{width:0;height:0;border-left:10px solid transparent;border-right:10px solid transparent;border-top:10px solid #535353;margin:0 auto;}
    </style>
</head>
<body>
    <form method="post" action="checkTest.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMjA0OTM4MTAwNGRkU+SP3bu4QJNH9S9XtdwPbEE8YODY/YlkotOt6l692s8=" />
</div>
<div class="aspNetHidden">
    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgKroLr3AwKM54rGBtLTfCTwYmYnb6l8tnp5jtojhvORYMJ6bPzAI+qbaDlU" />
</div>
    <br /><br /><br />
    <div>
    <div style="width:100px">
    <div style="height:70px">
                <div style="margin-bottom:5px;" class="message">
                    <div class="noChangesMessage">No changes were made!</div>
                    <div class="tipEnd"></div>
                </div></div>
            <div style="">
                <input type="submit" name="Button1" value="Save Changes" id="Button1" class="Button1" /></div>
            </div>
    </div>
    </form>
</body>
</html>
</code>```

答:
this has to do with asp.net dynamically naming html elements, one way you can get the Id value is to use clientId something like Button1.clinetId

```<code> $("#<%=Button1.ClientID %>").click(function () {
    $(".message").stop(true,true).slideToggle().fadeOut(6000);
});
</code>```

it's that simple

Body:
I'm trying to get this function to work in an aspx page but I'm having a rotten time.  Basically it works fine in a regular HTML page but in the aspx page, when click on the button all you can see is a sliver of the top part and on occasion (every 5th+ single button click & every double click) the message shows and fades like it should.  What am I missing?  Could it be getting tied up in the postback?

FIDDLE HERE

Code using in aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="checkTest.aspx.cs" Inherits="WebApplication2.checkTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

No changes were made!

                <asp:Button ID="Button1" runat="server" Text="Save Changes"  />

    </form>

my code via view source for amit_g

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>
</title>

    <form method="post" action="checkTest.aspx" id="form1">

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMjA0OTM4MTAwNGRkU+SP3bu4QJNH9S9XtdwPbEE8YODY/YlkotOt6l692s8=" />

    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgKroLr3AwKM54rGBtLTfCTwYmYnb6l8tnp5jtojhvORYMJ6bPzAI+qbaDlU" />

No changes were made!

                <input type="submit" name="Button1" value="Save Changes" id="Button1" class="Button1" />

    </form>

Body:
this has to do with asp.net dynamically naming html elements, one way you can get the Id value is to use clientId something like Button1.clinetId

 $("#<%=Button1.ClientID %>").click(function () {
    $(".message").stop(true,true).slideToggle().fadeOut(6000);
});

it's that simple


来源: stackexchange

问:
Add all files to a commit except a single file?
I have a bunch of files in a changeset, but I want to specifically ignore a single modified file. Looks like this after git status:

```<code># modified:   main/dontcheckmein.txt
# deleted:    main/plzcheckmein.c
# deleted:    main/plzcheckmein2.c
...
</code>```

Is there a way I can do git add but just ignore the one text file I don't want to touch? Something like:

```<code>git add -u -except main/dontcheckmein.txt
</code>```

答: You can try this: git add * && git reset main/dontcheckmein.txt

ContentLicense: CC BY-SA 3.0

Body:
I have a bunch of files in a changeset, but I want to specifically ignore a single modified file. Looks like this after git status:

# modified:   main/dontcheckmein.txt
# deleted:    main/plzcheckmein.c
# deleted:    main/plzcheckmein2.c
...

Is there a way I can do git add but just ignore the one text file I don't want to touch? Something like:

git add -u -except main/dontcheckmein.txt

ContentLicense: CC BY-SA 4.0


问:
Azure blob upload with content-md5 set
Goal: Upload a file to Azure Blob Storage and set MD5 that can be validated when a  user downloads the file.

Using Azure CLI Powershell.

```<code>Get-FileHash -Algorithm MD5 .\AutoSetup.zip
Algorithm       Hash                                             Path
---------       ----                                             ----
MD5             693EF0DB938308AC2C362F50F7CB9F9F                 C:\MyFiles\AutoSetup.zip

az storage blob upload --account-name mystorageaccount --container-name mycontainername --file AutoSetup.zip --name Autosetup2.zip --content-md5 693EF0DB938308AC2C362F50F7CB9F9F
Finished[#############################################################]  100.0000%
The MD5 value specified in the request is invalid. MD5 value must be 128 bits and base64 encoded. ErrorCode: InvalidMd5
<?xml version="1.0" encoding="utf-8"?><Error><Code>InvalidMd5</Code><Message>The MD5 value specified in the request is invalid. MD5 value must be 128 bits and base64 encoded.
RequestId:9f27334a-801e-0028-6db4-3539c5000000
Time:2020-05-29T12:28:23.7677258Z</Message></Error>
</code>```

Edit 1:

I've also attempted getting the hash this way

```<code>$someFilePath = "C:\MyFiles\AutoSetup.zip"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
Write-Host $hash
69-3E-F0-DB-93-83-08-AC-2C-36-2F-50-F7-CB-9F-9F
</code>```

It seems that no matter what I do, the MD5 that is returned for the file is 693EF0DB938308AC2C362F50F7CB9F9F but Azure won't take it...

Edit 2:

I've generated a random 128-bit string $B&E)H@McQfTjWnZ and proceeded to encode it in Base64 which gave me JEImRSlIQE1jUWZUalduWg== When I attempt to upload a blob with THAT hash, I get a different error message:

```<code>The MD5 value specified in the request did not match with the MD5 value calculated by the server. ErrorCode: Md5Mismatch
</code>```

The above makes sense, cause I just created a random 128 bit base64 encoded hash. However, now I am wondering why the Powershell's Get-FileHash command gives me what seems to be incorrect?

What can be causing the error?

答:
I wanted to add my own "solution" to this, just in case someone prefers this approach.

Approach 1 is described in the answer by Gaurav. We read the bytes from the file, compute MD5, and encode it with Base64. This will result in MD5 string that az storage blob upload will validate and accept. This seems to be the correct way.

Approach 2 is to upload the file without setting content-md5 and update it after.

Get MD5 hash

```<code>Get-FileHash -Algorithm MD5 .\AutoSetup.zip
Algorithm       Hash                                             Path
---------       ----                                             ----
MD5             693EF0DB938308AC2C362F50F7CB9F9F                 C:\MyFiles\AutoSetup.zip
</code>```

Upload the blob without MD5

```<code>az storage blob upload --account-name mystorageaccount --container-name mycontainername --file AutoSetup.zip --name Autosetup2.zip
Finished[#############################################################]  100.0000%
</code>```

Update the blob with content-md5. We can write anything we want to it here, so using the MD5 from earlier is fine!

```<code>az storage blob update --account-name mystorageaccount --container-name mycontainername --name Autosetup2.zip -- content-md5 693EF0DB938308AC2C362F50F7CB9F9F
</code>```

I don't know how correct the 2nd approach is, but it will work nonetheless.

Title: Azure blob upload with content-md5 set

Body:
Goal: Upload a file to Azure Blob Storage and set MD5 that can be validated when a  user downloads the file.

Using Azure CLI Powershell.

Get-FileHash -Algorithm MD5 .\AutoSetup.zip
Algorithm       Hash                                             Path
---------       ----                                             ----
MD5             693EF0DB938308AC2C362F50F7CB9F9F                 C:\MyFiles\AutoSetup.zip

az storage blob upload --account-name mystorageaccount --container-name mycontainername --file AutoSetup.zip --name Autosetup2.zip --content-md5 693EF0DB938308AC2C362F50F7CB9F9F
Finished[#############################################################]  100.0000%
The MD5 value specified in the request is invalid. MD5 value must be 128 bits and base64 encoded. ErrorCode: InvalidMd5
<?xml version="1.0" encoding="utf-8"?><Error>InvalidMd5<Message>The MD5 value specified in the request is invalid. MD5 value must be 128 bits and base64 encoded.
RequestId:9f27334a-801e-0028-6db4-3539c5000000
Time:2020-05-29T12:28:23.7677258Z</Message></Error>

Edit 1:

I've also attempted getting the hash this way

$someFilePath = "C:\MyFiles\AutoSetup.zip"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
Write-Host $hash
69-3E-F0-DB-93-83-08-AC-2C-36-2F-50-F7-CB-9F-9F

It seems that no matter what I do, the MD5 that is returned for the file is 693EF0DB938308AC2C362F50F7CB9F9F but Azure won't take it...

Edit 2:

I've generated a random 128-bit string $B&E)H@McQfTjWnZ and proceeded to encode it in Base64 which gave me JEImRSlIQE1jUWZUalduWg== When I attempt to upload a blob with THAT hash, I get a different error message:

The MD5 value specified in the request did not match with the MD5 value calculated by the server. ErrorCode: Md5Mismatch

The above makes sense, cause I just created a random 128 bit base64 encoded hash. However, now I am wondering why the Powershell's Get-FileHash command gives me what seems to be incorrect?

What can be causing the error?

Body:
I wanted to add my own "solution" to this, just in case someone prefers this approach.

Approach 1 is described in the answer by Gaurav. We read the bytes from the file, compute MD5, and encode it with Base64. This will result in MD5 string that az storage blob upload will validate and accept. This seems to be the correct way.

Approach 2 is to upload the file without setting content-md5 and update it after.

Get MD5 hash

Get-FileHash -Algorithm MD5 .\AutoSetup.zip
Algorithm       Hash                                             Path
---------       ----                                             ----
MD5             693EF0DB938308AC2C362F50F7CB9F9F                 C:\MyFiles\AutoSetup.zip

Upload the blob without MD5

az storage blob upload --account-name mystorageaccount --container-name mycontainername --file AutoSetup.zip --name Autosetup2.zip
Finished[#############################################################]  100.0000%

Update the blob with content-md5. We can write anything we want to it here, so using the MD5 from earlier is fine!

az storage blob update --account-name mystorageaccount --container-name mycontainername --name Autosetup2.zip -- content-md5 693EF0DB938308AC2C362F50F7CB9F9F

I don't know how correct the 2nd approach is, but it will work nonetheless.


问:
DoCmd.RunSavedImportExport - Returns nothing when used on older computers, but works on newer computers. Ram Management?
I currently have to load many SQL_Developer 'Loader' files into an Access DB on bi-weekly basis and the machine that does the import can be random. The code below works fine on a newer computer (i5 16gb ram, i7 16gb ram). For some reason though it will not load anything into the designated table after I call imexImport_LoaderFile a few times on a less than great computer (i3 8gb of ram, various laptops). It works for the first few and then as it goes down the list of calls to the imexImport_LoaderFile function it will just stop on a random one and not load the information into the access table. If I restart the computer it can get further down the list or imexImport_LoaderFile calls. The table it fails on is random, but after each subsequent try it gets less and less further down the list of imexImport_LoaderFile calls. I can then give up on the sad computer walk over to a newer model and it loads just fine from begging to end. I am assuming its a memory management issue, but I am clearing my objects in the function so I'm really stumped here. Any input at all would be amazing. Oh, and the source file has to be LOADER files which is why I am even using RunSavedImportExport.</p>

```<code>Sub XYZ
do things..

ColNames = Array("a", "b", "c", "d", "e", "f", "g")
CurrentTempTableMaxDate = imexImport_LoaderFile(FilePath, FileName, AccessTableNameTemp, AccessTableName, ColNames)
If CurrentTempTableMaxDate <= DBTablesMaxDate Then Err.Raise Number:=10002
ColNames = Array("1", "2", "3", "4", "5", "6", "7")
CurrentTempTableMaxDate = imexImport_LoaderFile(FilePath, FileName, AccessTableNameTemp, AccessTableName, ColNames)
If CurrentTempTableMaxDate <= DBTablesMaxDate Then Err.Raise Number:=10002
ColNames = Array("a1", "b2", "c3", "d4", "e5", "f6", "g7")
CurrentTempTableMaxDate = imexImport_LoaderFile(FilePath, FileName, AccessTableNameTemp, AccessTableName, ColNames)
If CurrentTempTableMaxDate <= DBTablesMaxDate Then Err.Raise Number:=10002

do other things...
end sub

Public Function imexImport_LoaderFile(ByVal FilePath As String, ByVal FileName As String, ByVal AccessTempTableName As String, ByVal AccessTableName As String, ByVal ColNames As Variant) As Date
Dim name_of_spec As String
Dim imexObjs As Object
Dim ColNumber As Integer
Dim xml As String
name_of_spec = "imspec" & FileName
On Error Resume Next
If CurrentProject.ImportExportSpecifications.Count > 0 Then
    If Err.Number = 0 Then
        Set imexObjs = CurrentProject.ImportExportSpecifications
        For Each imexObj In imexObjs
            If imexObj.NAME = name_of_spec Then imexObj.Delete
        Next
        Set imexObjs = Nothing
    End If
End If

If TableExist(AccessTempTableName) Then DoCmd.DeleteObject acTable = acDefault, AccessTempTableName
LoaderFile_Cleanup (FilePath & FileName)

xml = ""
xml = xml & "<?xml version=""1.0"" encoding=""utf-8"" ?>" & vbCrLf
xml = xml & "<ImportExportSpecification Path=" & Chr(34) & FilePath & FileName & Chr(34) & " xmlns=""urn:www.microsoft.com/office/access/imexspec"">" & vbCrLf
xml = xml & "   <ImportText TextFormat=""Delimited"" FirstRowHasNames=""0"" FieldDelimiter=""|"" CodePage=""437"" Destination=" & Chr(34) & AccessTempTableName & Chr(34) & " >" & vbCrLf
xml = xml & "      <DateFormat DateOrder=""MDY"" DateDelimiter=""/"" TimeDelimiter="":"" FourYearDates=""true"" DatesLeadingZeros=""false"" />" & vbCrLf
xml = xml & "      <NumberFormat DecimalSymbol=""."" />" & vbCrLf
xml = xml & "           <Columns PrimaryKey=""{none}"">" & vbCrLf

For ColNumber = LBound(ColNames) To UBound(ColNames)
xml = xml & "                    <Column Name=""Col" & ColNumber + 1 & """ FieldName=""" & ColNames(ColNumber) & """ Indexed=""NO""               SkipColumn=""false"" DataType=""Text""    Width=""12"" />" & vbCrLf
Next ColNumber

xml = xml & "         </Columns>" & vbCrLf
xml = xml & "     </ImportText>" & vbCrLf
xml = xml & "</ImportExportSpecification>"
'''debug.print xml
CurrentProject.ImportExportSpecifications.Add name_of_spec, Trim(xml)
DoCmd.RunSavedImportExport name_of_spec
imexImport_LoaderFile = DMax("[MEGA_EFFDT]", "[" & AccessTempTableName & "]") 'Format(DMax("[EXPORTDATE]", "[" & AccessTempTableName & "]"), "mm/dd/yyyy") 'CDate(Int(DMax("[EXPORTDATE]", "[" & AccessTempTableName & "]")))
''debug.print imexImport_LoaderFile
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, AccessTempTableName, CID_BE_Dir & AccessTempTableName, True

CleanExitTask:
Set imexObjs = Nothing
End Function
</code>```

答:
ok so this isn't really a fix, but its a work around that seems to work on the network I am on. I'm only posting it here in case it helps someone else because this has been a nightmare on my end. My best guess is its a network/anti virus issues when using the imex spec and muliple large files. Anyway, my workaround was to just add a retry. Now when the import fails it just trys it again. So far it has worked on every second try when and if it comes up.</p>

```<code>Public Function imexImport_LoaderFile(ByVal FilePath As String, ByVal FileName As String, ByVal AccessTempTableName As String, ByVal AccessTableName As String, ByVal ColNames As Variant) As Date
Dim name_of_spec As String
Dim imexObjs As Object
Dim ColNumber As Integer
Dim xml As String
name_of_spec = "imspec" & FileName
On Error Resume Next

retry_import:
If CurrentProject.ImportExportSpecifications.Count > 0 Then
    If Err.Number = 0 Then
        Set imexObjs = CurrentProject.ImportExportSpecifications
        For Each imexObj In imexObjs
            If imexObj.NAME = name_of_spec Then imexObj.Delete
        Next
        Set imexObjs = Nothing
    End If
End If

LoaderFile_Cleanup (FilePath & FileName)

xml = ""
xml = xml & "<?xml version=""1.0"" encoding=""utf-8"" ?>" & vbCrLf
xml = xml & "<ImportExportSpecification Path=" & Chr(34) & FilePath & FileName & Chr(34) & " xmlns=""urn:www.microsoft.com/office/access/imexspec"">" & vbCrLf
xml = xml & "   <ImportText TextFormat=""Delimited"" FirstRowHasNames=""0"" FieldDelimiter=""|"" CodePage=""437"" AppendToTable=" & Chr(34) & AccessTempTableName & Chr(34) & " >" & vbCrLf
xml = xml & "      <DateFormat DateOrder=""MDY"" DateDelimiter=""/"" TimeDelimiter="":"" FourYearDates=""true"" DatesLeadingZeros=""false"" />" & vbCrLf
xml = xml & "      <NumberFormat DecimalSymbol=""."" />" & vbCrLf
xml = xml & "           <Columns PrimaryKey=""{none}"">" & vbCrLf

For ColNumber = LBound(ColNames) To UBound(ColNames)
        xml = xml & "                    <Column Name=""Col" & ColNumber + 1 & """ FieldName=""" & ColNames(ColNumber) & """ Indexed=""NO""               SkipColumn=""false"" DataType=""Text""    Width=""12"" />" & vbCrLf
Next ColNumber

xml = xml & "         </Columns>" & vbCrLf
xml = xml & "     </ImportText>" & vbCrLf
xml = xml & "</ImportExportSpecification>"
'''debug.print xml
CurrentProject.ImportExportSpecifications.Add name_of_spec, Trim(xml)
DoCmd.RunSavedImportExport name_of_spec
DoEvents
imexImport_LoaderFile = DMax("[MEGA_EFFDT]", "[" & AccessTempTableName & "]") 'Format(DMax("[EXPORTDATE]", "[" & AccessTempTableName & "]"), "mm/dd/yyyy") 'CDate(Int(DMax("[EXPORTDATE]", "[" & AccessTempTableName & "]")))
''debug.print imexImport_LoaderFile

If DCount("EMPLID", AccessTempTableName) = 0 Then
    If MsgBox(FileName & " import failed. Would you like to retry?", vbYesNo) = vbYes Then
        GoTo retry_import
    End If
End If
CleanExitTask:
Set imexObjs = Nothing
End Function
</code>```

Body:
I currently have to load many SQL_Developer 'Loader' files into an Access DB on bi-weekly basis and the machine that does the import can be random. The code below works fine on a newer computer (i5 16gb ram, i7 16gb ram). For some reason though it will not load anything into the designated table after I call imexImport_LoaderFile a few times on a less than great computer (i3 8gb of ram, various laptops). It works for the first few and then as it goes down the list of calls to the imexImport_LoaderFile function it will just stop on a random one and not load the information into the access table. If I restart the computer it can get further down the list or imexImport_LoaderFile calls. The table it fails on is random, but after each subsequent try it gets less and less further down the list of imexImport_LoaderFile calls. I can then give up on the sad computer walk over to a newer model and it loads just fine from begging to end. I am assuming its a memory management issue, but I am clearing my objects in the function so I'm really stumped here. Any input at all would be amazing. Oh, and the source file has to be LOADER files which is why I am even using RunSavedImportExport.

Sub XYZ
do things..

ColNames = Array("a", "b", "c", "d", "e", "f", "g")
CurrentTempTableMaxDate = imexImport_LoaderFile(FilePath, FileName, AccessTableNameTemp, AccessTableName, ColNames)
If CurrentTempTableMaxDate <= DBTablesMaxDate Then Err.Raise Number:=10002
ColNames = Array("1", "2", "3", "4", "5", "6", "7")
CurrentTempTableMaxDate = imexImport_LoaderFile(FilePath, FileName, AccessTableNameTemp, AccessTableName, ColNames)
If CurrentTempTableMaxDate <= DBTablesMaxDate Then Err.Raise Number:=10002
ColNames = Array("a1", "b2", "c3", "d4", "e5", "f6", "g7")
CurrentTempTableMaxDate = imexImport_LoaderFile(FilePath, FileName, AccessTableNameTemp, AccessTableName, ColNames)
If CurrentTempTableMaxDate <= DBTablesMaxDate Then Err.Raise Number:=10002

do other things...
end sub

Public Function imexImport_LoaderFile(ByVal FilePath As String, ByVal FileName As String, ByVal AccessTempTableName As String, ByVal AccessTableName As String, ByVal ColNames As Variant) As Date
Dim name_of_spec As String
Dim imexObjs As Object
Dim ColNumber As Integer
Dim xml As String
name_of_spec = "imspec" & FileName
On Error Resume Next
If CurrentProject.ImportExportSpecifications.Count > 0 Then
    If Err.Number = 0 Then
        Set imexObjs = CurrentProject.ImportExportSpecifications
        For Each imexObj In imexObjs
            If imexObj.NAME = name_of_spec Then imexObj.Delete
        Next
        Set imexObjs = Nothing
    End If
End If

If TableExist(AccessTempTableName) Then DoCmd.DeleteObject acTable = acDefault, AccessTempTableName
LoaderFile_Cleanup (FilePath & FileName)

xml = ""
xml = xml & "<?xml version=""1.0"" encoding=""utf-8"" ?>" & vbCrLf
xml = xml & "<ImportExportSpecification Path=" & Chr(34) & FilePath & FileName & Chr(34) & " xmlns=""urn:www.microsoft.com/office/access/imexspec"">" & vbCrLf
xml = xml & "   <ImportText TextFormat=""Delimited"" FirstRowHasNames=""0"" FieldDelimiter=""|"" CodePage=""437"" Destination=" & Chr(34) & AccessTempTableName & Chr(34) & " >" & vbCrLf
xml = xml & "      <DateFormat DateOrder=""MDY"" DateDelimiter=""/"" TimeDelimiter="":"" FourYearDates=""true"" DatesLeadingZeros=""false"" />" & vbCrLf
xml = xml & "      <NumberFormat DecimalSymbol=""."" />" & vbCrLf
xml = xml & "           <Columns PrimaryKey=""{none}"">" & vbCrLf

For ColNumber = LBound(ColNames) To UBound(ColNames)
xml = xml & "                    <Column Name=""Col" & ColNumber + 1 & """ FieldName=""" & ColNames(ColNumber) & """ Indexed=""NO""               SkipColumn=""false"" DataType=""Text""    Width=""12"" />" & vbCrLf
Next ColNumber

xml = xml & "         </Columns>" & vbCrLf
xml = xml & "     </ImportText>" & vbCrLf
xml = xml & "</ImportExportSpecification>"
'''debug.print xml
CurrentProject.ImportExportSpecifications.Add name_of_spec, Trim(xml)
DoCmd.RunSavedImportExport name_of_spec
imexImport_LoaderFile = DMax("[MEGA_EFFDT]", "[" & AccessTempTableName & "]") 'Format(DMax("[EXPORTDATE]", "[" & AccessTempTableName & "]"), "mm/dd/yyyy") 'CDate(Int(DMax("[EXPORTDATE]", "[" & AccessTempTableName & "]")))
''debug.print imexImport_LoaderFile
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, AccessTempTableName, CID_BE_Dir & AccessTempTableName, True

CleanExitTask:
Set imexObjs = Nothing
End Function

Body:
ok so this isn't really a fix, but its a work around that seems to work on the network I am on. I'm only posting it here in case it helps someone else because this has been a nightmare on my end. My best guess is its a network/anti virus issues when using the imex spec and muliple large files. Anyway, my workaround was to just add a retry. Now when the import fails it just trys it again. So far it has worked on every second try when and if it comes up.

Public Function imexImport_LoaderFile(ByVal FilePath As String, ByVal FileName As String, ByVal AccessTempTableName As String, ByVal AccessTableName As String, ByVal ColNames As Variant) As Date
Dim name_of_spec As String
Dim imexObjs As Object
Dim ColNumber As Integer
Dim xml As String
name_of_spec = "imspec" & FileName
On Error Resume Next

retry_import:
If CurrentProject.ImportExportSpecifications.Count > 0 Then
    If Err.Number = 0 Then
        Set imexObjs = CurrentProject.ImportExportSpecifications
        For Each imexObj In imexObjs
            If imexObj.NAME = name_of_spec Then imexObj.Delete
        Next
        Set imexObjs = Nothing
    End If
End If

LoaderFile_Cleanup (FilePath & FileName)

xml = ""
xml = xml & "<?xml version=""1.0"" encoding=""utf-8"" ?>" & vbCrLf
xml = xml & "<ImportExportSpecification Path=" & Chr(34) & FilePath & FileName & Chr(34) & " xmlns=""urn:www.microsoft.com/office/access/imexspec"">" & vbCrLf
xml = xml & "   <ImportText TextFormat=""Delimited"" FirstRowHasNames=""0"" FieldDelimiter=""|"" CodePage=""437"" AppendToTable=" & Chr(34) & AccessTempTableName & Chr(34) & " >" & vbCrLf
xml = xml & "      <DateFormat DateOrder=""MDY"" DateDelimiter=""/"" TimeDelimiter="":"" FourYearDates=""true"" DatesLeadingZeros=""false"" />" & vbCrLf
xml = xml & "      <NumberFormat DecimalSymbol=""."" />" & vbCrLf
xml = xml & "           <Columns PrimaryKey=""{none}"">" & vbCrLf

For ColNumber = LBound(ColNames) To UBound(ColNames)
        xml = xml & "                    <Column Name=""Col" & ColNumber + 1 & """ FieldName=""" & ColNames(ColNumber) & """ Indexed=""NO""               SkipColumn=""false"" DataType=""Text""    Width=""12"" />" & vbCrLf
Next ColNumber

xml = xml & "         </Columns>" & vbCrLf
xml = xml & "     </ImportText>" & vbCrLf
xml = xml & "</ImportExportSpecification>"
'''debug.print xml
CurrentProject.ImportExportSpecifications.Add name_of_spec, Trim(xml)
DoCmd.RunSavedImportExport name_of_spec
DoEvents
imexImport_LoaderFile = DMax("[MEGA_EFFDT]", "[" & AccessTempTableName & "]") 'Format(DMax("[EXPORTDATE]", "[" & AccessTempTableName & "]"), "mm/dd/yyyy") 'CDate(Int(DMax("[EXPORTDATE]", "[" & AccessTempTableName & "]")))
''debug.print imexImport_LoaderFile

If DCount("EMPLID", AccessTempTableName) = 0 Then
    If MsgBox(FileName & " import failed. Would you like to retry?", vbYesNo) = vbYes Then
        GoTo retry_import
    End If
End If
CleanExitTask:
Set imexObjs = Nothing
End Function


问:
How to cancel requests incase of triggering them using forkJoin Rxjs , Angular
I have a set of 6 http get requests which I have to make irrespective of their sequence on a button click.I am using forkJoin for that purpose

```<code><button click="getData()">Get Data</button>

getData(){

  const ids = [1,2,3,4,5,6];

  const obs = ids.map(id => this.http.get('<my url>/' + id)

  forkJoin(...obs).subscribe(res => console.log(res));

}
</code>```

If a user clicks on the button multiple time, is there a way I could cancel previous uncompleted requests and only make new fresh calls to the backend ?

I did some research and understood switchMap operator helps in cancelling requests but I am not sure how I would be using it here.

Please help

答:
I think, the operator you are looking for is ExhaustMap

The older version of ExhaustMap is the flatMapFirst() operator which propagates data from the first mapped observable, and it only goes to the next when it finishes discarding all the other observables before finishing.

Body:
I have a set of 6 http get requests which I have to make irrespective of their sequence on a button click.I am using forkJoin for that purpose

<button click="getData()">Get Data</button>

getData(){

  const ids = [1,2,3,4,5,6];

  const obs = ids.map(id => this.http.get('<my url>/' + id)

  forkJoin(...obs).subscribe(res => console.log(res));

}

If a user clicks on the button multiple time, is there a way I could cancel previous uncompleted requests and only make new fresh calls to the backend ?

I did some research and understood switchMap operator helps in cancelling requests but I am not sure how I would be using it here.

Please help


问:
How to find derivative in Python using SymPy
I want to find derivative of a certain function inputted by the user.

```<code>x = np.linspace(-5,5)

print('Options are:')
print('1. y = x')
print('2. y = ax^2')
print('3. y = k(x-a)(x-b)')
print('4. y = k(x-a)(x-b)(x-c)')

n = int(input('Your option is: '))

if n == 1:
    func = x
    plt.plot(x,func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        print('Derivative is 1')
    else:
        print('Done')

elif n == 2:
    a = int(input('Enter a value for a: '))
    func = a*x**2
    plt.plot(x,func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        x = sp.Symbol('x')
        print(sp.diff(func,x))
    else:
        print('Done')
</code>```

When n == 2,
i will need the user to input the 'a' value for the ax^2 function.
The code will then plot the graph ax^2.
Then proceeds to ask whether the user wants the derivative of the function.
In this part I'm confused because with the syntax i used above, it doesnt show the derivative, but it instead shows a list of 0s like below.

```<code>1. y = x
2. y = ax^2
3. y = k(x-a)(x-b)
4. y = k(x-a)(x-b)(x-c)
Your option is: 2
Enter a value for a: 3
Do you wanna find its derivative? (Y/N)Y
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code>```

How do i fix this problem?

答:
The problem happens at the line where you set func = a*x**2. As you can see, x is a vector (not a symbol yet). Which means that func is also a vector. When func gets passed to sp.diff it's no longer a function, it's a vector now which lead to that problem.

So, you need to change the sp.diff line to be like so:

```<code>sp.diff(a*x**2, x)
# 6*x (when a=3)
</code>```

Sidenote

It's a very bad idea to use x as both a variable and a symbol. It's messy and will lead to a lot of problems later.

Body:
I want to find derivative of a certain function inputted by the user.

x = np.linspace(-5,5)

print('Options are:')
print('1. y = x')
print('2. y = ax^2')
print('3. y = k(x-a)(x-b)')
print('4. y = k(x-a)(x-b)(x-c)')

n = int(input('Your option is: '))

if n == 1:
    func = x
    plt.plot(x,func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        print('Derivative is 1')
    else:
        print('Done')

elif n == 2:
    a = int(input('Enter a value for a: '))
    func = a*x**2
    plt.plot(x,func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        x = sp.Symbol('x')
        print(sp.diff(func,x))
    else:
        print('Done')

When n == 2,
i will need the user to input the 'a' value for the ax^2 function.
The code will then plot the graph ax^2.
Then proceeds to ask whether the user wants the derivative of the function.
In this part I'm confused because with the syntax i used above, it doesnt show the derivative, but it instead shows a list of 0s like below.

1. y = x
2. y = ax^2
3. y = k(x-a)(x-b)
4. y = k(x-a)(x-b)(x-c)
Your option is: 2
Enter a value for a: 3
Do you wanna find its derivative? (Y/N)Y
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

How do i fix this problem?

Body:
The problem happens at the line where you set func = a*x**2. As you can see, x is a vector (not a symbol yet). Which means that func is also a vector. When func gets passed to sp.diff it's no longer a function, it's a vector now which lead to that problem.

So, you need to change the sp.diff line to be like so:

sp.diff(a*x**2, x)
# 6*x (when a=3)

Sidenote

It's a very bad idea to use x as both a variable and a symbol. It's messy and will lead to a lot of problems later.


问:
Jenkins: Passing user defined variables to Email-Ext plugin
I'm using the Email-Ext plugin to send a results email at the end of my build in the post build stage of a declarative pipeline.  In the body of the email I'm trying to insert some environment variables and some user defined environment variables.

The built in variables show up fine, however any user defined variables I define are just empty in the body of the email or don't work in the attachmentPattern field either:

My environment variables:

```<code>pipeline {
    agent any
    environment {
        buildFolder = "build_${BUILD_NUMBER}"
        robotFolder = "build_${BUILD_NUMBER}/robotDemo"
        serverName = "abc123"
        robotResults = "${buildFolder}/*.txt"
    }
</code>```

The email-ext format I am using in my post{} build:

```<code>emailext attachLog: true, attachmentsPattern: 'build_${env.BUILD_NUMBER}/Robot_Results.txt', body: '<b>Job Name:</b> ${ENV, var="JOB_NAME"}<br><b>Build Number:</b> ${ENV, var="BUILD_NUMBER"}<br><br><b>Build URL:</b><br>${ENV, var="BUILD_URL"}<br><br><b>Log Files:<br><br><br>```${BUILD_LOG_EXCERPT, start="^====", end="^report.html"}``````${ENV, var="serverName"}```', mimeType: 'text/html', subject: 'ABS Results', to: 'richard.scott@sap.com'

</code>```

For example:  ${ENV, var="JOB_NAME"}, shows up fine.  However  ${ENV, var="serverName"} doesn't show at all.

I've tried variations such as...

${serverName}

   ${env.serverName}

...but they don't work either.

Any ideas how to use user defined environment variables like 'serverName' above in the email-ext plug-in?

Thanks & best regards, Richard.

答:
You’re using single quotes, but only double quotes allow variables to be interpolated.

I would suggest you to use a Groovy script for rendering the email contents.

You can either use the predefined Groovy script like this:

```<code>emailext body: '''${SCRIPT, template="groovy-html.template"}'''
</code>```

Or add your own template like described in the documentation. I couldn't figure our if it's possible to load that template from the workspace, but you could try it with:

```<code>emailext body: '''${SCRIPT, template="$WORKSPACE/groovy-html.template"}'''
</code>```

The syntax for getting values from the environment or parameters when interpolating is:

```<code>${env.MY_ENVVAR}
${param.MY_BUILDPARAM}
</code>```

(env and param is ja Groovy map holding all the values)

And for all other variables:

```<code>${varName}
</code>```

Body:
I'm using the Email-Ext plugin to send a results email at the end of my build in the post build stage of a declarative pipeline.  In the body of the email I'm trying to insert some environment variables and some user defined environment variables.

The built in variables show up fine, however any user defined variables I define are just empty in the body of the email or don't work in the attachmentPattern field either:

My environment variables:

pipeline {
    agent any
    environment {
        buildFolder = "build_${BUILD_NUMBER}"
        robotFolder = "build_${BUILD_NUMBER}/robotDemo"
        serverName = "abc123"
        robotResults = "${buildFolder}/*.txt"
    }

The email-ext format I am using in my post{} build:

emailext attachLog: true, attachmentsPattern: 'build_${env.BUILD_NUMBER}/Robot_Results.txt', body: 'Job Name: ${ENV, var="JOB_NAME"}
Build Number: ${ENV, var="BUILD_NUMBER"}

Build URL:
${ENV, var="BUILD_URL"}

Log Files:

${BUILD_LOG_EXCERPT, start="^====", end="^report.html"}

${ENV, var="serverName"}
', mimeType: 'text/html', subject: 'ABS Results', to: 'richard.scott@sap.com'

For example:  ${ENV, var="JOB_NAME"}, shows up fine.  However  ${ENV, var="serverName"} doesn't show at all.

I've tried variations such as...

${serverName}

   ${env.serverName}

...but they don't work either.

Any ideas how to use user defined environment variables like 'serverName' above in the email-ext plug-in?

Thanks & best regards, Richard.

Body:
You’re using single quotes, but only double quotes allow variables to be interpolated.

I would suggest you to use a Groovy script for rendering the email contents.

You can either use the predefined Groovy script like this:

emailext body: '''${SCRIPT, template="groovy-html.template"}'''

Or add your own template like described in the documentation. I couldn't figure our if it's possible to load that template from the workspace, but you could try it with:

emailext body: '''${SCRIPT, template="$WORKSPACE/groovy-html.template"}'''

The syntax for getting values from the environment or parameters when interpolating is:

${env.MY_ENVVAR}
${param.MY_BUILDPARAM}

(env and param is ja Groovy map holding all the values)

And for all other variables:

${varName}


问:
Can managed code perform computations as fast as unmamanged?
I've been interested in different chess engines lately. There are many open and closed sources project in this field. They are all (most of them anyway) written in C/C++. This is kind of an obvious thing - you have a computationally intensive task, you use C/C++ so you get both portability and speed. This seems like a no-brainier.

However, I would like to question that idea. When .NET first appeared, there were many people saying that .NET idea would not work because .NET programs were doomed to be super-slow. In reality this did not happen. Somebody did a good job with the VM, JIT, etc and we have decent performance for most tasks now. But not all. Microsoft never promised that .NET will be suitable for all task and admitted for some tasks you will still need C/C++.

Going back to the question of computationally heavy task - is there a way to write a .NET program so that it does not perform computations considerably worse that an unmanaged code using the same algorithms? I'd be happy with "constant" speed loss, but anything worse than that is going to be a problem.

What do you think? Can we be close in speed to unmanaged code for computations in managed code, or unmanaged code is the only viable answer? If we can, how? If we can't why?

Update:  a lot of good feedback here. I'm going to accept the most up-voted answer.

答:
In general, managed code will have at least some speed loss compared to compiled code, proportional to the size of your code.This loss comes in when the VM first JIT compiles your code. Assuming the JIT compiler is just as good as a normal compiler, after that, the code will perform the same.

However, depending on how it's written, it's even possible that the JIT compiler will perform better than a normal compiler. The JIT compiler knows many more things about the target platform than a normal compiler would--it knows what code is "hot", it can cache results for proven pure functions, it knows which instruction set extensions the target platform supports, etc, whereas depending on the compiler, and how specializing you (and your intended application) allow it to be, the compiler may not be able to optimize nearly as well.

Honestly, it completely depends on your application. Especially with something so algorithmic as a chess engine, it's possible that code in a JIT compiled language, following expected semantics and regular patterns, may run faster than the equivalent in C/C++.

Write something and test it out!


问:
JMeter - how to call Oracle function via JDBC Request
I'm using JMeter to test some Oracle functions and procedures. I want to use JDBC request sampler to call a function (not a stored procedure). Function I want to call is specific as it contains a DML operation inside it (does an insert) so I cannot put it into a select statement as it would result in ORA-14551 - cannot perform a DML operation inside a query  error.

So trying to execute a JDBC Request with query type callable statement:

```<code>BEGIN

  {call MY_PACKAGE.MY_FUNCTION(?,?)};

END;
</code>```

or

```<code>{call MY_PACKAGE.MY_FUNCTION(?,?)};
</code>```

!EDIT!

Adding a screenshot to show a function cannot be called that way:

or select statement:

```<code>select MY_PACKAGE.MY_FUNCTION(?,?) from dual
</code>```

will not work (returns PLS-00221 and ORA-14551 respectively). Now I know how to handle that kind of function via JSR223 Sampler (ex. Groovy script), but the question is can it be done via JDBC Request (and as a result to store output of the function into jmeter variable)?

For testing purposes, the function I am calling is defined in package as:

```<code>create or replace package my_package
is
    function my_function(par1 varchar2, par2 varchar2) return varchar2;
end my_package;

create or replace package body my_package
is

    function my_function(par1 varchar2, par2 varchar2) return varchar2
    is

    begin
        return 'Test_Output';
    end my_function;

end my_package;
</code>```

答:
Try this:

```<code>declare
  c varchar2(500);
begin
  c := your.function(?, ?);
  select c into ? from dual; --this is to return the value to JMeter
end;
</code>```

Parameter values: TEST,TEST,OUT

Parameter types: VARCHAR,VARCHAR,OUT VARCHAR

Other variable names are not really needed, but you can set them if you use them later in test plan.

This might also work (I did not test it):

```<code>? := your.function(?, ?);
</code>```

(note: the out parameter is first now, unlike above, where it was last - adjust the parameter values and types in the JMeter config)

Body:
I'm using JMeter to test some Oracle functions and procedures. I want to use JDBC request sampler to call a function (not a stored procedure). Function I want to call is specific as it contains a DML operation inside it (does an insert) so I cannot put it into a select statement as it would result in ORA-14551 - cannot perform a DML operation inside a query  error.

So trying to execute a JDBC Request with query type callable statement:

BEGIN

  {call MY_PACKAGE.MY_FUNCTION(?,?)};

END;

or

{call MY_PACKAGE.MY_FUNCTION(?,?)};

!EDIT!

Adding a screenshot to show a function cannot be called that way:

or select statement:

select MY_PACKAGE.MY_FUNCTION(?,?) from dual

will not work (returns PLS-00221 and ORA-14551 respectively). Now I know how to handle that kind of function via JSR223 Sampler (ex. Groovy script), but the question is can it be done via JDBC Request (and as a result to store output of the function into jmeter variable)?

For testing purposes, the function I am calling is defined in package as:

create or replace package my_package
is
    function my_function(par1 varchar2, par2 varchar2) return varchar2;
end my_package;

create or replace package body my_package
is

    function my_function(par1 varchar2, par2 varchar2) return varchar2
    is

    begin
        return 'Test_Output';
    end my_function;

end my_package;

Body:
Try this:

declare
  c varchar2(500);
begin
  c := your.function(?, ?);
  select c into ? from dual; --this is to return the value to JMeter
end;

Parameter values: TEST,TEST,OUT

Parameter types: VARCHAR,VARCHAR,OUT VARCHAR

Other variable names are not really needed, but you can set them if you use them later in test plan.

This might also work (I did not test it):

? := your.function(?, ?);

(note: the out parameter is first now, unlike above, where it was last - adjust the parameter values and types in the JMeter config)


答:
As this answer states:

Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort().

var xhr = $.ajax({
    type: "POST",
    url: "some.php",
    success: function(msg){
       alert("Done");
    }
});

//kill the request
xhr.abort()
```

Title: How to cancel requests incase of triggering them using forkJoin Rxjs , Angular


问:
How to properly declare a self-referencing template type?
How do I declare a templated type that refers to itself?

```<code>template <class T = Animal> class Animal
{
public:
    T getChild ();
}
</code>```

With this, I get a compiler error concerning a missing type specifier. I tried to forward-declare Animal, without success.

I am trying to impose a type constraint. A Lion can only have a Lion as a child, a Bear has a Bear, and so on.

EDIT

I'll post part of the actual class. It is a template for classes that can appear in a linked list:

```<code>template <class T = Linked<T> > class Linked
{
private:
    T* m_prev;
    T* m_next;
}
</code>```

I want to enforce that the class can only point to object of the same class (or a subclass).

答:
You can't create a template class wherein the template type is the class itself.  This is a logical recursion that your compiler can't mitigate.  Since templates require the compiler to construct the object when a specific typing is encountered ( say Animal ), you have to have a complete definition of the template type.  Otherwise, the compiler will recursively try to construct objects.  Since your object self-references, this will be an non-terminating recursion.

This use-case seems much more appropriate for inheritance than for templates.

Doing this will let you compile:
    template  class Animal
    {
    public:
        T getPrey ();
    }

Or, if you really wan't a default argument:

```<code>template <class T=Cheetah> class Animal
{
public:
    T getPrey ();
}
</code>```

Yet, cheetah must not use itself or Animal as one of its potential template types.

Body:
How do I declare a templated type that refers to itself?

template <class T = Animal> class Animal
{
public:
    T getChild ();
}

With this, I get a compiler error concerning a missing type specifier. I tried to forward-declare Animal, without success.

I am trying to impose a type constraint. A Lion can only have a Lion as a child, a Bear has a Bear, and so on.

EDIT

I'll post part of the actual class. It is a template for classes that can appear in a linked list:

template <class T = Linked<T> > class Linked
{
private:
    T* m_prev;
    T* m_next;
}

I want to enforce that the class can only point to object of the same class (or a subclass).

Body:
You can't create a template class wherein the template type is the class itself.  This is a logical recursion that your compiler can't mitigate.  Since templates require the compiler to construct the object when a specific typing is encountered ( say Animal ), you have to have a complete definition of the template type.  Otherwise, the compiler will recursively try to construct objects.  Since your object self-references, this will be an non-terminating recursion.

This use-case seems much more appropriate for inheritance than for templates.

Doing this will let you compile:
    template  class Animal
    {
    public:
        T getPrey ();
    }

Or, if you really wan't a default argument:

template <class T=Cheetah> class Animal
{
public:
    T getPrey ();
}

Yet, cheetah must not use itself or Animal as one of its potential template types.


问:
How to use form fields in the same order for Amazon S3 upload file using presigned url
I have a postdata presigned URL of Amazon S3. I want to use it in a Karate feature file to upload a file (say: pdf)

Here is a sample Curl request that I need to perform Using Karate POST request

```<code>curl --location --request POST '<s3bucketURL>' \
--form 'key=some_key_fileName' \
--form 'x-amz-meta-payload={JsonObject}' \
--form 'Content-Type=application/pdf' \
--form 'bucket=<BucketName>' \
--form 'X-Amz-Algorithm=AWS4-HMAC-SHA256' \
--form 'X-Amz-Credential=<AWS_Credential>' \
--form 'X-Amz-Date=<Date>' \
--form 'Policy=<Policy_Hash>' \
--form 'X-Amz-Signature=<Signature_Hash>' \
--form 'file=@/Users/sahildua/validfile.pdf'
</code>```

I got a response (having the preSignedUrl) from a server and used using below code in a feature-file

```<code>  "url": "<s3bucketURL>",
  "fields": {
    "key": "some_key_fileName",
    "x-amz-meta-payload": "{JsonObject}",
    "Content-Type": "application/pdf",
    "bucket": "<BucketName>",
    "X-Amz-Algorithm": "AWS4-HMAC-SHA256",
    "X-Amz-Credential": "<AWS_Credential>",
    "X-Amz-Date": "<Date>",
    "Policy": "<Policy_Hash>",
    "X-Amz-Signature": "<Signature_Hash>"
</code>```

I tried

```<code>Given url response.url
* def fieldData = response.fields
* print fieldData
* form fields fieldData
And multipart file file = { read: '../testData/validPdfFile.pdf'}
When method post
Then match responseStatus ==  204
</code>```

I see the request format of Karate log as:
18:29:08.560 [ForkJoinPool-1-worker-3] DEBUG com.intuit.karate - request:

```<code>2 > POST https://s3.amazonaws.com/devtest
2 > Accept-Encoding: gzip,deflate
2 > Connection: Keep-Alive
2 > Content-Length: 10485
2 > Content-Type: multipart/form-data; boundary=xdW8JqUa4Z2DxRAQSN1i0LntgmN8ZII7VEBuJUs
2 > Host: s3.amazonaws.com
2 > User-Agent: Apache-HttpClient/4.5.11 (Java/13.0.1)

18:29:10.891 [ForkJoinPool-1-worker-3] DEBUG com.intuit.karate - response time in milliseconds: 2328.56
2 < 400
2 < Connection: close
2 < Content-Type: application/xml
2 < Date: Fri, 29 May 2020 12:59:09 GMT
2 < Server: AmazonS3
2 < Transfer-Encoding: chunked
2 < x-amz-id-2: IA9kNim1i7HTUx5RpMmyT34KrRdRj1UfbKGtiWQ7uoj4virV8Oq2UMU8vY/OBqn7T2SLk8VVgo4=
2 < x-amz-request-id: BF19F92FE6DB16E2
<?xml version="1.0" encoding="UTF-8"?>
</code>```

I see the form data is not even passed in the actual request
But I get a validation XML error from Amazon S3 for incorrect order of field values

```<code><Error>
<Code>InvalidArgument</Code>
<Message>Bucket POST must contain a field named 'key'. If it is specified, please check the order of the fields.</Message>
<ArgumentName>key</ArgumentName>
<ArgumentValue></ArgumentValue>
<RequestId><id></RequestId>
<HostId><someid></HostId>
</Error>
</code>```

I expect 204 No Content and the file to be uploaded the S3 bucket

答:
I just used multipart fields instead of form fields and it worked
Changed:
* form fields fieldData
to
And multipart fields fieldData

Body:
I have a postdata presigned URL of Amazon S3. I want to use it in a Karate feature file to upload a file (say: pdf)

Here is a sample Curl request that I need to perform Using Karate POST request

curl --location --request POST '<s3bucketURL>' \
--form 'key=some_key_fileName' \
--form 'x-amz-meta-payload={JsonObject}' \
--form 'Content-Type=application/pdf' \
--form 'bucket=<BucketName>' \
--form 'X-Amz-Algorithm=AWS4-HMAC-SHA256' \
--form 'X-Amz-Credential=<AWS_Credential>' \
--form 'X-Amz-Date=<Date>' \
--form 'Policy=<Policy_Hash>' \
--form 'X-Amz-Signature=<Signature_Hash>' \
--form 'file=@/Users/sahildua/validfile.pdf'

I got a response (having the preSignedUrl) from a server and used using below code in a feature-file

  "url": "<s3bucketURL>",
  "fields": {
    "key": "some_key_fileName",
    "x-amz-meta-payload": "{JsonObject}",
    "Content-Type": "application/pdf",
    "bucket": "<BucketName>",
    "X-Amz-Algorithm": "AWS4-HMAC-SHA256",
    "X-Amz-Credential": "<AWS_Credential>",
    "X-Amz-Date": "<Date>",
    "Policy": "<Policy_Hash>",
    "X-Amz-Signature": "<Signature_Hash>"

I tried

Given url response.url
* def fieldData = response.fields
* print fieldData
* form fields fieldData
And multipart file file = { read: '../testData/validPdfFile.pdf'}
When method post
Then match responseStatus ==  204

I see the request format of Karate log as:
18:29:08.560 [ForkJoinPool-1-worker-3] DEBUG com.intuit.karate - request:

2 > POST https://s3.amazonaws.com/devtest
2 > Accept-Encoding: gzip,deflate
2 > Connection: Keep-Alive
2 > Content-Length: 10485
2 > Content-Type: multipart/form-data; boundary=xdW8JqUa4Z2DxRAQSN1i0LntgmN8ZII7VEBuJUs
2 > Host: s3.amazonaws.com
2 > User-Agent: Apache-HttpClient/4.5.11 (Java/13.0.1)

18:29:10.891 [ForkJoinPool-1-worker-3] DEBUG com.intuit.karate - response time in milliseconds: 2328.56
2 < 400
2 < Connection: close
2 < Content-Type: application/xml
2 < Date: Fri, 29 May 2020 12:59:09 GMT
2 < Server: AmazonS3
2 < Transfer-Encoding: chunked
2 < x-amz-id-2: IA9kNim1i7HTUx5RpMmyT34KrRdRj1UfbKGtiWQ7uoj4virV8Oq2UMU8vY/OBqn7T2SLk8VVgo4=
2 < x-amz-request-id: BF19F92FE6DB16E2
<?xml version="1.0" encoding="UTF-8"?>

I see the form data is not even passed in the actual request
But I get a validation XML error from Amazon S3 for incorrect order of field values

<Error>
InvalidArgument
<Message>Bucket POST must contain a field named 'key'. If it is specified, please check the order of the fields.</Message>
<ArgumentName>key</ArgumentName>
<ArgumentValue></ArgumentValue>
<RequestId><id></RequestId>
<HostId><someid></HostId>
</Error>

I expect 204 No Content and the file to be uploaded the S3 bucket


问:
How to add header to a bokeh dashboard in python?
I created a dashboard in bokeh, but how I can I ad a universal header to it?

I did a lot of research before, but it seems like nobody asked this simple question before.

Thanks for helping me :)

答:
As Eugene mentioned you can use a div-container to set the title and later set it in the column output.

Here some example code that might be helpful to understand:

```<code>output_file("slider.html")
title = Div(text='<h1 style="text-align: center">Example Header</h1>')
p1 = figure(plot_width=300, plot_height=300)
p1.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
tab1 = Panel(child=p1, title="circle")

p2 = figure(plot_width=300, plot_height=300)
p2.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=3, color="navy", alpha=0.5)
tab2 = Panel(child=p2, title="line")

tabs = Tabs(tabs=[tab1, tab2])

layout = column(title, tabs, sizing_mode='scale_width')

curdoc().add_root(layout)
</code>```

Body:
As Eugene mentioned you can use a div-container to set the title and later set it in the column output.

Here some example code that might be helpful to understand:

output_file("slider.html")
title = Div(text='<h1 style="text-align: center">Example Header</h1>')
p1 = figure(plot_width=300, plot_height=300)
p1.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
tab1 = Panel(child=p1, title="circle")

p2 = figure(plot_width=300, plot_height=300)
p2.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=3, color="navy", alpha=0.5)
tab2 = Panel(child=p2, title="line")

tabs = Tabs(tabs=[tab1, tab2])

layout = column(title, tabs, sizing_mode='scale_width')

curdoc().add_root(layout)


问:
Intel SGX pass ints from Application to Enclave
I am trying to pass two integers to the SGX enclave, combine them and then return the result back to the application.
However, nothing seems to happen when compiling the code aside from the enclave getting created. No error given and it seemingly never reaches the ECALL function.

If anyone is aware of a tutorial that does this that I can use as reference then that would be hugely appreciated.

EDL:

```<code>enclave {
    from "sgx_tae_service.edl" import *;

    /* enum definition */
    enum TEE_ERROR {
        TEE_ERROR_INVALID_SIGNATURE = 0,
        TEE_ERROR_INVALID_COUNTER = 1,
        TEE_ERROR_INVALID_SECRET = 2
    };

    trusted {
        /* define ECALLs here. */
        public int in_enclave([in] int* a, [in] int* b);
};

    untrusted {
        /* define OCALLs here. */
        void ocall_print_int([out] int* i);
    };
};
</code>```

Enclave.cpp

```<code>int in_enclave(int* a, int* b){
        ocall_print("In the Enclave.");
        int result =0;
        result = a + b;
        ocall_print_int(&result);

}
</code>```

App.cpp

```<code>int test(void) {
    if (initialize_enclave(&global_eid, "enclave.token", "enclave.signed.so") < 0) {
        std::cout << "Fail to initialize enclave." << std::endl;
        return 1;
    }else{

    std::cout<<"Enclave made. "<<"\n";
}
        int a =34, b =23,point = 0;
        in_enclave(global_eid,&point,&a,&b);

    return 0;                                                                                }
</code>```

答:
See the corrections below. The trusted function in_enclave receives a and b, computes the sum, and returns the result. In the (untrusted) application code the function result is placed in point.

When calling the function check the return value. The return value, from the perspective of the main application code, is of type sgx_status_t where OK is SGX_SUCCESS. There is a list of error codes in the SGX developer reference or look for sgx_error.h in the source code. In this example, we could use the value of status to find why the ecall failed.

EDL

```<code>    trusted {
        public int in_enclave(int a, int b);
    };
</code>```

Enclave

```<code>    int in_enclave(int a, int b){
        return a + b;
    }
</code>```

Application

```<code>    int a = 34, b = 23, point = 0;
    sgx_status_t status = in_enclave(global_eid, &point, a, b);
    if (SGX_SUCCESS != status) {
        // error occurred!
    }
    printf("%d\n", point);
</code>```

Body:
I am trying to pass two integers to the SGX enclave, combine them and then return the result back to the application.
However, nothing seems to happen when compiling the code aside from the enclave getting created. No error given and it seemingly never reaches the ECALL function.

If anyone is aware of a tutorial that does this that I can use as reference then that would be hugely appreciated.

EDL:

enclave {
    from "sgx_tae_service.edl" import *;

    /* enum definition */
    enum TEE_ERROR {
        TEE_ERROR_INVALID_SIGNATURE = 0,
        TEE_ERROR_INVALID_COUNTER = 1,
        TEE_ERROR_INVALID_SECRET = 2
    };

    trusted {
        /* define ECALLs here. */
        public int in_enclave([in] int* a, [in] int* b);
};

    untrusted {
        /* define OCALLs here. */
        void ocall_print_int([out] int* i);
    };
};

Enclave.cpp

int in_enclave(int* a, int* b){
        ocall_print("In the Enclave.");
        int result =0;
        result = a + b;
        ocall_print_int(&result);

}

App.cpp

int test(void) {
    if (initialize_enclave(&global_eid, "enclave.token", "enclave.signed.so") < 0) {
        std::cout << "Fail to initialize enclave." << std::endl;
        return 1;
    }else{

    std::cout<<"Enclave made. "<<"\n";
}
        int a =34, b =23,point = 0;
        in_enclave(global_eid,&point,&a,&b);

    return 0;                                                                                }

Body:
See the corrections below. The trusted function in_enclave receives a and b, computes the sum, and returns the result. In the (untrusted) application code the function result is placed in point.

When calling the function check the return value. The return value, from the perspective of the main application code, is of type sgx_status_t where OK is SGX_SUCCESS. There is a list of error codes in the SGX developer reference or look for sgx_error.h in the source code. In this example, we could use the value of status to find why the ecall failed.

EDL

    trusted {
        public int in_enclave(int a, int b);
    };

Enclave

    int in_enclave(int a, int b){
        return a + b;
    }

Application

    int a = 34, b = 23, point = 0;
    sgx_status_t status = in_enclave(global_eid, &point, a, b);
    if (SGX_SUCCESS != status) {
        // error occurred!
    }
    printf("%d\n", point);


问:
How to know the correct location of File Path in python?
I have a code as shown below, but I dont know the exact location of the given file. How to find the exact location of file? In code, they have used join method.

```<code>       ```
       Code:
       kmatrixconfigxlsx = os.path.join('.', "Polarion_InterfacesSSD.xlsx")
       signalmatrixconfigxlsx = os.path.join('.', "SignalMatrice.xlsx")
       sstconfigxlsx = os.path.join('.', "SST.xlsx")

       Output:
       '.\\Polarion_InterfacesSSD.xlsx'
       ```
</code>```

Could you let me know, where the exact file location will be?

答: os.getcwd() shows the current directory.</p>

Body:
I have a code as shown below, but I dont know the exact location of the given file. How to find the exact location of file? In code, they have used join method.

       ```
       Code:
       kmatrixconfigxlsx = os.path.join('.', "Polarion_InterfacesSSD.xlsx")
       signalmatrixconfigxlsx = os.path.join('.', "SignalMatrice.xlsx")
       sstconfigxlsx = os.path.join('.', "SST.xlsx")

       Output:
       '.\\Polarion_InterfacesSSD.xlsx'
       ```

Could you let me know, where the exact file location will be?


问:
How to format Interval type to HH:MM format?
I am using oracle DB with below column

START_TIME INTERVAL DAY(0) TO SECOND(0)

I am using jdbc template in java code to access this value using the row mapper and getString() method like below: (I am running a basic select query to fetch values from DB)

```<code>String startTime = rs.getString("START_TIME");
</code>```

and the value I get is in this format

```<code>System.out.println(startTime); // 0 9:30:0.0
</code>```

I am not able to format this value in the HH:MM format string. I do not need the seconds as I am ignoring that value. So what I want is something like this 09:30

Found this which looks similar but I am using swagger open API yaml based generation for DTOs and don't know how can I achieve this. Also, I am not using hibernate. It's plain JDBC Template.

EDIT: Observed that when I have +00 11:00:00.000000 in the DB, the rs.getString("START_TIME") fetches 0 11:0:0.0 and when +00 09:30:00.000000 it fetches 0 9:30:0.0 but my requirement is 11:00 and 09:30. Hope this helps a little more.

答:
I believe that manipulating the string value is the easiest and simplest solution, so I will present an alternative solution.

From the Oracle documentation for the INTERVAL DAY TO SECOND data type and from the definition of column START_TIME in your question, the column values cannot span more than one day nor can they contain fractional seconds.

From the Oracle JDBC documentation, the datatype INTERVAL DAY TO SECOND maps to the java class oracle.sql.INTERVALDS. (This is one of the classes in the Oracle JDBC driver JAR file.)

From the javadoc of class oracle.sql.INTERVALDS:

The internal data for this object is stored as a 11 byte array in the super class' storage area. The bytes are arranged as follows:

```<code> Byte       Represents
   0         High byte of day
   1         2nd high byte of day
   2         3rd high byte of day
   3         least byte of day
   4         hour val + 60
   5         min + 60
   6         sec + 60
   7         High byte of Fractional second
   8         2nd high byte of Fractional Second
   9         3rd high byte of Fractional Second
   10        least byte of Fractional Second
</code>```

You know that only bytes 4, 5 and 6 are relevant because of the definition of column START_TIME, i.e. zero days and zero fractional seconds. But since you wrote in your question that you are ignoring the seconds, that means only bytes 4 and 5 are relevant. Hence the code for retrieving the value from the ResultSet and converting it to a string in your desired format is:

INTERVALDS intervalDS = (INTERVALDS) rs.getObject("START_TIME");
byte[] bytes = intervalDS.toBytes();
int hour = bytes[4] - 60;
int minute = bytes[5] - 60;
String result = String.format("%02d:%02d", hour, minute);
```

Body:
I am using oracle DB with below column

START_TIME INTERVAL DAY(0) TO SECOND(0)

I am using jdbc template in java code to access this value using the row mapper and getString() method like below: (I am running a basic select query to fetch values from DB)

String startTime = rs.getString("START_TIME");

and the value I get is in this format

System.out.println(startTime); // 0 9:30:0.0

I am not able to format this value in the HH:MM format string. I do not need the seconds as I am ignoring that value. So what I want is something like this 09:30

Found this which looks similar but I am using swagger open API yaml based generation for DTOs and don't know how can I achieve this. Also, I am not using hibernate. It's plain JDBC Template.

EDIT: Observed that when I have +00 11:00:00.000000 in the DB, the rs.getString("START_TIME") fetches 0 11:0:0.0 and when +00 09:30:00.000000 it fetches 0 9:30:0.0 but my requirement is 11:00 and 09:30. Hope this helps a little more.

Body:
I believe that manipulating the string value is the easiest and simplest solution, so I will present an alternative solution.

From the Oracle documentation for the INTERVAL DAY TO SECOND data type and from the definition of column START_TIME in your question, the column values cannot span more than one day nor can they contain fractional seconds.

From the Oracle JDBC documentation, the datatype INTERVAL DAY TO SECOND maps to the java class oracle.sql.INTERVALDS. (This is one of the classes in the Oracle JDBC driver JAR file.)

From the javadoc of class oracle.sql.INTERVALDS:

The internal data for this object is stored as a 11 byte array in the super class' storage area. The bytes are arranged as follows:

 Byte       Represents
   0         High byte of day
   1         2nd high byte of day
   2         3rd high byte of day
   3         least byte of day
   4         hour val + 60
   5         min + 60
   6         sec + 60
   7         High byte of Fractional second
   8         2nd high byte of Fractional Second
   9         3rd high byte of Fractional Second
   10        least byte of Fractional Second

You know that only bytes 4, 5 and 6 are relevant because of the definition of column START_TIME, i.e. zero days and zero fractional seconds. But since you wrote in your question that you are ignoring the seconds, that means only bytes 4 and 5 are relevant. Hence the code for retrieving the value from the ResultSet and converting it to a string in your desired format is:

INTERVALDS intervalDS = (INTERVALDS) rs.getObject("START_TIME");
byte[] bytes = intervalDS.toBytes();
int hour = bytes[4] - 60;
int minute = bytes[5] - 60;
String result = String.format("%02d:%02d", hour, minute);


问:
React inline style with a variable from a function
I am trying to display the product getting the size it should be from a Json database. I am new to react so have tried a few ways and this is what I have been able to do.
I tried making a function (FontSize) that creates a variable (percentage) with the value I want before and then tried calling the function in the render in the tag with the product. I am getting no errors but the size of the paragraph tag is not changing.

This is my component.

```<code>import React, { Component } from 'react';
import { Loading } from './LoadingComponent';
const API = 'http://localhost:3000/products';

class Products extends Component {
  constructor(props) {
    super(props);
    this.state = {
      products: [],
      isLoading: false,
      error: null,
    };
  }

componentDidMount() {
    this.setState({ isLoading: true });
    fetch(API)
      .then(response => {
        if (response.ok) {
          return response.json();
        } else {
          throw new Error('Something went wrong ...');
        }
      })
      .then(data => this.setState({ products: data, isLoading: false }))
      .catch(error => this.setState({ error, isLoading: false }));
  }

FontSize = () => {

    const { products } = this.state;
    var percentage = products.size + 'px';
    return percentage;
  }

  render() {

  const Prods = () => {
    return (
    <div>
       <div className="row">
           <button onClick={this.sortPrice}>sort by price lower to higher</button>
           <button onClick={this.sortSize}>sort by size small to big</button>
           <button onClick={this.sortId}>sort by Id</button>
        </div>
            {products.map(product =>
            <div className="row">
                <div className="col-3">
                  <p> Price: ${(product.price/100).toFixed(2)}</p>
                </div>

                <div className="col-3">
                  <p style={{fontSize : this.FontSize()}} > {product.face}</p>
                </div>

                <div className="col-3">
                  <p>Date: {product.date} {this.time_ago}</p>
                </div>
            </div>
            )}
            <p>"~END OF CATALOG~"</p>
      </div>
    );
  };

    const { products, isLoading, error } = this.state;
    if (error) {
      return <p>{error.message}</p>;
    }
    if (isLoading) {
      return  <Loading />;
    }
    return (
      <Prods />

    );
  }
}

export default Products;
</code>```

What I get in the console using console.log(products)

答:
I think you need quotes around your style value to work properly.

With concatenation it would look like this for Example:

```<code>style={{gridTemplateRows: "repeat(" + artist.gallery_images.length + ", 100px)"}}
</code>```

Another general example from React:

```<code>const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!</div>;
}
</code>```

Body:
I am trying to display the product getting the size it should be from a Json database. I am new to react so have tried a few ways and this is what I have been able to do.
I tried making a function (FontSize) that creates a variable (percentage) with the value I want before and then tried calling the function in the render in the tag with the product. I am getting no errors but the size of the paragraph tag is not changing.

This is my component.

import React, { Component } from 'react';
import { Loading } from './LoadingComponent';
const API = 'http://localhost:3000/products';

class Products extends Component {
  constructor(props) {
    super(props);
    this.state = {
      products: [],
      isLoading: false,
      error: null,
    };
  }

componentDidMount() {
    this.setState({ isLoading: true });
    fetch(API)
      .then(response => {
        if (response.ok) {
          return response.json();
        } else {
          throw new Error('Something went wrong ...');
        }
      })
      .then(data => this.setState({ products: data, isLoading: false }))
      .catch(error => this.setState({ error, isLoading: false }));
  }

FontSize = () => {

    const { products } = this.state;
    var percentage = products.size + 'px';
    return percentage;
  }

  render() {

  const Prods = () => {
    return (

           <button onClick={this.sortPrice}>sort by price lower to higher</button>
           <button onClick={this.sortSize}>sort by size small to big</button>
           <button onClick={this.sortId}>sort by Id</button>

            {products.map(product =>

 Price: ${(product.price/100).toFixed(2)}

 {product.face}

Date: {product.date} {this.time_ago}

            )}

"~END OF CATALOG~"

    );
  };

    const { products, isLoading, error } = this.state;
    if (error) {
      return
{error.message}
;
    }
    if (isLoading) {
      return  <Loading />;
    }
    return (
      <Prods />

    );
  }
}

export default Products;

What I get in the console using console.log(products)

Body:
I think you need quotes around your style value to work properly.

With concatenation it would look like this for Example:

style={{gridTemplateRows: "repeat(" + artist.gallery_images.length + ", 100px)"}}

Another general example from React:

const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!</div>;
}


问:
The process cannot access the file because it is being used by another process in python
```<code> def worker(ip, started_date, full_path):

    planner_file = full_path+"\\"+"export_"+str(ip)+".txt"

    print "planner file", planner_file

    arg_list = []
    action ="MakeExport"
    arg_list.append(upnp_path)
    arg_lista.append(action)
    arg_list.append(' ip=')
    arg_list.append(ip)
    arg_list.append(" 2>NULL")

    command = ['python', arg_list]

    p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)

    output = p.stdout.read()

   with open(planner_file, "a") as pf:
       pf.write(output)

if __name__=='__main__':

    rack_number, started_date, full_path, ips = main()

    pid = os.getpid()

   print('Main Process is started and PID is: ' + str(pid))

   process_list = []

   for ip in ips:
        p = Process(target=worker, args=(ip, started_date, full_path))
        p.start()
        child_pid = str(p.pid)
        print('PID is:' + child_pid)
        process_list.append(child_pid)

   children = multiprocessing.active_children()

   # print process_list

  while children != []:
     time.sleep(1)
     children = multiprocessing.active_children()
</code>```

I am trying to export some ip addresses data to txt files. While it works OK with single ip address, if I try my script for multiple ip addresses, I get the following error in the all other ip txt file.

For the first ip address, script exports data correctly. For all other remaining ips it says;

'The process cannot access the file because it is being used by another process.'

For example :
export_1.8.5.20.txt (First ip data exported correctly)
export_1.8.5.21.txt (it says the process can not access the file)

I do not get any errors from my script. Just get the above details inside the txt files.

Any helps would be appreciated. Thanks

答:
This seems to be the known bug: https://bugs.python.org/issue33369 or https://bugs.python.org/issue19575

Try to put a lock around the Popen() call.

Body:
 def worker(ip, started_date, full_path):

    planner_file = full_path+"\\"+"export_"+str(ip)+".txt"

    print "planner file", planner_file

    arg_list = []
    action ="MakeExport"
    arg_list.append(upnp_path)
    arg_lista.append(action)
    arg_list.append(' ip=')
    arg_list.append(ip)
    arg_list.append(" 2>NULL")

    command = ['python', arg_list]

    p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)

    output = p.stdout.read()

   with open(planner_file, "a") as pf:
       pf.write(output)

if __name__=='__main__':

    rack_number, started_date, full_path, ips = main()

    pid = os.getpid()

   print('Main Process is started and PID is: ' + str(pid))

   process_list = []

   for ip in ips:
        p = Process(target=worker, args=(ip, started_date, full_path))
        p.start()
        child_pid = str(p.pid)
        print('PID is:' + child_pid)
        process_list.append(child_pid)

   children = multiprocessing.active_children()

   # print process_list

  while children != []:
     time.sleep(1)
     children = multiprocessing.active_children()

I am trying to export some ip addresses data to txt files. While it works OK with single ip address, if I try my script for multiple ip addresses, I get the following error in the all other ip txt file.

For the first ip address, script exports data correctly. For all other remaining ips it says;

'The process cannot access the file because it is being used by another process.'

For example :
export_1.8.5.20.txt (First ip data exported correctly)
export_1.8.5.21.txt (it says the process can not access the file)

I do not get any errors from my script. Just get the above details inside the txt files.

Any helps would be appreciated. Thanks


问:
Comparing records to find improvements
I have 2 Rails models Client and HealthProfile:

```<code>class Client < ApplicationRecord
    has_many :health_profiles
end

class HealthProfile < ApplicationRecord
    belongs_to :client, optional: true
    scope :start, -> { where(status: 'start' ) }
    scope :end, -> { where(status: 'end' ) }
end
</code>```

HealthProfile contains information such as :panic_attacks (there are 25 other conditions) and I want to see what percentage of clients show improvement.  To show improvement they would have panic_attacks: true in their :start health_profile and panic_attacks: false in their :end health_profile.  The issue is that :panic_attacks defaults to false.

Is there a query I can perform to capture all clients that responded true to :panic_attacks in their :start and false to :panic_attacks in their :end?  Ideally this solution will work for all 25 conditions.

答:
What you want to do instead is to create a a many to many association and query it:

```<code>class HealthProfile < ApplicationRecord
  belongs_to :client, optional: true
  has_many :panic_attacks
end
</code>```

```<code>class PanicAttack
  belongs_to :health_profile
end
</code>```

This would let you for example count the number of attacks by using grouping:

```<code>profile = HealthProfile.find(1)
# this is postgres specific - use the group_date gem if you need something polyglot
per_month = profile.panic_attacks
                   .group("date_trunc('month', panic_attacks.started_at)")
                   .count
</code>```

And you can also use other sorts of aggregate functions like averages and means to get meaningful stats. For example an imrovement could be a reduction in the count or average length.

Boolean columns are a scurge.

Title: Comparing records to find improvements

Body:
I have 2 Rails models Client and HealthProfile:

class Client < ApplicationRecord
    has_many :health_profiles
end

class HealthProfile < ApplicationRecord
    belongs_to :client, optional: true
    scope :start, -> { where(status: 'start' ) }
    scope :end, -> { where(status: 'end' ) }
end

HealthProfile contains information such as :panic_attacks (there are 25 other conditions) and I want to see what percentage of clients show improvement.  To show improvement they would have panic_attacks: true in their :start health_profile and panic_attacks: false in their :end health_profile.  The issue is that :panic_attacks defaults to false.

Is there a query I can perform to capture all clients that responded true to :panic_attacks in their :start and false to :panic_attacks in their :end?  Ideally this solution will work for all 25 conditions.

Body:
What you want to do instead is to create a a many to many association and query it:

class HealthProfile < ApplicationRecord
  belongs_to :client, optional: true
  has_many :panic_attacks
end

class PanicAttack
  belongs_to :health_profile
end

This would let you for example count the number of attacks by using grouping:

profile = HealthProfile.find(1)
# this is postgres specific - use the group_date gem if you need something polyglot
per_month = profile.panic_attacks
                   .group("date_trunc('month', panic_attacks.started_at)")
                   .count

And you can also use other sorts of aggregate functions like averages and means to get meaningful stats. For example an imrovement could be a reduction in the count or average length.

Boolean columns are a scurge.


问:
EditForm - How can I prevent submit on pressing enter key
I've found this article but I'm having a hard time to understand how can I prevent submit on "enter" key independently by any <input>

<EditForm Model="exampleModel" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText id="name" @bind-Value="exampleModel.Name" />
    <InputText id="name2" @bind-Value="exampleModel.Name2" />

    <button type="submit">Submit</button>
</EditForm>
```

<pre class="lang-cs prettyprint-override"><code>@code {
    private ExampleModel exampleModel = new ExampleModel();

    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }

    public class ExampleModel
    {
         [Required]
         [StringLength(10, ErrorMessage = "Name is too long.")]
         public string Name { get; set; }
         public string Name2 {get; set;}
    }
}
</code>```

Use Case

Enter key On HTML forms if you are filling out a text box and press the enter key it will submit the form, even if you haven't finished filling in the rest of the information. There are many websites which use this feature such as Google search box will submit when you press the enter key. This works because you only have one text box to fill out, but if there are more than one field to fill in you don't want the form to submit on the enter key.

答:
As Enet suggested in the comments, there isn't a full Blazor (Csharp) solution for this use-case. You have to interact with JavaScript.

Currently, I solved with this workaround:

blazor-side

@inject IJSRuntime JS
<EditForm id="askQuestionForm" Model="exampleModel" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText id="name" @bind-Value="exampleModel.Name" />
    <InputText id="name2" @bind-Value="exampleModel.Name2" />

    <button type="submit">Submit</button>
</EditForm>
```

<pre class="lang-cs prettyprint-override"><code>@code {
    private ExampleModel exampleModel = new ExampleModel();

    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            JS.InvokeVoidAsync("PreventEnterKey", "askQuestionForm");
        }
    }

    public class ExampleModel
    {
         [Required]
         [StringLength(10, ErrorMessage = "Name is too long.")]
         public string Name { get; set; }
         public string Name2 {get; set;}
    }
}
</code>```

interop.js

function PreventEnterKey(id) {
    $(`#${id}`).keydown(function (event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            return false;
        }
    });
}
```

I hope Microsoft will develop this feature in the future.

Thanks to Enet.

Body:
I've found this article but I'm having a hard time to understand how can I prevent submit on "enter" key independently by any <input>

<EditForm Model="exampleModel" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText id="name" @bind-Value="exampleModel.Name" />
    <InputText id="name2" @bind-Value="exampleModel.Name2" />

    <button type="submit">Submit</button>
</EditForm>

@code {
    private ExampleModel exampleModel = new ExampleModel();

    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }

    public class ExampleModel
    {
         [Required]
         [StringLength(10, ErrorMessage = "Name is too long.")]
         public string Name { get; set; }
         public string Name2 {get; set;}
    }
}

Use Case

Enter key On HTML forms if you are filling out a text box and press the enter key it will submit the form, even if you haven't finished filling in the rest of the information. There are many websites which use this feature such as Google search box will submit when you press the enter key. This works because you only have one text box to fill out, but if there are more than one field to fill in you don't want the form to submit on the enter key.

Body:
As Enet suggested in the comments, there isn't a full Blazor (Csharp) solution for this use-case. You have to interact with JavaScript.

Currently, I solved with this workaround:

blazor-side

@inject IJSRuntime JS
<EditForm id="askQuestionForm" Model="exampleModel" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText id="name" @bind-Value="exampleModel.Name" />
    <InputText id="name2" @bind-Value="exampleModel.Name2" />

    <button type="submit">Submit</button>
</EditForm>

@code {
    private ExampleModel exampleModel = new ExampleModel();

    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            JS.InvokeVoidAsync("PreventEnterKey", "askQuestionForm");
        }
    }

    public class ExampleModel
    {
         [Required]
         [StringLength(10, ErrorMessage = "Name is too long.")]
         public string Name { get; set; }
         public string Name2 {get; set;}
    }
}

interop.js

function PreventEnterKey(id) {
    $(`#${id}`).keydown(function (event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            return false;
        }
    });
}

I hope Microsoft will develop this feature in the future.

Thanks to Enet.


问:
Confusion with Arrays
I'm new to JavaScript and although I have looked at many forums/tutorials I'm struggling with exactly what I need to change to achieve what I want.

I currently have a Google spreadsheet that is populated with UK post codes, these postcodes are automatically added at various points using a combination of google forms and Microsoft forms/flow.

What I want to do is to automatically calculate the distance in miles between 2 post codes that are in each row.

For example, in column C there would be a pickup post code, and in column D there would be a Drop off post code - in column E I would like the mileage to automatically display when a new row with new post codes is added.

Currently, I am using the below customer function to calculate the distance in miles, but I need to be able to wrap it in the ARRAYFORMULA function in google sheets but when I do only the first cell displays the correct mileage (the others remain blank)

The code below seems to work very well I just can't figure out how to be able to allow the GOOGLEDISTANCE function to accept an array of Pick up post codes and an array of drop off post codes and then return an array of the calculated mileage in miles.

Code:

function GOOGLEDISTANCE(pick_up,drop_off,return_type) {
      Utilities.sleep(1000);
      var travelMode = Maps.DirectionFinder.Mode.BICYCLING;
      var directions = Maps.newDirectionFinder()
      .setRegion('UK')
      .setLanguage('en-GB')
      .setOrigin(pick_up)
      .setDestination(drop_off)
      // .addWaypoint(waypoint1)
      .setMode(travelMode)
      .getDirections();

      if (directions.status !== "OK")
      return "Error: " + directions.status;

     var route = directions.routes[0].legs[0];
     var time = route.duration.value;
     var distance = route.distance.value;

     var steps = route.steps.map(function(step) {
      return step.html_instructions.replace(/<[^>]+>/g, "");
     }).join("\n");

     switch(return_type) {
      case "MILES":
      case "miles":
      return distance * 0.000621371;
      break;
      case "KILOMETERS":
      case "kilometers":
      return distance / 1000;
      break;
      case "MINUTES":
      case "minutes":
      return time / 60;
      break;
      case "HOURS":
      case "hours":
      return time / 60 / 60;
      break;
      case "STEPS":
      case "steps":
      return steps;
      break;
      default:
      // Default to miles
     return distance * 0.000621371;
    }
}
```

答:
According to docs it should have similar structure to code below.

=arrayFormula(GOOGLEDISTANCE_WRAPPER())

function GOOGLEDISTANCE_WRAPPER(data) {
  if(Array.isArray(data)) {
    return data.map(GOOGLEDISTANCE)
  }

  return GOOGLEDISTANCE(data);
}

function GOOGLEDISTANCE(pick_up, drop_off, return_type) {
  ...code...
}

```

Title: Confusion with Arrays


问:
How to speed up MySQL query involving a "like" condition on a varchar column?
I have a table with a varchar column that contains stock market tickers. The values can have the stock exchange prepended to the actual ticker, but some don't. For example:

```<code>NYSE:MSFT
NYSE:AAPL
AMT:STZ
^SPX
JMAT
</code>```

These are all valid tickers. Now, when someone searches for a ticker, then the query looks something like:

```<code>select * from stocks where ticker like '%'.$string.'%'
</code>```

The table, in production, will have over 100k entries. I want to get ahead of that potential problem by indexing on the column, but it appears based on MySQL docs that it is not possible, not for a query like this anyway.

The docs state that a varchar index is possible, but in a like query it won't work if there's a wildcard before the search string. And I do need a wildcard before the search string.

Is there another option to speeding up this query?

答:
If you want to speed up the query you'll need to avoid matching with patterns that start with a %. To do this you'll need to add some redundancy to keep the second value in a separate column.

Therefore, your table should look like:

```<code>full_ticker  ticker
-----------  ------
NYSE:MSFT    MSFT
NYSE:AAPL    AAPL
AMT:STZ      STZ
^SPX         ^SPX
JMAT         JMAT
</code>```

Simple string manipulation will produce the second (new) column; for 100k rows this will take no time.

Now you can create two indexes, one per column:

```<code>create index ix1 on stocks (full_ticker);

create index ix2 on stocks (ticker);
</code>```

Finally, when a search comes in with a colon, then use the first index:

```<code>select * from stocks where full_ticker like $string.'%'
</code>```

If a search comes in without a colon, then use the second index:

```<code>select * from stocks where ticker like $string.'%'
</code>```

Notice that both searches avoid using the % at the beginning of the pattern. This way, your queries will use the indexes and will be blazing fast.

A final note: Another option is to create the second, redundant column as a "virtual column"; virtual columns can actually be indexed, to produce the same experience I detailed here. Just a though.

Body:
I have a table with a varchar column that contains stock market tickers. The values can have the stock exchange prepended to the actual ticker, but some don't. For example:

NYSE:MSFT
NYSE:AAPL
AMT:STZ
^SPX
JMAT

These are all valid tickers. Now, when someone searches for a ticker, then the query looks something like:

select * from stocks where ticker like '%'.$string.'%'

The table, in production, will have over 100k entries. I want to get ahead of that potential problem by indexing on the column, but it appears based on MySQL docs that it is not possible, not for a query like this anyway.

The docs state that a varchar index is possible, but in a like query it won't work if there's a wildcard before the search string. And I do need a wildcard before the search string.

Is there another option to speeding up this query?

Body:
If you want to speed up the query you'll need to avoid matching with patterns that start with a %. To do this you'll need to add some redundancy to keep the second value in a separate column.

Therefore, your table should look like:

full_ticker  ticker
-----------  ------
NYSE:MSFT    MSFT
NYSE:AAPL    AAPL
AMT:STZ      STZ
^SPX         ^SPX
JMAT         JMAT

Simple string manipulation will produce the second (new) column; for 100k rows this will take no time.

Now you can create two indexes, one per column:

create index ix1 on stocks (full_ticker);

create index ix2 on stocks (ticker);

Finally, when a search comes in with a colon, then use the first index:

select * from stocks where full_ticker like $string.'%'

If a search comes in without a colon, then use the second index:

select * from stocks where ticker like $string.'%'

Notice that both searches avoid using the % at the beginning of the pattern. This way, your queries will use the indexes and will be blazing fast.

A final note: Another option is to create the second, redundant column as a "virtual column"; virtual columns can actually be indexed, to produce the same experience I detailed here. Just a though.


问:
How to solve an error that appears in conda proxy configuration?
I am trying to install Rdkit on ubuntu and I have problem with the conda configuration.

I have reinstalled anaconda3 and python3 versions on my desktop and installed it from the beginning.

When I run the command: conda create -c rdkit -n my-rdkit-env rdkit

The error I am experiencing is this one:

```<code>Collecting package metadata (current_repodata.json): failed

ProxyError: Conda cannot proceed due to an error in your proxy configuration.
Check for typos and other configuration errors in any '.netrc' file in your home directory,
any environment variables ending in '_PROXY', and any other system-wide proxy
configuration settings.
</code>```

Does anybody knows how to solve this problem, so that I can install the program called Rdkit?

答:
I had the same issue today on Linux 18.04. I solved it by adding my username and password when exporting the $http_proxy and $https_proxy

Here is an command structure:

```<code>$ export http_proxy=http://username:password@proxy:port
$ export https_proxy=https://username:password@proxy:port
</code>```

If your password contain special character such as !@#$%, make sure to input it as Flash code. For example #->%23, @->%40. You can search it for more symbol.

Also I have removed the .condarc file from the home directory.

Hope this work for you.

Body:
I am trying to install Rdkit on ubuntu and I have problem with the conda configuration.

I have reinstalled anaconda3 and python3 versions on my desktop and installed it from the beginning.

When I run the command: conda create -c rdkit -n my-rdkit-env rdkit

The error I am experiencing is this one:

Collecting package metadata (current_repodata.json): failed

ProxyError: Conda cannot proceed due to an error in your proxy configuration.
Check for typos and other configuration errors in any '.netrc' file in your home directory,
any environment variables ending in '_PROXY', and any other system-wide proxy
configuration settings.

Does anybody knows how to solve this problem, so that I can install the program called Rdkit?

Body:
I had the same issue today on Linux 18.04. I solved it by adding my username and password when exporting the $http_proxy and $https_proxy

Here is an command structure:

$ export http_proxy=http://username:password@proxy:port
$ export https_proxy=https://username:password@proxy:port

If your password contain special character such as !@#$%, make sure to input it as Flash code. For example #->%23, @->%40. You can search it for more symbol.

Also I have removed the .condarc file from the home directory.

Hope this work for you.


问:
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU.

I am getting the above error for code:-

    def get_model(path, device):
        model = models.vgg16(pretrained=False)

        for param in model.parameters():
            param.requires_grad = False
        n_inputs = model.classifier[6].in_features

        model.classifier[6] = torch.nn.Sequential(
            torch.nn.Linear(n_inputs, 256), torch.nn.ReLU(), torch.nn.Dropout(0.2),
            torch.nn.Linear(256, 10), torch.nn.LogSoftmax(dim=1))

        model.load_state_dict(torch.load(path), map_location=torch.device('cpu'))
        model.to(device)
        model.eval()
        return model

    device = torch.device("cpu")
    model = get_model('vgg16.pt', device)
```

答:
You are passing the map_location to the wrong function (to model.load_state_dict instead of torch.load).

The corrected line would look like this:

model.load_state_dict(torch.load(path, map_location=torch.device('cpu')))
```


问:
How to avoid to go back after click on back button of browser in rails 5?
I am using Rails 5 and jQuery. After logging in, the home page is displayed, but when I click on the back button of browser, it will show me log in page again.

When I click on the back button, I want it to redirect to the home page, Please help me to solve this problem..

答:
How did I solved this problem?

I used the jQuery to solve this porblem.. add those lines inside the script tag of html login page.

```<code><script type="text/javascript">
  function preback(){
    window.history.forward();
  }
  setTimeout("preback()", 0);
  window.onunload=function(){null};
</script>
</code>```

Body:
How did I solved this problem?

I used the jQuery to solve this porblem.. add those lines inside the script tag of html login page.

<script type="text/javascript">
  function preback(){
    window.history.forward();
  }
  setTimeout("preback()", 0);
  window.onunload=function(){null};
</script>


问:
How to make discord.js bot reply to DM but only once
I'm trying to make the bot reply to any DM it was sent with a specific message but only once so if it was dmed again by the same user it would ignore it.

This is my code
But right now it keeps sending the message if they keep dming I have no clue how to confront this

```<code>  if (msg.channel.type == "dm") {
    msg.author.send("test");
    return;
  }
});
</code>```

答:
You could save the IDs like Alan suggested but you don't really need to

if (msg.channel.type == "dm") {
    if (msg.author.dmChannel.lastMessage) return;
    //code
}
```

Body:
I'm trying to make the bot reply to any DM it was sent with a specific message but only once so if it was dmed again by the same user it would ignore it.

This is my code
But right now it keeps sending the message if they keep dming I have no clue how to confront this

  if (msg.channel.type == "dm") {
    msg.author.send("test");
    return;
  }
});