问:
Pandas merging connected groups from multiple columns
How can I group rows which have at least one value in common? I can pass multiple columns to groupby but I want any one of them to be considered, not all of them.

Sample code:

import pandas as pd

input = pd.DataFrame({
  'fruit': ['peach', 'banana', pd.NA, 'peach', 'apple', 'avocado', pd.NA],
  'vegetable': [pd.NA, pd.NA, 'zucchini', pd.NA, pd.NA, pd.NA, 'potato'],
  'sugar': [17, 17, 2, 18, 20, pd.NA, 4],
  'color': ['orange', 'yellow', 'green', 'orange', 'red', 'green', 'brown']
})

output = input.groupby(['fruit', 'vegetable', 'sugar', 'color']).agg({
  'fruit': lambda x: list(set(x)),
  'vegetable': lambda x: list(set(x)),
  'sugar': lambda x: list(set(x)),
  'color': lambda x: list(set(x))
})
```
<p>Input:</p>
```    fruit       vegetable   sugar   color
0   peach                   17      orange
1   banana                  17      yellow
2               zucchini    2       green
3   peach                   18      orange
4   apple                   20      red
5   avocado                         green
6               potato      4       brown
```
<p>Expected output:</p>
```    fruit               vegetable   sugar       color
0   [peach, banana]     []          [17, 18]    [orange, yellow]
1   [avocado]           [zucchini]  [2]         [green]
2   [apple]             []          [20]        [red]
3   []                  [potato]    [4]         [brown]
```

答:
After a "challenge" by the @mozway, I tried to give a chance and this is my "Hard way" attempt on the above mentioned problem:

```<code>import pandas as pd

df = pd.DataFrame({
    'fruit': ['peach', 'banana', pd.NA, 'peach', 'apple', 'avocado', pd.NA],
    'vegetable': [pd.NA, pd.NA, 'zucchini', pd.NA, pd.NA, pd.NA, 'potato'],
    'sugar': [17, 17, 2, 18, 20, pd.NA, 4],
    'color': ['orange', 'yellow', 'green', 'orange', 'red', 'green', 'brown']
})

# Replacing pd.NA with empty string
df.replace(pd.NA, '', inplace=True)

# Initializing output dataframe with the columns of input dataframe
output_df = df2 = pd.DataFrame(data=None, columns=df.columns)

# Converting all the values per each row to list and removing empty values from it
df['common'] = df.values.tolist()
df['common'] = df['common'].apply(lambda x: list(filter(lambda y: y != '', x)))

check_list = set()
index = 0

# Iterating over each row of df
for i, row_i in df.iterrows():
    # Check if the index of row_i is not in check_list
    if i not in check_list:
        # Looping through the columns and setting up the output_df with each value as a list
        for column in df.columns[:-1]:
            temp = str(df.at[i, column])
            output_df.at[index, column] = [temp] if temp else []
        # Looping throught the dataframe again to compare the 'common' values
        for j, row_j in df.iterrows():
            # Check if index of row_j is not in check_list and not matches with the index of row_i
            if i != j and j not in check_list:
                # Check the common values between row_i and row_j
                # if found, update the output_df and append the values into the already defined list
                if set(row_i['common']).intersection(row_j['common']):
                    for column in df.columns[:-1]:
                        temp = str(df.at[j, column])
                        # Avoid the duplicate values in the column
                        if temp and temp not in output_df.at[index, column]:
                            output_df.at[index, column].append(temp)
                    check_list.add(j)
        # Increment the index of output_df
        index += 1

print(output_df)
</code>```

And this is the output, I am getting:

```<code>             fruit   vegetable     sugar             color
0  [peach, banana]          []  [17, 18]  [orange, yellow]
1        [avocado]  [zucchini]       [2]           [green]
2          [apple]          []      [20]             [red]
3               []    [potato]       [4]           [brown]
</code>```

But anyway, the answer give my @mozway is subtle, easy and short.

Body:
How can I group rows which have at least one value in common? I can pass multiple columns to groupby but I want any one of them to be considered, not all of them.

Sample code:

import pandas as pd

input = pd.DataFrame({
  'fruit': ['peach', 'banana', pd.NA, 'peach', 'apple', 'avocado', pd.NA],
  'vegetable': [pd.NA, pd.NA, 'zucchini', pd.NA, pd.NA, pd.NA, 'potato'],
  'sugar': [17, 17, 2, 18, 20, pd.NA, 4],
  'color': ['orange', 'yellow', 'green', 'orange', 'red', 'green', 'brown']
})

output = input.groupby(['fruit', 'vegetable', 'sugar', 'color']).agg({
  'fruit': lambda x: list(set(x)),
  'vegetable': lambda x: list(set(x)),
  'sugar': lambda x: list(set(x)),
  'color': lambda x: list(set(x))
})

Input:

    fruit       vegetable   sugar   color
0   peach                   17      orange
1   banana                  17      yellow
2               zucchini    2       green
3   peach                   18      orange
4   apple                   20      red
5   avocado                         green
6               potato      4       brown

Expected output:

    fruit               vegetable   sugar       color
0   [peach, banana]     []          [17, 18]    [orange, yellow]
1   [avocado]           [zucchini]  [2]         [green]
2   [apple]             []          [20]        [red]
3   []                  [potato]    [4]         [brown]

Body:
After a "challenge" by the @mozway, I tried to give a chance and this is my "Hard way" attempt on the above mentioned problem:

import pandas as pd

df = pd.DataFrame({
    'fruit': ['peach', 'banana', pd.NA, 'peach', 'apple', 'avocado', pd.NA],
    'vegetable': [pd.NA, pd.NA, 'zucchini', pd.NA, pd.NA, pd.NA, 'potato'],
    'sugar': [17, 17, 2, 18, 20, pd.NA, 4],
    'color': ['orange', 'yellow', 'green', 'orange', 'red', 'green', 'brown']
})

# Replacing pd.NA with empty string
df.replace(pd.NA, '', inplace=True)

# Initializing output dataframe with the columns of input dataframe
output_df = df2 = pd.DataFrame(data=None, columns=df.columns)

# Converting all the values per each row to list and removing empty values from it
df['common'] = df.values.tolist()
df['common'] = df['common'].apply(lambda x: list(filter(lambda y: y != '', x)))

check_list = set()
index = 0

# Iterating over each row of df
for i, row_i in df.iterrows():
    # Check if the index of row_i is not in check_list
    if i not in check_list:
        # Looping through the columns and setting up the output_df with each value as a list
        for column in df.columns[:-1]:
            temp = str(df.at[i, column])
            output_df.at[index, column] = [temp] if temp else []
        # Looping throught the dataframe again to compare the 'common' values
        for j, row_j in df.iterrows():
            # Check if index of row_j is not in check_list and not matches with the index of row_i
            if i != j and j not in check_list:
                # Check the common values between row_i and row_j
                # if found, update the output_df and append the values into the already defined list
                if set(row_i['common']).intersection(row_j['common']):
                    for column in df.columns[:-1]:
                        temp = str(df.at[j, column])
                        # Avoid the duplicate values in the column
                        if temp and temp not in output_df.at[index, column]:
                            output_df.at[index, column].append(temp)
                    check_list.add(j)
        # Increment the index of output_df
        index += 1

print(output_df)

And this is the output, I am getting:

             fruit   vegetable     sugar             color
0  [peach, banana]          []  [17, 18]  [orange, yellow]
1        [avocado]  [zucchini]       [2]           [green]
2          [apple]          []      [20]             [red]
3               []    [potato]       [4]           [brown]

But anyway, the answer give my @mozway is subtle, easy and short.


来源: stackexchange

问:
golang why comparing two variables pointing to struct behaves differently?
I have created two instances of same struct, Confused by the output when I compare two variables point to instances of struct.

```<code>package main

import "fmt"

type Person struct {
    name string
}

func main() {
   p1 := &Person{name: "guru"}
   p2 := &Person{name: "guru"}
   fmt.Println(p1 == p2) // false, compares by address?
   p3 := Person{name: "guru"}
   p4 := Person{name: "guru"}
   fmt.Println(p3 == p4) // true , why? compares by content?
}
</code>```

does == operator works like overload operator?

答:
p1 == p2 is pointer comparison, it compares the pointer values (the memory addresses). Since you used 2 composite literals (and took their addresses), they will point to 2 distinct variables, so the addresses will be different (since size of Person is not zero). Spec: Composite literals:

Taking the address of a composite literal generates a pointer to a unique variable initialized with the literal's value.

p3 == p4 compares struct values, it compares them field-by-field, and since the matching fields have equal values, the comparison will result in true.

Comparison rules are in Spec: Comparison operators:

The equality operators == and != apply to operands that are comparable. The ordering operators <, <=, >, and >= apply to operands that are ordered. These terms and the result of the comparisons are defined as follows:

[...]

Pointer values are comparable. Two pointer values are equal if they point to the same variable or if both have value nil. Pointers to distinct zero-size variables may or may not be equal.

[...]

Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

ContentLicense: CC BY-SA 4.0

Body:
I have created two instances of same struct, Confused by the output when I compare two variables point to instances of struct.

package main

import "fmt"

type Person struct {
    name string
}

func main() {
   p1 := &Person{name: "guru"}
   p2 := &Person{name: "guru"}
   fmt.Println(p1 == p2) // false, compares by address?
   p3 := Person{name: "guru"}
   p4 := Person{name: "guru"}
   fmt.Println(p3 == p4) // true , why? compares by content?
}

does == operator works like overload operator?


问:
How do I filter the below array and get ["h","a"] output?
```<code>Const array = [1,2,3,4,"h","a","$","@"]
// Here array of numbers, strings, special characters
</code>```

I wanted the output to be

```<code>["h","a"]
</code>```

答:
```<code>const alphabets = array.filter(item => {
    return typeof item === "string" && item.match(/[a-z]/i)
}
)
console.log(alphabets)
</code>```

Body:
Const array = [1,2,3,4,"h","a","$","@"]
// Here array of numbers, strings, special characters

I wanted the output to be

["h","a"]


问:
How can I check the maximum value from a set of tables in SQL Server (if possible)?
We have a set of databases (80 in total). Every single one has a table called tblProfessions. The tables are not standardized. For example:

EDIT: all the databases are on the same server.

The DB1.dbo.tblProfessions is like:

intProfessionCode
strProfessionDescription

1
lawyer

2
dentist

...
...

30
doctor

And the DB72.dbo.tblProfessions is as follows:

intProfessionCode
strProfessionDescription

1
designer

2
butcher

...
...

80
chef

Suppose I ran a script from DBO1 to DBO72, and I found that the biggest table has 80 entries (in this case the DBO72 is the biggest one).

By my limited knowledge, all I know is to run the below script database by database, and write it down in a spreadsheet manually:

```<code>SELECT MAX(intProfessionCode) FROM [DB].dbo.tblProfessions;
</code>```

Is there a script to run and loop through all the tblProfessions and get the one with the most entries? All I want is the biggest number found.

Thanks in advance.

答:
You should be able to do something like this:

```<code>WITH dat
AS
(
SELECT 'db1' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB1.dbo.tblProfessions
UNION ALL
...
UNION ALL
SELECT 'db72' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB72.dbo.tblProfessions
)
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
            FROM dat) y
            ON dat.max_intProfessionCode = y.max_intProfessionCode_overall
