问:
Alternative to $MyInvocation
When deploying PowerShell scripts from my RMM (NinjaOne), the scripts are called from a .bat (batch file).

Example:

@powershell -ExecutionPolicy Bypass -File "test.ps1" -stringParam "testing" -switchParam > "output.txt" 2>&1
```
<p>The script I am calling requires PowerShell 7+, so I need to restart the script by calling <code>pwsh</code> with the current parameters. I planned to accomplish this via the following:</p>
<pre class="lang-ps prettyprint-override"><code>Invoke-Command { & pwsh -Command $MyInvocation.Line } -NoNewScope
</code>```

Unfortunately, $MyInvocation.Line does not return the correct result when a PowerShell script is called from a batch file. What alternatives exist that would work in this scenario?

Notes:

I am unable to make changes to the .bat file.

$PSBoundParameters also does not return the expected result.

Testing Script (called from batch):

```<code>Param(
  [string]$string,
  [switch]$switch
)

if (!($PSVersionTable.PSVersion.Major -ge 7)) {
  Write-Output "`n"
  Write-Output 'Attempting to restart in PowerShell 7'
  if(!$MyInvocation.Line) {
    Write-Output 'Parameters not carried over - cannot restart'
    Exit
  } else { Write-Output $MyInvocation.Line }
  Invoke-Command { & pwsh -Command $MyInvocation.Line } -NoNewScope # PowerShell 7
  Exit
}

Write-Output 'Parameters carried over:'
Write-Output $PSBoundParameters

Write-Output "`nSuccessfully restarted"

</code>```

Edit: I've discovered the reason for $MyInvocation / $PSBoundParameters not being set properly is due to the use of -File instead of -Command when my RMM provider calls the PowerShell script from the .bat file. I've suggested they implement this change to resolve the issue. Until they do, I am still looking for alternatives.

答:
I'd try putting a file called powershell.bat early on your path (at least, in a directory earlier on the path than the C:\Windows\System32\WindowsPowerShell\v1.0\; entry) and assemble the appropriate parameters (I've no idea of your required structure for $myinvocationline - no doubt it could be derived from the parameters delivered to powershell.bat).

My thinking is that this should override powershell, re-assemble the bits and deliver them to pwsh.

Title: Alternative to $MyInvocation

Body:
When deploying PowerShell scripts from my RMM (NinjaOne), the scripts are called from a .bat (batch file).

Example:

@powershell -ExecutionPolicy Bypass -File "test.ps1" -stringParam "testing" -switchParam > "output.txt" 2>&1

The script I am calling requires PowerShell 7+, so I need to restart the script by calling pwsh with the current parameters. I planned to accomplish this via the following:

Invoke-Command { & pwsh -Command $MyInvocation.Line } -NoNewScope

Unfortunately, $MyInvocation.Line does not return the correct result when a PowerShell script is called from a batch file. What alternatives exist that would work in this scenario?

Notes:

I am unable to make changes to the .bat file.

$PSBoundParameters also does not return the expected result.

Testing Script (called from batch):

Param(
  [string]$string,
  [switch]$switch
)

if (!($PSVersionTable.PSVersion.Major -ge 7)) {
  Write-Output "`n"
  Write-Output 'Attempting to restart in PowerShell 7'
  if(!$MyInvocation.Line) {
    Write-Output 'Parameters not carried over - cannot restart'
    Exit
  } else { Write-Output $MyInvocation.Line }
  Invoke-Command { & pwsh -Command $MyInvocation.Line } -NoNewScope # PowerShell 7
  Exit
}

Write-Output 'Parameters carried over:'
Write-Output $PSBoundParameters

Write-Output "`nSuccessfully restarted"

Edit: I've discovered the reason for $MyInvocation / $PSBoundParameters not being set properly is due to the use of -File instead of -Command when my RMM provider calls the PowerShell script from the .bat file. I've suggested they implement this change to resolve the issue. Until they do, I am still looking for alternatives.


来源: stackexchange

问:
How do I reduce a python (docker) image size using a multi-stage build?
I am looking for a way to create multistage builds with python and Dockerfile:

For example, using the following images:

1st image: install all compile-time requirements, and install all needed python modules

2nd image: copy all compiled/built packages from the first image to the second, without the compilers themselves (gcc, postgers-dev, python-dev, etc..)

The final objective is to have a smaller image, running python and the python packages that I need.

In short: how can I 'wrap' all the compiled modules (site-packages / external libs) that were created in the first image, and copy them in a 'clean' manner, to the 2nd image.

答:
This is a place where using a Python virtual environment inside Docker can be useful.  Copying a virtual environment normally is tricky since it needs to be the exact same filesystem path on the exact same Python build, but in Docker you can guarantee that.

(This is the same basic recipe @mpoisot describes in their answer and it appears in other SO answers as well.)

Say you're installing the psycopg PostgreSQL client library.  The extended form of this requires the Python C development library plus the PostgreSQL C client library headers; but to run it you only need the PostgreSQL C runtime library.  So here you can use a multi-stage build: the first stage installs the virtual environment using the full C toolchain, and the final stage copies the built virtual environment but only includes the minimum required libraries.

A typical Dockerfile could look like:

# Name the single Python image we're using everywhere.
ARG python=python:3.10-slim

# Build stage:
FROM ${python} AS build

# Install a full C toolchain and C build-time dependencies for
# everything we're going to need.
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --no-install-recommends --assume-yes \
      build-essential \
      libpq-dev

# Create the virtual environment.
RUN python3 -m venv /venv
ENV PATH=/venv/bin:$PATH

# Install the Python library dependencies, including those with
# C extensions.  They'll get installed into the virtual environment.
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

# Final stage:
FROM ${python}

# Install the runtime-only C library dependencies we need.
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --no-install-recommends --assume-yes \
      libpq5

# Copy the virtual environment from the first stage.
COPY --from=build /venv /venv
ENV PATH=/venv/bin:$PATH

# Copy the application in.
COPY . .
CMD ["./main.py"]
```

If your application uses a Python entry point script then you can do everything in the first stage: RUN pip install . will copy the application into the virtual environment and create a wrapper script in /venv/bin for you.  In the final stage you don't need to COPY the application again.  Set the CMD to run the wrapper script out of the virtual environment, which is already at the front of the $PATH.

Again, note that this approach only works because it is the same Python base image in both stages, and because the virtual environment is on the exact same path.  If it is a different Python or a different container path the transplanted virtual environment may not work correctly.

ContentLicense: CC BY-SA 4.0

Body:
This is a place where using a Python virtual environment inside Docker can be useful.  Copying a virtual environment normally is tricky since it needs to be the exact same filesystem path on the exact same Python build, but in Docker you can guarantee that.

(This is the same basic recipe @mpoisot describes in their answer and it appears in other SO answers as well.)

Say you're installing the psycopg PostgreSQL client library.  The extended form of this requires the Python C development library plus the PostgreSQL C client library headers; but to run it you only need the PostgreSQL C runtime library.  So here you can use a multi-stage build: the first stage installs the virtual environment using the full C toolchain, and the final stage copies the built virtual environment but only includes the minimum required libraries.

A typical Dockerfile could look like:

# Name the single Python image we're using everywhere.
ARG python=python:3.10-slim

# Build stage:
FROM ${python} AS build

# Install a full C toolchain and C build-time dependencies for
# everything we're going to need.
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --no-install-recommends --assume-yes \
      build-essential \
      libpq-dev

# Create the virtual environment.
RUN python3 -m venv /venv
ENV PATH=/venv/bin:$PATH

# Install the Python library dependencies, including those with
# C extensions.  They'll get installed into the virtual environment.
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

# Final stage:
FROM ${python}

# Install the runtime-only C library dependencies we need.
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --no-install-recommends --assume-yes \
      libpq5

# Copy the virtual environment from the first stage.
COPY --from=build /venv /venv
ENV PATH=/venv/bin:$PATH

# Copy the application in.
COPY . .
CMD ["./main.py"]

If your application uses a Python entry point script then you can do everything in the first stage: RUN pip install . will copy the application into the virtual environment and create a wrapper script in /venv/bin for you.  In the final stage you don't need to COPY the application again.  Set the CMD to run the wrapper script out of the virtual environment, which is already at the front of the $PATH.

Again, note that this approach only works because it is the same Python base image in both stages, and because the virtual environment is on the exact same path.  If it is a different Python or a different container path the transplanted virtual environment may not work correctly.


问:
C# How to store string values in a list outputted from a loop
Q: How can I capture the data within my string list. After it's been looped? Therefore, I can use the list variable elsewhere in my method.

Goal: The output to the console needs to contain the value of what it's holding (i.e. the alphabet letters). The function only runs one time. In my progress...my desired/expect outcome almost-occurs when I loop my list a.k.a my string value within a foreach loop. However, I only want the output data one time...so a for loop is preferable (because it only runs once.)

I believed the simplest way to solve my dilemma is to add another for loop to iterate over the existing list. Then print the index + 1, and the value at that index to find the solution. But I am having issues.

Expected output (only runs once in a loop)

```<code>ABC
DEF
GHI
JKL
MNO
</code>```

Example Code:

```<code>            var FriendsList = new List<string>();
            foreach (var friends in Obj.users)
            {
                FriendsList.Add(friend.user);

                foreach (var i in FriendsList)
                {
                    Trace.WriteLine(i);
                }

            }
</code>```

Undesirable output example:

```<code>001
001
002
001
002
003
001
002
003
004
001
002
003
004
005
</code>```

I don't believe this to be a good solution

```<code>//Using Linq to itterate over an array
var Arr = new string[4] {"one", "Two", "Three", "Four"};
Trace.WriteLine(Arr.Select((s, i) => $"Item no: {i + 1}, Value: {s}"));
</code>```

It's wasteful.

I appreciate the help!
Please provide examples.

答:
Each time you read a value inside Obj you print the whole new List FriendsList and that's not what you are expecting...

Capturing datas in this way is correct but not the way you wanna print them, you can simply capture them and print friend object values.

```<code>var FriendsList = new List<string>();
foreach (var friend in Obj.users)
{
 FriendsList.Add(friend.user);
 Console.WriteLine("{0}: {1}", friend, friend.user);
}
</code>```

Otherwise you can use this function after the foreach loop

```<code>var FriendsList = new List<string>();
foreach (var friend in Obj.users)
{
 FriendsList.Add(friend.user);
}

