问:
How can I get MIDL to search additional include directories for qualified paths
Update: Just over six months after opening a support call to Microsoft it has been rejected, they claim it is not a bug (since the documentation doesn't explicitly say that the behaviour seen isn't the correct one). They rejected the DCR saying that since they haven't heard any complaints in the last 10 years this is obviously not a common use case.

This is a call to arms, if you have run into the same issue, please open a support call with Microsoft so they understand that it should be fixed. I know that at least someone has run into the same problem becasue I found this comment in Chrome's source code:

# Building .idl files.

# This is a total mess.  MIDL needs to be run from $OPEN_DIR because it's too

# stupid to apply its include paths to a relative path like "ui/ie/bla.idl"

# (it only looks in the current dir).  So we have to jump through hoops to fix

# up our relative include paths and output files.

Original question:

I have the following file structure:

C:\first\Foo.idl

C:\second\Bar.idl

Where Bar.idl contains the following line:

```<code>import "first/Foo.idl";
</code>```

How can I get midl to compile Bar.idl when compiling from C:\second?

If I imported Foo.idl directly (without specifying first/) then specifying first as an additional include directory would be enough (midl /I c:\first Bar.idl) and it would find Foo.idl

Alternately if I compiled from C:\ (midl second\Bar.idl) that would be OK too.

The problem is that when compiling from within C:\second with the command line midl /I C:\ Bar.idl, I get the following compilation error:

c1 : fatal error C1083: Cannot open source file: 'first\Foo.idl': No such file or directory

It looks like midl is willing to search relative paths only if they are relative to the current directory and not to one of the specified additional include directories and uses the additional include directories only for unqualified file names, this behaviour is specific to the import keyword, when using include the results are as expected.

I would like to be able to add two different additional include directories so that if I have the file on my local machine midl will take that version, otherwise it will take the file from the server (so chdiring to the root folder is not an option).

Is there a way to get around this?

答:
This is a call to arms...

12 years, 6 months later, I'm here with my pitchfork, ready to go.

In the meantime, for an easier fix, you can go to Project Properties -> MIDL -> General -> Additional Include Directories. Setting that to "$(MSBuildProjectDirectory)\YourSubFolder" works just fine.

Body:
Update: Just over six months after opening a support call to Microsoft it has been rejected, they claim it is not a bug (since the documentation doesn't explicitly say that the behaviour seen isn't the correct one). They rejected the DCR saying that since they haven't heard any complaints in the last 10 years this is obviously not a common use case.

This is a call to arms, if you have run into the same issue, please open a support call with Microsoft so they understand that it should be fixed. I know that at least someone has run into the same problem becasue I found this comment in Chrome's source code:

# Building .idl files.

# This is a total mess.  MIDL needs to be run from $OPEN_DIR because it's too

# stupid to apply its include paths to a relative path like "ui/ie/bla.idl"

# (it only looks in the current dir).  So we have to jump through hoops to fix

# up our relative include paths and output files.

Original question:

I have the following file structure:

C:\first\Foo.idl

C:\second\Bar.idl

Where Bar.idl contains the following line:

import "first/Foo.idl";

How can I get midl to compile Bar.idl when compiling from C:\second?

If I imported Foo.idl directly (without specifying first/) then specifying first as an additional include directory would be enough (midl /I c:\first Bar.idl) and it would find Foo.idl

Alternately if I compiled from C:\ (midl second\Bar.idl) that would be OK too.

The problem is that when compiling from within C:\second with the command line midl /I C:\ Bar.idl, I get the following compilation error:

c1 : fatal error C1083: Cannot open source file: 'first\Foo.idl': No such file or directory

It looks like midl is willing to search relative paths only if they are relative to the current directory and not to one of the specified additional include directories and uses the additional include directories only for unqualified file names, this behaviour is specific to the import keyword, when using include the results are as expected.

I would like to be able to add two different additional include directories so that if I have the file on my local machine midl will take that version, otherwise it will take the file from the server (so chdiring to the root folder is not an option).

Is there a way to get around this?


来源: stackexchange

问:
what does $a = new $b() mean in PHP?
Although I get it that

```<code>$a = new b()
</code>```

would be initializing an object for the class b, but what would

```<code>$a = new $b()
</code>```

mean because I came across some code that happens to work otherwise!

答:
This code:

```<code>$b = "Foo";
$a = new $b();
</code>```

is equivalent to the following:

```<code>$a = new Foo();
</code>```

Meaning that you can use syntax like $b() to dynamically refer to a function name or a class name.

ContentLicense: CC BY-SA 3.0

Title: what does $a = new $b() mean in PHP?

Body:
Although I get it that

$a = new b()

would be initializing an object for the class b, but what would

$a = new $b()

mean because I came across some code that happens to work otherwise!

Body:
This code:

$b = "Foo";
$a = new $b();

is equivalent to the following:

$a = new Foo();

Meaning that you can use syntax like $b() to dynamically refer to a function name or a class name.


问:
Count the number of multiple values in a single column in SQL
I have a long list of string values that I would like to count, in one particular column of a table.  I know this works for counting all unique values.

```<code>SELECT
    code_id ,
    COUNT(*) AS num
FROM
    mydb
GROUP BY
    code_id
ORDER BY
    code_id
</code>```

I only have a certain selection of values to count, therefore do now want all.  My list is long, but for example, if I just wanted to count the numbers of strings 'ax1', 'c39', and 'x1a' in my code_id column?  I've seen examples with multiple lines of code, one for each value which will be huge for counting many values.  I'm hoping for something like :

```<code>SELECT
    code_id ,
    COUNT(* = ('ax1, 'c39', 'x1a')) AS num
FROM
    mydb
GROUP BY
    code_id
ORDER BY
    code_id
</code>```

Desired output would be

```<code>code_id    count
ax1         39
c39         42
x1a          0
</code>```

Is there an easy way, rather than a line of code for each value to be counted?