</code>```

For situations like this, I usually query the catalog to write the above script rather than typing it out:

```<code>    WITH
    dat AS
    (
    SELECT STRING_AGG('SELECT ''' + QUOTENAME(s.name) + ''' AS db,
    MAX(intProfessionCode) AS max_intProfessionCode
    FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME('dbo') + '.' + QUOTENAME('tblProfessions') + '
    UNION ALL',' ') AS s
    FROM sys.databases s
    WHERE s.name LIKE 'DB%' --EDIT APPROPRIATELY
    )
    SELECT 'WITH dat
AS
(' + SUBSTRING(s,1,LEN(s) - LEN(' UNION ALL')) + ')
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
            FROM dat) y
            ON dat.max_intProfessionCode = y.max_intProfessionCode_overall' AS scrpt
    FROM dat;
</code>```

Make sure the above is only returning data for the appropriate databases by editing the WHERE clause in the CTE, then copy the output, paste elsewhere and run it to get your results.

Body:
We have a set of databases (80 in total). Every single one has a table called tblProfessions. The tables are not standardized. For example:

EDIT: all the databases are on the same server.

The DB1.dbo.tblProfessions is like:

intProfessionCode
strProfessionDescription

1
lawyer

2
dentist

...
...

30
doctor

And the DB72.dbo.tblProfessions is as follows:

intProfessionCode
strProfessionDescription

1
designer

2
butcher

...
...

80
chef

Suppose I ran a script from DBO1 to DBO72, and I found that the biggest table has 80 entries (in this case the DBO72 is the biggest one).

By my limited knowledge, all I know is to run the below script database by database, and write it down in a spreadsheet manually:

SELECT MAX(intProfessionCode) FROM [DB].dbo.tblProfessions;

Is there a script to run and loop through all the tblProfessions and get the one with the most entries? All I want is the biggest number found.

Thanks in advance.

Body:
You should be able to do something like this:

WITH dat
AS
(
SELECT 'db1' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB1.dbo.tblProfessions
UNION ALL
...
UNION ALL
SELECT 'db72' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB72.dbo.tblProfessions
)
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
            FROM dat) y
            ON dat.max_intProfessionCode = y.max_intProfessionCode_overall

For situations like this, I usually query the catalog to write the above script rather than typing it out:

    WITH
    dat AS
    (
    SELECT STRING_AGG('SELECT ''' + QUOTENAME(s.name) + ''' AS db,
    MAX(intProfessionCode) AS max_intProfessionCode
    FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME('dbo') + '.' + QUOTENAME('tblProfessions') + '
    UNION ALL',' ') AS s
    FROM sys.databases s
    WHERE s.name LIKE 'DB%' --EDIT APPROPRIATELY
    )
    SELECT 'WITH dat
AS
(' + SUBSTRING(s,1,LEN(s) - LEN(' UNION ALL')) + ')
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
            FROM dat) y
            ON dat.max_intProfessionCode = y.max_intProfessionCode_overall' AS scrpt
    FROM dat;

Make sure the above is only returning data for the appropriate databases by editing the WHERE clause in the CTE, then copy the output, paste elsewhere and run it to get your results.


问:
ImportError: cannot import name 'tasks_v2' from 'google.cloud' (unknown location) in Python fastapi
I'm trying to incorporate google-cloud-tasks Python client within my fastapi app. But it's giving me an import error like this:

```<code>from google.cloud import tasks_v2
ImportError: cannot import name 'tasks_v2' from 'google.cloud' (unknown location)
</code>```

packages in my project, pip freeze:

```<code>aiohttp==3.8.1
aiosignal==1.2.0
async-timeout==4.0.2
attrs==21.4.0
boto3==1.20.51
botocore==1.23.51
CacheControl==0.12.10
cachetools==4.2.4
certifi==2021.10.8
charset-normalizer==2.0.11
click==7.1.2
confuse==1.4.0
firebase-admin==5.0.1
Flask==1.1.4
frozenlist==1.3.0
google-api-core==1.31.5
google-api-python-client==2.36.0
google-auth==1.35.0
google-auth-httplib2==0.1.0
google-cloud==0.34.0
google-cloud-core==2.2.2
google-cloud-firestore==2.3.4
google-cloud-storage==2.1.0
google-cloud-tasks==2.7.2
google-crc32c==1.3.0
google-resumable-media==2.2.0
googleapis-common-protos==1.54.0
greenlet==1.1.2
grpc-google-iam-v1==0.12.3
grpcio==1.43.0
grpcio-status==1.43.0
httplib2==0.20.4
idna==3.3
itsdangerous==1.1.0
Jinja2==2.11.3
jmespath==0.10.0
MarkupSafe==1.1.1
msgpack==1.0.3
multidict==6.0.2
numpy==1.22.2
packaging==21.3
pandas==1.3.2
proto-plus==1.20.0
protobuf==3.19.4
pyasn1==0.4.8
pyasn1-modules==0.2.8
pycryptodome==3.14.1
pyee==7.0.4
PyMySQL==1.0.2
pyparsing==3.0.7
python-dateutil==2.8.2
python-dotenv==0.19.1
pytz==2021.3
PyYAML==6.0
requests==2.27.1
rsa==4.8
s3transfer==0.5.1
schedule==1.1.0
six==1.16.0
slackclient==2.9.3
slackeventsapi==2.2.1
SQLAlchemy==1.4.22
uritemplate==4.1.1
urllib3==1.26.8
Werkzeug==1.0.1
yarl==1.7.2
</code>```

Python version I'm using for this virtualenv is Python 3.8.9

OS: macOS Monterey 12.1

Tried this solution here, but it didn't work. :(

答:
After doing some more research online I realized that installation of some packages is missed due to some existing packages. This issue helped me realize I need to reorder the position of google-cloud-tasks in my requirements.txt. So what I did was pretty simple, created a new virtualenv installed google-cloud-tasks as my first package and then installed everything else and finally the problem is solved.

Long story short the issue is the order in which packages are installed and that's why some packages are getting missed.

Body:
I'm trying to incorporate google-cloud-tasks Python client within my fastapi app. But it's giving me an import error like this:

from google.cloud import tasks_v2
ImportError: cannot import name 'tasks_v2' from 'google.cloud' (unknown location)

packages in my project, pip freeze:

aiohttp==3.8.1
aiosignal==1.2.0
async-timeout==4.0.2
attrs==21.4.0
boto3==1.20.51
botocore==1.23.51
CacheControl==0.12.10
cachetools==4.2.4
certifi==2021.10.8
charset-normalizer==2.0.11
click==7.1.2
confuse==1.4.0
firebase-admin==5.0.1
Flask==1.1.4
frozenlist==1.3.0
google-api-core==1.31.5
google-api-python-client==2.36.0
google-auth==1.35.0
google-auth-httplib2==0.1.0
google-cloud==0.34.0
google-cloud-core==2.2.2
google-cloud-firestore==2.3.4
google-cloud-storage==2.1.0
google-cloud-tasks==2.7.2
google-crc32c==1.3.0
google-resumable-media==2.2.0
googleapis-common-protos==1.54.0
greenlet==1.1.2
grpc-google-iam-v1==0.12.3
grpcio==1.43.0
grpcio-status==1.43.0
httplib2==0.20.4
idna==3.3
itsdangerous==1.1.0
Jinja2==2.11.3
jmespath==0.10.0
MarkupSafe==1.1.1
msgpack==1.0.3
multidict==6.0.2
numpy==1.22.2
packaging==21.3
pandas==1.3.2
proto-plus==1.20.0
protobuf==3.19.4
pyasn1==0.4.8
pyasn1-modules==0.2.8
pycryptodome==3.14.1
pyee==7.0.4
PyMySQL==1.0.2
pyparsing==3.0.7
python-dateutil==2.8.2
python-dotenv==0.19.1
pytz==2021.3
PyYAML==6.0
requests==2.27.1
rsa==4.8
s3transfer==0.5.1
schedule==1.1.0
six==1.16.0
slackclient==2.9.3
slackeventsapi==2.2.1
SQLAlchemy==1.4.22
uritemplate==4.1.1
urllib3==1.26.8
Werkzeug==1.0.1
yarl==1.7.2

Python version I'm using for this virtualenv is Python 3.8.9

OS: macOS Monterey 12.1

Tried this solution here, but it didn't work. :(


问:
Keyword arguments in python class inheritance
Hello I am recently looking about the metaclass in Python.

I learned about we can attach a metaclass to a class in this way:

class Metaclass(type):
    ...

class MyClass(metaclass=Metaclass):
    ...
```
<ul>
<li>The first question</li>
</ul>
<p>I wonder what's the principle of the keyword argument (<code>metaclass=...</code>) in the above example. There seems no description for that in the doc</p>
<p>I know that there is keyword argument for a function, but I've never seen the form occurred in class inheritance.</p>
<ul>
<li>The second question</li>
</ul>
<p>We know that we can create a class using <code>type()</code> function in this way</p>
<pre class="lang-py prettyprint-override"><code>cls = type(class_name, (base_class,), {func_name: func_ref})
</code>```

Considering the metaclass=... form, how can I pass metaclass when creating class using type() instead of class keyword?

Thanks stackoverflowers!

答:
In general, the keyword arguments used with a class statement are passed to __init_subclass__, to be used however that function sees fit. metaclass, however, is used by the code generator itself to determine what gets called in order to define the class.

The metaclass is not an argument to be passed to a call to type; it is the callable that gets called instead of type. Very roughly speaking,

```<code>class MyClass(metaclass=Metaclass):
    ...
</code>```

is turned into

```<code>MyClass = Metaclass('MyClass', (), ...)
</code>```

type is simply the default metaclass.

(The gory details of how a class statement is executed can be found in Section 3.3.3 of the language documentation.)

Note that a metaclass does not have to be a subclass of type. You can do truly horrific things with metaclasses, like

```<code>>>> class A(metaclass=lambda x, y, z: 3): pass
...
>>> type(A)
<class 'int'>
>>> A
3
</code>```

It doesn't really matter what the metaclass returns, as long as it accepts 3 arguments.

Please don't write actual code like this, though. A class statement should produce something that at least resembles a type.

In some sense, class statements are less magical than other statements. def statements, for example, can't be customized to produce something other than instances of function, and it's far harder to create a function object by calling types.FunctionType explicitly.

Body:
Hello I am recently looking about the metaclass in Python.

I learned about we can attach a metaclass to a class in this way:

class Metaclass(type):
    ...

class MyClass(metaclass=Metaclass):
    ...

The first question

I wonder what's the principle of the keyword argument (metaclass=...) in the above example. There seems no description for that in the doc

I know that there is keyword argument for a function, but I've never seen the form occurred in class inheritance.

The second question

We know that we can create a class using type() function in this way

cls = type(class_name, (base_class,), {func_name: func_ref})

Considering the metaclass=... form, how can I pass metaclass when creating class using type() instead of class keyword?

Thanks stackoverflowers!

Body:
In general, the keyword arguments used with a class statement are passed to __init_subclass__, to be used however that function sees fit. metaclass, however, is used by the code generator itself to determine what gets called in order to define the class.

The metaclass is not an argument to be passed to a call to type; it is the callable that gets called instead of type. Very roughly speaking,

class MyClass(metaclass=Metaclass):
    ...

is turned into

MyClass = Metaclass('MyClass', (), ...)

type is simply the default metaclass.

(The gory details of how a class statement is executed can be found in Section 3.3.3 of the language documentation.)

Note that a metaclass does not have to be a subclass of type. You can do truly horrific things with metaclasses, like

>>> class A(metaclass=lambda x, y, z: 3): pass
...
>>> type(A)
<class 'int'>
>>> A
3

It doesn't really matter what the metaclass returns, as long as it accepts 3 arguments.

Please don't write actual code like this, though. A class statement should produce something that at least resembles a type.

In some sense, class statements are less magical than other statements. def statements, for example, can't be customized to produce something other than instances of function, and it's far harder to create a function object by calling types.FunctionType explicitly.


问:
Which is better to use: $arrayName['literal'] or $arrayName[literal]?
Both are working fine. I'm just curious how php parse the two. Do they have difference on speed, efficiency, etc. Why does php allow us to use both?</p>

答:
http://php.net/manual/en/language.types.array.php

Array do's and don'ts
  *Why is $foo[bar] wrong?*

Always use quotes around a string literal array index. For example,
  $foo['bar'] is correct, while $foo[bar] is not. But why? It is common
  to encounter this kind of syntax in old scripts:

```<code><?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>
</code>```

This is wrong, but it works. The reason is that this code has an
  undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for
  such code, have the same name. It works because PHP automatically
  converts a bare string (an unquoted string which does not correspond
  to any known symbol) into a string which contains the bare string. For
  instance, if there is no defined constant named bar, then PHP will
  substitute in the string 'bar' and use that.

ContentLicense: CC BY-SA 3.0

Body:
http://php.net/manual/en/language.types.array.php

Array do's and don'ts
  *Why is $foo[bar] wrong?*

Always use quotes around a string literal array index. For example,
  $foo['bar'] is correct, while $foo[bar] is not. But why? It is common
  to encounter this kind of syntax in old scripts:

<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>

This is wrong, but it works. The reason is that this code has an
  undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for
  such code, have the same name. It works because PHP automatically
  converts a bare string (an unquoted string which does not correspond
  to any known symbol) into a string which contains the bare string. For
  instance, if there is no defined constant named bar, then PHP will
  substitute in the string 'bar' and use that.


答:
Two pointers values are only equal when they point to the same value in the memory or if they are nil in Golang.
You create two instances of struct, thus they have different address</p>
```<code>   p1 := &Person{name: "guru"}
   p2 := &Person{name: "guru"}
</code>```

Title: golang why comparing two variables pointing to struct behaves differently?

Body:
Two pointers values are only equal when they point to the same value in the memory or if they are nil in Golang.
You create two instances of struct, thus they have different address

   p1 := &Person{name: "guru"}
   p2 := &Person{name: "guru"}


问:
Mac - Getting audio devices vendor-ID and product-id and adjust it the uid I get from CoreAudio
I am building a list of the OSX audio devices.
I am using CoreAudio for getting the list
and I would like also to get the vendor-id and product-id for each one of them.

Any idea how to do it?

答:
You’ll need to first look up the audio device in the I/O registry and get the VID/PID from there, as it was outlined a while ago on the CoreAudio mailing list:

#include <IOKit/IOKitLib.h>
#include <IOKit/audio/IOAudioDefines.h>
#include <IOKit/usb/USB.h>

AudioDeviceID deviceID = ...

// get device UID for AudioDevice ID
AudioObjectPropertyAddress address = {kAudioDevicePropertyDeviceUID, kAudioObjectPropertyScopeOutput, 0};
UInt32 size = sizeof(CFStringRef);
CFStringRef uid = NULL;
OSStatus err = AudioObjectGetPropertyData(deviceID, &address, 0, NULL, &size, &uid);

NSNumber *vid, *pid;

// find matching IOAudioEngine object
io_iterator_t it;
if (IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching(kIOAudioEngineClassName), &it) == KERN_SUCCESS) {
    io_service_t service;
    while ((service = IOIteratorNext(it)) != 0) {
        CFStringRef uniqueID = IORegistryEntryCreateCFProperty(service, CFSTR(kIOAudioEngineGlobalUniqueIDKey), kCFAllocatorDefault, 0);
        if (uniqueID && CFEqual(uniqueID, uid)) {
            vid = CFBridgingRelease(IORegistryEntryCreateCFProperty(service, CFSTR(kUSBVendorID), kCFAllocatorDefault, 0));
            pid = CFBridgingRelease(IORegistryEntryCreateCFProperty(service, CFSTR(kUSBProductID), kCFAllocatorDefault, 0));
        }
        CFRelease(uniqueID);
        if (vid || pid) break;
    }
    IOObjectRelease(it);
}
```

The same technique can also be used to get other USB properties of the audio device like the USB location ID (kUSBDevicePropertyLocationID), e.g. to correlate audio with CoreMIDI devices.

Body:
You’ll need to first look up the audio device in the I/O registry and get the VID/PID from there, as it was outlined a while ago on the CoreAudio mailing list:

#include <IOKit/IOKitLib.h>
#include <IOKit/audio/IOAudioDefines.h>
#include <IOKit/usb/USB.h>

AudioDeviceID deviceID = ...

// get device UID for AudioDevice ID
AudioObjectPropertyAddress address = {kAudioDevicePropertyDeviceUID, kAudioObjectPropertyScopeOutput, 0};
UInt32 size = sizeof(CFStringRef);
CFStringRef uid = NULL;
OSStatus err = AudioObjectGetPropertyData(deviceID, &address, 0, NULL, &size, &uid);

NSNumber *vid, *pid;

// find matching IOAudioEngine object
io_iterator_t it;
if (IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching(kIOAudioEngineClassName), &it) == KERN_SUCCESS) {
    io_service_t service;
    while ((service = IOIteratorNext(it)) != 0) {
        CFStringRef uniqueID = IORegistryEntryCreateCFProperty(service, CFSTR(kIOAudioEngineGlobalUniqueIDKey), kCFAllocatorDefault, 0);
        if (uniqueID && CFEqual(uniqueID, uid)) {
            vid = CFBridgingRelease(IORegistryEntryCreateCFProperty(service, CFSTR(kUSBVendorID), kCFAllocatorDefault, 0));
            pid = CFBridgingRelease(IORegistryEntryCreateCFProperty(service, CFSTR(kUSBProductID), kCFAllocatorDefault, 0));
        }
        CFRelease(uniqueID);
        if (vid || pid) break;
    }
    IOObjectRelease(it);
}

The same technique can also be used to get other USB properties of the audio device like the USB location ID (kUSBDevicePropertyLocationID), e.g. to correlate audio with CoreMIDI devices.


问:
localStorage is not defined in nextjs
I had trouble using Local Storage in Next JS, and sometimes Windows, and sometimes Local Storage is not defined.
I want to keep the values for Front, not on the server

If you have an example or solution, thank you

答:
With Next.js, components are rendered server-side. localStorage - or the window - are not available until rendered in a browser.

You can use useEffect or a conditional that checks if the window is defined: const clientSide = typeof window !== 'undefined'

Title: localStorage is not defined in nextjs


问:
SSAS - Cannot create relationships due to dupicate column entries
I am currently building a tabular cube in SSAS, however I'm having issues when creating relationships.

I have 3 tables

Master

Supplier

Customer

In the master table I have a list of unique IDs, these ID's appear in the other 2 tables (there can be duplicate records for the ID in the Supplier and Customer table).

What I'm tring to do is create a relationship between the Master table and the Supplier and Customer table. One to Many. But SSAS gives me an error The relationship cannot be created because each column contains duplicate values. Select at least one column that contains only unique values.

Any advise would be greatly appreciated

答: Based on the error message it seems to be there are some duplicate values in the master table within the column that is being selected for relationship.</p>


问:
How to add delay to my execution of program
I want to make a simple program, but I want to add some delay() before the program clears the screen.

I have tried the sleep() and delay() functions, but they don't work!

Can anyone help out?

```<code>#include <iostream>
#include <string>
#include <cstring>
#include <fstream>

using namespace std;

class div
{
private:
    string mon= "IICT lab at 8:30AM, PF lab at 10:10AM, PF lecture at 1:50PM";
    string tue= "Maths at 8:30AM, Physics lab at 10:10AM";
    string wed= "English at 8:30AM, IICT lecture at 12:10PM";
    string thurs= "Physics lecture at 8:30AM, English at 10:10AM, PAkSTD at 1:50PM";
    string fri= "Maths at 8:30AM, PF lecture at 10:10AM, QT at 2:50PM";
public:

    timetable(int choice)
    {
        switch(choice)
        {
            case 1:
                cout<<mon<<endl;
                break;
            case 2:
                cout<<tue<<endl;
                break;
            case 3:
                cout<<wed<<endl;
                break;
            case 4:
                cout<<thurs<<endl;
                break;
            case 5:
                cout<<fri<<endl;
                break;
        }
    }

    mainwin()
    {
        cout<<"-------------------------------------------------Time Table-----------------------------------------------"<<endl;
        cout<<"||                                           1.Monday                                                   ||"<<endl;
        cout<<"||                                           2.Tuesday                                                  ||"<<endl;
        cout<<"||                                           3.Wednesday                                                ||"<<endl;
        cout<<"||                                           4.Thursday                                                 ||"<<endl;
        cout<<"||                                           5.Friday                                                   ||"<<endl;
        cout<<"||                                           0.EXIT                                                     || "<<endl;
        cout<<"=========================================================================================================="<<endl;
    }
};

int main()
{
    div t;
    int choice1;
    do{
        t.mainwin();
        cout<< "Enter Your Choice: ";
        cin>>choice1;
        t.timetable(choice1);
        system("cls");
    }while(choice1 != 0);
}
</code>```

This doesn't work.  I use the windows.h header file but it doesn't work and gives an error that a ; is missing before t.

答:
```<code>#include <thread>
#include <chrono>

#include <iostream>
#include <string>
#include <cstring>
#include <fstream>

using namespace std::chrono_literals;
using namespace std;

class div
{
private:
    string mon= "IICT lab at 8:30AM, PF lab at 10:10AM, PF lecture at 1:50PM";
    string tue= "Maths at 8:30AM, Physics lab at 10:10AM";
    string wed= "English at 8:30AM, IICT lecture at 12:10PM";
    string thurs= "Physics lecture at 8:30AM, English at 10:10AM, PAkSTD at 1:50PM";
    string fri= "Maths at 8:30AM, PF lecture at 10:10AM, QT at 2:50PM";
public:
    void timetable(int choice)
    {
        switch(choice)
        {
            case 1:
                cout<<mon<<endl;
                break;
            case 2:
                cout<<tue<<endl;
                break;
            case 3:
                cout<<wed<<endl;
                break;
            case 4:
                cout<<thurs<<endl;
                break;
            case 5:
                cout<<fri<<endl;
                break;
        }
    }
    void mainwin()
    {
        cout<<"-------------------------------------------------Time Table-----------------------------------------------"<<endl;
        cout<<"||                                           1.Monday                                                   ||"<<endl;
        cout<<"||                                           2.Tuesday                                                  ||"<<endl;
        cout<<"||                                           3.Wednesday                                                ||"<<endl;
        cout<<"||                                           4.Thursday                                                 ||"<<endl;
        cout<<"||                                           5.Friday                                                   ||"<<endl;
        cout<<"||                                           0.EXIT                                                     || "<<endl;
        cout<<"=========================================================================================================="<<endl;
    }
};

int main()
{
class div t;
int choice1;
do{
    t.mainwin();
    cout<< "Enter Your Choice: ";
    cin>>choice1;
    t.timetable(choice1);
    std::this_thread::sleep_for(2000ms);
} while(choice1 != 0);

}
</code>```

Body:
I want to make a simple program, but I want to add some delay() before the program clears the screen.

I have tried the sleep() and delay() functions, but they don't work!

Can anyone help out?

#include <iostream>
#include <string>
#include <cstring>
#include <fstream>

using namespace std;

class div
{
private:
    string mon= "IICT lab at 8:30AM, PF lab at 10:10AM, PF lecture at 1:50PM";
    string tue= "Maths at 8:30AM, Physics lab at 10:10AM";
    string wed= "English at 8:30AM, IICT lecture at 12:10PM";
    string thurs= "Physics lecture at 8:30AM, English at 10:10AM, PAkSTD at 1:50PM";
    string fri= "Maths at 8:30AM, PF lecture at 10:10AM, QT at 2:50PM";
public:

    timetable(int choice)
    {
        switch(choice)
        {
            case 1:
                cout<<mon<<endl;
                break;
            case 2:
                cout<<tue<<endl;
                break;
            case 3:
                cout<<wed<<endl;
                break;
            case 4:
                cout<<thurs<<endl;
                break;
            case 5:
                cout<<fri<<endl;
                break;
        }
    }

    mainwin()
    {
        cout<<"-------------------------------------------------Time Table-----------------------------------------------"<<endl;
        cout<<"||                                           1.Monday                                                   ||"<<endl;
        cout<<"||                                           2.Tuesday                                                  ||"<<endl;
        cout<<"||                                           3.Wednesday                                                ||"<<endl;
        cout<<"||                                           4.Thursday                                                 ||"<<endl;
        cout<<"||                                           5.Friday                                                   ||"<<endl;
        cout<<"||                                           0.EXIT                                                     || "<<endl;
        cout<<"=========================================================================================================="<<endl;
    }
};

int main()
{
    div t;
    int choice1;
    do{
        t.mainwin();
        cout<< "Enter Your Choice: ";
        cin>>choice1;
        t.timetable(choice1);
        system("cls");
    }while(choice1 != 0);
}

This doesn't work.  I use the windows.h header file but it doesn't work and gives an error that a ; is missing before t.


问:
Flutter GetIn can't find the method of the services
I'm setting up a project with Flutter. I want to register services with GetIn. But I'm not able to find the methods of the service that I want to use.

This is the class locator in which I register the service, for example MongoDBService.

```<code>import 'package:app/services/mongodb.dart';
import 'package:get_it/get_it.dart';

final locator = GetIt.instance;

setupLocator() {
    locator.registerSingleton<MongoDBService>(MongoDBService());
}
</code>```

Then when I want to use the MongoDBService I am not able to find the functions that belong to the service.

```<code>void connect() async {
    await mongo.beginConnection();
}

final mongo = locator<MongoDBService>;
</code>```

The error is on beginConnection which is not defined. But currently it is defined in the MongoDBService.

Also I setup the locator by calling the setupLocator function in the main.

```<code>void main() {
    setupLocator();
    runApp(const MyApp());
}
</code>```

答:
Put final mongo = locator<MongoDBService>; in the connect method.

```<code>void connect() async {
    final mongo = locator<MongoDBService>();
    await mongo.beginConnection();
}
</code>```

Body:
I'm setting up a project with Flutter. I want to register services with GetIn. But I'm not able to find the methods of the service that I want to use.

This is the class locator in which I register the service, for example MongoDBService.

import 'package:app/services/mongodb.dart';
import 'package:get_it/get_it.dart';

final locator = GetIt.instance;

setupLocator() {
    locator.registerSingleton<MongoDBService>(MongoDBService());
}

Then when I want to use the MongoDBService I am not able to find the functions that belong to the service.

void connect() async {
    await mongo.beginConnection();
}

final mongo = locator<MongoDBService>;

The error is on beginConnection which is not defined. But currently it is defined in the MongoDBService.

Also I setup the locator by calling the setupLocator function in the main.

void main() {
    setupLocator();
    runApp(const MyApp());
}

Body:
Put final mongo = locator<MongoDBService>; in the connect method.

void connect() async {
    final mongo = locator<MongoDBService>();
    await mongo.beginConnection();
}


问:
How to know when an app is killed after being in recents for a long time?
Which function is called when an app is killed by keeping it in recent apps list for a long time?

I am not asking about when an app is killed by swiping app from the recents list.

答:
There is no such function in Android.

When user closes the app, the process is terminated with no notice. Even Activity's onDestroy method is not guaranteed to be called. Only when you explicitly call finish().

If you use ViewModel that is tied to the starting Activity's lifecycle, you can try to use onCleared() method, which is called always when ViewModel is no longer used and will be destroyed. See: https://developer.android.com/topic/libraries/architecture/viewmodel


问:
Send JSON request body without identifiers SPRING Boot
I am consuming a legacy rest service that receives xml text in the body but is sent as json as shown in the following image

Postman source request

I have done the process to transform the previous request to a request that receives a JSON in normal format
New JSON request

And then I transform it into the format that asks me for the source request, my problem is that I do not know how to send my string request because I get the following error when I try to send it
Request error new http request

I get the same error when I sent in my source request in plain text format
Plain text error legacy http request

however in code I already transformed this text into JSON format but probably incorrectly,in the following sample code the http entity is the xml string object required by the legacy service

```<code>@Value("${client.medExpInsuranceQuotation.uri}")
private String clientUri;

@Autowired
@Qualifier("restTemplategetPolicyWs")
private RestTemplate restTemplate;

@Override
public Object callMedicalExpenseInsuranceQuotation(MedicalExpenseInsuranceQuotationRequestClient requestClient) {

    Gson gson = new Gson();
    Object json = gson.toJson(requestClient.getXml(), String.class);
    System.out.println("Object: "+json);

    HttpEntity<Object> entity = new HttpEntity<>(json);
    log.info(requestClient.getXml());
    ResponseEntity<ResponseBean<Object>> responseEntity = restTemplate.exchange(clientUri, HttpMethod.POST, entity, new ParameterizedTypeReference<ResponseBean<Object>>() {
    });

    return responseEntity.getBody().getPayload();
}
</code>```

Notes:
The legacy service only receives the body in the format indicated in image 1 (Postman source request)

if I try to send the body in traditional json format with an attribute identifier
attemp send normal json format

I get the following error without information

```<code>{
    "Message": "An error has occurred."
}
</code>```

I hope you can help me greetings

答:
That rest service is consuming json format. Note the double quotes at the start and the end of the payload - this makes it json string. Not json object, or json array, but json string. You need to transform the xml payload into json string and send the correct content type header - application/json.

Edit: To get json string first you need the xml as a string(it's already a string, i know that sounds strange, but can't explain it better). Then you call toJson() on that xml. Something similar to this:

```<code>String xml = "<xml><tag></tag></xml>";
String jsonString = gson.toJson(xml);
System.out.println(jsonString);
</code>```

Body:
I am consuming a legacy rest service that receives xml text in the body but is sent as json as shown in the following image

Postman source request

I have done the process to transform the previous request to a request that receives a JSON in normal format
New JSON request

And then I transform it into the format that asks me for the source request, my problem is that I do not know how to send my string request because I get the following error when I try to send it
Request error new http request

I get the same error when I sent in my source request in plain text format
Plain text error legacy http request

however in code I already transformed this text into JSON format but probably incorrectly,in the following sample code the http entity is the xml string object required by the legacy service

@Value("${client.medExpInsuranceQuotation.uri}")
private String clientUri;

@Autowired
@Qualifier("restTemplategetPolicyWs")
private RestTemplate restTemplate;

@Override
public Object callMedicalExpenseInsuranceQuotation(MedicalExpenseInsuranceQuotationRequestClient requestClient) {

    Gson gson = new Gson();
    Object json = gson.toJson(requestClient.getXml(), String.class);
    System.out.println("Object: "+json);

    HttpEntity<Object> entity = new HttpEntity<>(json);
    log.info(requestClient.getXml());
    ResponseEntity<ResponseBean<Object>> responseEntity = restTemplate.exchange(clientUri, HttpMethod.POST, entity, new ParameterizedTypeReference<ResponseBean<Object>>() {
    });

    return responseEntity.getBody().getPayload();
}

Notes:
The legacy service only receives the body in the format indicated in image 1 (Postman source request)

if I try to send the body in traditional json format with an attribute identifier
attemp send normal json format

I get the following error without information

{
    "Message": "An error has occurred."
}

I hope you can help me greetings

Body:
That rest service is consuming json format. Note the double quotes at the start and the end of the payload - this makes it json string. Not json object, or json array, but json string. You need to transform the xml payload into json string and send the correct content type header - application/json.

Edit: To get json string first you need the xml as a string(it's already a string, i know that sounds strange, but can't explain it better). Then you call toJson() on that xml. Something similar to this:

String xml = "<xml><tag></tag></xml>";
String jsonString = gson.toJson(xml);
System.out.println(jsonString);


问:
Kubernetes - delete all jobs in bulk
I can delete all jobs inside a custer running

```<code>kubectl delete jobs --all
</code>```

However, jobs are deleted one after another which is pretty slow (for ~200 jobs I had the time to write this question and it was not even done).

Is there a faster approach ?

答:
There is an easier way to do it:

To delete successful jobs:

kubectl delete jobs --field-selector status.successful=1

To delete failed or long-running jobs:

kubectl delete jobs --field-selector status.successful=0

Title: Kubernetes - delete all jobs in bulk

Body:
I can delete all jobs inside a custer running

kubectl delete jobs --all

However, jobs are deleted one after another which is pretty slow (for ~200 jobs I had the time to write this question and it was not even done).

Is there a faster approach ?


问:
mute/unmute icon js fontawesome
My function should change the icon to mute or to unmute but it sometimes said that the class is undefined. I don't know why.

var i = document.getElementById("sound")
var unmute = false

function change() {
  console.log(i.className)
  if (unmute == false) {
    i.className = "fas fa-volume volumen"
    console.log("unmute")
    unmute = true;
  } else {
    i.className = "fas fa-volume-mute volumen"
    console.log("mute")
    unmute = false
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<strike>
    <i id="sound" onclick="change()" class="fas fa-volume-mute volumen"></i>
<strike></code>```

答:
Try putting the declaration of i inside the function.

```<code>var unmute = false;

function change() {
    let i = document.getElementById("sound");
    console.log(i.className)

    if (unmute == false) {
        i.className = "fal fa-volume volumen";
        console.log("unmute");
        unmute = true;
    } else {
        i.className = "fal fa-volume-mute volumen";
        console.log("mute");
        unmute = false;
    }
}
</code>```

Are you going to use the variable unmute in other functions? If not, you could try doing this instead:

```<code>function change() {
    let i = document.getElementById("sound");
    let current_class = i.className;

    current_class = current_class == "fal fa-volume-mute volumen" ? "fal fa-volume volumen" : "fal fa-volume-mute volumen";
}
</code>```

You can also use jQuery to toggle between class names:

```<code>$("#sound").on('click', function(){
    $("#sound", this)
         .toggleClass("fal fa-volume volumen")
         .toggleClass("fal fa-volume-mute volumen");
});
</code>```

Title: mute/unmute icon js fontawesome

Body:
My function should change the icon to mute or to unmute but it sometimes said that the class is undefined. I don't know why.

var i = document.getElementById("sound")
var unmute = false

function change() {
  console.log(i.className)
  if (unmute == false) {
    i.className = "fas fa-volume volumen"
    console.log("unmute")
    unmute = true;
  } else {
    i.className = "fas fa-volume-mute volumen"
    console.log("mute")
    unmute = false
  }

}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />

Body:
Try putting the declaration of i inside the function.

var unmute = false;

function change() {
    let i = document.getElementById("sound");
    console.log(i.className)

    if (unmute == false) {
        i.className = "fal fa-volume volumen";
        console.log("unmute");
        unmute = true;
    } else {
        i.className = "fal fa-volume-mute volumen";
        console.log("mute");
        unmute = false;
    }
}

Are you going to use the variable unmute in other functions? If not, you could try doing this instead:

function change() {
    let i = document.getElementById("sound");
    let current_class = i.className;

    current_class = current_class == "fal fa-volume-mute volumen" ? "fal fa-volume volumen" : "fal fa-volume-mute volumen";
}

You can also use jQuery to toggle between class names:

$("#sound").on('click', function(){
    $("#sound", this)
         .toggleClass("fal fa-volume volumen")
         .toggleClass("fal fa-volume-mute volumen");
});


问:
Proper validation of a referenced file when editing OpenAPI json in IntelliJ
I'm editing an OpenAPI JSON spec in IntelliJ.  The automatic validation and code completion work very nicely.

The OpenAPI version used is 3.0.3, which IntelliJ detects correctly.  It seems that it uses "openapi30.json" internally for validation, and all is good.

However, the file is getting very large and it's time to move some commonly-used models out of it using $ref.

This is where things break.  The main spec looks like this (snippet):

```<code>{
  "openapi": "3.0.3",
  "info": {
    "title": "Cars REST API",
    "description": "Calls, Responses and DTOs for REST",
    "version": "1.0.0"
  },
  "components": {
    "schemas": {
      "car": {
        "$ref": "car.json"
      },
      "car-group": {
        "$ref": "car-group.json"
      }
</code>```

And when editing it, IntelliJ recognizes it as "openapi30".

However, the referenced documents are not recognized.  For example, the car.json file looks like this:

```<code>{
  "car": {
    "required": [
      "id",
      "name"
    ],
    "properties": {
      "id": {
        "type": "integer",
        "format": "int64"
      },
      "name": {
        "type": "string"
      },
      "tag": {
        "type": "string"
      }
    }
  }
}
</code>```

And it's recognized simply as a JSON document, not an OpenAPI one, so there is no proper validation and no code completion, etc.

How does one tell IntelliJ that the file is part of an OpenAPI specification, to be validated as such?  One should think this could be inferred from begin $ref'ed from the main spec, but this doesn't work.

Trying to add a $schema value in the referenced file had no effect (and probably isn't in line with the OpenAPI spec anyway).

Manually selecting the OpenAPI 3.0 file type for car.json is not helpful, because then validation (rightly) fails - as it doesn't have the top-level structure required (info, openapi, paths).

Perhaps some specific JSON schema mapping needs to be added in IntelliJ preferences?  If that's the case, it would be actually a sub-schema or some tag in the main OpenAPI spec, how can that be done?

IntelliJ version is: IntelliJ IDEA 2021.3.2 (Ultimate Edition)

Any help would be greatly appreciated.

答:
Ron!

Such functionality is not yet supported. Please vote for https://youtrack.jetbrains.com/issue/IDEA-284305

Body:
I'm editing an OpenAPI JSON spec in IntelliJ.  The automatic validation and code completion work very nicely.

The OpenAPI version used is 3.0.3, which IntelliJ detects correctly.  It seems that it uses "openapi30.json" internally for validation, and all is good.

However, the file is getting very large and it's time to move some commonly-used models out of it using $ref.

This is where things break.  The main spec looks like this (snippet):

{
  "openapi": "3.0.3",
  "info": {
    "title": "Cars REST API",
    "description": "Calls, Responses and DTOs for REST",
    "version": "1.0.0"
  },
  "components": {
    "schemas": {
      "car": {
        "$ref": "car.json"
      },
      "car-group": {
        "$ref": "car-group.json"
      }

And when editing it, IntelliJ recognizes it as "openapi30".

However, the referenced documents are not recognized.  For example, the car.json file looks like this:

{
  "car": {
    "required": [
      "id",
      "name"
    ],
    "properties": {
      "id": {
        "type": "integer",
        "format": "int64"
      },
      "name": {
        "type": "string"
      },
      "tag": {
        "type": "string"
      }
    }
  }
}

And it's recognized simply as a JSON document, not an OpenAPI one, so there is no proper validation and no code completion, etc.

How does one tell IntelliJ that the file is part of an OpenAPI specification, to be validated as such?  One should think this could be inferred from begin $ref'ed from the main spec, but this doesn't work.

Trying to add a $schema value in the referenced file had no effect (and probably isn't in line with the OpenAPI spec anyway).

Manually selecting the OpenAPI 3.0 file type for car.json is not helpful, because then validation (rightly) fails - as it doesn't have the top-level structure required (info, openapi, paths).

Perhaps some specific JSON schema mapping needs to be added in IntelliJ preferences?  If that's the case, it would be actually a sub-schema or some tag in the main OpenAPI spec, how can that be done?

IntelliJ version is: IntelliJ IDEA 2021.3.2 (Ultimate Edition)

Any help would be greatly appreciated.


问:
Odoo 10: How to know if record is already in database or a new one?

I'm working on to compute the average of x records and I don't want to include the last one (the record where I trigger the action).I can trigger the action in existing record or in a new one (not yet in database).

Here is my code:

```<code>@api.one
@api.depends('stc')
def _compute_average_gross(self):
    if self.stc:
        base_seniority = 12
        match_seniority = self.seniority.split()
        total_seniority = int(match_seniority[0]) + int(match_seniority[2]) * 12
        if total_seniority < 12:
            base_seniority = total_seniority if total_seniority else 1  # avoid dividing by 0
        # if the hr.payslip is already in db
        if self._origin.id:
            limit = 13
            # could be self.env.cr.execute()
            sum_sbr = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit)[1:].mapped('line_ids').filtered(lambda x: x.code == 'SBR').mapped('amount'))
            sum_average_gross = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit)[1:].mapped('average_gross'))
        else:
            limit = 12
            # could be self.env.cr.execute()
            sum_sbr = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit).mapped('line_ids').filtered(lambda x: x.code == 'SBR').mapped('amount'))
            sum_average_gross = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit).mapped('average_gross'))
        self.average_gross = round((sum_sbr + sum_average_gross) / base_seniority, 2)
</code>```

With that I got an error that self doesn't have _origin, I trier with origin but got the same error. I also tried with self.context['params'].get('id') but it doesn't work as expected.

Could you help me?

答:
for all who are coming to this after the accepted answer:

the correct solution should be this

```<code>if isinstance(self.id, models.NewId) and not self._origin:
    # record is not saved in database.
    # do your logic

# record is saved in databse
if not isinstance(self.id, models.NewId) or self._origin:
    # ....
</code>```

I'm not sure if _origin already existed in Odoo 10, but needed the same in Odoo 13

I haven't tested in a single record but with res.partner and the partner contacts (field child_ids) and the problem is if you open an existing contact and change any field, odoo transfers the existing record in a new record and you get a false positive answer as the record.id is a new ID but the origin exists in DB

haven't tested with copy functionality but i'm sure oodo is correctly resetting the origin in the new record so my answer should be right

Body:
I'm working on to compute the average of x records and I don't want to include the last one (the record where I trigger the action).I can trigger the action in existing record or in a new one (not yet in database).

Here is my code:

@api.one
@api.depends('stc')
def _compute_average_gross(self):
    if self.stc:
        base_seniority = 12
        match_seniority = self.seniority.split()
        total_seniority = int(match_seniority[0]) + int(match_seniority[2]) * 12
        if total_seniority < 12:
            base_seniority = total_seniority if total_seniority else 1  # avoid dividing by 0
        # if the hr.payslip is already in db
        if self._origin.id:
            limit = 13
            # could be self.env.cr.execute()
            sum_sbr = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit)[1:].mapped('line_ids').filtered(lambda x: x.code == 'SBR').mapped('amount'))
            sum_average_gross = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit)[1:].mapped('average_gross'))
        else:
            limit = 12
            # could be self.env.cr.execute()
            sum_sbr = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit).mapped('line_ids').filtered(lambda x: x.code == 'SBR').mapped('amount'))
            sum_average_gross = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit).mapped('average_gross'))
        self.average_gross = round((sum_sbr + sum_average_gross) / base_seniority, 2)

With that I got an error that self doesn't have _origin, I trier with origin but got the same error. I also tried with self.context['params'].get('id') but it doesn't work as expected.

Could you help me?

Body:
for all who are coming to this after the accepted answer:

the correct solution should be this

if isinstance(self.id, models.NewId) and not self._origin:
    # record is not saved in database.
    # do your logic

# record is saved in databse
if not isinstance(self.id, models.NewId) or self._origin:
    # ....

I'm not sure if _origin already existed in Odoo 10, but needed the same in Odoo 13

I haven't tested in a single record but with res.partner and the partner contacts (field child_ids) and the problem is if you open an existing contact and change any field, odoo transfers the existing record in a new record and you get a false positive answer as the record.id is a new ID but the origin exists in DB

haven't tested with copy functionality but i'm sure oodo is correctly resetting the origin in the new record so my answer should be right


问:
iOS-Charts draw slice text outside the slices in pie chart
I want to draw the slice text outside the slices in pie chart, like in this image:

slice text outside slices

How can I achieve this?

Thanks :)

答:
To do this you can try the following. If using PieChart it will draw the value outside of the slice with some line pointing to the right slice.

```<code>dataSet.yValuePosition = .outsideSlice
</code>```

Above will give you the following result

Body:
To do this you can try the following. If using PieChart it will draw the value outside of the slice with some line pointing to the right slice.

dataSet.yValuePosition = .outsideSlice

Above will give you the following result


问:
Determine what resource was not found from "Error from server (NotFound): the server could not find the requested resource"
I'm running kubectl create -f notRelevantToThisQuestion.yml

The response I get is:

Error from server (NotFound): the server could not find the requested
  resource

Is there any way to determine which resource was requested that was not found?

kubectl get ns returns

NAME          STATUS    AGE
 default       Active    243d

  kube-public   Active    243d
 kube-system   Active    243d

This is not a cron job.

Client version 1.9

Server version 1.6

This is very similar to https://devops.stackexchange.com/questions/2956/how-do-i-get-kubernetes-to-work-when-i-get-an-error-the-server-could-not-find-t?rq=1 but my k8s cluster has been deployed correctly (everything's been working for almost a year, I'm adding a new pod now).

答:
I stumbled upon this question when creating resource from Dashboard.

The resource was namespaced and I had no namespace selected. Selecting namespace fixed the server could not find the requested resource error.


问:
Whats wrong with my Javascript Date Comparison
Im tyring to compare two dates in javascript but im getting strange values when calculating the dates.

Can anyone see anything obvious in my code that is causing the issue?

The problem is the Todays date variable looks like a normal date, but my calculation for next week and last week are coming out as large numbers and the comparison wont work.

```<code>//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek ) {
        alert('Date Under Week');
    }
    if ( date > nextWeek ) {
        alert('Date Over Week');
    }
}
</code>```

And here is the Code in Debug so you can see the values:

EDIT:
Solution

```<code>//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Get the dates in easier to compare format
    nextWeek = new Date(nextWeek);
    lastWeek = new Date(lastWeek);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek) {
        alert('Date Under Week');
    }
    if ( date > nextWeek) {
        alert('Date Over Week');
    }
}
</code>```

答:
Another method is to set dates like this.</p>

```<code>var today = new Date();
var nextWeek = new Date();
nextWeek.setDate(today.getDate() + 7);
var lastWeek = new Date();
lastWeek.setDate(today.getDate() - 7);
</code>```

Body:
Im tyring to compare two dates in javascript but im getting strange values when calculating the dates.

Can anyone see anything obvious in my code that is causing the issue?

The problem is the Todays date variable looks like a normal date, but my calculation for next week and last week are coming out as large numbers and the comparison wont work.

//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek ) {
        alert('Date Under Week');
    }
    if ( date > nextWeek ) {
        alert('Date Over Week');
    }
}

And here is the Code in Debug so you can see the values:

EDIT:
Solution

//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Get the dates in easier to compare format
    nextWeek = new Date(nextWeek);
    lastWeek = new Date(lastWeek);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek) {
        alert('Date Under Week');
    }
    if ( date > nextWeek) {
        alert('Date Over Week');
    }
}

Body:
Another method is to set dates like this.

var today = new Date();
var nextWeek = new Date();
nextWeek.setDate(today.getDate() + 7);
var lastWeek = new Date();
lastWeek.setDate(today.getDate() - 7);


问:
Error downloading celebA dataset using torchvision
Using the torchvision module datasets, I can't download the celebA image dataset.
I am pretty sure that I am doing everything right.

```<code>dataset = datasets.CelebA(
    root='../datasets/celebA/train_images',
    split='train',
    target_type='identity',
    transform=transforms.Compose([transforms.ToTensor()]),
    download=True)
</code>```

The error:

```<code>BadZipFile: File is not a zip file
</code>```

答:
It is a known issue that has been already reported in #1920, and it seems it was fixed in #4109 but the commit is not yet included in a stable release.

In the meanwhile you can do the following:

Look at the source code of datasets.CelebA, search for file_list and take note of the files in it.

Download those files from here, and copy the files in a new directory called celeba

Unzip img_align_celeba.zip in the same directory

Finally call datasets.CelebA() with download=False.

Body:
Using the torchvision module datasets, I can't download the celebA image dataset.
I am pretty sure that I am doing everything right.

dataset = datasets.CelebA(
    root='../datasets/celebA/train_images',
    split='train',
    target_type='identity',
    transform=transforms.Compose([transforms.ToTensor()]),
    download=True)

The error:

BadZipFile: File is not a zip file


问:
DAX PERCENTILE.INC by category in calculated column
I would like to calculate a quartile (ntile) by category using PERCENTILE.INC in a calculated column. My question is a variation to this question:
Equal bins in DAX equivalent of NTILE function

How to modify the accepted solution to the problem if we want to calculate the result by a category?

```<code>Bucket =
VAR N = 4
VAR Percentiles =
    ADDCOLUMNS (
        GENERATESERIES ( 1, N ),
        "Percentile", PERCENTILE.INC ( Table1[Col1], [Value] / N )
    )
RETURN
    MINX ( FILTER ( Percentiles, Table1[Col1] <= [Percentile] ), [Value] )
</code>```

I tried this but the results are not desired values:

```<code>VAR N = 4
VAR Percentiles =
    ADDCOLUMNS(
        CROSSJOIN( VALUES( Tab[Category] ), GENERATESERIES( 1, N ) ),
        "Percentile",
            PERCENTILEX.INC(
                VAR Category = 'Tab'[Category] RETURN FILTER( Tab, 'Tab'[Category] = Category ),
                Tab[Quantity] * 1.0,
                [Value] / N
            )
    )
RETURN
    MINX(
        FILTER(
            Percentiles,
            Tab[Quantity] <= [Percentile]
                && 'Tab'[Category] = [Category]
        ),
        [Value]
    )
</code>```

Edit.

Sample data:

```<code>Table =
DATATABLE (
    "No", INTEGER,
    "Category", STRING,
    "Quantity", DOUBLE,
    {
        {  1 , "apple"  , 1 },
        {  2 , "apple"  , 5 },
        {  3 , "apple"  , 1 },
        {  4 , "apple"  , 4 },
        {  5 , "apple"  , 1 },
        {  6 , "apple"  , 2 },
        {  7 , "apple"  , 5 },
        {  8 , "apple"  , 4 },
        {  9 , "banana" , 9 },
        { 10 , "banana" , 7 },
        { 11 , "banana" , 6 },
        { 12 , "banana" , 4 },
        { 13 , "banana" , 5 },
        { 14 , "banana" , 7 },
        { 15 , "banana" , 8 },
        { 16 , "banana" , 9 }
    }
)
</code>```

答:
I managed to put my solution to work:

```<code>Bucket by Category =
VAR N = 4
VAR Percentiles =
    ADDCOLUMNS(
        CROSSJOIN(
            SELECTCOLUMNS( VALUES( 'Table'[Category] ), "TheCategory", 'Table'[Category] ), // Change column name to new name
            GENERATESERIES( 1, N )
        ),
        "Percentile",
            PERCENTILEX.INC(
                VAR Category = 'Table'[Category] RETURN FILTER( 'Table', 'Table'[Category] = Category ),
                'Table'[Quantity] * 1.0,
                [Value] / N
            )
    )
RETURN
    MINX(
        FILTER(
            Percentiles,
            'Table'[Quantity] <= [Percentile]
                && 'Table'[Category] = [TheCategory] // Here we can reference the new name
        ),
        [Value]
    )
</code>```

It turned out that the only fix was to change the column name of Percentiles table [Category] to something else. So that when we reference the new name [TheCategory] it is clear that we reference Percentiles table and not 'Table'. This solution may not be optimized so I welcome any other solutions.

Body:
I would like to calculate a quartile (ntile) by category using PERCENTILE.INC in a calculated column. My question is a variation to this question:
Equal bins in DAX equivalent of NTILE function

How to modify the accepted solution to the problem if we want to calculate the result by a category?

Bucket =
VAR N = 4
VAR Percentiles =
    ADDCOLUMNS (
        GENERATESERIES ( 1, N ),
        "Percentile", PERCENTILE.INC ( Table1[Col1], [Value] / N )
    )
RETURN
    MINX ( FILTER ( Percentiles, Table1[Col1] <= [Percentile] ), [Value] )

I tried this but the results are not desired values:

VAR N = 4
VAR Percentiles =
    ADDCOLUMNS(
        CROSSJOIN( VALUES( Tab[Category] ), GENERATESERIES( 1, N ) ),
        "Percentile",
            PERCENTILEX.INC(
                VAR Category = 'Tab'[Category] RETURN FILTER( Tab, 'Tab'[Category] = Category ),
                Tab[Quantity] * 1.0,
                [Value] / N
            )
    )
RETURN
    MINX(
        FILTER(
            Percentiles,
            Tab[Quantity] <= [Percentile]
                && 'Tab'[Category] = [Category]
        ),
        [Value]
    )

Edit.

Sample data:

Table =
DATATABLE (
    "No", INTEGER,
    "Category", STRING,
    "Quantity", DOUBLE,
    {
        {  1 , "apple"  , 1 },
        {  2 , "apple"  , 5 },
        {  3 , "apple"  , 1 },
        {  4 , "apple"  , 4 },
        {  5 , "apple"  , 1 },
        {  6 , "apple"  , 2 },
        {  7 , "apple"  , 5 },
        {  8 , "apple"  , 4 },
        {  9 , "banana" , 9 },
        { 10 , "banana" , 7 },
        { 11 , "banana" , 6 },
        { 12 , "banana" , 4 },
        { 13 , "banana" , 5 },
        { 14 , "banana" , 7 },
        { 15 , "banana" , 8 },
        { 16 , "banana" , 9 }
    }
)

Body:
I managed to put my solution to work:

Bucket by Category =
VAR N = 4
VAR Percentiles =
    ADDCOLUMNS(
        CROSSJOIN(
            SELECTCOLUMNS( VALUES( 'Table'[Category] ), "TheCategory", 'Table'[Category] ), // Change column name to new name
            GENERATESERIES( 1, N )
        ),
        "Percentile",
            PERCENTILEX.INC(
                VAR Category = 'Table'[Category] RETURN FILTER( 'Table', 'Table'[Category] = Category ),
                'Table'[Quantity] * 1.0,
                [Value] / N
            )
    )
RETURN
    MINX(
        FILTER(
            Percentiles,
            'Table'[Quantity] <= [Percentile]
                && 'Table'[Category] = [TheCategory] // Here we can reference the new name
        ),
        [Value]
    )

It turned out that the only fix was to change the column name of Percentiles table [Category] to something else. So that when we reference the new name [TheCategory] it is clear that we reference Percentiles table and not 'Table'. This solution may not be optimized so I welcome any other solutions.


问:
How do I correctly override a statically typed method with multiple @overloads (ArgumentParser.parse_args)
I am trying to extend argparse.ArgumentParser.parse_args, but mypy tells me I am doing it wrong:

from argparse import ArgumentParser, Namespace
from typing import Sequence

class MyArgumentParser(ArgumentParser):

    def parse_args(
        self,
        args: Sequence[str] = None,
        namespace: Namespace = None,
    ) -> Namespace:
        parsed_args = super().parse_args(args, namespace)
        # process parsed_args
        return parsed_args
```
<p>I am getting these errors:</p>
```Signature of "parse_args" incompatible with supertype "ArgumentParser"
    Superclass:
        @overload
        def parse_args(self, args: Optional[Sequence[str]] = ...) -> Namespace
        @overload
        def parse_args(self, args: Optional[Sequence[str]], namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, args: Optional[Sequence[str]], namespace: _N) -> _N
        @overload
        def parse_args(self, *, namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, *, namespace: _N) -> _N
    Subclass:
        def parse_args(self, args: Optional[Sequence[str]] = ..., namespace: Optional[Namespace] = ...) -> Namespace
```

I have read https://mypy.readthedocs.io/en/stable/class_basics.html#overriding-statically-typed-methods, but still, a number of things are unclear to me:

Where are these five different method signatures coming from? I can only find a single relevant implementation, here:
https://github.com/python/cpython/blob/f20ca766fe404a20daea29230f161a0eb71bb489/Lib/argparse.py#L1843

Do I have to match one of these signatures, or all of them (using some kind of  superset)?

Why is namespace not optional for all of the signatures, although it clearly is in the above implementation?

What is _N?

答:
All signatures of superclass must be matched. Example:

```<code>class A:
    @overload
    def f(self, a: int) -> int: ...
    @overload
    def f(self, a: str) -> str:...

    def f(self, a) -> str | int:
        return a

class B(A):
    # Mypy: Signature of "f" incompatible with supertype "A"
    # Superclass:
    #   @overload def f(self, a: int) -> int
    #   @overload def f(self, a: str) -> str
    # Subclass:
    #   def f(self, a: int) -> int
    def f(self, a: int) -> int:
        return super().f(a)
</code>```

If you are sure about your signature you can ask mypy to ignore the
override error with type: ignore[override] which ignore only the override error:

```<code>class C(A):
    def f(self, a: int) -> int:  # type: ignore[override]
        return super().f(a)

C().f(3)  # Mypy: OK
C().f('3')  # Mypy: Argument 1 to "f" of "C" has incompatible type
            # "str"; expected "int" [arg-type]
</code>```

Another solution with overload:

```<code>class C(A):
    @overload
    def f(self, a: int) -> int: ...

    @overload
    def f(self, a: str) -> str:...

    def f(self, a: int | str) -> int | str:
        return super().f(a)
</code>```

Another one with TypeVar which works in this simple case:

```<code>T = TypeVar("T", int, str)

class B(A):

    def f(self, a: T) -> T:
        return super().f(a)
</code>```

Note: You can ignore every single Mypy error with ignore[error].
To know the error of Mypy you should launch mypy with --show-error-codes.

Body:
I am trying to extend argparse.ArgumentParser.parse_args, but mypy tells me I am doing it wrong:

from argparse import ArgumentParser, Namespace
from typing import Sequence

class MyArgumentParser(ArgumentParser):

    def parse_args(
        self,
        args: Sequence[str] = None,
        namespace: Namespace = None,
    ) -> Namespace:
        parsed_args = super().parse_args(args, namespace)
        # process parsed_args
        return parsed_args

I am getting these errors:

Signature of "parse_args" incompatible with supertype "ArgumentParser"
    Superclass:
        @overload
        def parse_args(self, args: Optional[Sequence[str]] = ...) -> Namespace
        @overload
        def parse_args(self, args: Optional[Sequence[str]], namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, args: Optional[Sequence[str]], namespace: _N) -> _N
        @overload
        def parse_args(self, *, namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, *, namespace: _N) -> _N
    Subclass:
        def parse_args(self, args: Optional[Sequence[str]] = ..., namespace: Optional[Namespace] = ...) -> Namespace

I have read https://mypy.readthedocs.io/en/stable/class_basics.html#overriding-statically-typed-methods, but still, a number of things are unclear to me:

Where are these five different method signatures coming from? I can only find a single relevant implementation, here:
https://github.com/python/cpython/blob/f20ca766fe404a20daea29230f161a0eb71bb489/Lib/argparse.py#L1843

Do I have to match one of these signatures, or all of them (using some kind of  superset)?

Why is namespace not optional for all of the signatures, although it clearly is in the above implementation?

What is _N?

Body:
All signatures of superclass must be matched. Example:

class A:
    @overload
    def f(self, a: int) -> int: ...
    @overload
    def f(self, a: str) -> str:...

    def f(self, a) -> str | int:
        return a

class B(A):
    # Mypy: Signature of "f" incompatible with supertype "A"
    # Superclass:
    #   @overload def f(self, a: int) -> int
    #   @overload def f(self, a: str) -> str
    # Subclass:
    #   def f(self, a: int) -> int
    def f(self, a: int) -> int:
        return super().f(a)

If you are sure about your signature you can ask mypy to ignore the
override error with type: ignore[override] which ignore only the override error:

class C(A):
    def f(self, a: int) -> int:  # type: ignore[override]
        return super().f(a)

C().f(3)  # Mypy: OK
C().f('3')  # Mypy: Argument 1 to "f" of "C" has incompatible type
            # "str"; expected "int" [arg-type]

Another solution with overload:

class C(A):
    @overload
    def f(self, a: int) -> int: ...

    @overload
    def f(self, a: str) -> str:...

    def f(self, a: int | str) -> int | str:
        return super().f(a)

Another one with TypeVar which works in this simple case:

T = TypeVar("T", int, str)

class B(A):

    def f(self, a: T) -> T:
        return super().f(a)

Note: You can ignore every single Mypy error with ignore[error].
To know the error of Mypy you should launch mypy with --show-error-codes.


问:
How to test button that on click renders html element within the same component in React testing library, Jest?
My OrderModuleHeader is a clickable div that renders div when clicked like shown below:

```<code> const [orderModuleIsOpen, setOrderModuleIsOpen] = useState(true);

render (
<div>

     <OrderModuleHeader data-testid="orderModuleHeaderButton"
              onClick={() => setOrderModuleIsOpen(!orderModuleIsOpen)}
            >
              <NavigationArrow>
                <FontAwesomeIcon
                  icon={orderModuleIsOpen ? faChevronUp : faChevronDown}
                  className="fa-xs"
                />
              </NavigationArrow>
     </OrderModuleHeader>
            {orderModuleIsOpen && (
              <OrderModuleBody>Some content</OrderModuleBody>
)
 </div>)
</code>```

So div OrderModuleBody is displayed only when we click the button.

I started my test by the following:

```<code>describe('Expand body button', () => {
it('should render OrderModuleBody when clicked', () => {
      const button = screen.getByTestId('orderModuleHeaderButton');

      fireEvent.change() ...
    });
}
</code>```

I realize that I made div clickable and in test I call it a button.

I don't know what exactly I need to write in fireEvent to test if OrderModuleBody (div) renders on click.

NOTE: I'm not allowed to bring in shallow method from Enzyme or use any other testing frameworks except Jest, React testing library.

Any advice is appreciated.

答:
You'll need to render your component in order to test it. You then access the button after which you simulate a button click, and then eventually expect your change to occur.

The testing library has a function named userEvent which can simulate a button click.

```<code>import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

describe('Expand body button', async () => {
    it('should render OrderModuleBody when clicked', () => {
        // render your component
        render(<YourComponent />)
        // access your button
        const button = screen.getByTestId('orderModuleHeaderButton')
        // simulate button click
        userEvent.click(button);

        // expect result
        await waitFor(() =>
            expect(screen.getByText("Some content")).toBeInTheDocument();
       });
}
</code>```

Body:
My OrderModuleHeader is a clickable div that renders div when clicked like shown below:

 const [orderModuleIsOpen, setOrderModuleIsOpen] = useState(true);

render (

     <OrderModuleHeader data-testid="orderModuleHeaderButton"
              onClick={() => setOrderModuleIsOpen(!orderModuleIsOpen)}
            >
              <NavigationArrow>
                <FontAwesomeIcon
                  icon={orderModuleIsOpen ? faChevronUp : faChevronDown}
                  className="fa-xs"
                />
              </NavigationArrow>
     </OrderModuleHeader>
            {orderModuleIsOpen && (
              <OrderModuleBody>Some content</OrderModuleBody>
)

)

So div OrderModuleBody is displayed only when we click the button.

I started my test by the following:

describe('Expand body button', () => {
it('should render OrderModuleBody when clicked', () => {
      const button = screen.getByTestId('orderModuleHeaderButton');

      fireEvent.change() ...
    });
}

I realize that I made div clickable and in test I call it a button.

I don't know what exactly I need to write in fireEvent to test if OrderModuleBody (div) renders on click.

NOTE: I'm not allowed to bring in shallow method from Enzyme or use any other testing frameworks except Jest, React testing library.

Any advice is appreciated.

Body:
You'll need to render your component in order to test it. You then access the button after which you simulate a button click, and then eventually expect your change to occur.

The testing library has a function named userEvent which can simulate a button click.

import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

describe('Expand body button', async () => {
    it('should render OrderModuleBody when clicked', () => {
        // render your component
        render(<YourComponent />)
        // access your button
        const button = screen.getByTestId('orderModuleHeaderButton')
        // simulate button click
        userEvent.click(button);

        // expect result
        await waitFor(() =>
            expect(screen.getByText("Some content")).toBeInTheDocument();
       });
}


问:
js function to get filename from url
I have a url like http://www.example.com/blah/th.html

I need a javascript function to give me the 'th' value from that.

All my urls have the same format (2 letter filenames, with .html extension).

I want it to be a safe function, so if someone passes in an empty url it doesn't break.

I know how to check for length, but I should be checking for null to right?

答:
Simple Function (Using RegEx Pattern)

function pathInfo(s) {
    s=s.match(/(.*?\/)?(([^/]*?)(\.[^/.]+?)?)(?:[?#].*)?$/);
    return {path:s[1],file:s[2],name:s[3],ext:s[4]};
}

var sample='/folder/another/file.min.js?query=1';
var result=pathInfo(sample);
console.log(result);
/*
{
  "path": "/folder/another/",
  "file": "file.min.js",
  "name": "file.min",
  "ext": ".js"
}
*/
console.log(result.name);```

OwnerDisplayName: Blankman

ContentLicense: CC BY-SA 2.5

Title: js function to get filename from url


问:
How to set a type of an array in an anonymous Object
How do I set the type of the array, because grid: []: number[] wont work

```<code>const game = {
  sizeX: 9,
  sizeY: 5,
  SCALE: 80,
  grid: [],  //Object literal's property 'grid' implicitly has an 'any[]' type.
  money: 600,
}
</code>```

答:
You can type the whole object: (This is strongly recommended)

```<code>interface Game {
  sizeX: number
  sizeY: number
  SCALE: number
  grid: number[]
}

const game: Game = {
  sizeX: 9,
  sizeY: 5,
  SCALE: 80,
  grid: [],
  money: 600,
}
</code>```

Or you can cast the empty array:

```<code>grid: [] as number[]
</code>```

Or you can make the array non empty:

```<code>grid: [123]
</code>```

To name a few

Body:
How do I set the type of the array, because grid: []: number[] wont work

const game = {
  sizeX: 9,
  sizeY: 5,
  SCALE: 80,
  grid: [],  //Object literal's property 'grid' implicitly has an 'any[]' type.
  money: 600,
}

Body:
You can type the whole object: (This is strongly recommended)

interface Game {
  sizeX: number
  sizeY: number
  SCALE: number
  grid: number[]
}

const game: Game = {
  sizeX: 9,
  sizeY: 5,
  SCALE: 80,
  grid: [],
  money: 600,
}

Or you can cast the empty array:

grid: [] as number[]

Or you can make the array non empty:

grid: [123]

To name a few


问:
Recursively search a table in VBA
I have a BOM that I can get a structured look like this, where it pulls for all my products.

I'm trying to pull all members of a particular BOM recursively through VBA. so far I can get the top level items, but I cannot get anything beyond that. Can someone point me in the right direction with my code on what I need to do next? IF something better than recursion could work here I could do that as well, it was just my initial thought.

```<code>'getMembers gets all items of the member field
    Function getMembers(member As String) As Variant
        'declare range of BOM
        Dim rng As range
        Set rng = Worksheets("Allboms").range("All_Boms[name]")

        Dim i As Integer
        i = 0
        Dim members() As String
        ReDim members(1)

        For Each cell In rng
            If cell.Value = member Then
                members(i) = cell.Offset(, 4).Value
                i = i + 1
                ReDim Preserve members(i)
            End If
        Next
        getMembers = members
    End Function

Sub getMemberItems()
    'declare where product is
    Dim product As String
    product = range("C3").Value
    Dim item As Variant

    For Each item In getMembers(product)
        Debug.print item
    Next item

End Sub
</code>```

答:
Non-recursive approach using a Collection as a queue:

Sub Tester()
    Dim m
    For Each m In getMembers("A")
        Debug.Print m
    Next m
End Sub

'getMembers gets all items of the member field
Function getMembers(member As String) As Collection
    Dim rng As Range, c As Range
    Dim rv As New Collection, q As New Collection, m, v

    Set rng = Worksheets("Allboms").Range("All_Boms[name]")
    q.Add member 'start the queue

    Do While q.Count > 0
        m = q(1)
        q.Remove 1
        For Each c In rng.Cells
            If c.Value = m Then
                v = c.Offset(, 4).Value
                If Not IsError(Application.Match(v, rng, 0)) Then
                    q.Add v  'has sub-members: add to queue
                Else
                    rv.Add v 'no sub-members: add to output
                End If
            End If
        Next
    Loop
    Set getMembers = rv
End Function
```

Title: Recursively search a table in VBA

Body:
I have a BOM that I can get a structured look like this, where it pulls for all my products.

I'm trying to pull all members of a particular BOM recursively through VBA. so far I can get the top level items, but I cannot get anything beyond that. Can someone point me in the right direction with my code on what I need to do next? IF something better than recursion could work here I could do that as well, it was just my initial thought.

'getMembers gets all items of the member field
    Function getMembers(member As String) As Variant
        'declare range of BOM
        Dim rng As range
        Set rng = Worksheets("Allboms").range("All_Boms[name]")

        Dim i As Integer
        i = 0
        Dim members() As String
        ReDim members(1)

        For Each cell In rng
            If cell.Value = member Then
                members(i) = cell.Offset(, 4).Value
                i = i + 1
                ReDim Preserve members(i)
            End If
        Next
        getMembers = members
    End Function

Sub getMemberItems()
    'declare where product is
    Dim product As String
    product = range("C3").Value
    Dim item As Variant

    For Each item In getMembers(product)
        Debug.print item
    Next item

End Sub


问:
When a file is copied from usb flash, why does its speed increase and decrease?
Why does this happens when I try to copy my files to/from a usb flash memory? What causes this fluctuation?

答:
File transfer speed depends both on file size and the number of files. As the size and type of file being copied changes the speed will fluctuate. You can read more here:
https://www.reddit.com/r/explainlikeimfive/comments/2ve4g6/eli5_why_do_pc_to_usb_transfer_rates_mbs/</p>


问:
How do I add a document reference with an auto generated ID when writing a batch in Firebase?
When doing normal transactions in Firebase you can just use the .add function to add a new document with an auto generated ID; however, when doing a batch write with Web version 9 of the API I cannot find any documentation on how to add a new document with a auto generated ID. Currently I have the following code which is not working:

let ref = doc(db, "projects", doc())
batch.add(ref, element);
await batch.commit();```

This throws the error "Function doc() cannot be called with an empty path.". In Web version 8 this worked apparently by just calling .doc(). How does one accomplish this?

答:
According to the Firebase documentation on adding a document:

In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc():

```<code>import { collection, doc, setDoc } from "firebase/firestore";

// Add a new document with a generated id
const newCityRef = doc(collection(db, "cities"));

// later...
await setDoc(newCityRef, data);
</code>```

So it seems you'll need:

```<code>let ref = doc(db, collection("projects"))
</code>```

Body:
When doing normal transactions in Firebase you can just use the .add function to add a new document with an auto generated ID; however, when doing a batch write with Web version 9 of the API I cannot find any documentation on how to add a new document with a auto generated ID. Currently I have the following code which is not working:

let ref = doc(db, "projects", doc())
batch.add(ref, element);
await batch.commit();

This throws the error "Function doc() cannot be called with an empty path.". In Web version 8 this worked apparently by just calling .doc(). How does one accomplish this?

Body:
According to the Firebase documentation on adding a document:

In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc():

import { collection, doc, setDoc } from "firebase/firestore";

// Add a new document with a generated id
const newCityRef = doc(collection(db, "cities"));

// later...
await setDoc(newCityRef, data);

So it seems you'll need:

let ref = doc(db, collection("projects"))


问:
Unable to reconnect container created by "Clone Repository in Container Volume" easily?
I started with a blank new window and use the command Remote-Containers: Clone Repository in Container Volume to clone a git hub repo that I wanted to work with. This spawned a container in which I made some changes. However, after I close the window, it seems there's no way for me to re-open that container easily in VS Code. I had to manually restart that container in the shell and use the command Remote-Containers: Attach to Running Container to continue my development. What I'm missing here? or this is what it is?

答:
Perhaps a slightly easier way would be to use the Docker extension. You can right-click on a container and select "Attach Visual Studio Code".

Screenshot


问:
(Windows) Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)
I see that is question is asked a lot, but I cannot find solutions for Windows but only for Ubuntu. I amtrying to follow an sql tutorial, so I installed everything but I keep getting this error.

Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)

The server service is running and I am not sure where to start. I also cannot find the file mysql.nfc that I thought I needed....
Can somebody help?

答: Try switching the Connection Type to local: Edit your connection.</p>