FrindsList.ForEach(Console.WriteLine);
</code>```

Body:
Q: How can I capture the data within my string list. After it's been looped? Therefore, I can use the list variable elsewhere in my method.

Goal: The output to the console needs to contain the value of what it's holding (i.e. the alphabet letters). The function only runs one time. In my progress...my desired/expect outcome almost-occurs when I loop my list a.k.a my string value within a foreach loop. However, I only want the output data one time...so a for loop is preferable (because it only runs once.)

I believed the simplest way to solve my dilemma is to add another for loop to iterate over the existing list. Then print the index + 1, and the value at that index to find the solution. But I am having issues.

Expected output (only runs once in a loop)

ABC
DEF
GHI
JKL
MNO

Example Code:

            var FriendsList = new List<string>();
            foreach (var friends in Obj.users)
            {
                FriendsList.Add(friend.user);

                foreach (var i in FriendsList)
                {
                    Trace.WriteLine(i);
                }

            }

Undesirable output example:

001
001
002
001
002
003
001
002
003
004
001
002
003
004
005

I don't believe this to be a good solution

//Using Linq to itterate over an array
var Arr = new string[4] {"one", "Two", "Three", "Four"};
Trace.WriteLine(Arr.Select((s, i) => $"Item no: {i + 1}, Value: {s}"));

It's wasteful.

I appreciate the help!
Please provide examples.

Body:
Each time you read a value inside Obj you print the whole new List FriendsList and that's not what you are expecting...

Capturing datas in this way is correct but not the way you wanna print them, you can simply capture them and print friend object values.

var FriendsList = new List<string>();
foreach (var friend in Obj.users)
{
 FriendsList.Add(friend.user);
 Console.WriteLine("{0}: {1}", friend, friend.user);
}

Otherwise you can use this function after the foreach loop

var FriendsList = new List<string>();
foreach (var friend in Obj.users)
{
 FriendsList.Add(friend.user);
}

FrindsList.ForEach(Console.WriteLine);


问:
Strange behavior of (python) str.split when using the default sep value (None)
Does anyone have a clear way to explain the rule regarding str.split(sep=None)? The Docstring provides some explanation but not enough to understand the following behaviors

```<code>>>> s = '\n Hello\t World\nOpps\t '
>>> print(s.split()) #by default sep = None
['Hello', 'World', 'Opps']
>>> print(s.split(maxsplit = 1))
['Hello', 'World\nOpps\t ']
</code>```

The first print seems reasonable since it splits whenever whitespace appears, and then dump all the empty strings.

The second one is a bit harder to understanding: if it only splits once, then it should condiser the 1st '\n' as the delimiter and results in an empty string '' (which should be dumped next) and ' Hello World\nOpps\t'.

Thank you in advance for any consistent and logical explanation you may provide.

PS: I have included the Docstring in below, and I am aware of this question, and an answer there offers some help but a clear rule with official source is still missing. Without official source explanation, a rule is just something for users to memorize without understanding.

sep

The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.

答:
You should look at the official docs, where this is explained in detail:

If sep is not specified or is None, a different splitting
algorithm is applied: runs of consecutive whitespace are regarded as
a single separator, and the result will contain no empty strings at
the start or end if the string has leading or trailing whitespace.
Consequently, splitting an empty string or a string consisting of just
whitespace with a None separator returns [].

Bold emphasis added by me.

However, this does leave ambiguity regarding what a "split" is in the case of `sep=None, maxsplit=some_positive_number). But apparently, the leading and trailing whitespace acts, at least conceptually, as if it simply wasn't there. But notice:

```<code>>>> "   a   b c ".split(maxsplit=1)
['a', 'b c ']
</code>```

So it isn't actually removed.

Body:
Does anyone have a clear way to explain the rule regarding str.split(sep=None)? The Docstring provides some explanation but not enough to understand the following behaviors

>>> s = '\n Hello\t World\nOpps\t '
>>> print(s.split()) #by default sep = None
['Hello', 'World', 'Opps']
>>> print(s.split(maxsplit = 1))
['Hello', 'World\nOpps\t ']

The first print seems reasonable since it splits whenever whitespace appears, and then dump all the empty strings.

The second one is a bit harder to understanding: if it only splits once, then it should condiser the 1st '\n' as the delimiter and results in an empty string '' (which should be dumped next) and ' Hello World\nOpps\t'.

Thank you in advance for any consistent and logical explanation you may provide.

PS: I have included the Docstring in below, and I am aware of this question, and an answer there offers some help but a clear rule with official source is still missing. Without official source explanation, a rule is just something for users to memorize without understanding.

sep

The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.

Body:
You should look at the official docs, where this is explained in detail:

If sep is not specified or is None, a different splitting
algorithm is applied: runs of consecutive whitespace are regarded as
a single separator, and the result will contain no empty strings at
the start or end if the string has leading or trailing whitespace.
Consequently, splitting an empty string or a string consisting of just
whitespace with a None separator returns [].

Bold emphasis added by me.

However, this does leave ambiguity regarding what a "split" is in the case of `sep=None, maxsplit=some_positive_number). But apparently, the leading and trailing whitespace acts, at least conceptually, as if it simply wasn't there. But notice:

>>> "   a   b c ".split(maxsplit=1)
['a', 'b c ']

So it isn't actually removed.


问:
How can I make my function return all the combinations of a grid horizontally?
So I wrote a function slanted(grid) which takes in a grid and returns the combination of letters horizontally.

For instance, if grid is

```<code>['q','q','d'],
['s','d','e'],
['e','g','h']
</code>```

then slanted(grid) should return

```<code>['d','qe','qdh','sg','e']
</code>```

I tried to do this by writing up this code for slanted(grid)

```<code>def slanted(grid):
    results = []
    for j in range(len(grid)-1):
        tmp = ""
        for i in range(len(grid)):
            tmp += [j+i][i]
            results.append(tmp)
    return results

print(slanted([['q','q','d'],['s','d','e'],['e','g','h']]))
</code>```

but I'm getting an error message saying:

```<code>TypeError: can only concatenate str (not "int") to str
</code>```

what changes to my code should I make to get the right output as indicated above?

答:
[j + i][i] creates a singleton list with one integer, and then attempts to access that integer. You should try to access an element of grid, e.g. by doing grid[j + i][i], but this causes an IndexError.

Here is my approach to your task. You can think of this as reading a series of diagonals, each starting from a different start row / column index. For each start index, we extract that given diagonal:

def extract_diagonal(grid, start_row, start_col):
    row = start_row
    col = start_col
    letters = []

    while row < len(grid) and col < len(grid[0]):
        letters.append(grid[row][col])
        row += 1
        col += 1

    return ''.join(letters)

def slanted(grid):
    results = []
    for col in range(len(grid) - 1, -1, -1):
        results.append(extract_diagonal(grid, 0, col))

    for row in range(1, len(grid)):
        results.append(diagonal(grid, row, 0))

    return results

# Prints ['d','qe','qdh','sg','e'].
print(slanted([['q','q','d'],['s','d','e'],['e','g','h']]))
```

Note that we're using ''.join() rather than repeated string concatenation here, as the former has a better time complexity. For more discussion on this, see this answer.

Body:
So I wrote a function slanted(grid) which takes in a grid and returns the combination of letters horizontally.

For instance, if grid is

['q','q','d'],
['s','d','e'],
['e','g','h']

then slanted(grid) should return

['d','qe','qdh','sg','e']

I tried to do this by writing up this code for slanted(grid)

def slanted(grid):
    results = []
    for j in range(len(grid)-1):
        tmp = ""
        for i in range(len(grid)):
            tmp += [j+i][i]
            results.append(tmp)
    return results

print(slanted([['q','q','d'],['s','d','e'],['e','g','h']]))

but I'm getting an error message saying:

TypeError: can only concatenate str (not "int") to str

what changes to my code should I make to get the right output as indicated above?

Body:
[j + i][i] creates a singleton list with one integer, and then attempts to access that integer. You should try to access an element of grid, e.g. by doing grid[j + i][i], but this causes an IndexError.

Here is my approach to your task. You can think of this as reading a series of diagonals, each starting from a different start row / column index. For each start index, we extract that given diagonal:

def extract_diagonal(grid, start_row, start_col):
    row = start_row
    col = start_col
    letters = []

    while row < len(grid) and col < len(grid[0]):
        letters.append(grid[row][col])
        row += 1
        col += 1

    return ''.join(letters)

def slanted(grid):
    results = []
    for col in range(len(grid) - 1, -1, -1):
        results.append(extract_diagonal(grid, 0, col))

    for row in range(1, len(grid)):
        results.append(diagonal(grid, row, 0))

    return results

# Prints ['d','qe','qdh','sg','e'].
print(slanted([['q','q','d'],['s','d','e'],['e','g','h']]))

Note that we're using ''.join() rather than repeated string concatenation here, as the former has a better time complexity. For more discussion on this, see this answer.


问:
Removing Junk Character from a string
I have a SQL statement in a case condition in one of the query which determines if a record is a pass or fail.

The condition is like below:

```<code>CASE
    WHEN PATINDEX('%[^a-zA-Z0-9 [-^+!#.,&''""():/-]%', [NAME1]) = 0
        THEN 'Pass'
        ELSE 'Fail'
    END AS RESULTS
</code>```

meaning, we are checking for any junk chars in the string, but there are some hidden chars in some of the strings between two words (in the space) like ex: U+A0 (got to know this from an online tool check)

Now, how do I include this check in the above condition which I have? I tried the COLLATE function which I saw in this group, but either I'm not using it correctly or its not working.

Could someone help me on how I can achieve this?

Thanks.

答:
You mentioned trying COLLATE, but you didn't show specifically what your tried. Did you try something like PATINDEX('%[^...]%', [NAME1] COLLATE Latin1_General_BIN)? The Latin1_General_BIN collation forces pretty much an exact (extended-ASCII) compare.

I suspect your environment may be defaulting to some other collation that includes a lot of character equivalences, such as space ~= non-breaking space. That would also affect some of the character ranges you have in your pattern, such as alpha characters including the accented variants.

The following applies your pattern to a range of characters 0x20 - 0xFF and shows results both without and with the Latin1_General_BIN collation.

```<code>DECLARE @Pattern VARCHAR(100) = '%[^a-zA-Z0-9 [-^+!#.,&''""():/-]%'

SELECT CHARCODE, C, S, Result1, Result2, Result3
FROM ( -- Generate 32..255 (x20..xFF)
    SELECT CharCode = d1 * 16 + d2
    FROM (VALUES (2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15)) D1(d1)
    CROSS APPLY (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15)) D2(d2)
) CC
CROSS APPLY (
    SELECT
        C = CHAR(CC.CharCode),
        S = 'ABC' + CHAR(CC.CharCode) + 'XYZ'
) S
CROSS APPLY (
    SELECT
        Result1 = CASE
            WHEN PATINDEX(@Pattern, S) = 0
            THEN '----'
            ELSE 'Fail'
            END,
        Result2 = CASE
            WHEN PATINDEX(@Pattern, S COLLATE Latin1_General_CI_AI) = 0
            THEN '----'
            ELSE 'Fail'
            END,
        Result3 = CASE
            WHEN PATINDEX(@Pattern, S COLLATE Latin1_General_BIN) = 0
            THEN '----'
            ELSE 'Fail'
            END
) R
ORDER BY CC.CharCode
</code>```

See db<>fiddle. The interesting results start at character code 128 (0x80).

Title: Removing Junk Character from a string

Body:
I have a SQL statement in a case condition in one of the query which determines if a record is a pass or fail.

The condition is like below:

CASE
    WHEN PATINDEX('%[^a-zA-Z0-9 [-^+!#.,&''""():/-]%', [NAME1]) = 0
        THEN 'Pass'
        ELSE 'Fail'
    END AS RESULTS

