问:
Group and create three new columns by condition [Low, Hit, High]
I have a large dataset (~5 Mio rows) with results from a Machine Learning training. Now I want to check to see if the results hit the "target range" or not. Lets say this range contains all values between -0.25 and +0.25. If it's inside this range, it's a Hit, if it's below Low and on the other side High.

I now would create this three columns Hit, Low, High and calculate for each row which condition applies and put a 1 into this col, the other two would become 0. After that I would group the values and sum them up. But I suspect there must be a better and faster way, such as calculate it directly while grouping.

Data

```<code>import pandas as pd

df = pd.DataFrame({"Type":["RF", "RF", "RF", "MLP", "MLP", "MLP"], "Value":[-1.5,-0.1,1.7,0.2,-0.7,-0.6]})

+----+--------+---------+
|    | Type   |   Value |
|----+--------+---------|
|  0 | RF     |    -1.5 | <- Low
|  1 | RF     |    -0.1 | <- Hit
|  2 | RF     |     1.7 | <- High
|  3 | MLP    |     0.2 | <- Hit
|  4 | MLP    |    -0.7 | <- Low
|  5 | MLP    |    -0.6 | <- Low
+----+--------+---------+
</code>```

Expected Output

```<code>pd.DataFrame({"Type":["RF", "MLP"], "Low":[1,2], "Hit":[1,1], "High":[1,0]})

+----+--------+-------+-------+--------+
|    | Type   |   Low |   Hit |   High |
|----+--------+-------+-------+--------|
|  0 | RF     |     1 |     1 |      1 |
|  1 | MLP    |     2 |     1 |      0 |
+----+--------+-------+-------+--------+
</code>```

答:
You could use cut to define the groups and pivot_table to reshape:

(df.assign(group=pd.cut(df['Value'],
                        [float('-inf'), -0.25, 0.25, float('inf')],
                        labels=['Low', 'Hit', 'High']))
   .pivot_table(index='Type', columns='group', values='Value', aggfunc='count')
   .reset_index()
   .rename_axis(None, axis=1)
)
```
<p>Or <code>crosstab</code>:</p>
```(pd.crosstab(df['Type'],
             pd.cut(df['Value'],
                    [float('-inf'), -0.25, 0.25, float('inf')],
                    labels=['Low', 'Hit', 'High'])
             )
   .reset_index().rename_axis(None, axis=1)
 )
```
<p>output:</p>
```  Type  Low  Hit  High
0  MLP    2    1     0
1   RF    1    1     1
```

Body:
I have a large dataset (~5 Mio rows) with results from a Machine Learning training. Now I want to check to see if the results hit the "target range" or not. Lets say this range contains all values between -0.25 and +0.25. If it's inside this range, it's a Hit, if it's below Low and on the other side High.

I now would create this three columns Hit, Low, High and calculate for each row which condition applies and put a 1 into this col, the other two would become 0. After that I would group the values and sum them up. But I suspect there must be a better and faster way, such as calculate it directly while grouping.

Data

import pandas as pd

df = pd.DataFrame({"Type":["RF", "RF", "RF", "MLP", "MLP", "MLP"], "Value":[-1.5,-0.1,1.7,0.2,-0.7,-0.6]})

+----+--------+---------+
|    | Type   |   Value |
|----+--------+---------|
|  0 | RF     |    -1.5 | <- Low
|  1 | RF     |    -0.1 | <- Hit
|  2 | RF     |     1.7 | <- High
|  3 | MLP    |     0.2 | <- Hit
|  4 | MLP    |    -0.7 | <- Low
|  5 | MLP    |    -0.6 | <- Low
+----+--------+---------+

Expected Output

pd.DataFrame({"Type":["RF", "MLP"], "Low":[1,2], "Hit":[1,1], "High":[1,0]})

+----+--------+-------+-------+--------+
|    | Type   |   Low |   Hit |   High |
|----+--------+-------+-------+--------|
|  0 | RF     |     1 |     1 |      1 |
|  1 | MLP    |     2 |     1 |      0 |
+----+--------+-------+-------+--------+

Body:
You could use cut to define the groups and pivot_table to reshape:

(df.assign(group=pd.cut(df['Value'],
                        [float('-inf'), -0.25, 0.25, float('inf')],
                        labels=['Low', 'Hit', 'High']))
   .pivot_table(index='Type', columns='group', values='Value', aggfunc='count')
   .reset_index()
   .rename_axis(None, axis=1)
)

Or crosstab:

(pd.crosstab(df['Type'],
             pd.cut(df['Value'],
                    [float('-inf'), -0.25, 0.25, float('inf')],
                    labels=['Low', 'Hit', 'High'])
             )
   .reset_index().rename_axis(None, axis=1)
 )

output:

  Type  Low  Hit  High
0  MLP    2    1     0
1   RF    1    1     1


来源: stackexchange

问:
Powershell script to show file extensions in File Explorer
I'm fairly new to the world of Powershell and currently I'm trying to push a Powershell script via Intune to the company devices (all Windows 10 21H2 machines) that will show the file extensions in File Explorer.

So far, I've found this:

```<code>Set-Itemproperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced' -Name 'HideFileExt' -value 0
</code>```

The PS script is pushed via Intune to a test device and the monitor tells me the policy is applied successfuly but the file extensions are still not visible.

Is there something wrong with the line of code?

答:
My original comment which helped:

The script works fine. I am positive that it is not applied successfully, despite Intune telling you it did. While it is not part of that question, I suppose you should check the user context in which the script is applied and if the eventvwr or any other possible source tells you why the script did not apply correctly. Also, after trying the script locally for myself, you need to refresh the explorer tab via f5 for the change to apply.

Solution was to set it as system/device rights, since it was indeed run as user context, hence solving the problem.

ContentLicense: CC BY-SA 4.0

Body:
I'm fairly new to the world of Powershell and currently I'm trying to push a Powershell script via Intune to the company devices (all Windows 10 21H2 machines) that will show the file extensions in File Explorer.

So far, I've found this:

Set-Itemproperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced' -Name 'HideFileExt' -value 0

The PS script is pushed via Intune to a test device and the monitor tells me the policy is applied successfuly but the file extensions are still not visible.

Is there something wrong with the line of code?


问:
How can I put multiple elements into ‘elem’
Let’s say I want to do something like"ace" `elem` "abcdefg". Of course we can’t because you need a list of the first elements type. Instead is there a way we could turn this into taking every char in "ace" and comparing them individually with "abcdefg", then using or statements to combine them, but without manually doing this (because in my program it’s a variable of unknown length and characters).

答:
This is a specific case of a more general problem: you have a function Char -> Bool (or a -> Bool) and you want to adapt it as a function [a] -> Bool. In other words, what you need is a function

```<code>adaptOr :: (a -> Bool) -> ([a] -> Bool)
</code>```

Well, that's actually something you can ask Hoogle about! The first hits are

```<code>any :: (a -> Bool) -> [a] -> Bool
base GHC.List GHC.OldList
Applied to a predicate and a list, any determines if any element of the list satisfies the predicate. For the result to be False, the list must be finite; True, however, results from a True value for the predicate applied to an element at a finite index of a finite or infinite list.

>>> any (> 3) []
False

>>> any (> 3) [1,2]
False

>>> any (> 3) [1,2,3,4,5]
True

>>> any (> 3) [1..]
True

>>> any (> 3) [0, -1..]
* Hangs forever *

all :: (a -> Bool) -> [a] -> Bool
base GHC.List GHC.OldList
Applied to a predicate and a list, all determines if all elements of the list satisfy the predicate. For the result to be True, the list must be finite; False, however, results from a False value for the predicate applied to an element at a finite index of a finite or infinite list.

>>> all (> 3) []
True

>>> all (> 3) [1,2]
False

>>> all (> 3) [1,2,3,4,5]
False

>>> all (> 3) [1..]
False

>>> all (> 3) [4..]
* Hangs forever *
</code>```

Now you need to think which of these is right for your case, and then use it accordingly. You want

```<code>  all⁄any (\c -> c`elem`"abcdefg") "ace"
</code>```

This can also be written with an infix section:

```<code>  all⁄any (`elem`"abcdefg") "ace"
</code>```

Body:
This is a specific case of a more general problem: you have a function Char -> Bool (or a -> Bool) and you want to adapt it as a function [a] -> Bool. In other words, what you need is a function

adaptOr :: (a -> Bool) -> ([a] -> Bool)

Well, that's actually something you can ask Hoogle about! The first hits are

any :: (a -> Bool) -> [a] -> Bool
base GHC.List GHC.OldList
Applied to a predicate and a list, any determines if any element of the list satisfies the predicate. For the result to be False, the list must be finite; True, however, results from a True value for the predicate applied to an element at a finite index of a finite or infinite list.

>>> any (> 3) []
False

>>> any (> 3) [1,2]
False

>>> any (> 3) [1,2,3,4,5]
True

>>> any (> 3) [1..]
True

>>> any (> 3) [0, -1..]
* Hangs forever *

all :: (a -> Bool) -> [a] -> Bool
base GHC.List GHC.OldList
Applied to a predicate and a list, all determines if all elements of the list satisfy the predicate. For the result to be True, the list must be finite; False, however, results from a False value for the predicate applied to an element at a finite index of a finite or infinite list.

>>> all (> 3) []
True

>>> all (> 3) [1,2]
False

>>> all (> 3) [1,2,3,4,5]
False

>>> all (> 3) [1..]
False

>>> all (> 3) [4..]
* Hangs forever *

Now you need to think which of these is right for your case, and then use it accordingly. You want

  all⁄any (\c -> c`elem`"abcdefg") "ace"

This can also be written with an infix section:

  all⁄any (`elem`"abcdefg") "ace"


问:
Prompt user to close application during uninstall (in WiX)
I am using Windows Installer XML 3.0 (WIX3) to install some software.

Everything works fine, however, I'm having a really hard time to handle the following use case: the installed software is still running, when the user tries to uninstall it. The default behavior seems to remove all files but lets the application running (which is hard to see in my case, because it's sitting in the task tray).

I added the following code in my installer.wxs file:

```<code><InstallExecuteSequence>
  <Custom Action="WixCloseApplications" Before="RemoveFiles" />
</InstallExecuteSequence>

<util:CloseApplication Id="CloseFoobar"
                       CloseMessage="no"
                       Description="FooBar is still running!"
                       ElevatedCloseMessage="no"
                       RebootPrompt="no"
                       Target="foobar.exe" />
