问:
How to create a class that returns different objects
I am trying to do the following:

#A wrapper object that based on it's parameters returns other objects
class A():
   def __new__(cls, config):
     if config.type == "1":
       return C(config)
     elif config.type == "2":
       return D(config)
```

How do you call this pattern and how do you do it in python? __new__ doesn't seem to accept arguments.

答:
__new__ does accept arguments and it can be used as a factory for other classes like your example attempts to do. From The standard type hierarchy

Classes are callable. These objects normally act as factories for new
instances of themselves, but variations are possible for class types
that override new(). The arguments of the call are passed to
new() and, in the typical case, to init() to initialize the new instance.

A working example is

```<code>class C:

    def __init__(self, val):
        self.what = "C"
        print("i am C")

class D:

    def __init__(self, val):
        self.what = "D"
        print("i am D")

class A():
   def __new__(cls, config):
     if config == "1":
       return C(config)
     elif config == "2":
       return D(config)

foo = A("1")
print(foo.what, type(foo))
bar = A("2")
print(bar.what, type(bar))
</code>```

Body:
I am trying to do the following:

#A wrapper object that based on it's parameters returns other objects
class A():
   def __new__(cls, config):
     if config.type == "1":
       return C(config)
     elif config.type == "2":
       return D(config)

How do you call this pattern and how do you do it in python? __new__ doesn't seem to accept arguments.

Body:
__new__ does accept arguments and it can be used as a factory for other classes like your example attempts to do. From The standard type hierarchy

Classes are callable. These objects normally act as factories for new
instances of themselves, but variations are possible for class types
that override new(). The arguments of the call are passed to
new() and, in the typical case, to init() to initialize the new instance.

A working example is

class C:

    def __init__(self, val):
        self.what = "C"
        print("i am C")

class D:

    def __init__(self, val):
        self.what = "D"
        print("i am D")

class A():
   def __new__(cls, config):
     if config == "1":
       return C(config)
     elif config == "2":
       return D(config)

foo = A("1")
print(foo.what, type(foo))
bar = A("2")
print(bar.what, type(bar))


来源: stackexchange

问:
Replace a dependency version in pom.xml programmatically?
Assuming I have a pom.xml containing a parent dependency like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.example</groupId>
        <artifactId>some-parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
</project>
</code>```

Is there a way I can replace the 1.0.0-SNAPSHOT version programmatically, maybe via a script?

My use case:

I have lots of pom.xml files that I need to change the parent version of

I'm using git-xargs to make changes across multiple repos, so I can apply a bash script to each pom.xml to change it.

For example, I can do the following, but this will update all occurrences of 1.0.0-SNAPSHOT in the pom.xml, and I want to limit it to just the some-parent artifact that has a version 1.0.0-SNAPSHOT:

```<code>git-xargs \
  --branch-name test-branch \
  --github-org <your-github-org> \
  --commit-message "Update pom.xml" \
  sed -i 's/1.0.0-SNAPSHOT/2.0.1/g' pom.xml
</code>```

As per the git-xargs docs, I can use any type of script to process the pom.xml, bash, python, ruby etc: https://github.com/gruntwork-io/git-xargs#how-to-supply-commands-or-scripts-to-run

UPDATE:

The following xmlstarlet approach works up to a point:

```<code>if [[ $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:artifactId' pom.xml) == "some-parent" && $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:version' pom.xml) == "1.0.0-SNAPSHOT" ]]; then xmlstarlet edit -L -N my=http://maven.apache.org/POM/4.0.0 --update '//my:project/my:parent/my:version' --value '2.0.6' pom.xml; fi
</code>```

xmlstarlet is correctly updating the xml element I want, but its also reordering the xsi:schemaLocation, xmlns and xmlns:xsi at the top of my file.

It's updating it from:

```<code><project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</code>```

to:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
</code>```

which is no good for me.

答:
You could use xq.

Just setting a certain element to a new value would be as simple as

xq -x '.project.parent.version = "2.0.1"' pom.xml
```
<p>Setting it on condition would be</p>
<pre class="lang-sh prettyprint-override"><code>xq -x '(.project.parent | select(
  .artifactId == "some-parent" and .version == "1.0.0-SNAPSHOT"
)).version = "2.0.1"' pom.xml
</code>```

Fed with the sample data, both would produce

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.example</groupId>
    <artifactId>some-parent</artifactId>
    <version>2.0.1</version>
  </parent>
</project>
```
<p>As you can see, the <strong>order</strong> of the attributes stays the same, however the <strong>indentation</strong> is different, especially your in-tag <strong>line breaks</strong> were swallowed. Also, the <strong>XML declaration</strong> (first line) is missing, as would <strong>comments</strong>, if present in the input. Maybe this isn't viable for you either, but consider</p>
<ul>
<li>editing the logical structure (rather than its textual representation) is less error-prone,</li>
<li>all of these issues (except for the missing comments, of course) could easily be remedied using one of many XML pretty-printers available for the command-line. This is a (non-exhaustive) list of where to go from here.</li>
</ul>
<p>For instance, let's go with tidy.</p>
<p>With this configuration</p>
<pre class="lang-sh prettyprint-override"><code>xq -x '…' pom.xml |
tidy -xml -iq -utf8 --indent-with-tabs yes --indent-spaces 4 --tab-size 4 \
  --indent-attributes yes --add-xml-decl yes
</code>```

you would get as far as

<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>some-parent</artifactId>
        <version>2.0.1</version>
    </parent>
</project>
```

For what I can see, this is still lacking the encoding="UTF-8" in the top-line declaration (tidy refuses to print obvious declarations), and the indentation of the attributes is still off by 1 character. If this is still an issue, try playing around with the other pretty-printers out there. Chances are you'll find the right one for the perfect finishing.

ContentLicense: CC BY-SA 4.0

Body:
Assuming I have a pom.xml containing a parent dependency like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.example</groupId>
        <artifactId>some-parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
</project>

Is there a way I can replace the 1.0.0-SNAPSHOT version programmatically, maybe via a script?

My use case:

I have lots of pom.xml files that I need to change the parent version of

I'm using git-xargs to make changes across multiple repos, so I can apply a bash script to each pom.xml to change it.

For example, I can do the following, but this will update all occurrences of 1.0.0-SNAPSHOT in the pom.xml, and I want to limit it to just the some-parent artifact that has a version 1.0.0-SNAPSHOT:

git-xargs \
  --branch-name test-branch \
  --github-org <your-github-org> \
  --commit-message "Update pom.xml" \
  sed -i 's/1.0.0-SNAPSHOT/2.0.1/g' pom.xml

As per the git-xargs docs, I can use any type of script to process the pom.xml, bash, python, ruby etc: https://github.com/gruntwork-io/git-xargs#how-to-supply-commands-or-scripts-to-run

UPDATE:

The following xmlstarlet approach works up to a point:

if [[ $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:artifactId' pom.xml) == "some-parent" && $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:version' pom.xml) == "1.0.0-SNAPSHOT" ]]; then xmlstarlet edit -L -N my=http://maven.apache.org/POM/4.0.0 --update '//my:project/my:parent/my:version' --value '2.0.6' pom.xml; fi

xmlstarlet is correctly updating the xml element I want, but its also reordering the xsi:schemaLocation, xmlns and xmlns:xsi at the top of my file.

It's updating it from:

<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

to:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

which is no good for me.

Body:
You could use xq.

Just setting a certain element to a new value would be as simple as

xq -x '.project.parent.version = "2.0.1"' pom.xml

Setting it on condition would be

xq -x '(.project.parent | select(
  .artifactId == "some-parent" and .version == "1.0.0-SNAPSHOT"
)).version = "2.0.1"' pom.xml

Fed with the sample data, both would produce

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.example</groupId>
    <artifactId>some-parent</artifactId>
    <version>2.0.1</version>
  </parent>
</project>

As you can see, the order of the attributes stays the same, however the indentation is different, especially your in-tag line breaks were swallowed. Also, the XML declaration (first line) is missing, as would comments, if present in the input. Maybe this isn't viable for you either, but consider

editing the logical structure (rather than its textual representation) is less error-prone,

all of these issues (except for the missing comments, of course) could easily be remedied using one of many XML pretty-printers available for the command-line. This is a (non-exhaustive) list of where to go from here.

For instance, let's go with tidy.

With this configuration

xq -x '…' pom.xml |
tidy -xml -iq -utf8 --indent-with-tabs yes --indent-spaces 4 --tab-size 4 \
  --indent-attributes yes --add-xml-decl yes

you would get as far as

<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>some-parent</artifactId>
        <version>2.0.1</version>
    </parent>
</project>

For what I can see, this is still lacking the encoding="UTF-8" in the top-line declaration (tidy refuses to print obvious declarations), and the indentation of the attributes is still off by 1 character. If this is still an issue, try playing around with the other pretty-printers out there. Chances are you'll find the right one for the perfect finishing.


问:
Use PowerShell to extract GPS Latitude etc. (Properties > Details) from an image file
I am looking for a way to extract the GPS Latitude and Longitude values from a lot of .jpg files.

I know that Exiftool can sort of do it, but as the values I'm after are visible in Windows 10 Explorer for that file (Properties > Detail > GPS heading > Latitude)... Can I use PS to directly grab them? I'm assuming it would be quicker that way.

I know how to extract $img.FullName etc., but can't get to Latitude this way.

答:
Using @dwids and @stackprotector answers, I came up with the following to run through all files in a folder.  It's not the tidiest, but it's self explanatory:

```<code>cls

$FolderPath = "c:\MyFolder"

Get-ChildItem $FolderPath -Filter *.* | where { ! $_.PSIsContainer } |
Foreach-Object {
    # Get the file name and path, write it out to screen
    $FileName = $_.FullName
    Write-Host "$FileName"

    # Create an ImageFile object and load an image file
    $image = New-Object -ComObject Wia.ImageFile
    $image.LoadFile($FileName)

    # Read your desirered metadata, if it doesn't contain any, say NONE
    try
    {
        #Clear variables for Lat and Lon
        Clear-Variable Lat*
        Clear-Variable Lon*
        $LatDEG = $image.Properties.Item('GpsLatitude').Value[1].Value
        $LatMIN = $image.Properties.Item('GpsLatitude').Value[2].Value
        $LatSEC = $image.Properties.Item('GpsLatitude').Value[3].Value
        $LatREF = $image.Properties.Item('GpsLatitudeRef').Value
        $LonDEG = $image.Properties.Item('GpsLongitude').Value[1].Value
        $LonMIN = $image.Properties.Item('GpsLongitude').Value[2].Value
        $LonSEC = $image.Properties.Item('GpsLongitude').Value[3].Value
        $LonREF = $image.Properties.Item('GpsLongitudeRef').Value

        # Convert them to Degrees Minutes Seconds Ref
        $LatSTR = "$LatDEG$([char]176) $LatMIN$([char]39) $LatSEC$([char]34) $LatREF"
        $LonSTR = "$LonDEG$([char]176) $LonMIN$([char]39) $LonSEC$([char]34) $LonREF"

        # Write the full coordinates out
        Write-Host "$LatSTR $LonSTR"
    }
    catch
    {
        Write-Host "NONE"
    }
}
</code>```