meaning, we are checking for any junk chars in the string, but there are some hidden chars in some of the strings between two words (in the space) like ex: U+A0 (got to know this from an online tool check)

Now, how do I include this check in the above condition which I have? I tried the COLLATE function which I saw in this group, but either I'm not using it correctly or its not working.

Could someone help me on how I can achieve this?

Thanks.

Body:
You mentioned trying COLLATE, but you didn't show specifically what your tried. Did you try something like PATINDEX('%[^...]%', [NAME1] COLLATE Latin1_General_BIN)? The Latin1_General_BIN collation forces pretty much an exact (extended-ASCII) compare.

I suspect your environment may be defaulting to some other collation that includes a lot of character equivalences, such as space ~= non-breaking space. That would also affect some of the character ranges you have in your pattern, such as alpha characters including the accented variants.

The following applies your pattern to a range of characters 0x20 - 0xFF and shows results both without and with the Latin1_General_BIN collation.

DECLARE @Pattern VARCHAR(100) = '%[^a-zA-Z0-9 [-^+!#.,&''""():/-]%'

SELECT CHARCODE, C, S, Result1, Result2, Result3
FROM ( -- Generate 32..255 (x20..xFF)
    SELECT CharCode = d1 * 16 + d2
    FROM (VALUES (2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15)) D1(d1)
    CROSS APPLY (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15)) D2(d2)
) CC
CROSS APPLY (
    SELECT
        C = CHAR(CC.CharCode),
        S = 'ABC' + CHAR(CC.CharCode) + 'XYZ'
) S
CROSS APPLY (
    SELECT
        Result1 = CASE
            WHEN PATINDEX(@Pattern, S) = 0
            THEN '----'
            ELSE 'Fail'
            END,
        Result2 = CASE
            WHEN PATINDEX(@Pattern, S COLLATE Latin1_General_CI_AI) = 0
            THEN '----'
            ELSE 'Fail'
            END,
        Result3 = CASE
            WHEN PATINDEX(@Pattern, S COLLATE Latin1_General_BIN) = 0
            THEN '----'
            ELSE 'Fail'
            END
) R
ORDER BY CC.CharCode

See db<>fiddle. The interesting results start at character code 128 (0x80).


问:
Conditional useNavigate(), within button, based on error response
I have a signup form. Upon submit, if the inputs fail any validations, I need for the errors to be visible to the user, and for the browser to stay on the /signup page. If the form inputs pass all validations, I need for the submit button to navigate away to another page ('/about', as a placeholder).

The form submit button has an onSubmit(). At the end of the onSubmit I am calling the useNavigate hook to navigate away from /signup. I need something like a ternary which could, for example, say

```<code>errors ? null : navigate('/about)
</code>```

"If there are errors, do not navigate, else navigate." I've tried many combinations but can't get it.

My full code:

```<code>import { React, useState } from 'react'
import './Signup.css'
import { useNavigate } from "react-router-dom";

export default function Signup() {

    const navigate = useNavigate()

    const [username, setUsername] = useState("");
    const [name, setName] = useState("");
    const [password, setPassword] = useState("");
    const [passwordConfirmation, setPasswordConfirmation] = useState("");
    const [errors, setErrors] = useState([])

    function onSubmit(e){
        e.preventDefault()
        const user = {
            name: name,
            username: username,
            password: password,
            password_confirmation: passwordConfirmation
        }
        fetch('http://localhost:3000/users', {
            method:'POST',
            headers:{'Content-Type': 'application/json'},
            body:JSON.stringify(user)
        })
        .then(res => res.json())
        .then(json => {
            if(json.errors) setErrors(Object.entries(json.errors))
        })
        // need something like a ternary which says,
        // if errors, stay on current page/render errors
        // else, navigate away
        navigate('/about')
    }

    return (
        <>
            <form onSubmit={onSubmit} className="form">
                {/* <div className="container1"> */}
                    <h3 className="login-h3">Sign ur ass uPPP</h3>
                    <input
                        type="text"
                        id="name"
                        placeholder="name"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        />
                    <input
                        type="text"
                        id="username"
                        placeholder="username"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                        />
                    <input
                        type="password"
                        id="password"
                        placeholder="password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        />
                    <input
                        type="password"
                        id="password_confirmation"
                        placeholder="confirm password"
                        value={passwordConfirmation}
                        onChange={(e) => setPasswordConfirmation(e.target.value)}
                        />
                    <button

                        type="submit">Sign up!
                    </button>
                {/* </div> */}
            </form>
            { errors ? errors.map(e => <div>{e[0]+' : ' + e[1]}</div>) : null}
        </>
    )
}
</code>```

答:
If you like, you can use

```<code>!errors && navigate('url')
</code>```

Or you can configure your API return to generate error and use .catch, like that in your .then you can just follow the ok way.

Body:
I have a signup form. Upon submit, if the inputs fail any validations, I need for the errors to be visible to the user, and for the browser to stay on the /signup page. If the form inputs pass all validations, I need for the submit button to navigate away to another page ('/about', as a placeholder).

The form submit button has an onSubmit(). At the end of the onSubmit I am calling the useNavigate hook to navigate away from /signup. I need something like a ternary which could, for example, say

errors ? null : navigate('/about)

"If there are errors, do not navigate, else navigate." I've tried many combinations but can't get it.

My full code:

import { React, useState } from 'react'
import './Signup.css'
import { useNavigate } from "react-router-dom";

export default function Signup() {

    const navigate = useNavigate()

    const [username, setUsername] = useState("");
    const [name, setName] = useState("");
    const [password, setPassword] = useState("");
    const [passwordConfirmation, setPasswordConfirmation] = useState("");
    const [errors, setErrors] = useState([])

    function onSubmit(e){
        e.preventDefault()
        const user = {
            name: name,
            username: username,
            password: password,
            password_confirmation: passwordConfirmation
        }
        fetch('http://localhost:3000/users', {
            method:'POST',
            headers:{'Content-Type': 'application/json'},
            body:JSON.stringify(user)
        })
        .then(res => res.json())
        .then(json => {
            if(json.errors) setErrors(Object.entries(json.errors))
        })
        // need something like a ternary which says,
        // if errors, stay on current page/render errors
        // else, navigate away
        navigate('/about')
    }

    return (
        <>
            <form onSubmit={onSubmit} className="form">
                {/*
 */}

Sign ur ass uPPP

                    <input
                        type="text"
                        id="name"
                        placeholder="name"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        />
                    <input
                        type="text"
                        id="username"
                        placeholder="username"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                        />
                    <input
                        type="password"
                        id="password"
                        placeholder="password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        />
                    <input
                        type="password"
                        id="password_confirmation"
                        placeholder="confirm password"
                        value={passwordConfirmation}
                        onChange={(e) => setPasswordConfirmation(e.target.value)}
                        />
                    <button

                        type="submit">Sign up!
                    </button>
                {/*
 */}
            </form>
            { errors ? errors.map(e =>
{e[0]+' : ' + e[1]}
) : null}
        </>
    )
}

Body:
If you like, you can use

!errors && navigate('url')

Or you can configure your API return to generate error and use .catch, like that in your .then you can just follow the ok way.


问:
How can I display something in the console if I clicked on an event in fullcalendar?
In config:

```<code> select: this.handleManualSelect.bind(this),
      dateClick: this.dateClick.bind(this),
      eventClick: info => {
        console.log(info, 'click');
      },
      eventMouseEnter: info => {
        console.log(info, 'enter');
      },
      eventMouseLeave: info => {
        console.log(info, 'leave');
      },
      eventDidMount: info => {
        console.log(info, 'DidMount');
      },
</code>```

When I try to click on the event, nothing is displayed in the console, what am I doing wrong?

答:
I have added the click listener to options. It works. Perhaps some other configurations or how your project is set up is causing this.

calendarOptions = {
 //...
    events: [
      {
        title: 'Sample event',
        start: moment(),
        end:moment().add(30, 'minutes'),
        resourceId: 1
      }
    ],
    eventClick: (info) => {
      console.log(info)
    },
  };
```
<pre class="lang-js prettyprint-override"><code>{
allDay: false
className: []
end: Moment {_isAMomentObject: true, _isUTC: false, _pf: {…}, _locale: Locale, _fullCalendar: true, …}
resourceId: "1"
resourceIds: null
source: constructor {calendar: constructor, className: Array(0), uid: '1', eventDefs: Array(1), rawEventDefs: Array(1), …}
start: Moment {_isAMomentObject: true, _isUTC: false, _pf: {…}, _locale: Locale, _fullCalendar: true, …}
title: "Sample event"
_id: "_fc1"
}
</code>```

Find the sample calendar event and click on it.

Working example: https://stackblitz.com/edit/angular-fullcalendar-issue-cun3ms?file=app%2Fapp.component.ts

Body:
In config:

 select: this.handleManualSelect.bind(this),
      dateClick: this.dateClick.bind(this),
      eventClick: info => {
        console.log(info, 'click');
      },
      eventMouseEnter: info => {
        console.log(info, 'enter');
      },
      eventMouseLeave: info => {
        console.log(info, 'leave');
      },
      eventDidMount: info => {
        console.log(info, 'DidMount');
      },

When I try to click on the event, nothing is displayed in the console, what am I doing wrong?

Body:
I have added the click listener to options. It works. Perhaps some other configurations or how your project is set up is causing this.

calendarOptions = {
 //...
    events: [
      {
        title: 'Sample event',
        start: moment(),
        end:moment().add(30, 'minutes'),
        resourceId: 1
      }
    ],
    eventClick: (info) => {
      console.log(info)
    },
  };

{
allDay: false
className: []
end: Moment {_isAMomentObject: true, _isUTC: false, _pf: {…}, _locale: Locale, _fullCalendar: true, …}
resourceId: "1"
resourceIds: null
source: constructor {calendar: constructor, className: Array(0), uid: '1', eventDefs: Array(1), rawEventDefs: Array(1), …}
start: Moment {_isAMomentObject: true, _isUTC: false, _pf: {…}, _locale: Locale, _fullCalendar: true, …}
title: "Sample event"
_id: "_fc1"
}

Find the sample calendar event and click on it.

Working example: https://stackblitz.com/edit/angular-fullcalendar-issue-cun3ms?file=app%2Fapp.component.ts


问:
Problem with Git: "ssh: connect to host gitlab port 22: connection refused"
i am writing my bachelors thesis at a company and got access to gitlab from the admin, but I am new to Git. I created a new project for my thesis. I already had a folder with some stuff on my computer. I used the following commands in the git bash (as recommended by gitlab):

```<code>git init
git remote add origin git@gitlab:USER/TITLE.git
git add [stuff]
git commit
git push -u origin master
</code>```

Committing was successfull, but the last command created the error

"ssh: connect to host gitlab port 22: Connection refused
  fatal: Could not read from remote repository.
  Please make sure you have the correct access rights
  and the repository exists."

I tried to switch to port 443, because apparently, that is a thing.

```<code>ssh -T -p 443 git@altssh.gitlab.com
</code>```

That got me:

"The authenticity of host '[altssh.gitlab.com]:443 ([35.190.168.187]:443)' can't be established.

  ECDSA key fingerprint is [...].

  Are you sure you want to continue connecting (yes/no/[fingerprint])?"

After typing yes:

"Warning: Permanently added '[altssh.gitlab.com]:443,[35.190.168.187]:443' (ECDSA) to the list of known hosts.

  git@altssh.gitlab.com: Permission denied (publickey)."

When going back to port 22, the connection timed out.
The error after the push command is still the same.

According to canyouseeme.org, the ports 22 and 443 are not open.

I also tried to make new rules for the ports in the windows defender firewall menu.

Still the same error.
I would really appreciate any help or ideas from you :)