</code>```

But this doesn't work - even worse, it shows a dialog that asks for a reboot during install!

What would be the correct way to do it?

答:
As far as I remember it should be enough to add the following references to your UI:

```<code><DialogRef Id="FilesInUse" />
<DialogRef Id="MsiRMFilesInUse" />
</code>```

The CloseApplication stuff is only for closing applications during install, but it is buggy (at least when I tried it some months ago, maybe it's fixed now?)

Unfortunately, this is again an example for the very poor documentation of WiX, not even standard install/uninstall scenarios like this one are documented.

ContentLicense: CC BY-SA 2.5

Body:
I am using Windows Installer XML 3.0 (WIX3) to install some software.

Everything works fine, however, I'm having a really hard time to handle the following use case: the installed software is still running, when the user tries to uninstall it. The default behavior seems to remove all files but lets the application running (which is hard to see in my case, because it's sitting in the task tray).

I added the following code in my installer.wxs file:

<InstallExecuteSequence>
  <Custom Action="WixCloseApplications" Before="RemoveFiles" />
</InstallExecuteSequence>

<util:CloseApplication Id="CloseFoobar"
                       CloseMessage="no"
                       Description="FooBar is still running!"
                       ElevatedCloseMessage="no"
                       RebootPrompt="no"
                       Target="foobar.exe" />

But this doesn't work - even worse, it shows a dialog that asks for a reboot during install!

What would be the correct way to do it?

Body:
As far as I remember it should be enough to add the following references to your UI:

<DialogRef Id="FilesInUse" />
<DialogRef Id="MsiRMFilesInUse" />

The CloseApplication stuff is only for closing applications during install, but it is buggy (at least when I tried it some months ago, maybe it's fixed now?)

Unfortunately, this is again an example for the very poor documentation of WiX, not even standard install/uninstall scenarios like this one are documented.

OwnerDisplayName: divo


问:
raw_input in python variable to cmd
How can I take this code, and take the raw_input and add "ping" before it in cmd, so it'll look like this in command prompt: [ping (raw_input)]

HERE IS THE CODE:

```<code>          RS_usr = raw_input('input user here: ')
          from subprocess import Popen, PIPE, STDOUT

          p = Popen(['cmd.exe'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)

          out,err = p.communicate(input=RS_usr)
          print(out)
</code>```

答:
If I understood you correctly you should change a couple of lines in your script:</p>

```<code>p = Popen(['cmd.exe', '/k', 'set PROMPT=[Hello, (' + RS_usr + ')]' ], stdout=PIPE, stdin=PIPE, stderr=STDOUT)

out,err = p.communicate()
</code>```

ContentLicense: CC BY-SA 3.0

Title: raw_input in python variable to cmd

Body:
How can I take this code, and take the raw_input and add "ping" before it in cmd, so it'll look like this in command prompt: [ping (raw_input)]

HERE IS THE CODE:

          RS_usr = raw_input('input user here: ')
          from subprocess import Popen, PIPE, STDOUT

          p = Popen(['cmd.exe'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)

          out,err = p.communicate(input=RS_usr)
          print(out)

Body:
If I understood you correctly you should change a couple of lines in your script:

p = Popen(['cmd.exe', '/k', 'set PROMPT=[Hello, (' + RS_usr + ')]' ], stdout=PIPE, stdin=PIPE, stderr=STDOUT)

out,err = p.communicate()


问:
Why I get Execution failed for task ':app:kaptDebugKotlin' if I use Moshi?
Hy

I created an app which uses dagger, room, Moshi, Retrofit etc...

It works correctly until I add this line to my Model class : @JsonClass(generateAdapter = true)

After that I get this error:

A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution

java.lang.reflect.InvocationTargetException (no error message)

I don't know what is the problem, beacuse my another app is uses Moshi, and it works good.

I added all of the Moshi dependencies, and plugins

```<code>My gradle settings:
buildTypes {
        all {
            buildConfigField 'String', 'API_URL', "\"$apiurl\""

            lintOptions {
                abortOnError true
                //ignoreWarnings true
                fatal 'MissingTranslation', 'ExtraTranslation'
            }

        }

        debug {
            //applicationIdSuffix ".debug"
            ext.enableCrashlytics = false
            ext.alwaysUpdateBuildId = false
            multiDexEnabled true
        }

        staged {
            signingConfig signingConfigs.debug
            //applicationIdSuffix ".staged"
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro', getDefaultProguardFile('proguard-android-optimize.txt')

            matchingFallbacks = ['debug']
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro', getDefaultProguardFile('proguard-android-optimize.txt')
        }
    }

ApiModule:

  @Provides
    @Singleton
    fun provideMoshi(): Moshi {
        return Moshi.Builder()
            .add(DateConverter())
            .add(BigDecimalConverer())
            .add(KotlinJsonAdapterFactory())
            .build()
    }

@Provides
@Singleton
fun provideAuthApi(@Named("base_url") url: String, moshi: Moshi): AuthApi {

    var builder = OkHttpClient.Builder()
    builder = BuildTypeInitializations.setupInterceptor(builder)

    return Retrofit.Builder()
        .baseUrl(url)
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .client(builder.build())
        .build()
        .create(AuthApi::class.java)
}

</code>```

答: I had a similar problem where InvocationTargetException was being thrown by kapt when processing Room entities, saying something about a nonexisting type. After a long investigation I found out the library which contained the entities also used Moshi and tagged one entity with @Json annotations, but since the app which used this library did not import Moshi kapt couldn't resolve the type which caused the error. The solution was importing Moshi in the lib via "api" instead of "implementation" or importing Moshi in the client app via "implementation".

Body:
Hy

I created an app which uses dagger, room, Moshi, Retrofit etc...

It works correctly until I add this line to my Model class : @JsonClass(generateAdapter = true)

After that I get this error:

A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution

java.lang.reflect.InvocationTargetException (no error message)

I don't know what is the problem, beacuse my another app is uses Moshi, and it works good.

I added all of the Moshi dependencies, and plugins

My gradle settings:
buildTypes {
        all {
            buildConfigField 'String', 'API_URL', "\"$apiurl\""

            lintOptions {
                abortOnError true
                //ignoreWarnings true
                fatal 'MissingTranslation', 'ExtraTranslation'
            }

        }

        debug {
            //applicationIdSuffix ".debug"
            ext.enableCrashlytics = false
            ext.alwaysUpdateBuildId = false
            multiDexEnabled true
        }

        staged {
            signingConfig signingConfigs.debug
            //applicationIdSuffix ".staged"
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro', getDefaultProguardFile('proguard-android-optimize.txt')

            matchingFallbacks = ['debug']
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro', getDefaultProguardFile('proguard-android-optimize.txt')
        }
    }

ApiModule:

  @Provides
    @Singleton
    fun provideMoshi(): Moshi {
        return Moshi.Builder()
            .add(DateConverter())
            .add(BigDecimalConverer())
            .add(KotlinJsonAdapterFactory())
            .build()
    }

@Provides
@Singleton
fun provideAuthApi(@Named("base_url") url: String, moshi: Moshi): AuthApi {

    var builder = OkHttpClient.Builder()
    builder = BuildTypeInitializations.setupInterceptor(builder)

    return Retrofit.Builder()
        .baseUrl(url)
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .client(builder.build())
        .build()
        .create(AuthApi::class.java)
}


问:
sFTP with SSH Key & Password in Python
Trying to use pysftp to pull files from an sFTP server that requires both ssh key & password for authentication without much luck.  Can use pysftp with just key and just password, but it breaks when I attempt to use both.  Hoping someone has some experience with this.  Open to using a different library if that works better.

Error output is:

paramiko.ssh_exception.BadAuthenticationType: Bad authentication type; allowed types: ['publickey']

```<code>import pysftp

connection_host = '1.1.1.1'
connection_user = 'username'
connection_password = 'password'
connection_private_key = '/path/to/key'
connection_dir='/dir/on/remote/host'

with pysftp.Connection(host=connection_host, username=connection_user, password=connection_password, private_key=connection_private_key) as sftp:
    files = sftp.listdir(remotepath=connection_dir)

    for file in files:
        print("found the following file: {}".format(file))
        with sftp.cd(connection_dir):
            sftp.get(file)
</code>```

答:
Working code if anyone runs into the same issue:</p>
```<code>

connection_host = '0.0.0.0'
connection_user = 'username'
connection_password = 'password'
connection_private_key = '/path/to/key.pem'
connection_dir='/remote/path'

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)

ssh.connect(connection_host, username=connection_user, password=connection_password, key_filename=connection_private_key)
sftp_client = ssh.open_sftp()

files = sftp_client.listdir(connection_dir)
sftp_client.chdir(connection_dir)

for file in files:
    print("found the following file {}".format(file))
    sftp_client.get(file,file)

if sftp_client:
    sftp_client.close()

if ssh:
    ssh.close()
</code>```

Title: sFTP with SSH Key & Password in Python

Body:
Trying to use pysftp to pull files from an sFTP server that requires both ssh key & password for authentication without much luck.  Can use pysftp with just key and just password, but it breaks when I attempt to use both.  Hoping someone has some experience with this.  Open to using a different library if that works better.

Error output is:

paramiko.ssh_exception.BadAuthenticationType: Bad authentication type; allowed types: ['publickey']

import pysftp

connection_host = '1.1.1.1'
connection_user = 'username'
connection_password = 'password'
connection_private_key = '/path/to/key'
connection_dir='/dir/on/remote/host'

with pysftp.Connection(host=connection_host, username=connection_user, password=connection_password, private_key=connection_private_key) as sftp:
    files = sftp.listdir(remotepath=connection_dir)

    for file in files:
        print("found the following file: {}".format(file))
        with sftp.cd(connection_dir):
            sftp.get(file)

Body:
Working code if anyone runs into the same issue:

connection_host = '0.0.0.0'
connection_user = 'username'
connection_password = 'password'
connection_private_key = '/path/to/key.pem'
connection_dir='/remote/path'

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)

ssh.connect(connection_host, username=connection_user, password=connection_password, key_filename=connection_private_key)
sftp_client = ssh.open_sftp()

files = sftp_client.listdir(connection_dir)
sftp_client.chdir(connection_dir)

for file in files:
    print("found the following file {}".format(file))
    sftp_client.get(file,file)

if sftp_client:
    sftp_client.close()

if ssh:
    ssh.close()


答:
You can assign it with np.select then crosstab

```<code>c1 = df.Value<=-0.25
c2 = df.Value>=0.25
out = pd.crosstab(df['Type'], np.select([c1,c2], ['Low','High'], default='Hit'))
out
Out[32]:
col_0  High  Hit  Low
Type
MLP       0    1    2
RF        1    1    1
</code>```

Title: Group and create three new columns by condition [Low, Hit, High]

Body:
You can assign it with np.select then crosstab

c1 = df.Value<=-0.25
c2 = df.Value>=0.25
out = pd.crosstab(df['Type'], np.select([c1,c2], ['Low','High'], default='Hit'))
out
Out[32]:
col_0  High  Hit  Low
Type
MLP       0    1    2
RF        1    1    1


问:
Most efficient way to search for object in an array by a specific property's value
What would be the fastest, most efficient way to implement a search method that will return an object with a qualifying id?

Sample object array:

```<code>$array = [
    (object) ['id' => 'one', 'color' => 'white'],
    (object) ['id' => 'two', 'color' => 'red'],
    (object) ['id' => 'three', 'color' => 'blue']
];
</code>```

What do I write inside of:

```<code>function findObjectById($id){

}
</code>```

The desired result would return the object at $array[0] if I called:

```<code>$obj = findObjectById('one')
</code>```

Otherwise, it would return false if I passed 'four' as the parameter.

答:
Well, you would would have to loop through them and check compare the ID's unless your array is sorted (by ID) in which case you can implement a searching algorithm like binary search or something of that sort to make it quicker.

My suggestion would be to first sort the arrays using a sorting algorithm (binary sort, insertion sort or quick sort) if the array is not sorted already. Then you can implement a search algorithm which should improve performance and I think that's as good as it gets.

http://www.algolist.net/Algorithms/Binary_search

Body:
What would be the fastest, most efficient way to implement a search method that will return an object with a qualifying id?

Sample object array:

$array = [
    (object) ['id' => 'one', 'color' => 'white'],
    (object) ['id' => 'two', 'color' => 'red'],
    (object) ['id' => 'three', 'color' => 'blue']
];

What do I write inside of:

function findObjectById($id){

}

The desired result would return the object at $array[0] if I called:

$obj = findObjectById('one')

Otherwise, it would return false if I passed 'four' as the parameter.


问:
Angular Service Worker (ngsw) or Workbox
Please let me ask a question.

Firstly,I would like to build angular progressive web app.

And I found that I can use angular native service worker (ngsw) or also framework-agnostic library called Workbox to build progressive web app.

Which approach is easier to start with, which library is simpler to use, and which resulting PWA is more convenient to maintain.

Which library should I use ,please advice me(ngsw or  workbox)

Please can somebody explain with pros and cons.

答:
I took this information from the International Javascript Conference and the Angular University.

Both have been created for the same purpose, to implement a service worker in your projects, ngsw is easier and workbox is more configurable.

Angular Service Worker (ngsw)

Easy to start ng add @angular/pwa --project <name of project as in angular.json>

Seamless integration with angular

Coding-free basic features

Angular-friendly approach

In a sentence...

ngsw is everything the Angular team thinks a project needs to implement a service worker.

Workbox

Framework-agnostic npm install workbox-build --save-dev

Rich functionality

Maximum flexible configuration

Full power of your own service worker

In a sentence...

workbox helps you create a fully configurable service worker. It's like ngsw but on steroids.


问:
Select columns which have more the 2 values in other column
I have a table which have 3 columns and we need to select data of those rows which have multiple entry in the table.

```<code> Column1  Colum2    Colum3
 ---------------------------
 ARRG   | MEM      | 10.12
 ARRG   | MHH      | 0.245
 ARRG   | MHH      | 0.246
 ABC    | HQ       | 0.246
 CDE    | PRT      | 97.0
 TST    | TRY      | 97.0