Obviously you can remove the Write-Host "$FileName" (file path and name) if you just want a list of coordinates.  Or you can change it to Write-Host "$_" if you only want the file name.

You can add -Recurse to Get-ChildItem $FolderPath -Filter *.* | so it would be Get-ChildItem $FolderPath -Filter *.* -Recurse | to look at all files in all sub-folders.

Body:
Using @dwids and @stackprotector answers, I came up with the following to run through all files in a folder.  It's not the tidiest, but it's self explanatory:

cls

$FolderPath = "c:\MyFolder"

Get-ChildItem $FolderPath -Filter *.* | where { ! $_.PSIsContainer } |
Foreach-Object {
    # Get the file name and path, write it out to screen
    $FileName = $_.FullName
    Write-Host "$FileName"

    # Create an ImageFile object and load an image file
    $image = New-Object -ComObject Wia.ImageFile
    $image.LoadFile($FileName)

    # Read your desirered metadata, if it doesn't contain any, say NONE
    try
    {
        #Clear variables for Lat and Lon
        Clear-Variable Lat*
        Clear-Variable Lon*
        $LatDEG = $image.Properties.Item('GpsLatitude').Value[1].Value
        $LatMIN = $image.Properties.Item('GpsLatitude').Value[2].Value
        $LatSEC = $image.Properties.Item('GpsLatitude').Value[3].Value
        $LatREF = $image.Properties.Item('GpsLatitudeRef').Value
        $LonDEG = $image.Properties.Item('GpsLongitude').Value[1].Value
        $LonMIN = $image.Properties.Item('GpsLongitude').Value[2].Value
        $LonSEC = $image.Properties.Item('GpsLongitude').Value[3].Value
        $LonREF = $image.Properties.Item('GpsLongitudeRef').Value

        # Convert them to Degrees Minutes Seconds Ref
        $LatSTR = "$LatDEG$([char]176) $LatMIN$([char]39) $LatSEC$([char]34) $LatREF"
        $LonSTR = "$LonDEG$([char]176) $LonMIN$([char]39) $LonSEC$([char]34) $LonREF"

        # Write the full coordinates out
        Write-Host "$LatSTR $LonSTR"
    }
    catch
    {
        Write-Host "NONE"
    }
}

Obviously you can remove the Write-Host "$FileName" (file path and name) if you just want a list of coordinates.  Or you can change it to Write-Host "$_" if you only want the file name.

You can add -Recurse to Get-ChildItem $FolderPath -Filter *.* | so it would be Get-ChildItem $FolderPath -Filter *.* -Recurse | to look at all files in all sub-folders.


问:
Google Sheet SUMIFS formula returning 0?
I have a SUMIFS formula in Google Sheets which is the following:

=SUMIFS('AWIN MASTER'!$AW:$AW,'AWIN MASTER'!$AT:$AT,">=" &A101,'AWIN MASTER'!$AT:$AT,"<" &A102)

This formula is the sum of a cost on another sheet, when the date is between two dates on the current sheet.

which is returning 0 when it shouldn't... it's working for my other formula but not mine... Could someone help please?

答:
try:

```<code>=SUM(IFERROR(FILTER('AWIN MASTER'!AW:AW;
                    'AWIN MASTER'!AT:AT >= A101;
                    'AWIN MASTER'!AT:AT <  A102)))
</code>```

or see if you got the right conditions:

```<code>=FILTER('AWIN MASTER'!AW:AW;
        'AWIN MASTER'!AT:AT >= A101;
        'AWIN MASTER'!AT:AT <  A102)
</code>```

Body:
try:

=SUM(IFERROR(FILTER('AWIN MASTER'!AW:AW;
                    'AWIN MASTER'!AT:AT >= A101;
                    'AWIN MASTER'!AT:AT <  A102)))

or see if you got the right conditions:

=FILTER('AWIN MASTER'!AW:AW;
        'AWIN MASTER'!AT:AT >= A101;
        'AWIN MASTER'!AT:AT <  A102)


问:
Kusto table - How to recover soft-deleted data that is retained by the Recoverability = enabled set
I have a Kusto database with the following retention policy:

```<code>{
  "SoftDeletePeriod": "30.00:00:00",
  "Recoverability": "Enabled"
}
</code>```

Yesterday some data was removed from a table in the database since it was over 30 days old.

According to the retention policy docs, if the Recoverability attribute is set, "If set to Enabled, the data will be recoverable for 14 days after it's been soft-deleted."

My question is what is the query I execute to recover the soft-deleted data that has been lost?

I'm guessing it's something like:

.<name-of-command> table <tableName>;? Maybe there's an option somewhere to specify just how many days to recover? How do I recover soft-deleted data that is retained by the Recoverability=enabled set?

答: Such a recovery currently requires opening a support ticket, via the Azure portal:

Body:
I have a Kusto database with the following retention policy:

{
  "SoftDeletePeriod": "30.00:00:00",
  "Recoverability": "Enabled"
}

Yesterday some data was removed from a table in the database since it was over 30 days old.

According to the retention policy docs, if the Recoverability attribute is set, "If set to Enabled, the data will be recoverable for 14 days after it's been soft-deleted."

My question is what is the query I execute to recover the soft-deleted data that has been lost?

I'm guessing it's something like:

.<name-of-command> table <tableName>;? Maybe there's an option somewhere to specify just how many days to recover? How do I recover soft-deleted data that is retained by the Recoverability=enabled set?


问:
Confused when I should and shouldn't use "const" in C
I have a dictionary that goes like this:

```<code>typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;
</code>```

And a get() function that goes like this:

```<code>char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}
</code>```

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

```<code>Dict *currPtr = dict;
</code>```

If I add a "const" before that line like this:

```<code>const Dict *currPtr = dict;
</code>```

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

```<code>Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}
</code>```

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

答:
Keep in mind that const may appear on either or both sides of * in a pointer declaration, and that's semantically significant...

```<code>const char * foo = bar;
</code>```

is not the same as

```<code>char * const foo = bar;
</code>```

The first says the content is const, and the second says the pointer is const.

For maximal constness there's:

```<code>const char * const foo = bar;
</code>```

OwnerDisplayName: Nazgulled

ContentLicense: CC BY-SA 2.5

Body:
I have a dictionary that goes like this:

typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;

And a get() function that goes like this:

char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

Dict *currPtr = dict;

If I add a "const" before that line like this:

const Dict *currPtr = dict;

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

Body:
Keep in mind that const may appear on either or both sides of * in a pointer declaration, and that's semantically significant...

const char * foo = bar;

is not the same as

char * const foo = bar;

The first says the content is const, and the second says the pointer is const.

For maximal constness there's:

const char * const foo = bar;

OwnerDisplayName: dwc

LastEditorDisplayName: dwc


问:
What is the easiest way to generate a String of n repeated characters?
Given a character c and a number n, how can I create a String that consists of n repetitions of c? Doing it manually is too cumbersome:

```<code>StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
{
    sb.append(c);
}
String result = sb.toString();
</code>```

Surely there is some static library function that already does this for me?

答:
If you can, use StringUtils from Apache Commons Lang:</p>

```<code>StringUtils.repeat("ab", 3);  //"ababab"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given a character c and a number n, how can I create a String that consists of n repetitions of c? Doing it manually is too cumbersome:

StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
{
    sb.append(c);
}
String result = sb.toString();

Surely there is some static library function that already does this for me?

Body:
If you can, use StringUtils from Apache Commons Lang:

StringUtils.repeat("ab", 3);  //"ababab"


问:
AWS Codebuild Buildspec Terraform init backend error
I am trying to initialize my backend for the first time via AWS Codebuild.  Up until this point I have been able to run the initial deployment.  Once the Terraform Apply has been completed I try to initialize the backend and move it to S3. Here is the code post apply running with an active statefile in the directory:

Buildspec Section

```<code>- |
    echo "" >> main.tf
    echo "" >> main.tf
    echo "terraform { " >> main.tf
    echo "   backend \"s3\" { " >> main.tf
    echo "  }" >> main.tf
    echo "}" >> main.tf
    echo "yes" | terraform init \
      -backend-config="bucket=${backend_env}" \
      -backend-config="key=global/state/${bucketconfig}/terraform.tfstate" \
      -backend-config="region=us-east-1" \
      -backend-config="encrypt=true" \
      -backend-config="kms_key_id=${kmykeyid}" \
      -backend-config="dynamodb_table=iha-${tf_appenv}-${tf_tenant}-db-${bucketconfig}"
- echo "Complete"
</code>```

Now note everything has worked up until the point where I add the backend configuration. As you also notice I have attempted to add the s3 resource dynamically which works.  By running cat main.tf I am able to see that the s3 backend resource has been added to the file.

```<code>terraform {
  backend "s3" {

  }
}
</code>```

I have validated all the variables and made sure all buckets and resources exist.  I can't figure out why it's failing.  One more note the sample code you see there is in the build spec file and its in a multiline section.

I am not exactly sure what's causing the issue with the command line CLI and I am looking for anyone to point me in the right direction.

答:
After trying a few things i got this version to work.

```<code>echo "yes" | terraform init -backend-config="bucket=${backend_env}" -backend-config="key=global/s3/state/${bucketconfig}/terraform.tfstate" -backend-config="region=us-east-1" -backend-config="encrypt=true" -backend-config="kms_key_id=${kmskeyid}" -backend-config="dynamodb_table=iha-${tf_appenv}-${tf_tenant}-db-${bucketconfig}"
</code>```

My issue was that the backend would not initialize.  I do believe the other syntax works but I am probably sending it through incorrectly.  That said this worked.  Appreciate the help from others who tried to help with this problem.

Body:
I am trying to initialize my backend for the first time via AWS Codebuild.  Up until this point I have been able to run the initial deployment.  Once the Terraform Apply has been completed I try to initialize the backend and move it to S3. Here is the code post apply running with an active statefile in the directory:

Buildspec Section

- |
    echo "" >> main.tf
    echo "" >> main.tf
    echo "terraform { " >> main.tf
    echo "   backend \"s3\" { " >> main.tf
    echo "  }" >> main.tf
    echo "}" >> main.tf
    echo "yes" | terraform init \
      -backend-config="bucket=${backend_env}" \
      -backend-config="key=global/state/${bucketconfig}/terraform.tfstate" \
      -backend-config="region=us-east-1" \
      -backend-config="encrypt=true" \
      -backend-config="kms_key_id=${kmykeyid}" \
      -backend-config="dynamodb_table=iha-${tf_appenv}-${tf_tenant}-db-${bucketconfig}"
- echo "Complete"

Now note everything has worked up until the point where I add the backend configuration. As you also notice I have attempted to add the s3 resource dynamically which works.  By running cat main.tf I am able to see that the s3 backend resource has been added to the file.

terraform {
  backend "s3" {

  }
}

I have validated all the variables and made sure all buckets and resources exist.  I can't figure out why it's failing.  One more note the sample code you see there is in the build spec file and its in a multiline section.

I am not exactly sure what's causing the issue with the command line CLI and I am looking for anyone to point me in the right direction.

Body:
After trying a few things i got this version to work.

echo "yes" | terraform init -backend-config="bucket=${backend_env}" -backend-config="key=global/s3/state/${bucketconfig}/terraform.tfstate" -backend-config="region=us-east-1" -backend-config="encrypt=true" -backend-config="kms_key_id=${kmskeyid}" -backend-config="dynamodb_table=iha-${tf_appenv}-${tf_tenant}-db-${bucketconfig}"

My issue was that the backend would not initialize.  I do believe the other syntax works but I am probably sending it through incorrectly.  That said this worked.  Appreciate the help from others who tried to help with this problem.


问:
List operation, keeping track of old list
After I apply an operation to a list, I would like to get access to both the modified list and the original one.
Somehow I am not able to.

In the following code snippet, I define two functions with which I modify the original list.
Afterwards, I get my values from a class and apply the transformation.

```<code>def get_min_by_col(li, col):                          # get minimum from list
    return min(li, key=lambda x: x[col - 1])[col - 1]