Peter

答: Check if you are not behind a VPN, I spent like half an hour before I thought about that.</p>

Body:
i am writing my bachelors thesis at a company and got access to gitlab from the admin, but I am new to Git. I created a new project for my thesis. I already had a folder with some stuff on my computer. I used the following commands in the git bash (as recommended by gitlab):

git init
git remote add origin git@gitlab:USER/TITLE.git
git add [stuff]
git commit
git push -u origin master

Committing was successfull, but the last command created the error

"ssh: connect to host gitlab port 22: Connection refused
  fatal: Could not read from remote repository.
  Please make sure you have the correct access rights
  and the repository exists."

I tried to switch to port 443, because apparently, that is a thing.

ssh -T -p 443 git@altssh.gitlab.com

That got me:

"The authenticity of host '[altssh.gitlab.com]:443 ([35.190.168.187]:443)' can't be established.

  ECDSA key fingerprint is [...].

  Are you sure you want to continue connecting (yes/no/[fingerprint])?"

After typing yes:

"Warning: Permanently added '[altssh.gitlab.com]:443,[35.190.168.187]:443' (ECDSA) to the list of known hosts.

  git@altssh.gitlab.com: Permission denied (publickey)."

When going back to port 22, the connection timed out.
The error after the push command is still the same.

According to canyouseeme.org, the ports 22 and 443 are not open.

I also tried to make new rules for the ports in the windows defender firewall menu.

Still the same error.
I would really appreciate any help or ideas from you :)

Peter


问:
Hidden  tags
I'm sure there is a better way to write this code but these were the two ways I was trying to pull a specific sentence from a wiki page on Python. When I got to the correct tag path, the  tag I was wanting to pull was hidden. Does anyone know why it does not come up when I return all the a tags from the website?

Web Scraping Code

Soup Instance

What I'm trying to pull from the wiki page

```<code>    import requests
    from bs4 import BeautifulSoup

    req = requests.get('https://en.wikipedia.org/wiki/Python_(programming_language)')
    soup = BeautifulSoup(req.content, 'html.parser')
    body = soup.find('body')

    # first method to get to my desired a tag
    a = body.select('div div div div p sup a', attrs = {'href': '/wiki/Backward_compatibility','title': 'Backward compatability'})

    # second method to get to my desired a tag
    div1 = soup.body.find('div', attrs = {'id': 'content'})
    div2 = div1.find('div', attrs = {'id': 'bodyContent'})
    div3 = div2.find('div', attrs = {'id': 'mw-content-text'})
    div4 = div3.find('div', attrs = {'class': 'mw-parser-output'})
    sup = div4.find('sup', attrs = {'id': 'cite_ref-33'})
    sup.contents

    # this show all the a tags on the page but I couldn't find the one that has 'href' = /wiki/Backward_compatibility' shown in the third screenshot above
    # a = body.find_all('a')

</code>```

答:
You can get the whole paragraph with one long css selectors statement...

```<code>print(soup.select_one('p:has(a[title="Backward compatibility"][href="/wiki/Backward_compatibility"])').text)
</code>```

Output:

```<code>Guido van Rossum began working on Python in the late 1980s, as a successor to the \ABC programming language, and first released it in 1991 as Python 0.9.0.[33] Python 2.0 was released in 2000 and introduced new features, such as list comprehensions and a cycle-detecting garbage collection system (in addition to reference counting). Python 3.0 was released in 2008 and was a major revision of the language that is not completely backward-compatible. Python 2 was discontinued with version 2.7.18 in 2020.[34]
</code>```

Title: Hidden <a> tags

Body:
I'm sure there is a better way to write this code but these were the two ways I was trying to pull a specific sentence from a wiki page on Python. When I got to the correct tag path, the  tag I was wanting to pull was hidden. Does anyone know why it does not come up when I return all the a tags from the website?

Web Scraping Code

Soup Instance

What I'm trying to pull from the wiki page

    import requests
    from bs4 import BeautifulSoup

    req = requests.get('https://en.wikipedia.org/wiki/Python_(programming_language)')
    soup = BeautifulSoup(req.content, 'html.parser')
    body = soup.find('body')

    # first method to get to my desired a tag
    a = body.select('div div div div p sup a', attrs = {'href': '/wiki/Backward_compatibility','title': 'Backward compatability'})

    # second method to get to my desired a tag
    div1 = soup.body.find('div', attrs = {'id': 'content'})
    div2 = div1.find('div', attrs = {'id': 'bodyContent'})
    div3 = div2.find('div', attrs = {'id': 'mw-content-text'})
    div4 = div3.find('div', attrs = {'class': 'mw-parser-output'})
    sup = div4.find('sup', attrs = {'id': 'cite_ref-33'})
    sup.contents

    # this show all the a tags on the page but I couldn't find the one that has 'href' = /wiki/Backward_compatibility' shown in the third screenshot above
    # a = body.find_all('a')

Body:
You can get the whole paragraph with one long css selectors statement...

print(soup.select_one('p:has(a[title="Backward compatibility"][href="/wiki/Backward_compatibility"])').text)

Output:

Guido van Rossum began working on Python in the late 1980s, as a successor to the \ABC programming language, and first released it in 1991 as Python 0.9.0.[33] Python 2.0 was released in 2000 and introduced new features, such as list comprehensions and a cycle-detecting garbage collection system (in addition to reference counting). Python 3.0 was released in 2008 and was a major revision of the language that is not completely backward-compatible. Python 2 was discontinued with version 2.7.18 in 2020.[34]


问:
How to use read_csv to read .gz file with sep='\' in python3?
I would like to read some gz files by pandas, in which data are split by '', in python 3.

If I use the code:

```<code>pd.read_csv('my file.gz',sep='\')
</code>```

I will get the error "EOL while scanning string literal".

What is the correct way to do this?

答:
The backslash is an escape character. You must escape it
sep='\\'.

Body:
I would like to read some gz files by pandas, in which data are split by '', in python 3.

If I use the code:

pd.read_csv('my file.gz',sep='\')

I will get the error "EOL while scanning string literal".

What is the correct way to do this?


问:
Importing `File Should Exist` Keyword from multiple libraries
Robot Framework provides the File Should Exist Keyword in both OperatingSystem and SSHLibrary. This is true for some other Keywords as well but just taking this as an example.
My question is how do I tell my test case which Keyword I am intending to use?

I believe File Should Exist from OperatingSystem works on the local file system (where the TC is being run) and the File Should Exist from SSHLibrary works on the remote server file system. Or am I wrong here too?

答:
You are right. File Should Exist from OperatingSystem works on the local file system (where the TC is being run) and the File Should Exist from SSHLibrary works on the remote server file system.

But you are connecting to a remote system from local. After connecting to remote if you want to do some operation on local you can by using the OperatingSystem library keywords.

So, when you have keywords with the same name in different libraries use the library name as prefix.

```<code>*** Test Cases ***
Sample Test
    SSHLibrary.File Should Exit    ${args}
    SSHLibrary.Get File  <filename>
    OperatingSystem.File Should Exist    ${args}
</code>```

In the above case even though  you connected to remote system, still you can do operations on local system.

ContentLicense: CC BY-SA 3.0

Body:
You are right. File Should Exist from OperatingSystem works on the local file system (where the TC is being run) and the File Should Exist from SSHLibrary works on the remote server file system.

But you are connecting to a remote system from local. After connecting to remote if you want to do some operation on local you can by using the OperatingSystem library keywords.

So, when you have keywords with the same name in different libraries use the library name as prefix.

*** Test Cases ***
Sample Test
    SSHLibrary.File Should Exit    ${args}
    SSHLibrary.Get File  <filename>
    OperatingSystem.File Should Exist    ${args}

In the above case even though  you connected to remote system, still you can do operations on local system.


问:
Convert IEnumerable to IEnumerable<T> when T isn't known until runtime
How can I convert IEnumerable to IEnumerable<T> when T isn't known until runtime?

I have a method that absolutely needs an IEnumerable<T> where T isn't known until runtime and T must be the actual type and not an ancestor type like object.

I'm betting the reflection API allows for something like this but I don't know exactly how.

Update

I can get a type object like this:

```<code>var first = results.Cast<object>().FirstOrDefault();
if (first != null)
{
    var type = first.GetType();

}
</code>```

Update2

The "method" I was referring to was actually the Setter of the WPF DataGrid's ItemSource property.
The problem I'm having is that if I don't pass it an IEnumerable<T> the rows generated in the Datagrid are all blank, as if it's method of reflecting over the properties of T is not working and it can't generate columns.

Even using this code has this unwanted effect:

```<code>    public CollectionResultWindow(IEnumerable results)
    {
        Contract.Requires(results != null, "results is null.");

        InitializeComponent();
        DataContext = this;

        var first = results.Cast<object>().FirstOrDefault();
        if (first != null)
        {
            Type type = first.GetType();
            var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(type);
            dynamic genericResults = castMethod.Invoke(null, new[] { results });
            Results = genericResults; // Results is a dependency property that DataGrid.ItemSource is bound to.
        }

    }
</code>```

答:
```<code>var elementType = ...
var results = ...
var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(elementType);
var genericResults = castMethod.Invoke(null, new[] { results });
</code>```

The genericResults variable refers to an object of type IEnumerable<T> (where T is the type represented by the elementType variable). But keep in mind that statically, genericResults is still of type object; there is no way to tell the compiler that it is an IEnumerable<T>, since T isn't known statically.

Body:
How can I convert IEnumerable to IEnumerable<T> when T isn't known until runtime?

I have a method that absolutely needs an IEnumerable<T> where T isn't known until runtime and T must be the actual type and not an ancestor type like object.

I'm betting the reflection API allows for something like this but I don't know exactly how.

Update

I can get a type object like this:

var first = results.Cast<object>().FirstOrDefault();
if (first != null)
{
    var type = first.GetType();

}

Update2

The "method" I was referring to was actually the Setter of the WPF DataGrid's ItemSource property.
The problem I'm having is that if I don't pass it an IEnumerable<T> the rows generated in the Datagrid are all blank, as if it's method of reflecting over the properties of T is not working and it can't generate columns.

Even using this code has this unwanted effect:

    public CollectionResultWindow(IEnumerable results)
    {
        Contract.Requires(results != null, "results is null.");

        InitializeComponent();
        DataContext = this;

        var first = results.Cast<object>().FirstOrDefault();
        if (first != null)
        {
            Type type = first.GetType();
            var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(type);
            dynamic genericResults = castMethod.Invoke(null, new[] { results });
            Results = genericResults; // Results is a dependency property that DataGrid.ItemSource is bound to.
        }

    }

Body:
var elementType = ...
var results = ...
var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(elementType);
var genericResults = castMethod.Invoke(null, new[] { results });

The genericResults variable refers to an object of type IEnumerable<T> (where T is the type represented by the elementType variable). But keep in mind that statically, genericResults is still of type object; there is no way to tell the compiler that it is an IEnumerable<T>, since T isn't known statically.


问:
how to use python and c++ at the same time in vscode
I change my IDE from MSVS to VS Code because I want to use python with c++ for codeforce.
However, there is a problem that I can't run my python file even though I add python configuration in 'launch.json'.

Below picture is my workspace folder.

```<code>  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Current File",
      "type": "python",
      "request": "launch",
      "program": "${file}",
      "console": "integratedTerminal"
    },
    {
      "name": "g++.exe - 활성 파일 빌드 및 디버그",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${fileDirname}",
      "environment": [],
      "externalConsole": true,
      "MIMode": "gdb",
      "miDebuggerPath": "D:\\mingw64\\bin\\gdb.exe",
      "setupCommands": [
        {
          "description": "gdb에 자동 서식 지정 사용",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        },
        {
          "description": "디스어셈블리 버전을 Intel(으)로 설정",
          "text": "-gdb-set disassembly-flavor intel",
          "ignoreFailures": true
        }
      ],
      "preLaunchTask": "C/C++: g++.exe 활성 파일 빌드"
    }
  ]

 {
  "tasks": [
    {
      "type": "cppbuild",
      "label": "C/C++: g++.exe 활성 파일 빌드",
      "command": "D:\\mingw64\\bin\\g++.exe",
      "args": [
        "-fdiagnostics-color=always",
        "-g",
        "${file}",
        "-o",
        "${fileDirname}\\${fileBasenameNoExtension}.exe"
      ],
      "options": {
        "cwd": "${fileDirname}"
      },
      "problemMatcher": [
        "$gcc"
      ],
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "detail": "디버거에서 생성된 작업입니다."
    }
  ],
  "version": "2.0.0"
}
</code>```

Error log says, "active file is not c or c++ file, so cannot build it"

How can I run python files in this case?

答:
If i recall correctly, there a little run button at the top right of the python file you are opening pressing it should run your program

It not the best solution, other can think of better way but use this for now until other help you.

Body:
I change my IDE from MSVS to VS Code because I want to use python with c++ for codeforce.
However, there is a problem that I can't run my python file even though I add python configuration in 'launch.json'.

Below picture is my workspace folder.

  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Current File",
      "type": "python",
      "request": "launch",
      "program": "${file}",
      "console": "integratedTerminal"
    },
    {
      "name": "g++.exe - 활성 파일 빌드 및 디버그",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${fileDirname}",
      "environment": [],
      "externalConsole": true,
      "MIMode": "gdb",
      "miDebuggerPath": "D:\\mingw64\\bin\\gdb.exe",
      "setupCommands": [
        {
          "description": "gdb에 자동 서식 지정 사용",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        },
        {
          "description": "디스어셈블리 버전을 Intel(으)로 설정",
          "text": "-gdb-set disassembly-flavor intel",
          "ignoreFailures": true
        }
      ],
      "preLaunchTask": "C/C++: g++.exe 활성 파일 빌드"
    }
  ]

 {
  "tasks": [
    {
      "type": "cppbuild",
      "label": "C/C++: g++.exe 활성 파일 빌드",
      "command": "D:\\mingw64\\bin\\g++.exe",
      "args": [
        "-fdiagnostics-color=always",
        "-g",
        "${file}",
        "-o",
        "${fileDirname}\\${fileBasenameNoExtension}.exe"
      ],
      "options": {
        "cwd": "${fileDirname}"
      },
      "problemMatcher": [
        "$gcc"
      ],
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "detail": "디버거에서 생성된 작업입니다."
    }
  ],
  "version": "2.0.0"
}