答:
I think this should work.</p>
```<code>SELECT
    code_id ,
    sum(1) AS num
FROM Mydb
WHERE code_id in ('ax1', 'c39', 'x1a')
GROUP BY code_id
ORDER BY code_id
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a long list of string values that I would like to count, in one particular column of a table.  I know this works for counting all unique values.

SELECT
    code_id ,
    COUNT(*) AS num
FROM
    mydb
GROUP BY
    code_id
ORDER BY
    code_id

I only have a certain selection of values to count, therefore do now want all.  My list is long, but for example, if I just wanted to count the numbers of strings 'ax1', 'c39', and 'x1a' in my code_id column?  I've seen examples with multiple lines of code, one for each value which will be huge for counting many values.  I'm hoping for something like :

SELECT
    code_id ,
    COUNT(* = ('ax1, 'c39', 'x1a')) AS num
FROM
    mydb
GROUP BY
    code_id
ORDER BY
    code_id

Desired output would be

code_id    count
ax1         39
c39         42
x1a          0

Is there an easy way, rather than a line of code for each value to be counted?

Body:
I think this should work.

SELECT
    code_id ,
    sum(1) AS num
FROM Mydb
WHERE code_id in ('ax1', 'c39', 'x1a')
GROUP BY code_id
ORDER BY code_id


问:
Run a GitHub Action Last
I have a bunch of GitHub actions for services that each build a container if something changes in their corresponding directories. Then I have a final GitHub actions that sets up a cloud environment with Terraform and uses the containers created by the other actions to deploy the microservices and API for my project.

Currently I'm running that final action manually after all the other actions complete. However, I was wondering if there is any way to automate this. I realize I can chain actions but I'm unsure how to handle this since any number of actions might be running and might finish in any order.

答: In one workflow? You can run all actions in parallel in their own job. Then use needs: for the final job to depend on all the other jobs and deploy the application in that job.

Title: Run a GitHub Action Last


问:
Docker failed to start on Windows 11
I intend to run a Linux-based container on Windows. I installed Docker 4.3.2 and 4.4.4 community editions based on WLS2 to do that. After enabling all prerequisites for windows (WSL2, Hyper-V, Containers) and installing Docker, I tried to launch the docker desktop, at first, the docker icon appears on the taskbar but after a few seconds it disappears without showing any error message.

System specification:

OS: Windows 11 pro version 21H2 Build 22000.376

Docker version: 4.3.2 community edition

WSL: wsl v2

Here is the log for last try:

```<code>[001:21:20:01.354][I] (25d488c5) 2784eefb-BackendAPI S<-C 5cad5efc-GoBackendClient-CSharp GET /settings
[   at Docker.Core.HttpClientExtensions.<GetJsonAsync>d__0`1.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\HttpClientExtensions.cs:line 16
[   at Docker.Core.HttpClientExtensions.GetJsonAsync[T](HttpClient httpClient, String uri, CancellationToken cancellationToken)
[   at Docker.Core.GoBackend.GoBackendClient.GetSettingsAsync() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\GoBackend\GoBackendClient.cs:line 248
[   at Docker.Core.SettingsLoader.<WatchSettingsFile>d__9.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\SettingsLoader.cs:line 71
[   at Docker.Core.SettingsLoader.WatchSettingsFile()
[001:21:20:01.356][I] (25d488c5) 2784eefb-BackendAPI S->C 5cad5efc-GoBackendClient-CSharp GET /settings (542.5µs): {"acceptCanaryUpdates":false,"activeOrganizationName":"","analyticsEnabled":true,"autoDownloadUpdates":false,"autoStart":true,"cpus":2,"credentialHelper":"docker-credential-wincred.exe","customWslDistroDir":"","dataFolder":"C:\\ProgramData\\DockerDesktop\\vm-data","disableHardwareAcceleration":false,"disableTips":false,"disableUpdate":false,"diskSizeMiB":65536,"diskTRIM":true,"displayRestartDialog":true,"displaySwitchVersionPack":true,"displaySwitchWinLinContainers":true,"displayed18362Deprecation":false,"displayedElectronPopup":[],"displayedTutorial":false,"dns":"8.8.8.8","enableIntegrationWithDefaultWslDistro":true,"exposeDockerAPIOnTCP2375":false,"filesharingDirectories":[],"integratedWslDistros":[],"kubernetesEnabled":false,"kubernetesInitialInstallPerformed":false,"lastLoginDate":0,"latestBannerKey":"","licenseTermsVersion":2,"lifecycleTimeoutSeconds":600,"memoryMiB":2048,"openUIOnStartupDisabled":false,"overrideProxyExclude":"","overrideProxyHttp":"","overrideProxyHttps":"","proxyHttpMode":"system","settingsVersion":16,"showKubernetesSystemContainers":false,"skipUpdateToWSLPrompt":true,"skipWSLMountPerfWarning":false,"socksProxyPort":0,"swapMiB":1024,"swarmFederationExplicitlyLoggedOut":false,"synchronizedDirectories":[],"tipLastId":"float64","tipLastViewedTime":0,"updateAvailableTime":0,"updatePopupAppearanceTime":0,"updateSkippedBuild":"","useCredentialHelper":true,"useDnsForwarder":true,"useNightlyBuildUpdates":false,"useVirtualizationFramework":false,"useVpnkit":true,"useWindowsContainers":false,"versionPack":"default","vpnKitMaxPortIdleTime":"float64","vpnKitTransparentProxy":false,"vpnkitCIDR":"1...4","wslEnableGrpcfuse":false,"wslEngineEnabled":true}
[001:21:20:01.357][I] (18c069ce) 2784eefb-BackendAPI S<-C 5cad5efc-GoBackendClient-CSharp GET /ping
[   at Docker.Core.GoBackend.GoBackendClient.WaitForServer(Object state) in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\GoBackend\GoBackendClient.cs:line 88
[001:21:20:01.357][I] (18c069ce) 2784eefb-BackendAPI S->C 5cad5efc-GoBackendClient-CSharp GET /ping (0s): {"serverTime":1641043201357640200}
[001:21:20:01.482][I] (3a878ee0) 2784eefb-BackendAPI S<-C 5cad5efc-GoBackendClient-CSharp GET /settings
[   at Docker.Core.HttpClientExtensions.<GetJsonAsync>d__0`1.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\HttpClientExtensions.cs:line 16
[   at Docker.Core.HttpClientExtensions.GetJsonAsync[T](HttpClient httpClient, String uri, CancellationToken cancellationToken)
[   at Docker.Core.GoBackend.GoBackendClient.GetSettingsAsync() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\GoBackend\GoBackendClient.cs:line 248
[   at Docker.Core.SettingsLoader.<<OnChanged>b__10_0>d.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\SettingsLoader.cs:line 102
[   at Docker.Core.SettingsLoader.<OnChanged>b__10_0()
[001:21:20:01.483][I] (3a878ee0) 2784eefb-BackendAPI S->C 5cad5efc-GoBackendClient-CSharp GET /settings (1.1523ms): {"acceptCanaryUpdates":false,"activeOrganizationName":"","analyticsEnabled":true,"autoDownloadUpdates":false,"autoStart":true,"cpus":2,"credentialHelper":"docker-credential-wincred.exe","customWslDistroDir":"","dataFolder":"C:\\ProgramData\\DockerDesktop\\vm-data","disableHardwareAcceleration":false,"disableTips":false,"disableUpdate":false,"diskSizeMiB":65536,"diskTRIM":true,"displayRestartDialog":true,"displaySwitchVersionPack":true,"displaySwitchWinLinContainers":true,"displayed18362Deprecation":false,"displayedElectronPopup":[],"displayedTutorial":false,"dns":"8.8.8.8","enableIntegrationWithDefaultWslDistro":true,"exposeDockerAPIOnTCP2375":false,"filesharingDirectories":[],"integratedWslDistros":[],"kubernetesEnabled":false,"kubernetesInitialInstallPerformed":false,"lastLoginDate":0,"latestBannerKey":"","licenseTermsVersion":2,"lifecycleTimeoutSeconds":600,"memoryMiB":2048,"openUIOnStartupDisabled":false,"overrideProxyExclude":"","overrideProxyHttp":"","overrideProxyHttps":"","proxyHttpMode":"system","settingsVersion":16,"showKubernetesSystemContainers":false,"skipUpdateToWSLPrompt":true,"skipWSLMountPerfWarning":false,"socksProxyPort":0,"swapMiB":1024,"swarmFederationExplicitlyLoggedOut":false,"synchronizedDirectories":[],"tipLastId":"float64","tipLastViewedTime":0,"updateAvailableTime":0,"updatePopupAppearanceTime":0,"updateSkippedBuild":"","useCredentialHelper":true,"useDnsForwarder":true,"useNightlyBuildUpdates":false,"useVirtualizationFramework":false,"useVpnkit":true,"useWindowsContainers":false,"versionPack":"default","vpnKitMaxPortIdleTime":"float64","vpnKitTransparentProxy":false,"vpnkitCIDR":"1...4","wslEnableGrpcfuse":false,"wslEngineEnabled":true}
[001:21:20:01.506][I] (b724d811) 2784eefb-BackendAPI S<-C 5cad5efc-GoBackendClient-CSharp GET /settings
[   at Docker.Core.HttpClientExtensions.<GetJsonAsync>d__0`1.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\HttpClientExtensions.cs:line 16
[   at Docker.Core.HttpClientExtensions.GetJsonAsync[T](HttpClient httpClient, String uri, CancellationToken cancellationToken)
[   at Docker.Core.GoBackend.GoBackendClient.GetSettingsAsync() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\GoBackend\GoBackendClient.cs:line 248
[   at Docker.Core.SettingsLoader.<<OnChanged>b__10_0>d.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\SettingsLoader.cs:line 102
[   at Docker.Core.SettingsLoader.<OnChanged>b__10_0()
[001:21:20:01.506][I] (b724d811) 2784eefb-BackendAPI S->C 5cad5efc-GoBackendClient-CSharp GET /settings (557.5µs): {"acceptCanaryUpdates":false,"activeOrganizationName":"","analyticsEnabled":true,"autoDownloadUpdates":false,"autoStart":true,"cpus":2,"credentialHelper":"docker-credential-wincred.exe","customWslDistroDir":"","dataFolder":"C:\\ProgramData\\DockerDesktop\\vm-data","disableHardwareAcceleration":false,"disableTips":false,"disableUpdate":false,"diskSizeMiB":65536,"diskTRIM":true,"displayRestartDialog":true,"displaySwitchVersionPack":true,"displaySwitchWinLinContainers":true,"displayed18362Deprecation":false,"displayedElectronPopup":[],"displayedTutorial":false,"dns":"8.8.8.8","enableIntegrationWithDefaultWslDistro":true,"exposeDockerAPIOnTCP2375":false,"filesharingDirectories":[],"integratedWslDistros":[],"kubernetesEnabled":false,"kubernetesInitialInstallPerformed":false,"lastLoginDate":0,"latestBannerKey":"","licenseTermsVersion":2,"lifecycleTimeoutSeconds":600,"memoryMiB":2048,"openUIOnStartupDisabled":false,"overrideProxyExclude":"","overrideProxyHttp":"","overrideProxyHttps":"","proxyHttpMode":"system","settingsVersion":16,"showKubernetesSystemContainers":false,"skipUpdateToWSLPrompt":true,"skipWSLMountPerfWarning":false,"socksProxyPort":0,"swapMiB":1024,"swarmFederationExplicitlyLoggedOut":false,"synchronizedDirectories":[],"tipLastId":"float64","tipLastViewedTime":0,"updateAvailableTime":0,"updatePopupAppearanceTime":0,"updateSkippedBuild":"","useCredentialHelper":true,"useDnsForwarder":true,"useNightlyBuildUpdates":false,"useVirtualizationFramework":false,"useVpnkit":true,"useWindowsContainers":false,"versionPack":"default","vpnKitMaxPortIdleTime":"float64","vpnKitTransparentProxy":false,"vpnkitCIDR":"1...4","wslEnableGrpcfuse":false,"wslEngineEnabled":true}
[001:21:20:01.544][I] (dafb5e19) 2784eefb-BackendAPI S<-C 5cad5efc-GoBackendClient-CSharp GET /features
[   at Docker.Core.GoBackend.GoBackendClient.<GetFeaturesAsync>d__15.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\GoBackend\GoBackendClient.cs:line 196
[   at Docker.Core.GoBackend.GoBackendClient.GetFeaturesAsync()
[   at Docker.Core.Features.Features.get_FeatureList() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\Features\Features.cs:line 21
[   at Docker.Core.Features.Features.GetEnabled() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\Features\Features.cs:line 74
[   at Docker.ApiServices.Analytics.SegmentApi.<Track>d__21.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.ApiServices\Analytics\Analytics.cs:line 115
[   at Docker.ApiServices.Analytics.SegmentApi.Track(String eventType, IDictionary`2 additionalProperties, Settings settings)
[   at Docker.ApiServices.Analytics.SegmentApi.<TrackAsync>d__19.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.ApiServices\Analytics\Analytics.cs:line 70
[   at Docker.ApiServices.Analytics.SegmentApi.TrackAsync(AnalyticEvents analyticEvent, IDictionary`2 additionalProperties)
[   at Docker.Program.Run(IReadOnlyCollection`1 args) in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Desktop\Program.cs:line 235
[   at Docker.Program.Main(String[] args) in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Desktop\Program.cs:line 131
[001:21:20:01.550][I] (dafb5e19) 2784eefb-BackendAPI S->C 5cad5efc-GoBackendClient-CSharp GET /features (1.1525ms): {"Auth0":{"description":"Login and authentication is handled by auth0","enabled":false,"label":"Perform login via auth0","name":"Login via auth0","type":1},"NightlyBuilds":{"description":"Switch the application update to the night builds","enabled":false,"label":"Enable nightly builds","name":"Nightly builds","type":1},"ProUser":{"description":"You can upgrade your current tier [here](URL)","enabled":false,"label":"personal","name":"ProUser","type":3},"Procd":{"description":"Enable advanced process management functionality like suspend and resume of containers and the VM","enabled":true,"label":"Enable process management daemon","name":"Process management daemon","type":1},"SignInBanner":{"description":"Show persistent non-dismissible banner to encourage sign in","enabled":false,"label":"Display sign in banner if not logged in","name":"Sign in banner","type":1},"SimultaneousLinuxAndWindowsContainers":{"description":"Allow both Linux and Windows containers simultaneously using docker cli contexts","enabled":false,"label":"Simultaneous Linux and Windows containers","name":"Simultaneous Linux and Windows containers","type":3},"WhaleMenuRedesign":{"description":"Display Whale menu done with Electron","enabled":false,"label":"Enable Whale Menu Redesign","name":"Whale Menu Redesign","type":1},"grpcfuseV2":{"description":"Switch off to use the legacy osxfs file sharing instead.","enabled":true,"label":"Use grpcfuse for filesharing by default","name":"Grpcfuse","type":1},"mutagenV0":{"description":"Use Mutagen to synchronize files in a container with your local disk.","enabled":false,"label":"Two-way file synchronisation","name":"Mutagen","type":1}}
</code>```

Failed tries:

```<code>1- check with different version of Docker desktop 2,3,4.3.2,4.4.4
2- Reconfig the JSON file
3- disable and enabling Docker related services on windows (Hyper-v, Containers, WSL2)
4- updating WSL2
5- installing different Linux distributions on WSL2
6- running the Docker services manually
7- running DockerCli on privileged permission using PowerShell
8- running Docker debugger tools to identify the problem
9- search on Docker repository for a similar issue
</code>```

答:
After too many searches and tries, finally I resolved it by fresh installations of Windows 11.
There is a problem with the upgraded windows version especially if you already installed and config WSL2 or other Docker dependencies on the previous version.</p>

Title: Docker failed to start on Windows 11

Body:
I intend to run a Linux-based container on Windows. I installed Docker 4.3.2 and 4.4.4 community editions based on WLS2 to do that. After enabling all prerequisites for windows (WSL2, Hyper-V, Containers) and installing Docker, I tried to launch the docker desktop, at first, the docker icon appears on the taskbar but after a few seconds it disappears without showing any error message.

System specification:

OS: Windows 11 pro version 21H2 Build 22000.376

Docker version: 4.3.2 community edition

WSL: wsl v2

Here is the log for last try:

[001:21:20:01.354][I] (25d488c5) 2784eefb-BackendAPI S<-C 5cad5efc-GoBackendClient-CSharp GET /settings
[   at Docker.Core.HttpClientExtensions.<GetJsonAsync>d__0`1.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\HttpClientExtensions.cs:line 16
[   at Docker.Core.HttpClientExtensions.GetJsonAsync[T](HttpClient httpClient, String uri, CancellationToken cancellationToken)
[   at Docker.Core.GoBackend.GoBackendClient.GetSettingsAsync() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\GoBackend\GoBackendClient.cs:line 248
[   at Docker.Core.SettingsLoader.<WatchSettingsFile>d__9.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\SettingsLoader.cs:line 71
[   at Docker.Core.SettingsLoader.WatchSettingsFile()
[001:21:20:01.356][I] (25d488c5) 2784eefb-BackendAPI S->C 5cad5efc-GoBackendClient-CSharp GET /settings (542.5µs): {"acceptCanaryUpdates":false,"activeOrganizationName":"","analyticsEnabled":true,"autoDownloadUpdates":false,"autoStart":true,"cpus":2,"credentialHelper":"docker-credential-wincred.exe","customWslDistroDir":"","dataFolder":"C:\\ProgramData\\DockerDesktop\\vm-data","disableHardwareAcceleration":false,"disableTips":false,"disableUpdate":false,"diskSizeMiB":65536,"diskTRIM":true,"displayRestartDialog":true,"displaySwitchVersionPack":true,"displaySwitchWinLinContainers":true,"displayed18362Deprecation":false,"displayedElectronPopup":[],"displayedTutorial":false,"dns":"8.8.8.8","enableIntegrationWithDefaultWslDistro":true,"exposeDockerAPIOnTCP2375":false,"filesharingDirectories":[],"integratedWslDistros":[],"kubernetesEnabled":false,"kubernetesInitialInstallPerformed":false,"lastLoginDate":0,"latestBannerKey":"","licenseTermsVersion":2,"lifecycleTimeoutSeconds":600,"memoryMiB":2048,"openUIOnStartupDisabled":false,"overrideProxyExclude":"","overrideProxyHttp":"","overrideProxyHttps":"","proxyHttpMode":"system","settingsVersion":16,"showKubernetesSystemContainers":false,"skipUpdateToWSLPrompt":true,"skipWSLMountPerfWarning":false,"socksProxyPort":0,"swapMiB":1024,"swarmFederationExplicitlyLoggedOut":false,"synchronizedDirectories":[],"tipLastId":"float64","tipLastViewedTime":0,"updateAvailableTime":0,"updatePopupAppearanceTime":0,"updateSkippedBuild":"","useCredentialHelper":true,"useDnsForwarder":true,"useNightlyBuildUpdates":false,"useVirtualizationFramework":false,"useVpnkit":true,"useWindowsContainers":false,"versionPack":"default","vpnKitMaxPortIdleTime":"float64","vpnKitTransparentProxy":false,"vpnkitCIDR":"1...4","wslEnableGrpcfuse":false,"wslEngineEnabled":true}
[001:21:20:01.357][I] (18c069ce) 2784eefb-BackendAPI S<-C 5cad5efc-GoBackendClient-CSharp GET /ping
[   at Docker.Core.GoBackend.GoBackendClient.WaitForServer(Object state) in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\GoBackend\GoBackendClient.cs:line 88
[001:21:20:01.357][I] (18c069ce) 2784eefb-BackendAPI S->C 5cad5efc-GoBackendClient-CSharp GET /ping (0s): {"serverTime":1641043201357640200}
[001:21:20:01.482][I] (3a878ee0) 2784eefb-BackendAPI S<-C 5cad5efc-GoBackendClient-CSharp GET /settings
[   at Docker.Core.HttpClientExtensions.<GetJsonAsync>d__0`1.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\HttpClientExtensions.cs:line 16
[   at Docker.Core.HttpClientExtensions.GetJsonAsync[T](HttpClient httpClient, String uri, CancellationToken cancellationToken)
[   at Docker.Core.GoBackend.GoBackendClient.GetSettingsAsync() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\GoBackend\GoBackendClient.cs:line 248
[   at Docker.Core.SettingsLoader.<<OnChanged>b__10_0>d.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\SettingsLoader.cs:line 102
[   at Docker.Core.SettingsLoader.<OnChanged>b__10_0()
[001:21:20:01.483][I] (3a878ee0) 2784eefb-BackendAPI S->C 5cad5efc-GoBackendClient-CSharp GET /settings (1.1523ms): {"acceptCanaryUpdates":false,"activeOrganizationName":"","analyticsEnabled":true,"autoDownloadUpdates":false,"autoStart":true,"cpus":2,"credentialHelper":"docker-credential-wincred.exe","customWslDistroDir":"","dataFolder":"C:\\ProgramData\\DockerDesktop\\vm-data","disableHardwareAcceleration":false,"disableTips":false,"disableUpdate":false,"diskSizeMiB":65536,"diskTRIM":true,"displayRestartDialog":true,"displaySwitchVersionPack":true,"displaySwitchWinLinContainers":true,"displayed18362Deprecation":false,"displayedElectronPopup":[],"displayedTutorial":false,"dns":"8.8.8.8","enableIntegrationWithDefaultWslDistro":true,"exposeDockerAPIOnTCP2375":false,"filesharingDirectories":[],"integratedWslDistros":[],"kubernetesEnabled":false,"kubernetesInitialInstallPerformed":false,"lastLoginDate":0,"latestBannerKey":"","licenseTermsVersion":2,"lifecycleTimeoutSeconds":600,"memoryMiB":2048,"openUIOnStartupDisabled":false,"overrideProxyExclude":"","overrideProxyHttp":"","overrideProxyHttps":"","proxyHttpMode":"system","settingsVersion":16,"showKubernetesSystemContainers":false,"skipUpdateToWSLPrompt":true,"skipWSLMountPerfWarning":false,"socksProxyPort":0,"swapMiB":1024,"swarmFederationExplicitlyLoggedOut":false,"synchronizedDirectories":[],"tipLastId":"float64","tipLastViewedTime":0,"updateAvailableTime":0,"updatePopupAppearanceTime":0,"updateSkippedBuild":"","useCredentialHelper":true,"useDnsForwarder":true,"useNightlyBuildUpdates":false,"useVirtualizationFramework":false,"useVpnkit":true,"useWindowsContainers":false,"versionPack":"default","vpnKitMaxPortIdleTime":"float64","vpnKitTransparentProxy":false,"vpnkitCIDR":"1...4","wslEnableGrpcfuse":false,"wslEngineEnabled":true}
[001:21:20:01.506][I] (b724d811) 2784eefb-BackendAPI S<-C 5cad5efc-GoBackendClient-CSharp GET /settings
[   at Docker.Core.HttpClientExtensions.<GetJsonAsync>d__0`1.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\HttpClientExtensions.cs:line 16
[   at Docker.Core.HttpClientExtensions.GetJsonAsync[T](HttpClient httpClient, String uri, CancellationToken cancellationToken)
[   at Docker.Core.GoBackend.GoBackendClient.GetSettingsAsync() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\GoBackend\GoBackendClient.cs:line 248
[   at Docker.Core.SettingsLoader.<<OnChanged>b__10_0>d.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\SettingsLoader.cs:line 102
[   at Docker.Core.SettingsLoader.<OnChanged>b__10_0()
[001:21:20:01.506][I] (b724d811) 2784eefb-BackendAPI S->C 5cad5efc-GoBackendClient-CSharp GET /settings (557.5µs): {"acceptCanaryUpdates":false,"activeOrganizationName":"","analyticsEnabled":true,"autoDownloadUpdates":false,"autoStart":true,"cpus":2,"credentialHelper":"docker-credential-wincred.exe","customWslDistroDir":"","dataFolder":"C:\\ProgramData\\DockerDesktop\\vm-data","disableHardwareAcceleration":false,"disableTips":false,"disableUpdate":false,"diskSizeMiB":65536,"diskTRIM":true,"displayRestartDialog":true,"displaySwitchVersionPack":true,"displaySwitchWinLinContainers":true,"displayed18362Deprecation":false,"displayedElectronPopup":[],"displayedTutorial":false,"dns":"8.8.8.8","enableIntegrationWithDefaultWslDistro":true,"exposeDockerAPIOnTCP2375":false,"filesharingDirectories":[],"integratedWslDistros":[],"kubernetesEnabled":false,"kubernetesInitialInstallPerformed":false,"lastLoginDate":0,"latestBannerKey":"","licenseTermsVersion":2,"lifecycleTimeoutSeconds":600,"memoryMiB":2048,"openUIOnStartupDisabled":false,"overrideProxyExclude":"","overrideProxyHttp":"","overrideProxyHttps":"","proxyHttpMode":"system","settingsVersion":16,"showKubernetesSystemContainers":false,"skipUpdateToWSLPrompt":true,"skipWSLMountPerfWarning":false,"socksProxyPort":0,"swapMiB":1024,"swarmFederationExplicitlyLoggedOut":false,"synchronizedDirectories":[],"tipLastId":"float64","tipLastViewedTime":0,"updateAvailableTime":0,"updatePopupAppearanceTime":0,"updateSkippedBuild":"","useCredentialHelper":true,"useDnsForwarder":true,"useNightlyBuildUpdates":false,"useVirtualizationFramework":false,"useVpnkit":true,"useWindowsContainers":false,"versionPack":"default","vpnKitMaxPortIdleTime":"float64","vpnKitTransparentProxy":false,"vpnkitCIDR":"1...4","wslEnableGrpcfuse":false,"wslEngineEnabled":true}
[001:21:20:01.544][I] (dafb5e19) 2784eefb-BackendAPI S<-C 5cad5efc-GoBackendClient-CSharp GET /features
[   at Docker.Core.GoBackend.GoBackendClient.<GetFeaturesAsync>d__15.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\GoBackend\GoBackendClient.cs:line 196
[   at Docker.Core.GoBackend.GoBackendClient.GetFeaturesAsync()
[   at Docker.Core.Features.Features.get_FeatureList() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\Features\Features.cs:line 21
[   at Docker.Core.Features.Features.GetEnabled() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Core\Features\Features.cs:line 74
[   at Docker.ApiServices.Analytics.SegmentApi.<Track>d__21.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.ApiServices\Analytics\Analytics.cs:line 115
[   at Docker.ApiServices.Analytics.SegmentApi.Track(String eventType, IDictionary`2 additionalProperties, Settings settings)
[   at Docker.ApiServices.Analytics.SegmentApi.<TrackAsync>d__19.MoveNext() in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.ApiServices\Analytics\Analytics.cs:line 70
[   at Docker.ApiServices.Analytics.SegmentApi.TrackAsync(AnalyticEvents analyticEvent, IDictionary`2 additionalProperties)
[   at Docker.Program.Run(IReadOnlyCollection`1 args) in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Desktop\Program.cs:line 235
[   at Docker.Program.Main(String[] args) in C:\workspaces\4.3.x\src\github.com\docker\pinata\win\src\Docker.Desktop\Program.cs:line 131
[001:21:20:01.550][I] (dafb5e19) 2784eefb-BackendAPI S->C 5cad5efc-GoBackendClient-CSharp GET /features (1.1525ms): {"Auth0":{"description":"Login and authentication is handled by auth0","enabled":false,"label":"Perform login via auth0","name":"Login via auth0","type":1},"NightlyBuilds":{"description":"Switch the application update to the night builds","enabled":false,"label":"Enable nightly builds","name":"Nightly builds","type":1},"ProUser":{"description":"You can upgrade your current tier [here](URL)","enabled":false,"label":"personal","name":"ProUser","type":3},"Procd":{"description":"Enable advanced process management functionality like suspend and resume of containers and the VM","enabled":true,"label":"Enable process management daemon","name":"Process management daemon","type":1},"SignInBanner":{"description":"Show persistent non-dismissible banner to encourage sign in","enabled":false,"label":"Display sign in banner if not logged in","name":"Sign in banner","type":1},"SimultaneousLinuxAndWindowsContainers":{"description":"Allow both Linux and Windows containers simultaneously using docker cli contexts","enabled":false,"label":"Simultaneous Linux and Windows containers","name":"Simultaneous Linux and Windows containers","type":3},"WhaleMenuRedesign":{"description":"Display Whale menu done with Electron","enabled":false,"label":"Enable Whale Menu Redesign","name":"Whale Menu Redesign","type":1},"grpcfuseV2":{"description":"Switch off to use the legacy osxfs file sharing instead.","enabled":true,"label":"Use grpcfuse for filesharing by default","name":"Grpcfuse","type":1},"mutagenV0":{"description":"Use Mutagen to synchronize files in a container with your local disk.","enabled":false,"label":"Two-way file synchronisation","name":"Mutagen","type":1}}

Failed tries:

1- check with different version of Docker desktop 2,3,4.3.2,4.4.4
2- Reconfig the JSON file
3- disable and enabling Docker related services on windows (Hyper-v, Containers, WSL2)
4- updating WSL2
5- installing different Linux distributions on WSL2
6- running the Docker services manually
7- running DockerCli on privileged permission using PowerShell
8- running Docker debugger tools to identify the problem
9- search on Docker repository for a similar issue


问:
How to import a Javascript file that is ESM from a CommonJS module? Gulp. Error: [ERR_REQUIRE_ESM]
My project is entirely written as CommonJS module and I don't plan to change it. The problem is that I have to use a library that is ESM when using gulp.

The file where this situation appears:

const { dest, src } = require('gulp')
const imagemin = require('gulp-imagemin') // This is a ESM. Compiler gives error [ERR_REQUIRE_ESM]

const images = () => {
    // We have specific configs for jpeg and png files to try
    // to really pull down asset sizes
    return src('./src/images/**/*')
        .pipe(
            imagemin(
                [
                    imagemin.mozjpeg({ quality: 60, progressive: true }),
                    imagemin.optipng({ optimizationLevel: 5, interlaced: null })
                ],
                {
                    silent: true
                }
            )
        )
        .pipe(dest('./dist/images'))
}

module.exports = images
```
<p>This is the error that node gives</p>
```Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\Lucas\Documents\repos\nexus-materiales\node_modules\gulp-imagemin\index.js from C:\Users\Lucas\Documents\repos\nexus-materiales\gulp-tasks\images.js not supported.
Instead change the require of index.js in C:\Users\Lucas\Documents\repos\nexus-materiales\gulp-tasks\images.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (C:\Users\Lucas\Documents\repos\nexus-materiales\gulp-tasks\images.js:2:18)
    at Object.<anonymous> (C:\Users\Lucas\Documents\repos\nexus-materiales\gulpfile.js:4:16)
    at async Promise.all (index 0) {
  code: 'ERR_REQUIRE_ESM'
}
```

So, How could I include this file using commonJS if it's an ESM? Is this possible?

答:
To import an ES module from CommonJS code, use a dynamic import.

ES module imports are asynchronous: you'll have to make sure that the gulp-imagemin import has completed before creating the gulp stream. This can be achieved with gulp.series.

const { dest, series, src } = require('gulp');
let imagemin;

const images = series(
    async () => {
        imagemin = await import('gulp-imagemin');
    },
    () => src('./src/images/**/*')
        .pipe(
            imagemin.default(
                [
                    imagemin.mozjpeg({ quality: 60, progressive: true }),
                    imagemin.optipng({ optimizationLevel: 5, interlaced: null })
                ],
                {
                    silent: true
                }
            )
        )
        .pipe(dest('./dist/images'))
);
```

Note that I used imagemin.default to access the default export of gulp-imagemin, since it's being imported dynamically.

Body:
My project is entirely written as CommonJS module and I don't plan to change it. The problem is that I have to use a library that is ESM when using gulp.

The file where this situation appears:

const { dest, src } = require('gulp')
const imagemin = require('gulp-imagemin') // This is a ESM. Compiler gives error [ERR_REQUIRE_ESM]

const images = () => {
    // We have specific configs for jpeg and png files to try
    // to really pull down asset sizes
    return src('./src/images/**/*')
        .pipe(
            imagemin(
                [
                    imagemin.mozjpeg({ quality: 60, progressive: true }),
                    imagemin.optipng({ optimizationLevel: 5, interlaced: null })
                ],
                {
                    silent: true
                }
            )
        )
        .pipe(dest('./dist/images'))
}

module.exports = images

This is the error that node gives

Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\Lucas\Documents\repos\nexus-materiales\node_modules\gulp-imagemin\index.js from C:\Users\Lucas\Documents\repos\nexus-materiales\gulp-tasks\images.js not supported.
Instead change the require of index.js in C:\Users\Lucas\Documents\repos\nexus-materiales\gulp-tasks\images.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (C:\Users\Lucas\Documents\repos\nexus-materiales\gulp-tasks\images.js:2:18)
    at Object.<anonymous> (C:\Users\Lucas\Documents\repos\nexus-materiales\gulpfile.js:4:16)
    at async Promise.all (index 0) {
  code: 'ERR_REQUIRE_ESM'
}

So, How could I include this file using commonJS if it's an ESM? Is this possible?

Body:
To import an ES module from CommonJS code, use a dynamic import.

ES module imports are asynchronous: you'll have to make sure that the gulp-imagemin import has completed before creating the gulp stream. This can be achieved with gulp.series.

const { dest, series, src } = require('gulp');
let imagemin;

const images = series(
    async () => {
        imagemin = await import('gulp-imagemin');
    },
    () => src('./src/images/**/*')
        .pipe(
            imagemin.default(
                [
                    imagemin.mozjpeg({ quality: 60, progressive: true }),
                    imagemin.optipng({ optimizationLevel: 5, interlaced: null })
                ],
                {
                    silent: true
                }
            )
        )
        .pipe(dest('./dist/images'))
);

Note that I used imagemin.default to access the default export of gulp-imagemin, since it's being imported dynamically.


问:
How do I replace the key in a JSON file?
Could you please tell me how can I replace the key in a JSON file?

JSON file structure:

```<code>[
   {
      "id" : "365",
      "credits" : [ {
        "login" : "user1",
        "password" : "pa$$w0rd"
      } ]
    }, {
      "id" : "366",
      "credits" : [ {
        "Login" : "user2",
        "password" : "pa$$w0rd"
      } ]
    }
]
</code>```

it is necessary that the login key be of the same type, i.e. with one register throughout the document, all Login keys become login.

This is necessary for further analysis and downloading of information from the JSON file.

```<code>with open ("test.json", "r") as read_file_json:
    data_json = json.load(read_file_json)
    for n in range(len(data_json)):
        id = (data_json[n]['id'])
        id = str(id)
        for credits in data_json[n]["credits"]:
            login = credits["login"]
</code>```

Thank you very much!

答:
There's no need to work with the id key. It serves no purpose. All you need is:

```<code>import json

with open ('test.json', encoding='utf-8') as read_file_json:
    js = json.load(read_file_json)
    for d in js:
        for c in d['credits']:
            if (v := c.get('Login', None)) is not None:
                c['login'] = v
                del c['Login']
    print(json.dumps(js, indent=2))
</code>```

Body:
Could you please tell me how can I replace the key in a JSON file?

JSON file structure:

[
   {
      "id" : "365",
      "credits" : [ {
        "login" : "user1",
        "password" : "pa$$w0rd"
      } ]
    }, {
      "id" : "366",
      "credits" : [ {
        "Login" : "user2",
        "password" : "pa$$w0rd"
      } ]
    }
]

it is necessary that the login key be of the same type, i.e. with one register throughout the document, all Login keys become login.

This is necessary for further analysis and downloading of information from the JSON file.

with open ("test.json", "r") as read_file_json:
    data_json = json.load(read_file_json)
    for n in range(len(data_json)):
        id = (data_json[n]['id'])
        id = str(id)
        for credits in data_json[n]["credits"]:
            login = credits["login"]

Thank you very much!

Body:
There's no need to work with the id key. It serves no purpose. All you need is:

import json

with open ('test.json', encoding='utf-8') as read_file_json:
    js = json.load(read_file_json)
    for d in js:
        for c in d['credits']:
            if (v := c.get('Login', None)) is not None:
                c['login'] = v
                del c['Login']
    print(json.dumps(js, indent=2))


问:
Doing multiple sorts across more than one line of code?
I have an array that stores the order that I want to sort a list by.

```<code>SortOrderArray: "Color", "Volume", "Weight"
</code>```

So I want to order my list by Color, Volume, then Weight

```<code>MyList.OrderBy(a=>a.Color).ThenBy(a=>a.Volume).ThenBy(a=>a.Weight).ToList();
</code>```

So that's pretty good.  Now, I want to be able to write a function that does this sorting based on the sortOrder array I send in:

```<code>public List<row> GetSortedList(List<row> list, string[] sortOrder){
    ???
}
</code>```

I can't figure out how to do this without writing a linq query for every combination of sortOrders (27 different queries just seems like the worst way to accomplish this, and has a fairly high possibility of me making a tiny mistake).  I would like to be able to just write 3 linq queries that reorders the list according to each of the 3 sorting methods, something like this:

```<code>switch(sortOrder[0]){
    Sort by the first sort method
}
switch(sortOrder[1]){
    Sort by the second sort method
}
switch(sortOrder[2]){
    Sort by the third sort method
}
</code>```

But if I try doing the above code, it just resorts it each time, instead of doing sub-sorts after the one above it.  Hope that is clear, any help would be appreciated.

答: Two things.   You need a sort method that performs a "stable sort" - it keeps the existing order of items with identical keys.    And then you need to call it in reverse order of your sort criteria , so that the primary sort is the last one you do.   </p>

Body:
I have an array that stores the order that I want to sort a list by.

SortOrderArray: "Color", "Volume", "Weight"

So I want to order my list by Color, Volume, then Weight

MyList.OrderBy(a=>a.Color).ThenBy(a=>a.Volume).ThenBy(a=>a.Weight).ToList();

So that's pretty good.  Now, I want to be able to write a function that does this sorting based on the sortOrder array I send in:

public List<row> GetSortedList(List<row> list, string[] sortOrder){
    ???
}

I can't figure out how to do this without writing a linq query for every combination of sortOrders (27 different queries just seems like the worst way to accomplish this, and has a fairly high possibility of me making a tiny mistake).  I would like to be able to just write 3 linq queries that reorders the list according to each of the 3 sorting methods, something like this:

switch(sortOrder[0]){
    Sort by the first sort method
}
switch(sortOrder[1]){
    Sort by the second sort method
}
switch(sortOrder[2]){
    Sort by the third sort method
}

But if I try doing the above code, it just resorts it each time, instead of doing sub-sorts after the one above it.  Hope that is clear, any help would be appreciated.


问:
CSS offset-path move along arc without rotating
I'm trying to create a circle button, with "flap" on side, when you click on the button, the flap should move alongside the circle to the bottom.

The flap gets to the bottom but it starts with rotating. How can I move it alongside the circle without the initial rotation?

Questions related to this code. Why isn't the flap clickable? Why is the cursor not a pointer even though it's set in css? How to make the animation reverse when it's not active?

Thank you

$(".kolecko").on('click', function(){
$(this).toggleClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.kolecko{
        width: 150px;
        height: 150px;
        border-radius: 50%;
        background: #001f49;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        text-align: center;
        position: relative;
        cursor: pointer;
        }
        .kolecko::after{
          font-family: "Font Awesome 5 Free";
          font-weight: 900;
          content: "\f138";
          width: 40px;
          height: 50px;
          position: absolute;
          left: 100%;
          top: 50%;
          transform: translate(-4px,-50%);
          background: #8bc1ff;
          line-height: 50px;
          font-size: 25px;
          z-index: -1;
          border-top-right-radius: 10px;
          border-bottom-right-radius: 10px;
          cursor:pointer;
        }

 .kolecko.active::after{
          content: "\f139";
          offset-path: path('M-75,-75 A75,75 -45 0,1 -75,75');
          animation: move 1000ms ease-in-out forwards;
        }
@keyframes move {
  0% {
    offset-distance: 50%;
  }
  100% {
    offset-distance: 100%;
  }
}</code>```

<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"
integrity="sha384-
 B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU"
  crossorigin="anonymous">

                        chci
                        ZALOŽIT s.r.o. NA KLÍČ

```

答:
Fixed it by replacing "after" with element with svg background. Added animation to swing back.

Using translate to flip the element and also tuck it under the main circle.
Inspiration on using translate by @laaouatni-anas

 $(".kolecko").on('click', function (){
            const data = $(this).data('for');

            if($(this).hasClass('active')){
                $(this).removeClass('active');
                $('.kolecko').not(this).removeClass('non-active');
                $(this).addClass('wasActive')
                    .delay(1000)
                    .queue(function(next){
                        $(this).removeClass('wasActive');
                        next();
                    });
            }
            else if($(this).hasClass('non-active')){
                $('.kolecko').not(this)
                    .removeClass('active')
                    .addClass('non-active wasActive')
                    .delay(1000)
                    .queue(function(next){
                        $(this).removeClass('wasActive');
                        next();
                    });
                $(this).removeClass('non-active').addClass('active');

            }
            else{
                $('.kolecko').not(this).addClass('non-active');
                $(this).addClass('active');

            }

    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .kolecko{
        width: 150px;
        height: 150px;
        border-radius: 50%;
        background: #001f49;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        text-align: center;
        position: relative;
        cursor: pointer;
 }
  .kolecko.active .ucho{
          background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1175 1175'%3E%3Cpath style='fill:%23ed174a' class='fil0' d='M957 1l-957 -1c65,184 101,381 101,587 0,206 -36,404 -101,587l957 1c120,0 218,-98 218,-218l0 -738c0,-120 -98,-218 -218,-218z'/%3E%3C/svg%3E");
          offset-path: path('M-75,-75 A75,75 0 0,1 -75,75');
          animation: move 1000ms ease-in-out forwards;
          transform: rotate(-90deg) translate(calc(50% - 4px),0);
  }
.kolecko.active .ucho::after{
            content: "\f137";
          }

.kolecko.wasActive .ucho{
        offset-path: path('M-75,-75 A75,75 0 0,1 -75,75');
        animation: moveback 1000ms ease-in-out forwards;
        transform: rotate(-90deg) translate(calc(50% - 4px),0);
 }
.ucho{
          background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1175 1175'%3E%3Cpath style='fill: %239BA1C6' class='fil0' d='M957 1l-957 -1c65,184 101,381 101,587 0,206 -36,404 -101,587l957 1c120,0 218,-98 218,-218l0 -738c0,-120 -98,-218 -218,-218z'/%3E%3C/svg%3E");
          background-repeat: no-repeat;
          width: 45px;
          height: 45px;
          background-size: 100% 100%;
          line-height: 45px;
          position: absolute;
          left: 100%;
          top: 50%;
          transform: translate(-4px,-50%);
          cursor: pointer;
}
.ucho::after{
            font-family: "Font Awesome 5 Free";
            font-weight: 900;
            content: "\f138";
            font-size:25px;
}

@keyframes move {
  0% {
    offset-distance: 50%;
  }

  100% {
    offset-distance: 100%;
  }
}
@keyframes moveback {
  0% {
    offset-distance: 100%;
  }

  100% {
    offset-distance: 50%;

  }
}</code>```

<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"
integrity="sha384-
 B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU"
  crossorigin="anonymous">

                        chci
                        ZALOŽIT s.r.o. NA KLÍČ

```

Body:
I'm trying to create a circle button, with "flap" on side, when you click on the button, the flap should move alongside the circle to the bottom.

The flap gets to the bottom but it starts with rotating. How can I move it alongside the circle without the initial rotation?

Questions related to this code. Why isn't the flap clickable? Why is the cursor not a pointer even though it's set in css? How to make the animation reverse when it's not active?

Thank you

$(".kolecko").on('click', function(){
$(this).toggleClass('active');
});

.kolecko{
        width: 150px;
        height: 150px;
        border-radius: 50%;
        background: #001f49;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        text-align: center;
        position: relative;
        cursor: pointer;
        }
        .kolecko::after{
          font-family: "Font Awesome 5 Free";
          font-weight: 900;
          content: "\f138";
          width: 40px;
          height: 50px;
          position: absolute;
          left: 100%;
          top: 50%;
          transform: translate(-4px,-50%);
          background: #8bc1ff;
          line-height: 50px;
          font-size: 25px;
          z-index: -1;
          border-top-right-radius: 10px;
          border-bottom-right-radius: 10px;
          cursor:pointer;
        }

 .kolecko.active::after{
          content: "\f139";
          offset-path: path('M-75,-75 A75,75 -45 0,1 -75,75');
          animation: move 1000ms ease-in-out forwards;
        }
@keyframes move {
  0% {
    offset-distance: 50%;
  }
  100% {
    offset-distance: 100%;
  }
}

<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"
integrity="sha384-
 B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU"
  crossorigin="anonymous">

                        chci
                        ZALOŽIT s.r.o. NA KLÍČ

Body:
Fixed it by replacing "after" with element with svg background. Added animation to swing back.

Using translate to flip the element and also tuck it under the main circle.
Inspiration on using translate by @laaouatni-anas

 $(".kolecko").on('click', function (){
            const data = $(this).data('for');

            if($(this).hasClass('active')){
                $(this).removeClass('active');
                $('.kolecko').not(this).removeClass('non-active');
                $(this).addClass('wasActive')
                    .delay(1000)
                    .queue(function(next){
                        $(this).removeClass('wasActive');
                        next();
                    });
            }
            else if($(this).hasClass('non-active')){
                $('.kolecko').not(this)
                    .removeClass('active')
                    .addClass('non-active wasActive')
                    .delay(1000)
                    .queue(function(next){
                        $(this).removeClass('wasActive');
                        next();
                    });
                $(this).removeClass('non-active').addClass('active');

            }
            else{
                $('.kolecko').not(this).addClass('non-active');
                $(this).addClass('active');

            }

    });

 .kolecko{
        width: 150px;
        height: 150px;
        border-radius: 50%;
        background: #001f49;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        text-align: center;
        position: relative;
        cursor: pointer;
 }
  .kolecko.active .ucho{
          background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1175 1175'%3E%3Cpath style='fill:%23ed174a' class='fil0' d='M957 1l-957 -1c65,184 101,381 101,587 0,206 -36,404 -101,587l957 1c120,0 218,-98 218,-218l0 -738c0,-120 -98,-218 -218,-218z'/%3E%3C/svg%3E");
          offset-path: path('M-75,-75 A75,75 0 0,1 -75,75');
          animation: move 1000ms ease-in-out forwards;
          transform: rotate(-90deg) translate(calc(50% - 4px),0);
  }
.kolecko.active .ucho::after{
            content: "\f137";
          }

.kolecko.wasActive .ucho{
        offset-path: path('M-75,-75 A75,75 0 0,1 -75,75');
        animation: moveback 1000ms ease-in-out forwards;
        transform: rotate(-90deg) translate(calc(50% - 4px),0);
 }
.ucho{
          background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1175 1175'%3E%3Cpath style='fill: %239BA1C6' class='fil0' d='M957 1l-957 -1c65,184 101,381 101,587 0,206 -36,404 -101,587l957 1c120,0 218,-98 218,-218l0 -738c0,-120 -98,-218 -218,-218z'/%3E%3C/svg%3E");
          background-repeat: no-repeat;
          width: 45px;
          height: 45px;
          background-size: 100% 100%;
          line-height: 45px;
          position: absolute;
          left: 100%;
          top: 50%;
          transform: translate(-4px,-50%);
          cursor: pointer;
}
.ucho::after{
            font-family: "Font Awesome 5 Free";
            font-weight: 900;
            content: "\f138";
            font-size:25px;
}

@keyframes move {
  0% {
    offset-distance: 50%;
  }

  100% {
    offset-distance: 100%;
  }
}
@keyframes moveback {
  0% {
    offset-distance: 100%;
  }

  100% {
    offset-distance: 50%;

  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"
integrity="sha384-
 B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU"
  crossorigin="anonymous">
<div class="kolecko" data-for="zalozit-klic">
                        <span class="chci">chci</span>
                        <span class="nazev-sluzby">ZALOŽIT s.r.o. NA KLÍČ</span>
                        <span class="ucho">
                    </div>


问:
function to drop outliers
I created a function to drop my outliers. Here is the function

```<code>def dropping_outliers(train, condition):
    drop_index = train[condition].index
    #print(drop_index)
    train = train.drop(drop_index,axis = 0)
</code>```

and when I do

```<code>dropping_outliers(train, ((train.SalePrice<100000)  & (train.LotFrontage>150)))
</code>```

Nothing is being dropped.However when I manually execute the function. i.e get the index in the dataframe for this condition, I do get a valid index (943) and when I do

```<code>train = train.drop([943],axis = 0)
</code>```

Then the row I want is being dropped correctly. I don't understand why the function wouldn't work as its supposed to be doing exactly what I am doing manually.

答:
At the end of dropping_outliers, it's assigning the result of drop to a local variable, not altering the dataframe passed in. Try this instead:

```<code>def dropping_outliers(train, condition):
    drop_index = train[condition].index
    #print(drop_index)
    return train.drop(drop_index,axis = 0)
</code>```

Then do the assignment when you call the function.

```<code>train = dropping_outliers(train, ((train.SalePrice<100000)  & (train.LotFrontage>150)))
</code>```

Also see python pandas dataframe, is it pass-by-value or pass-by-reference.

Title: function to drop outliers

Body:
I created a function to drop my outliers. Here is the function

def dropping_outliers(train, condition):
    drop_index = train[condition].index
    #print(drop_index)
    train = train.drop(drop_index,axis = 0)

and when I do

dropping_outliers(train, ((train.SalePrice<100000)  & (train.LotFrontage>150)))

Nothing is being dropped.However when I manually execute the function. i.e get the index in the dataframe for this condition, I do get a valid index (943) and when I do

train = train.drop([943],axis = 0)

Then the row I want is being dropped correctly. I don't understand why the function wouldn't work as its supposed to be doing exactly what I am doing manually.

Body:
At the end of dropping_outliers, it's assigning the result of drop to a local variable, not altering the dataframe passed in. Try this instead:

def dropping_outliers(train, condition):
    drop_index = train[condition].index
    #print(drop_index)
    return train.drop(drop_index,axis = 0)

Then do the assignment when you call the function.

train = dropping_outliers(train, ((train.SalePrice<100000)  & (train.LotFrontage>150)))

Also see python pandas dataframe, is it pass-by-value or pass-by-reference.


问:
Unable to copy file .exe in Visual Studio 2017
I have an asp.net core project that references .NET Framework and I'm using Visual Studio 2017 Enterprise. When I try to build my solution, I came across with this error:

```<code>Unable to copy file "obj\Debug\net461\MyProject.exe" to "bin\Debug\net461\MyProject.exe".
Access to the path 'bin\Debug\net461\MyProject.exe' is denied.
</code>```

Even if I cleaned the solution and build again, I still have this error.

Anyone faced this error?

答: Close the application and delete Obj and bin folder</p>

Body:
I have an asp.net core project that references .NET Framework and I'm using Visual Studio 2017 Enterprise. When I try to build my solution, I came across with this error:

Unable to copy file "obj\Debug\net461\MyProject.exe" to "bin\Debug\net461\MyProject.exe".
Access to the path 'bin\Debug\net461\MyProject.exe' is denied.

Even if I cleaned the solution and build again, I still have this error.

Anyone faced this error?


问:
PyQt5 combo retrieve the value rather than the key or text
In my class definition I have:

```<code>    colours = {
        None: None,
        "Red": "255,0,0",
        "Green": "0, 255, 0",
        "Blue": "0, 0, 255",
    }

    self.colourComboTop.addItems(colours)
</code>```

In my code:

```<code>def some_function(self):

    self.colourComboTop.currentIndex()
</code>```

Gets the index, 0, 1, 2, 3

```<code>    self.colourComboTop.itemText(self.colourComboTop.currentIndex())
</code>```

Gets the displayed text.

How do I access the value associated with the key? So with {"Red": "255,0,0"} I want the rgb value as a string.

答:
Either set the RGB value as the userData argument,

```<code>for key, value in colours.items():
    self.colourComboTop.addItem(key, value)

key = self.colourComboTop.currentText()
rgb = self.colourComboTop.currentData()
</code>```

Or keep a reference to the dict and just map it.

```<code>self.colours = {
    None: None,
    "Red": "255,0,0",
    "Green": "0, 255, 0",
    "Blue": "0, 0, 255",
}

self.colourComboTop.addItems(self.colours)

key = self.colourComboTop.currentText()
rgb = self.colours[key]
</code>```

Body:
In my class definition I have:

    colours = {
        None: None,
        "Red": "255,0,0",
        "Green": "0, 255, 0",
        "Blue": "0, 0, 255",
    }

    self.colourComboTop.addItems(colours)

In my code:

def some_function(self):

    self.colourComboTop.currentIndex()

Gets the index, 0, 1, 2, 3

    self.colourComboTop.itemText(self.colourComboTop.currentIndex())

Gets the displayed text.

How do I access the value associated with the key? So with {"Red": "255,0,0"} I want the rgb value as a string.

Body:
Either set the RGB value as the userData argument,

for key, value in colours.items():
    self.colourComboTop.addItem(key, value)

key = self.colourComboTop.currentText()
rgb = self.colourComboTop.currentData()

Or keep a reference to the dict and just map it.

self.colours = {
    None: None,
    "Red": "255,0,0",
    "Green": "0, 255, 0",
    "Blue": "0, 0, 255",
}

self.colourComboTop.addItems(self.colours)

key = self.colourComboTop.currentText()
rgb = self.colours[key]


问:
How to best use JSF2 resources from Javascript
Using resources in JSF2 is a great thing because you can store the resource at some location and then reference them using different alternatives in HTML or in JSF2. I use the resources like this in XHTML pages:

```<code><h:graphicImage value="#{resource['image:sort_up.png']}"/>
</code>```

or I use the resources from Java when I create my own taglib:

```<code>ResourceHandler resHandler = context.getApplication().getResourceHandler();
Resource minus = resHandler.createResource(IMAGES_TOGGLE_MINUS_PNG,"image");
writer.startElement("img", toComponent);
writer.writeAttribute("src", minus.getRequestPath(), "src");
</code>```

The translated path in the HTML then looks something like this:

```<code>/nbfrontend/jsf2frontend/javax.faces.resource/sort_up.png.xhtml?ln=image
</code>```

The question is: How do I reference those images from JavaScript?

One way would be to create a hidden element where I would store the path, and then use getElementByID to retrieve the hidden element and retrieve the value from there. But this does not scale well when a lot of images are used in the application.

Another workaround would be to pass the path to the images to the JavaScript functions, but this is not feasible for JavaScript functions that are not called directly.

Is there any other alternative to use such JSF2 resources in JavaScript?

答:
Use it as CSS background image instead which you serve by <h:outputStylesheet>.

.toggle {
    background-image: url(#{resource['image:sort_up.png']});
}

.toggle.up {
    background-image: url(#{resource['image:sort_down.png']});
}
```

<p>in combination with this JS (jQuery flavored)</p>

```$('.toggle').click(function() {
    $(this).toggleClass('up');
    // ...
});
```

Body:
Using resources in JSF2 is a great thing because you can store the resource at some location and then reference them using different alternatives in HTML or in JSF2. I use the resources like this in XHTML pages:

<h:graphicImage value="#{resource['image:sort_up.png']}"/>

or I use the resources from Java when I create my own taglib:

ResourceHandler resHandler = context.getApplication().getResourceHandler();
Resource minus = resHandler.createResource(IMAGES_TOGGLE_MINUS_PNG,"image");
writer.startElement("img", toComponent);
writer.writeAttribute("src", minus.getRequestPath(), "src");

The translated path in the HTML then looks something like this:

/nbfrontend/jsf2frontend/javax.faces.resource/sort_up.png.xhtml?ln=image

The question is: How do I reference those images from JavaScript?

One way would be to create a hidden element where I would store the path, and then use getElementByID to retrieve the hidden element and retrieve the value from there. But this does not scale well when a lot of images are used in the application.

Another workaround would be to pass the path to the images to the JavaScript functions, but this is not feasible for JavaScript functions that are not called directly.

Is there any other alternative to use such JSF2 resources in JavaScript?

Body:
Use it as CSS background image instead which you serve by <h:outputStylesheet>.

.toggle {
    background-image: url(#{resource['image:sort_up.png']});
}

.toggle.up {
    background-image: url(#{resource['image:sort_down.png']});
}

in combination with this JS (jQuery flavored)

$('.toggle').click(function() {
    $(this).toggleClass('up');
    // ...
});


问:
assert properties of a object are non-null using a function's arguments
I want to achieve a type-safe API that takes a generic and only executes if a condition is met:

```<code>const doSomethingWith = (data: unknown) => data

const fn = <T extends unknown>(data: T, opts: { if: boolean }): void => {
  if (opts.if == false) return;

  doSomethingWith(data)
}
</code>```

How can I make opts.if a valid predicate in this context? Consider the following cases:

```<code>type Data = { abc: string }

// should be valid - checks to make sure data.abc is non-null
const data: Partial<Data> = {}
fn<Data>(data, { if: data.abc != null  })

// should be valid - all data is given
const data2: Data = { abc: '123' }
fn<Data>(data2)

// should be invalid - no null check occurs
const data3: Partial<Data> = {}
fn<Data>(data3)
</code>```

Typescript Playground.

答:
My first attempt at this was way over-complicated.  But upon reading your question again, I think we can make this really simple.

Solution

You can require that your arguments are valid using function overloads.

```<code>function fn<T>(data: Partial<T>, opts: { if: boolean }): void
function fn<T>(data: T): void
function fn<T>(data: T, opts?: { if: boolean }): void {
  if (opts?.if == false) return;

  doSomethingWith(data);
}
</code>```

The third fn line is the implementation signature, and the first two lines are the function signatures that you must match.

Explanation

All three of your examples expect that doSomethingWith will be called with a complete Data object.

If your data variable is incomplete then opts must be provided.  The first overload signature allows for Partial<Data> but requires opts:

```<code>function fn<T>(data: Partial<T>, opts: { if: boolean }): void
</code>```

which matches example #1:

```<code>// should be valid - checks to make sure data.abc is non-null
const data: Partial<Data> = {}
fn<Data>(data, { if: data.abc != null  })
</code>```

If we already know that the data variable is complete, then you don't need to provide any opts.  That is this signature:

```<code>function fn<T>(data: T): void
</code>```

which matches example #2:

```<code>// should be valid - all data is given
const data2: Data = { abc: '123' }
fn<Data>(data2)
</code>```

Your third example fails as expected because it does not match either of the overloaded function signatures.  Since we haven't provided an opts argument, the first argument must be a complete Data object.  But data3 is Partial<Data> so we get an error:

```<code>// should be invalid - no null check occurs
const data3: Partial<Data> = {}
fn<Data>(data3)
</code>```
```<code>Argument of type 'Partial<Data>' is not assignable to parameter of type 'Data'.
  Types of property 'abc' are incompatible.
   Type 'string | undefined' is not assignable to type 'string'.
     Type 'undefined' is not assignable to type 'string'.(2345)
</code>```

TypeScript Playground Link

Body:
I want to achieve a type-safe API that takes a generic and only executes if a condition is met:

const doSomethingWith = (data: unknown) => data

const fn = <T extends unknown>(data: T, opts: { if: boolean }): void => {
  if (opts.if == false) return;

  doSomethingWith(data)
}

How can I make opts.if a valid predicate in this context? Consider the following cases:

type Data = { abc: string }

// should be valid - checks to make sure data.abc is non-null
const data: Partial<Data> = {}
fn<Data>(data, { if: data.abc != null  })

// should be valid - all data is given
const data2: Data = { abc: '123' }
fn<Data>(data2)

// should be invalid - no null check occurs
const data3: Partial<Data> = {}
fn<Data>(data3)

<a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBAJiAyiAtgUygCwJZgOYDq2WMAvDABRwCGU1AXDAK5gDWYIA7mAJRkB88WtQCwAKHGhIsAGZgyMADwAVGGgAeUNGDgRmbDt35VhjZQBoYIAA5QIAfkYBvGNhmMARiBAAbNNXkAXx5GADcQbDgBGCdxGFcZShs7ewA6NzJyGWofCDQ+ACcMJgKwAG5xOPgkVAwcfCIsEzoecUDKsSgAT2s0GAARYQUXag9gRmgC3DwYdokxAHoFmAhMECYfKI8+0JzImABaGGBMNGBWPSgQGBRqVj6IEr6aOlTR4Fc9DjADsA2fSTgaBCOiMAAK1AKUGwOUUgzognITjmcjhwmML2olhcbkYmLeYxgAEJyH8fD54sEOksVmsNlsdnsokcchTMZ8YHhsKFtIDpCDqAAmRjw6jDGDvRgAcgAjIKAMxS2biVGijHCQWteY01brTYwbauMC7Hz7I4cGBkiknM6sKzAYAlCB84GY+XgyHQ2Fq4YosBohHNajynhAA" rel="nofollow noreferrer">Typescript Playground.

Body:
My first attempt at this was way over-complicated.  But upon reading your question again, I think we can make this really simple.

Solution

You can require that your arguments are valid using function overloads.

function fn<T>(data: Partial<T>, opts: { if: boolean }): void
function fn<T>(data: T): void
function fn<T>(data: T, opts?: { if: boolean }): void {
  if (opts?.if == false) return;

  doSomethingWith(data);
}

The third fn line is the implementation signature, and the first two lines are the function signatures that you must match.

Explanation

All three of your examples expect that doSomethingWith will be called with a complete Data object.

If your data variable is incomplete then opts must be provided.  The first overload signature allows for Partial<Data> but requires opts:

function fn<T>(data: Partial<T>, opts: { if: boolean }): void

which matches example #1:

// should be valid - checks to make sure data.abc is non-null
const data: Partial<Data> = {}
fn<Data>(data, { if: data.abc != null  })

If we already know that the data variable is complete, then you don't need to provide any opts.  That is this signature:

function fn<T>(data: T): void

which matches example #2:

// should be valid - all data is given
const data2: Data = { abc: '123' }
fn<Data>(data2)

Your third example fails as expected because it does not match either of the overloaded function signatures.  Since we haven't provided an opts argument, the first argument must be a complete Data object.  But data3 is Partial<Data> so we get an error:

// should be invalid - no null check occurs
const data3: Partial<Data> = {}
fn<Data>(data3)

Argument of type 'Partial<Data>' is not assignable to parameter of type 'Data'.
  Types of property 'abc' are incompatible.
   Type 'string | undefined' is not assignable to type 'string'.
     Type 'undefined' is not assignable to type 'string'.(2345)

TypeScript Playground Link


问:
Data from back end not showing in front end using django
I am trying to insert data into my frontend but not sure what I did wrong here. Here is the code...

I don't have any errors showing in my terminal or web browser.

my views.py

```<code>from django.shortcuts import render, get_list_or_404

from adopt.models import Adopt

# Create your views here.
def adopt(request):
    return render(request, 'adopts/adopt.html')

def adopt_detail(request, id):
    single_pet = get_list_or_404(Adopt, pk=id)

    data = {
        'single_pet': single_pet,
    }
    return render(request, 'adopts/adopt_detail.html', data)

def search(request):
    adopt = Adopt.objects.order_by('-created_date')

    if 'keyword' in request.GET:
        keyword = request.GET['keyword']
        if keyword:
            adopt = adopt.filter(description__icontains=keyword)
            data = {
                'adopt': adopt,
            }
            return render(request, 'adopts/search.html', data)
</code>```

my models.py

```<code>from django.db import models
from datetime import datetime
from ckeditor.fields import RichTextField

# Create your models here.
class Adopt(models.Model):

    pet_gender = (
        ('F','Female'),
        ('M', 'Male'),
    )

    state_choice = (
        ('AL', 'Alabama'),
        ('AK', 'Alaska'),
        ('AZ', 'Arizona'),
        ('AR', 'Arkansas'),
        ('CA', 'California'),
        ('CO', 'Colorado'),
        ('CT', 'Connecticut'),
        ('DE', 'Delaware'),
        ('DC', 'District Of Columbia'),
        ('FL', 'Florida'),
        ('GA', 'Georgia'),
        ('HI', 'Hawaii'),
        ('ID', 'Idaho'),
        ('IL', 'Illinois'),
        ('IN', 'Indiana'),
        ('IA', 'Iowa'),
        ('KS', 'Kansas'),
        ('KY', 'Kentucky'),
        ('LA', 'Louisiana'),
        ('ME', 'Maine'),
        ('MD', 'Maryland'),
        ('MA', 'Massachusetts'),
        ('MI', 'Michigan'),
        ('MN', 'Minnesota'),
        ('MS', 'Mississippi'),
        ('MO', 'Missouri'),
        ('MT', 'Montana'),
        ('NE', 'Nebraska'),
        ('NV', 'Nevada'),
        ('NH', 'New Hampshire'),
        ('NJ', 'New Jersey'),
        ('NM', 'New Mexico'),
        ('NY', 'New York'),
        ('NC', 'North Carolina'),
        ('ND', 'North Dakota'),
        ('OH', 'Ohio'),
        ('OK', 'Oklahoma'),
        ('OR', 'Oregon'),
        ('PA', 'Pennsylvania'),
        ('RI', 'Rhode Island'),
        ('SC', 'South Carolina'),
        ('SD', 'South Dakota'),
        ('TN', 'Tennessee'),
        ('TX', 'Texas'),
        ('UT', 'Utah'),
        ('VT', 'Vermont'),
        ('VA', 'Virginia'),
        ('WA', 'Washington'),
        ('WV', 'West Virginia'),
        ('WI', 'Wisconsin'),
        ('WY', 'Wyoming'),
    )

    year_choice = []
    for r in range(2000, (datetime.now().year+1)):
        year_choice.append((r,r))

    pet_title = models.CharField(max_length=255)
    state = models.CharField(choices=state_choice, max_length=100)
    city = models.CharField(max_length=100)
    gender = models.CharField(choices=pet_gender, max_length=100, blank=True)
    breed = models.CharField(max_length=100)
    year = models.IntegerField(('year'), choices=year_choice)
    pet_photo = models.ImageField(upload_to='photots/%Y/%m/%d/')
    description = RichTextField()
    price = models.IntegerField()
    created_date = models.DateTimeField(default=datetime.now, blank=True)

    def __str__(self):
        return self.pet_title
</code>```

答:
    {% extends 'base.html' %}

    {% block content %}

Featured Pets

            {% for adopt in adopts %}

{{adopt.pet_title}}

{{adopt.price}}

{{adopt.description | safe}}

                        Go somewhere

            {% endfor %}

    {% endblock %}

```

Body:
I am trying to insert data into my frontend but not sure what I did wrong here. Here is the code...

I don't have any errors showing in my terminal or web browser.

my views.py

from django.shortcuts import render, get_list_or_404

from adopt.models import Adopt

# Create your views here.
def adopt(request):
    return render(request, 'adopts/adopt.html')

def adopt_detail(request, id):
    single_pet = get_list_or_404(Adopt, pk=id)

    data = {
        'single_pet': single_pet,
    }
    return render(request, 'adopts/adopt_detail.html', data)

def search(request):
    adopt = Adopt.objects.order_by('-created_date')

    if 'keyword' in request.GET:
        keyword = request.GET['keyword']
        if keyword:
            adopt = adopt.filter(description__icontains=keyword)
            data = {
                'adopt': adopt,
            }
            return render(request, 'adopts/search.html', data)

my models.py

from django.db import models
from datetime import datetime
from ckeditor.fields import RichTextField

# Create your models here.
class Adopt(models.Model):

    pet_gender = (
        ('F','Female'),
        ('M', 'Male'),
    )

    state_choice = (
        ('AL', 'Alabama'),
        ('AK', 'Alaska'),
        ('AZ', 'Arizona'),
        ('AR', 'Arkansas'),
        ('CA', 'California'),
        ('CO', 'Colorado'),
        ('CT', 'Connecticut'),
        ('DE', 'Delaware'),
        ('DC', 'District Of Columbia'),
        ('FL', 'Florida'),
        ('GA', 'Georgia'),
        ('HI', 'Hawaii'),
        ('ID', 'Idaho'),
        ('IL', 'Illinois'),
        ('IN', 'Indiana'),
        ('IA', 'Iowa'),
        ('KS', 'Kansas'),
        ('KY', 'Kentucky'),
        ('LA', 'Louisiana'),
        ('ME', 'Maine'),
        ('MD', 'Maryland'),
        ('MA', 'Massachusetts'),
        ('MI', 'Michigan'),
        ('MN', 'Minnesota'),
        ('MS', 'Mississippi'),
        ('MO', 'Missouri'),
        ('MT', 'Montana'),
        ('NE', 'Nebraska'),
        ('NV', 'Nevada'),
        ('NH', 'New Hampshire'),
        ('NJ', 'New Jersey'),
        ('NM', 'New Mexico'),
        ('NY', 'New York'),
        ('NC', 'North Carolina'),
        ('ND', 'North Dakota'),
        ('OH', 'Ohio'),
        ('OK', 'Oklahoma'),
        ('OR', 'Oregon'),
        ('PA', 'Pennsylvania'),
        ('RI', 'Rhode Island'),
        ('SC', 'South Carolina'),
        ('SD', 'South Dakota'),
        ('TN', 'Tennessee'),
        ('TX', 'Texas'),
        ('UT', 'Utah'),
        ('VT', 'Vermont'),
        ('VA', 'Virginia'),
        ('WA', 'Washington'),
        ('WV', 'West Virginia'),
        ('WI', 'Wisconsin'),
        ('WY', 'Wyoming'),
    )

    year_choice = []
    for r in range(2000, (datetime.now().year+1)):
        year_choice.append((r,r))

    pet_title = models.CharField(max_length=255)
    state = models.CharField(choices=state_choice, max_length=100)
    city = models.CharField(max_length=100)
    gender = models.CharField(choices=pet_gender, max_length=100, blank=True)
    breed = models.CharField(max_length=100)
    year = models.IntegerField(('year'), choices=year_choice)
    pet_photo = models.ImageField(upload_to='photots/%Y/%m/%d/')
    description = RichTextField()
    price = models.IntegerField()
    created_date = models.DateTimeField(default=datetime.now, blank=True)

    def __str__(self):
        return self.pet_title

Body:
    {% extends 'base.html' %}

    {% block content %}

    <div class="Featured-container">
        <div class="row">
            <div class="col-12">
                <div class="Featured-header">
                    <h1>Featured Pets</h1>
                </div>
            </div>
        </div>

        <div class="row">
            {% for adopt in adopts %}
            <div class="col-sm-12 col-md-3 col-lg-3 col-xl-3">
                <div class="card Featured-card Pet-card">
                    <img class=" card-img-top" src="
   {{adopt.pet_photo.url}}" alt="Card image cap"
                    style="min-height:262px; max-height: 262px;">
                    <div class="card-body">
                        <h5 class="card-title">{{adopt.pet_title}}</h5>
                        <p class="card-text">{{adopt.price}}</p>
                        <p class="card-text">{{adopt.description | safe}}</p>
                        <a href="{% url 'adopt_detail' adopt.id %}" class="btn btn-primary">Go somewhere</a>
                    </div>
                </div>
            </div>
            {% endfor %}

        </div>
    </div>

    {% endblock %}


问:
How to select points from matrix with given probability?
I have a numpy.ndarray points representing a set of coordinate points:

```<code>[[0 0]
 [0 1]
 [0 2]
 [1 0]
 [1 1]
 [1 2]
 [2 0]
 [2 1]
 [2 2]]
</code>```

I want to get a subset of this points some_points where each point is independently taken with probability prob. How can I do this using only numpy?

P.S. For instance, if prob=0.5 some_points will contain about a half of original points.

答:
You could for example create a vector with n samples from the uniform distribution, with n being the number of points and compare those with your desired probability. For all samples smaller than the probability you take the corresponding point. In code

import numpy as np
prob = 0.5
some_points = points[np.random.rand(points.shape[0]) < prob, :]
```

Body:
I have a numpy.ndarray points representing a set of coordinate points:

[[0 0]
 [0 1]
 [0 2]
 [1 0]
 [1 1]
 [1 2]
 [2 0]
 [2 1]
 [2 2]]

I want to get a subset of this points some_points where each point is independently taken with probability prob. How can I do this using only numpy?

P.S. For instance, if prob=0.5 some_points will contain about a half of original points.


问:
How to find 7 days weather forecast in openweather API?
I am trying to find 7 days weather forecast using openweather API , but when I am calling the openweather API then the data are not coming for the current location, can anyone guide me to find the correct API to get weather forecast for the current location.

API's used so far

```<code>1. api.openweathermap.org/data/2.5/forecast?q={city name}&appid={API key}
2. https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API key}
</code>```

Reference links:

https://openweathermap.org/forecast5

https://openweathermap.org/api/one-call-api

Request: https://api.openweathermap.org/data/2.5/forecast?q=India&appid={MY_API_ID}
Response: (Added only 2 days data out of 40)

```<code>{
    "cod": "200",
    "message": 0,
    "cnt": 40,
    "list": [
        {
            "dt": 1600668000,
            "main": {
                "temp": 283.42,
                "feels_like": 282.81,
                "temp_min": 283.42,
                "temp_max": 284.26,
                "pressure": 1018,
                "sea_level": 1018,
                "grnd_level": 862,
                "humidity": 84,
                "temp_kf": -0.84
            },
            "weather": [
                {
                    "id": 802,
                    "main": "Clouds",
                    "description": "scattered clouds",
                    "icon": "03d"
                }
            ],
            "clouds": {
                "all": 32
            },
            "wind": {
                "speed": 0.1,
                "deg": 22
            },
            "visibility": 10000,
            "pop": 0,
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2020-09-21 06:00:00"
        },
        {
            "dt": 1600722000,
            "main": {
                "temp": 283.34,
                "feels_like": 282.29,
                "temp_min": 283.34,
                "temp_max": 283.34,
                "pressure": 1016,
                "sea_level": 1016,
                "grnd_level": 861,
                "humidity": 86,
                "temp_kf": 0
            },
            "weather": [
                {
                    "id": 500,
                    "main": "Rain",
                    "description": "light rain",
                    "icon": "10n"
                }
            ],
            "clouds": {
                "all": 66
            },
            "wind": {
                "speed": 0.82,
                "deg": 149
            },
            "visibility": 823,
            "pop": 0.35,
            "rain": {
                "3h": 0.18
            },
            "sys": {
                "pod": "n"
            },
            "dt_txt": "2020-09-21 21:00:00"
        }
    ],
    "city": {
        "id": 3168508,
        "name": "Innichen",
        "coord": {
            "lat": 46.7406,
            "lon": 12.2797
        },
        "country": "IT",
        "population": 3107,
        "timezone": 7200,
        "sunrise": 1600664205,
        "sunset": 1600708262
    }
}
</code>```

答:
For 7 days forecast you have to pass lat long and api id to below url

"https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&appid=${api}"

to get the lat long of the searched city, you can create an api call to below url first and then use that data to pass to above url.
https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api}

Hope this will help you. One way to try this.

// to get the lat long :

const getData = async () => {
    let city = document.getElementById("cityName").value; //input from user.
    let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api}`;
    try {
      let res = await fetch(url);
      let data = await res.json();
      let lat = data.coord.lat;
      let lon = data.coord.lon;
      getDatafor7days(lat, lon);
    } catch (error) {
      console.log(error);
    }
  };```
</div>
</div>
</p>
<p>// passing lat long to get the 7 days forecast :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const getDatafor7days = async (lat, lon) => {
    let url = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&appid=${api}`;
    try {
      let res = await fetch(url);
      let data = await res.json();
      console.log("data", data);
    } catch (error) {
      console.log(error);
    }
  };</code>```

Body:
I am trying to find 7 days weather forecast using openweather API , but when I am calling the openweather API then the data are not coming for the current location, can anyone guide me to find the correct API to get weather forecast for the current location.

API's used so far

1. api.openweathermap.org/data/2.5/forecast?q={city name}&appid={API key}
2. https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API key}

Reference links:

https://openweathermap.org/forecast5

https://openweathermap.org/api/one-call-api

Request: https://api.openweathermap.org/data/2.5/forecast?q=India&appid={MY_API_ID}
Response: (Added only 2 days data out of 40)

{
    "cod": "200",
    "message": 0,
    "cnt": 40,
    "list": [
        {
            "dt": 1600668000,
            "main": {
                "temp": 283.42,
                "feels_like": 282.81,
                "temp_min": 283.42,
                "temp_max": 284.26,
                "pressure": 1018,
                "sea_level": 1018,
                "grnd_level": 862,
                "humidity": 84,
                "temp_kf": -0.84
            },
            "weather": [
                {
                    "id": 802,
                    "main": "Clouds",
                    "description": "scattered clouds",
                    "icon": "03d"
                }
            ],
            "clouds": {
                "all": 32
            },
            "wind": {
                "speed": 0.1,
                "deg": 22
            },
            "visibility": 10000,
            "pop": 0,
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2020-09-21 06:00:00"
        },
        {
            "dt": 1600722000,
            "main": {
                "temp": 283.34,
                "feels_like": 282.29,
                "temp_min": 283.34,
                "temp_max": 283.34,
                "pressure": 1016,
                "sea_level": 1016,
                "grnd_level": 861,
                "humidity": 86,
                "temp_kf": 0
            },
            "weather": [
                {
                    "id": 500,
                    "main": "Rain",
                    "description": "light rain",
                    "icon": "10n"
                }
            ],
            "clouds": {
                "all": 66
            },
            "wind": {
                "speed": 0.82,
                "deg": 149
            },
            "visibility": 823,
            "pop": 0.35,
            "rain": {
                "3h": 0.18
            },
            "sys": {
                "pod": "n"
            },
            "dt_txt": "2020-09-21 21:00:00"
        }
    ],
    "city": {
        "id": 3168508,
        "name": "Innichen",
        "coord": {
            "lat": 46.7406,
            "lon": 12.2797
        },
        "country": "IT",
        "population": 3107,
        "timezone": 7200,
        "sunrise": 1600664205,
        "sunset": 1600708262
    }
}

Body:
For 7 days forecast you have to pass lat long and api id to below url

"https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&appid=${api}"

to get the lat long of the searched city, you can create an api call to below url first and then use that data to pass to above url.
https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api}

Hope this will help you. One way to try this.

// to get the lat long :

const getData = async () => {
    let city = document.getElementById("cityName").value; //input from user.
    let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api}`;
    try {
      let res = await fetch(url);
      let data = await res.json();
      let lat = data.coord.lat;
      let lon = data.coord.lon;
      getDatafor7days(lat, lon);
    } catch (error) {
      console.log(error);
    }
  };

// passing lat long to get the 7 days forecast :

const getDatafor7days = async (lat, lon) => {
    let url = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&appid=${api}`;
    try {
      let res = await fetch(url);
      let data = await res.json();
      console.log("data", data);
    } catch (error) {
      console.log(error);
    }
  };


问:
c++ Extract parameter type list from function pointer
Im trying to get the argument types from a function pointer

This should be the working end product

```<code>std::function<void(TestAppObject*, MemberFuncArgs<decltype(&TestAppObject::TestMethod)>::InputArgs)> func = &TestAppObject::TestMethod;
</code>```

Current MemberFuncArgs class

```<code>template<typename T>
struct MemberFuncArgs;

template<typename RT, typename Owner, typename ...Args>
struct MemberFuncArgs<RT(Owner::*)(Args...)>
{
    static const size_t ArgCount = sizeof...(Args);
    typedef RT ReturnType;
    typedef Args InputArgs;
};
</code>```

Compiler throws the error 'Args': parameter pack must be expanded in this context.

I just need a way to extract the Args... type from the function pointer, its probably just a syntax issue that im too dumb to see...

答:
The compiler say the you can't define a single type InputArgs

```<code>typedef Args InputArgs;
</code>```

given that Args is a variadic list.

Maybe you can define a type base on a tuple

```<code>using InArgsTuple = std::tuple<Args...>;
</code>```

so you can extract the single types in Args... using std::tuple_element

So, with a little template meta-programming, you should be able to write something as

```<code>using TplT = MemberFuncArgs<decltype(&TestAppObject::TestMethod)>::InArgsTuple;

std::function<void(TestAppObject*, typename std::tuple_element<Is, TplT>::type ...)>
   func = &TestAppObject::TestMethod;
</code>```

assuming that Is... is a variadic sequence of template integer values from zero to sizeof...(Args)-1.

The following is a full compiling C++20 example

```<code>#include <tuple>
#include <functional>

struct TestAppObject
{
  int TestMethod (char, short, int, long, long long)
  { return 0; }
};

template <typename T>
struct MemberFuncArgs;

template <typename RT, typename Owner, typename ... Args>
struct MemberFuncArgs<RT(Owner::*)(Args...)>
{
  static constexpr std::size_t ArgCount = sizeof...(Args);

  using ReturnType  = RT;
  using InArgsTuple = std::tuple<Args...>;
};

int main()
{
  using MFA  = MemberFuncArgs<decltype(&TestAppObject::TestMethod)>;
  using FunT = decltype([]<std::size_t ... Is>(std::index_sequence<Is...>)
     -> std::function<void(TestAppObject*,
           typename std::tuple_element<Is, MFA::InArgsTuple>::type ...)>
     { return {}; }
     (std::make_index_sequence<MFA::ArgCount>{}));

  FunT  func = &TestAppObject::TestMethod;
}
</code>```

If you can't use C++20 (so no template lambda and no lambda in not evaluated context) you can substitute the lambda with a traditional template function, only declared (because is used only inside decltype().

The following is a full compiling C++14/C++17 example.
#include
#include

```<code>struct TestAppObject
{
  int TestMethod (char, short, int, long, long long)
  { return 0; }
};

template <typename T>
struct MemberFuncArgs;

template <typename RT, typename Owner, typename ... Args>
struct MemberFuncArgs<RT(Owner::*)(Args...)>
{
  static constexpr std::size_t ArgCount = sizeof...(Args);

  using ReturnType  = RT;
  using InArgsTuple = std::tuple<Args...>;
};

template <typename MFA, std::size_t ... Is>
std::function<void(TestAppObject*,
   typename std::tuple_element<Is, typename MFA::InArgsTuple>::type ...)>
      extra_function (std::index_sequence<Is...>);

int main()
{
  using MFA  = MemberFuncArgs<decltype(&TestAppObject::TestMethod)>;
  using FunT = decltype(extra_function<MFA>
                           (std::make_index_sequence<MFA::ArgCount>{}));

  FunT  func = &TestAppObject::TestMethod;
}
</code>```

Body:
Im trying to get the argument types from a function pointer

This should be the working end product

std::function<void(TestAppObject*, MemberFuncArgs<decltype(&TestAppObject::TestMethod)>::InputArgs)> func = &TestAppObject::TestMethod;

Current MemberFuncArgs class

template<typename T>
struct MemberFuncArgs;

template<typename RT, typename Owner, typename ...Args>
struct MemberFuncArgs<RT(Owner::*)(Args...)>
{
    static const size_t ArgCount = sizeof...(Args);
    typedef RT ReturnType;
    typedef Args InputArgs;
};

Compiler throws the error 'Args': parameter pack must be expanded in this context.

I just need a way to extract the Args... type from the function pointer, its probably just a syntax issue that im too dumb to see...

Body:
The compiler say the you can't define a single type InputArgs

typedef Args InputArgs;

given that Args is a variadic list.

Maybe you can define a type base on a tuple

using InArgsTuple = std::tuple<Args...>;

so you can extract the single types in Args... using std::tuple_element

So, with a little template meta-programming, you should be able to write something as

using TplT = MemberFuncArgs<decltype(&TestAppObject::TestMethod)>::InArgsTuple;

std::function<void(TestAppObject*, typename std::tuple_element<Is, TplT>::type ...)>
   func = &TestAppObject::TestMethod;

assuming that Is... is a variadic sequence of template integer values from zero to sizeof...(Args)-1.

The following is a full compiling C++20 example

#include <tuple>
#include <functional>

struct TestAppObject
{
  int TestMethod (char, short, int, long, long long)
  { return 0; }
};

template <typename T>
struct MemberFuncArgs;

template <typename RT, typename Owner, typename ... Args>
struct MemberFuncArgs<RT(Owner::*)(Args...)>
{
  static constexpr std::size_t ArgCount = sizeof...(Args);

  using ReturnType  = RT;
  using InArgsTuple = std::tuple<Args...>;
};

int main()
{
  using MFA  = MemberFuncArgs<decltype(&TestAppObject::TestMethod)>;
  using FunT = decltype([]<std::size_t ... Is>(std::index_sequence<Is...>)
     -> std::function<void(TestAppObject*,
           typename std::tuple_element<Is, MFA::InArgsTuple>::type ...)>
     { return {}; }
     (std::make_index_sequence<MFA::ArgCount>{}));

  FunT  func = &TestAppObject::TestMethod;
}

If you can't use C++20 (so no template lambda and no lambda in not evaluated context) you can substitute the lambda with a traditional template function, only declared (because is used only inside decltype().

The following is a full compiling C++14/C++17 example.
#include
#include

struct TestAppObject
{
  int TestMethod (char, short, int, long, long long)
  { return 0; }
};

template <typename T>
struct MemberFuncArgs;

template <typename RT, typename Owner, typename ... Args>
struct MemberFuncArgs<RT(Owner::*)(Args...)>
{
  static constexpr std::size_t ArgCount = sizeof...(Args);

  using ReturnType  = RT;
  using InArgsTuple = std::tuple<Args...>;
};

template <typename MFA, std::size_t ... Is>
std::function<void(TestAppObject*,
   typename std::tuple_element<Is, typename MFA::InArgsTuple>::type ...)>
      extra_function (std::index_sequence<Is...>);

int main()
{
  using MFA  = MemberFuncArgs<decltype(&TestAppObject::TestMethod)>;
  using FunT = decltype(extra_function<MFA>
                           (std::make_index_sequence<MFA::ArgCount>{}));

  FunT  func = &TestAppObject::TestMethod;
}


问:
dictionary in flask_jwt_extended create_access_token
How can i use dictionary in token identity with flask_jwt_extended.
Any suggestions for pass multiple values in token?

```<code>create_access_token(identity=????)
</code>```

Thanks

答:
Yes this is totally can be done by passing a dictionary like:

```<code>create_access_token(identity= {"name":"Hello", "age":35} )
</code>```

and this would work by implementing a callback function decorated with user_identity_loader. The callback function should take one argument and returns JSON string:

```<code>jwt = JWTManager(app)

import json

@jwt.user_identity_loader
def user_maker(obj):
    return json.dumps(obj)
</code>```

read more

Body:
How can i use dictionary in token identity with flask_jwt_extended.
Any suggestions for pass multiple values in token?

create_access_token(identity=????)

Thanks

Body:
Yes this is totally can be done by passing a dictionary like:

create_access_token(identity= {"name":"Hello", "age":35} )

and this would work by implementing a callback function decorated with user_identity_loader. The callback function should take one argument and returns JSON string:

jwt = JWTManager(app)

import json

@jwt.user_identity_loader
def user_maker(obj):
    return json.dumps(obj)

read more