</code>```

Now I want to write a query to select rows from Column1 which have unique values in Colum2
Basically i want to print the rows of ARRG as this have 2 different values in Colum2.

```<code>ARRG   | MEM      | 10.12
ARRG   | MHH      | 0.245
</code>```

答:
Try:

```<code>select Column1,Colum2,Colum3
from test
where Column1 in (select Column1
                  from test
                  group by Column1
                  having count(distinct Colum2)>1
                 )
group by Column1,Colum2,Colum3;
</code>```

Demo

Body:
I have a table which have 3 columns and we need to select data of those rows which have multiple entry in the table.

 Column1  Colum2    Colum3
 ---------------------------
 ARRG   | MEM      | 10.12
 ARRG   | MHH      | 0.245
 ARRG   | MHH      | 0.246
 ABC    | HQ       | 0.246
 CDE    | PRT      | 97.0
 TST    | TRY      | 97.0

Now I want to write a query to select rows from Column1 which have unique values in Colum2
Basically i want to print the rows of ARRG as this have 2 different values in Colum2.

ARRG   | MEM      | 10.12
ARRG   | MHH      | 0.245

Body:
Try:

select Column1,Colum2,Colum3
from test
where Column1 in (select Column1
                  from test
                  group by Column1
                  having count(distinct Colum2)>1
                 )
group by Column1,Colum2,Colum3;

Demo


问:
How do I filter view controller by type?
This is my simple function:

```<code>func popTo<T: UIViewController>(type: T.Type, from context: UINavigationController?) {
    let mytype = type
    guard let controller = context?.viewControllers.first(where: { $0 is T }) else {
        return
    }
    print(mytype) //1
    print(context?.viewControllers) //2
    print(controller) //3
    context?.popToViewController(controller, animated: true)
}
</code>```

After I put a breakpoint and print out the following lines, I get console output:

```<code>PLZ.GroupViewController //1

▿ Optional<Array<UIViewController>> //2
  ▿ some : 5 elements
    ▿ 0 : <PLZ.GroupsViewController: 0x11dd68660>
    ▿ 1 : <PLZ.GroupViewController: 0x11f415c70>
    ▿ 2 : <PLZ.ProductViewController: 0x11f619d00>
    ▿ 3 : <PLZ.ConfirmViewController: 0x11f538cd0>
    ▿ 4 : <PLZ.ConfirmationViewController: 0x11f53e330>

<PLZ.GroupsViewController: 0x11dd68660> //3
</code>```

Why it returns GroupsViewController when it should GroupViewController?

How do I call that function?

```<code>if let type = viewModel.returnControllerType {
    print(type) //4
    self?.router.popTo(type: type, from: self?.navigationController)
}

PLZ.GroupViewController //4
</code>```

returnControllerType is defined:

```<code>let returnControllerType: UIViewController.Type?
</code>```

答:
The simplest solution ever is:</p>
```<code>func popTo<T: UIViewController>(type: T.Type, from context: UINavigationController?) {
    guard let controller = context?.viewControllers.first(where: { $0.isKind(of: type) }) else {
        return
    }
    context?.popToViewController(controller, animated: true)
}
</code>```

Body:
This is my simple function:

func popTo<T: UIViewController>(type: T.Type, from context: UINavigationController?) {
    let mytype = type
    guard let controller = context?.viewControllers.first(where: { $0 is T }) else {
        return
    }
    print(mytype) //1
    print(context?.viewControllers) //2
    print(controller) //3
    context?.popToViewController(controller, animated: true)
}

After I put a breakpoint and print out the following lines, I get console output:

PLZ.GroupViewController //1

▿ Optional<Array<UIViewController>> //2
  ▿ some : 5 elements
    ▿ 0 : <PLZ.GroupsViewController: 0x11dd68660>
    ▿ 1 : <PLZ.GroupViewController: 0x11f415c70>
    ▿ 2 : <PLZ.ProductViewController: 0x11f619d00>
    ▿ 3 : <PLZ.ConfirmViewController: 0x11f538cd0>
    ▿ 4 : <PLZ.ConfirmationViewController: 0x11f53e330>

<PLZ.GroupsViewController: 0x11dd68660> //3

Why it returns GroupsViewController when it should GroupViewController?

How do I call that function?

if let type = viewModel.returnControllerType {
    print(type) //4
    self?.router.popTo(type: type, from: self?.navigationController)
}

PLZ.GroupViewController //4

returnControllerType is defined:

let returnControllerType: UIViewController.Type?

Body:
The simplest solution ever is:

func popTo<T: UIViewController>(type: T.Type, from context: UINavigationController?) {
    guard let controller = context?.viewControllers.first(where: { $0.isKind(of: type) }) else {
        return
    }
    context?.popToViewController(controller, animated: true)
}


问:
No migrations to apply
```<code>$python manage.py syncdb
Operations to perform:
  Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
  No migrations to apply.
  Your models have changes that are not yet reflected in a migration, and so won't be applied.
  Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
</code>```

the error printscreen

i don't know what the problem !

答:
Hi my friend after all these steps if there was still this problem.

1- Clear all tables in the database.

2-Clear all history in the migrations folder of your project directory.

3-python manage.py makemigrations

4-python manage.py migrate

Title: No migrations to apply

Body:
$python manage.py syncdb
Operations to perform:
  Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
  No migrations to apply.
  Your models have changes that are not yet reflected in a migration, and so won't be applied.
  Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

the error printscreen

i don't know what the problem !


问:
Is declaring a field volatile enough in case of a single writing thread?
Consider the following code:

```<code>public class MyAtomicInteger {
    private volatile int value;

    public int get() {
        return value;
    }

    public void increment() {
        value++;
    }

}
</code>```

I was asked the following question during an interview: is this code thread-safe if only one thread calls increment() and multiple threads can call get()?

I understand that if we have multiple writing threads, race conditions can occur. However, when there is a single writing thread in each reading thread we will get the values in order, i.e. we won't read 0 after 1 because write of 1 happens before the first read of 1 and, consequently, all subsequent reads in the same thread. Is this reasoning correct, or I am missing something?

答:
It is sufficient to have only volatile.

What is required is that a happens-before edge needs to exist between the read and the write. Otherwise, there is a data race. And a volatile generates such happens before edges.

These happens-before edges prevent reading an older value after you read a newer value. A correctly synchronized program in Java is only allowed to have sequential consistent executions. Every sequential consistent execution is automatically coherent because coherence is a relaxation of sequential consistency. And coherence prevents reading an older value after a newer value is read.

[note]
If you would have concurrent increments, with a volatile variable you will not have a data race, but you will have a race condition.

Body:
Consider the following code:

public class MyAtomicInteger {
    private volatile int value;

    public int get() {
        return value;
    }

    public void increment() {
        value++;
    }

}

I was asked the following question during an interview: is this code thread-safe if only one thread calls increment() and multiple threads can call get()?

I understand that if we have multiple writing threads, race conditions can occur. However, when there is a single writing thread in each reading thread we will get the values in order, i.e. we won't read 0 after 1 because write of 1 happens before the first read of 1 and, consequently, all subsequent reads in the same thread. Is this reasoning correct, or I am missing something?


问:
Search for value contained in array of objects in property of object contained in array
can someone help me with this?
I need a function that given a fieldID, searchs within objects and returns the objectID that fieldID is in.

```<code>  const objects = [
    {
      objectID: 11,
      fields: [
        { id: 12, name: 'Source ID' },
        { id: 12, name: 'Source ID' },
      ],
    },
    {objectID: 14,
      fields: [
        { id: 15, name: 'Creator' },
      ],},
    {objectID: 16,
      fields: [
        { id: 17, name: 'Type' },
        { id: 18, name: 'Name' },
        { id: 19, name: 'Description' },
      ],},
  ];
</code>```

SOLVED:
Got it working like this:

```<code> const getObjectID = fieldId => {
    for (const object of objects) {
      if (object.fields.find(field => field.id === fieldId)) {
        return object.objectID;
      }
    }
  };
</code>```

答:
Using the find array method:

const objects = [
  { objectId: 1, fields: ["aaa"] },
  { objectId: 2, fields: ["bbb"] },
  { objectId: 3, fields: ["ccc"] },
];

const getObjectId = (id) => objects.find(object.objectId === id);

console.log(getObjectId(2));
// { objectId: 2, fields: ["bbb"] }
```

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Body:
can someone help me with this?
I need a function that given a fieldID, searchs within objects and returns the objectID that fieldID is in.

  const objects = [
    {
      objectID: 11,
      fields: [
        { id: 12, name: 'Source ID' },
        { id: 12, name: 'Source ID' },
      ],
    },
    {objectID: 14,
      fields: [
        { id: 15, name: 'Creator' },
      ],},
    {objectID: 16,
      fields: [
        { id: 17, name: 'Type' },
        { id: 18, name: 'Name' },
        { id: 19, name: 'Description' },
      ],},
  ];

SOLVED:
Got it working like this:

 const getObjectID = fieldId => {
    for (const object of objects) {
      if (object.fields.find(field => field.id === fieldId)) {
        return object.objectID;
      }
    }
  };

Body:
Using the find array method:

const objects = [
  { objectId: 1, fields: ["aaa"] },
  { objectId: 2, fields: ["bbb"] },
  { objectId: 3, fields: ["ccc"] },
];

const getObjectId = (id) => objects.find(object.objectId === id);

console.log(getObjectId(2));
// { objectId: 2, fields: ["bbb"] }

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find


Title: Concatenate numpy arrays to a single array

Body:
I am trying to merge the two <class 'numpy.ndarray'> into a single array.

Code that I tried:

for emb in embs:
   print(np.concatenate( emb['name'], axis=0 ))

Input:

[[-0.05646843 -0.00381141 -0.05721215 0.06029008]
 [-0.02690301  0.04218878  0.00404305 0.05841358]]
[[-0.02675129  0.03649405 -0.04379312 -0.04826404]
 [ 0.01131434  0.0581139   0.00785002  -0.02065904]]

Output:

[[-0.05646843 -0.00381141 -0.05721215 0.06029008]
 [-0.02690301  0.04218878  0.00404305 0.05841358]
 [-0.02675129  0.03649405 -0.04379312 -0.04826404]
 [ 0.01131434  0.0581139   0.00785002  -0.02065904]]

Any leads would be appreciated.

Body:
input :

data1 = [[-0.05646843 ,-0.00381141,  -0.05721215, 0.06029008],
         [-0.02690301 , 0.04218878 , 0.00404305, 0.05841358]]

data2 = [[-0.02675129 , 0.03649405, -0.04379312, -0.04826404],
         [ 0.01131434 , 0.0581139 ,  0.00785002 , -0.02065904]]

output:

concatenated_data = np.concatenate((np.array(data1),np.array(data2)))

print(concatenated_data)


问:
infinitetly loop array with setTimeout javascript
I have an array of strings that I'm passing to a for loop with a setTimeout inside.
I've tried to for(; ;) and while(true) the function but this just causes the browser to crash.

I've also tried adding an if statement inside the function

```<code>if (x == links.length) { loopUrls() }
</code>```

Which works kind of but skips the entire interval section of the function, cycling the entire array infinitely with no wait.

```<code>        function loopUrls() {
            for (var x = 0, ln = links.length; x < ln; x++) {
                setTimeout(function (y) {
                    document.getElementById('ifURLS').src = links[y];
                },x * 500,x);
            }
    };

    loopUrls();
</code>```

The aim is to have a list of urls that infinitely assigned to the iframe to show reports on a sreen. (the time interval is just small for testing purposes)

答:
If I understand correctly, you want for every link to have some function that is being executed every X milliseconds.

In order to achieve this I think it's better to use setInterval.

You can do something like:

```<code>links.forEach((link) => {
  setInterval(() => {
    //do something every X milliseconds
  }, X)
})
</code>```

Body:
I have an array of strings that I'm passing to a for loop with a setTimeout inside.
I've tried to for(; ;) and while(true) the function but this just causes the browser to crash.

I've also tried adding an if statement inside the function

if (x == links.length) { loopUrls() }

Which works kind of but skips the entire interval section of the function, cycling the entire array infinitely with no wait.

        function loopUrls() {
            for (var x = 0, ln = links.length; x < ln; x++) {
                setTimeout(function (y) {
                    document.getElementById('ifURLS').src = links[y];
                },x * 500,x);
            }
    };

    loopUrls();

The aim is to have a list of urls that infinitely assigned to the iframe to show reports on a sreen. (the time interval is just small for testing purposes)

Body:
If I understand correctly, you want for every link to have some function that is being executed every X milliseconds.

In order to achieve this I think it's better to use setInterval.

You can do something like:

links.forEach((link) => {
  setInterval(() => {
    //do something every X milliseconds
  }, X)
})


问:
Why isn't there space between my menu items?
I'm making a test site to get better at html and CSS. I found a design and started to try to make that design right now I have this:

But as you can see the navbar items are way too close to each other and for some reason the icon wont show up.

can someone explain to me why the navbar items wont get space between each other and why my icon is not showing up? Thanks in advance.

nav {
  display: flex;
  justify-content: space-between;
  padding: 1rem;
}

nav .logo {
  font-size: 2.5rem;
}

nav ul {
  display: flex;
  list-style-type: none;
  padding: 0;
}

nav li a {
  color: white;
  padding: 1rem 2rem;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class='container'>
  <div class='logo'><i class="fa-solid fa-otter"></i>Sea otters</div>

  <ul>
    <li a href='#'>Home</li>
    <li a href='#'>Species</li>
    <li a href='#'>Habitat</li>
    <li a href='#'>Behavior</li>
    <li a href='#' class='highlight'>Ecology</li>
  </ul>
</nav></code>```

答:
You've merged your list item and anchor element markup. They're separate elements and need separate tags.</p>
```<code><li><a href='#'>Home</a></li>
</code>```

Body:
I'm making a test site to get better at html and CSS. I found a design and started to try to make that design right now I have this:

But as you can see the navbar items are way too close to each other and for some reason the icon wont show up.

can someone explain to me why the navbar items wont get space between each other and why my icon is not showing up? Thanks in advance.

nav {
  display: flex;
  justify-content: space-between;
  padding: 1rem;
}

nav .logo {
  font-size: 2.5rem;
}

nav ul {
  display: flex;
  list-style-type: none;
  padding: 0;
}

nav li a {
  color: white;
  padding: 1rem 2rem;
  text-decoration: none;
}

Sea otters

Home

Species

Habitat

Behavior

Ecology

Body:
You've merged your list item and anchor element markup. They're separate elements and need separate tags.

<li><a href='#'>Home</a></li>


问:
return a boolean value from request to use it outside the request response promise
I have the following method

```<code>function testSkipping(channel='US', test:any) : boolean{
cy.log(test) // will print SkipPaymentTests

    cy.request({
        method: 'GET',
        url: Cypress.env('EndPoint') + 'features',
        headers: {
            'Channel': `${channel}`,
            'Subscription-Key': Cypress.env('sKey'),
        }
    }).then(function (response) {
            if (response?.status === 200) {
                expect(response.body.feature).to.exist;
            cy.log(response.body.featureFlags.test)

                if (response.body.feature[`${test}`]) {
                    return true /// I need to return this value
                } else
                {
                  return false // I need to return this value
                }
            }
        }
    )
}
</code>```

this code does not return the proper value stored in the backend

the response of the call is

```<code>{
"SkipPaymentTests":true
}
</code>```

答:
I don't think return will give you proper value here. You can try to create global variable and set as below :</p>
```<code>var sucessValue = false;
function testSkipping(channel='US', test:any) : boolean{
cy.log(test) // will print SkipPaymentTests

    cy.request({
        method: 'GET',
        url: Cypress.env('EndPoint') + 'features',
        headers: {
            'Channel': `${channel}`,
            'Subscription-Key': Cypress.env('sKey'),
        }
    }).then(function (response) {
            if (response?.status === 200) {
                expect(response.body.feature).to.exist;
            cy.log(response.body.featureFlags.test)

                if (response.body.feature[`${test}`]) {
                    sucessValue = true; /// I need to return this value
                } else
                {
                  sucessValue = false; // I need to return this value
                }
            }
        }
    )
}
</code>```

Body:
I have the following method

function testSkipping(channel='US', test:any) : boolean{
cy.log(test) // will print SkipPaymentTests

    cy.request({
        method: 'GET',
        url: Cypress.env('EndPoint') + 'features',
        headers: {
            'Channel': `${channel}`,
            'Subscription-Key': Cypress.env('sKey'),
        }
    }).then(function (response) {
            if (response?.status === 200) {
                expect(response.body.feature).to.exist;
            cy.log(response.body.featureFlags.test)

                if (response.body.feature[`${test}`]) {
                    return true /// I need to return this value
                } else
                {
                  return false // I need to return this value
                }
            }
        }
    )
}

this code does not return the proper value stored in the backend

the response of the call is

{
"SkipPaymentTests":true
}

Body:
I don't think return will give you proper value here. You can try to create global variable and set as below :

var sucessValue = false;
function testSkipping(channel='US', test:any) : boolean{
cy.log(test) // will print SkipPaymentTests

    cy.request({
        method: 'GET',
        url: Cypress.env('EndPoint') + 'features',
        headers: {
            'Channel': `${channel}`,
            'Subscription-Key': Cypress.env('sKey'),
        }
    }).then(function (response) {
            if (response?.status === 200) {
                expect(response.body.feature).to.exist;
            cy.log(response.body.featureFlags.test)

                if (response.body.feature[`${test}`]) {
                    sucessValue = true; /// I need to return this value
                } else
                {
                  sucessValue = false; // I need to return this value
                }
            }
        }
    )
}


答: The information you are looking for is in 'clusters', where each list corresponds to an entity. Within each entity list, you will find the mentions referring to the same entity. The number are indices that mark the beginning and ending of each coreferential mention. E.g. Paul Allen [0,1] and Allen [24, 24].</p>

Title: How to interpret Allen NLP Coreference resolution model output?

Body:
I am working on extracting people and tasks from texts (multiple sentences) and need a way to resolve coreferencing. I found this model, and it seems very promising, but once I installed the required libraries allennlp and allennlp_models and testing the model out for myself I got:

Script:

predictor = Predictor.from_path("https://storage.googleapis.com/allennlp-public-models/coref-spanbert-large-2021.03.10.tar.gz")
prediction = predictor.predict(
    document="Paul Allen was born on January 21, 1953, in Seattle, Washington, to Kenneth Sam Allen and Edna Faye Allen. Allen attended Lakeside School, a private school in Seattle, where he befriended Bill Gates, two years younger, with whom he shared an enthusiasm for computers.")
print(prediction)

Output:

{'top_spans': [[0, 1], [3, 3], [5, 8], [5, 14], [8, 8], [11, 13], [11, 14], [13, 13], [16, 18], [16, 22], [20, 22], [24, 24], [26, 52], [33, 33], [36, 36], [37, 37], [38, 52], [41, 42], [47, 47], [48, 48], [49, 52]],
 'antecedent_indices': [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]],
 'predicted_antecedents': [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, 5, 11, -1, -1, -1, 11, -1, -1],
 'document': ['Paul', 'Allen', 'was', 'born', 'on', 'January', '21', ',', '1953', ',', 'in', 'Seattle', ',', 'Washington', ',', 'to', 'Kenneth', 'Sam', 'Allen', 'and', 'Edna', 'Faye', 'Allen', '.', 'Allen', 'attended', 'Lakeside', 'School', ',', 'a', 'private', 'school', 'in', 'Seattle', ',', 'where', 'he', 'befriended', 'Bill', 'Gates', ',', 'two', 'years', 'younger', ',', 'with', 'whom', 'he', 'shared', 'an', 'enthusiasm', 'for', 'computers', '.'],
 'clusters': [[[0, 1], [24, 24], [36, 36], [47, 47]], [[11, 13], [33, 33]]]}

I'm having trouble interpreting the format of this output. I was expecting something like

{entity_0_spans: [LIST_OF_INDEX_TUPLES],  # Paul Allen in this example
 entity_1_spans: [LIST_OF_INDEX_TUPLES],  # Seattle in this example
 ...}

or something that more closely resembles the visualisation available on the demo page:

I've looked through https://demo.allennlp.org/coreference-resolution but couldn't find a breakdown of how to use the model output yet - can anyone suggest some resources that will help me? Any pointers are much appreciated!


问:
selenium keeps asking me for a service even though i already have have passed it
I am trying to run my selenium project on heroku but i keep getting this error

```<code>DeprecationWarning: executable_path has been deprecated, please pass in a Service object
</code>```

this is error did not show before when i was running the code on computer,
so i searched about and now instead of this:

```<code>driver = webdriver.Chrome( options=options,executable_path=os.environ.get("CHROMEDRIVER_PATH"))
</code>```

im writing this:

```<code> driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options,executable_path=os.environ.get("CHROMEDRIVER_PATH"))
</code>```

but i keeps getting the same error does anyone knows why is this?

答: just remove executable_path and it should work</p>

Body:
I am trying to run my selenium project on heroku but i keep getting this error

DeprecationWarning: executable_path has been deprecated, please pass in a Service object

this is error did not show before when i was running the code on computer,
so i searched about and now instead of this:

driver = webdriver.Chrome( options=options,executable_path=os.environ.get("CHROMEDRIVER_PATH"))

im writing this:

 driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options,executable_path=os.environ.get("CHROMEDRIVER_PATH"))

but i keeps getting the same error does anyone knows why is this?


问:
define score limit for pylint with pre-commit git hook
I am trying to set a accepted pylint score limit for my pre-commit git hook. I have tried two approaches:

A) adding it to the .pylintrc file

```<code>[pre-commit-hook]
command=custom_pylint
disable=E0401, C0301
limit=8.0
</code>```

B) adding it as argument to .pre-commit-config.yaml

```<code>  - repo: https://github.com/pycqa/pylint
    rev: v2.12.2
    hooks:
      - id: pylint
        args:
          - --limit=7
          - --rcfile=./.pylintrc