def hashCluster(coords):                              # transform to origin
    min_row = get_min_by_col(coords,0)
    min_col = get_min_by_col(coords,1)
    for pix in coords:
        pix[1] = pix[1] - min_row
        pix[0] = pix[0] - min_col
    return (coords)

pixCoords = hashCoords = originalPixCoords = []       # making sure they are empty
for j in dm.getPixelsForCluster(dm.clusters[i]):
    pixCoords.append([j['m_column'], j['m_row']])     # getting some values from a class -- ex:   [[613, 265], [613, 266]]   or    [[615, 341], [615, 342], [616, 341], [616, 342]]
originalPixCoords = pixCoords.copy()                  # just to be safe, I make a copy of the original list
print ('Original : ', originalPixCoords)
hashCoords = hashCluster(pixCoords)                   # apply transformation
print ('Modified : ', hashCoords)
print ('Original : ', originalPixCoords)              # should get the original list
</code>```

Some results [Jupyter Notebook]:

```<code>Original :  [[607, 268]]
Modified :  [[0, 0]]
Original :  [[0, 0]]

Original :  [[602, 264], [603, 264]]
Modified :  [[0, 0], [1, 0]]
Original :  [[0, 0], [1, 0]]

Original :  [[613, 265], [613, 266]]
Modified :  [[0, 0], [0, 1]]
Original :  [[0, 0], [0, 1]]
</code>```

Is the function hashCluster able to modify the new list as well? Even after the .copy()?

What am I doing wrong? My goal is to have access to both the original and modified lists, with as less operations and copies of lists as possible (since I am looping over a very large document).

答:
You have a list of lists, and are modifying the inner lists. The operation pixCoords.copy() creates a shallow copy of the outer list. Both pixCoords and originalPixCoords now have two list buffers pointing to the same mutable objects. There are two ways to handle this situation, each with its own pros and cons.

The knee-jerk method that most users seem to have is to make a deep copy:

```<code>originalPixCoords = copy.deepcopy(pixCoords)
</code>```

I would argue that this method is the less pythonic and more error prone approach. A better solution would be to make hashCluster actually return a new list. By doing that, you will make it treat the input as immutable, and eliminate the problem entirely. I consider this more pythonic because it reduces the maintenance burden. Also, conventionally, python functions that return a value create a new list without modifying the input while in-place operations generally don't return a value.

```<code>def hashCluster(coords):
    min_row = get_min_by_col(coords, 0)
    min_col = get_min_by_col(coords, 1)
    return [[pix[0] - min_col, pix[1] - min_row] for pix in coords]
</code>```

Body:
After I apply an operation to a list, I would like to get access to both the modified list and the original one.
Somehow I am not able to.

In the following code snippet, I define two functions with which I modify the original list.
Afterwards, I get my values from a class and apply the transformation.

def get_min_by_col(li, col):                          # get minimum from list
    return min(li, key=lambda x: x[col - 1])[col - 1]

def hashCluster(coords):                              # transform to origin
    min_row = get_min_by_col(coords,0)
    min_col = get_min_by_col(coords,1)
    for pix in coords:
        pix[1] = pix[1] - min_row
        pix[0] = pix[0] - min_col
    return (coords)

pixCoords = hashCoords = originalPixCoords = []       # making sure they are empty
for j in dm.getPixelsForCluster(dm.clusters[i]):
    pixCoords.append([j['m_column'], j['m_row']])     # getting some values from a class -- ex:   [[613, 265], [613, 266]]   or    [[615, 341], [615, 342], [616, 341], [616, 342]]
originalPixCoords = pixCoords.copy()                  # just to be safe, I make a copy of the original list
print ('Original : ', originalPixCoords)
hashCoords = hashCluster(pixCoords)                   # apply transformation
print ('Modified : ', hashCoords)
print ('Original : ', originalPixCoords)              # should get the original list

Some results [Jupyter Notebook]:

Original :  [[607, 268]]
Modified :  [[0, 0]]
Original :  [[0, 0]]

Original :  [[602, 264], [603, 264]]
Modified :  [[0, 0], [1, 0]]
Original :  [[0, 0], [1, 0]]

Original :  [[613, 265], [613, 266]]
Modified :  [[0, 0], [0, 1]]
Original :  [[0, 0], [0, 1]]

Is the function hashCluster able to modify the new list as well? Even after the .copy()?

What am I doing wrong? My goal is to have access to both the original and modified lists, with as less operations and copies of lists as possible (since I am looping over a very large document).

Body:
You have a list of lists, and are modifying the inner lists. The operation pixCoords.copy() creates a shallow copy of the outer list. Both pixCoords and originalPixCoords now have two list buffers pointing to the same mutable objects. There are two ways to handle this situation, each with its own pros and cons.

The knee-jerk method that most users seem to have is to make a deep copy:

originalPixCoords = copy.deepcopy(pixCoords)

I would argue that this method is the less pythonic and more error prone approach. A better solution would be to make hashCluster actually return a new list. By doing that, you will make it treat the input as immutable, and eliminate the problem entirely. I consider this more pythonic because it reduces the maintenance burden. Also, conventionally, python functions that return a value create a new list without modifying the input while in-place operations generally don't return a value.

def hashCluster(coords):
    min_row = get_min_by_col(coords, 0)
    min_col = get_min_by_col(coords, 1)
    return [[pix[0] - min_col, pix[1] - min_row] for pix in coords]


问:
Declare a SystemVerilog variable with type depending on a parameter
I want to write reusable SystemVerilog code so I need to have in module one variable with type, depending on a parameter (not different bus WIDTH, but different structs). Maybe it is possible to have one parametrized structure or to have different structures but in this case how to declare variable selecting needed struct as a type. Different structs could be declared in generte-if blocks, but they will be local to it blocks, so outside can't to get them. Maybe type conversion might help somehow.

P. S. Interfaces are not allowed to use as well as defines (macros are allowed).

Code example, I want to achieve:

```<code>typedef struct packed
{
  logic a;
  logic b;
} str_s;

typedef struct packed
{
  logic a;
  logic b;
  logic c;
} str_s_with_c;

// A is a parameter
generate
if (A == "ON")
   str_s_with_c array;

if (A == "OFF")
   str_s array;
endgenerate

assign array.a = 1'b1;

logic t;

assign t = array.a;
</code>```

or

```<code>generate
if (A == "ON")
begin
   typedef struct packed
   {
     logic a;
     logic b;
   } str_s;
end

if (A == "OFF")
begin
   typedef struct packed
   {
     logic a;
     logic b;
     logic c;
   } str_s;
end
endhenerate

str_s array;

array.a = 1.b1;
</code>```

答:
A usual way of doing it is to pass struct as a parameter type to the module instance.

```<code>module inst#(type struct_t=int)();
    struct_t v;
endmodule

typedef struct packed
{
  logic a;
  logic b;
} str_s;

typedef struct packed
{
  logic a;
  logic b;
  logic c;
} str_s_with_c;

module top;
  inst #(.struct_t(str_s)) inst1();
  inst #(.struct_t(str_s_with_c)) inst2();
endmodule
</code>```

Answering the comment below for a single instance. In this case you can use a generate block, instantiating the module conditionally:

```<code>module top #(ON=1)
    typedef struct packed
    {
        logic a;
        logic b;
    } str_s;
    typedef struct packed
    {
        logic a;
        logic b;
        logic c;
    } str_s_with_c;

  if (ON == 1) begin: ON1
    inst #(.struct_t(str_s)) inst1();
  end
  else begin: ON0
    inst #(.struct_t(str_s_with_c)) inst2();
  end
