问:
Get file names from folder and subfolder function change
i have this code below to get files names from a specific folder and it works great. i like how is transposes the file names it works really well with how i do my work.

what i want to change is to have it also return the file names with in the subfolders to. but carry on transposing it accrss my work sheet.

Thank you.

```<code>Function GetFileNames6(ByVal FolderPath As String) As Variant
Dim Result As Variant
Dim i As Integer
Dim MyFile As Object
Dim MyFSO As Object
Dim myFolder As Object
Dim MyFiles As Object
Set MyFSO = CreateObject("Scripting.FileSystemObject")
Set myFolder = MyFSO.GetFolder(FolderPath)
Set MyFiles = myFolder.Files
ReDim Result(1 To MyFiles.Count)
i = 1
o = 1
For Each MyFile In MyFiles
Result(i) = MyFile.name & " " & MyFile.DateCreated
i = i + 1

Next MyFile
GetFileNames6 = Result

End Function
</code>```

答:
Return File Names From All Folders and Subfolders

Issues

Files containing 'non-standard' characters like e.g. žćčšđ will be returned by the ArrFilePaths function using the WScript Host but will not be found by the FileSystemObject object (nor the Dir function) hence the complications in the GetFileNames6function. If you have such characters in your file- or folder names, you can ask another question.

I've used something like Dim Arr() As String: Arr = Split("") to get an 'empty' string array in both functions. Not sure if that's the ideal way since I've never seen it done before.

Option Explicit

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Tests the 'GetFileNames6' function.
' Calls:        GetFileNames6
'                   ArrFilePaths
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub GetFileNames6TEST()

    Const FolderPath As String = "C:\Test\"

    Dim NamesDates() As String: NamesDates = GetFileNames6(FolderPath)

    If UBound(NamesDates) = -1 Then
        Debug.Print "No files found."
        Exit Sub
    End If

    Debug.Print Join(NamesDates, vbLf)

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns a zero-based string array containing the concatenated
'               names and dates ('DateCreated') from a given zero-based string
'               array containing file paths.
' Calls:        ArrFilePaths.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetFileNames6( _
    ByVal FolderPath As String, _
    Optional ByVal Delimiter As String = " ") _
As String()
    Const ProcName As String = "GetFileNames6"
    On Error GoTo ClearError

    ' Ensuring that a string array is passed if an error occurs.
    GetFileNames6 = Split("") ' LB = 0 , UB = -1

    Dim FilePaths() As String: FilePaths = ArrFilePaths(FolderPath)
    'Debug.Print Join(FilePaths, vbLf)

    Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")

    Dim fsoFile As Object
    Dim n As Long ' Files Count
    Dim fCount As Long ' Found Files Count

    For n = 0 To UBound(FilePaths)
        If fso.FileExists(FilePaths(n)) Then
            Set fsoFile = fso.GetFile(FilePaths(n))
            FilePaths(fCount) = fsoFile.Name & Delimiter & fsoFile.DateCreated
            fCount = fCount + 1
        Else ' happens if not 'standard characters' (character map?)
            Debug.Print "Not found:             " & FilePaths(n)
        End If
    Next n

    If fCount < n Then
        ReDim Preserve FilePaths(0 To fCount - 1)
        'Debug.Print Join(FilePaths, vbLf)
        Debug.Print "Initially found files: " & n
        Debug.Print "Finally found files:   " & fCount
    End If

    GetFileNames6 = FilePaths

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns the file paths of the files in a folder in an array.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function ArrFilePaths( _
    ByVal FolderPath As String, _
    Optional ByVal FilePattern As String = "*.*", _
    Optional ByVal DirSwitches As String = "/s/b/a-d") _