</code>```

Sadly for A, it just does not except it independent of the score. For B, I get the error, pylint: error: no such option: --limit.

Best regards

答:
You should use --fail-under=7, not --limit see documentation.

You can also read the output of pylint --help.

Body:
I am trying to set a accepted pylint score limit for my pre-commit git hook. I have tried two approaches:

A) adding it to the .pylintrc file

[pre-commit-hook]
command=custom_pylint
disable=E0401, C0301
limit=8.0

B) adding it as argument to .pre-commit-config.yaml

  - repo: https://github.com/pycqa/pylint
    rev: v2.12.2
    hooks:
      - id: pylint
        args:
          - --limit=7
          - --rcfile=./.pylintrc

Sadly for A, it just does not except it independent of the score. For B, I get the error, pylint: error: no such option: --limit.

Best regards


问:
ERR_SSL_VERSION_OR_CIPHER_MISMATCH error on Chrome only
While opening my private website, I am getting the following error in CHROME only.  in internet explorer its working without any issue.

I tried resetting chrome, delete all cache but no luck. nothing changed from backend site and error was started as of sudden.

weird thing is, if I open Fiddler 4 at the same time then its working. don't know what Fiddler is doing to fix that prob but when I close it again, then its again giving the same error.

答:
RC4 is a 30 year old cipher and TLS 1.0 is also outdated and insecure - as per security reasons enterprise managed devices are not allowed to use them.

Even if you find a with a temporary workaround (Going back to Chrome 97 and enable  chrome://flags/#enable-quic) TLS 1.0 and 1.1 will be deprecated and your website host will need to update their Transport Layer Security.

This issue is listed in the official Google Known issues article:
https://support.google.com/chrome/a/known-issues/1700835?visit_id=1-636640442263392447-217633526&hl=en&rd=1

I have also found a third party article with additional information on the matter:
https://blog.pcisecuritystandards.org/are-you-ready-for-30-june-2018-sayin-goodbye-to-ssl-early-tls


问:
Error in R: Unused arguments: Error in SN(0.1, 0, 1, 0.4, 0) : unused arguments (0.4, 0)
I have following code:

```<code>SN<- function(n) {
  SE<-0
  for(i in 1:n){
    if(i==1){
      SE<- x[i]*(1/t*(1-exp(-x[n+1]*t)))
    }
    if(i!=1){
      SE<-x[i+1]*(SE*i-(((x[n+1]*t)^(i)*exp(-x[n+1]*t))/(x[n+1])))
    }
  }
  SE<-x[n+2]+(1/t)*SE
  return(SE)
}

SN(c(0.1,0,1),0.4,1)

</code>```

My goal was to set x[0]=0.1, x[1]=0, x[2]=1, t=0.4 and n=1

But i got error: Error in SN(0.1, 0, 1, 0.4, 0) : unused arguments (0.4, 0)

I know that there is a mistake that argument used does not match the arguments in the argument list. But in my case I do not know how to fix it.

Any help?

答:
This produces an answer.  You'll have to make sure it's the answer you think it should be:

  SN<- function(x,t,n) {
  SE<-0
  for(i in 1:n){
    if(i==1){
      SE<- x[i]*(1/t*(1-exp(-x[n+1]*t)))
    }
    if(i!=1){
      SE<-x[i+1]*(SE*i-(((x[n+1]*t)^(i)*exp(-x[n+1]*t))/(x[n+1])))
    }
  }
  SE<-x[n+2]+(1/t)*SE
  return(SE)
}

SN(c(0.1,0,1),0.4,1)
#> [1] 1
```

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

Body:
I have following code:

SN<- function(n) {
  SE<-0
  for(i in 1:n){
    if(i==1){
      SE<- x[i]*(1/t*(1-exp(-x[n+1]*t)))
    }
    if(i!=1){
      SE<-x[i+1]*(SE*i-(((x[n+1]*t)^(i)*exp(-x[n+1]*t))/(x[n+1])))
    }
  }
  SE<-x[n+2]+(1/t)*SE
  return(SE)
}

SN(c(0.1,0,1),0.4,1)

My goal was to set x[0]=0.1, x[1]=0, x[2]=1, t=0.4 and n=1

But i got error: Error in SN(0.1, 0, 1, 0.4, 0) : unused arguments (0.4, 0)

I know that there is a mistake that argument used does not match the arguments in the argument list. But in my case I do not know how to fix it.

Any help?

Body:
This produces an answer.  You'll have to make sure it's the answer you think it should be:

  SN<- function(x,t,n) {
  SE<-0
  for(i in 1:n){
    if(i==1){
      SE<- x[i]*(1/t*(1-exp(-x[n+1]*t)))
    }
    if(i!=1){
      SE<-x[i+1]*(SE*i-(((x[n+1]*t)^(i)*exp(-x[n+1]*t))/(x[n+1])))
    }
  }
  SE<-x[n+2]+(1/t)*SE
  return(SE)
}

SN(c(0.1,0,1),0.4,1)
#> [1] 1

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


问:
EF Core : expression trees - GroupJoin transform to SelectMany dynamically
I would like to transform the below query:

```<code>(from documentType in entitySet
 join userGroupId in Repository.ConvertToBigIntTable(userGroupIds, "userGroupId")
      on documentType.Id equals userGroupId.Id into UserGroupIds
 from userGroupId in UserGroupIds.DefaultIfEmpty()
 join documentTypePermission in Repository.DocumentTypePermissions
      on documentType.Id equals documentTypePermission.DocumentTypeId
 join userSelectionParam in Repository.UserSelectionParams
      on documentTypePermission.UserSelectionId equals userSelectionParam.Id
 where documentTypePermission.IsActive &&
       ((userSelectionParam.UserGroupId != null && userGroupId.Id != null)
        || (userSelectionParam.UserId != null && userSelectionParam.UserId == CurrentUserId))
 select documentTypePermission);
</code>```

to something like this:

```<code>
var query =
    from documentType in entitySet
    from userGroupId in Repository.ConvertToBigIntTable(userGroupIds, "userGroupId")
        .Where(userGroupId => documentType.Id == userGroupId.Id)
        .DefaultIfEmpty()
    join documentTypePermission in Repository.DocumentTypePermissions
        on documentType.Id equals documentTypePermission.DocumentTypeId
    join userSelectionParam in Repository.UserSelectionParams
        on documentTypePermission.UserSelectionId equals userSelectionParam.Id

    ....

</code>```

Note:

I have the setup ready for intercepting the expression tree evaluation using QueryTranslationPreprocessor

I need the logic to generate the output of .Call, .SelectMany etc by using the first linq and then translating the same to second linq query shown above

The caveats are that internally the expression engine generates so many Anonymous types that I am unable to write a generic code that would suffice different cases of linq with such groupjoins

Reason to do this:

There are several kinds of GroupJoin issues in EF Core 6 which the community isn’t ready to resolve

I can't make the change to Linq query directly as there are 1000s of them and in several places

答:
So after evaluating multiple options, the best way to do the above is as below at VisitMethodCall(MethodCallExpression node)</p>
```<code>        if (node.Method.DeclaringType == typeof(Queryable) && node.Method.Name == nameof(Queryable.GroupJoin) && node.Arguments.Count == 5)
        {
            var outer = Visit(node.Arguments[0]);
            var inner = Visit(node.Arguments[1]);
            var outerKeySelector = Visit(node.Arguments[2]).UnwrapLambdaFromQuote();
            var innerKeySelector = Visit(node.Arguments[3]).UnwrapLambdaFromQuote();
            var resultSelector = Visit(node.Arguments[4]).UnwrapLambdaFromQuote();

            var outerKey = outerKeySelector.Body.ReplaceParameter(outerKeySelector.Parameters[0], resultSelector.Parameters[0]);
            var innerKey = innerKeySelector.Body;
            var keyMatch = MatchKeys(outerKey, innerKey);

            var innerQuery = Expression.Call(
                typeof(Queryable), nameof(Queryable.Where), new[] { innerKeySelector.Parameters[0].Type },
                inner, Expression.Lambda(keyMatch, innerKeySelector.Parameters));

            var asEnumerableInnerQuery = Expression.Call(
                            typeof(Enumerable),
                            nameof(Enumerable.AsEnumerable),
                            new Type[] { innerKeySelector.Parameters[0].Type }, innerQuery);

            var resultTypes = resultSelector.Parameters.Select(p => p.Type).ToArray();
            var tempProjectionType = typeof(Tuple<,>).MakeGenericType(resultTypes);
            var tempProjection = Expression.New(
                tempProjectionType.GetConstructor(resultTypes),
                new Expression[] { resultSelector.Parameters[0], asEnumerableInnerQuery },
                tempProjectionType.GetProperty("Item1"), tempProjectionType.GetProperty("Item2"));

            var tempQuery = Expression.Call(
                typeof(Queryable), nameof(Queryable.Select), new[] { outerKeySelector.Parameters[0].Type, tempProjectionType },
                outer, Expression.Lambda(tempProjection, resultSelector.Parameters[0]));

            var tempResult = Expression.Parameter(tempProjectionType, "p");
            var projection = resultSelector.Body
                .ReplaceParameter(resultSelector.Parameters[0], Expression.Property(tempResult, "Item1"))
                .ReplaceParameter(resultSelector.Parameters[1], Expression.Property(tempResult, "Item2"));

            var query = Expression.Call(
                typeof(Queryable), nameof(Queryable.Select), new[] { tempProjectionType, projection.Type },
                tempQuery, Expression.Lambda(projection, tempResult));
            return query;
        }
        return base.VisitMethodCall(node);
    }
</code>```

Body:
I would like to transform the below query:

(from documentType in entitySet
 join userGroupId in Repository.ConvertToBigIntTable(userGroupIds, "userGroupId")
      on documentType.Id equals userGroupId.Id into UserGroupIds
 from userGroupId in UserGroupIds.DefaultIfEmpty()
 join documentTypePermission in Repository.DocumentTypePermissions
      on documentType.Id equals documentTypePermission.DocumentTypeId
 join userSelectionParam in Repository.UserSelectionParams
      on documentTypePermission.UserSelectionId equals userSelectionParam.Id
 where documentTypePermission.IsActive &&
       ((userSelectionParam.UserGroupId != null && userGroupId.Id != null)
        || (userSelectionParam.UserId != null && userSelectionParam.UserId == CurrentUserId))
 select documentTypePermission);

to something like this:

var query =
    from documentType in entitySet
    from userGroupId in Repository.ConvertToBigIntTable(userGroupIds, "userGroupId")
        .Where(userGroupId => documentType.Id == userGroupId.Id)
        .DefaultIfEmpty()
    join documentTypePermission in Repository.DocumentTypePermissions
        on documentType.Id equals documentTypePermission.DocumentTypeId
    join userSelectionParam in Repository.UserSelectionParams
        on documentTypePermission.UserSelectionId equals userSelectionParam.Id

    ....

Note:

I have the setup ready for intercepting the expression tree evaluation using QueryTranslationPreprocessor

I need the logic to generate the output of .Call, .SelectMany etc by using the first linq and then translating the same to second linq query shown above

The caveats are that internally the expression engine generates so many Anonymous types that I am unable to write a generic code that would suffice different cases of linq with such groupjoins

Reason to do this:

There are several kinds of GroupJoin issues in EF Core 6 which the community isn’t ready to resolve

I can't make the change to Linq query directly as there are 1000s of them and in several places

Body:
So after evaluating multiple options, the best way to do the above is as below at VisitMethodCall(MethodCallExpression node)

        if (node.Method.DeclaringType == typeof(Queryable) && node.Method.Name == nameof(Queryable.GroupJoin) && node.Arguments.Count == 5)
        {
            var outer = Visit(node.Arguments[0]);
            var inner = Visit(node.Arguments[1]);
            var outerKeySelector = Visit(node.Arguments[2]).UnwrapLambdaFromQuote();
            var innerKeySelector = Visit(node.Arguments[3]).UnwrapLambdaFromQuote();
            var resultSelector = Visit(node.Arguments[4]).UnwrapLambdaFromQuote();

            var outerKey = outerKeySelector.Body.ReplaceParameter(outerKeySelector.Parameters[0], resultSelector.Parameters[0]);
            var innerKey = innerKeySelector.Body;
            var keyMatch = MatchKeys(outerKey, innerKey);

            var innerQuery = Expression.Call(
                typeof(Queryable), nameof(Queryable.Where), new[] { innerKeySelector.Parameters[0].Type },
                inner, Expression.Lambda(keyMatch, innerKeySelector.Parameters));

            var asEnumerableInnerQuery = Expression.Call(
                            typeof(Enumerable),
                            nameof(Enumerable.AsEnumerable),
                            new Type[] { innerKeySelector.Parameters[0].Type }, innerQuery);

            var resultTypes = resultSelector.Parameters.Select(p => p.Type).ToArray();
            var tempProjectionType = typeof(Tuple<,>).MakeGenericType(resultTypes);
            var tempProjection = Expression.New(
                tempProjectionType.GetConstructor(resultTypes),
                new Expression[] { resultSelector.Parameters[0], asEnumerableInnerQuery },
                tempProjectionType.GetProperty("Item1"), tempProjectionType.GetProperty("Item2"));

            var tempQuery = Expression.Call(
                typeof(Queryable), nameof(Queryable.Select), new[] { outerKeySelector.Parameters[0].Type, tempProjectionType },
                outer, Expression.Lambda(tempProjection, resultSelector.Parameters[0]));

            var tempResult = Expression.Parameter(tempProjectionType, "p");
            var projection = resultSelector.Body
                .ReplaceParameter(resultSelector.Parameters[0], Expression.Property(tempResult, "Item1"))
                .ReplaceParameter(resultSelector.Parameters[1], Expression.Property(tempResult, "Item2"));

            var query = Expression.Call(
                typeof(Queryable), nameof(Queryable.Select), new[] { tempProjectionType, projection.Type },
                tempQuery, Expression.Lambda(projection, tempResult));
            return query;
        }
        return base.VisitMethodCall(node);
    }


问:
In Django how to add user to many-to-many filed
I like to add permission to those users who I add to a many-to-many relation.
I have a Projekt model where I like to add multiple users like this:

```<code>class Projekt(models.Model):

def __str__(self):
    return str(self.projekt)

    projekt = models.TextField(max_length=150)
    company_name = models.ForeignKey('Company', on_delete=models.CASCADE, default=1)
    jogosult_01 = models.ManyToManyField(User)
    date = models.DateField(auto_now_add=True, auto_now=False, blank=True)
</code>```

I add the users in the Django Admin page with holding down cmd then save and it shows everything is OK.

If try to get the values like this:

```<code>{% for u in jogosult %}
    {{ u.jogosult_01 }}
{% endfor %}
</code>```

it say auth.user none.

views.py

```<code>@login_required
def projects(request):

    jogosult = Projekt.objects.filter(jogosult_01_id=request.user).order_by('-date')

     context = {
        'jogosult': jogosult,
     }

     return render(request, 'stressz/projects.html', context)
</code>```

答:
User objects have access to their related Projekt objects:

```<code>@login_required
def projects(request):

    jogosult = request.user.projekt_set.all() #<-- HERE!

     context = {
        'jogosult': jogosult,
     }

     return render(request, 'stressz/projects.html', context)
</code>```

Is full documented at Many-to-many relationships

Body:
I like to add permission to those users who I add to a many-to-many relation.
I have a Projekt model where I like to add multiple users like this:

class Projekt(models.Model):

def __str__(self):
    return str(self.projekt)

    projekt = models.TextField(max_length=150)
    company_name = models.ForeignKey('Company', on_delete=models.CASCADE, default=1)
    jogosult_01 = models.ManyToManyField(User)
    date = models.DateField(auto_now_add=True, auto_now=False, blank=True)

I add the users in the Django Admin page with holding down cmd then save and it shows everything is OK.

If try to get the values like this:

{% for u in jogosult %}
    {{ u.jogosult_01 }}
{% endfor %}

it say auth.user none.

views.py

@login_required
def projects(request):

    jogosult = Projekt.objects.filter(jogosult_01_id=request.user).order_by('-date')

     context = {
        'jogosult': jogosult,
     }

     return render(request, 'stressz/projects.html', context)

Body:
User objects have access to their related Projekt objects:

@login_required
def projects(request):

    jogosult = request.user.projekt_set.all() #<-- HERE!

     context = {
        'jogosult': jogosult,
     }

     return render(request, 'stressz/projects.html', context)

Is full documented at Many-to-many relationships


问:
Plug.Conn, all plugs must receive a connection (conn) and return a connection
so I'm trying to update a schema by matching the params["state"] on a callback, In my controller, I'm doing something like this.

```<code>def create(conn, params) do
  viewer = GiftActions.get_gift_user!(params["user_id"])

  case params["state"] do
    "captured" ->
      GiftActions.validate_gift_order(viewer, params)
      Logger.info("Request is validated sending code to #{inspect(viewer.email)}")

      {:ok, id} ->
        put_status(conn, 200)
        |> json(%{data: id})

      _ -> put_status(conn, 404) |> json(%{data: ""})
  end
end
</code>```

My function will handle update if params["state"] is captured, like this

```<code>def validate_gift_order(viewer, attrs) do
 {:ok, gift_order} = __MODULE__.get_gift_by_payment_id(viewer, attrs["id"])

 gift_order
 |> GiftOrders.changeset(%{state: attrs["state"]})
 |> Repo.update()
end
</code>```

Everything work's fine but in the end I'm failing to return Plug.Conn. Error is saying

```<code>[error] #PID<0.5693.0> running VWeb.Endpoint (connection #PID<0.5692.0>, stream id 1) terminated
Server: localhost:4000 (http)
Request: POST /api/v1/gift-callback?user_id=#######
** (exit) an exception was raised:
    ** (RuntimeError) expected action/2 to return a Plug.Conn, all plugs must receive a connection (conn) and return a connection, got: :ok
        (viavolo 0.1.0) lib/v_web/controllers/gif_callback_controller.ex:1: VWeb.GiftCallbackController.phoenix_controller_pipeline/2
        (phoenix 1.5.9) lib/phoenix/router.ex:352: Phoenix.Router.__call__/2
        (viavolo 0.1.0) lib/viavolo_web/endpoint.ex:1: ViavoloWeb.Endpoint.plug_builder_call/2
        (viavolo 0.1.0) lib/viavolo_web/endpoint.ex:1: VWeb.Endpoint."call (overridable 3)"/2
        (viavolo 0.1.0) lib/plug/debugger.ex:136: VWeb.Endpoint."call (overridable 4)"/2
        (viavolo 0.1.0) lib/v_web/endpoint.ex:1: VWeb.Endpoint.call/2
</code>```

and I'm not entirely sure why? What I'm I supposed to return here?

答:
I will answer this question with a quote, you can find the rest here !

The stack trace is telling you that your controller action is not returning a Plug.Conn struct. In Elixir, the result of the very last expression of a function is returned. Look at the last line of your function and ensure it is returning the result of your case expression

Body:
so I'm trying to update a schema by matching the params["state"] on a callback, In my controller, I'm doing something like this.

def create(conn, params) do
  viewer = GiftActions.get_gift_user!(params["user_id"])

  case params["state"] do
    "captured" ->
      GiftActions.validate_gift_order(viewer, params)
      Logger.info("Request is validated sending code to #{inspect(viewer.email)}")

      {:ok, id} ->
        put_status(conn, 200)
        |> json(%{data: id})

      _ -> put_status(conn, 404) |> json(%{data: ""})
  end
end

My function will handle update if params["state"] is captured, like this

def validate_gift_order(viewer, attrs) do
 {:ok, gift_order} = __MODULE__.get_gift_by_payment_id(viewer, attrs["id"])

 gift_order
 |> GiftOrders.changeset(%{state: attrs["state"]})
 |> Repo.update()
end

Everything work's fine but in the end I'm failing to return Plug.Conn. Error is saying

[error] #PID<0.5693.0> running VWeb.Endpoint (connection #PID<0.5692.0>, stream id 1) terminated
Server: localhost:4000 (http)
Request: POST /api/v1/gift-callback?user_id=#######
** (exit) an exception was raised:
    ** (RuntimeError) expected action/2 to return a Plug.Conn, all plugs must receive a connection (conn) and return a connection, got: :ok
        (viavolo 0.1.0) lib/v_web/controllers/gif_callback_controller.ex:1: VWeb.GiftCallbackController.phoenix_controller_pipeline/2
        (phoenix 1.5.9) lib/phoenix/router.ex:352: Phoenix.Router.__call__/2
        (viavolo 0.1.0) lib/viavolo_web/endpoint.ex:1: ViavoloWeb.Endpoint.plug_builder_call/2
        (viavolo 0.1.0) lib/viavolo_web/endpoint.ex:1: VWeb.Endpoint."call (overridable 3)"/2
        (viavolo 0.1.0) lib/plug/debugger.ex:136: VWeb.Endpoint."call (overridable 4)"/2
        (viavolo 0.1.0) lib/v_web/endpoint.ex:1: VWeb.Endpoint.call/2

and I'm not entirely sure why? What I'm I supposed to return here?


问:
Store the the state of the icon and update it only when conditions are satisfied
I am very new to flutter and i have this code:

```<code>[if (led.last.contains('1'))...
   [const Icon(
   Icons.fingerprint,
   color: Colors.blue,
   )]
else if (led.last.contains('2')) ...
   [const Icon(
   Icons.fingerprint,
   color: Colors.grey,
   )]
</code>```

edited: I want to store the the state of the icon and update it only when conditions are satisfied.

Please help me.

答:
You can actually omit the square brackets if there is only 1 Widget.
You can just add the else statement like the else if statement.