endmodule
</code>```

One caveat. You'd better declare the structs outside of the generate statements. LRM does not prevent you from declaring them inside, but this feature is not implemented in at least some of the compilers.

Body:
I want to write reusable SystemVerilog code so I need to have in module one variable with type, depending on a parameter (not different bus WIDTH, but different structs). Maybe it is possible to have one parametrized structure or to have different structures but in this case how to declare variable selecting needed struct as a type. Different structs could be declared in generte-if blocks, but they will be local to it blocks, so outside can't to get them. Maybe type conversion might help somehow.

P. S. Interfaces are not allowed to use as well as defines (macros are allowed).

Code example, I want to achieve:

typedef struct packed
{
  logic a;
  logic b;
} str_s;

typedef struct packed
{
  logic a;
  logic b;
  logic c;
} str_s_with_c;

// A is a parameter
generate
if (A == "ON")
   str_s_with_c array;

if (A == "OFF")
   str_s array;
endgenerate

assign array.a = 1'b1;

logic t;

assign t = array.a;

or

generate
if (A == "ON")
begin
   typedef struct packed
   {
     logic a;
     logic b;
   } str_s;
end

if (A == "OFF")
begin
   typedef struct packed
   {
     logic a;
     logic b;
     logic c;
   } str_s;
end
endhenerate

str_s array;

array.a = 1.b1;

Body:
A usual way of doing it is to pass struct as a parameter type to the module instance.

module inst#(type struct_t=int)();
    struct_t v;
endmodule

typedef struct packed
{
  logic a;
  logic b;
} str_s;

typedef struct packed
{
  logic a;
  logic b;
  logic c;
} str_s_with_c;

module top;
  inst #(.struct_t(str_s)) inst1();
  inst #(.struct_t(str_s_with_c)) inst2();
endmodule

Answering the comment below for a single instance. In this case you can use a generate block, instantiating the module conditionally:

module top #(ON=1)
    typedef struct packed
    {
        logic a;
        logic b;
    } str_s;
    typedef struct packed
    {
        logic a;
        logic b;
        logic c;
    } str_s_with_c;

  if (ON == 1) begin: ON1
    inst #(.struct_t(str_s)) inst1();
  end
  else begin: ON0
    inst #(.struct_t(str_s_with_c)) inst2();
  end
endmodule

One caveat. You'd better declare the structs outside of the generate statements. LRM does not prevent you from declaring them inside, but this feature is not implemented in at least some of the compilers.


问:
web crypto api - how to export key pair?
This is what I've got so far to export a public and private key from a keypair:

```<code>let pub = await crypto.subtle.exportKey("spki", keyPair.publicKey);
let prv = await crypto.subtle.exportKey("spki", keyPair.privateKey);
</code>```

This results in two individual array buffers holding my public and private key.

I would like to find out how to export the entire keypair at once into a single array buffer?

Something like this:

```<code>let pair = await crypto.subtle.exportKeyPair("spki", keyPair);
</code>```

Is there a web api and a format for this?

Otherwise is there a safe way to concatenate the two array buffers (the exported public and private key) together in such a way that I can split them up again when importing? I would then need to have some mechanism to handle malformed input when importing the exported key pair.

I must do this because my interface requires me to return a single array buffer.

答:
I found that I can export the public key using the following code. I haven't figured out the private key just yet. Also I built this sample from the code on:

https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey#subjectpublickeyinfo_export

```<code>const exported = pub;
const exportedAsString = String.fromCharCode.apply(null, new Uint8Array(exported));
const exportedAsBase64 = window.btoa(exportedAsString);
const pemExported = '-----BEGIN PUBLIC KEY-----\n'+exportedAsBase64+'\n-----END PUBLIC KEY-----`;
console.log("Public Exported Key: ", pemExported);
</code>```

Body:
This is what I've got so far to export a public and private key from a keypair:

let pub = await crypto.subtle.exportKey("spki", keyPair.publicKey);
let prv = await crypto.subtle.exportKey("spki", keyPair.privateKey);

This results in two individual array buffers holding my public and private key.

I would like to find out how to export the entire keypair at once into a single array buffer?

Something like this:

let pair = await crypto.subtle.exportKeyPair("spki", keyPair);

Is there a web api and a format for this?

Otherwise is there a safe way to concatenate the two array buffers (the exported public and private key) together in such a way that I can split them up again when importing? I would then need to have some mechanism to handle malformed input when importing the exported key pair.

I must do this because my interface requires me to return a single array buffer.

Body:
I found that I can export the public key using the following code. I haven't figured out the private key just yet. Also I built this sample from the code on:

https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey#subjectpublickeyinfo_export

const exported = pub;
const exportedAsString = String.fromCharCode.apply(null, new Uint8Array(exported));
const exportedAsBase64 = window.btoa(exportedAsString);
const pemExported = '-----BEGIN PUBLIC KEY-----\n'+exportedAsBase64+'\n-----END PUBLIC KEY-----`;
console.log("Public Exported Key: ", pemExported);


问:
How merge with master without conflict after rebase in feature branch?
I plan on creating a feature branch, and in addition to the new commits in the feature branch, I might also make file edits to an older commit in the feature branch through git rebase. Then I plan on merging the feature branch to the master branch.

I tested this scenario with a fake test repo, and I actually got a merge conflict with the rebased commit in the feature branch.

How can I avoid having this conflict at merge time?

答:
You're asking the wrong question. Let me ask you a question: Why avoid the conflict at merge time?

Seriously, I do what you describe all the time, reaching back into earlier commits to improve history thanks to interactive rebase. And as I move forward from there, I always get merge conflicts. So what? I expected them, I resolve them, I move on.

Moreover, working in a collaborative environment, I get merge conflicts nearly every day, particularly in situations where one of us has edited a file and another has removed or renamed it. So what? That sort of thing is natural when many people are working on a project. I expect it. I resolve the conflicts, I move on.

Repurpose your thinking. Merge conflicts are not bad. They are not "conflicts" at all. They are merely Git's expression of a situation where normal merge logic is not sufficient to know what you want so as to perform the totality of the merge automatically. But you know what you want, and resolving the "conflict" is how you tell Git what it is. So just play the game the way Git is asking you to play it, and don't worry, be happy.

So there's my answer to your question, "How merge with master without conflict after rebase in feature branch?" Don't try to merge without conflict. Don't want to merge without conflict. Merge, and if you get a conflict, resolve it.


问:
Custom validation attribute that allows specific integer in C#
How to create a custom validation attribute that allows only specified integers. adding a custom error message.</p>

答:
Create a class and inherit from ValidationAttribute class.

Follow the example code below

```<code>public class IntegersAllowedAttribute : ValidationAttribute
    {
        private readonly int[] _values;

        public IntegersAllowedAttribute(params int[] values)
        {
            _values = values;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            int valuesToValidate = (int)value;

            if (!_values.Contains(valuesToValidate))
            {
                string errorMessage = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(errorMessage);
            }
            return ValidationResult.Success;
        }
    }
</code>```

Then place attribute on the property

```<code> public class Example
    {
        [IntValuesAllowed(1, 2, 3, ErrorMessage = "error message goes here")]
        public int Values { get; set; }
    }
</code>```

Body:
Create a class and inherit from ValidationAttribute class.

Follow the example code below

public class IntegersAllowedAttribute : ValidationAttribute
    {
        private readonly int[] _values;

        public IntegersAllowedAttribute(params int[] values)
        {
            _values = values;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            int valuesToValidate = (int)value;

            if (!_values.Contains(valuesToValidate))
            {
                string errorMessage = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(errorMessage);
            }
            return ValidationResult.Success;
        }
    }

Then place attribute on the property

 public class Example
    {
        [IntValuesAllowed(1, 2, 3, ErrorMessage = "error message goes here")]
        public int Values { get; set; }
    }


问:
Rails - Linkedin Auth: Not found. Authentication passthru
Hi have an application with Linkedin Authentication that used to work fine. Today I got complains from user saying they see: Not found. Authentication passthru. when clicking on login with Linkedin. it takes them to the page: http://XXXXX/users/auth/linkedin?locale=en

When i check in the logs I get :

```<code>Started GET "/users/auth/linkedin?locale=en" for ::1 at 2021-07-12 18:04:13 +0800
Processing by OmniauthCallbacksController#passthru as HTML
  Parameters: {"locale"=>"en"}
  Rendering text template
  Rendered text template (0.0ms)
Completed 404 Not Found in 3ms (Views: 0.9ms | ActiveRecord: 0.3ms)
</code>```

My controller looks like:

```<code>class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def linkedin

    @user = User.connect_to_linkedin(request.env["omniauth.auth"],current_user)
    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success"
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.linkedin_uid"] = request.env["omniauth.auth"].except("extra")
      redirect_to new_user_registration_url
      flash[:notice] = I18n.t "devise.omniauth_callbacks.failure"

    end
  end
</code>```

I have the following in my model:

devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable, :omniauthable, :omniauth_providers => [:linkedin

```<code>             user_linkedin_omniauth_authorize GET|POST /users/auth/linkedin(.:format)                                                omniauth_callbacks#passthru
              user_linkedin_omniauth_callback GET|POST /users/auth/linkedin/callback(.:format)                                       omniauth_callbacks#linkedin
</code>```

When I add the POST method to the link_to, i get the following:

```<code>Started POST "/users/auth/linkedin?locale=en" for ::1 at 2021-07-12 21:56:18 +0800
D, [2021-07-12T21:56:18.416654 #65475] DEBUG -- omniauth: (linkedin) Request phase initiated.
W, [2021-07-12T21:56:18.417955 #65475]  WARN -- omniauth: Attack prevented by OmniAuth::AuthenticityTokenProtection
E, [2021-07-12T21:56:18.418089 #65475] ERROR -- omniauth: (linkedin) Authentication failure! authenticity_error: OmniAuth::AuthenticityError, Forbidden
Processing by OmniauthCallbacksController#failure as HTML
</code>```

And other stuff

Do you see what could be teh reason behind this sudden problem please?
I did a Bundle Update few days ago and a lot of errors started showing up.

None of what i saw so far could help.

答:
I found this was because of CSRF protection enabled by default in OmniAuth 2 and above, and GET requests no longer supported like the one you are trying.

I was able to fix it with two things:

Add omniauth-rails_csrf_protection gem: https://github.com/cookpad/omniauth-rails_csrf_protection

Update your config/initializers/omniauth.rb to include:

```<code>OmniAuth.config.allowed_request_methods = [:get, :post]
</code>```

Body:
Hi have an application with Linkedin Authentication that used to work fine. Today I got complains from user saying they see: Not found. Authentication passthru. when clicking on login with Linkedin. it takes them to the page: http://XXXXX/users/auth/linkedin?locale=en

When i check in the logs I get :

Started GET "/users/auth/linkedin?locale=en" for ::1 at 2021-07-12 18:04:13 +0800
Processing by OmniauthCallbacksController#passthru as HTML
  Parameters: {"locale"=>"en"}
  Rendering text template
  Rendered text template (0.0ms)
Completed 404 Not Found in 3ms (Views: 0.9ms | ActiveRecord: 0.3ms)

My controller looks like:

class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def linkedin

    @user = User.connect_to_linkedin(request.env["omniauth.auth"],current_user)
    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success"
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.linkedin_uid"] = request.env["omniauth.auth"].except("extra")
      redirect_to new_user_registration_url
      flash[:notice] = I18n.t "devise.omniauth_callbacks.failure"

    end
  end

I have the following in my model:

devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable, :omniauthable, :omniauth_providers => [:linkedin

             user_linkedin_omniauth_authorize GET|POST /users/auth/linkedin(.:format)                                                omniauth_callbacks#passthru
              user_linkedin_omniauth_callback GET|POST /users/auth/linkedin/callback(.:format)                                       omniauth_callbacks#linkedin

When I add the POST method to the link_to, i get the following:

Started POST "/users/auth/linkedin?locale=en" for ::1 at 2021-07-12 21:56:18 +0800
D, [2021-07-12T21:56:18.416654 #65475] DEBUG -- omniauth: (linkedin) Request phase initiated.
W, [2021-07-12T21:56:18.417955 #65475]  WARN -- omniauth: Attack prevented by OmniAuth::AuthenticityTokenProtection
E, [2021-07-12T21:56:18.418089 #65475] ERROR -- omniauth: (linkedin) Authentication failure! authenticity_error: OmniAuth::AuthenticityError, Forbidden
Processing by OmniauthCallbacksController#failure as HTML

And other stuff

Do you see what could be teh reason behind this sudden problem please?
I did a Bundle Update few days ago and a lot of errors started showing up.

None of what i saw so far could help.

Body:
I found this was because of CSRF protection enabled by default in OmniAuth 2 and above, and GET requests no longer supported like the one you are trying.

I was able to fix it with two things:

Add omniauth-rails_csrf_protection gem: https://github.com/cookpad/omniauth-rails_csrf_protection

Update your config/initializers/omniauth.rb to include:

OmniAuth.config.allowed_request_methods = [:get, :post]


问:
Swift realm : incorrect object written to db
Here is a class to add/get data from Realm :

```<code>import Foundation
import RealmSwift

class WeatherDataOneDay {
    var temperature: Int = 0
    var temperatureDescription: String = ""
    var condition: Int = 0
    var city: String = ""
    var weatherIconName: String = ""
    var sunset: Double = 0
    var sunrise: Double = 0
    var humidity: Int = 0
    var windSpeed: Float = 0.0
    var date: Double = 0
    var feelsLike: Int = 0

    var clouds: Int = 0
    var lon: Float = 0.0
    var lat: Float = 0.0

    func printSelf()
    {
        print("temperature : \(temperature)")
        print("temperatureDescription : \(temperatureDescription)")
        print("condition : \(condition)")
        print("city : \(city)")
        print("weatherIconName : \(weatherIconName)")
        print("sunset : \(sunset)")
        print("sunrise : \(sunrise)")
        print("humidity : \(humidity)")
        print("windSpeed : \(windSpeed)")
        print("date : \(date)")
        print("feelsLike : \(feelsLike)")
        print("clouds : \(clouds)")
        print("lon : \(lon)")
        print("lat : \(lat)")
    }
}

@objcMembers class WeatherDataOneDayCached: Object {
    dynamic var poi: String?

    dynamic var temperature: Int?
    dynamic var temperatureDescription: String?
    dynamic var condition: Int?
    dynamic var city: String?
    dynamic var weatherIconName: String?
    dynamic var sunset: Double?
    dynamic var sunrise: Double?
    dynamic var humidity: Int?
    dynamic var windSpeed: Float?
    dynamic var date: Double?
    dynamic var feelsLike: Int?
    dynamic var clouds: Int?
    dynamic var lon: Float?
    dynamic var lat: Float?

    override static func primaryKey() -> String? {
        return "poi"
    }

    func printSelf()
    {
        print("temperature : \(temperature)")
        print("temperatureDescription : \(temperatureDescription)")
        print("condition : \(condition)")
        print("city : \(city)")
        print("weatherIconName : \(weatherIconName)")
        print("sunset : \(sunset)")
        print("sunrise : \(sunrise)")
        print("humidity : \(humidity)")
        print("windSpeed : \(windSpeed)")
        print("date : \(date)")
        print("feelsLike : \(feelsLike)")
        print("clouds : \(clouds)")
        print("lon : \(lon)")
        print("lat : \(lat)")
    }

}

class WeatherDataOneDayDbProvider {
    private var realm: Realm?

    init() {
        var config = Realm.Configuration()
        config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("weather_data_one_day.realm")
        realm = try? Realm(configuration: config)
    }

    func getOneDayWeatherDataForPoi(poi : String) -> WeatherDataOneDay? {
        let weatherData = realm?.object(ofType: WeatherDataOneDayCached.self, forPrimaryKey: poi)
        if let weatherData = weatherData {
            let result = WeatherDataOneDay()
            result.temperature = weatherData.temperature ?? 0
            result.temperatureDescription = weatherData.temperatureDescription ?? ""
            result.condition = weatherData.condition ?? 0
            result.city = weatherData.city ?? ""
            result.weatherIconName = weatherData.weatherIconName ?? ""
            result.sunset = weatherData.sunset ?? 0.0
            result.sunrise = weatherData.sunrise ?? 0.0
            result.humidity = weatherData.humidity ?? 0
            result.windSpeed = weatherData.windSpeed ?? 0.0
            result.date = weatherData.date ?? 0.0
            result.feelsLike = weatherData.feelsLike ?? 0
            result.clouds = weatherData.clouds ?? 0
            result.lon = weatherData.lon ?? 0.0
            result.lat = weatherData.lat ?? 0.0

            return result
        } else {
            return nil
        }
    }

    func addOneDayWeatherDataForPoi(poi : String, weatherData: WeatherDataOneDay) {
        let cachedWeatherData = WeatherDataOneDayCached()
        cachedWeatherData.poi = poi

        cachedWeatherData.temperature = weatherData.temperature
        cachedWeatherData.temperatureDescription = weatherData.temperatureDescription
        cachedWeatherData.condition = weatherData.condition
        cachedWeatherData.city = weatherData.city
        cachedWeatherData.weatherIconName = weatherData.weatherIconName
        cachedWeatherData.sunset = weatherData.sunset
        cachedWeatherData.sunrise = weatherData.sunrise
        cachedWeatherData.humidity = weatherData.humidity
        cachedWeatherData.windSpeed = weatherData.windSpeed
        cachedWeatherData.date = weatherData.date
        cachedWeatherData.feelsLike = weatherData.feelsLike
        cachedWeatherData.clouds = weatherData.clouds
        cachedWeatherData.lon = weatherData.lon
        cachedWeatherData.lat = weatherData.lat

        if isWeatherDataExist(poi: poi) {
            try? realm?.write {
                realm?.add(cachedWeatherData, update: .all)
            }
        } else {
            try? realm?.write {
                realm?.add(cachedWeatherData)
            }
        }
    }

    func isWeatherDataExist(poi: String) -> Bool {
        return realm?.object(ofType: WeatherDataOneDayCached.self, forPrimaryKey: poi) != nil
    }
}

class WeatherDataOneDayDB {
    private let dbDataProvider : WeatherDataOneDayDbProvider = WeatherDataOneDayDbProvider()

    static var shared: WeatherDataOneDayDB = {
        let instance = WeatherDataOneDayDB()
        return instance
    }()

    private init() {}

    func getOneDayWeatherDataForPoi(poi : String) -> WeatherDataOneDay? {
        return dbDataProvider.getOneDayWeatherDataForPoi(poi: poi)
    }

    func addOneDayWeatherDataForPoi(poi : String, weatherData: WeatherDataOneDay) {
        return dbDataProvider.addOneDayWeatherDataForPoi(poi: poi, weatherData: weatherData)
    }
}
</code>```

And this is a test snippet :

```<code>let test = WeatherDataOneDay()
test.temperature = 26
test.temperatureDescription = "clear sky"
test.condition = 800
test.city = "Globe"
test.weatherIconName = ""
test.sunset = 1644517064.0
test.sunrise = 1644473452.0
test.humidity = 80
test.windSpeed = 2.4
test.date = 1644521917.0
test.feelsLike = 29
test.clouds = 0
test.lon = 0.0
test.lat = 0.0
print("!!!!!!!DEBUUUUUUUUG!!!!!!!!!!!")
let db = WeatherDataOneDayDB.shared
db.addOneDayWeatherDataForPoi(poi: "Москва",
                              weatherData: test)

if let obj = db.getOneDayWeatherDataForPoi(poi: "Москва") {
    obj.printSelf()
}
</code>```

I see that the object is not completely written to DB - only few members are fine and all the rest are nil. This is what I receive :

```<code>temperature : 0
temperatureDescription : clear sky
condition : 0
city : Globe
weatherIconName :
sunset : 0.0
sunrise : 0.0 ....
</code>```

I access the DB from main thread only. What am I missing?

答:
Here is the solution for my case (seems to be an issue with optional usage somehow) :</p>
```<code>class WeatherDataOneDayCached: Object {
    @objc dynamic var poi: String = ""

    @objc dynamic var temperature: Int = 0
    @objc dynamic var temperatureDescription: String = ""
    @objc dynamic var condition: Int = 0
    @objc dynamic var city: String = ""
    @objc dynamic var weatherIconName: String = ""
    @objc dynamic var sunset: Double = 0
    @objc dynamic var sunrise: Double = 0
    @objc dynamic var humidity: Int = 0
    @objc dynamic var windSpeed: Float = 0
    @objc dynamic var date: Double = 0
    @objc dynamic var feelsLike: Int = 0
    @objc dynamic var clouds: Int = 0
    @objc dynamic var lon: Float = 0
    @objc dynamic var lat: Float = 0

    override static func primaryKey() -> String? {
        return "poi"
    }

    func printSelf()
    {
        print("temperature : \(temperature)")
        print("temperatureDescription : \(temperatureDescription)")
        print("condition : \(condition)")
        print("city : \(city)")
        print("weatherIconName : \(weatherIconName)")
        print("sunset : \(sunset)")
        print("sunrise : \(sunrise)")
        print("humidity : \(humidity)")
        print("windSpeed : \(windSpeed)")
        print("date : \(date)")
        print("feelsLike : \(feelsLike)")
        print("clouds : \(clouds)")
        print("lon : \(lon)")
        print("lat : \(lat)")
    }

}
</code>```

Body:
Here is a class to add/get data from Realm :

import Foundation
import RealmSwift

class WeatherDataOneDay {
    var temperature: Int = 0
    var temperatureDescription: String = ""
    var condition: Int = 0
    var city: String = ""
    var weatherIconName: String = ""
    var sunset: Double = 0
    var sunrise: Double = 0
    var humidity: Int = 0
    var windSpeed: Float = 0.0
    var date: Double = 0
    var feelsLike: Int = 0

    var clouds: Int = 0
    var lon: Float = 0.0
    var lat: Float = 0.0

    func printSelf()
    {
        print("temperature : \(temperature)")
        print("temperatureDescription : \(temperatureDescription)")
        print("condition : \(condition)")
        print("city : \(city)")
        print("weatherIconName : \(weatherIconName)")
        print("sunset : \(sunset)")
        print("sunrise : \(sunrise)")
        print("humidity : \(humidity)")
        print("windSpeed : \(windSpeed)")
        print("date : \(date)")
        print("feelsLike : \(feelsLike)")
        print("clouds : \(clouds)")
        print("lon : \(lon)")
        print("lat : \(lat)")
    }
}

@objcMembers class WeatherDataOneDayCached: Object {
    dynamic var poi: String?

    dynamic var temperature: Int?
    dynamic var temperatureDescription: String?
    dynamic var condition: Int?
    dynamic var city: String?
    dynamic var weatherIconName: String?
    dynamic var sunset: Double?
    dynamic var sunrise: Double?
    dynamic var humidity: Int?
    dynamic var windSpeed: Float?
    dynamic var date: Double?
    dynamic var feelsLike: Int?
    dynamic var clouds: Int?
    dynamic var lon: Float?
    dynamic var lat: Float?

    override static func primaryKey() -> String? {
        return "poi"
    }

    func printSelf()
    {
        print("temperature : \(temperature)")
        print("temperatureDescription : \(temperatureDescription)")
        print("condition : \(condition)")
        print("city : \(city)")
        print("weatherIconName : \(weatherIconName)")
        print("sunset : \(sunset)")
        print("sunrise : \(sunrise)")
        print("humidity : \(humidity)")
        print("windSpeed : \(windSpeed)")
        print("date : \(date)")
        print("feelsLike : \(feelsLike)")
        print("clouds : \(clouds)")
        print("lon : \(lon)")
        print("lat : \(lat)")
    }

}

class WeatherDataOneDayDbProvider {
    private var realm: Realm?

    init() {
        var config = Realm.Configuration()
        config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("weather_data_one_day.realm")
        realm = try? Realm(configuration: config)
    }

    func getOneDayWeatherDataForPoi(poi : String) -> WeatherDataOneDay? {
        let weatherData = realm?.object(ofType: WeatherDataOneDayCached.self, forPrimaryKey: poi)
        if let weatherData = weatherData {
            let result = WeatherDataOneDay()
            result.temperature = weatherData.temperature ?? 0
            result.temperatureDescription = weatherData.temperatureDescription ?? ""
            result.condition = weatherData.condition ?? 0
            result.city = weatherData.city ?? ""
            result.weatherIconName = weatherData.weatherIconName ?? ""
            result.sunset = weatherData.sunset ?? 0.0
            result.sunrise = weatherData.sunrise ?? 0.0
            result.humidity = weatherData.humidity ?? 0
            result.windSpeed = weatherData.windSpeed ?? 0.0
            result.date = weatherData.date ?? 0.0
            result.feelsLike = weatherData.feelsLike ?? 0
            result.clouds = weatherData.clouds ?? 0
            result.lon = weatherData.lon ?? 0.0
            result.lat = weatherData.lat ?? 0.0

            return result
        } else {
            return nil
        }
    }

    func addOneDayWeatherDataForPoi(poi : String, weatherData: WeatherDataOneDay) {
        let cachedWeatherData = WeatherDataOneDayCached()
        cachedWeatherData.poi = poi

        cachedWeatherData.temperature = weatherData.temperature
        cachedWeatherData.temperatureDescription = weatherData.temperatureDescription
        cachedWeatherData.condition = weatherData.condition
        cachedWeatherData.city = weatherData.city
        cachedWeatherData.weatherIconName = weatherData.weatherIconName
        cachedWeatherData.sunset = weatherData.sunset
        cachedWeatherData.sunrise = weatherData.sunrise
        cachedWeatherData.humidity = weatherData.humidity
        cachedWeatherData.windSpeed = weatherData.windSpeed
        cachedWeatherData.date = weatherData.date
        cachedWeatherData.feelsLike = weatherData.feelsLike
        cachedWeatherData.clouds = weatherData.clouds
        cachedWeatherData.lon = weatherData.lon
        cachedWeatherData.lat = weatherData.lat

        if isWeatherDataExist(poi: poi) {
            try? realm?.write {
                realm?.add(cachedWeatherData, update: .all)
            }
        } else {
            try? realm?.write {
                realm?.add(cachedWeatherData)
            }
        }
    }

    func isWeatherDataExist(poi: String) -> Bool {
        return realm?.object(ofType: WeatherDataOneDayCached.self, forPrimaryKey: poi) != nil
    }
}

class WeatherDataOneDayDB {
    private let dbDataProvider : WeatherDataOneDayDbProvider = WeatherDataOneDayDbProvider()

    static var shared: WeatherDataOneDayDB = {
        let instance = WeatherDataOneDayDB()
        return instance
    }()

    private init() {}

    func getOneDayWeatherDataForPoi(poi : String) -> WeatherDataOneDay? {
        return dbDataProvider.getOneDayWeatherDataForPoi(poi: poi)
    }

    func addOneDayWeatherDataForPoi(poi : String, weatherData: WeatherDataOneDay) {
        return dbDataProvider.addOneDayWeatherDataForPoi(poi: poi, weatherData: weatherData)
    }
}

And this is a test snippet :

let test = WeatherDataOneDay()
test.temperature = 26
test.temperatureDescription = "clear sky"
test.condition = 800
test.city = "Globe"
test.weatherIconName = ""
test.sunset = 1644517064.0
test.sunrise = 1644473452.0
test.humidity = 80
test.windSpeed = 2.4
test.date = 1644521917.0
test.feelsLike = 29
test.clouds = 0
test.lon = 0.0
test.lat = 0.0
print("!!!!!!!DEBUUUUUUUUG!!!!!!!!!!!")
let db = WeatherDataOneDayDB.shared
db.addOneDayWeatherDataForPoi(poi: "Москва",
                              weatherData: test)

if let obj = db.getOneDayWeatherDataForPoi(poi: "Москва") {
    obj.printSelf()
}

I see that the object is not completely written to DB - only few members are fine and all the rest are nil. This is what I receive :

temperature : 0
temperatureDescription : clear sky
condition : 0
city : Globe
weatherIconName :
sunset : 0.0
sunrise : 0.0 ....

I access the DB from main thread only. What am I missing?

Body:
Here is the solution for my case (seems to be an issue with optional usage somehow) :

class WeatherDataOneDayCached: Object {
    @objc dynamic var poi: String = ""

    @objc dynamic var temperature: Int = 0
    @objc dynamic var temperatureDescription: String = ""
    @objc dynamic var condition: Int = 0
    @objc dynamic var city: String = ""
    @objc dynamic var weatherIconName: String = ""
    @objc dynamic var sunset: Double = 0
    @objc dynamic var sunrise: Double = 0
    @objc dynamic var humidity: Int = 0
    @objc dynamic var windSpeed: Float = 0
    @objc dynamic var date: Double = 0
    @objc dynamic var feelsLike: Int = 0
    @objc dynamic var clouds: Int = 0
    @objc dynamic var lon: Float = 0
    @objc dynamic var lat: Float = 0

    override static func primaryKey() -> String? {
        return "poi"
    }

    func printSelf()
    {
        print("temperature : \(temperature)")
        print("temperatureDescription : \(temperatureDescription)")
        print("condition : \(condition)")
        print("city : \(city)")
        print("weatherIconName : \(weatherIconName)")
        print("sunset : \(sunset)")
        print("sunrise : \(sunrise)")
        print("humidity : \(humidity)")
        print("windSpeed : \(windSpeed)")
        print("date : \(date)")
        print("feelsLike : \(feelsLike)")
        print("clouds : \(clouds)")
        print("lon : \(lon)")
        print("lat : \(lat)")
    }

}


问:
How to add event handlers to button elements rendered in an OL using Javascript and get the index position?
I'm trying to build a simple to do list application. I've linked my input field to an array which gets rendered out as an ordered list, and there are two buttons added to each item, one to state "completed" and one for "remove".

I've having difficulty with two parts: 1) adding event handlers to the buttons rendered out in the OL (I've managed to in the code below but I'm not sure if it's the right way. Part 2) identifying the index of the item so that I can modify it with the completed and remove buttons.

I've tried to use event delegation to tackle part 1 but I'm not sure if this is correct, and I don't know how to relate it to part 2.

```<code>document.getElementById("parent-list").addEventListener("click", function(e) {
    if(e.target && e.target.nodeName == "BUTTON") {
        console.log(e.target);
    }
});
</code>```

答:
First off, you should keep track of the items

```<code>const items = document.querySelectorAll('.my-classname');
</code>```

This will create an items array where you can do all sorts of stuff, like .forEach(). This is great, because you need the index of the item as well.

That would solve part 2.

Now, for part 1..

You should add classnames to each buttons, like

```<code><button class="completed-btn"></button>
<button class="remove-btn"></button>
</code>```

The reason you need this is to be able to differentiate them and their handlers.

Next step is same as with items. You want to keep track of each button.

```<code>const completedButtons = document.querySelectorAll('.completed-btn');
const removeButtons = document.querySelectorAll('.remove-btn');
</code>```

You can now add your handlers

```<code>completedButtons.forEach((button, i) => {
  button.addEventListener("click", function (e) {
    const item = items[i];
    const target = e.target;

    // do stuff
  });
});

removeButtons.forEach((button, i) => {
  button.addEventListener("click", function (e) {
    const item = items[i];
    const target = e.target;

    // do stuff
  });
});
</code>```

The variable i will match the index of the clicked item's button, therefore will match the index of the item.

Body:
I'm trying to build a simple to do list application. I've linked my input field to an array which gets rendered out as an ordered list, and there are two buttons added to each item, one to state "completed" and one for "remove".

I've having difficulty with two parts: 1) adding event handlers to the buttons rendered out in the OL (I've managed to in the code below but I'm not sure if it's the right way. Part 2) identifying the index of the item so that I can modify it with the completed and remove buttons.

I've tried to use event delegation to tackle part 1 but I'm not sure if this is correct, and I don't know how to relate it to part 2.

document.getElementById("parent-list").addEventListener("click", function(e) {
    if(e.target && e.target.nodeName == "BUTTON") {
        console.log(e.target);
    }
});

Body:
First off, you should keep track of the items

const items = document.querySelectorAll('.my-classname');

This will create an items array where you can do all sorts of stuff, like .forEach(). This is great, because you need the index of the item as well.

That would solve part 2.

Now, for part 1..

You should add classnames to each buttons, like

<button class="completed-btn"></button>
<button class="remove-btn"></button>

The reason you need this is to be able to differentiate them and their handlers.

Next step is same as with items. You want to keep track of each button.

const completedButtons = document.querySelectorAll('.completed-btn');
const removeButtons = document.querySelectorAll('.remove-btn');

You can now add your handlers

completedButtons.forEach((button, i) => {
  button.addEventListener("click", function (e) {
    const item = items[i];
    const target = e.target;

    // do stuff
  });
});

removeButtons.forEach((button, i) => {
  button.addEventListener("click", function (e) {
    const item = items[i];
    const target = e.target;

    // do stuff
  });
});

The variable i will match the index of the clicked item's button, therefore will match the index of the item.


问:
Strange! python datetime.datetime.now() randomly generate unix second and nanosecond timestamp
I have deployed a GCP cloud function that updates Firestore time_created and time_updated fields in Firestore. My front-end app first creates these fields in Firestore but my function updates them after processing the documents. A snippet of code below generates the timestamp and I use Firestore update function to update the document. There are a few instances where the fields in Firestore will be updated as a dictionary with keys as "seconds" and "nano_seconds" and their values but not as Timestamp. I have been wondering and trying to track down where the issue is coming from. I suspect datetime.now() sometimes does not generate a timestamp value. Help me if you have an idea or seen something like this before. I have attached a snapshot below. The image attached shows an instance of the wrongly formatted date returned from Firestore to my Front-end.

Documents affected have the field showing as this:

time_created: {'seconds': 1637694047.0, 'nanoseconds': 580592000.0}

```<code>from datetime import datetime

update_doc = {
                u"time_created": datetime.now(),
                u"time_updated": datetime.now()
            }
</code>```

答:
Per @mark-tolonen, please don't include images in questions when it's trivial to copy-and-paste the test. Various reasons.

I experienced a different issue with Firestore timestamps and using the Go SDK. When I read your question, I wondered if the issues were related but, I think not.

That said, you can perform some diagnosis. You can emit the Python datetime.now() values of course to ensure you know what's being applied.

You could (!) then use the underlying REST API directly to mimic|repro the calls that your code is making to determine whether the error arises in the API itself or the Python SDK (or your code).

Here's projects.databases.documents.patch which I think underlies the Set. There's also projects.databases.documents.create. In both cases, APIs Explorer provides a way for you to try the API methods in the browser and will yield the e.g. curl equivalents for you.

NOTE

The API requires a parent parameter, defined to be something of the form projects/{project_id}/databases/{databaseId}/documents. Replace project_id with your Project ID and use (default) (with the parenthesis) for the value of {databaseId}.

Body:
I have deployed a GCP cloud function that updates Firestore time_created and time_updated fields in Firestore. My front-end app first creates these fields in Firestore but my function updates them after processing the documents. A snippet of code below generates the timestamp and I use Firestore update function to update the document. There are a few instances where the fields in Firestore will be updated as a dictionary with keys as "seconds" and "nano_seconds" and their values but not as Timestamp. I have been wondering and trying to track down where the issue is coming from. I suspect datetime.now() sometimes does not generate a timestamp value. Help me if you have an idea or seen something like this before. I have attached a snapshot below. The image attached shows an instance of the wrongly formatted date returned from Firestore to my Front-end.

Documents affected have the field showing as this:

time_created: {'seconds': 1637694047.0, 'nanoseconds': 580592000.0}

from datetime import datetime

update_doc = {
                u"time_created": datetime.now(),
                u"time_updated": datetime.now()
            }


问:
SQLite: How to create a combination of unrelated elements of two queries?
I have one table that I need to get some metrics from.

For example I have the following table:

meas_count
skippings
links
extra

10
8
4.2
some

10
9
5.8
some

10
9
5.8
some_2

11
8
4.2
some

11
8
5.8
some

11
9
5.9
some

I need to get a view of an existing table in the following form for further work:

meas_count
skippings
links_min
links_max

10
8
0
4

10
8
4
5

10
8
5
6

10
9
0
4

10
9
4
5

10
9
5
6

11
8
0
4

11
8
4
5

11
8
5
6

11
9
0
4

11
9
4
5

11
9
5
6

At the moment I have 2 queries, the results of which I need to combine to get the result I need.

First request:

SELECT meas_count,skippings FROM current_stats GROUP BY meas_count,skippings
```
<p>Creates the following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>meas_count</th>
<th>skippings</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>8</td>
</tr>
<tr>
<td>10</td>
<td>9</td>
</tr>
<tr>
<td>11</td>
<td>8</td>
</tr>
<tr>
<td>11</td>
<td>9</td>
</tr>
</tbody>
</table>
</div>
<p>Second request:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
LAG(rounded) OVER (ORDER BY rounded) as links_min,
rounded as links_max FROM
(SELECT * FROM
(SELECT ROUND(links, 1) as rounded FROM current_stats)
GROUP BY rounded ORDER BY rounded)
</code>```

Creates the following:

links_min
links_max

NULL
4

4
5

5
6

I need something like result of sets multiplication...

What query should be executed to get the table of the view I need as a result?

I also have an additional question: is the execution of the second query slowed down due to several SELECTs inside?

答:
You can do that by doing an INNER JOIN on the two tables without specifying a join condition.  That will give you every combination of the two sets of rows.

```<code>SELECT * FROM
(
    SELECT meas_count,skippings
    FROM current_stats
    GROUP BY meas_count,skippings)
AS one
INNER JOIN
(
    SELECT LAG(rounded) OVER (ORDER BY rounded) as links_min,
 rounded as links_max FROM
    (SELECT * FROM
       (SELECT ROUND(links, 1) as rounded FROM current_stats)
     GROUP BY rounded
     ORDER BY rounded
    )
) AS two;
</code>```

As for performance, that's really only an issue if there is a better way to do it.  Of course nested SELECTs take time, but the query optimizers in today's SQL engine are pretty good at determining what you MEANT from what you SAID.

Body:
I have one table that I need to get some metrics from.

For example I have the following table:

meas_count
skippings
links
extra

10
8
4.2
some

10
9
5.8
some

10
9
5.8
some_2

11
8
4.2
some

11
8
5.8
some

11
9
5.9
some

I need to get a view of an existing table in the following form for further work:

meas_count
skippings
links_min
links_max

10
8
0
4

10
8
4
5

10
8
5
6

10
9
0
4

10
9
4
5

10
9
5
6

11
8
0
4

11
8
4
5

11
8
5
6

11
9
0
4

11
9
4
5

11
9
5
6

At the moment I have 2 queries, the results of which I need to combine to get the result I need.

First request:

SELECT meas_count,skippings FROM current_stats GROUP BY meas_count,skippings

Creates the following:

meas_count
skippings

10
8

10
9

11
8

11
9

Second request:

SELECT
LAG(rounded) OVER (ORDER BY rounded) as links_min,
rounded as links_max FROM
(SELECT * FROM
(SELECT ROUND(links, 1) as rounded FROM current_stats)
GROUP BY rounded ORDER BY rounded)

Creates the following:

links_min
links_max

NULL
4

4
5

5
6

I need something like result of sets multiplication...

What query should be executed to get the table of the view I need as a result?

I also have an additional question: is the execution of the second query slowed down due to several SELECTs inside?

Body:
You can do that by doing an INNER JOIN on the two tables without specifying a join condition.  That will give you every combination of the two sets of rows.

SELECT * FROM
(
    SELECT meas_count,skippings
    FROM current_stats
    GROUP BY meas_count,skippings)
AS one
INNER JOIN
(
    SELECT LAG(rounded) OVER (ORDER BY rounded) as links_min,
 rounded as links_max FROM
    (SELECT * FROM
       (SELECT ROUND(links, 1) as rounded FROM current_stats)
     GROUP BY rounded
     ORDER BY rounded
    )
) AS two;

As for performance, that's really only an issue if there is a better way to do it.  Of course nested SELECTs take time, but the query optimizers in today's SQL engine are pretty good at determining what you MEANT from what you SAID.


问:
Trying to get spaces between codons and stop the generation when reaching a certain codon for RNA to protein simulation
Here's some things I need help with.

But first of all, please let me pull up the code first.

```<code>from base_printer import *

def dna_complement(dna):
  coup = ""
  for letter in dna:
    if letter == "C":
      coup += "G"
    if letter == "G":
      coup += "C"
    if letter == "A":
      coup += "T"
    if letter == "T":
      coup += "A"
  return coup

def convert_to_rna(dna):
  coup2 = ""
  for letter in dna:
    if letter == "C":
      coup2 += "G"
    if letter == "G":
      coup2 += "C"
    if letter == "A":
      coup2 += "U"
    if letter == "T":
      coup2 += "A"
  return coup2

def translate(rna):
  amino_acid = ""
  for i in range(len(rna)-2):
    three_letter = rna[i:i+3]
    if three_letter in CODON_TABLE:
      amino_acid += CODON_TABLE[three_letter]
      i += 2
  return amino_acid

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu','CUA':'Leu','CUG':'Leu','AUU':'Ile','AUC':'Ile','AUA':'Ile','AUG':'Met','GUU':'Val','GUC':'Val','GUA':'Val','GUG':'Val','UCU':'Ser','UCC':'Ser','UCA':'Ser','UCG':'Ser','CCU':'Pro','CCC':'Pro','CCA':'Pro','CCG':'Pro','ACU':'Thr','ACC':'Thr','ACA':'Thr','ACG':'Thr','GCU':'Ala','GCC':'Ala','GCA':'Ala','GCG':'Ala','UAU':'Tyr','UAC':'Tyr','UAA':'STOP','UAG':'STOP','CAU':'His','CAC':'His','CAA':'Gln','CAG':'Gln','AAU':'Asn','AAC':'Asn','AAA':'Lys','AAG':'Lys','GAU':'Asp','GAC':'Asp','GAA':'Glu','GAG':'Glu','UGU':'Cys','UGC':'Cys','UGA':'STOP','UGG':'Trp','CGU':'Arg','CGC':'Arg','CGA':'Arg','CGG':'Arg','AGU':'Ser','AGC':'Ser','AGA':'Arg','AGG':'Arg','GGU':'Gly','GGC':'Gly','GGA':'Gly','GGG':'Gly'}

dna="AAGAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTCTTAGCGGGGCCACATCGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGTTACAGCGAGCATAC"

def main():
  print("\nWelcome to the DNA program: The Code of Life.")
  print("\nSample DNA strand:\n")
  print("Regular DNA:")
  print_bases(dna)
  print("DNA after complement: ")
  dna2 = dna_complement(dna)
  print_bases(dna2)
  print("DNA after RNA convertion: ")
  rna = convert_to_rna(dna)
  print_bases(rna)
  print("The result of translation: ")
  amino_acid = translate(rna)
  print_bases(amino_acid)

main()
</code>```

I was trying to get the Codon printing out as everyone can see, the output of translation have been successfully printed out as

```<code>PHESERLEUSERLEUTYRTHRARGGLYVALSTOPASNTHRGLNARGGLYGLYGLYGLYALAPROARGGLYGLUARGGLYASPTHRARGASPTHRARGASPTHRARGGLUARGGLUASNILESERARGALAPROPROPROARGGLYVALCYSVALSTOPSERALAPROARGGLYVALTRPGLYALAARGASPTHRARGGLYGLYASPTHRARGGLYGLYGLYASPTHRPROLEUSERPROPROHISTHRPROARGGLYGLYGLYVALTRPGLYALAPROARGGLYALAGLNASNMETCYSVALSERARGALALEUSERARGVALTYRMET
</code>```

Now what I want to do is to have spaces separating each of the Codons listed in the program outputs and stop the generation once it reached UAA/UGA/UAG which is what I'm trying to figure out. But now the problem is I don't know where I should even start with which is embarrassing.

An example of output I want: Phe Ser Leu Ser Leu Tyr (Stops once reaching the UAA/UGA/UAG)

Would someone be willing to offer some tips?

Edit: Here's the information of base_print , it basically prints the output out in different colors

```<code>import colorama as cr
cr.init(autoreset=True)

def print_bases(string):
    """prints dna/rna bases with color coding for each base"""
    for char in string.upper():
        if char == "A":
            print(cr.Back.BLACK + cr.Fore.GREEN + cr.Style.BRIGHT + char, end="")
        elif char == "C":
            print(cr.Back.BLACK + cr.Fore.YELLOW + cr.Style.BRIGHT + char, end="")
        elif char == "T":
            print(cr.Back.BLACK + cr.Fore.BLUE + cr.Style.BRIGHT + char, end="")
        elif char == "G":
            print(cr.Back.BLACK + cr.Fore.MAGENTA + cr.Style.BRIGHT + char, end="")
        elif char == "U":
            print(cr.Back.BLACK + cr.Fore.WHITE + char, end="")
        else:
            print(char, end="")
    print()
</code>```

答:
Assuming you're trying to print everything prior to 'STOP' sliced into 3 characters each, here's an extension of your main function:

    res = amino_acid[:amino_acid.index('STOP')]  if 'STOP' in amino_acid else amino_acid
    res = ' '.join(res[i:i+3] for i in range(0, len(res), 3))
    print(res)
```
<p>Alternatively, if you only want to translate until you reach a stop codon <strong>and</strong> already have you amino acid with spaces, here's a modification of your <code>translate</code> function:</p>
```def translate(rna):
    amino_acid = ""
    for i in range(len(rna) - 2):
        three_letter = rna[i:i + 3]
        if three_letter in CODON_TABLE:
            next_aa = CODON_TABLE[three_letter]
            if next_aa == 'STOP':
                return amino_acid.strip()
            amino_acid += ' ' + next_aa
            i += 2
    return amino_acid.strip()
```
<p>Output:</p>
```Phe Ser Leu Ser Leu Tyr Thr Arg Gly Val
```

Body:
Here's some things I need help with.

But first of all, please let me pull up the code first.

from base_printer import *

def dna_complement(dna):
  coup = ""
  for letter in dna:
    if letter == "C":
      coup += "G"
    if letter == "G":
      coup += "C"
    if letter == "A":
      coup += "T"
    if letter == "T":
      coup += "A"
  return coup

def convert_to_rna(dna):
  coup2 = ""
  for letter in dna:
    if letter == "C":
      coup2 += "G"
    if letter == "G":
      coup2 += "C"
    if letter == "A":
      coup2 += "U"
    if letter == "T":
      coup2 += "A"
  return coup2

def translate(rna):
  amino_acid = ""
  for i in range(len(rna)-2):
    three_letter = rna[i:i+3]
    if three_letter in CODON_TABLE:
      amino_acid += CODON_TABLE[three_letter]
      i += 2
  return amino_acid

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu','CUA':'Leu','CUG':'Leu','AUU':'Ile','AUC':'Ile','AUA':'Ile','AUG':'Met','GUU':'Val','GUC':'Val','GUA':'Val','GUG':'Val','UCU':'Ser','UCC':'Ser','UCA':'Ser','UCG':'Ser','CCU':'Pro','CCC':'Pro','CCA':'Pro','CCG':'Pro','ACU':'Thr','ACC':'Thr','ACA':'Thr','ACG':'Thr','GCU':'Ala','GCC':'Ala','GCA':'Ala','GCG':'Ala','UAU':'Tyr','UAC':'Tyr','UAA':'STOP','UAG':'STOP','CAU':'His','CAC':'His','CAA':'Gln','CAG':'Gln','AAU':'Asn','AAC':'Asn','AAA':'Lys','AAG':'Lys','GAU':'Asp','GAC':'Asp','GAA':'Glu','GAG':'Glu','UGU':'Cys','UGC':'Cys','UGA':'STOP','UGG':'Trp','CGU':'Arg','CGC':'Arg','CGA':'Arg','CGG':'Arg','AGU':'Ser','AGC':'Ser','AGA':'Arg','AGG':'Arg','GGU':'Gly','GGC':'Gly','GGA':'Gly','GGG':'Gly'}

dna="AAGAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTCTTAGCGGGGCCACATCGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGTTACAGCGAGCATAC"

def main():
  print("\nWelcome to the DNA program: The Code of Life.")
  print("\nSample DNA strand:\n")
  print("Regular DNA:")
  print_bases(dna)
  print("DNA after complement: ")
  dna2 = dna_complement(dna)
  print_bases(dna2)
  print("DNA after RNA convertion: ")
  rna = convert_to_rna(dna)
  print_bases(rna)
  print("The result of translation: ")
  amino_acid = translate(rna)
  print_bases(amino_acid)

main()

I was trying to get the Codon printing out as everyone can see, the output of translation have been successfully printed out as

PHESERLEUSERLEUTYRTHRARGGLYVALSTOPASNTHRGLNARGGLYGLYGLYGLYALAPROARGGLYGLUARGGLYASPTHRARGASPTHRARGASPTHRARGGLUARGGLUASNILESERARGALAPROPROPROARGGLYVALCYSVALSTOPSERALAPROARGGLYVALTRPGLYALAARGASPTHRARGGLYGLYASPTHRARGGLYGLYGLYASPTHRPROLEUSERPROPROHISTHRPROARGGLYGLYGLYVALTRPGLYALAPROARGGLYALAGLNASNMETCYSVALSERARGALALEUSERARGVALTYRMET

Now what I want to do is to have spaces separating each of the Codons listed in the program outputs and stop the generation once it reached UAA/UGA/UAG which is what I'm trying to figure out. But now the problem is I don't know where I should even start with which is embarrassing.

An example of output I want: Phe Ser Leu Ser Leu Tyr (Stops once reaching the UAA/UGA/UAG)

Would someone be willing to offer some tips?

Edit: Here's the information of base_print , it basically prints the output out in different colors

import colorama as cr
cr.init(autoreset=True)

def print_bases(string):
    """prints dna/rna bases with color coding for each base"""
    for char in string.upper():
        if char == "A":
            print(cr.Back.BLACK + cr.Fore.GREEN + cr.Style.BRIGHT + char, end="")
        elif char == "C":
            print(cr.Back.BLACK + cr.Fore.YELLOW + cr.Style.BRIGHT + char, end="")
        elif char == "T":
            print(cr.Back.BLACK + cr.Fore.BLUE + cr.Style.BRIGHT + char, end="")
        elif char == "G":
            print(cr.Back.BLACK + cr.Fore.MAGENTA + cr.Style.BRIGHT + char, end="")
        elif char == "U":
            print(cr.Back.BLACK + cr.Fore.WHITE + char, end="")
        else:
            print(char, end="")
    print()

Body:
Assuming you're trying to print everything prior to 'STOP' sliced into 3 characters each, here's an extension of your main function:

    res = amino_acid[:amino_acid.index('STOP')]  if 'STOP' in amino_acid else amino_acid
    res = ' '.join(res[i:i+3] for i in range(0, len(res), 3))
    print(res)

Alternatively, if you only want to translate until you reach a stop codon and already have you amino acid with spaces, here's a modification of your translate function:

def translate(rna):
    amino_acid = ""
    for i in range(len(rna) - 2):
        three_letter = rna[i:i + 3]
        if three_letter in CODON_TABLE:
            next_aa = CODON_TABLE[three_letter]
            if next_aa == 'STOP':
                return amino_acid.strip()
            amino_acid += ' ' + next_aa
            i += 2
    return amino_acid.strip()

Output:

Phe Ser Leu Ser Leu Tyr Thr Arg Gly Val


问:
Immediately raise exceptions in concurrent.futures
I run several threads concurrently using concurrent.futures. All of them are necessary to run successfully for the next steps in the code to succeed.

While at the end of all processes I can raise any exceptions by running .result(), ideally any exception raised in a single thread would immediately stop all threads. This would be helpful to identify bugs in any task sooner, rather than waiting until all long-running processes complete.

Is this possible?

答:
It's possible to exit after the first exception and not submit any new jobs to the Executor. However, once a job has been submitted, it can't be cancelled, you have to wait for all submitted jobs to finish (or timeout). See this question for details. Here's a short example that cancels any unsubmitted jobs once the first exception occurs. However, it still waits for the already submitted jobs to finish. This uses the "FIRST EXCEPTION" keyword listed in the concurrent.futures docs.

```<code>import time
import concurrent.futures

def example(i):
    print(i)
    assert i != 1
    time.sleep(i)
    return i

if __name__ == "__main__":
    futures = []
    with concurrent.futures.ThreadPoolExecutor() as executor:
        for number in range(5):
            futures.append(executor.submit(example, number))

        exception = False
        for completed, running_or_error in concurrent.futures.wait(futures, return_when="FIRST_EXCEPTION"):
            try:
                 running_or_error.result()
            except Exception as e:
                for future in futures:
                    print(future.cancel()) # cancel all unstarted futures
                raise e
</code>```

Body:
It's possible to exit after the first exception and not submit any new jobs to the Executor. However, once a job has been submitted, it can't be cancelled, you have to wait for all submitted jobs to finish (or timeout). See this question for details. Here's a short example that cancels any unsubmitted jobs once the first exception occurs. However, it still waits for the already submitted jobs to finish. This uses the "FIRST EXCEPTION" keyword listed in the concurrent.futures docs.

import time
import concurrent.futures

def example(i):
    print(i)
    assert i != 1
    time.sleep(i)
    return i

if __name__ == "__main__":
    futures = []
    with concurrent.futures.ThreadPoolExecutor() as executor:
        for number in range(5):
            futures.append(executor.submit(example, number))

        exception = False
        for completed, running_or_error in concurrent.futures.wait(futures, return_when="FIRST_EXCEPTION"):
            try:
                 running_or_error.result()
            except Exception as e:
                for future in futures:
                    print(future.cancel()) # cancel all unstarted futures
                raise e


问:
How to check if object has any properties in JavaScript?
Assuming I declare

```<code>var ad = {};
</code>```

How can I check whether this object will contain any user-defined properties?

答:
I'm not sure if this is a good approach but I use this condition to check if an object has or hasn't any property. Could be easily transformed into a function.</p>
```<code>const obj = {};

if(function(){for (key in obj){return true}return false}())
{
  //do something;
}
else
{
  //do something else;
}

//Condition could be shorted by e.g. function(){for(key in obj){return 1}return 0}()
</code>```

Body:
Assuming I declare

var ad = {};

How can I check whether this object will contain any user-defined properties?

Body:
I'm not sure if this is a good approach but I use this condition to check if an object has or hasn't any property. Could be easily transformed into a function.

const obj = {};

if(function(){for (key in obj){return true}return false}())
{
  //do something;
}
else
{
  //do something else;
}

//Condition could be shorted by e.g. function(){for(key in obj){return 1}return 0}()