Error log says, "active file is not c or c++ file, so cannot build it"

How can I run python files in this case?


问:
Remove duplicates with the same NAME and keep the one with a higher USER RATING COUNT. (python)
I have sorted a list of tuples by name, each tuple has the elements id, name, average_rating, rating_count, developers, and size.

I'm now trying to remove the duplicate name and only keep the one with the higher rating_count.

A snip of my sorted list of tuples

```<code>[(320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 16, 'Yoshikazu Kakinoki', 3940352),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]
</code>```

I would like an output of

```<code>[(320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]
</code>```

only keeping '5x5 Shogi (MiniShogi) K55' with the highest rating_count which is 900.

My take

```<code>    for i in range(len(list_of_games)):
        if list_of_games[i][1] == list_of_games[i+1][1] and \
                list_of_games[i][3] > list_of_games[i+1][3]:
            list_of_games.remove(list_of_games[i+1])
        elif list_of_games[i][1] == list_of_games[i+1][1] and \
                list_of_games[i][3] < list_of_games[i+1][3]:
            list_of_games.remove(list_of_games[i])
</code>```

But I got an out of range error

```<code>line 222, in main
    if list_of_games[i][1] == list_of_games[i+1][1] and \
IndexError: list index out of range
</code>```

May I know how do I solve this?

答:
I might tackle this by resorting the list by name and rating_count then adding the items to a dictionary with a key of name or id. Then you can take the values of that new dictionary.

