问:
Fastest way to copy files (but not the entire directory) from one location to another
Summary

I am currently tasked with migrating around 6TB of data to a cloud server, and am trying to optimise how fast this can be done.

I would use standard Robocopy to do this usually, but there is a requirement that I am to only transfer files that are present in a filetable in SQL, and not the entire directories (due to a lot of junk being inside these folders that we do not want to migrate).

What I have tried

Feeding in individual files from an array into Robocopy is unfeasibly slow, as Robocopy instances were being started sequentially for each file, so I tried to speed up this process in 2 ways.

It was pointless to have /MT set above 1 if only one file was being transferred, so I attempted to simulate the multithreading feature. I did this by utilising the new ForEach-Object –Parallel feature in PowerShell 7.0, and setting the throttle limit to 4. With this, I was able to pass the array in and run 4 Robocopy jobs in parallel (still starting and stopping for each file), which increased speed a bit.

Secondly, I split the array into 4 equal arrays, and ran the above function across each array as a job, which again increased the speed by quite a bit. For clarity, I had equal 4 arrays fed to 4 ForEach-Object -Parallel code blocks that were running 4 Robocopy instances, so a total of 16 Robocopy instances at once.

Issues

I encountered a few problems.

My simulation of the multithreading feature did not behave in the way that the /MT flag works in Robocopy. When examining the processes running, my code executes 16 instances of Robocopy at once, whereas the normal /MT:16 flag of Robocopy would only kick off one Robocopy instance (but still be multithreading).

Secondly, the code causes a memory leak. The memory usage starts to increase when the jobs and accumulates over time, until a large portion of memory is being utilised. When the jobs complete, the memory usage is still high until I close PowerShell and the memory is released. Normal Robocopy did not do this.

Finally, I decided to compare the time taken for my method, and then a standard Robocopy of the entire testing directory, and the normal Robocopy was still over 10x faster, and had a better success rate (a lot of the files weren’t copied over with my code, and a lot of the time I was receiving error messages that the files were currently in use and couldn’t be Robocopied, presumably because they were in the process of being Robocopied).

Are there any faster alternatives, or is there a way to manually create a multithreading instance of robocopy that would perform like the /MT flag of the standard robocopy? I appreciate any insight/alternative ways of looking at this. Thanks!

```<code>#Item(0) is the Source excluding the filename, Item(2) is the Destination, Item(1) is the filename
$robocopy0 = $tables.Tables[0].Rows
$robocopy1 = $tables.Tables[1].Rows
$robocopy0 | ForEach-Object -Parallel {robocopy $_.Item(0) $_.Item(2) $_.Item(1) /e /w:1 /r:1 /tee /NP /xo /mt:1 /njh /njs /ns
                                      } -ThrottleLimit 4 -AsJob
$robocopy1 | ForEach-Object -Parallel {robocopy $_.Item(0) $_.Item(2) $_.Item(1) /e /w:1 /r:1 /tee /NP /xo /mt:1 /njh /njs /ns
                                      } -ThrottleLimit 4 -AsJob
#*8 for 8 arrays
</code>```

答:
RunspaceFactory multithreading might be optimally suited for this type of work--with one HUGE caveat.  There are quite a few articles out on the net about it.  Essentially you create a scriptblock that takes parameters for the source file to copy and the destination to write to and uses those parameters to execute robocopy against it.  You create individual PowerShell instances to execute each variant of the scriptblock and append it to the RunspaceFactory.  The RunspaceFactory will queue up the jobs and work against the probably millions of jobs X number at a time, where X is equal to the number of threads you allocate for the factory.

CAVEAT:  First and foremost, to queue up millions of jobs relative to the probable millions of files you have across 6TB, you'll likely need monumental amounts of memory.  Assuming an average path length for source and destination of 40 characters (probably very generous) * a WAG of 50 million files is nearly 4GB in memory by itself, which doesn't include object structural overhead, the PowerShell instances, etc.  You can overcome this either breaking up the job into smaller chunks or use a server with 128GB RAM or better.  Additionally, if you don't terminate the jobs once they've been processed, you'll also experience what appears to be a memory leak but is just your jobs producing information that you're not closing when completed.

Here's a sample from a recent project I did migrating files from an old domain NAS to a new domain NAS -- I'm using Quest SecureCopy instead of RoboCopy but you should be able to easily replace those bits:

```<code>## MaxThreads is an arbitrary number I use relative to the hardware I have available to run jobs I'm working on.
$FileRSpace_MaxThreads = 15
$FileRSpace = [runspacefactory]::CreateRunspacePool(1, $FileRSpace_MaxThreads, ([System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()), $Host)
$FileRSpace.ApartmentState = 'MTA'
$FileRSpace.Open()

## The scriptblock that does the actual work.
$sb = {
param(
    $sp,
    $dp
)

    ## This is my output object I'll emit through STDOUT so I can consume the status of the job in the main thread after each instance is completed.
    $n = [pscustomobject]@{
        'source'  = $sp
        'dest'    = $dp
        'status'  = $null
        'sdtm'    = [datetime]::Now
        'edtm'    = $null
        'elapsed' = $null
    }

    ## Remove the Import-Module and SecureCopy cmdlet and replace it with the RoboCopy version
    try {
        Import-Module "C:\Program Files\Quest\Secure Copy 7\SCYPowerShellCore.dll" -ErrorAction Stop
        Start-SecureCopyJob -Database "C:\Program Files\Quest\Secure Copy 7\SecureCopy.ssd" -JobName "Default" -Source $sp -Target $dp -CopySubFolders $true -Quiet $true -ErrorAction Stop | Out-Null
        $n.status = $true
    } catch {
        $n.status = $_
    }
    $n.edtm    = [datetime]::Now
    $n.elapsed = ("{0:N2} minutes" -f (($n.edtm - $n.sdtm).TotalMinutes))
    $n
}

## The array to hold the individual runspaces and ulitimately iterate over to watch for completion.
$FileWorkers = @()

$js = [datetime]::now
log "Job starting at $js"

## $peers is a [pscustomobject] I precreate that just contains every source (property 's') and the destination (property 'd') -- modify to suit your needs as necessary
foreach ($c in $peers) {

    try {

        log "Configuring migration job for '$($c.s)' and '$($c.d)'"
        $runspace = [powershell]::Create()
        [void]$runspace.AddScript($sb)

        [void]$runspace.AddArgument($c.s)
        [void]$runspace.AddArgument($c.d)

        $runspace.RunspacePool = $FileRSpace
        $FileWorkers += [pscustomobject]@{
            'Pipe'   = $runspace
            'Async'  = $runspace.BeginInvoke()
        }

        log "Successfully created a multi-threading job for '$($c.s)' and '$($c.d)'"
    } catch {
        log "An error occurred creating a multi-threading job for '$($c.s)' and '$($c.d)'"
    }
}

while ($FileWorkers.Async.IsCompleted -contains $false) {
    $Completed = $FileWorkers | ? { $_.Async.IsCompleted -eq $true }
    [pscustomobject]@{
        'Numbers' = ("{0}/{1}" -f $Completed.Count, $FileWorkers.Count)
        'PercComplete' = ("{0:P2}" -f ($Completed.Count / $FileWorkers.Count))
        'ElapsedMins' = ("{0:N2}" -f ([datetime]::Now - $js).TotalMinutes)
    }

    $Completed | % { $_.Pipe.EndInvoke($_.Async) } | Export-Csv -NoTypeInformation ".\$($DtmStamp)_SecureCopy_Results.csv"

    Start-Sleep -Seconds 15
}

## This is to handle a race-condition where the final job(s) aren't completed before the sleep but do when the while is re-eval'd
$FileWorkers | % { $_.Pipe.EndInvoke($_.Async) } | Export-Csv -NoTypeInformation ".\$($DtmStamp)_SecureCopy_Results.csv"
</code>```

Suggested strategies if you don't have a beefy server to queue up all the jobs simultaneously is to either batch out the files in statically sized blocks (e.g. 100,000 or whatever your hw can take) or you could group files together to send to each script block (e.g. 100 files per scriptblock) which would minimize the number of jobs to queue up in the runspace factory (but would require some code change).

HTH

Edit 1:  To Address constructing the input object I'm using

```<code>$destRoot = '\\destinationserver.com\share'

$peers = @()

$children = @()
$children += (get-childitem '\\sourceserver\share' -Force) | Select -ExpandProperty FullName

foreach ($c in $children) {

    $peers += [pscustomobject]@{
        's' = $c
        'd' = "$($destRoot)\$($c.Split('\')[3])\$($c | Split-Path -Leaf)"
    }
}
</code>```

In my case, I was taking stuff from \server1\share1\subfolder1 and moving it to something like \server2\share1\subfolder1\subfolder2.  So in essence, all the '$peers' array is doing is constructing an object that took in the fullname of the source target and constructing the corresponding destination path (since the source/dest server names are different and possibly share name too).

You don't have to do this, you can dynamically construct the destination and just loop through the source folders.  I perform this extra step because now I have a two property array that I can verify is pre-constructed accurately as well as perform tests to ensure things exist and are accessible.

There is a lot of extra bloat in my script due to custom objects meant to give me output from each thread put into the multi-threader so I can see the status of each copy attempt--to track things like folders that were successful or not, how long it took to perform that individual copy, etc.  If you're using robocopy and dumping the results to a text file, you may not need this.  If you want me to pair down script to it's barebone components just to get things multi-threading, I can do that if you like.

Body:
Summary

I am currently tasked with migrating around 6TB of data to a cloud server, and am trying to optimise how fast this can be done.

I would use standard Robocopy to do this usually, but there is a requirement that I am to only transfer files that are present in a filetable in SQL, and not the entire directories (due to a lot of junk being inside these folders that we do not want to migrate).

What I have tried

Feeding in individual files from an array into Robocopy is unfeasibly slow, as Robocopy instances were being started sequentially for each file, so I tried to speed up this process in 2 ways.

It was pointless to have /MT set above 1 if only one file was being transferred, so I attempted to simulate the multithreading feature. I did this by utilising the new ForEach-Object –Parallel feature in PowerShell 7.0, and setting the throttle limit to 4. With this, I was able to pass the array in and run 4 Robocopy jobs in parallel (still starting and stopping for each file), which increased speed a bit.

Secondly, I split the array into 4 equal arrays, and ran the above function across each array as a job, which again increased the speed by quite a bit. For clarity, I had equal 4 arrays fed to 4 ForEach-Object -Parallel code blocks that were running 4 Robocopy instances, so a total of 16 Robocopy instances at once.

Issues

I encountered a few problems.