```<code>[
    if (led.contains('1'))
      const Icon(
        Icons.fingerprint,
        color: Colors.blue,
      )
    else if (led.contains('2'))
      const Icon(
        Icons.fingerprint,
        color: Colors.grey,
      )
    else
      const Icon(
        Icons.fingerprint,
        color: Colors.blue,
      )
  ]
</code>```

Body:
I am very new to flutter and i have this code:

[if (led.last.contains('1'))...
   [const Icon(
   Icons.fingerprint,
   color: Colors.blue,
   )]
else if (led.last.contains('2')) ...
   [const Icon(
   Icons.fingerprint,
   color: Colors.grey,
   )]

edited: I want to store the the state of the icon and update it only when conditions are satisfied.

Please help me.

Body:
You can actually omit the square brackets if there is only 1 Widget.
You can just add the else statement like the else if statement.

[
    if (led.contains('1'))
      const Icon(
        Icons.fingerprint,
        color: Colors.blue,
      )
    else if (led.contains('2'))
      const Icon(
        Icons.fingerprint,
        color: Colors.grey,
      )
    else
      const Icon(
        Icons.fingerprint,
        color: Colors.blue,
      )
  ]


问:
Manipulating data within a subset is using data outside the subset(??)
I am scratching my head why my code, which clearly defines a subset of data, is using a row outside that subset in doing a calculation. Here is an example. My data is all from the same batch ("batch1"), but I want to calculate NPOC using only the first set of rows before the first "B" it encounters. Then NPOC is calculated by subtracting the "B" row's resultC10 value from that row's resultC10 value. So the F row - B row, then U row - B row. All the data is from the same batch, but because I'm defining a subset, why would it even know about the data in the rest of the batch?

```<code>dat <- data.frame(sample_ind=c("F","X","B","F","X","B"),
                  resultC=c(7.31,3.12,.79,7.38,2.28,.59),
                  batch=c('batch1','batch1','batch1','batch1','batch1','batch1'))
dat$resultC10=dat$resultC*10
dat$NPOC <- NA

start_row = 1

for (i in nrow(dat)) {
  if (dat[i,1]=='B') {
    dat[start_row:i,] <- dat[start_row:i,] %>%
      group_by(batch) %>%
      mutate(NPOC = resultC10-resultC10[sample_ind=='B']) %>%
      ungroup
    start_row = i+1
  }
}
</code>```

Here is the result I'm getting:

```<code>  sample_ind resultC  batch resultC10 NPOC
1          F    7.31 batch1      73.1 65.2  **NPOC OK-using row 3 (73.1-7.9)
2          X    3.12 batch1      31.2 25.3  **NPOC should be 23.3; it's using row 6 (31.2-5.9)
3          B    0.79 batch1       7.9  0.0
4          F    7.38 batch1      73.8 67.9  **OK-using row 6
5          X    2.28 batch1      22.8 14.9  **should be 16.9; it's using row 3
6          B    0.59 batch1       5.9  0.0
</code>```

Any help is greatly appreciated.

答:
You can achieve this without having to use for-loops:</p>
```<code>dat <- data.frame(sample_ind=c("F","X","B","F","X","B"),
                  resultC=c(7.31,3.12,.79,7.38,2.28,.59),
                  batch=c('batch1','batch1','batch1','batch1','batch1','batch1'))
dat$resultC10=dat$resultC*10

dat %>%
  group_by(lag(cumsum(sample_ind == "B"), default = 0)) %>%
  mutate(NPOC = resultC10-last(resultC10)) %>%
  ungroup() %>%
  select(-`lag(cumsum(sample_ind == "B"), default = 0)`)
</code>```

Body:
I am scratching my head why my code, which clearly defines a subset of data, is using a row outside that subset in doing a calculation. Here is an example. My data is all from the same batch ("batch1"), but I want to calculate NPOC using only the first set of rows before the first "B" it encounters. Then NPOC is calculated by subtracting the "B" row's resultC10 value from that row's resultC10 value. So the F row - B row, then U row - B row. All the data is from the same batch, but because I'm defining a subset, why would it even know about the data in the rest of the batch?

dat <- data.frame(sample_ind=c("F","X","B","F","X","B"),
                  resultC=c(7.31,3.12,.79,7.38,2.28,.59),
                  batch=c('batch1','batch1','batch1','batch1','batch1','batch1'))
dat$resultC10=dat$resultC*10
dat$NPOC <- NA

start_row = 1

for (i in nrow(dat)) {
  if (dat[i,1]=='B') {
    dat[start_row:i,] <- dat[start_row:i,] %>%
      group_by(batch) %>%
      mutate(NPOC = resultC10-resultC10[sample_ind=='B']) %>%
      ungroup
    start_row = i+1
  }
}

Here is the result I'm getting:

  sample_ind resultC  batch resultC10 NPOC
1          F    7.31 batch1      73.1 65.2  **NPOC OK-using row 3 (73.1-7.9)
2          X    3.12 batch1      31.2 25.3  **NPOC should be 23.3; it's using row 6 (31.2-5.9)
3          B    0.79 batch1       7.9  0.0
4          F    7.38 batch1      73.8 67.9  **OK-using row 6
5          X    2.28 batch1      22.8 14.9  **should be 16.9; it's using row 3
6          B    0.59 batch1       5.9  0.0

Any help is greatly appreciated.

Body:
You can achieve this without having to use for-loops:

dat <- data.frame(sample_ind=c("F","X","B","F","X","B"),
                  resultC=c(7.31,3.12,.79,7.38,2.28,.59),
                  batch=c('batch1','batch1','batch1','batch1','batch1','batch1'))
dat$resultC10=dat$resultC*10

dat %>%
  group_by(lag(cumsum(sample_ind == "B"), default = 0)) %>%
  mutate(NPOC = resultC10-last(resultC10)) %>%
  ungroup() %>%
  select(-`lag(cumsum(sample_ind == "B"), default = 0)`)


问:
Interact with multiple versions of an external jar file
JavaApplication1 wants to instantiate objects defined in the jar file of (fully trusted) JavaApplication2.  Not normally a problem - add the external JavaApplication2 jar file to the build path of the JavaApplication1 project and then import the appropriate classes. Simples.

But imagine a scenario where JavaApplication1 needs to use multiple different historical versions of JavaApplication2 at the same time. e.g. Instantiate an instance of a JavaApplication2Object from version 1.5 of JavaApplication2.jar, and then, in the same thread, instantiate a separate instance of JavaApplication2Object from version 1.8 of JavaApplication2.jar.

In C#, I would use reflection to load and interact with the correct DLL.  How does one do the same thing in Java in order to deal with the fact that the namespaces and class names are all identical across all versions of JavaApplication2?

答:
To load different versions of the same class, you have to load them using different class loaders, no way around it.

```<code>URL jarV15 = Paths.get("path", "to", "JavaApplication2v15.jar").toUri().toURL();
ClassLoader loaderV15 = new URLClassLoader(new URL[] {url});
Class<?> clazz = loaderV15.loadClass("my.package.JavaApplication2Object");
JavaApplication2Object v15Instance = clazz.getConstructor().newInstance();
</code>```

Then do the exact same for v1.8.

Alternatively, you can use ServiceLoader instead of manual lookup and instantiation of classes:

```<code>ServiceLoader<JavaApplication2Object> serviceLoader = ServiceLoader.load(JavaApplication2Object.class, loaderV15);
</code>```

Of course, both of your jars need to have proper manifest entries for that.

Body:
To load different versions of the same class, you have to load them using different class loaders, no way around it.

URL jarV15 = Paths.get("path", "to", "JavaApplication2v15.jar").toUri().toURL();
ClassLoader loaderV15 = new URLClassLoader(new URL[] {url});
Class<?> clazz = loaderV15.loadClass("my.package.JavaApplication2Object");
JavaApplication2Object v15Instance = clazz.getConstructor().newInstance();

Then do the exact same for v1.8.

Alternatively, you can use ServiceLoader instead of manual lookup and instantiation of classes:

ServiceLoader<JavaApplication2Object> serviceLoader = ServiceLoader.load(JavaApplication2Object.class, loaderV15);

Of course, both of your jars need to have proper manifest entries for that.


问:
Save website theme (eg. dark mode) across pages
I'm currently building a music blog which uses the following JavaScript code to toggle dark mode / light mode buttons:

```<code>function swapStylesheet(sheet) {
    document.getElementById('swap').setAttribute('href', sheet);
}
</code>```

My issue is that the website reverts back to the default CSS sheet whenever the page is refreshed or a new page is visited, instead of remembering the chosen theme. Might I be able to have my website remember the user's last chosen theme via cookies or localstorage or something else?

Please let me know! Thank you so much. =]

答:
Short answer is yes.
You could save it via Cookies or Local Storage, and there's many ways to achieve this, I'll just give you reference for cookies, you could test it on W3School

The question you gave right now is only for between pages, but in cases that you want it to retain based on user accounts, then the answer is you need to centralize the "Theme" data for each account somewhere like Database or Server Cache.

https://www.w3schools.com/js/js_cookies.asp

function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  let expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function checkCookie() {
  let user = getCookie("username");
  if (user != "") {
    alert("Welcome again " + user);
  } else {
    user = prompt("Please enter your name:", "");
    if (user != "" && user != null) {
      setCookie("username", user, 30);
    }
  }
}

checkCookie();```

Body:
I'm currently building a music blog which uses the following JavaScript code to toggle dark mode / light mode buttons:

function swapStylesheet(sheet) {
    document.getElementById('swap').setAttribute('href', sheet);
}

My issue is that the website reverts back to the default CSS sheet whenever the page is refreshed or a new page is visited, instead of remembering the chosen theme. Might I be able to have my website remember the user's last chosen theme via cookies or localstorage or something else?

Please let me know! Thank you so much. =]


问:
I want to fetch the date_part and runid from the path of s3 for snowflake
I have a S3 path "S3:sample/logs/datepart=20220210/runid=2/". It consist of my data files inside this path.I want to create the datepart and runid as a partition using  the external stage of the snowflake. Can you please help me in providing the query for it. How can i fetch the date part and runid.</p>

答:
I understood you load the files and also want to process these two parameters - runid and datepart.

You can include the METADATA$FILENAME in your loading-process with the COPY INTO and then process further with SQL (SUBSTR, LEFT/RIGHT, ...)

https://docs.snowflake.com/en/user-guide/querying-metadata.html


问:
LINQ GroupBy extremely slow
The following code takes 5 minutes to run on 100,000 rows. That seems crazy to me. What am I doing wrong?

```<code>        var query =
            from foo in fooStuff.AsEnumerable()
            group foo by foo.Field<Int64>("FooID") into g
            select new
            {
                    FooID = g.Key,
                    FooTier = g.Min(foo => foo.Field<int>("Tier"))
            };