data_in = [
    (320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
    (299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 16, 'Yoshikazu Kakinoki', 3940352),
    (299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]

data_out = {x[1]: x for x in sorted(data_in, key=lambda x : (x[1], x[3]))}.values()
print(list(data_out))
```
<p>gives you:</p>
```[
    (320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
    (299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]
```

If you don't care about preserving the ordering by name, you could also just sort by rating_count rather than name and rating count.

Body:
I have sorted a list of tuples by name, each tuple has the elements id, name, average_rating, rating_count, developers, and size.

I'm now trying to remove the duplicate name and only keep the one with the higher rating_count.

A snip of my sorted list of tuples

[(320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 16, 'Yoshikazu Kakinoki', 3940352),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]

I would like an output of

[(320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
(299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]

only keeping '5x5 Shogi (MiniShogi) K55' with the highest rating_count which is 900.

My take

    for i in range(len(list_of_games)):
        if list_of_games[i][1] == list_of_games[i+1][1] and \
                list_of_games[i][3] > list_of_games[i+1][3]:
            list_of_games.remove(list_of_games[i+1])
        elif list_of_games[i][1] == list_of_games[i+1][1] and \
                list_of_games[i][3] < list_of_games[i+1][3]:
            list_of_games.remove(list_of_games[i])

But I got an out of range error

line 222, in main
    if list_of_games[i][1] == list_of_games[i+1][1] and \
IndexError: list index out of range

May I know how do I solve this?

Body:
I might tackle this by resorting the list by name and rating_count then adding the items to a dictionary with a key of name or id. Then you can take the values of that new dictionary.

data_in = [
    (320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
    (299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 16, 'Yoshikazu Kakinoki', 3940352),
    (299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]

data_out = {x[1]: x for x in sorted(data_in, key=lambda x : (x[1], x[3]))}.values()
print(list(data_out))

gives you:

[
    (320469536, '4_IN_1_ROW_Lite', 2.5, 3593, 'AOBO Co.,Ltd', 7750656),
    (299139129, '5x5 Shogi (MiniShogi) K55', 4.0, 900, 'Yoshikazu Kakinoki', 3940352)
]

If you don't care about preserving the ordering by name, you could also just sort by rating_count rather than name and rating count.


问:
How can I flatten a multilevel nested list to a specified depth?
I am trying to flatten a list that has 3 levels into a list that has 2 levels.... In other words, I have a nested list as such :

```<code>ls <- list(
  a = list(
    a1 = list(
       a11 = list(data),
    a2 = list(
       a21 = list(data2)),
  b = list(
    b1 = list(
       b11 = list(data3),
    b2 = list(
       b21 = list(data4)))

</code>```

I would like to flatten this so that it looks like this:

```<code>flat_ls <- list(
  a_a1 = list(
     a11 = list(data),
  a_a2 = list(
     a21 = list(data2)),
  b_b1 = list(
     b11 = list(data3),
  b_b2 = list(
     b21 = list(data4)))

</code>```

I know there function flatten() or lapply(rapply(y, enquote, how="unlist"), eval) can make a multilevel list into a flat list. However, I want to keep the last layer of the list, without flattening that. How can I accomplish this?

答:
purrr::flatten() actually does exactly what you're looking for. per (purrr) the documentation, flatten() and friends "only ever remove a single layer of hierarchy."

```<code>library(purrr)

# placeholder values for `data` etc
data <- as.symbol("data")
data2 <- as.symbol("data2")
data3 <- as.symbol("data3")
data4 <- as.symbol("data4")

# added a few missing parens; raised error in original
ls <- list(
  a = list(
    a1 = list(
      a11 = list(data)
    ),
    a2 = list(
      a21 = list(data2)
    )
  ),
  b = list(
    b1 = list(
      b11 = list(data3)
    ),
    b2 = list(
      b21 = list(data4)
    )
  )
)

# (added step in response to comment):
# combine top two levels of names
ls_renamed <- imap(ls, ~ set_names(.x, paste(.y, names(.x), sep = "_")))

# flatten top level
flat_ls <- flatten(ls_renamed)

dput(flat_ls)
# list(
#   a_a1 = list(
#     a11 = list(data)
#   ),
#   a_a2 = list(
#     a21 = list(data2)
#   ),
#   b_b1 = list(
#     b11 = list(data3)
#   ),
#   b_b2 = list(
#     b21 = list(data4)
#   )
# )
</code>```

Body:
I am trying to flatten a list that has 3 levels into a list that has 2 levels.... In other words, I have a nested list as such :

ls <- list(
  a = list(
    a1 = list(
       a11 = list(data),
    a2 = list(
       a21 = list(data2)),
  b = list(
    b1 = list(
       b11 = list(data3),
    b2 = list(
       b21 = list(data4)))

I would like to flatten this so that it looks like this:

flat_ls <- list(
  a_a1 = list(
     a11 = list(data),
  a_a2 = list(
     a21 = list(data2)),
  b_b1 = list(
     b11 = list(data3),
  b_b2 = list(
     b21 = list(data4)))

I know there function flatten() or lapply(rapply(y, enquote, how="unlist"), eval) can make a multilevel list into a flat list. However, I want to keep the last layer of the list, without flattening that. How can I accomplish this?

Body:
purrr::flatten() actually does exactly what you're looking for. per (purrr) the documentation, flatten() and friends "only ever remove a single layer of hierarchy."

library(purrr)

# placeholder values for `data` etc
data <- as.symbol("data")
data2 <- as.symbol("data2")
data3 <- as.symbol("data3")
data4 <- as.symbol("data4")

# added a few missing parens; raised error in original
ls <- list(
  a = list(
    a1 = list(
      a11 = list(data)
    ),
    a2 = list(
      a21 = list(data2)
    )
  ),
  b = list(
    b1 = list(
      b11 = list(data3)
    ),
    b2 = list(
      b21 = list(data4)
    )
  )
)

# (added step in response to comment):
# combine top two levels of names
ls_renamed <- imap(ls, ~ set_names(.x, paste(.y, names(.x), sep = "_")))

# flatten top level
flat_ls <- flatten(ls_renamed)

dput(flat_ls)
# list(
#   a_a1 = list(
#     a11 = list(data)
#   ),
#   a_a2 = list(
#     a21 = list(data2)
#   ),
#   b_b1 = list(
#     b11 = list(data3)
#   ),
#   b_b2 = list(
#     b21 = list(data4)
#   )
# )


问:
Improving a List Comprehension
The list comprehension below achieves the desired result/output:

Each tuple in the list is indexed sequentially

The names are grouped together by suit

The names are in a consistent order

Code (deck of cards toy example):

```<code>Suits = ["Hearts"]*3 +["Diamonds"]*3
Names = ["Two","Ten","King"]

z = [(i,Names[(i-1)%3],Suits[((i-1)%6)]) for i in range(1,7)]
</code>```

Output z:

```<code>[(1, 'Two', 'Hearts'),
 (2, 'Ten', 'Hearts'),
 (3, 'King', 'Hearts'),
 (4, 'Two', 'Diamonds'),
 (5, 'Ten', 'Diamonds'),
 (6, 'King', 'Diamonds')]
</code>```

It works because the original Suits list was changed from ["Hearts","Diamonds"] to["Hearts"]*3 +["Diamonds"]*3.

This feels contrived; although it works, I'm looking for a better solution.

答:
you could use a two level nested comprehension with enumerate to get numbering:</p>
```<code>Suits = ["Hearts","Diamonds"]
Names = ["Two","Ten","King"]

r = [(j+i,n,s) for j,s in enumerate(Suits)
               for i,n in enumerate(Names,j*len(Suits)+1) ]

print(*r,sep="\n")
(1, 'Two', 'Hearts')
(2, 'Ten', 'Hearts')
(3, 'King', 'Hearts')
(4, 'Two', 'Diamonds')
(5, 'Ten', 'Diamonds')
(6, 'King', 'Diamonds')
</code>```

Title: Improving a List Comprehension

Body:
The list comprehension below achieves the desired result/output:

Each tuple in the list is indexed sequentially

The names are grouped together by suit

The names are in a consistent order

Code (deck of cards toy example):

Suits = ["Hearts"]*3 +["Diamonds"]*3
Names = ["Two","Ten","King"]

z = [(i,Names[(i-1)%3],Suits[((i-1)%6)]) for i in range(1,7)]

Output z:

[(1, 'Two', 'Hearts'),
 (2, 'Ten', 'Hearts'),
 (3, 'King', 'Hearts'),
 (4, 'Two', 'Diamonds'),
 (5, 'Ten', 'Diamonds'),
 (6, 'King', 'Diamonds')]

It works because the original Suits list was changed from ["Hearts","Diamonds"] to["Hearts"]*3 +["Diamonds"]*3.

This feels contrived; although it works, I'm looking for a better solution.

Body:
you could use a two level nested comprehension with enumerate to get numbering:

Suits = ["Hearts","Diamonds"]
Names = ["Two","Ten","King"]

r = [(j+i,n,s) for j,s in enumerate(Suits)
               for i,n in enumerate(Names,j*len(Suits)+1) ]

print(*r,sep="\n")
(1, 'Two', 'Hearts')
(2, 'Ten', 'Hearts')
(3, 'King', 'Hearts')
(4, 'Two', 'Diamonds')
(5, 'Ten', 'Diamonds')
(6, 'King', 'Diamonds')


问:
Axios failing to downloand an image from s3 due to CORS
When making Axios GET call to retrieve an image from s3 bucket it creates a preflight check using OPTIONS method. Options method response includes the Access-Controll-Allow-Origin: * header with a wild card but the subsequent GET call fails to retrieve the image.

Browser console out put:
Access to XMLHttpRequest at 'https://example.com' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Response headers from the OPTIONS call:

Response headers from the subsequent GET call:

Axios config for the GET call:

答: Go to bucket permission and configure cors [https://docs.aws.amazon.com/AmazonS3/latest/userguide/ManageCorsUsing.html][s3 cors documentation]


问:
Count the semiprime numbers in the given range [a..b]
I am solving Codility problem CountSemiprimes: Count the semiprime numbers in the given range [a..b].

Task description

A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.

A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. The first few semiprimes are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26.

You are given two non-empty arrays P and Q, each consisting of M integers. These arrays represent queries about the number of semiprimes within specified ranges.

Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 ≤ P[K] ≤ Q[K] ≤ N.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..50,000];

M is an integer within the range [1..30,000];

each element of arrays P, Q is an integer within the range [1..N];
P[i] ≤ Q[i].

My solution

My current score is 66% and problem is preformance for large data set:

large random, length = ~30,000

all max ranges

Test says, that it should take about 2sec, but my solution takes over 7sec.

This is my current solution

```<code>class Solution {
    private static List<Integer> getPrimes(int max) {
        List<Integer> primes = new ArrayList<>(max / 2);

        for (int i = 0; i < max; i++)
            if (isPrime(i))
                primes.add(i);

        return primes;
    }

    private static boolean isPrime(int val) {
        if (val <= 1)
            return false;
        if (val <= 3)
            return true;

        for (int i = 2, sqrt = (int)Math.sqrt(val); i <= sqrt; i++)
            if (val % i == 0)
                return false;

        return true;
    }

    private static boolean[] getSemiPrimes(int N) {
        List<Integer> primes = getPrimes(N);
        boolean[] semiPrimes = new boolean[N + 1];

        for (int i = 0; i < primes.size(); i++) {
            if (primes.get(i) > N)
                break;

            for (int j = i; j < primes.size(); j++) {
                if (primes.get(j) > N || N / primes.get(i) < primes.get(j))
                    break;

                int semiPrime = primes.get(i) * primes.get(j);

                if (semiPrime <= N)
                    semiPrimes[semiPrime] = true;
            }
        }

        return semiPrimes;
    }

    public static int[] solution(int N, int[] P, int[] Q) {
        boolean[] semiPrimes = getSemiPrimes(N);
        int[] res = new int[P.length];

        for (int i = 0; i < res.length; i++)
            for (int j = P[i]; j <= Q[i]; j++)
                if (semiPrimes[j])
                    res[i]++;

        return res;
    }
}
</code>```

Any ideas about improving performance? My last one was to remove Set for holding semi-primes with array. It helped me to solve couple of performance tests.

答:
```<code>/**
     * https://app.codility.com/demo/results/trainingPBRVXK-28Q/
     * time complexity: O(N * log(log N) + M
     * space complexity: O(2N + N)
     */
public class CountSemiPrime {

    /**
     * 2D array for sieving numbers 1..N
     * 1 - prime, 2 - semiprime, 3 - composite
     */
    public int[][] sieve(int N) {
        int[][] sieve = new int[N+1][1];
        for (int i=1; i<=N; i++) {
            sieve[i][0] = 1; // make prime default
        }
        for (int i=2; i<= N; i++) {
            if (sieve[i][0] == 1) { // if this num is prime, tag its multiples as semi-prime
                int next_number = i + i;
                while (next_number <= N) {
                    sieve[next_number][0] = 2;
                    next_number += i;
                }
            }
            // if this num is semi-prime, tag its multiples as composite
            else if (sieve[i][0] == 2) {
                int next_number = i + i;
                while (next_number <= N) {
                    sieve[next_number][0] = 3;
                    next_number += i;
                }
            }
        }
        return sieve;
    }

    public int[] solution(int N, int[] P, int[] Q) {
        // first, we need to establish prime and semi-prime numbers from 1 to N, in a sieve
        int[][] sieve = sieve(N);
        int[] prefix_sum_of_sieve = new int[sieve.length];

        for (int i=1; i<sieve.length; i++) {
            if (sieve[i][0]==2) {
                prefix_sum_of_sieve[i] = prefix_sum_of_sieve[i-1] + 1;
            }
            else {
                prefix_sum_of_sieve[i] = prefix_sum_of_sieve[i-1];
            }
        }

        int[] results = new int[P.length];
        // we count the semiprime of N from P and Q, for each P & Q from the prefix sum
        for (int i=0; i < P.length; i++) {
            results[i] = prefix_sum_of_sieve[Q[i]] - prefix_sum_of_sieve[P[i]-1];
        }

        return results;
    }
}
</code>```

Hope the explanation / comments are easy to understand.

Body:
I am solving Codility problem CountSemiprimes: Count the semiprime numbers in the given range [a..b].

Task description

A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.

A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. The first few semiprimes are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26.

You are given two non-empty arrays P and Q, each consisting of M integers. These arrays represent queries about the number of semiprimes within specified ranges.

Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 ≤ P[K] ≤ Q[K] ≤ N.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..50,000];

M is an integer within the range [1..30,000];

each element of arrays P, Q is an integer within the range [1..N];
P[i] ≤ Q[i].

My solution

My current score is 66% and problem is preformance for large data set:

large random, length = ~30,000

all max ranges

Test says, that it should take about 2sec, but my solution takes over 7sec.

This is my current solution

class Solution {
    private static List<Integer> getPrimes(int max) {
        List<Integer> primes = new ArrayList<>(max / 2);

        for (int i = 0; i < max; i++)
            if (isPrime(i))
                primes.add(i);

        return primes;
    }

    private static boolean isPrime(int val) {
        if (val <= 1)
            return false;
        if (val <= 3)
            return true;

        for (int i = 2, sqrt = (int)Math.sqrt(val); i <= sqrt; i++)
            if (val % i == 0)
                return false;

        return true;
    }

    private static boolean[] getSemiPrimes(int N) {
        List<Integer> primes = getPrimes(N);
        boolean[] semiPrimes = new boolean[N + 1];

        for (int i = 0; i < primes.size(); i++) {
            if (primes.get(i) > N)
                break;

            for (int j = i; j < primes.size(); j++) {
                if (primes.get(j) > N || N / primes.get(i) < primes.get(j))
                    break;

                int semiPrime = primes.get(i) * primes.get(j);

                if (semiPrime <= N)
                    semiPrimes[semiPrime] = true;
            }
        }

        return semiPrimes;
    }

    public static int[] solution(int N, int[] P, int[] Q) {
        boolean[] semiPrimes = getSemiPrimes(N);
        int[] res = new int[P.length];

        for (int i = 0; i < res.length; i++)
            for (int j = P[i]; j <= Q[i]; j++)
                if (semiPrimes[j])
                    res[i]++;

        return res;
    }
}

Any ideas about improving performance? My last one was to remove Set for holding semi-primes with array. It helped me to solve couple of performance tests.

Body:
/**
     * https://app.codility.com/demo/results/trainingPBRVXK-28Q/
     * time complexity: O(N * log(log N) + M
     * space complexity: O(2N + N)
     */
public class CountSemiPrime {

    /**
     * 2D array for sieving numbers 1..N
     * 1 - prime, 2 - semiprime, 3 - composite
     */
    public int[][] sieve(int N) {
        int[][] sieve = new int[N+1][1];
        for (int i=1; i<=N; i++) {
            sieve[i][0] = 1; // make prime default
        }
        for (int i=2; i<= N; i++) {
            if (sieve[i][0] == 1) { // if this num is prime, tag its multiples as semi-prime
                int next_number = i + i;
                while (next_number <= N) {
                    sieve[next_number][0] = 2;
                    next_number += i;
                }
            }
            // if this num is semi-prime, tag its multiples as composite
            else if (sieve[i][0] == 2) {
                int next_number = i + i;
                while (next_number <= N) {
                    sieve[next_number][0] = 3;
                    next_number += i;
                }
            }
        }
        return sieve;
    }

    public int[] solution(int N, int[] P, int[] Q) {
        // first, we need to establish prime and semi-prime numbers from 1 to N, in a sieve
        int[][] sieve = sieve(N);
        int[] prefix_sum_of_sieve = new int[sieve.length];

        for (int i=1; i<sieve.length; i++) {
            if (sieve[i][0]==2) {
                prefix_sum_of_sieve[i] = prefix_sum_of_sieve[i-1] + 1;
            }
            else {
                prefix_sum_of_sieve[i] = prefix_sum_of_sieve[i-1];
            }
        }

        int[] results = new int[P.length];
        // we count the semiprime of N from P and Q, for each P & Q from the prefix sum
        for (int i=0; i < P.length; i++) {
            results[i] = prefix_sum_of_sieve[Q[i]] - prefix_sum_of_sieve[P[i]-1];
        }

        return results;
    }
}

Hope the explanation / comments are easy to understand.


问:
How to run the function when the specified url is entered reactjs
I have two urls in my project. the first one: http://localhost:3000/?/#chain=Matic, and the other one: http://localhost:3000/?/#chain=Bsc. I want the function I created to run when entered with this url. How can I do that?

For example, when this http://localhost:3000/?/#chain=Matic address is entered, I want the relevant function to be loaded automatically after the page is loaded. Is there a way to do this?

答:
You'd want to amend the URL so that we're pulling from the get parameters. Then we can look for the variable when the page first loads and run logic depending on what the value is:

Here's a complete example: https://codesandbox.io/s/resolve-url-parameter-2odpc


问:
reference to partial object in typescript?
I have an object and it's typed

```<code>interface formDataType {
  tesla: {
    made: string
  },
  ford: {
    made: string
  }
}
const formData: formDataType = {
    "tesla": {
      "made":"2021"
    },
    "ford": {
      "made": "2022"
    }
  };
</code>```

then I've a function where its argument is one of [string]:{made: string}, how can I use back formDataType? is there something like objectOf formDataType?

demo https://codesandbox.io/s/react-typescript-forked-cwv9p

答:
You can create a type to use in your FormDataType, then reuse that type in your function:

TS Playground

type VehicleDetails = { made: string };

type FormDataType = {
  ford: VehicleDetails;
  tesla: VehicleDetails;
};

// The following is the same type, written using the Record utility:
// type FormDataType = Record<'ford' | 'tesla', VehicleDetails>;

const formData: FormDataType = {
  tesla: {made: '2021'},
  ford: {made: '2022'},
};

function doSomethingWithVehicleDetails (details: VehicleDetails) {
  // console.log(details);
}

```
<hr />
<p>Update in response to your comment:</p>
<p>You can also derive a union of all the types of the values of the keys in your <code>FormData</code> type (and if they're all the same type, the union will effectively be that one type):</p>
<p>TS Playground</p>
<pre class="lang-ts prettyprint-override"><code>type FormDataType = {
  ford: { made: string };
  tesla: { made: string };
};

type VehicleDetails = FormDataType[keyof FormDataType];

function doSomethingWithVehicleDetails (details: VehicleDetails) {
  // console.log(details);
}

</code>```

Body:
I have an object and it's typed

interface formDataType {
  tesla: {
    made: string
  },
  ford: {
    made: string
  }
}
const formData: formDataType = {
    "tesla": {
      "made":"2021"
    },
    "ford": {
      "made": "2022"
    }
  };

then I've a function where its argument is one of [string]:{made: string}, how can I use back formDataType? is there something like objectOf formDataType?

demo https://codesandbox.io/s/react-typescript-forked-cwv9p

Body:
You can create a type to use in your FormDataType, then reuse that type in your function:

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/C4TwDgpgBAahAWBLAxgGwgEQsAho1AzlALxQDeUAtjgCYQBcUBwATogHYDmUAvgNwAoAaEhQAYgHsWlDDlwAVcNFJkBUKADMpNRnCRpM2PIUHrgEAqhy6EKdFlz4Cg-kID0bqPPjQtqVBIA7hzciETAPkw4lNAiEAA0UIFswObsUACuBCFQEdAAShDI2pnA+Iig9AIeuUriUjJyOIqipIXFLDQAPADkWp09UAA+UD3mljg9iXp2ho6EAHyCAsXszJoNsriMktJbzXUqarkWVoxk1HSMPQBMAAw3AIw9PPHH-Trklwyj9zc3LzergEGgy7GQZQk6RoEgAyhIYhEQgB1CrwGYGBzGIgACjo8wINn09iMTgAlORjjVVgQJOgAHQBTh40mEMkuARAA" rel="nofollow noreferrer">TS Playground

type VehicleDetails = { made: string };

type FormDataType = {
  ford: VehicleDetails;
  tesla: VehicleDetails;
};

// The following is the same type, written using the Record utility:
// type FormDataType = Record<'ford' | 'tesla', VehicleDetails>;

const formData: FormDataType = {
  tesla: {made: '2021'},
  ford: {made: '2022'},
};

function doSomethingWithVehicleDetails (details: VehicleDetails) {
  // console.log(details);
}

Update in response to your comment:

You can also derive a union of all the types of the values of the keys in your FormData type (and if they're all the same type, the union will effectively be that one type):

TS Playground

type FormDataType = {
  ford: { made: string };
  tesla: { made: string };
};

type VehicleDetails = FormDataType[keyof FormDataType];

function doSomethingWithVehicleDetails (details: VehicleDetails) {
  // console.log(details);
}


答:
You may need to add your SSH key in your gitlab preferences.

Click on your head on the top right, then Preferences and SSH Keys.

If needed, more info on gitlab documentation.

Title: Problem with Git: "ssh: connect to host gitlab port 22: connection refused"

Body:
i am writing my bachelors thesis at a company and got access to gitlab from the admin, but I am new to Git. I created a new project for my thesis. I already had a folder with some stuff on my computer. I used the following commands in the git bash (as recommended by gitlab):

git init
git remote add origin git@gitlab:USER/TITLE.git
git add [stuff]
git commit
git push -u origin master

Committing was successfull, but the last command created the error

"ssh: connect to host gitlab port 22: Connection refused
  fatal: Could not read from remote repository.
  Please make sure you have the correct access rights
  and the repository exists."

I tried to switch to port 443, because apparently, that is a thing.

ssh -T -p 443 git@altssh.gitlab.com

That got me:

"The authenticity of host '[altssh.gitlab.com]:443 ([35.190.168.187]:443)' can't be established.

  ECDSA key fingerprint is [...].

  Are you sure you want to continue connecting (yes/no/[fingerprint])?"

After typing yes:

"Warning: Permanently added '[altssh.gitlab.com]:443,[35.190.168.187]:443' (ECDSA) to the list of known hosts.

  git@altssh.gitlab.com: Permission denied (publickey)."

When going back to port 22, the connection timed out.
The error after the push command is still the same.

According to canyouseeme.org, the ports 22 and 443 are not open.

I also tried to make new rules for the ports in the windows defender firewall menu.

Still the same error.
I would really appreciate any help or ideas from you :)

Peter


问:
factorplot main title overlaps sub titles in seaborn
I have produced the below chart. As you can see the main title is overlapping the subtitles of the graphs. I tried different methods but none of them seems to be working. I have also attached my code.

```<code>def save_multi_columns_categorical_charts(df, chart, columns, y, hue, title, single_statistic=False,
                                          single_statistic_name=None, kind='point', col='Message Size (Bytes)'):
    filename = chart + ".png"
    print("Creating chart: " + title + ", File name: " + filename)
    fig, ax = plt.subplots()
    all_columns = [col,'Back-end Service Delay (ms)', 'Concurrent Users','Scenario Name']
    all_columns.extend(columns)
    df_results = df[all_columns]

    df_results['new_var'] = df_results[col] + ' - ' + df_results['Scenario Name']

    g = sns.factorplot(x="Concurrent Users", y='Throughput (Requests/sec)',
                       hue='new_var', col='Back-end Service Delay (ms)',
                       data=df_results, kind=kind,
                       size=5, aspect=1, col_wrap=2, legend=False)

    plt.subplots_adjust(top=10, left=0.1)
    g.fig.suptitle(title,y=1.08)  # can also get the figure from plt.gcf()
    plt.legend(loc=2, frameon=True, title="Response Time Summary")

    plt.savefig(filename)
    plt.clf()
    plt.cla()
    plt.close(fig)
</code>```

答:
Try giving the offset of the title from the top of the axes (in points), in order to add some gap between the main title and the underlying graphs as:

plt.title('Title of the plot', pad=100)

Keep increasing the pad value to adjust the gap as per your need.

Body:
I have produced the below chart. As you can see the main title is overlapping the subtitles of the graphs. I tried different methods but none of them seems to be working. I have also attached my code.

def save_multi_columns_categorical_charts(df, chart, columns, y, hue, title, single_statistic=False,
                                          single_statistic_name=None, kind='point', col='Message Size (Bytes)'):
    filename = chart + ".png"
    print("Creating chart: " + title + ", File name: " + filename)
    fig, ax = plt.subplots()
    all_columns = [col,'Back-end Service Delay (ms)', 'Concurrent Users','Scenario Name']
    all_columns.extend(columns)
    df_results = df[all_columns]

    df_results['new_var'] = df_results[col] + ' - ' + df_results['Scenario Name']

    g = sns.factorplot(x="Concurrent Users", y='Throughput (Requests/sec)',
                       hue='new_var', col='Back-end Service Delay (ms)',
                       data=df_results, kind=kind,
                       size=5, aspect=1, col_wrap=2, legend=False)

    plt.subplots_adjust(top=10, left=0.1)
    g.fig.suptitle(title,y=1.08)  # can also get the figure from plt.gcf()
    plt.legend(loc=2, frameon=True, title="Response Time Summary")

    plt.savefig(filename)
    plt.clf()
    plt.cla()
    plt.close(fig)


问:
Python BS4 append extraSoup after a TEXT
I have a file and I need to modify it with Python. there is a text inside of the file which is not included in any tag. it is like this:

```<code>===TEXT===
</code>```

I need to append data after this text. I have a python script with BS4:

```<code>for index, row in df.iterrows():
        with open("template.html", 'r') as inf:
            html = inf.read()
            soup = bs4.BeautifulSoup(html, features="html.parser")

            extraSoup = bs4.BeautifulSoup("""
            {{transclude name="link" }}
            """, "html.parser")

            for container in soup.find(text="===TEXT==="):
                container.append(extraSoup)
        prettyHTML = soup.prettify()
        with open("template.html", 'w') as outf:
            outf.write(str(prettyHTML))
</code>```

I am trying to find the text and append the extraSoup. But I get error

```<code>AttributeError: 'NoneType' object has no attribute
</code>```

Is it even possible to do this with BS4? cause I think BS4 only work with tags? is there any way to achieve this?

答:
I think BS4 only work with tags?

It's not clear where you got this idea. BS4, like any spec-compliant HTML parser, will parse otherwise unbound text into a text node. Use find_all() and check its contents for your templating constant (===TEST===) before using insert_after to insert the content you're after into the DOM.

Test HTML:

```<code><span id="test1">
 test
</span>
===TEXT===
<span id="test2">
 test
</span>
</code>```

Updated Python script:

```<code>import bs4
with open("template.html", 'r') as inf:
  html = inf.read()
  soup = bs4.BeautifulSoup(html, features="html.parser")

  for container in soup.findAll(text=True):
    print(container.text)
    if container.text.strip() == "===TEXT===":
      container.insert_after('{{transclude name="link" }}')
  prettyHTML = soup.prettify()
with open("template2.html", 'w') as outf:
  outf.write(str(prettyHTML))
</code>```

Output:

```<code><span id="test1">
 test
</span>
===TEXT===
{{transclude name="link" }}
<span id="test2">
 test
</span>
</code>```

Repl.it

Body:
I have a file and I need to modify it with Python. there is a text inside of the file which is not included in any tag. it is like this:

===TEXT===

I need to append data after this text. I have a python script with BS4:

for index, row in df.iterrows():
        with open("template.html", 'r') as inf:
            html = inf.read()
            soup = bs4.BeautifulSoup(html, features="html.parser")

            extraSoup = bs4.BeautifulSoup("""
            {{transclude name="link" }}
            """, "html.parser")

            for container in soup.find(text="===TEXT==="):
                container.append(extraSoup)
        prettyHTML = soup.prettify()
        with open("template.html", 'w') as outf:
            outf.write(str(prettyHTML))

I am trying to find the text and append the extraSoup. But I get error

AttributeError: 'NoneType' object has no attribute

Is it even possible to do this with BS4? cause I think BS4 only work with tags? is there any way to achieve this?

Body:
I think BS4 only work with tags?

It's not clear where you got this idea. BS4, like any spec-compliant HTML parser, will parse otherwise unbound text into a text node. Use find_all() and check its contents for your templating constant (===TEST===) before using insert_after to insert the content you're after into the DOM.

Test HTML:

<span id="test1">
 test
</span>
===TEXT===
<span id="test2">
 test
</span>

Updated Python script:

import bs4
with open("template.html", 'r') as inf:
  html = inf.read()
  soup = bs4.BeautifulSoup(html, features="html.parser")

  for container in soup.findAll(text=True):
    print(container.text)
    if container.text.strip() == "===TEXT===":
      container.insert_after('{{transclude name="link" }}')
  prettyHTML = soup.prettify()
with open("template2.html", 'w') as outf:
  outf.write(str(prettyHTML))

Output:

<span id="test1">
 test
</span>
===TEXT===
{{transclude name="link" }}
<span id="test2">
 test
</span>

Repl.it


问:
Unable to validate the following destination configurations (S3 to SQS)
I am trying to set up a workflow with serverless that creates a new S3 bucket, a new SQS queue and when an object is created in the S3 bucket, puts a messages on the queue and spins up a lambda once there are enough messages on the queue. I have the following in my resources block:

```<code>resources:
  Resources:
    AnalyticsQueue:
      Type: "AWS::SQS::Queue"
      Properties:
        QueueName: "my-queue"
    S3EventQueuePolicy:
      Type: AWS::SQS::QueuePolicy
      DependsOn: AnalyticsQueue
      Properties:
        PolicyDocument:
          Id: SQSPolicy
          Statement:
            - Effect: Allow
              Action: sqs:SendMessage:*
              Resource: !Ref AnalyticsQueue
        Queues:
          - !GetAtt AnalyticsQueue.Arn
    AnalyticsBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: "my-bucket"
        NotificationConfiguration:
          QueueConfigurations:
            - Event: s3:ObjectCreated:*
              Queue: !GetAtt AnalyticsQueue.Arn
</code>```

When I try to deploy this I receive the following error:

An error occurred: AnalyticsBucket - Unable to validate the following destination configurations (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument; Request ID: E2A1F8BD6BEE6EF4;).

Some googling and I found that the issue is in the NotificationConfiguration block on the AnalyticsBucket. If I remove that whole sub-block, it deploys just fine but then obviously won't generate messages on the queue when objects get created.

Looking for a way to resolve this.

答:
This errror may be predominantly due to encryption enabled in the sqs queue.
The solution is either disable encryption in sqs or else use an encryption key with proper permissions to key the encrypt/decrypt s3 notification.</p>

Body:
I am trying to set up a workflow with serverless that creates a new S3 bucket, a new SQS queue and when an object is created in the S3 bucket, puts a messages on the queue and spins up a lambda once there are enough messages on the queue. I have the following in my resources block:

resources:
  Resources:
    AnalyticsQueue:
      Type: "AWS::SQS::Queue"
      Properties:
        QueueName: "my-queue"
    S3EventQueuePolicy:
      Type: AWS::SQS::QueuePolicy
      DependsOn: AnalyticsQueue
      Properties:
        PolicyDocument:
          Id: SQSPolicy
          Statement:
            - Effect: Allow
              Action: sqs:SendMessage:*
              Resource: !Ref AnalyticsQueue
        Queues:
          - !GetAtt AnalyticsQueue.Arn
    AnalyticsBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: "my-bucket"
        NotificationConfiguration:
          QueueConfigurations:
            - Event: s3:ObjectCreated:*
              Queue: !GetAtt AnalyticsQueue.Arn

When I try to deploy this I receive the following error:

An error occurred: AnalyticsBucket - Unable to validate the following destination configurations (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument; Request ID: E2A1F8BD6BEE6EF4;).

Some googling and I found that the issue is in the NotificationConfiguration block on the AnalyticsBucket. If I remove that whole sub-block, it deploys just fine but then obviously won't generate messages on the queue when objects get created.

Looking for a way to resolve this.


问:
Create quiz questions for exam applications with codeigniter
Please Help me I am not getting it perfectly..actually I am fetching 60 quiz question each having four different options from database..displaying those data using pagination one at a time with 5 options..now when I switch after answering first question and go back to previous I found radio button gets unchecked.. I want it should be checked. please help me

Controller :

```<code>$data = array(
    'id_aptitude' => $this->input->post('id_aptitude'),
    'pilihan'     => $this->input->post('pilihan'),
    'a'           => $this->input->post('A'),
    'b'           => $this->input->post('B'),
    'c'           => $this->input->post('C'),
    'd'           => $this->input->post('D'),
    'e'           => $this->input->post('E'),
);
$this->session->set_userdata($data);
</code>```

and this is my view :

```<code><?php $jawab_array = array(
    $row->a,
    $row->b,
    $row->c,
    $row->d,
    $row->e );
?>

<?php $checked_value = $this->session->set_userdata('data'); ?>

<input type="hidden" name="id_aptitude" value=<?= $row->id_aptitude ?>>

<address>
    <strong>
        <label class="form-check-label">
            <input type="radio" class="form-check-input" name="pilihan<?= $row->id_aptitude?>" value="A"<?=($checked_value == 'A') ? 'checked="checked"' :''; ?> /> A
        </label>
    </strong>
</address>

<address>
    <strong>
        <label class="form-check-label">
            <input type="radio" class="form-check-input" name="pilihan<?= $row->id_aptitude?>" value="B" <?=($checked_value == 1) ? 'checked="checked"' :'' ?> /> B
        </label>
    </strong>
</address>
<address>
    <strong>
        <label class="form-check-label">
            <input type="radio" class="form-check-input" name="pilihan<?= $row->id_aptitude?>" value="C" <?=($checked_value == 2) ? 'checked="checked"' :'' ?> /> C
        </label>
    </strong>
</address>
<address>
    <strong>
        <label class="form-check-label">
            <input type="radio" class="form-check-input" name="pilihan<?= $row->id_aptitude?>" value="D" <?=($checked_value == 3) ? 'checked="checked"' :'' ?>> D
        </label>
    </strong>
</address>
<address>
    <strong>
        <label class="form-check-label">
            <input type="radio" class="form-check-input" name="pilihan<?= $row->id_aptitude?>" value="E" <?=($checked_value == 4) ? 'checked="checked"' :'' ?>> E
        </label>
    </strong>
</address>
</code>```

答:
I think you can do it in 2 ways:

Prevent your user from going back because that's how it should be. Once you answer, you can never go back. Or

Each time the user answers, insert that answer into a database so that every time the user goes back to the previous question, you can pull out the answer from the database and display what they answered.

Body:
Please Help me I am not getting it perfectly..actually I am fetching 60 quiz question each having four different options from database..displaying those data using pagination one at a time with 5 options..now when I switch after answering first question and go back to previous I found radio button gets unchecked.. I want it should be checked. please help me

Controller :

$data = array(
    'id_aptitude' => $this->input->post('id_aptitude'),
    'pilihan'     => $this->input->post('pilihan'),
    'a'           => $this->input->post('A'),
    'b'           => $this->input->post('B'),
    'c'           => $this->input->post('C'),
    'd'           => $this->input->post('D'),
    'e'           => $this->input->post('E'),
);
$this->session->set_userdata($data);

and this is my view :

<?php $jawab_array = array(
    $row->a,
    $row->b,
    $row->c,
    $row->d,
    $row->e );
?>

<?php $checked_value = $this->session->set_userdata('data'); ?>

<input type="hidden" name="id_aptitude" value=<?= $row->id_aptitude ?>>

<address>

            <input type="radio" class="form-check-input" name="pilihan<?= $row->id_aptitude?>" value="A"<?=($checked_value == 'A') ? 'checked="checked"' :''; ?> /> A

</address>

<address>

            <input type="radio" class="form-check-input" name="pilihan<?= $row->id_aptitude?>" value="B" <?=($checked_value == 1) ? 'checked="checked"' :'' ?> /> B

</address>
<address>

            <input type="radio" class="form-check-input" name="pilihan<?= $row->id_aptitude?>" value="C" <?=($checked_value == 2) ? 'checked="checked"' :'' ?> /> C

</address>
<address>

            <input type="radio" class="form-check-input" name="pilihan<?= $row->id_aptitude?>" value="D" <?=($checked_value == 3) ? 'checked="checked"' :'' ?>> D

</address>
<address>

            <input type="radio" class="form-check-input" name="pilihan<?= $row->id_aptitude?>" value="E" <?=($checked_value == 4) ? 'checked="checked"' :'' ?>> E

</address>