As String()
    Const ProcName As String = "ArrFilePaths"
    On Error GoTo ClearError

    ' Ensuring that a string array is passed if an error occurs.
    ArrFilePaths = Split("") ' LB = 0 , UB = -1

    Dim pSep As String: pSep = Application.PathSeparator
    If Right(FolderPath, 1) <> pSep Then FolderPath = FolderPath & pSep
    Dim ExecString As String ' '%comspec%' or 'cmd.exe' ?
    ExecString = "%comspec% /c Dir """ _
        & FolderPath & FilePattern & """ " & DirSwitches
    Dim Arr() As String: Arr = Split(CreateObject("WScript.Shell") _
        .Exec(ExecString).StdOut.ReadAll, vbCrLf)
    If UBound(Arr) > 0 Then
        ReDim Preserve Arr(0 To UBound(Arr) - 1)
    End If
    ArrFilePaths = Arr

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function
```

Body:
i have this code below to get files names from a specific folder and it works great. i like how is transposes the file names it works really well with how i do my work.

what i want to change is to have it also return the file names with in the subfolders to. but carry on transposing it accrss my work sheet.

Thank you.

Function GetFileNames6(ByVal FolderPath As String) As Variant
Dim Result As Variant
Dim i As Integer
Dim MyFile As Object
Dim MyFSO As Object
Dim myFolder As Object
Dim MyFiles As Object
Set MyFSO = CreateObject("Scripting.FileSystemObject")
Set myFolder = MyFSO.GetFolder(FolderPath)
Set MyFiles = myFolder.Files
ReDim Result(1 To MyFiles.Count)
i = 1
o = 1
For Each MyFile In MyFiles
Result(i) = MyFile.name & " " & MyFile.DateCreated
i = i + 1

Next MyFile
GetFileNames6 = Result

End Function


来源: stackexchange

问:
jQuery/JavaScript "this" pointer confusion
The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

```<code>// a class with a method

function foo() {

    this.bar();  // when called here, "this" is the foo instance

    var barf = this.bar;
    barf();   // when called here, "this" is the global object

    // when called from a click, "this" is the html element
    $("#thing").after($("<div>click me</div>").click(barf));
}

foo.prototype.bar = function() {
    alert(this);
}
</code>```

答:
This is because this is always the instance that the function is attached to. In the case of an EventHandler it is the class that triggered the event.

You can help your self with an anonymous function like this:

```<code>function foo() {
  var obj = this;
  $("#thing").after($("<div>click me</div>").click(function(){obj.bar();}));
}

foo.prototype.bar = function() {
  alert(this);
}
</code>```

OwnerDisplayName: I. J. Kennedy

ContentLicense: CC BY-SA 2.5

Body:
The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

// a class with a method

function foo() {

    this.bar();  // when called here, "this" is the foo instance

    var barf = this.bar;
    barf();   // when called here, "this" is the global object

    // when called from a click, "this" is the html element
    $("#thing").after($("
click me
").click(barf));
}

foo.prototype.bar = function() {
    alert(this);
}

Body:
This is because this is always the instance that the function is attached to. In the case of an EventHandler it is the class that triggered the event.

You can help your self with an anonymous function like this:

function foo() {
  var obj = this;
  $("#thing").after($("<div>click me</div>").click(function(){obj.bar();}));
}

foo.prototype.bar = function() {
  alert(this);
}

OwnerDisplayName: mutzel

LastEditorDisplayName: mutzel


问:
GetDrives and Files Sometimes Failing
I am recursively entering my computer drives to list all files available. But sometimes the program runs then stops and says it can't access a directory. </p>

<p>What should I do now, I am using win7. </p>

答: Some of your directories are not readable for your user account. Please show some code or the correct error methods where its throwing exceptions for you. </p>

ContentLicense: CC BY-SA 3.0

Title: GetDrives and Files Sometimes Failing

Body:
I am recursively entering my computer drives to list all files available. But sometimes the program runs then stops and says it can't access a directory.

What should I do now, I am using win7.


问:
List<Integer> to List<Long> conversion in Java 11 using Streams
I have a list of Integer and would like to convert into a list of Long (or any other type) by using Streams. I tried multiple options but all failed. How do I do that?</p>
```<code>List<Integer> arr = new ArrayList<Integer>();
    arr.add(1);
    arr.add(3);
    arr.add(5);
    arr.add(7);
    arr.add(9);
</code>```

答:
```<code>List<Long> longList =  arr.stream().map(Long::valueOf).collect(Collectors.toList());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list of Integer and would like to convert into a list of Long (or any other type) by using Streams. I tried multiple options but all failed. How do I do that?

List<Integer> arr = new ArrayList<Integer>();
    arr.add(1);
    arr.add(3);
    arr.add(5);
    arr.add(7);
    arr.add(9);


问:
reuse nested variables declared in another repository
With Auzre pipeline, I would like to how to reuse the variables declared in another repository.

Just a background, if all the three files organization_vars.yml, project_vars.yml, and cicd.yml are in the same repo, without using the resources like shown in project_vars.yml, it works.

Now I need to put the file organization_vars.yml in another repository in order to share it to every projects in the same organization, I tried with resources as explained here: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/templates?view=azure-devops#use-other-repositories , but it doesn't work.

In the pipeline, I got the error message Unexpected value 'resources' from the very beginning.

Hereunder a simplified example for the 3 files:

# file organization_vars.yml in the calling repository

variables:
  orgName: xxx
```
<pre class="lang-yaml prettyprint-override"><code># file project_vars.yml in the caller repository

resources:
  repositories:
    - repository: calling_repository
      type: git
      name: another_project/calling_repository

variables:
  - template: organization_vars.yml@caller_repository
  - name: callerVar
    value: $(orgName)_xxx
</code>```

# file cicd.yml in the caller repository, this file will be runned by the pipeline

trigger: xxx

variables:
  - template: project_vars.yml
  - name: otherVar
    value: xxx

pool:
  vmImage: xxx

steps:
  xxx
```

答: I found it by myself, just need to move the resources part from the file project_vars.yml to the file cicd.yml

Body:
With Auzre pipeline, I would like to how to reuse the variables declared in another repository.

Just a background, if all the three files organization_vars.yml, project_vars.yml, and cicd.yml are in the same repo, without using the resources like shown in project_vars.yml, it works.

Now I need to put the file organization_vars.yml in another repository in order to share it to every projects in the same organization, I tried with resources as explained here: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/templates?view=azure-devops#use-other-repositories , but it doesn't work.

In the pipeline, I got the error message Unexpected value 'resources' from the very beginning.

Hereunder a simplified example for the 3 files:

# file organization_vars.yml in the calling repository

variables:
  orgName: xxx

# file project_vars.yml in the caller repository

resources:
  repositories:
    - repository: calling_repository
      type: git
      name: another_project/calling_repository

variables:
  - template: organization_vars.yml@caller_repository
  - name: callerVar
    value: $(orgName)_xxx

# file cicd.yml in the caller repository, this file will be runned by the pipeline

trigger: xxx

variables:
  - template: project_vars.yml
  - name: otherVar
    value: xxx

pool:
  vmImage: xxx

steps:
  xxx


问:
JavaScript array flatting
i need to get every unique color in the array below fit in one single array

const colours = [{
    mood: "happy",
    fish: "robin",
    colours: ["blue", "green"]
  },
  {
    mood: "tired",
    fish: "panther",
    colours: ["green", "black", "orange", "blue"]
  },
  {
    mood: "sad",
    fish: "goldfish",
    colours: ["green", "red"]
  }
];
console.log(colours.map(e => {
  let flatArray = e.colours.reduce((acc, curVal) => {
    return acc.concat(curVal)
  }, []);
  return flatArray
}))```
</div>
</div>
</p>
<p>It currently outputs:</p>
```[
   [ 'blue', 'green' ],
   [ 'green', 'black', 'orange', 'blue' ],
   [ 'green', 'red' ]
]
```

答:
 let colours = [{
        mood: "happy",
        fish: "robin",
        colours: ["blue", "green"]
    },
    {
        mood: "tired",
        fish: "panther",
        colours: ["green", "black", "orange", "blue"]
    },
    {
        mood: "sad",
        fish: "goldfish",
        colours: ["green", "red"]
    }];

let distinct =(value,index,self)=>{return self.indexOf(value)===index;};

console.log(colours.reduce((acc, curVal) => {
        return acc.concat(curVal.colours)
    }, []).filter(distinct));```

Title: JavaScript array flatting

Body:
i need to get every unique color in the array below fit in one single array

const colours = [{
    mood: "happy",
    fish: "robin",
    colours: ["blue", "green"]
  },
  {
    mood: "tired",
    fish: "panther",
    colours: ["green", "black", "orange", "blue"]
  },
  {
    mood: "sad",
    fish: "goldfish",
    colours: ["green", "red"]
  }
];
console.log(colours.map(e => {
  let flatArray = e.colours.reduce((acc, curVal) => {
    return acc.concat(curVal)
  }, []);
  return flatArray
}))

It currently outputs:

[
   [ 'blue', 'green' ],
   [ 'green', 'black', 'orange', 'blue' ],
   [ 'green', 'red' ]
]


问:
Openrowset with bulk option cannot retrieve records due to an invalid type DATE
When trying to read a parquet file with the openrowset and bulk options I encounter the following error:

Error handling external file: 'Inserting value to batch for column type DATE failed. Invalid argument provided.'

This problem indicates that the file couldn't be read because the data contains values that are not DATE type - indeed, there are undefined and 0001-01-01 records, so when the BULK operation is performed these values prevent from loading the entire parquet file (see the code from below).

```<code>SELECT
TOP 100
POST_SEARCH_DATE,
SEARCH_DATE

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'

) AS [result]
</code>```

One alternative I thought was to convert the column to a varchar to bypass the error but unfortunately, that didn't make any difference (see below).

```<code>SELECT
TOP 100
POST_SEARCH_DATE,
SEARCH_DATE

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'

) AS [result]

WHERE cast(POST_SEARCH_DEPARTURE_DATE as varchar(100))!= 'undefined'

and cast (SEARCH_DEPARTURE_DATE as varchar(100)) != 'undefined'
and cast (SEARCH_DEPARTURE_DATE as varchar(100)) != '0001-01-01'
and cast(POST_SEARCH_DEPARTURE_DATE as varchar(100))!= '0001-01-01'
</code>```

I found some suggestions about inserting every record into a temporary table and from there you can disregard the records that fail. Can someone help me to give me more details about this solution or another alternative?

答:
Have you tried using WITH to define the data types, while using OPENROWSET?

```<code>SELECT
  TOP 100
  POST_SEARCH_DATE,
  SEARCH_DATE,
  EXAMPLE_COL

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'
    WITH (
        [SEARCH_DEPARTURE_DATE] VARCHAR(100) COLLATE Latin1_General_BIN2 3,
        [POST_SEARCH_DEPARTURE_DATE] VARCHAR(100) COLLATE Latin1_General_BIN2 2,
        [EXAMPLE_COL] VARCHAR(100)
) AS [r]
</code>```

Body:
When trying to read a parquet file with the openrowset and bulk options I encounter the following error:

Error handling external file: 'Inserting value to batch for column type DATE failed. Invalid argument provided.'

This problem indicates that the file couldn't be read because the data contains values that are not DATE type - indeed, there are undefined and 0001-01-01 records, so when the BULK operation is performed these values prevent from loading the entire parquet file (see the code from below).

SELECT
TOP 100
POST_SEARCH_DATE,
SEARCH_DATE

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'

) AS [result]

One alternative I thought was to convert the column to a varchar to bypass the error but unfortunately, that didn't make any difference (see below).

SELECT
TOP 100
POST_SEARCH_DATE,
SEARCH_DATE

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'

) AS [result]

WHERE cast(POST_SEARCH_DEPARTURE_DATE as varchar(100))!= 'undefined'

and cast (SEARCH_DEPARTURE_DATE as varchar(100)) != 'undefined'
and cast (SEARCH_DEPARTURE_DATE as varchar(100)) != '0001-01-01'
and cast(POST_SEARCH_DEPARTURE_DATE as varchar(100))!= '0001-01-01'

I found some suggestions about inserting every record into a temporary table and from there you can disregard the records that fail. Can someone help me to give me more details about this solution or another alternative?

Body:
Have you tried using WITH to define the data types, while using OPENROWSET?

SELECT
  TOP 100
  POST_SEARCH_DATE,
  SEARCH_DATE,
  EXAMPLE_COL

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'
    WITH (
        [SEARCH_DEPARTURE_DATE] VARCHAR(100) COLLATE Latin1_General_BIN2 3,
        [POST_SEARCH_DEPARTURE_DATE] VARCHAR(100) COLLATE Latin1_General_BIN2 2,
        [EXAMPLE_COL] VARCHAR(100)
) AS [r]


问:
Start a build and passing variables through Azure DevOps Rest API
I would like to start a Azure Pipelines build through the REST API. There is an API for queuing builds but I couldn't find a way to define variables.</p>

答:
For anyone looking this, I was able to make it work with 'templateParameters', which allow you to send an Object instead of a String on version 7.1.

Method: POST

URL: https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=7.1-preview.7

Body: JSON example:

{
  "sourceBranch":"Development",
  "definition": {
    "id": 5
  }
  "templateParameters": {
    "PARAMETER1": "value1",
    "parameter2": "valuex"
  }
}
```

Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/build/builds/queue?view=azure-devops-rest-7.1

Body:
For anyone looking this, I was able to make it work with 'templateParameters', which allow you to send an Object instead of a String on version 7.1.

Method: POST

URL: https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=7.1-preview.7

Body: JSON example:

{
  "sourceBranch":"Development",
  "definition": {
    "id": 5
  }
  "templateParameters": {
    "PARAMETER1": "value1",
    "parameter2": "valuex"
  }
}

Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/build/builds/queue?view=azure-devops-rest-7.1


问:
Printing Fibonacci Series having 2 similar codes but different outputs. Why?
Resolve CODE 2 to print output as CODE 1 and give the reason why both of the codes have different outputs.

Fibonacci Series

CODE 1

```<code>x = 0
y = 1
while x < 10:
    print(x)
    x, y = y, x + y
</code>```

output
0
1
1
2
3
5
8

CODE 2

```<code>x = 0
y = 1
while x < 10:
    print(x)
    x = y
    y = x + y
</code>```

Output
0
1
2
4
8

答:
Those are simply not identical.
In the first code block y becomes x+y and in the second code block y becomes 2*y.

Just a quick note the output of the second code block is 0 1 2 4 8 and not what you wrote (this was fixed).

Body:
Resolve CODE 2 to print output as CODE 1 and give the reason why both of the codes have different outputs.

Fibonacci Series

CODE 1

x = 0
y = 1
while x < 10:
    print(x)
    x, y = y, x + y

output
0
1
1
2
3
5
8

CODE 2

x = 0
y = 1
while x < 10:
    print(x)
    x = y
    y = x + y

Output
0
1
2
4
8


问:
Grpc python SSLV3_ALERT_HANDSHAKE_FAILURE
I'm working in a project which is based on Grpc. Nevertheless I have a problem when I try to connect to my service with the following code:

import grpc
from grpc_health.v1 import health_pb2
from grpc_health.v1 import health_pb2_grpc

with open('ca_chain_pem_path', 'rb') as f:
    ca = f.read()
credentials = grpc.ssl_channel_credentials(ca)
with grpc.secure_channel('host_domain:50051', credentials) as channel:
    stub = health_pb2_grpc.HealthStub(channel)
    request = health_pb2.HealthCheckRequest()
    response = stub.Check(request)
```

It raises the following error:
Handshake failed with fatal error SSL_ERROR_SSL: error:10000410:SSL routines:OPENSSL_internal:SSLV3_ALERT_HANDSHAKE_FAILURE and I do not know how to fix it. My service is located behind a load balancer in AWS and I can connect to it via grpcurl and grpcui but not with python and it's frustrating.

I was looking for a solution in google and in this page without success. Thanks in advance

PD: the certificate I'm reading in the code is the one that sign the deployed service in the aws domain

答:
if it's a private certificate I think you should also specify it to ssl_channel_credentials:

```<code>with open(certs_folder / "client.key", 'rb') as fh:
    key = fh.read()
with open(certs_folder / "client.pem", 'rb') as fh:
    cert = fh.read()
with open(certs_folder / "server.pem", 'rb') as fh:
    root_ca = fh.read()

credentials = grpc.ssl_channel_credentials(root_certificates=root_ca,
    private_key=key, certificate_chain=cert)
</code>```

does the host_domain:50051 matches what's in the certificate? If not you may need to use options=(('grpc.ssl_target_name_override', in the grpc.secure_channel

Body:
I'm working in a project which is based on Grpc. Nevertheless I have a problem when I try to connect to my service with the following code:

import grpc
from grpc_health.v1 import health_pb2
from grpc_health.v1 import health_pb2_grpc

with open('ca_chain_pem_path', 'rb') as f:
    ca = f.read()
credentials = grpc.ssl_channel_credentials(ca)
with grpc.secure_channel('host_domain:50051', credentials) as channel:
    stub = health_pb2_grpc.HealthStub(channel)
    request = health_pb2.HealthCheckRequest()
    response = stub.Check(request)

It raises the following error:
Handshake failed with fatal error SSL_ERROR_SSL: error:10000410:SSL routines:OPENSSL_internal:SSLV3_ALERT_HANDSHAKE_FAILURE and I do not know how to fix it. My service is located behind a load balancer in AWS and I can connect to it via grpcurl and grpcui but not with python and it's frustrating.

I was looking for a solution in google and in this page without success. Thanks in advance

PD: the certificate I'm reading in the code is the one that sign the deployed service in the aws domain

Body:
if it's a private certificate I think you should also specify it to ssl_channel_credentials:

with open(certs_folder / "client.key", 'rb') as fh:
    key = fh.read()
with open(certs_folder / "client.pem", 'rb') as fh:
    cert = fh.read()
with open(certs_folder / "server.pem", 'rb') as fh:
    root_ca = fh.read()

credentials = grpc.ssl_channel_credentials(root_certificates=root_ca,
    private_key=key, certificate_chain=cert)

does the host_domain:50051 matches what's in the certificate? If not you may need to use options=(('grpc.ssl_target_name_override', in the grpc.secure_channel


问:
Count co-occurrences of two words but the order is not important in r
WHAT I WANT: I want to count co-occurrence of two words. But I don't care the order they appear in the string.

MY PROBLEM: I don't know how to deal When two given words appear in different order.

SO FAR: I use unnest_token function to split the string by words using the "skip_ngrams" option for the token argument. Then I filtered the combination of exactly two words. I use separate to create word1 and word2 columns. Finally, I count the occurrence.

The output that I get is like this:

```<code># A tibble: 3 × 3
  word1 word2      n
  <chr> <chr>  <dbl>
1 a     c          3
2 b     a          1
3 c     a          5
</code>```

But words "a" and "c" occur in a different order so they are counted as a different element. What I want is this:

```<code># A tibble: 2 × 3
  word1 word2      n
  <chr> <chr>  <dbl>
1 a     c          8
2 b     a          1
</code>```

MY DATA: My data looks like this and this is the whole process with different data but the same problem. In this case "a b" and "c a" should take a value of n = 2.

library(tidyverse)
library(tidytext)
enframe(c("a b c a d e")) %>%
  unnest_tokens(skipgram, value, token = "skip_ngrams", n = 5) %>%
  mutate(n_words = str_count(skipgram, pattern = "\\S+")) %>%
  filter(n_words == 2) %>%
  separate(col = skipgram, into = c("word1", "word2"), sep = "\\s+") %>%
  count(word1, word2)
#> # A tibble: 9 × 3
#>   word1 word2     n
#>   <chr> <chr> <int>
#> 1 a     b         1
#> 2 a     c         1
#> 3 a     d         1
#> 4 a     e         1
#> 5 b     a         1
#> 6 b     c         1
#> 7 c     a         1
#> 8 c     d         1
#> 9 d     e         1
```

Created on 2022-02-09 by the reprex package (v2.0.1)

答:
The pmin/pmax approach by @akrun is super efficient. Here is another option with igraph

```<code>library(tidytext)
library(dplyr)
library(stringr)
library(tidyr)
library(igraph)

enframe(c("a b c a d e")) %>%
  unnest_tokens(skipgram, value, token = "skip_ngrams", n = 5) %>%
  mutate(n_words = str_count(skipgram, pattern = "\\S+")) %>%
  filter(n_words == 2) %>%
  separate(col = skipgram, into = c("word1", "word2"), sep = "\\s+") %>%
  count(word1, word2) %>%
  graph_from_data_frame(directed = FALSE) %>%
  simplify(edge.attr.comb = "sum") %>%
  get.data.frame()
</code>```

which gives

```<code>  from to n
1    a  b 2
2    a  c 2
3    a  d 1
4    a  e 1
5    b  c 1
6    c  d 1
7    d  e 1
</code>```

Body:
WHAT I WANT: I want to count co-occurrence of two words. But I don't care the order they appear in the string.

MY PROBLEM: I don't know how to deal When two given words appear in different order.

SO FAR: I use unnest_token function to split the string by words using the "skip_ngrams" option for the token argument. Then I filtered the combination of exactly two words. I use separate to create word1 and word2 columns. Finally, I count the occurrence.

The output that I get is like this:

# A tibble: 3 × 3
  word1 word2      n
  <chr> <chr>  <dbl>
1 a     c          3
2 b     a          1
3 c     a          5

But words "a" and "c" occur in a different order so they are counted as a different element. What I want is this:

# A tibble: 2 × 3
  word1 word2      n
  <chr> <chr>  <dbl>
1 a     c          8
2 b     a          1

MY DATA: My data looks like this and this is the whole process with different data but the same problem. In this case "a b" and "c a" should take a value of n = 2.

library(tidyverse)
library(tidytext)
enframe(c("a b c a d e")) %>%
  unnest_tokens(skipgram, value, token = "skip_ngrams", n = 5) %>%
  mutate(n_words = str_count(skipgram, pattern = "\\S+")) %>%
  filter(n_words == 2) %>%
  separate(col = skipgram, into = c("word1", "word2"), sep = "\\s+") %>%
  count(word1, word2)
#> # A tibble: 9 × 3
#>   word1 word2     n
#>   <chr> <chr> <int>
#> 1 a     b         1
#> 2 a     c         1
#> 3 a     d         1
#> 4 a     e         1
#> 5 b     a         1
#> 6 b     c         1
#> 7 c     a         1
#> 8 c     d         1
#> 9 d     e         1

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
The pmin/pmax approach by @akrun is super efficient. Here is another option with igraph

library(tidytext)
library(dplyr)
library(stringr)
library(tidyr)
library(igraph)

enframe(c("a b c a d e")) %>%
  unnest_tokens(skipgram, value, token = "skip_ngrams", n = 5) %>%
  mutate(n_words = str_count(skipgram, pattern = "\\S+")) %>%
  filter(n_words == 2) %>%
  separate(col = skipgram, into = c("word1", "word2"), sep = "\\s+") %>%
  count(word1, word2) %>%
  graph_from_data_frame(directed = FALSE) %>%
  simplify(edge.attr.comb = "sum") %>%
  get.data.frame()

which gives

  from to n
1    a  b 2
2    a  c 2
3    a  d 1
4    a  e 1
5    b  c 1
6    c  d 1
7    d  e 1


问:
Accessing a float value in AsyncTask
Here is a pseudo code :

```
class MoWeFi extends Activity</p>

```    static TouchSurfaceView TSV;
    static DrawRenderer mRenderer;
    static UserInterface mUI;
    DownloadData mDD = new DownloadData();
    static float zoom = 1.f;

    mDD.execute();
    mUI = new UserInterface();
    setContentView(mUI);
```

<p>class UserInterface extends LinearLayout
    MoWeFi.TSV = new TouchSurfaceView(context);
    MoWeFi.mRenderer = new DrawRenderer(context);
    MoWeFi.TSV.setRenderer(MoWeFi.mRenderer);
    MoWeFi.TSV.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    this.addView(MoWeFi.TSV);</p>

```    TextView tv = new TextView(context);
    this.addView(tv);

    TextView tv2 = new TextView(context);
    this.addView(tv2);
```

<p>class DownloadData extends AsyncTask
    protected Void doInBackground(){
        do{
        this.publishProgress();
        try{Thread.sleep(1000);catch (InterruptedException e){}
        }while(running)
    }
    @Override
    protected void onProgressUpdate(){
    //...
    MoWeFi.TSV.requestRender();
    MoWeFi.mUI.tv.setText("zoom="+MoWeFi.zoom); // IT DOES NOT WORK !!! ALWAYS GET 1.f.
    }</p>

<p>class TouchSurfaceView extends GLSurfaceView
    gl.glTranslatef(0, 0, -1.f / MoWeFi.zoom); // IT WORKS !!!</p>

<p>class DrawRenderer implements GLSurfaceView.Renderer
    //Pinch-zoom
    ...
    MoWeFi.zoom *= detector.getScaleFactor();
        MoWeFi.zoom = Math.max(0.5f, Math.min(MoWeFi.zoom, 5.0f));</p>

<code>MoWeFi.mUI.tv2.setText("zoom="+MoWeFi.zoom); // IT WORKS !!!
</code>```

So no error whatsoever. Just not able to access my zoom variable everywhere.
I am new to Java, I am surely missing important concept.

EDIT add float in the first lines

EDIT 2 add publishProgress in the asyncTask

EDIT 3 logcat shows nothing

答:
There is a problem in the declaration of the zoom variable. You must explicitly tell the java compiler what is zoom, is it a String, Integer, Float, etc.

The declaration should go like:

public static int zoom = 100; for integer values.

public static String zoom = "My String"; for string values.

public static double zoom = 1.4; for double values and so on.

Title: Accessing a float value in AsyncTask

Body:
Here is a pseudo code :

class MoWeFi extends Activity

    static TouchSurfaceView TSV;
    static DrawRenderer mRenderer;
    static UserInterface mUI;
    DownloadData mDD = new DownloadData();
    static float zoom = 1.f;

    mDD.execute();
    mUI = new UserInterface();
    setContentView(mUI);

class UserInterface extends LinearLayout
    MoWeFi.TSV = new TouchSurfaceView(context);
    MoWeFi.mRenderer = new DrawRenderer(context);
    MoWeFi.TSV.setRenderer(MoWeFi.mRenderer);
    MoWeFi.TSV.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    this.addView(MoWeFi.TSV);

    TextView tv = new TextView(context);
    this.addView(tv);

    TextView tv2 = new TextView(context);
    this.addView(tv2);

class DownloadData extends AsyncTask
    protected Void doInBackground(){
        do{
        this.publishProgress();
        try{Thread.sleep(1000);catch (InterruptedException e){}
        }while(running)
    }
    @Override
    protected void onProgressUpdate(){
    //...
    MoWeFi.TSV.requestRender();
    MoWeFi.mUI.tv.setText("zoom="+MoWeFi.zoom); // IT DOES NOT WORK !!! ALWAYS GET 1.f.
    }

class TouchSurfaceView extends GLSurfaceView
    gl.glTranslatef(0, 0, -1.f / MoWeFi.zoom); // IT WORKS !!!

class DrawRenderer implements GLSurfaceView.Renderer
    //Pinch-zoom
    ...
    MoWeFi.zoom *= detector.getScaleFactor();
        MoWeFi.zoom = Math.max(0.5f, Math.min(MoWeFi.zoom, 5.0f));

MoWeFi.mUI.tv2.setText("zoom="+MoWeFi.zoom); // IT WORKS !!!

So no error whatsoever. Just not able to access my zoom variable everywhere.
I am new to Java, I am surely missing important concept.

EDIT add float in the first lines

EDIT 2 add publishProgress in the asyncTask

EDIT 3 logcat shows nothing


问:
How to get Request.User in Django-Rest-Framework serializer?
I've tried something like this, it does not work. </p>

```<code>class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post

    def save(self):
        user = self.context['request.user']
        title = self.validated_data['title']
        article = self.validated_data['article']
</code>```

<p>I need a way of being able to access request.user from my Serializer class.  </p>

答:
drf srz page

in my project it worked my user field was read only so i needed to get
user id in the create method

```<code>class CommentSerializer(serializers.ModelSerializer):
    comment_replis = RecursiveField(many=True, read_only=True)
    user = UserSerializer(read_only=True)

    class Meta:
        model = PostComment
        fields = ('_all_')

    def create(self, validated_data):

        post = PostComment.objects.create(**validated_data)
        print(self._dict_['_kwargs']['data']["user"]) # geting #request.data["user"] #  <- mian code
        post.user=User.objects.get(id=self._dict_['_kwargs']['data']["user"])
        return post

</code>```

in my project i tried this way and it work

Body:
I've tried something like this, it does not work.

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post

    def save(self):
        user = self.context['request.user']
        title = self.validated_data['title']
        article = self.validated_data['article']

I need a way of being able to access request.user from my Serializer class.

Body:
drf srz page

in my project it worked my user field was read only so i needed to get
user id in the create method

class CommentSerializer(serializers.ModelSerializer):
    comment_replis = RecursiveField(many=True, read_only=True)
    user = UserSerializer(read_only=True)

    class Meta:
        model = PostComment
        fields = ('_all_')

    def create(self, validated_data):

        post = PostComment.objects.create(**validated_data)
        print(self._dict_['_kwargs']['data']["user"]) # geting #request.data["user"] #  <- mian code
        post.user=User.objects.get(id=self._dict_['_kwargs']['data']["user"])
        return post

in my project i tried this way and it work


问:
curl command works in powershell, but not with python subprocess.run()
I execute a curl command to fetch an html, containing a word meaning in powershell and it works as expected.
Then I want to execute it with python with subprocess.run(), it returns no errors and I see that the arguments in run() are parsed correctly, but the returned page is the "word not found" page of the website, instead of the page that curl returns in powershell. I want to get the same results as if I execute the command normally in powershell or terminal.</p>
```<code>    import sys, subprocess
    response = subprocess.run(["curl", f"http://rechnik.info/{sys.argv[1]}", "-o", "query.html"], encoding='utf-8', capture_output=True)
    print(response)
    exit()
</code>```

答: sometimes on windows curl is not installed. try using reqursts insteade so it will work on every OS.

Body:
I execute a curl command to fetch an html, containing a word meaning in powershell and it works as expected.
Then I want to execute it with python with subprocess.run(), it returns no errors and I see that the arguments in run() are parsed correctly, but the returned page is the "word not found" page of the website, instead of the page that curl returns in powershell. I want to get the same results as if I execute the command normally in powershell or terminal.

    import sys, subprocess
    response = subprocess.run(["curl", f"http://rechnik.info/{sys.argv[1]}", "-o", "query.html"], encoding='utf-8', capture_output=True)
    print(response)
    exit()


问:
How to lock the job during execution in Laravel?
I see withoutOverlapping() mutex for commands, but I don't see it for jobs. How can I protect jobs of the same type from overlapping each other?

Thanks!

答:
I think it's possible using the following:
https://laravel.com/docs/8.x/queues#unique-jobs

You can specify a needed key that you can pass to the job to mark its uniqueness. In my case, I need to limit requests to a third-party API that happens in the job so if I have more than one worker handling the queue, it's possible to get 429 from the API. As soon as I have many API-keys (per user of the app), I can use it to have the same type of job being exxecuted independently across the app users but lock the job execution if the current job with a specific key is not completed.

Like this:

```<code>    //In the class defining you must use ShouldBeUnique interface
    class UpdateSpreadsheet implements ShouldQueue, ShouldBeUnique

    //some other code

    public function __construct($keyValue)
    {
    //some other constructor code if needed
    $this->keyValue= $keyValue;
    }

    //This function allows to set the unique key
    public function uniqueId()
    {
        return $this->keyValue;
    }

    //If you don't need to wait until the job is processed, you may also specify
    //the time for the force lock removing (so you'll be able to queue another
    //job with this key after 10 seconds even if the current job is
    //still in process)

    public $uniqueFor = 10;
</code>```

Body:
I think it's possible using the following:
https://laravel.com/docs/8.x/queues#unique-jobs

You can specify a needed key that you can pass to the job to mark its uniqueness. In my case, I need to limit requests to a third-party API that happens in the job so if I have more than one worker handling the queue, it's possible to get 429 from the API. As soon as I have many API-keys (per user of the app), I can use it to have the same type of job being exxecuted independently across the app users but lock the job execution if the current job with a specific key is not completed.

Like this:

    //In the class defining you must use ShouldBeUnique interface
    class UpdateSpreadsheet implements ShouldQueue, ShouldBeUnique

    //some other code

    public function __construct($keyValue)
    {
    //some other constructor code if needed
    $this->keyValue= $keyValue;
    }

    //This function allows to set the unique key
    public function uniqueId()
    {
        return $this->keyValue;
    }

    //If you don't need to wait until the job is processed, you may also specify
    //the time for the force lock removing (so you'll be able to queue another
    //job with this key after 10 seconds even if the current job is
    //still in process)

    public $uniqueFor = 10;


问:
no result values expectedcompilerWrongResultCount
I have this two functions

```<code>func fib_memo(n int) {
    memo := make([]int, n+1)
    return fib_2(n, memo)
}
func fib_2(n int, memo []int) int {
    result := 0
    if &memo[n] != nil {
        return memo[n]
    }
    if n == 1 || n == 2 {
        result = 1
    } else {
        result = fib_2(n-1, memo) + fib_2(n-2, memo)
        memo[n] = result
    }
    return result
}
</code>```

But the first in giving me a compiler error i don't no why please help : no result values expectedcompilerWrongResultCount

答:
```<code>func fib_memo(n int) (result int) {
    memo := make([]int, n+1)
    return fib_2(n, memo)
}
</code>```

Body:
I have this two functions

func fib_memo(n int) {
    memo := make([]int, n+1)
    return fib_2(n, memo)
}
func fib_2(n int, memo []int) int {
    result := 0
    if &memo[n] != nil {
        return memo[n]
    }
    if n == 1 || n == 2 {
        result = 1
    } else {
        result = fib_2(n-1, memo) + fib_2(n-2, memo)
        memo[n] = result
    }
    return result
}

But the first in giving me a compiler error i don't no why please help : no result values expectedcompilerWrongResultCount


问:
Entity Relationship Diagram: Can someone verify my ERD?
I have made an ERD diagram (well kind of as it doesn't adhere to all the principles of an ERD diagram).

Following are the requirements:

Manager/user can have many projects

The user can enter many bugs

A bug has a creator(user)

A bug has a developer who'll solve the bug(user)

A bug belongs to a project

A project can have many users

A project can have many bugs too.

The bug has a descriptive title and deadline and a screenshot, type, and status

Screen shot should be an image either .png or .gif no other type of image is allowed.

Description and the screenshot is not compulsory but title and status and type are compulsory.

The title of a bug should be unique throughout the project

Type can have two values (feature, bug)

Status is a drop down having values (new, started, completed) if it's a feature or (new, started and resolved) if it's a bug.

Here is my understanding.

There is a User table that will contain the (unique) ID (I may use UUID for that), Username, Email, UserType (Enum: Manager, Developer, QA), and encrypted User password.

A User can have multiple projects so that's why it has 1:Many relationships with the table Project. This table will have a unique Project ID, Manager ID (The creator of the project), and a project title.

I'm thinking of creating a 3rd table i.e. Working On, which will keep track of which user is currently present under the project (Requirement 5). Project ID and User Id, both will be FKs from respective tables and their combination will make a Primary Key. Is this approach feasible?

Each project can have multiple Bugs, so 1:Many relationships will be defined between Project and Bug. Bug ID will be the primary key.

Each bug can have an optional set of screenshot(s) (Max 10), which I'm thinking of storing in another table Screenshots. Its primary key will be composed of BugId and ImageID.

Can anyone please go through this logic and help me in identifying any errors in this approach? It is very important that I correctly categorize my databases so that implementation in Ruby on Rails becomes easier.

答:
This is mostly a generic database design question and not really much to do with Rails. If you were to express the above as some very stripped-back model classes, we'd know that you understood the likes of belongs_to, has_many and so-forth, and could at least verify it for Rails on that level. That said, at a glance it looks generally OK; some things you might want to consider:

You don't have to get this right first time, although of course it's always nice to get it as close as you can. It's easy to write migrations in Rails to change data layers, and no matter how good your initial design, applications and requirements evolve - your data will too.

You ought to call the primary key in all tables id. Only the foreign keys for relationships should be of the form foo_id. Your ERD also doesn't name the fields as they'd be in the database; you've "humanised" them with capitalisation and spaces. It'd be a little clearer if you used Rails naming conventions for that so we could, again, see that this was understood. I wonder if you might come from a Microsoft/C#-style background given the capitalisation and tendency to give the primary keys longer names.

"Working On" is just a join table and perhaps does not need to be extracted specifically, though I know there's been a more recent movement in the Rails community to dislike "has and belongs to many" in favour of "has many through". Personally I don't mind it most of the time; "Working On"  just joins "user" to "project" and using a standard Rails naming convention HABTM relationship will let you do user.projects and project.users easily enough, without worrying about maintaining the "thing in the middle".

I personally quite like using enumerations in PostgreSQL for columns with fixed arrays of values, but they are a little fiddly in Rails and an area where migrations are more difficult. You will probably find it easier to just use an indexed text field (depending on your database - you don't say what the engine will be) and have the corresponding Rails model define a series of constants for validating values. This makes it easier to extend in future.

class Bug < ApplicationRecord
  # ...
  STATUS_OPEN    = 'open'
  STATUS_FIXED   = 'fixed'
  STATUS_WONTFIX = 'wont_fix'

  STATUSES = Set[
    STATUS_OPEN,
    STATUS_FIXED,
    STATUS_WONTFIX
  ]

  validates :status, presence: true, inclusion: { in: STATUSES }
  # ...
end
```


问:
Polyline Set color option for Google Api V2 getting error ?? C# Web App
i am getting error on the line to set polyline color option my code,

```<code>GEvent.addListener(polyline, "click", function() {polyline.setOptions(options: { strokeColor: 'blue' })};
</code>```

but if i try this,

```<code>GEvent.addListener(polyline, "click", function() {alert("clicked");});
</code>```

it works fine

How to set polyline color on click ??

i also try this,

```<code>GEvent.addListener(polyline, "click", function() {PolylineOptions({ strokeStyle: new StrokeStyle({color: 0xFF0000})});
</code>```

it is also resulting in error HOPES for your reply...

答:
It looks like you're mixing up the Maps API V3 and Maps API V2 syntax.

Maps API V2 uses setStrokeStyle not setOptions to change Polyline options

Maps API V2 uses hex color codes (rather than 'blue' etc)

The following should work.

```<code>GEvent.addListener(polyline, "click", function() {
  polyline.setStrokeStyle({ color: "#FF0000" });
};
</code>```

Body:
i am getting error on the line to set polyline color option my code,

GEvent.addListener(polyline, "click", function() {polyline.setOptions(options: { strokeColor: 'blue' })};

but if i try this,

GEvent.addListener(polyline, "click", function() {alert("clicked");});

it works fine

How to set polyline color on click ??

i also try this,

GEvent.addListener(polyline, "click", function() {PolylineOptions({ strokeStyle: new StrokeStyle({color: 0xFF0000})});

it is also resulting in error HOPES for your reply...

Body:
It looks like you're mixing up the Maps API V3 and Maps API V2 syntax.

Maps API V2 uses setStrokeStyle not setOptions to change Polyline options

Maps API V2 uses hex color codes (rather than 'blue' etc)

The following should work.

GEvent.addListener(polyline, "click", function() {
  polyline.setStrokeStyle({ color: "#FF0000" });
};


问:
How to prevent a popup Form from exceeding screen area?
I am building a two column custom context menu layout using Forms.

I named the class of the form of the custom context menu as ContextMenu.

I created a flag function to check whether it exceeds the device screen dimension upon invocation.

Single cases like exceeding only the length or only the height of device screen works.

However, when it comes to exceeding both the length and height of device screen, it somehow didn't work. I've tried to print the values in the console for checking purposes(example). The values printed are correct, but for some reason, it didn't enter the switch case for it.

Did I missed something anywhere in the codes?

Below is the flag function. case 3 doesn't work(example).

```<code>//exceed screen flag function
private Point processContextMenuFormLocation(ContextMenu theContextMenu, int screenExceedFlag, Point mouseCoor)
{
    //local form coordinate
    int formXCoor;
    int formYCoor;

    switch (screenExceedFlag)
    {
        case 1: //if exceed right boundary
            formXCoor = (mouseCoor.X) - (contextMenuObj.Width); //move context menu to the left
            formYCoor = mouseCoor.Y; //no need changes
            //after exceedFlag, set where context menu position is
            theContextMenu.Location = new Point(formXCoor, formYCoor);
            break;
        case 2: //if exceed bottom boundary
            formXCoor = (mouseCoor.X); //no need changes
            formYCoor = (mouseCoor.Y) - (contextMenuObj.Height); //move context menu to the top
            theContextMenu.Location = new Point(formXCoor, formYCoor);
            break;
        case 3: //if exceed right & bottom boundary
            formXCoor = (mouseCoor.X) - (contextMenuObj.Width); //move context menu to the left
            formYCoor = (mouseCoor.Y) - (contextMenuObj.Height); //move context menu to the top
            theContextMenu.Location = new Point(formXCoor, formYCoor);
            break;
        case -1: //if exceeded nothing
            theContextMenu.Location = new Point(mouseCoor.X, mouseCoor.Y);
            break;
    }
    //return the new location of context menu
    return theContextMenu.Location;
}
</code>```

Below is the event handler, which calls the above function:

```<code>//mouse up event handler
private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
{
    //set default CM closed so that won't open concurrently
    richContextStrip.Visible = false;

    if (e.Button == MouseButtons.Right)
    {
        IsKeyUp((int)MouseButtons.Right); //set rmbIsUp = true

        //here because the rmb event handler is above this
        bool canDisplay = contextMenuDisplayFlag(ctrlIsDown, rmbIsUp); //get ctrl and rmb flag status

        if (canDisplay)
        {
            //to process whether custom context menu was opened beyond screen area or not
            exceedScreenFlag = isBeyondScreen(Cursor.Position.X, Cursor.Position.Y, contextMenuObj.Width, contextMenuObj.Height);

            //obtain mouse coordinates
            Point theMouseCoor = new Point(Cursor.Position.X, Cursor.Position.Y);

            //exceed screen flag function
            Point formLocation = processContextMenuFormLocation(contextMenuObj, exceedScreenFlag, theMouseCoor);

            //center the cursor at context menu
            Point cursorLocation = processContextMenuCursorLocation(contextMenuObj, formLocation);

            displayCustomContextMenu(contextMenuObj, formLocation, cursorLocation);
            toolStripStatusLabel1.Text = "Custom context menu opened!";
        }
        else //if ctrl key is not pressed
        {
            richContextStrip.Visible = true;
            toolStripStatusLabel1.Text = "Default context menu opened!";
        }
    }
}
</code>```

答:
You may want to consider that the current mouse Pointer location is returned by MouseEventArgs.Location. You just need to convert this value to Screen coordinates using the [Control].PointToScreen() method.

Then compare the initial Location - plus the Width and Height of your Popup - with the value returned by Screen.FromControl([Control]).WorkingArea and verify whether the Popup is contained within this bounds.

If it's not, then subtract the Popup's Width and/or Height from the WorkingArea left and right bounds.

Something like this:

Note that these measures don't include the Form's invisible borders. The distance from the screen's sides will be 14~16 pixels. Adjust it if you prefer a tighter position

```<code>private void someControl_MouseUp(object sender, MouseEventArgs e)
{
    var f = new Form() { Width = 400, Height = 400, StartPosition = FormStartPosition.Manual };
    f.Location = SetPopupLocation(Screen.FromControl(this), f, (sender as Control).PointToScreen(e.Location));
    f.Show();
}

private Point SetPopupLocation(Screen screen, Form form, Point initPosition)
{
    var p = new Point();
    var wrkArea = screen.WorkingArea;
    p.X = wrkArea.Right - (initPosition.X + form.Width);
    p.Y = wrkArea.Bottom - (initPosition.Y + form.Height);
    p.X = p.X < 0 ? wrkArea.Right - form.Width : initPosition.X;
    p.Y = p.Y < 0 ? wrkArea.Bottom - form.Height : initPosition.Y;
    return p;
}
</code>```

Your app needs to be DpiAware to receive reliable measures and coordinates.

See the notes in Using SetWindowPos with multiple monitors

Body:
I am building a two column custom context menu layout using Forms.

I named the class of the form of the custom context menu as ContextMenu.

I created a flag function to check whether it exceeds the device screen dimension upon invocation.

Single cases like exceeding only the length or only the height of device screen works.

However, when it comes to exceeding both the length and height of device screen, it somehow didn't work. I've tried to print the values in the console for checking purposes(example). The values printed are correct, but for some reason, it didn't enter the switch case for it.

Did I missed something anywhere in the codes?

Below is the flag function. case 3 doesn't work(example).

//exceed screen flag function
private Point processContextMenuFormLocation(ContextMenu theContextMenu, int screenExceedFlag, Point mouseCoor)
{
    //local form coordinate
    int formXCoor;
    int formYCoor;

    switch (screenExceedFlag)
    {
        case 1: //if exceed right boundary
            formXCoor = (mouseCoor.X) - (contextMenuObj.Width); //move context menu to the left
            formYCoor = mouseCoor.Y; //no need changes
            //after exceedFlag, set where context menu position is
            theContextMenu.Location = new Point(formXCoor, formYCoor);
            break;
        case 2: //if exceed bottom boundary
            formXCoor = (mouseCoor.X); //no need changes
            formYCoor = (mouseCoor.Y) - (contextMenuObj.Height); //move context menu to the top
            theContextMenu.Location = new Point(formXCoor, formYCoor);
            break;
        case 3: //if exceed right & bottom boundary
            formXCoor = (mouseCoor.X) - (contextMenuObj.Width); //move context menu to the left
            formYCoor = (mouseCoor.Y) - (contextMenuObj.Height); //move context menu to the top
            theContextMenu.Location = new Point(formXCoor, formYCoor);
            break;
        case -1: //if exceeded nothing
            theContextMenu.Location = new Point(mouseCoor.X, mouseCoor.Y);
            break;
    }
    //return the new location of context menu
    return theContextMenu.Location;
}

Below is the event handler, which calls the above function:

//mouse up event handler
private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
{
    //set default CM closed so that won't open concurrently
    richContextStrip.Visible = false;

    if (e.Button == MouseButtons.Right)
    {
        IsKeyUp((int)MouseButtons.Right); //set rmbIsUp = true

        //here because the rmb event handler is above this
        bool canDisplay = contextMenuDisplayFlag(ctrlIsDown, rmbIsUp); //get ctrl and rmb flag status

        if (canDisplay)
        {
            //to process whether custom context menu was opened beyond screen area or not
            exceedScreenFlag = isBeyondScreen(Cursor.Position.X, Cursor.Position.Y, contextMenuObj.Width, contextMenuObj.Height);

            //obtain mouse coordinates
            Point theMouseCoor = new Point(Cursor.Position.X, Cursor.Position.Y);

            //exceed screen flag function
            Point formLocation = processContextMenuFormLocation(contextMenuObj, exceedScreenFlag, theMouseCoor);

            //center the cursor at context menu
            Point cursorLocation = processContextMenuCursorLocation(contextMenuObj, formLocation);

            displayCustomContextMenu(contextMenuObj, formLocation, cursorLocation);
            toolStripStatusLabel1.Text = "Custom context menu opened!";
        }
        else //if ctrl key is not pressed
        {
            richContextStrip.Visible = true;
            toolStripStatusLabel1.Text = "Default context menu opened!";
        }
    }
}

Body:
You may want to consider that the current mouse Pointer location is returned by MouseEventArgs.Location. You just need to convert this value to Screen coordinates using the [Control].PointToScreen() method.

Then compare the initial Location - plus the Width and Height of your Popup - with the value returned by Screen.FromControl([Control]).WorkingArea and verify whether the Popup is contained within this bounds.

If it's not, then subtract the Popup's Width and/or Height from the WorkingArea left and right bounds.

Something like this:

Note that these measures don't include the Form's invisible borders. The distance from the screen's sides will be 14~16 pixels. Adjust it if you prefer a tighter position

private void someControl_MouseUp(object sender, MouseEventArgs e)
{
    var f = new Form() { Width = 400, Height = 400, StartPosition = FormStartPosition.Manual };
    f.Location = SetPopupLocation(Screen.FromControl(this), f, (sender as Control).PointToScreen(e.Location));
    f.Show();
}

private Point SetPopupLocation(Screen screen, Form form, Point initPosition)
{
    var p = new Point();
    var wrkArea = screen.WorkingArea;
    p.X = wrkArea.Right - (initPosition.X + form.Width);
    p.Y = wrkArea.Bottom - (initPosition.Y + form.Height);
    p.X = p.X < 0 ? wrkArea.Right - form.Width : initPosition.X;
    p.Y = p.Y < 0 ? wrkArea.Bottom - form.Height : initPosition.Y;
    return p;
}

Your app needs to be DpiAware to receive reliable measures and coordinates.

See the notes in Using SetWindowPos with multiple monitors


问:
Selenium webdriver verifying the text displayed in one row
I encountered a problem when trying to check if some text on a page is displayed in one row,
I mean the html does not contain br tag, but because of resolution / font size  - the text is wrapped to a second row. Is there a way to know it with selenium?</p>

答: It's not a great solution, but might give you some ideas.  We have text that is supposed to wrap to a second line when the browser width narrows to a certain point.  I started full width driver.manage().window().maximize(); and got the height and width of the element containing the text.  Then I set the browser window to a smaller size  driver.manage().window().setSize(new Dimension(width, height)); and got the height and width of the same element again, and then could verify that the new height is roughly double the previous height, and the width is less, indicating it may be wrapped.  I suppose the element height could grow but the text would not wrap (just be cut off), but this is the best I could think of.


问:
Iterate on page of returning execute_values
http://initd.org/psycopg/docs/extras.html

psycopg2.extras.execute_values has a parameters page_size.
I'm doing an INSERT INTO... ON CONFLICT... with RETURNING ID.

The problem is that the cursor.fetchall() give me back only the last "page", that is, 100 ids (default of page_size).

Without modifying page_size parameters, is it possible to iterate over the results, to get the total number of rows updated ?

答:
Without modifying page_size parameters, is it possible to iterate over
the results, to get the total number of rows updated ?

Yes.

try:
    conn = psycopg2.connect(...)
    cur = conn.cursor()
    query = """
        WITH
            items (eggs) AS (VALUES %s),
            inserted AS (
                INSERT INTO spam (eggs)
                SELECT eggs FROM items
                ON CONFLICT (eggs) DO NOTHING
                RETURNING id
            )
        SELECT id FROM spam
        WHERE eggs IN (SELECT eggs FROM items)
        UNION
        SELECT id FROM inserted
    """
    eggs = (('egg_{}'.format(i % 666),) for i in range(10_000))
    ids = psycopg2.extras.execute_values(cur, query, argslist=eggs, fetch=True)
    # Do whatever with `ids`. `len(ids)` I suppose?
finally:
    if connection:
        cur.close()
        conn.close()
```
<p>I overkilled query on purpose to address some gotchas:</p>
<ul>
<li><code>WITH items (eggs) AS (VALUES %s)</code> is done to be able to use <code>argslist</code> in two places at once;</li>
<li><code>RETURNING</code> with <code>ON CONFLICT</code> will return only <code>id</code>s which were actually inserted, conflicting ones are omitted from <code>INSERT</code>' direct results. To solve that all this <code>SELECT ... WHERE ... UNION SELECT</code> mumbo jumbo is done;</li>
<li>to get all values which you asked for: <code>ids = psycopg2.extras.execute_values(..., fetch=True)</code>.</li>
</ul>
<p>A horrible interface oddity considering that all other cases are done like</p>
<pre class="lang-py prettyprint-override"><code>cur.execute(...)  # or other kind of `execute`
rows = cur.fetchall()  # or other kind of `fetch`
</code>```

So if you want only the number of inserted rows then do

try:
    conn = psycopg2.connect(...)
    cur = conn.cursor()
    query = """
        INSERT INTO spam (eggs)
        VALUES %s
        ON CONFLICT (eggs) DO NOTHING
        RETURNING id
    """
    eggs = (('egg_{}'.format(i % 666),) for i in range(10_000))
    ids = psycopg2.extras.execute_values(cur, query, argslist=eggs, fetch=True)
    print(len(ids)
finally:
    if connection:
        cur.close()
        conn.close()
```

Body:
Without modifying page_size parameters, is it possible to iterate over
the results, to get the total number of rows updated ?

Yes.

try:
    conn = psycopg2.connect(...)
    cur = conn.cursor()
    query = """
        WITH
            items (eggs) AS (VALUES %s),
            inserted AS (
                INSERT INTO spam (eggs)
                SELECT eggs FROM items
                ON CONFLICT (eggs) DO NOTHING
                RETURNING id
            )
        SELECT id FROM spam
        WHERE eggs IN (SELECT eggs FROM items)
        UNION
        SELECT id FROM inserted
    """
    eggs = (('egg_{}'.format(i % 666),) for i in range(10_000))
    ids = psycopg2.extras.execute_values(cur, query, argslist=eggs, fetch=True)
    # Do whatever with `ids`. `len(ids)` I suppose?
finally:
    if connection:
        cur.close()
        conn.close()

I overkilled query on purpose to address some gotchas:

WITH items (eggs) AS (VALUES %s) is done to be able to use argslist in two places at once;

RETURNING with ON CONFLICT will return only ids which were actually inserted, conflicting ones are omitted from INSERT' direct results. To solve that all this SELECT ... WHERE ... UNION SELECT mumbo jumbo is done;

to get all values which you asked for: ids = psycopg2.extras.execute_values(..., fetch=True).

A horrible interface oddity considering that all other cases are done like

cur.execute(...)  # or other kind of `execute`
rows = cur.fetchall()  # or other kind of `fetch`

So if you want only the number of inserted rows then do

try:
    conn = psycopg2.connect(...)
    cur = conn.cursor()
    query = """
        INSERT INTO spam (eggs)
        VALUES %s
        ON CONFLICT (eggs) DO NOTHING
        RETURNING id
    """
    eggs = (('egg_{}'.format(i % 666),) for i in range(10_000))
    ids = psycopg2.extras.execute_values(cur, query, argslist=eggs, fetch=True)
    print(len(ids)
finally:
    if connection:
        cur.close()
        conn.close()


问:
YOY growth based on ID
I am trying to calculate year or year growth for a variable in a Pandas dataframe. My data looks like this:

Year
Country
Industry
Value

2000
USA
Manufacturing
5

2000
Mexico
Manufacturing
10

2001
Mexico
Manufacturing
15

2002
Mexico
Other
20

I have different number of observations depending on the Country or Industry. Expected output:

Year
Country
Industry
Value
YOY

2000
USA
Manufacturing
5
NaN

2000
Mexico
Manufacturing
10
NaN

2001
Mexico
Manufacturing
15
50%

2002
Mexico
Other
20
NaN

I tried different things including:

```<code>df.groupby(['Country','Industry','Year'])['Value'].pct_change()

df['YOY'] = (df['Value'] - df.sort_values(by=['Country','Industry','Year']).groupby(['Country','Industry'])['Value'].shift(1))) / df['Value']
</code>```

The first line calculates growth between rows without resetting for a new Country or Industry. The second one has incoherent results.

Any lead I could take? Thanks!!

答:
Try this:

```<code>df['YOY'] = df.groupby(['Country','Industry'])['Value'].pct_change().mul(100)
</code>```

Output:

```<code>>>> df
   Year Country       Industry  Value   YOY
0  2000     USA  Manufacturing      5   NaN
1  2000  Mexico  Manufacturing     10   NaN
2  2001  Mexico  Manufacturing     15  50.0
3  2002  Mexico          Other     20   NaN
</code>```

Title: YOY growth based on ID

Body:
I am trying to calculate year or year growth for a variable in a Pandas dataframe. My data looks like this:

Year
Country
Industry
Value

2000
USA
Manufacturing
5

2000
Mexico
Manufacturing
10

2001
Mexico
Manufacturing
15

2002
Mexico
Other
20

I have different number of observations depending on the Country or Industry. Expected output:

Year
Country
Industry
Value
YOY

2000
USA
Manufacturing
5
NaN

2000
Mexico
Manufacturing
10
NaN

2001
Mexico
Manufacturing
15
50%

2002
Mexico
Other
20
NaN

I tried different things including:

df.groupby(['Country','Industry','Year'])['Value'].pct_change()

df['YOY'] = (df['Value'] - df.sort_values(by=['Country','Industry','Year']).groupby(['Country','Industry'])['Value'].shift(1))) / df['Value']

The first line calculates growth between rows without resetting for a new Country or Industry. The second one has incoherent results.

Any lead I could take? Thanks!!

Body:
Try this:

df['YOY'] = df.groupby(['Country','Industry'])['Value'].pct_change().mul(100)

Output:

>>> df
   Year Country       Industry  Value   YOY
0  2000     USA  Manufacturing      5   NaN
1  2000  Mexico  Manufacturing     10   NaN
2  2001  Mexico  Manufacturing     15  50.0
3  2002  Mexico          Other     20   NaN


问:
Google SAML app_not_configured_for_user / equivalent of prompt=select_account SAML
I'm using Gsuite as an Saml IDP to authentify users of my organisation on internal apps.

Everything is working fine, except for one point:
when one of my users if logged in with his/her personal account only, Google will fail with:

403 Error: app_not_configured_for_user

This makes sense as the app is intended to be used by internal users only, but I would like to be able to force Google saml authentication to display the account selector even if the user is already logged in to one account as this is possible for oauth2 with prompt=select_account.

Any way to have the same behavior with SAML ?

[EDIT] I actually managed to achieve what I want by using

https://accounts.google.com/AccountChooser/?continue=$SAML_REQUEST$

[EDIT 2] Here is the code snippet for the adaptation in ruby on rails (using ruby-saml)

config/initializers/saml_override.rb

```<code>module OneLogin
  module RubySaml
    class Authrequest < SamlMessage
      GOOGLE_ACCOUNT_CHOOSER_URL = "https://accounts.google.com/AccountChooser?continue="
      alias_method :old_create, :create
      def create(settings, params = {})
        self.old_create(settings, params)
        @login_url = GOOGLE_ACCOUNT_CHOOSER_URL + CGI.escape(@login_url)
      end
    end
  end
end
</code>```

答:
Good that you've resolved your problem. I thought I'd add a few archirectural points.

SAML

ForceAuthn is a SAML Attribute that you can send in an authentication request. There are  others such as EntityId for apps that need to control which login method should be used.

OPENID CONNECT

This has better options I would say, as a more up to date standard. The JOSE based technologies work well for web and mobile clients, in pretty much any tech stack.

There are a greater number of request parameters such as acr_values to replace EntityId, and prompt has more options than ForceAuthn, as you pointed out. This also provides additional session management options as in this recent answer of mine.

PROVIDERS

Not all providers are standards based, and sone may not support ForceAuthn, prompt, acr_values etc, but you may still want to use them for login purposes. To solve your problem you had to resort to a non SAML Google specific request parameter. The more login providers you use, the worse this gets - and application complexity grows.

OPTIMAL ARCHITECTURE

For future reference, it is worth aiming for this architecture, in case any of this is new to you:

Application code only uses OpenID Connect, which is a much larger space than many people are aware of - have a look at this summary of standards.

Apps only redirect to an Authorization Server, which in turn manages connections to identity providers and their peculiarities. These connections can use SAML, OIDC or anything else needed.

The end result should be simple and portable code in apps, which also have support for the most cutting edge authentication flows.

At least that's sonething I like to aim for - identity remains a challenge, sometimes with too many annoyances :).

Body:
I'm using Gsuite as an Saml IDP to authentify users of my organisation on internal apps.

Everything is working fine, except for one point:
when one of my users if logged in with his/her personal account only, Google will fail with:

403 Error: app_not_configured_for_user

This makes sense as the app is intended to be used by internal users only, but I would like to be able to force Google saml authentication to display the account selector even if the user is already logged in to one account as this is possible for oauth2 with prompt=select_account.

Any way to have the same behavior with SAML ?

[EDIT] I actually managed to achieve what I want by using

https://accounts.google.com/AccountChooser/?continue=$SAML_REQUEST$

[EDIT 2] Here is the code snippet for the adaptation in ruby on rails (using ruby-saml)

config/initializers/saml_override.rb

module OneLogin
  module RubySaml
    class Authrequest < SamlMessage
      GOOGLE_ACCOUNT_CHOOSER_URL = "https://accounts.google.com/AccountChooser?continue="
      alias_method :old_create, :create
      def create(settings, params = {})
        self.old_create(settings, params)
        @login_url = GOOGLE_ACCOUNT_CHOOSER_URL + CGI.escape(@login_url)
      end
    end
  end
end


问:
Import HTML as string and test with Jest
I'm using sveltekit and I can't use the files api to import html templates. So I decided to import by writing a module that imports the content of the document as a string (described here).

```<code>// src/global.d.ts

/// <reference types="@sveltejs/kit" />
declare module '*.html' {
  const content: string
  export default content
}
</code>```

So far so good, but now I need to test the code and jest can't interpret the code.

```<code>● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

/home/developer/workspace/src/assets/html/confirm_email.html:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<!DOCTYPE html>
                                                                                ^

SyntaxError: Unexpected token '<'
</code>```

I don't understand how jest understands the .d.ts files... How do I get to test the code?

答:
1.Import html as string

I solved the problem using another approach...

I'm using a resource of vite to import the html file as an asset, as can be seen here in the documentation

```<code>import confirm_email_template from '../../../assets/html/confirm_email.html?raw'
</code>```

2.Test using Jest

For production it works perfectly, but for unit testing the code breaks because Jest can't import the asset as a module.

So the second part of the problem was fixed (I don't know if this is the best practice) using asset mocks.

```<code>// jest.config.cjs

{
⋮
  moduleNameMapper: {
      ⋮
      '([a-zA-Z_ ]+\\.html)\\?raw$': '<rootDir>/__mocks/$1.cjs'
  }
⋮
}
</code>```

To make it work, I created the following folder structure:

```<code>__mocks
      |
       confirm_email.html.cjs
       another_asset_mocked.html.cjs
</code>```

The confirm_email.html.cjs looks like this:

```<code>// __mocks/confirm_email.html.cjs
module.exports = '<html>content<html>'
</code>```

Body:
I'm using sveltekit and I can't use the files api to import html templates. So I decided to import by writing a module that imports the content of the document as a string (described here).

// src/global.d.ts

/// <reference types="@sveltejs/kit" />
declare module '*.html' {
  const content: string
  export default content
}

So far so good, but now I need to test the code and jest can't interpret the code.

● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

/home/developer/workspace/src/assets/html/confirm_email.html:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<!DOCTYPE html>
                                                                                ^

SyntaxError: Unexpected token '<'

I don't understand how jest understands the .d.ts files... How do I get to test the code?

Body:
1.Import html as string

I solved the problem using another approach...

I'm using a resource of vite to import the html file as an asset, as can be seen here in the documentation

import confirm_email_template from '../../../assets/html/confirm_email.html?raw'

2.Test using Jest

For production it works perfectly, but for unit testing the code breaks because Jest can't import the asset as a module.

So the second part of the problem was fixed (I don't know if this is the best practice) using asset mocks.

// jest.config.cjs

{
⋮
  moduleNameMapper: {
      ⋮
      '([a-zA-Z_ ]+\\.html)\\?raw$': '<rootDir>/__mocks/$1.cjs'
  }
⋮
}

To make it work, I created the following folder structure:

__mocks
      |
       confirm_email.html.cjs
       another_asset_mocked.html.cjs

The confirm_email.html.cjs looks like this:

// __mocks/confirm_email.html.cjs
module.exports = '<html>content<html>'


问:
How can I let the Debug Console print something 5 times instead of 1 time in Javascript, Visual Studio Code?
I am new to JavaScript. Is there a way to see the Hello 5 times instead see it showing that it was printed 5 times?

答:
Just put a counter with the console logs to see hello 5 times. Like

const a = [1, 2, 3, 4, 5];
a.forEach((num) => console.log(num, "hello"))```


问:
Component still rendering after unmount?
I have a component that look like this where I clear the state on unmount, however this is causing me problems. After the component has unmounted, the state is successfully cleared but then I get an error saying undefined is not an object (evaluating someState.first). I don't understand why this is still being rendered after unmount, from what I understand after a component has been unmounted the component shouldn't render anymore?

```<code>const SomeComponent = () => {
  const [someState, setSomeState] = ({
    first: 'John',
    last: 'Doe'
  });

  useEffect(()=>{
    someFunction();
    return () => {setSomeState()}
  }, []);

  const someFunction = () => {
    setSomeState({
      first: 'John',
      last: 'Doe',
    });
  }

  return (
    <View>
      <Text>{someState.first + ' ' + someState.last}</Text>
    </View>
  )
}
</code>```

答:
someState seems to be undefined in the beginnning.
Initialize it :

```<code>  const [someState, setSomeState] = ({  first: '',
      last: '',
});

</code>```

OR

Put a check in your JSX:

```<code> return (
    <View>
      {someState && <Text>{someState.first + ' ' + someState.last}</Text>}
    </View>
  )

</code>```

Body:
I have a component that look like this where I clear the state on unmount, however this is causing me problems. After the component has unmounted, the state is successfully cleared but then I get an error saying undefined is not an object (evaluating someState.first). I don't understand why this is still being rendered after unmount, from what I understand after a component has been unmounted the component shouldn't render anymore?

const SomeComponent = () => {
  const [someState, setSomeState] = ({
    first: 'John',
    last: 'Doe'
  });

  useEffect(()=>{
    someFunction();
    return () => {setSomeState()}
  }, []);

  const someFunction = () => {
    setSomeState({
      first: 'John',
      last: 'Doe',
    });
  }

  return (
    <View>
      <Text>{someState.first + ' ' + someState.last}</Text>
    </View>
  )
}

Body:
someState seems to be undefined in the beginnning.
Initialize it :

  const [someState, setSomeState] = ({  first: '',
      last: '',
});

OR

Put a check in your JSX:

 return (
    <View>
      {someState && <Text>{someState.first + ' ' + someState.last}</Text>}
    </View>
  )


问:
Typescript & inheritance - calling a static method from non-static method
Example code (simplified):

```<code>class Base {
   public static x: number;

   private static f() {
       console.log("static function's x is " + this.x);
       return this.x;
   }

   public g() {
      return Base.f();
   }

}

class Child extends Base {
    x = 5;
}

class OtherChild extends Base {
    x = 10;
}

const obj = new Child();
console.log("object's x is " + obj.x);
obj.g();
</code>```

Another class creates a Child object.

Looking at the child object I see x is set to 5.

Then I call g(), and inside it x is still defined as 5, and the type of "this" is Child.

Now g() calls f(), and inside it x is undefined, and the type of "this" is now Base.

I assume this is because I use Base.f(), but I can't use "this".

How can I call the static method of the base class from the non-static method without losing my object?

To clarify, I have static property that every child should have, so I want to define once it in the base class.

Every child has a different value for it, and the common functions in the base use this property (and obviously its value should depend on the subclass it was called from)

答:
When you call this from a static method it returns the class because you called the function from the class (Base.f()) and it's what static methods are meant for.

That being said, your code works as expected, but x is not being overridden by the subclass as you expect, because it's static (attached to the class) in the Base class and it's a class field (attached to the instance) in the Child class so they're two different things.

Body:
Example code (simplified):

class Base {
   public static x: number;

   private static f() {
       console.log("static function's x is " + this.x);
       return this.x;
   }

   public g() {
      return Base.f();
   }

}

class Child extends Base {
    x = 5;
}

class OtherChild extends Base {
    x = 10;
}

const obj = new Child();
console.log("object's x is " + obj.x);
obj.g();

Another class creates a Child object.

Looking at the child object I see x is set to 5.

Then I call g(), and inside it x is still defined as 5, and the type of "this" is Child.

Now g() calls f(), and inside it x is undefined, and the type of "this" is now Base.

I assume this is because I use Base.f(), but I can't use "this".

How can I call the static method of the base class from the non-static method without losing my object?

To clarify, I have static property that every child should have, so I want to define once it in the base class.

Every child has a different value for it, and the common functions in the base use this property (and obviously its value should depend on the subclass it was called from)


问:
Refresh token for google calendar API
Hi I am using the google calendar API for a school project and my tokens have expired and I don't know how to refresh them. Please help!!!</p>

答:
Here is an example [1] depending on the programming language you're using, for Python should be similar to the following:

```<code>...
developer_token: INSERT_DEVELOPER_TOKEN_HERE
client_id: INSERT_OAUTH2_CLIENT_ID_HERE
client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE
refresh_token: INSERT_OAUTH2_REFRESH_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE
...
</code>```

[1] https://developers.google.com/google-ads/api/docs/first-call/refresh-token

Title: Refresh token for google calendar API

Body:
Here is an example [1] depending on the programming language you're using, for Python should be similar to the following:

...
developer_token: INSERT_DEVELOPER_TOKEN_HERE
client_id: INSERT_OAUTH2_CLIENT_ID_HERE
client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE
refresh_token: INSERT_OAUTH2_REFRESH_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE
...

[1] https://developers.google.com/google-ads/api/docs/first-call/refresh-token


问:
problem with the result of a sql statement
I have the following scenario to achieve using SQL statement ,
I have an issue assigned to groups Triage,GX,GY:

group Triage --> group GX

group GX -->group Triage

group Triage --> group GY

I want to extract just the first time when my issue is assigned to group Triage and ignore the rest , I have tried to do that but always bad result(retrive all rows when the issue assigned to Triage group )

SQL Statement:

```<code>    select g.created ,ji.pkey as issueName
    from   changegroup g
    join   changeitem ci on (ci.groupid = g.id)
    join   jiraissue ji on (ji.id = g.issueid)
    join   project p on (p.id = ji.project)
    join   priority pr on (pr.id = ji.priority)
    where  ci.field = 'Group'
    and  ci.oldString = 'Triage'
    and  p.pname = 'Test'
    and pr.pname='P3'
    and  ji.created between '2011-08-11 14:01:00' and  '2011-08-12 14:11:00'
</code>```

the result of the statement (as you see ,the issue 200 is assigned to group Triage 2 times so the request retrieve 2 rows):

The table changegroup has this structure:

The table changeitem has this structure:

答:
Try this one. But it can be very slow query</p>

```<code>select g.created, ji.pkey as issueName
from   changegroup g
join   jiraissue ji on (ji.id = g.issueid)
where (g.created, issueName) in (
 select min(g.created) ,ji.pkey as issueName
 from   changegroup g
 join   changeitem ci on (ci.groupid = g.id)
 join   jiraissue ji on (ji.id = g.issueid)
 join   project p on (p.id = ji.project)
 join   priority pr on (pr.id = ji.priority)
 where  ci.field = 'Group'
 and  ci.oldString = 'Triage'
 and  p.pname = 'Test'
 and pr.pname='P3'
 and  ji.created between '2011-08-11 14:01:00' and  '2011-08-12 14:11:00'
 group by issueName
)
</code>```

Body:
I have the following scenario to achieve using SQL statement ,
I have an issue assigned to groups Triage,GX,GY:

group Triage --> group GX

group GX -->group Triage

group Triage --> group GY

I want to extract just the first time when my issue is assigned to group Triage and ignore the rest , I have tried to do that but always bad result(retrive all rows when the issue assigned to Triage group )

SQL Statement:

    select g.created ,ji.pkey as issueName
    from   changegroup g
    join   changeitem ci on (ci.groupid = g.id)
    join   jiraissue ji on (ji.id = g.issueid)
    join   project p on (p.id = ji.project)
    join   priority pr on (pr.id = ji.priority)
    where  ci.field = 'Group'
    and  ci.oldString = 'Triage'
    and  p.pname = 'Test'
    and pr.pname='P3'
    and  ji.created between '2011-08-11 14:01:00' and  '2011-08-12 14:11:00'

the result of the statement (as you see ,the issue 200 is assigned to group Triage 2 times so the request retrieve 2 rows):

The table changegroup has this structure:

The table changeitem has this structure:

Body:
Try this one. But it can be very slow query

select g.created, ji.pkey as issueName
from   changegroup g
join   jiraissue ji on (ji.id = g.issueid)
where (g.created, issueName) in (
 select min(g.created) ,ji.pkey as issueName
 from   changegroup g
 join   changeitem ci on (ci.groupid = g.id)
 join   jiraissue ji on (ji.id = g.issueid)
 join   project p on (p.id = ji.project)
 join   priority pr on (pr.id = ji.priority)
 where  ci.field = 'Group'
 and  ci.oldString = 'Triage'
 and  p.pname = 'Test'
 and pr.pname='P3'
 and  ji.created between '2011-08-11 14:01:00' and  '2011-08-12 14:11:00'
 group by issueName
)


问:
Flask go to new page on button click
I have a small flask app with an index page where the user selects a directory from a drop down menu. Once the user makes a selection and clicks "submit" on the webpage I would like to send them to a new page with info specific to that directory.

I'm trying to load the new page by simply calling the function after getting the input from the index page. My issue is that clicking submit on the webpage reloads the same index page.

Flask Code:

```<code>app = Flask(__name__)
dirname = os.path.dirname(sys.argv[0])

run_path = ""

@app.route("/", methods = ["GET", "POST"])
def index():
    dir_loc = "/Users/kregan1/Documents"
    dir_data = list(os.listdir(dir_loc))

    if request.method == "POST":
        run_dir = request.form.get("run_list")
        run_path = dir_loc + "/" + run_dir
        run(run_path)

    return render_template('index.html', data = dir_data)

@app.route("/run", methods = ["GET", "POST"])
def run(run_path):
    if os.path.isdir(run_path) == True:
        file_lists = []
        for f in os.listdir(run_path):
            if f.startswith("pattern"):
                file_lists.append(run_path + "/" + f)

        projects = []
        for fl in file_lists:
            with open(fl) as f:
                for row in f:
                    if row.split(",")[0] not in projects:
                        projects.append(row.split(",")[0])
    else:
        projects = ["a","b","c"]

    return render_template('run.html', run = run_path, proj_data = projects )
</code>```

index.html:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="{{url_for('static', filename='asp_javascript.js')}}"></script>
</head>
<body>

    <h2>Packaging Tool - Index</h2>
    <p>Select Run:</p>
    <form action="{{ url_for("index") }}" method="post">
        <select name="run_list">
            {% for d in data %}
            <option>{{d}}</option>
            {% endfor %}
        </select>
        <br>
        <input type="submit" value="submit">
    </form>

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

答:
You can use redirect(...) instead of just calling the function.

```<code>from flask import redirect
...
if request.method == "POST":
        run_dir = request.form.get("run_list")
        run_path = dir_loc + "/" + run_dir
        return redirect(url_for('run', run_path=run_path))

@app.route("/run/<run_path>", methods = ["GET", "POST"])
def run(run_path):
    if os.path.isdir(run_path) == True:
    ...
</code>```

Title: Flask go to new page on button click

Body:
I have a small flask app with an index page where the user selects a directory from a drop down menu. Once the user makes a selection and clicks "submit" on the webpage I would like to send them to a new page with info specific to that directory.

I'm trying to load the new page by simply calling the function after getting the input from the index page. My issue is that clicking submit on the webpage reloads the same index page.

Flask Code:

app = Flask(__name__)
dirname = os.path.dirname(sys.argv[0])

run_path = ""

@app.route("/", methods = ["GET", "POST"])
def index():
    dir_loc = "/Users/kregan1/Documents"
    dir_data = list(os.listdir(dir_loc))

    if request.method == "POST":
        run_dir = request.form.get("run_list")
        run_path = dir_loc + "/" + run_dir
        run(run_path)

    return render_template('index.html', data = dir_data)

@app.route("/run", methods = ["GET", "POST"])
def run(run_path):
    if os.path.isdir(run_path) == True:
        file_lists = []
        for f in os.listdir(run_path):
            if f.startswith("pattern"):
                file_lists.append(run_path + "/" + f)

        projects = []
        for fl in file_lists:
            with open(fl) as f:
                for row in f:
                    if row.split(",")[0] not in projects:
                        projects.append(row.split(",")[0])
    else:
        projects = ["a","b","c"]

    return render_template('run.html', run = run_path, proj_data = projects )

index.html:

<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">

Packaging Tool - Index

Select Run:

    <form action="{{ url_for("index") }}" method="post">
        <select name="run_list">
            {% for d in data %}
            <option>{{d}}</option>
            {% endfor %}
        </select>

        <input type="submit" value="submit">
    </form>

Body:
You can use redirect(...) instead of just calling the function.

from flask import redirect
...
if request.method == "POST":
        run_dir = request.form.get("run_list")
        run_path = dir_loc + "/" + run_dir
        return redirect(url_for('run', run_path=run_path))

@app.route("/run/<run_path>", methods = ["GET", "POST"])
def run(run_path):
    if os.path.isdir(run_path) == True:
    ...


问:
Replace {"errors":{"detail":"Not Found"}} with message in python
I am trying to write a script with python to extract stuff from a .pcap file. The output is written to a .csv file. This is what I have so far:
(please ignore the Dutch words, they are only for notes and names)

```<code>import csv
from encodings import utf_8
from enum import unique
import time
import dpkt.ethernet
import requests
import pyshark

from dpkt.utils import mac_to_str

#Opvragen bestand:
bestand = input("Voer hier het hele pad in naar de pcap(ng): ")

#Pcap reader inzetten:
f = open(bestand, 'rb')
pcap = dpkt.pcap.Reader(f)

#In de lege lijst worden de MAC addressen gezet:
maclist = []

#Voegt de source en destination toe in de maclist:
for timestamp, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    x = mac_to_str(eth.src)
    y = mac_to_str(eth.dst)
    maclist.append(x)
    maclist.append(y)

uniqueList = set(maclist)

#Schrijven naar een .csv bestand:
with open("output.csv", "w",encoding="UTF8") as a:
    writer  = csv.writer(a)

    for addr in uniqueList:
        extra = str(requests.get('http://api.macvendors.com/' + addr).text)
        time.sleep(1)
        print(f"MAC: {addr}, Fabrikant/serie/model: {extra}")

        writer.writerow([addr] + [extra])
    print("Zie ouput.csv voor het resultaat!")
</code>```

Unfortunally, sometimes my output looks like this:

```<code>MAC: <private>, Fabrikant/serie/model: {"errors":{"detail":"Not Found"}}
</code>```

Is there a way to replace this? It would make my output look a bit cleaner.

Thank you for your time!

答:
Check the value of extra and either skip the writing:

```<code>for addr in uniqueList:
    extra = str(requests.get('http://api.macvendors.com/' + addr).text)
    if extra == '{"errors":{"detail":"Not Found"}}':
         continue
</code>```

or replace it with something else, as the comments suggested

```<code>for addr in uniqueList:
    extra = str(requests.get('http://api.macvendors.com/' + addr).text)
    if extra == '{"errors":{"detail":"Not Found"}}':
         extra = "Not Found"
</code>```

Body:
I am trying to write a script with python to extract stuff from a .pcap file. The output is written to a .csv file. This is what I have so far:
(please ignore the Dutch words, they are only for notes and names)

import csv
from encodings import utf_8
from enum import unique
import time
import dpkt.ethernet
import requests
import pyshark

from dpkt.utils import mac_to_str

#Opvragen bestand:
bestand = input("Voer hier het hele pad in naar de pcap(ng): ")

#Pcap reader inzetten:
f = open(bestand, 'rb')
pcap = dpkt.pcap.Reader(f)

#In de lege lijst worden de MAC addressen gezet:
maclist = []

#Voegt de source en destination toe in de maclist:
for timestamp, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    x = mac_to_str(eth.src)
    y = mac_to_str(eth.dst)
    maclist.append(x)
    maclist.append(y)

uniqueList = set(maclist)

#Schrijven naar een .csv bestand:
with open("output.csv", "w",encoding="UTF8") as a:
    writer  = csv.writer(a)

    for addr in uniqueList:
        extra = str(requests.get('http://api.macvendors.com/' + addr).text)
        time.sleep(1)
        print(f"MAC: {addr}, Fabrikant/serie/model: {extra}")

        writer.writerow([addr] + [extra])
    print("Zie ouput.csv voor het resultaat!")

Unfortunally, sometimes my output looks like this:

MAC: <private>, Fabrikant/serie/model: {"errors":{"detail":"Not Found"}}

Is there a way to replace this? It would make my output look a bit cleaner.

Thank you for your time!

Body:
Check the value of extra and either skip the writing:

for addr in uniqueList:
    extra = str(requests.get('http://api.macvendors.com/' + addr).text)
    if extra == '{"errors":{"detail":"Not Found"}}':
         continue

or replace it with something else, as the comments suggested

for addr in uniqueList:
    extra = str(requests.get('http://api.macvendors.com/' + addr).text)
    if extra == '{"errors":{"detail":"Not Found"}}':
         extra = "Not Found"