</code>```

Note: On Mono.

答:
It is not a direct comparision and isn't on Mono, but I have some code which does something similar with a 6MB xml file which I read into a DataSet and it has 30,000 rows and takes 0.5 seconds, so I don't think it is the groupby itself that causes the problem.

To diagnose further, I would suggest

Testing how long it takes to read the information into a list, ie

```<code>var fooList = fooStuff.AsEnumerable().ToList();
</code>```

Testing how long it takes if you change the query to use fooList instead of fooStuff

Testing how long it takes if you remove FooTier = g.Min(foo => foo.Tier) from the select

Separate the .Field<> reflection from the groupby and time each section, ie first read the information from the datatable into a list , eg

```<code>var list2 =
(from foo in fooStuff.AsEnumerable()
select new {
    FooID = foo.Field<Int64>("FooID")
    Tier  = foo.Field<int>("Tier")
}).ToList();
</code>```

Then you can query this list

```<code>var query =
from foo in list2
group foo by foo.FooID into g
select new
{
        FooID = g.Key,
        FooTier = g.Min(foo => foo.Tier)
};
var results = query.ToList();
</code>```

If this query is slow, it would suggest that there is something wrong with mono's implementation of GroupBy. You might be able to verify that by using something like this

```<code>    public static Dictionary<TKey, List<TSrc>> TestGroupBy<TSrc, TKey>
     (this IEnumerable<TSrc> src, Func<TSrc,TKey> groupFunc)
    {
        var dict= new Dictionary<TKey, List<TSrc>>();

        foreach (TSrc s in src)
        {
            TKey key = groupFunc(s);
            List<TSrc> list ;

            if (!dict.TryGetValue(key, out list))
            {
                list = new List<TSrc>();
                dict.Add(key, list);
            }
            list.Add(s);
            }

        return dict;
}
</code>```

And to use it

```<code>  var results = list2.TestGroupBy(r=>r.FooID)
      .Select(r=>  new { FooID = r.Key, FooTier = r.Value.Min(r1=>r1.Tier)} );
</code>```

Note, this is not meant as a replacement for groupby and does not cope with null keys but should be enough to determine if their is a problem with groupby (assuming mono's implementation of Dictionary and List are ok).

Title: LINQ GroupBy extremely slow

Body:
The following code takes 5 minutes to run on 100,000 rows. That seems crazy to me. What am I doing wrong?

        var query =
            from foo in fooStuff.AsEnumerable()
            group foo by foo.Field<Int64>("FooID") into g
            select new
            {
                    FooID = g.Key,
                    FooTier = g.Min(foo => foo.Field<int>("Tier"))
            };

Note: On Mono.

Body:
It is not a direct comparision and isn't on Mono, but I have some code which does something similar with a 6MB xml file which I read into a DataSet and it has 30,000 rows and takes 0.5 seconds, so I don't think it is the groupby itself that causes the problem.

To diagnose further, I would suggest

Testing how long it takes to read the information into a list, ie

var fooList = fooStuff.AsEnumerable().ToList();

Testing how long it takes if you change the query to use fooList instead of fooStuff

Testing how long it takes if you remove FooTier = g.Min(foo => foo.Tier) from the select

Separate the .Field<> reflection from the groupby and time each section, ie first read the information from the datatable into a list , eg

var list2 =
(from foo in fooStuff.AsEnumerable()
select new {
    FooID = foo.Field<Int64>("FooID")
    Tier  = foo.Field<int>("Tier")
}).ToList();

Then you can query this list

var query =
from foo in list2
group foo by foo.FooID into g
select new
{
        FooID = g.Key,
        FooTier = g.Min(foo => foo.Tier)
};
var results = query.ToList();

If this query is slow, it would suggest that there is something wrong with mono's implementation of GroupBy. You might be able to verify that by using something like this

    public static Dictionary<TKey, List<TSrc>> TestGroupBy<TSrc, TKey>
     (this IEnumerable<TSrc> src, Func<TSrc,TKey> groupFunc)
    {
        var dict= new Dictionary<TKey, List<TSrc>>();

        foreach (TSrc s in src)
        {
            TKey key = groupFunc(s);
            List<TSrc> list ;

            if (!dict.TryGetValue(key, out list))
            {
                list = new List<TSrc>();
                dict.Add(key, list);
            }
            list.Add(s);
            }

        return dict;
}

And to use it

  var results = list2.TestGroupBy(r=>r.FooID)
      .Select(r=>  new { FooID = r.Key, FooTier = r.Value.Min(r1=>r1.Tier)} );

Note, this is not meant as a replacement for groupby and does not cope with null keys but should be enough to determine if their is a problem with groupby (assuming mono's implementation of Dictionary and List are ok).


问:
Java Optional with multiple commands and return object
Attempting to execute multiple commands and return an Object (ResponseEntity) using Optional.ifPresentOrElse

More complex does not work:

```<code>return ifPresentOrElse(
           repoService.findById(inId),
           i -> {
               i.setStatus(inStatus);
               repoService.save(i);
               ResponseEntity.ok().body(i);
           },
           () -> {
               LOG.error("Object not available");
               ResponseEntity.notFound().build();
           });
</code>```

Simpler works but doesn't execute all the commands required:

```<code>Optional<I> iOptional = repoService.findById(inId);

return iOptional.map(i -> ResponseEntity.ok().body(i))
                .orElse(ResponseEntity.notFound().build());
</code>```

Is there away to achieve this using Optional functions?

答:
Use Optional.map and Optional.orElseGet, like this:

```<code>var responseEntity = repoService.findById(inId)
  .map(record -> {
    record .setStatus(inStatus);
    repoService.save(record);
    return ResponseEntity.ok().body(record);
  }).orElseGet(() -> {
    LOG.error("Object not available");
    return ResponseEntity.notFound().build();
  });
</code>```

Body:
Attempting to execute multiple commands and return an Object (ResponseEntity) using Optional.ifPresentOrElse

More complex does not work:

return ifPresentOrElse(
           repoService.findById(inId),
           i -> {
               i.setStatus(inStatus);
               repoService.save(i);
               ResponseEntity.ok().body(i);
           },
           () -> {
               LOG.error("Object not available");
               ResponseEntity.notFound().build();
           });

Simpler works but doesn't execute all the commands required:

Optional iOptional = repoService.findById(inId);

return iOptional.map(i -> ResponseEntity.ok().body(i))
                .orElse(ResponseEntity.notFound().build());

Is there away to achieve this using Optional functions?

Body:
Use Optional.map and Optional.orElseGet, like this:

var responseEntity = repoService.findById(inId)
  .map(record -> {
    record .setStatus(inStatus);
    repoService.save(record);
    return ResponseEntity.ok().body(record);
  }).orElseGet(() -> {
    LOG.error("Object not available");
    return ResponseEntity.notFound().build();
  });


问:
Create a SQL query based on SELECT results
Im used to basic SQL statements only so far, but Im full of Ideas how to realise some tasks.

Hopefully someone is more skilled and could help:

I am about to alter columns types in different tables from TEXT/MEMO to VARCHAR(MAX).
There are really a lot of tables needed to be checked and querys to be individually made.
BUT, luckily we have an table, which holds that information and gives an overview in which table there are TEXT/MEMO columns.

The result of such an table (WHERE FIELD_TYPE ='M') looks for e.g. like that:

TAB_DESC
FIELD_NAME
FIELD_TYPE

DADA2
REMARKS
M

DADA3
COMMENT
M

DADA4
REMARK
M

That result means in our system, for e.g. that the Table "TABLE_QQ_DADA2" has a column "REMARKS" which is TEXT/MEMO. Now it needs to be VARCHAR(MAX).

So based on that table I would simply type create manually

```<code>ALTER TABLE TABLE_QQ_DADA2 ALTER COLUMN REMARKS VARCHAR(MAX)

ALTER TABLE TABLE_QQ_DADA3 ALTER COLUMN COMMENT VARCHAR(MAX)

ALTER TABLE TABLE_QQ_DADA4 ALTER COLUMN REMARK VARCHAR(MAX)
</code>```

But I am not satisfied with that and it tingles me to create some kind of loop, which would do that ALTER based on such result.
Some kind of pre-peraded Query, which replaces variables with the results in the columns above. (I hope you get my idea).

I tried to look up some String_Agg functions, but as it seems, sql server 2016 does not support String_Agg yet:/ but i would take that too, in case its easier. Temporarily i could use newer sql-server versions which support String_Agg.

I will be greatful for every idea :)

Thanks

答:
further research led me to an answer in that post:

T-SQL loop over query results

I didnt has the right keywords for proper research before.
Maybe an Admin can comment that?

Body:
Im used to basic SQL statements only so far, but Im full of Ideas how to realise some tasks.

Hopefully someone is more skilled and could help:

I am about to alter columns types in different tables from TEXT/MEMO to VARCHAR(MAX).
There are really a lot of tables needed to be checked and querys to be individually made.
BUT, luckily we have an table, which holds that information and gives an overview in which table there are TEXT/MEMO columns.

The result of such an table (WHERE FIELD_TYPE ='M') looks for e.g. like that:

TAB_DESC
FIELD_NAME
FIELD_TYPE

DADA2
REMARKS
M

DADA3
COMMENT
M

DADA4
REMARK
M

That result means in our system, for e.g. that the Table "TABLE_QQ_DADA2" has a column "REMARKS" which is TEXT/MEMO. Now it needs to be VARCHAR(MAX).

So based on that table I would simply type create manually

ALTER TABLE TABLE_QQ_DADA2 ALTER COLUMN REMARKS VARCHAR(MAX)

ALTER TABLE TABLE_QQ_DADA3 ALTER COLUMN COMMENT VARCHAR(MAX)

ALTER TABLE TABLE_QQ_DADA4 ALTER COLUMN REMARK VARCHAR(MAX)

But I am not satisfied with that and it tingles me to create some kind of loop, which would do that ALTER based on such result.
Some kind of pre-peraded Query, which replaces variables with the results in the columns above. (I hope you get my idea).

I tried to look up some String_Agg functions, but as it seems, sql server 2016 does not support String_Agg yet:/ but i would take that too, in case its easier. Temporarily i could use newer sql-server versions which support String_Agg.

I will be greatful for every idea :)

Thanks


问:
How can i train deeplabv3+ with detectron2 on coco dataset?
I need to train deeplabv3+ with detectron2 on coco instance segmentation dataset. I can train maskrcnn model on coco with detectron, but I could not use deeplab (detectron/projects/deeplab). Is there anyone who trained deeplab using detectron2 before?</p>

答: The DeepLab architecture is for semantic segmentation, not instance segmentation. I don't think it's possible to use any of the DeepLab architectures in detectron on the COCO instance segmentation dataset.</p>


问:
c# splitting and retrieving values from a string
I have a string like this:

```<code>"http://localhost:55164/Images/photos/2/2.jpg"
</code>```

I need to retrieve the filename and the 2 out of the /2/ and put them into their own strings. I've been messing around with StringBuilder and replace and substr to no avail since the filename length is variable.  Anyone have a quick way to do this?

Thanks

答:
I suggest you use the System.Uri class which is tailor-made for this purpose (providing easy access to parts of a URI), e.g.,</p>

```<code>Uri uri = new Uri("http://localhost:55164/Images/photos/2/2.jpg");
string[] segments = uri.Segments;
foreach (string segment in segments)
{
    Console.WriteLine(segment.Trim('/'));
}
</code>```

Body:
I have a string like this:

"http://localhost:55164/Images/photos/2/2.jpg"

I need to retrieve the filename and the 2 out of the /2/ and put them into their own strings. I've been messing around with StringBuilder and replace and substr to no avail since the filename length is variable.  Anyone have a quick way to do this?

Thanks

Body:
I suggest you use the System.Uri class which is tailor-made for this purpose (providing easy access to parts of a URI), e.g.,

Uri uri = new Uri("http://localhost:55164/Images/photos/2/2.jpg");
string[] segments = uri.Segments;
foreach (string segment in segments)
{
    Console.WriteLine(segment.Trim('/'));
}