My simulation of the multithreading feature did not behave in the way that the /MT flag works in Robocopy. When examining the processes running, my code executes 16 instances of Robocopy at once, whereas the normal /MT:16 flag of Robocopy would only kick off one Robocopy instance (but still be multithreading).

Secondly, the code causes a memory leak. The memory usage starts to increase when the jobs and accumulates over time, until a large portion of memory is being utilised. When the jobs complete, the memory usage is still high until I close PowerShell and the memory is released. Normal Robocopy did not do this.

Finally, I decided to compare the time taken for my method, and then a standard Robocopy of the entire testing directory, and the normal Robocopy was still over 10x faster, and had a better success rate (a lot of the files weren’t copied over with my code, and a lot of the time I was receiving error messages that the files were currently in use and couldn’t be Robocopied, presumably because they were in the process of being Robocopied).

Are there any faster alternatives, or is there a way to manually create a multithreading instance of robocopy that would perform like the /MT flag of the standard robocopy? I appreciate any insight/alternative ways of looking at this. Thanks!

#Item(0) is the Source excluding the filename, Item(2) is the Destination, Item(1) is the filename
$robocopy0 = $tables.Tables[0].Rows
$robocopy1 = $tables.Tables[1].Rows
$robocopy0 | ForEach-Object -Parallel {robocopy $_.Item(0) $_.Item(2) $_.Item(1) /e /w:1 /r:1 /tee /NP /xo /mt:1 /njh /njs /ns
                                      } -ThrottleLimit 4 -AsJob
$robocopy1 | ForEach-Object -Parallel {robocopy $_.Item(0) $_.Item(2) $_.Item(1) /e /w:1 /r:1 /tee /NP /xo /mt:1 /njh /njs /ns
                                      } -ThrottleLimit 4 -AsJob
#*8 for 8 arrays

Body:
RunspaceFactory multithreading might be optimally suited for this type of work--with one HUGE caveat.  There are quite a few articles out on the net about it.  Essentially you create a scriptblock that takes parameters for the source file to copy and the destination to write to and uses those parameters to execute robocopy against it.  You create individual PowerShell instances to execute each variant of the scriptblock and append it to the RunspaceFactory.  The RunspaceFactory will queue up the jobs and work against the probably millions of jobs X number at a time, where X is equal to the number of threads you allocate for the factory.

CAVEAT:  First and foremost, to queue up millions of jobs relative to the probable millions of files you have across 6TB, you'll likely need monumental amounts of memory.  Assuming an average path length for source and destination of 40 characters (probably very generous) * a WAG of 50 million files is nearly 4GB in memory by itself, which doesn't include object structural overhead, the PowerShell instances, etc.  You can overcome this either breaking up the job into smaller chunks or use a server with 128GB RAM or better.  Additionally, if you don't terminate the jobs once they've been processed, you'll also experience what appears to be a memory leak but is just your jobs producing information that you're not closing when completed.

Here's a sample from a recent project I did migrating files from an old domain NAS to a new domain NAS -- I'm using Quest SecureCopy instead of RoboCopy but you should be able to easily replace those bits:

## MaxThreads is an arbitrary number I use relative to the hardware I have available to run jobs I'm working on.
$FileRSpace_MaxThreads = 15
$FileRSpace = [runspacefactory]::CreateRunspacePool(1, $FileRSpace_MaxThreads, ([System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()), $Host)
$FileRSpace.ApartmentState = 'MTA'
$FileRSpace.Open()

## The scriptblock that does the actual work.
$sb = {
param(
    $sp,
    $dp
)

    ## This is my output object I'll emit through STDOUT so I can consume the status of the job in the main thread after each instance is completed.
    $n = [pscustomobject]@{
        'source'  = $sp
        'dest'    = $dp
        'status'  = $null
        'sdtm'    = [datetime]::Now
        'edtm'    = $null
        'elapsed' = $null
    }

    ## Remove the Import-Module and SecureCopy cmdlet and replace it with the RoboCopy version
    try {
        Import-Module "C:\Program Files\Quest\Secure Copy 7\SCYPowerShellCore.dll" -ErrorAction Stop
        Start-SecureCopyJob -Database "C:\Program Files\Quest\Secure Copy 7\SecureCopy.ssd" -JobName "Default" -Source $sp -Target $dp -CopySubFolders $true -Quiet $true -ErrorAction Stop | Out-Null
        $n.status = $true
    } catch {
        $n.status = $_
    }
    $n.edtm    = [datetime]::Now
    $n.elapsed = ("{0:N2} minutes" -f (($n.edtm - $n.sdtm).TotalMinutes))
    $n
}

## The array to hold the individual runspaces and ulitimately iterate over to watch for completion.
$FileWorkers = @()

$js = [datetime]::now
log "Job starting at $js"

## $peers is a [pscustomobject] I precreate that just contains every source (property 's') and the destination (property 'd') -- modify to suit your needs as necessary
foreach ($c in $peers) {

    try {

        log "Configuring migration job for '$($c.s)' and '$($c.d)'"
        $runspace = [powershell]::Create()
        [void]$runspace.AddScript($sb)

        [void]$runspace.AddArgument($c.s)
        [void]$runspace.AddArgument($c.d)

        $runspace.RunspacePool = $FileRSpace
        $FileWorkers += [pscustomobject]@{
            'Pipe'   = $runspace
            'Async'  = $runspace.BeginInvoke()
        }

        log "Successfully created a multi-threading job for '$($c.s)' and '$($c.d)'"
    } catch {
        log "An error occurred creating a multi-threading job for '$($c.s)' and '$($c.d)'"
    }
}

while ($FileWorkers.Async.IsCompleted -contains $false) {
    $Completed = $FileWorkers | ? { $_.Async.IsCompleted -eq $true }
    [pscustomobject]@{
        'Numbers' = ("{0}/{1}" -f $Completed.Count, $FileWorkers.Count)
        'PercComplete' = ("{0:P2}" -f ($Completed.Count / $FileWorkers.Count))
        'ElapsedMins' = ("{0:N2}" -f ([datetime]::Now - $js).TotalMinutes)
    }

    $Completed | % { $_.Pipe.EndInvoke($_.Async) } | Export-Csv -NoTypeInformation ".\$($DtmStamp)_SecureCopy_Results.csv"

    Start-Sleep -Seconds 15
}

## This is to handle a race-condition where the final job(s) aren't completed before the sleep but do when the while is re-eval'd
$FileWorkers | % { $_.Pipe.EndInvoke($_.Async) } | Export-Csv -NoTypeInformation ".\$($DtmStamp)_SecureCopy_Results.csv"

Suggested strategies if you don't have a beefy server to queue up all the jobs simultaneously is to either batch out the files in statically sized blocks (e.g. 100,000 or whatever your hw can take) or you could group files together to send to each script block (e.g. 100 files per scriptblock) which would minimize the number of jobs to queue up in the runspace factory (but would require some code change).

HTH

Edit 1:  To Address constructing the input object I'm using

$destRoot = '\\destinationserver.com\share'

$peers = @()

$children = @()
$children += (get-childitem '\\sourceserver\share' -Force) | Select -ExpandProperty FullName

foreach ($c in $children) {

    $peers += [pscustomobject]@{
        's' = $c
        'd' = "$($destRoot)\$($c.Split('\')[3])\$($c | Split-Path -Leaf)"
    }
}

In my case, I was taking stuff from \server1\share1\subfolder1 and moving it to something like \server2\share1\subfolder1\subfolder2.  So in essence, all the '$peers' array is doing is constructing an object that took in the fullname of the source target and constructing the corresponding destination path (since the source/dest server names are different and possibly share name too).

You don't have to do this, you can dynamically construct the destination and just loop through the source folders.  I perform this extra step because now I have a two property array that I can verify is pre-constructed accurately as well as perform tests to ensure things exist and are accessible.

There is a lot of extra bloat in my script due to custom objects meant to give me output from each thread put into the multi-threader so I can see the status of each copy attempt--to track things like folders that were successful or not, how long it took to perform that individual copy, etc.  If you're using robocopy and dumping the results to a text file, you may not need this.  If you want me to pair down script to it's barebone components just to get things multi-threading, I can do that if you like.


来源: stackexchange

问:
Cannot load ssl localhost in WKWebView
Environment:

iOS 10.15.3

Xcode 11.3.1

Swift 4.2

I have an Angular 5 app running locally at https://localhost:8300/vthome. I have installed a localhost cert and the page loads correctly without issue in chrome and safari.

I have an iOS app with a webview. I can load the Angular 5 app that is being served from our development server but I cannot load the version I have running locally.

When I try to load the Angular 5 app that is running locally in the webview in the simulator (iPhone 11 Pro Max 13.3):

```<code>    func loadWebViewUrl(url: String){
        let requestUrl = URL(string: url)
        print("Attempting to load url: \(requestUrl!)")
        let request = URLRequest(url: requestUrl!)

        webView.load(request as URLRequest)
    }
</code>```

I get this error in the output:

```<code>Attempting to load url: https://localhost:8300/vthome
2020-02-18 09:12:35.263998-0600 PayBridge[23492:2718338] Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service
2020-02-18 09:12:35.265999-0600 PayBridge[23492:2718338] Could not signal service com.apple.WebKit.Networking: 113: Could not find specified service
</code>```

And the webview just shows blank (no text, no errors, nothing). I found a lot of issues regarding loading static html files but I couldn't find anything that addressed loading localhost.

答: Although we are using HTTPS (TLS), iOS still did not like it. We solved this by adding: <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> to the info.plist file

ContentLicense: CC BY-SA 4.0

Title: Cannot load ssl localhost in WKWebView

Body:
Environment:

iOS 10.15.3

Xcode 11.3.1

Swift 4.2

I have an Angular 5 app running locally at https://localhost:8300/vthome. I have installed a localhost cert and the page loads correctly without issue in chrome and safari.

I have an iOS app with a webview. I can load the Angular 5 app that is being served from our development server but I cannot load the version I have running locally.

When I try to load the Angular 5 app that is running locally in the webview in the simulator (iPhone 11 Pro Max 13.3):

    func loadWebViewUrl(url: String){
        let requestUrl = URL(string: url)
        print("Attempting to load url: \(requestUrl!)")
        let request = URLRequest(url: requestUrl!)

        webView.load(request as URLRequest)
    }

I get this error in the output:

Attempting to load url: https://localhost:8300/vthome
2020-02-18 09:12:35.263998-0600 PayBridge[23492:2718338] Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service
2020-02-18 09:12:35.265999-0600 PayBridge[23492:2718338] Could not signal service com.apple.WebKit.Networking: 113: Could not find specified service

And the webview just shows blank (no text, no errors, nothing). I found a lot of issues regarding loading static html files but I couldn't find anything that addressed loading localhost.


问:
Identify missing dates for ID & Date table
My approach to identify missing dates for IDs is to use a left table (t1) which is a calendar table of 100 years of dates and to LEFT join (on date=date) the master table (t2) which has date & ID .

I was hoping when I do the left join I would have a full list of dates ranging from 1-365 for each year in (t1) and then a joined id from (t2) when the dates match. When the date's are missing there should be a NULL.

The current output and the desired output from my script is attached here desired output

Simplified script below:

```<code>SELECT t1.date,
       t2.date,
       t2.id
FROM t1
LEFT JOIN t2 ON t1.date= t2.date
ORDER BY t1.date,t2.id ASC
</code>```

答:
If you want

```<code>SELECT t1.date, t2.date, t2.id
FROM t1 LEFT JOIN
     t2
     ON t1.date = t2.date and t2.id = 28295
ORDER BY t1.date, t2.id ASC;
</code>```

If you want this for all ids (or a larger subset), use cross join to generate the ids and then left join:

```<code>SELECT t1.date, t2.date, i.id
FROM t1 CROSS JOIN
     (SELECT DISTINCT t2.id FROM t2) i LEFT JOIN
     t2
     ON t1.date = t2.date and t2.id = i.id
ORDER BY t1.date, t2.id ASC;
</code>```

Body:
My approach to identify missing dates for IDs is to use a left table (t1) which is a calendar table of 100 years of dates and to LEFT join (on date=date) the master table (t2) which has date & ID .

I was hoping when I do the left join I would have a full list of dates ranging from 1-365 for each year in (t1) and then a joined id from (t2) when the dates match. When the date's are missing there should be a NULL.

The current output and the desired output from my script is attached here desired output

Simplified script below:

SELECT t1.date,
       t2.date,
       t2.id
FROM t1
LEFT JOIN t2 ON t1.date= t2.date
ORDER BY t1.date,t2.id ASC

Body:
If you want

SELECT t1.date, t2.date, t2.id
FROM t1 LEFT JOIN
     t2
     ON t1.date = t2.date and t2.id = 28295
ORDER BY t1.date, t2.id ASC;

If you want this for all ids (or a larger subset), use cross join to generate the ids and then left join:

SELECT t1.date, t2.date, i.id
FROM t1 CROSS JOIN
     (SELECT DISTINCT t2.id FROM t2) i LEFT JOIN
     t2
     ON t1.date = t2.date and t2.id = i.id
ORDER BY t1.date, t2.id ASC;


Title: Parsing Data passed in multiple formats... how to get data I need from it


问:
Repeat a function in JavaScript doesn't work
So I am trying to make a simple translator. I am just having some issues with it. For example, I want it to register the letter B and then it will write bob. Now when I write b in the translate to box (which is the normal variable) it says in the translated to box (which is theifTalk) [object HTMLTextAreaElement]bob. And in the console it says: Cannot read property 'repeat' of undefined. Anyways here's my code:

```<code>const theifTalk = document.getElementById('theiftalk');
const normal = document.getElementById('normal');
const translateBtn = document.getElementById('translateBtn');

translateBtn.onclick = function() {
    theifTalk.value = "";
    translate();
}

function translate() {

    if (normal.value.includes("b")) {
        var bCount = normal.value.match(/b/g)||[].length;

        b().repeat(bCount.length);
    }

}

function b() {
    theifTalk.value = theifTalk + "bob";
}
</code>```

HTML CODE:

```<code><textarea type="text" id="normal" rows="15" cols="80" placeholder="Normal text goes in here..."></textarea>
<textarea type="text" id="theiftalk" rows="15" cols="80" placeholder="Theif Talk text goes out here..."></textarea>
<br>
<button id="translateBtn">translate</button>
</code>```

答:
As you are not returning anything from function explicitly undefined is returned. You have return the value from function. Also, theifTalk is the element itself, you should take the value from that:

```<code>function b() {
  theifTalk.value = theifTalk.value + "bob";
  return theifTalk.value;
}
</code>```

You also should set the value back to the theifTalk:

```<code>theifTalk.value = b().repeat(bCount.length);
</code>```

const theifTalk = document.getElementById('theiftalk');
const normal = document.getElementById('normal');
const translateBtn = document.getElementById('translateBtn');

translateBtn.onclick = function() {
  translate();
}
function translate() {
  if (normal.value.includes("b")) {
    var bCount = normal.value.match(/b/g)||[].length;
    theifTalk.value = b().repeat(bCount.length);
  }
}

function b() {
  theifTalk.value = theifTalk.value + "bob";
  return theifTalk.value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea type="text" id="normal" rows="15" cols="80" placeholder="Normal text goes in here..."></textarea>
<textarea type="text" id="theiftalk" rows="15" cols="80" placeholder="Theif Talk text goes out here..."></textarea>
<br>
<button id="translateBtn">translate</button></code>```

Body:
So I am trying to make a simple translator. I am just having some issues with it. For example, I want it to register the letter B and then it will write bob. Now when I write b in the translate to box (which is the normal variable) it says in the translated to box (which is theifTalk) [object HTMLTextAreaElement]bob. And in the console it says: Cannot read property 'repeat' of undefined. Anyways here's my code:

const theifTalk = document.getElementById('theiftalk');
const normal = document.getElementById('normal');
const translateBtn = document.getElementById('translateBtn');

translateBtn.onclick = function() {
    theifTalk.value = "";
    translate();
}

function translate() {

    if (normal.value.includes("b")) {
        var bCount = normal.value.match(/b/g)||[].length;

        b().repeat(bCount.length);
    }

}

function b() {
    theifTalk.value = theifTalk + "bob";
}

HTML CODE:

<textarea type="text" id="normal" rows="15" cols="80" placeholder="Normal text goes in here..."></textarea>
<textarea type="text" id="theiftalk" rows="15" cols="80" placeholder="Theif Talk text goes out here..."></textarea>

<button id="translateBtn">translate</button>

Body:
As you are not returning anything from function explicitly undefined is returned. You have return the value from function. Also, theifTalk is the element itself, you should take the value from that:

function b() {
  theifTalk.value = theifTalk.value + "bob";
  return theifTalk.value;
}

You also should set the value back to the theifTalk:

theifTalk.value = b().repeat(bCount.length);

const theifTalk = document.getElementById('theiftalk');
const normal = document.getElementById('normal');
const translateBtn = document.getElementById('translateBtn');

translateBtn.onclick = function() {
  translate();
}
function translate() {
  if (normal.value.includes("b")) {
    var bCount = normal.value.match(/b/g)||[].length;
    theifTalk.value = b().repeat(bCount.length);
  }
}

function b() {
  theifTalk.value = theifTalk.value + "bob";
  return theifTalk.value;
}

<textarea type="text" id="normal" rows="15" cols="80" placeholder="Normal text goes in here..."></textarea>
<textarea type="text" id="theiftalk" rows="15" cols="80" placeholder="Theif Talk text goes out here..."></textarea>
<br>
<button id="translateBtn">translate</button>


问:
Python can't find file
I am having great difficulty getting python 3.4 to recognize a path or text file on a windows 8 system. I have tried a variety of different approaches but get the similar errors (which likely implies something simple regarding the syntax).

The file itself is located in the same folder as the script file trying to open it:
C:\Users\User\Desktop\Python stuff\Data.txt

for simplicity, the simplest means to access the file (at least that I know of) is
f=open

These lines were coded as:

```<code>f = open("Data.txt", "r")
</code>```

and

```<code>f = open("C:/Users/User/Desktop/Python stuff/Data.txt", "r")
</code>```

but return the error:

```<code>Traceback (most recent call last):
  File "C:\Users\User\Desktop\Python stuff\Testscript.py", line 3, in <module>
    f = open("C:/Users/User/Desktop/Python stuff/Data.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/User/Desktop/Python stuff/Data.txt'
</code>```

答:
The problem might be, where exactly you are executing the file.

I had the same problem, but noticed, that the terminal in my IDE (VS Code) is executing the file in a different location. By simply cd to the files location in the terminal, everything went fine. ;)

ContentLicense: CC BY-SA 3.0

Title: Python can't find file

Body:
I am having great difficulty getting python 3.4 to recognize a path or text file on a windows 8 system. I have tried a variety of different approaches but get the similar errors (which likely implies something simple regarding the syntax).

The file itself is located in the same folder as the script file trying to open it:
C:\Users\User\Desktop\Python stuff\Data.txt

for simplicity, the simplest means to access the file (at least that I know of) is
f=open

These lines were coded as:

f = open("Data.txt", "r")

and

f = open("C:/Users/User/Desktop/Python stuff/Data.txt", "r")

but return the error:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\Python stuff\Testscript.py", line 3, in <module>
    f = open("C:/Users/User/Desktop/Python stuff/Data.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/User/Desktop/Python stuff/Data.txt'


问:
z3py: Retrieve branching conditions from z3 formula
Let's say I have a z3py program like this one:

```<code>import z3

a = z3.Int("a")
input_0 = z3.Int("input_0")
output = z3.Int("output")

some_formula = z3.If(a < input_0, 1, z3.If(a > 1, 4, 2))

s = z3.Solver()

s.add(output == some_formula)

s.check()
m = s.model()
print(m)
</code>```

Is there an elegant way for me to retrieve the branching conditions from some_formula?
So get a list like [a < input_0, a > 1]. It should work for arbitrarily deep nesting of if expressions.

I know there is some way to use cubes, but I am not able to retrieve more than two cube expressions. I am not sure how to configure the solver.

My ultimate goal is to force the solver to give me different outputs based on the constraints I push and pop. The constraints are the set of conditions I have inferred from this formula.

答:
You can print the cubes using:

for cube in s.cube():
    print cube
```

<p>But this isn't going to really help you. For your example, it prints:</p>

```[If(a + -1*input_0 >= 0, If(a <= 1, 2, 4), 1) == 1]
[Not(If(a + -1*input_0 >= 0, If(a <= 1, 2, 4), 1) == 1)]
```

which isn't quite what you were looking for.

The easiest way to go about your problem would be to directly walk down the AST of the formula yourself, and grab the conditions as you walk along the expressions. Of course, Z3 AST is quite a hairy object (pun intended!), so this will require quite a bit of programming. But reading through the constructors (If, Var etc.) in this file can get you started: https://z3prover.github.io/api/html/z3py_8py_source.html

Body:
Let's say I have a z3py program like this one:

import z3

a = z3.Int("a")
input_0 = z3.Int("input_0")
output = z3.Int("output")

some_formula = z3.If(a < input_0, 1, z3.If(a > 1, 4, 2))

s = z3.Solver()

s.add(output == some_formula)

s.check()
m = s.model()
print(m)

Is there an elegant way for me to retrieve the branching conditions from some_formula?
So get a list like [a < input_0, a > 1]. It should work for arbitrarily deep nesting of if expressions.

I know there is some way to use cubes, but I am not able to retrieve more than two cube expressions. I am not sure how to configure the solver.

My ultimate goal is to force the solver to give me different outputs based on the constraints I push and pop. The constraints are the set of conditions I have inferred from this formula.

Body:
You can print the cubes using:

for cube in s.cube():
    print cube

But this isn't going to really help you. For your example, it prints:

[If(a + -1*input_0 >= 0, If(a <= 1, 2, 4), 1) == 1]
[Not(If(a + -1*input_0 >= 0, If(a <= 1, 2, 4), 1) == 1)]

which isn't quite what you were looking for.

The easiest way to go about your problem would be to directly walk down the AST of the formula yourself, and grab the conditions as you walk along the expressions. Of course, Z3 AST is quite a hairy object (pun intended!), so this will require quite a bit of programming. But reading through the constructors (If, Var etc.) in this file can get you started: https://z3prover.github.io/api/html/z3py_8py_source.html


问:
Unable to install SimpleAudio with Conda or Pip
I am trying to install SimpleAudio with Conda although I run into errors. I then try Pip and get a different error.  I am running Raspbian Buster on the Raspberry Pi 4 with python version 3.6.6. Conda version 4.5.1. Pip version 18.0. Processor is ARM Cortex-A72.

I use to the following to install SimpleAudio:

```<code>conda install -c skmad simpleaudio
</code>```

I then recieve the following error:

```<code>Solving environment: failed

PackagesNotFoundError: The following packages are not available from current channels:

  - simpleaudio

Current channels:

  - https://conda.anaconda.org/skmad/linux-armv7l
  - https://conda.anaconda.org/skmad/noarch
  - https://conda.anaconda.org/rpi/linux-armv7l
  - https://conda.anaconda.org/rpi/noarch
  - https://repo.anaconda.com/pkgs/main/linux-armv7l
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/free/linux-armv7l
  - https://repo.anaconda.com/pkgs/free/noarch
  - https://repo.anaconda.com/pkgs/r/linux-armv7l
  - https://repo.anaconda.com/pkgs/r/noarch
  - https://repo.anaconda.com/pkgs/pro/linux-armv7l
  - https://repo.anaconda.com/pkgs/pro/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.
</code>```

I recieve this  error despite the script I run being suggested on the Annaconda website.

I then try the generic pip install (which finds the correct package) and get the following process and error message:

pi@raspberrypi:~ $ pip install simpleaudio

```<code>Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting simpleaudio
  Using cached https://files.pythonhosted.org/packages/94/1b/4dc29653733202b68c09d9c6ca085cf67ac54859ee860647ef21ac1ff3dc/simpleaudio-1.0.4.tar.gz
Building wheels for collected packages: simpleaudio
  Running setup.py bdist_wheel for simpleaudio ... error
  Complete output from command /home/pi/miniconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-ll1gm7ko/simpleaudio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-u1mh9fbx --python-tag cp36:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-armv7l-3.6
  creating build/lib.linux-armv7l-3.6/simpleaudio
  copying simpleaudio/__init__.py -> build/lib.linux-armv7l-3.6/simpleaudio
  copying simpleaudio/shiny.py -> build/lib.linux-armv7l-3.6/simpleaudio
  copying simpleaudio/functionchecks.py -> build/lib.linux-armv7l-3.6/simpleaudio
  creating build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  copying simpleaudio/test_audio/c.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  copying simpleaudio/test_audio/e.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  copying simpleaudio/test_audio/g.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  copying simpleaudio/test_audio/left_right.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  copying simpleaudio/test_audio/notes_2_16_44.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  running build_ext
  building 'simpleaudio._simpleaudio' extension
  creating build/temp.linux-armv7l-3.6
  creating build/temp.linux-armv7l-3.6/c_src
  gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -I/home/pi/miniconda3/include -march=armv7-a -mfpu=neon-vfpv4 -mfloat-abi=hard -fPIC -O2 -pipe -I/home/pi/miniconda3/include -march=armv7-a -mfpu=neon-vfpv4 -mfloat-abi=hard -fPIC -O2 -pipe -fPIC -DDEBUG=0 -I/home/pi/miniconda3/include/python3.6m -c c_src/simpleaudio_alsa.c -o build/temp.linux-armv7l-3.6/c_src/simpleaudio_alsa.o
  c_src/simpleaudio_alsa.c:8:10: fatal error: alsa/asoundlib.h: No such file or directory
   #include <alsa/asoundlib.h>
            ^~~~~~~~~~~~~~~~~~
  compilation terminated.
  error: command 'gcc' failed with exit status 1

  ----------------------------------------
  Failed building wheel for simpleaudio
  Running setup.py clean for simpleaudio
Failed to build simpleaudio
Installing collected packages: simpleaudio
  Running setup.py install for simpleaudio ... error
    Complete output from command /home/pi/miniconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-ll1gm7ko/simpleaudio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-fmdsq71s/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-armv7l-3.6
    creating build/lib.linux-armv7l-3.6/simpleaudio
    copying simpleaudio/__init__.py -> build/lib.linux-armv7l-3.6/simpleaudio
    copying simpleaudio/shiny.py -> build/lib.linux-armv7l-3.6/simpleaudio
    copying simpleaudio/functionchecks.py -> build/lib.linux-armv7l-3.6/simpleaudio
    creating build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    copying simpleaudio/test_audio/c.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    copying simpleaudio/test_audio/e.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    copying simpleaudio/test_audio/g.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    copying simpleaudio/test_audio/left_right.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    copying simpleaudio/test_audio/notes_2_16_44.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    running build_ext
    building 'simpleaudio._simpleaudio' extension
    creating build/temp.linux-armv7l-3.6
    creating build/temp.linux-armv7l-3.6/c_src
    gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -I/home/pi/miniconda3/include -march=armv7-a -mfpu=neon-vfpv4 -mfloat-abi=hard -fPIC -O2 -pipe -I/home/pi/miniconda3/include -march=armv7-a -mfpu=neon-vfpv4 -mfloat-abi=hard -fPIC -O2 -pipe -fPIC -DDEBUG=0 -I/home/pi/miniconda3/include/python3.6m -c c_src/simpleaudio_alsa.c -o build/temp.linux-armv7l-3.6/c_src/simpleaudio_alsa.o
    c_src/simpleaudio_alsa.c:8:10: fatal error: alsa/asoundlib.h: No such file or directory
     #include <alsa/asoundlib.h>
              ^~~~~~~~~~~~~~~~~~
    compilation terminated.
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/home/pi/miniconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-ll1gm7ko/simpleaudio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-fmdsq71s/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-ll1gm7ko/simpleaudio/
</code>```

Does anyone have any suggestions?

Thanks

答:
This was resolved by installing the dependencies required before using Pip.

Use the below script:

```<code>sudo apt-get install -y python3-dev libasound2-dev
</code>```

Body:
I am trying to install SimpleAudio with Conda although I run into errors. I then try Pip and get a different error.  I am running Raspbian Buster on the Raspberry Pi 4 with python version 3.6.6. Conda version 4.5.1. Pip version 18.0. Processor is ARM Cortex-A72.

I use to the following to install SimpleAudio:

conda install -c skmad simpleaudio

I then recieve the following error:

Solving environment: failed

PackagesNotFoundError: The following packages are not available from current channels:

  - simpleaudio

Current channels:

  - https://conda.anaconda.org/skmad/linux-armv7l
  - https://conda.anaconda.org/skmad/noarch
  - https://conda.anaconda.org/rpi/linux-armv7l
  - https://conda.anaconda.org/rpi/noarch
  - https://repo.anaconda.com/pkgs/main/linux-armv7l
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/free/linux-armv7l
  - https://repo.anaconda.com/pkgs/free/noarch
  - https://repo.anaconda.com/pkgs/r/linux-armv7l
  - https://repo.anaconda.com/pkgs/r/noarch
  - https://repo.anaconda.com/pkgs/pro/linux-armv7l
  - https://repo.anaconda.com/pkgs/pro/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

I recieve this  error despite the script I run being suggested on the Annaconda website.

I then try the generic pip install (which finds the correct package) and get the following process and error message:

pi@raspberrypi:~ $ pip install simpleaudio

Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting simpleaudio
  Using cached https://files.pythonhosted.org/packages/94/1b/4dc29653733202b68c09d9c6ca085cf67ac54859ee860647ef21ac1ff3dc/simpleaudio-1.0.4.tar.gz
Building wheels for collected packages: simpleaudio
  Running setup.py bdist_wheel for simpleaudio ... error
  Complete output from command /home/pi/miniconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-ll1gm7ko/simpleaudio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-u1mh9fbx --python-tag cp36:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-armv7l-3.6
  creating build/lib.linux-armv7l-3.6/simpleaudio
  copying simpleaudio/__init__.py -> build/lib.linux-armv7l-3.6/simpleaudio
  copying simpleaudio/shiny.py -> build/lib.linux-armv7l-3.6/simpleaudio
  copying simpleaudio/functionchecks.py -> build/lib.linux-armv7l-3.6/simpleaudio
  creating build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  copying simpleaudio/test_audio/c.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  copying simpleaudio/test_audio/e.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  copying simpleaudio/test_audio/g.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  copying simpleaudio/test_audio/left_right.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  copying simpleaudio/test_audio/notes_2_16_44.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
  running build_ext
  building 'simpleaudio._simpleaudio' extension
  creating build/temp.linux-armv7l-3.6
  creating build/temp.linux-armv7l-3.6/c_src
  gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -I/home/pi/miniconda3/include -march=armv7-a -mfpu=neon-vfpv4 -mfloat-abi=hard -fPIC -O2 -pipe -I/home/pi/miniconda3/include -march=armv7-a -mfpu=neon-vfpv4 -mfloat-abi=hard -fPIC -O2 -pipe -fPIC -DDEBUG=0 -I/home/pi/miniconda3/include/python3.6m -c c_src/simpleaudio_alsa.c -o build/temp.linux-armv7l-3.6/c_src/simpleaudio_alsa.o
  c_src/simpleaudio_alsa.c:8:10: fatal error: alsa/asoundlib.h: No such file or directory
   #include <alsa/asoundlib.h>
            ^~~~~~~~~~~~~~~~~~
  compilation terminated.
  error: command 'gcc' failed with exit status 1

  ----------------------------------------
  Failed building wheel for simpleaudio
  Running setup.py clean for simpleaudio
Failed to build simpleaudio
Installing collected packages: simpleaudio
  Running setup.py install for simpleaudio ... error
    Complete output from command /home/pi/miniconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-ll1gm7ko/simpleaudio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-fmdsq71s/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-armv7l-3.6
    creating build/lib.linux-armv7l-3.6/simpleaudio
    copying simpleaudio/__init__.py -> build/lib.linux-armv7l-3.6/simpleaudio
    copying simpleaudio/shiny.py -> build/lib.linux-armv7l-3.6/simpleaudio
    copying simpleaudio/functionchecks.py -> build/lib.linux-armv7l-3.6/simpleaudio
    creating build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    copying simpleaudio/test_audio/c.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    copying simpleaudio/test_audio/e.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    copying simpleaudio/test_audio/g.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    copying simpleaudio/test_audio/left_right.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    copying simpleaudio/test_audio/notes_2_16_44.wav -> build/lib.linux-armv7l-3.6/simpleaudio/test_audio
    running build_ext
    building 'simpleaudio._simpleaudio' extension
    creating build/temp.linux-armv7l-3.6
    creating build/temp.linux-armv7l-3.6/c_src
    gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -I/home/pi/miniconda3/include -march=armv7-a -mfpu=neon-vfpv4 -mfloat-abi=hard -fPIC -O2 -pipe -I/home/pi/miniconda3/include -march=armv7-a -mfpu=neon-vfpv4 -mfloat-abi=hard -fPIC -O2 -pipe -fPIC -DDEBUG=0 -I/home/pi/miniconda3/include/python3.6m -c c_src/simpleaudio_alsa.c -o build/temp.linux-armv7l-3.6/c_src/simpleaudio_alsa.o
    c_src/simpleaudio_alsa.c:8:10: fatal error: alsa/asoundlib.h: No such file or directory
     #include <alsa/asoundlib.h>
              ^~~~~~~~~~~~~~~~~~
    compilation terminated.
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/home/pi/miniconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-ll1gm7ko/simpleaudio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-fmdsq71s/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-ll1gm7ko/simpleaudio/

Does anyone have any suggestions?

Thanks

Body:
This was resolved by installing the dependencies required before using Pip.

Use the below script:

sudo apt-get install -y python3-dev libasound2-dev


问:
Regex match character only when NOT preceeded by specific word
The goal is to have regex match all newline character which are not preceded by a 2-decimal number. Here's some example text:

```<code>This line ends with text
this line ends with a number: 55
this line ends with a 2-decimal number: 5.00
here's 22.22, not at the end of the line
</code>```

Regex should match the end of lines 1, 2, and 4 (assuming a newline after the 4th line).  I thought negative lookahead was the answer so I tried

```<code>(?!\d*\.\d\d)\n
</code>```

without success as seen in this regex101 snippet: https://regex101.com/r/qbrKlt/4

<s>Edit: I later discovered the reason this didn't work is because Python's Regex doesn't support variable length negative lookahead - it only supports fixed-length negative lookahead.</s>

Unfortunately fixed-length look-ahead still didnt work:

```<code>(?!\.\d\d)\n
</code>```

Instead I did a workaround by running regex twice & subtracting the result:

find all indices of newline characters: \n

find all indices of newline characters preceded by 2-decimal numbers: \d*\.\d\d\n

remove indices found in step 2 from those found in step 1 for the answer

But I'm sure there's a way to do this in 1 go and I'd be grateful to anyone out there that can help in discovering the solution :)

答:
You need to use a negative lookbehind instead of a negative lookahead:

```<code>(?<!\.\d\d)\n
</code>```

Updated RegEx Demo

This will match \n if that is not immediately preceded by dot and 2 digits.

Body:
The goal is to have regex match all newline character which are not preceded by a 2-decimal number. Here's some example text:

This line ends with text
this line ends with a number: 55
this line ends with a 2-decimal number: 5.00
here's 22.22, not at the end of the line

Regex should match the end of lines 1, 2, and 4 (assuming a newline after the 4th line).  I thought negative lookahead was the answer so I tried

(?!\d*\.\d\d)\n

without success as seen in this regex101 snippet: https://regex101.com/r/qbrKlt/4

<s>Edit: I later discovered the reason this didn't work is because Python's Regex doesn't support variable length negative lookahead - it only supports fixed-length negative lookahead.</s>

Unfortunately fixed-length look-ahead still didnt work:

(?!\.\d\d)\n

Instead I did a workaround by running regex twice & subtracting the result:

find all indices of newline characters: \n

find all indices of newline characters preceded by 2-decimal numbers: \d*\.\d\d\n

remove indices found in step 2 from those found in step 1 for the answer

But I'm sure there's a way to do this in 1 go and I'd be grateful to anyone out there that can help in discovering the solution :)

Body:
You need to use a negative lookbehind instead of a negative lookahead:

(?<!\.\d\d)\n

Updated RegEx Demo

This will match \n if that is not immediately preceded by dot and 2 digits.


问:
Required request body is missing in Spring when Angular Post call is sent
In my Angular application I'm trying to create a POST request, with a json body, that will be sent to my Spring Restful back-end; I have created a service in Angular to handle the API Post method but when I try to send the request, I obtain this error in my front-end console:

core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://127.0.0.1:8080/center/search_1/page/0", ok: false, …}

and this error in my back-end console:

Required request body is missing: public org.springframework.data.domain.Page

This is the code of my service in Angular:

```<code>import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {FirstQuery} from '../../../_responseModels/firstQuery/first-query';
import {tap} from 'rxjs/operators';
import {stringify} from 'querystring';

@Injectable({
  providedIn: 'root'
})
export class ApiCenterSearch1Service {

  apiURL = 'http://127.0.0.1:8080/center/search_1/page/0';

  constructor(private httpClient: HttpClient) {}

  getFirstQuery(body: JSON): any {

    return  this.httpClient.post<FirstQuery[]>(this.apiURL, JSON.stringify(body),
      {
        headers : new HttpHeaders({'Content-Type': 'application/json'})
        // observe: 'response'
      });
  }

}
</code>```

and this is a part of the code of a component that triggers the API call:

```<code>funcThis.apiCenterSearch1Service.getFirstQuery(JSON.parse(jsonRequest)).subscribe(
              res => {
                console.log(res);
              });
</code>```

I've already tested my Spring API through Insomnia (an API tester application) and it works without any problems (and I also checked that the JSON required by the back-end is well formatted so I don't think that the problem is this).

Where am I doing wrong?

答:
Modify your code to this code. Problem could be that your backend wants a json object but you are sending a string.

```<code>import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {FirstQuery} from '../../../_responseModels/firstQuery/first-query';
import {tap} from 'rxjs/operators';
import {stringify} from 'querystring';

@Injectable({
  providedIn: 'root'
})
export class ApiCenterSearch1Service {

  apiURL = 'http://127.0.0.1:8080/center/search_1/page/0';

  constructor(private httpClient: HttpClient) {}

  getFirstQuery(body: Object): any {

    return  this.httpClient.post<FirstQuery[]>(this.apiURL, body,
      {
        headers : new HttpHeaders({'Content-Type': 'application/json'})
        // observe: 'response'
      });
  }

}
</code>```

Service

```<code>funcThis.apiCenterSearch1Service.getFirstQuery(jsonRequest).subscribe(
  res => {
    console.log(res);
  });
</code>```

Body:
In my Angular application I'm trying to create a POST request, with a json body, that will be sent to my Spring Restful back-end; I have created a service in Angular to handle the API Post method but when I try to send the request, I obtain this error in my front-end console:

core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://127.0.0.1:8080/center/search_1/page/0", ok: false, …}

and this error in my back-end console:

Required request body is missing: public org.springframework.data.domain.Page

This is the code of my service in Angular:

import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {FirstQuery} from '../../../_responseModels/firstQuery/first-query';
import {tap} from 'rxjs/operators';
import {stringify} from 'querystring';

@Injectable({
  providedIn: 'root'
})
export class ApiCenterSearch1Service {

  apiURL = 'http://127.0.0.1:8080/center/search_1/page/0';

  constructor(private httpClient: HttpClient) {}

  getFirstQuery(body: JSON): any {

    return  this.httpClient.post<FirstQuery[]>(this.apiURL, JSON.stringify(body),
      {
        headers : new HttpHeaders({'Content-Type': 'application/json'})
        // observe: 'response'
      });
  }

}

and this is a part of the code of a component that triggers the API call:

funcThis.apiCenterSearch1Service.getFirstQuery(JSON.parse(jsonRequest)).subscribe(
              res => {
                console.log(res);
              });

I've already tested my Spring API through Insomnia (an API tester application) and it works without any problems (and I also checked that the JSON required by the back-end is well formatted so I don't think that the problem is this).

Where am I doing wrong?

Body:
Modify your code to this code. Problem could be that your backend wants a json object but you are sending a string.

import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {FirstQuery} from '../../../_responseModels/firstQuery/first-query';
import {tap} from 'rxjs/operators';
import {stringify} from 'querystring';

@Injectable({
  providedIn: 'root'
})
export class ApiCenterSearch1Service {

  apiURL = 'http://127.0.0.1:8080/center/search_1/page/0';

  constructor(private httpClient: HttpClient) {}

  getFirstQuery(body: Object): any {

    return  this.httpClient.post<FirstQuery[]>(this.apiURL, body,
      {
        headers : new HttpHeaders({'Content-Type': 'application/json'})
        // observe: 'response'
      });
  }

}

Service

funcThis.apiCenterSearch1Service.getFirstQuery(jsonRequest).subscribe(
  res => {
    console.log(res);
  });


问:
xpath to pull every descendant beside the nested target tag
I have xml file looking like this:

```<code><root>

  <a>
    <b> test </b>
      <a> test 2</a>

      <c> test 3 </c>
     <d> test4 </d>
     <e> test5
        <f> test6 </f>
        </e>
    </a>

</root>
</code>```

is there any xpath 1.0 to catch every descendant of  except the nested ?
I've tried something like :

```<code>//a/*[not(self::a)]

//a/descendant::*
</code>```

答:
Your attempt of //a/*[not(self::a)] was close.

The issue is that you're matching child elements of a.

Try this instead:

//a//*[not(self::a)]
```

Body:
I have xml file looking like this:

<root>

     test
       test 2

      <c> test 3 </c>
     <d> test4 </d>
     <e> test5
        <f> test6 </f>
        </e>

</root>

is there any xpath 1.0 to catch every descendant of  except the nested ?
I've tried something like :

//a/*[not(self::a)]

//a/descendant::*


问:
REVERSE function returns just a single char
Using the built in REVERSE function on a nvarchar I expect '51.02' to be returned but instead receive 2.

```<code>DECLARE @HourMins nvarchar = '20.15'

SELECT REVERSE(@HourMins) digs
</code>```

Can anyone tell me why?

答:
Always include a length with varchar() and related types!!!

```<code>DECLARE @HourMins nvarchar(255) = '20.15';
</code>```

The default varies by context.  In this context, the default is 1, which is clearly not enough for five characters.

Body:
Using the built in REVERSE function on a nvarchar I expect '51.02' to be returned but instead receive 2.

DECLARE @HourMins nvarchar = '20.15'

SELECT REVERSE(@HourMins) digs

Can anyone tell me why?

Body:
Always include a length with varchar() and related types!!!

DECLARE @HourMins nvarchar(255) = '20.15';

The default varies by context.  In this context, the default is 1, which is clearly not enough for five characters.


问:
Run commands using the output of one command and using them as input to the next
Based on the values in the second column, I need to run another command on these values.

```<code>[root@box ~]# for i in $(openstack server list --all -c ID -f value); do openstack server show $i -f value -c name -c project_id | xargs printf '%-60s %s\n'; done
cf1-0                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-3                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-2                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-0                                  ebf0f23f424c4417afd3e7bbf4e3900f
</code>```

Here's an example of what I'm trying to do.

```<code>[root@box ~]# for i in $(openstack server list --all -c ID -f value); do openstack server show $i -f value -c name -c project_id | xargs printf "%-60s eval(openstack project show %s -f value -c name)"; done
 cf1-0                                  eval(openstack project show ebf0f23f424c4417afd3e7bbf4e3900f -f value -c name)
</code>```

The substitution from the second %s in printf works correctly, but I can't figure out how to execute the command.

The command needs to be executed in the same shell, and I cannot use environment variables.

Thanks.

** OUTPUT OF COMMANDS **

Here, -c var1 -c var2 can be placed in any order. -f just means print out the values, not the identifier.

```<code>[root@box~]# openstack server list --all -c Name -c ID -f value
2534ce5a-04da-4c7d-9ad5-b7bc466ae612 cf1-0

[root@box ~]# openstack server show 2534ce5a-04da-4c7d-9ad5-b7bc466ae612 -f value -c name -c project_id
cf1-0
ebf0f23f424c4417afd3e7bbf4e3900f

[root@box ~]# openstack project show ebf0f23f424c4417afd3e7bbf4e3900f -f value -c name
core

Desired output
===============
cf1-0 core
</code>```

答:
Don't make things further convoluted by adding further levels of xargs. Recommend using a while loop reading the output at each stage and processing them further. The below works in bash with <(..) process substitution

```<code>#!/usr/bin/env bash

while read -r id instname; do
    proj="$(openstack server show "$id" -f value -c project_id)"
    [ -z "$proj" ] && break
    name="$(openstack project show "$proj" -f value -c name)"
    printf '%s %s\n' "$instname" "$name"
done < <(openstack server list --all -c ID -c Name -f value)
</code>```

Body:
Based on the values in the second column, I need to run another command on these values.

[root@box ~]# for i in $(openstack server list --all -c ID -f value); do openstack server show $i -f value -c name -c project_id | xargs printf '%-60s %s\n'; done
cf1-0                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-3                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-2                                  ebf0f23f424c4417afd3e7bbf4e3900f
sf1-0                                  ebf0f23f424c4417afd3e7bbf4e3900f

Here's an example of what I'm trying to do.

[root@box ~]# for i in $(openstack server list --all -c ID -f value); do openstack server show $i -f value -c name -c project_id | xargs printf "%-60s eval(openstack project show %s -f value -c name)"; done
 cf1-0                                  eval(openstack project show ebf0f23f424c4417afd3e7bbf4e3900f -f value -c name)

The substitution from the second %s in printf works correctly, but I can't figure out how to execute the command.

The command needs to be executed in the same shell, and I cannot use environment variables.

Thanks.

** OUTPUT OF COMMANDS **

Here, -c var1 -c var2 can be placed in any order. -f just means print out the values, not the identifier.

[root@box~]# openstack server list --all -c Name -c ID -f value
2534ce5a-04da-4c7d-9ad5-b7bc466ae612 cf1-0

[root@box ~]# openstack server show 2534ce5a-04da-4c7d-9ad5-b7bc466ae612 -f value -c name -c project_id
cf1-0
ebf0f23f424c4417afd3e7bbf4e3900f

[root@box ~]# openstack project show ebf0f23f424c4417afd3e7bbf4e3900f -f value -c name
core

Desired output
===============
cf1-0 core

Body:
Don't make things further convoluted by adding further levels of xargs. Recommend using a while loop reading the output at each stage and processing them further. The below works in bash with <(..) process substitution

#!/usr/bin/env bash

while read -r id instname; do
    proj="$(openstack server show "$id" -f value -c project_id)"
    [ -z "$proj" ] && break
    name="$(openstack project show "$proj" -f value -c name)"
    printf '%s %s\n' "$instname" "$name"
done < <(openstack server list --all -c ID -c Name -f value)


问:
I cannot give string value to a string variable in this code. Why? I also didn't understand the error meessage
FYI, I'm new to programming.
When I try to compile this code it gives error saying:

```<code>[Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11
[Error] initializer-string for array of chars is too long [-fpermissive]
</code>```

I have searched a lot but all of the articles use this exact method. Can anyone explain why am I getting this error? Explain in language I can understand. I didn't understand most of the answers and reasons stated.

```<code>#include <stdio.h>
struct person{
    char name[] = "something";
};
int main(){
    struct person per;
    printf("%s",per.name);
}
</code>```

答:
Simply - because C language does not allow it as C does not have constructors. You need to initialize the variables yourself when you define them.</p>

```<code>#include <stdio.h>
struct person{
    char name[100];
};
int main(){
    struct person per = {.name = "something"};
    printf("%s",per.name);
}
</code>```

Body:
FYI, I'm new to programming.
When I try to compile this code it gives error saying:

[Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11
[Error] initializer-string for array of chars is too long [-fpermissive]

I have searched a lot but all of the articles use this exact method. Can anyone explain why am I getting this error? Explain in language I can understand. I didn't understand most of the answers and reasons stated.

#include <stdio.h>
struct person{
    char name[] = "something";
};
int main(){
    struct person per;
    printf("%s",per.name);
}

Body:
Simply - because C language does not allow it as C does not have constructors. You need to initialize the variables yourself when you define them.

#include <stdio.h>
struct person{
    char name[100];
};
int main(){
    struct person per = {.name = "something"};
    printf("%s",per.name);
}


问:
Eloquent Relationships - hasOneThrough
---------- tables ----------

users

user_id

customers

customer_id

user_id

schedules

schedule_id

mail_id

customer_id

mails

mail_id

subject

--------- models ----------

schedules_model

```<code>public function customer()
{
    return $this->belongsTo('App\Customer', 'customer_id');
}
public function mail()
{
    return $this->belongsTo('App\Mail', 'mail_id');
}
public function user()
{
    return $this->hasOneThrough(?);
}
</code>```

--------- controllers ----------

```<code>$schedules = schedules_model->with('customer')->with('mail')->get();
</code>```

Please help me how to get user information through customer ?
Many thanks for your support!

答:
Why getting the user information from the schedule directly, you can simply do

$schedules = schedules_model->with('customer.user')->with('mail')->get();
```

Title: Eloquent Relationships - hasOneThrough

Body:
---------- tables ----------

users

user_id

customers

customer_id

user_id

schedules

schedule_id

mail_id

customer_id

mails

mail_id

subject

--------- models ----------

schedules_model

public function customer()
{
    return $this->belongsTo('App\Customer', 'customer_id');
}
public function mail()
{
    return $this->belongsTo('App\Mail', 'mail_id');
}
public function user()
{
    return $this->hasOneThrough(?);
}

--------- controllers ----------

$schedules = schedules_model->with('customer')->with('mail')->get();

Please help me how to get user information through customer ?
Many thanks for your support!


问:
Elasticsearch: Improve research using special field as P.K. into the template
The following is a templeate in ElasticSearch, my question is, if there is a way to promote one of these fields, for example timeStamp, as primary key to help the research during the query; like it happens on database usually.

```<code>  {
  "order": 0,
  "template": "simsamples-*",
  "settings": {
    "index": {
      "number_of_shards": "1"
    }
  },
  "mappings": {
    "ProbeSamples": {
      "properties": {
        "date": {
          "index": "no",
          "type": "string"
        },
        "timeStamp": {
          "format": "epoch_second",
          "type": "date"
        },
        "temperatures": {
          "type": "double"
        },
        "id": {
          "index": "not_analyzed",
          "type": "string"
        }
      }
    }
  }
}
</code>```

答:
There is no primary key in elasticsearch. Every document automatically has an _id field, which is a kind of a primary key because it is a unique identifier.

Elasticsearch is creating indices for every field, so there is no need to specify one as primary key.

Body:
The following is a templeate in ElasticSearch, my question is, if there is a way to promote one of these fields, for example timeStamp, as primary key to help the research during the query; like it happens on database usually.

  {
  "order": 0,
  "template": "simsamples-*",
  "settings": {
    "index": {
      "number_of_shards": "1"
    }
  },
  "mappings": {
    "ProbeSamples": {
      "properties": {
        "date": {
          "index": "no",
          "type": "string"
        },
        "timeStamp": {
          "format": "epoch_second",
          "type": "date"
        },
        "temperatures": {
          "type": "double"
        },
        "id": {
          "index": "not_analyzed",
          "type": "string"
        }
      }
    }
  }
}


问:
Fast page retrieval in MySQL, index usage?
I would like to speed a MySQL query that basically retrieve a page of data following the pattern below

```<code>select
 my_field_A,
 my_field_B
where
 time_id >= UNIX_TIMESTAMP('1901-01-01  00:00:00') AND
 time_id < UNIX_TIMESTAMP('2009-01-16  00:00:00')
</code>```

The field time_id is an MySQL index, yet, the query behaves as if the entire database was read at each query (retrieving a couple of lines being already quite slow). I not an expert in MySQL. Can someone guess what I am doing wrong?

答:
As there are probably lots of time_id's falling under these criteria, MySQL may think that the full table scan is better.

Try forcing the index:

```<code>SELECT
 my_field_A,
 my_field_B
FROM mytable FORCE INDEX (index_name_on_time_id)
WHERE
 time_id >= UNIX_TIMESTAMP('1901-01-01  00:00:00') AND
 time_id < UNIX_TIMESTAMP('2009-01-16  00:00:00')
</code>```

OwnerDisplayName: Joannes Vermorel

ContentLicense: CC BY-SA 2.5

Body:
I would like to speed a MySQL query that basically retrieve a page of data following the pattern below

select
 my_field_A,
 my_field_B
where
 time_id >= UNIX_TIMESTAMP('1901-01-01  00:00:00') AND
 time_id < UNIX_TIMESTAMP('2009-01-16  00:00:00')

The field time_id is an MySQL index, yet, the query behaves as if the entire database was read at each query (retrieving a couple of lines being already quite slow). I not an expert in MySQL. Can someone guess what I am doing wrong?

LastEditorDisplayName: Joannes Vermorel

Body:
As there are probably lots of time_id's falling under these criteria, MySQL may think that the full table scan is better.

Try forcing the index:

SELECT
 my_field_A,
 my_field_B
FROM mytable FORCE INDEX (index_name_on_time_id)
WHERE
 time_id >= UNIX_TIMESTAMP('1901-01-01  00:00:00') AND
 time_id < UNIX_TIMESTAMP('2009-01-16  00:00:00')

OwnerDisplayName: Quassnoi


问:
How to decode a JSON string?
On the server side do I have 2 hashes I encode into JSON strings like so

```<code>my $j = JSON->new;
$j = $j->utf8;

my $data;
$data->{users}  = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string    = to_json($data);

print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
</code>```

On the client side I have

```<code>$(document).ready(function(){

    $('form').live('submit', function(){

    $.ajax({
        type: "GET",
        url: "/cgi-bin/ajax_confirm.pl",
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        data: $(this).serialize(),

        error: function(XMLHttpRequest, textStatus, errorThrown) {
        $('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
                        ", textStatus: " + textStatus +
                        ", errorThrown: " + errorThrown);
        $('div#create_result').addClass("error");
        },

        success: function(result){
        if (result.error) {
            $('div#create_result').text("result.error: " + result.error);
            $('div#create_result').addClass("error");
        } else { // perl script says everything is okay

            var users  = result.users;
            var owners = result.owners;
...
</code>```

users contains

```<code>{"ss":"Sandra Schlichting","fn":"Full name"}
</code>```

but it is not an array. When I use $.each() it takes on character at a time.

Problem

How do I turn it into an array, so I can use

```<code>function makeTable(users) {
    var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
    $.each(users, function(index, value) {
        result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
    });
    result += '</table>';
    return (result);
}
</code>```

which should produce

```<code>Initials    Full Name
ss  Sandra Schlichting
fn  Full name
</code>```

答:
You should use jQuery.getJSON() as mentioned at http://api.jquery.com/jQuery.getJSON/.

There is also $.parseJSON() method to parse string to json if you want to go that way.

Title: How to decode a JSON string?

Body:
On the server side do I have 2 hashes I encode into JSON strings like so

my $j = JSON->new;
$j = $j->utf8;

my $data;
$data->{users}  = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string    = to_json($data);

print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;

On the client side I have

$(document).ready(function(){

    $('form').live('submit', function(){

    $.ajax({
        type: "GET",
        url: "/cgi-bin/ajax_confirm.pl",
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        data: $(this).serialize(),

        error: function(XMLHttpRequest, textStatus, errorThrown) {
        $('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
                        ", textStatus: " + textStatus +
                        ", errorThrown: " + errorThrown);
        $('div#create_result').addClass("error");
        },

        success: function(result){
        if (result.error) {
            $('div#create_result').text("result.error: " + result.error);
            $('div#create_result').addClass("error");
        } else { // perl script says everything is okay

            var users  = result.users;
            var owners = result.owners;
...

users contains

{"ss":"Sandra Schlichting","fn":"Full name"}

but it is not an array. When I use $.each() it takes on character at a time.

Problem

How do I turn it into an array, so I can use

function makeTable(users) {
    var result = '
\n
Initials	Full Name
\n';
    $.each(users, function(index, value) {
        result += '
' + index + '	' + value + '
\n';
    });
    result += '
';
    return (result);
}

which should produce

Initials    Full Name
ss  Sandra Schlichting
fn  Full name


问:
Why is my AWS Congito user able to sign in, but "not authenticated" when using Auth.currentAuthenticatedUser()?
I have manually added an AWS Cognito user to my application's user pool via the AWS management console. The required user pool credentials have been confirmed for this user. I am setting up an auth guard to control access to the routes. Whenever I use the Auth.signIn() function, the promise resolves successfully, however, when calling Auth.currentAuthenticatedUser() after signing in, the promise within the canActivate() function returns an error message "not authenticated". I have read GitHub issues on cookieStorage causing issues with this, but do not have this configured.

sign-in.component.ts

```<code>signIn(username, password) {

    return new Promise(() => {
        Auth
            .signIn(username, password)
            .then(() => {
                this.router.navigate(['main/dashboard']); // navigates to main/dashboard as expected
            })
            .catch(err => {
                this.authenticationError = err.message;
            })
    });
}
</code>```

auth.guard.ts

```<code>canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return Auth
               .currentAuthenticatedUser()
               .then(() => {
                   return true;
               })
               .catch((err) => {
                   this.router.navigate(['signin']);
                   console.log(err) // "not authenticated"
                   return false;
               });
}
</code>```

答:
Users created via the AWS management console are not considered authenticated unless the status field for that user is CONFIRMED. The status field in my case was FORCE_CHANGE_PASSWORD. AWS expects that users created via the console change their password after the first sign in or verify their account using an email or mobile verification. In the case of my app, I did not want to use either email or mobile verification. To resolve this I used the following aws-cli command for that user.</p>

```<code>aws cognito-idp admin-set-user-password --user-pool-id your_user_pool_id --username username --password password --permanent
</code>```

Body:
I have manually added an AWS Cognito user to my application's user pool via the AWS management console. The required user pool credentials have been confirmed for this user. I am setting up an auth guard to control access to the routes. Whenever I use the Auth.signIn() function, the promise resolves successfully, however, when calling Auth.currentAuthenticatedUser() after signing in, the promise within the canActivate() function returns an error message "not authenticated". I have read GitHub issues on cookieStorage causing issues with this, but do not have this configured.

sign-in.component.ts

signIn(username, password) {

    return new Promise(() => {
        Auth
            .signIn(username, password)
            .then(() => {
                this.router.navigate(['main/dashboard']); // navigates to main/dashboard as expected
            })
            .catch(err => {
                this.authenticationError = err.message;
            })
    });
}

auth.guard.ts

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return Auth
               .currentAuthenticatedUser()
               .then(() => {
                   return true;
               })
               .catch((err) => {
                   this.router.navigate(['signin']);
                   console.log(err) // "not authenticated"
                   return false;
               });
}

Body:
Users created via the AWS management console are not considered authenticated unless the status field for that user is CONFIRMED. The status field in my case was FORCE_CHANGE_PASSWORD. AWS expects that users created via the console change their password after the first sign in or verify their account using an email or mobile verification. In the case of my app, I did not want to use either email or mobile verification. To resolve this I used the following aws-cli command for that user.

aws cognito-idp admin-set-user-password --user-pool-id your_user_pool_id --username username --password password --permanent


问:
How to decline a pull request on Bitbucket from Python?
How do you use Bitbucket's 2.0 API to decline a pull request via Python?

According to their documentaion, it should be something like:

```<code>import requests
kwargs = {
    'username': MY_BITBUCKET_ACCOUNT,
    'repo_slug': MY_BITBUCKET_REPO,
    'pull_request_id': pull_request_id
}
url = 'https://api.bitbucket.org/2.0/repositories/{username}/{repo_slug}/pullrequests/{pull_request_id}/decline'.format(**kwargs)
headers = {'Content-Type': 'application/json'}
response = requests.post(url, auth=(USERNAME, PASSWORD), headers=headers)
</code>```

However, this fails with response.text simply saying "Bad Request".

This similar code works for me with their other API endpoints, so I'm not sure why the decline method is failing.

What am I doing wrong?

答:
You have to authenticate with Oath. I wrote a wrapper for making these requests. Here is a simple example that works. The only thing I couldn't figure out was how to add a reason it was declined. I ended up making a request before I declined the PR that added a comment on why it was declined.

import os

from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session

class Bitbucket(object):

    def __init__(self, client_id, client_secret, workplace, repo_slug):
        self.workplace = workplace  # username or company username
        self.repo_slug = repo_slug
        self.token_url = 'https://bitbucket.org/site/oauth2/access_token'
        self.api_url = 'https://api.bitbucket.org/2.0/'
        self.max_pages = 10
        self.client = BackendApplicationClient(client_id=client_id)
        self.oauth = OAuth2Session(client=self.client)
        self.oauth.fetch_token(
            token_url=self.token_url,
            client_id=client_id,
            client_secret=client_secret
        )

    def get_api_url(self, endpoint):
        return f'{self.api_url}repositories/{self.workplace}/{self.repo_slug}/{endpoint}'

bitbucket = Bitbucket(os.environ['BITBUCKET_KEY'], os.environ['BITBUCKET_SECRET'], workplace='foo', repo_slug='bar')
pr_id = 1234
resp = bitbucket.oauth.post(f"{bitbucket.get_api_url('pullrequests')}/{pr_id}/decline")
if resp.status_code == 200:
    print('Declined')
else:
    print('Someting went wrong.')
```

Body:
How do you use Bitbucket's 2.0 API to decline a pull request via Python?

According to their documentaion, it should be something like:

import requests
kwargs = {
    'username': MY_BITBUCKET_ACCOUNT,
    'repo_slug': MY_BITBUCKET_REPO,
    'pull_request_id': pull_request_id
}
url = 'https://api.bitbucket.org/2.0/repositories/{username}/{repo_slug}/pullrequests/{pull_request_id}/decline'.format(**kwargs)
headers = {'Content-Type': 'application/json'}
response = requests.post(url, auth=(USERNAME, PASSWORD), headers=headers)

However, this fails with response.text simply saying "Bad Request".

This similar code works for me with their other API endpoints, so I'm not sure why the decline method is failing.

What am I doing wrong?


问:
Text data in Haskell
I am really confused with this Text data in Haskell. Can someone explain me what values it has, where can it be used and what actually is the difference between it and a normal String. Thank you in advance. </p>

答:
A String is a list of Chars, it is defined as:

```<code>type String = [Char]
</code>```

This is however not a good format when you want to process a large amount of text in bulk. The overhead in terms of memory, and in cycles will be quite large.

The Text data type stores characters as a chunk of UTF-16 characters. This thus means that there is no memory overhead, and furthermore it is better in terms of caching if the characters are located next to each other, so processing is done faster.

If you make use of strict Text (the one you import from Data.Text), then it means that the text needs to fit in memory. The Data.Text.Lazy works with chucks, and thus lazily calculates the next chunk, and thus can sometimes operate on strings that do not fit in memory in total.

Title: Text data in Haskell

Body:
A String is a list of Chars, it is defined as:

type String = [Char]

This is however not a good format when you want to process a large amount of text in bulk. The overhead in terms of memory, and in cycles will be quite large.

The Text data type stores characters as a chunk of UTF-16 characters. This thus means that there is no memory overhead, and furthermore it is better in terms of caching if the characters are located next to each other, so processing is done faster.

If you make use of strict Text (the one you import from Data.Text), then it means that the text needs to fit in memory. The Data.Text.Lazy works with chucks, and thus lazily calculates the next chunk, and thus can sometimes operate on strings that do not fit in memory in total.


问:
using special character in router.navigate appears to cause infinite loop
Gmail allows for adding additional stuff at the end to email the same address even though the email is already in use. Like so:

random.email+23287@gmail.com

We use this for testing, sometimes. Unfortunately right now, whenever I use this kind of email to navigate I get an infinite loop from the what I think is the built-in URI encoder for router.navigate() caused by the + symbol

I tested other special characters and have come to the conclusion that this might be the case with this example:

```<code>gotoconfirmationpage() {
    this.router.navigate(['/confirmation', '%@gmail.com']);
  }
</code>```

and the router looks like this:

```<code>  {
    path: 'confirmation/:email',
    component: ConfirmationComponent
  },
</code>```

I've also tried pre-encoding before I navigate, but the same thing. It seems like for any character that gets encoded, which is % as well as others like #, &, and so on, once you navigate you get something like this:

and your history looks something like this...

I'm no expert, but I'm pretty sure the encoding result for the % symbol is %25 and it looks like it gets encoded and then the navigation sees it again and goes "oh look another one!" and then we get %25252525252525252525... to infinity.

I checked the dev page for navigation() and it looks like this might be an existing issue but I've yet to find the solution. If anyone has any information or a solution, it'd be greatly appreciated.

答:
Can you please try encoding the URI component using the following method.

```<code> gotoconfirmationpage() {
    this.router.navigate(['/confirmation', encodeURIComponent('%@gmail.com')]);
  }
</code>```

In the component you might need to decodeURIcomponent as well to get the actual value.

Body:
Gmail allows for adding additional stuff at the end to email the same address even though the email is already in use. Like so:

random.email+23287@gmail.com

We use this for testing, sometimes. Unfortunately right now, whenever I use this kind of email to navigate I get an infinite loop from the what I think is the built-in URI encoder for router.navigate() caused by the + symbol

I tested other special characters and have come to the conclusion that this might be the case with this example:

gotoconfirmationpage() {
    this.router.navigate(['/confirmation', '%@gmail.com']);
  }

and the router looks like this:

  {
    path: 'confirmation/:email',
    component: ConfirmationComponent
  },

I've also tried pre-encoding before I navigate, but the same thing. It seems like for any character that gets encoded, which is % as well as others like #, &, and so on, once you navigate you get something like this:

and your history looks something like this...

I'm no expert, but I'm pretty sure the encoding result for the % symbol is %25 and it looks like it gets encoded and then the navigation sees it again and goes "oh look another one!" and then we get %25252525252525252525... to infinity.

I checked the dev page for navigation() and it looks like this might be an existing issue but I've yet to find the solution. If anyone has any information or a solution, it'd be greatly appreciated.

Body:
Can you please try encoding the URI component using the following method.

 gotoconfirmationpage() {
    this.router.navigate(['/confirmation', encodeURIComponent('%@gmail.com')]);
  }

In the component you might need to decodeURIcomponent as well to get the actual value.


答:
you need a size for the nVarchar - </p>

```<code>DECLARE @HourMins nvarchar(5) = '20.15'
SELECT REVERSE(@HourMins) digs
</code>```

<p>-- 51.02 result</p>

Title: REVERSE function returns just a single char

Body:
Using the built in REVERSE function on a nvarchar I expect '51.02' to be returned but instead receive 2.

DECLARE @HourMins nvarchar = '20.15'

SELECT REVERSE(@HourMins) digs

Can anyone tell me why?

Body:
you need a size for the nVarchar -

DECLARE @HourMins nvarchar(5) = '20.15'
SELECT REVERSE(@HourMins) digs

-- 51.02 result


问:
trying to debug npapi plugin in Chrome and Firefox , without success what is the right way?
i build working npapi pluging using firebreath framework , and its working just fine.

i compiled in debug mode . did regsvr32 myddl.dll and restart the Chrome browser.

now in visual studio 2008 express and did attached to process attached to Chrome process

but when i try to set breakpoint in the dll source code it gives me the error:

The breakpoint will not currently be
  hit. No symbols have been loaded for
  this document.

why this is the source of the plugin and its in debug mode .

this is also happen when i try with firefox browser , so i guess its something with my visual studio configuration

答: Chrome (and also Firefox) runs plugins out of process, so you aren't actually attaching to the process that has your plugin code. Run Chrome with the --plugin-startup-dialog flag, and when your plugin process starts Chrome will give you the process ID of the plugin process and then pause the plugin process and wait for a debugger to attach.


问:
How to use ChangeNotifier with Navigator
In my app, I have a model that store the user logged in my app.

```<code>class AuthenticationModel extends ChangeNotifier {
  User _user;
  User get user => _user;

  void authenticate(LoginData loginData) async {
    // _user = // get user from http call
    notifyListeners();
  }

  void restoreUser() async {
    //_user = // get user from shared prefs
    notifyListeners();
  }
}
</code>```

The model is registered at the top of the widget tree :

```<code>void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AuthenticationModel(),
      child: MaterialApp(
        title: 'My App',
        initialRoute: '/',
        routes: {
          '/': (context) => PrehomeScreen(),
          '/home': (context) => HomeScreen()
        },
      ),
    );
  }
}
</code>```

Somewhere down the widget tree, I have a button that calls the Model :

```<code>          child: Consumer<AuthenticationModel>(
            builder: (context, authModel, child) {
              return MyCustomButton(
                text: 'Connect',
                onPressed: () {
                  authModel.authenticate(...)
                },
              );
            },
          ),
</code>```

Now, I would like, somewhere, listen to the changes on the AuthenticationModel to trigger a Navigator.pushReplacmentNamed('/home') when the user is not null in the model.

I tried to do it in the builder of Prehome :

```<code>class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<AuthenticationModel>(
      builder: (context, authModel, child) {
        if (authModel.user != null) {
          Navigator.of(context).pushReplacementNamed("/home")
        }
        return Container(
          child: // Prehome UI
        );
      },
    );
  }
}
</code>```

but I have a error when doing it like this :

```<code>════════ (2) Exception caught by widgets library ═══════════════════════════════════════════════════
setState() or markNeedsBuild() called during build.
The relevant error-causing widget was:
  Consumer<AuthenticationModel> file:///Users/pierre.degand/Projects/cdc/course_du_coeur/lib/Prehome.dart:13:12
═══════════════════════════════════════════════════════════════════════════════
</code>```

How can I setup such a listener ? Is it a good practice to trigger navigation on model changes like this ?

Thanks

EDIT: I found a way to make this work. Instead of using Consumer inside the PrehomeScreen builder, I used the following code :

```<code>class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    Provider.of<AuthenticationModel>(context).addListener(() {
      Navigator.of(context).pushReplacementNamed("/home");
    });

    return Container(
      child: // UI
    );
  }
}
</code>```

It works fine, the navigation is executed when the model changes. But there is an error message in the console (printed 3 times) :

```<code>════════ (4) Exception caught by foundation library ════════════════════════════════════════════════
Looking up a deactivated widget's ancestor is unsafe.
════════════════════════════════════════════════════════════════════════════════════════════════════
</code>```

The app does not crash so, for now, I'm ok with this.
I still want to know if this is a good approach or not.

答:
```<code>void main() {
  Provider.debugCheckInvalidValueType = null;

  return runApp(
    Provider(
      create: (_) => AuthenticationModel(),
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final navigatorKey = GlobalKey<NavigatorState>();

    Provider.of<AuthenticationModel>(context).addListener(() {
      final authModel = Provider.of<AuthenticationModel>(context);

      if (authModel.user != null) {
        navigatorKey.currentState.pushReplacementNamed("/home");
      }
    });

    return MaterialApp(
      navigatorKey: navigatorKey,
      title: 'My App',
      initialRoute: '/',
      routes: {
        '/': (context) => PrehomeScreen(),
        '/home': (context) => HomeScreen()
      },
    );
  }
}
</code>```

Body:
In my app, I have a model that store the user logged in my app.

class AuthenticationModel extends ChangeNotifier {
  User _user;
  User get user => _user;

  void authenticate(LoginData loginData) async {
    // _user = // get user from http call
    notifyListeners();
  }

  void restoreUser() async {
    //_user = // get user from shared prefs
    notifyListeners();
  }
}

The model is registered at the top of the widget tree :

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AuthenticationModel(),
      child: MaterialApp(
        title: 'My App',
        initialRoute: '/',
        routes: {
          '/': (context) => PrehomeScreen(),
          '/home': (context) => HomeScreen()
        },
      ),
    );
  }
}

Somewhere down the widget tree, I have a button that calls the Model :

          child: Consumer<AuthenticationModel>(
            builder: (context, authModel, child) {
              return MyCustomButton(
                text: 'Connect',
                onPressed: () {
                  authModel.authenticate(...)
                },
              );
            },
          ),

Now, I would like, somewhere, listen to the changes on the AuthenticationModel to trigger a Navigator.pushReplacmentNamed('/home') when the user is not null in the model.

I tried to do it in the builder of Prehome :

class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<AuthenticationModel>(
      builder: (context, authModel, child) {
        if (authModel.user != null) {
          Navigator.of(context).pushReplacementNamed("/home")
        }
        return Container(
          child: // Prehome UI
        );
      },
    );
  }
}

but I have a error when doing it like this :

════════ (2) Exception caught by widgets library ═══════════════════════════════════════════════════
setState() or markNeedsBuild() called during build.
The relevant error-causing widget was:
  Consumer<AuthenticationModel> file:///Users/pierre.degand/Projects/cdc/course_du_coeur/lib/Prehome.dart:13:12
═══════════════════════════════════════════════════════════════════════════════

How can I setup such a listener ? Is it a good practice to trigger navigation on model changes like this ?

Thanks

EDIT: I found a way to make this work. Instead of using Consumer inside the PrehomeScreen builder, I used the following code :

class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    Provider.of<AuthenticationModel>(context).addListener(() {
      Navigator.of(context).pushReplacementNamed("/home");
    });

    return Container(
      child: // UI
    );
  }
}

It works fine, the navigation is executed when the model changes. But there is an error message in the console (printed 3 times) :

════════ (4) Exception caught by foundation library ════════════════════════════════════════════════
Looking up a deactivated widget's ancestor is unsafe.
════════════════════════════════════════════════════════════════════════════════════════════════════

The app does not crash so, for now, I'm ok with this.
I still want to know if this is a good approach or not.