问:
Assembly scanning with attribute and named service in .NET Core
I've been asked to create a .NET Core implementation of CQRS pattern with the peculiarity that the request and response need to be generic because are generated client side.

Limiting the example to queries, any query had an handle method like this:

```<code>public async Task<QueryResponseDTO> Handle (QueryRequestDTO request)
</code>```

Where DTOs have a property inside that indicate the QueryName and are received using a broker (KubeMQ by the way).

Given the fact that DTOs are always the same, I cannot use Mediatr to dispatch the queries, so I'm trying to create a mechanism using named service registration to make this work.

My idea is to create an attribute to be added to our queries classes and use that to populate a named service at startup.

I've created this attribute:

```<code>public class AutoWireQueryNameAttribute : Attribute
{
    public string QueryName { get; private set; }

    public AutoWireQueryNameAttribute(string queryName)
    {
        QueryName = queryName;
    }
}
</code>```

And class is tagged like this:

```<code>[AutoWireQueryName("GET_ALL_USERS")]
public class GetAllUsersQueryHandler : IRequestHandler<QueryRequestDTO, QueryResponseDTO>
{
    public async Task<QueryResponseDTO> Handle(QueryRequestDTO request)
    {
    }
}
</code>```

And then, at runtime, using something like this to resolve the correct handler:

```<code>var instance = container.GetInstance<IRequestHandler>("GET_ALL_USERS");
</code>```

My problem arise when I need to wire up everything inside the startup.cs with something like this:

```<code>services
    .Scan(scan => scan
        .FromApplicationDependencies()
        .AddClasses(f => f.WithAttribute<AutoWireQueryNameAttribute>())
        .UsingRegistrationStrategy(RegistrationStrategy.Append)
        .AsSelfWithInterfaces())
</code>```

I've come to understand that probably I will need an external IoC container to make this work (as scrutor is not the correct tool), but reading on Lighinject and Autofac documentation I couldn't find any useful indication on how to handle the service registration .

Any advice? I've taken a wrong road?

Body:
I've been asked to create a .NET Core implementation of CQRS pattern with the peculiarity that the request and response need to be generic because are generated client side.

Limiting the example to queries, any query had an handle method like this:

public async Task<QueryResponseDTO> Handle (QueryRequestDTO request)

Where DTOs have a property inside that indicate the QueryName and are received using a broker (KubeMQ by the way).

Given the fact that DTOs are always the same, I cannot use Mediatr to dispatch the queries, so I'm trying to create a mechanism using named service registration to make this work.

My idea is to create an attribute to be added to our queries classes and use that to populate a named service at startup.

I've created this attribute:

public class AutoWireQueryNameAttribute : Attribute
{
    public string QueryName { get; private set; }

    public AutoWireQueryNameAttribute(string queryName)
    {
        QueryName = queryName;
    }
}

And class is tagged like this:

[AutoWireQueryName("GET_ALL_USERS")]
public class GetAllUsersQueryHandler : IRequestHandler<QueryRequestDTO, QueryResponseDTO>
{
    public async Task<QueryResponseDTO> Handle(QueryRequestDTO request)
    {
    }
}

And then, at runtime, using something like this to resolve the correct handler:

var instance = container.GetInstance<IRequestHandler>("GET_ALL_USERS");

My problem arise when I need to wire up everything inside the startup.cs with something like this:

services
    .Scan(scan => scan
        .FromApplicationDependencies()
        .AddClasses(f => f.WithAttribute<AutoWireQueryNameAttribute>())
        .UsingRegistrationStrategy(RegistrationStrategy.Append)
        .AsSelfWithInterfaces())

I've come to understand that probably I will need an external IoC container to make this work (as scrutor is not the correct tool), but reading on Lighinject and Autofac documentation I couldn't find any useful indication on how to handle the service registration .

Any advice? I've taken a wrong road?


来源: stackexchange

问:
how get arguments from the command line to Asp.net Core 3.1 CreateHostBuilder(string args[])
I want to install an asp.net core 3.1 Web api as a windows service. The command to do this, is

```<code>sc start MyDotNetApi.dll
</code>```

it does not let you specify the port. In my app it is vital to let the user to specify the port so i tried this in my Program.cs

```<code>public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    log("test");
                    foreach (string arg in args)
                    {
                        log(arg);
                    }
                    string port = args.firstorDefault(a => a.StartsWith("--port"))?.Split('=')[1];
                    if (string.IsNullOrEmpty(port))
                    {
                        port = "3000";
                    }
                         webBuilder.UseStartup<Startup>();
                    webBuilder.UseUrls($"http://*:{port}"); ;
                }).UseWindowsService();
    }
</code>```

As you can see, i check if a --port argument is specified like this

```<code>sc start MyDotNetApi.dll --port=9000
</code>```

and if it is indeed specified i set the

```<code>string port
</code>```

to the value of the specified port. The problem is that the string[] args array is null. It works in debug but when i publish the solution and i try to actually start the service with the windows command line, it somehow does not recognize the arguments that are inputed in the command line. i tried to log the args[] and the logs show that it is null

i tried debbuging it by telling visual studio what the command line arguments should be and it works in debug.

ContentLicense: CC BY-SA 4.0

Body:
I want to install an asp.net core 3.1 Web api as a windows service. The command to do this, is

sc start MyDotNetApi.dll

it does not let you specify the port. In my app it is vital to let the user to specify the port so i tried this in my Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    log("test");
                    foreach (string arg in args)
                    {
                        log(arg);
                    }
                    string port = args.firstorDefault(a => a.StartsWith("--port"))?.Split('=')[1];
                    if (string.IsNullOrEmpty(port))
                    {
                        port = "3000";
                    }
                         webBuilder.UseStartup<Startup>();
                    webBuilder.UseUrls($"http://*:{port}"); ;
                }).UseWindowsService();
    }

As you can see, i check if a --port argument is specified like this

sc start MyDotNetApi.dll --port=9000

and if it is indeed specified i set the

string port

to the value of the specified port. The problem is that the string[] args array is null. It works in debug but when i publish the solution and i try to actually start the service with the windows command line, it somehow does not recognize the arguments that are inputed in the command line. i tried to log the args[] and the logs show that it is null

i tried debbuging it by telling visual studio what the command line arguments should be and it works in debug.


问:
web part SharePoint site, PNP search query template, search document name with FQL
I'm new to Sharepoint, and I'm using the PnP Search Webpart (search box, result search) on my site to search for documents in PDF and Doc format. So  I am using FQL to search the file names.

So the example that I used is the following:

```<code>Path:{Site} FileType:pdf FileType:png Title:{searchTerms}
</code>```

It's quite good, in case you typed the exact names of documents.

Instead, I want just the first three characters. I searched the documentation and found these functions.

```<code>starts-with()
</code>```
```<code>any()
</code>```

Unfortunately, this code did not go well with me.

```<code>Path:{Site} FileType:pdf FileType:png Title:starts-with({searchTerms})
</code>```

I don't know where the problem is because it seems like searchTerms didn't fill in the starts-with() function, or maybe starts-with accepts just strings as parameters.

I tried to use the starts-with function, but it always returned 0 documents.
When the user types three characters, I expect PnP to return documents that begin with the exact characters typed.

Body:
I'm new to Sharepoint, and I'm using the PnP Search Webpart (search box, result search) on my site to search for documents in PDF and Doc format. So  I am using FQL to search the file names.

So the example that I used is the following:

Path:{Site} FileType:pdf FileType:png Title:{searchTerms}

It's quite good, in case you typed the exact names of documents.

Instead, I want just the first three characters. I searched the documentation and found these functions.

starts-with()

any()

Unfortunately, this code did not go well with me.

Path:{Site} FileType:pdf FileType:png Title:starts-with({searchTerms})

I don't know where the problem is because it seems like searchTerms didn't fill in the starts-with() function, or maybe starts-with accepts just strings as parameters.

I tried to use the starts-with function, but it always returned 0 documents.
When the user types three characters, I expect PnP to return documents that begin with the exact characters typed.


问:
Does ASLR randomize .data when the binary has no PIE?
I've been playing with a binary programmed in C that has a buffer overflow to investigate how the different binary protections work and I've run into a situation that I can't quite figure out.
I made a small ROP chain to run execve to instance /bin/sh. The binary has no PIE and no canary, but on the host I do have ASLR enabled.
I'm running it in a virtual machine with Ubuntu 20.04 freshly installed.

Logically the gadget addresses are not going to be modified by ASLR, but when I write the /bin/sh string in a .data zone shouldn't this address be randomized? Doesn't ASLR randomize .data?

Right now I am able to get /bin/sh instance by hardcoding the .data address I want to write to.


问:
i can't get Auth::user(); in laravel
AuthController.php

```<code>public function signinAction(Request $request)
{
    $attempt_data = [
        'username' => $request->username,
        'password' => $request->password
    ];

    $login = Auth::attempt($attempt_data);
    if ($login){
        $admin = Auth::user();
        dd($admin);
        $admin->update(['last_login' => now()]);
        return redirect(route('index'))->with('msg','success login');
    }
}
</code>```

I wanted to get Auth::user(); but $login is true but $admin is null

auth.php

```<code>
'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'session',
        'provider' => 'users',
    ]
],

'providers' => [
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
    'users' => [
        'driver' => 'eloquent',
        'model' => \App\Models\User::class,
    ],
</code>```

I change guards
remove admin and change provider change users to admin
i can get Auth::user();
but i want to log in with the
other than 'web'=>[]

```<code>
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'api' => [
        'driver' => 'session',
        'provider' => 'users',
    ]
],

</code>```

Title: i can't get Auth::user(); in laravel

Body:
AuthController.php

public function signinAction(Request $request)
{
    $attempt_data = [
        'username' => $request->username,
        'password' => $request->password
    ];

    $login = Auth::attempt($attempt_data);
    if ($login){
        $admin = Auth::user();
        dd($admin);
        $admin->update(['last_login' => now()]);
        return redirect(route('index'))->with('msg','success login');
    }
}

I wanted to get Auth::user(); but $login is true but $admin is null

auth.php

'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'session',
        'provider' => 'users',
    ]
],

'providers' => [
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
    'users' => [
        'driver' => 'eloquent',
        'model' => \App\Models\User::class,
    ],

I change guards
remove admin and change provider change users to admin
i can get Auth::user();
but i want to log in with the
other than 'web'=>[]

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'api' => [
        'driver' => 'session',
        'provider' => 'users',
    ]
],


问:
I'm getting an il2cpp error when trying to build Unity
I keep getting this error while getting android build. Why is that?

Exception: System.ComponentModel.Win32Exception (740): The requested operation requires an upgrade.

```<code>Exception: System.ComponentModel.Win32Exception (740): İstenen işlem için yükseltme gerekiyor.
   at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at Unity.IL2CPP.Shell.SetupAndStart(ExecuteContext context, Boolean asyncMode)
   at Unity.IL2CPP.Shell.ExecuteAsync(ExecuteArgs executeArgs, IExecuteController controller, Boolean asyncMode)
   at Unity.IL2CPP.Shell.Execute(ExecuteArgs executeArgs, IExecuteController controller)
   at Unity.IL2CPP.Building.CppProgramBuilder.ProvideObjectFile(IntermediateObjectFileCompilationData data)
   at Unity.IL2CPP.Building.ParallelFor.<>c__DisplayClass1_0`2.<RunWithResult>b__0(Object o)
UnityEditorInternal.Runner.RunProgram (UnityEditor.Utils.Program p, System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditorInternal.Runner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, System.Action`1[T] setupStartInfo) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditorInternal.IL2CPPBuilder.RunIl2CppWithArguments (System.Collections.Generic.List`1[T] arguments, System.Action`1[T] setupStartInfo) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditorInternal.IL2CPPBuilder.ConvertPlayerDlltoCpp (UnityEditor.Il2Cpp.Il2CppBuildPipelineData data) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditorInternal.IL2CPPBuilder.Run () (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditorInternal.IL2CPPUtils.RunIl2Cpp (System.String tempFolder, System.String stagingAreaData, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, System.Action`1[T] modifyOutputBeforeCompile, UnityEditor.RuntimeClassRegistry runtimeClassRegistry) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditor.Android.PostProcessor.Tasks.RunIl2Cpp.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <762caba6f98a4d7e9d56f7b5bd6e35d6>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <762caba6f98a4d7e9d56f7b5bd6e35d6>:0)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (UnityEditor.BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <762caba6f98a4d7e9d56f7b5bd6e35d6>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <762caba6f98a4d7e9d56f7b5bd6e35d6>:0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
</code>```

I've been trying for 2 days, I've been searching, but I couldn't find a solution. Can anyone who knows please help?

Body:
I keep getting this error while getting android build. Why is that?

Exception: System.ComponentModel.Win32Exception (740): The requested operation requires an upgrade.

Exception: System.ComponentModel.Win32Exception (740): İstenen işlem için yükseltme gerekiyor.
   at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at Unity.IL2CPP.Shell.SetupAndStart(ExecuteContext context, Boolean asyncMode)
   at Unity.IL2CPP.Shell.ExecuteAsync(ExecuteArgs executeArgs, IExecuteController controller, Boolean asyncMode)
   at Unity.IL2CPP.Shell.Execute(ExecuteArgs executeArgs, IExecuteController controller)
   at Unity.IL2CPP.Building.CppProgramBuilder.ProvideObjectFile(IntermediateObjectFileCompilationData data)
   at Unity.IL2CPP.Building.ParallelFor.<>c__DisplayClass1_0`2.<RunWithResult>b__0(Object o)
UnityEditorInternal.Runner.RunProgram (UnityEditor.Utils.Program p, System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditorInternal.Runner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, System.Action`1[T] setupStartInfo) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditorInternal.IL2CPPBuilder.RunIl2CppWithArguments (System.Collections.Generic.List`1[T] arguments, System.Action`1[T] setupStartInfo) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditorInternal.IL2CPPBuilder.ConvertPlayerDlltoCpp (UnityEditor.Il2Cpp.Il2CppBuildPipelineData data) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditorInternal.IL2CPPBuilder.Run () (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditorInternal.IL2CPPUtils.RunIl2Cpp (System.String tempFolder, System.String stagingAreaData, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, System.Action`1[T] modifyOutputBeforeCompile, UnityEditor.RuntimeClassRegistry runtimeClassRegistry) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEditor.Android.PostProcessor.Tasks.RunIl2Cpp.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <762caba6f98a4d7e9d56f7b5bd6e35d6>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <762caba6f98a4d7e9d56f7b5bd6e35d6>:0)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (UnityEditor.BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <762caba6f98a4d7e9d56f7b5bd6e35d6>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <762caba6f98a4d7e9d56f7b5bd6e35d6>:0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <68089899e4c84456bfc1de3436accf4a>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

I've been trying for 2 days, I've been searching, but I couldn't find a solution. Can anyone who knows please help?


问:
Using Google Apps Script generate a list within specified parameters and export it in .xlsx format to a Drive folder
I have Google Sheets file, where on sheet "data" I have a dataset which I need to randomize based on the data of the sheet "list".

The sheet "data" contains of 2 columns. The sheet "list" contains a name of the company in the 1st column and the quantity of the transactions made in the 2nd column. Assuming a company from the list has a quantity of transactions of 10, I need to generate an .xlsx file for this company with 10 randon entries from the "data" sheet. The name of the file is the name of the company in the 1st column.

This should iterate over the list of companies and generate separate file for each company within the same dataset to randomize.

I've came up with a manual formula to do this:
=ARRAY_CONSTRAIN( UNIQUE( SORT( FILTER(data!$A$1:$A, data!$A$1:$A<>""), RANDARRAY( COUNTA(data!$A$1:$A), 1), TRUE)), 10, 1).

But for a list of 100 companies it's annoying to do this manually.

Link to the example file.


问:
Failed to Fetch Error when i try to upload image to aws s3 with axios in React

function to upload image to aws s3 with axios

const myUploader = async (file) =>{

```<code>    const f = file.files[0]

     var body = {
        locae: 'album',
        fileName: file.files[0].name,
        fileType: file.files[0].type

    }

    console.log(body)
</code>```

 code to get signed url

```<code>    const response = await axios({
        method: 'post',
        url: 'http://ec2-15-206-153/admin/signed/url',
        headers:{
            Authorization: `Bearer ${accessToken}`
          },
        data: body
    })
</code>```

 code to upload image with the signed url

```<code>    try{
        const result = await fetch(response.data.url, {
            method: "PUT",
            body: f,
          });

    }
    catch(e){
        console.log("error",e)
    }
</code>```

I try to upload image to aws s3 with axios in react but i get the failed to fetch error.

Body:
function to upload image to aws s3 with axios

const myUploader = async (file) =>{

    const f = file.files[0]

     var body = {
        locae: 'album',
        fileName: file.files[0].name,
        fileType: file.files[0].type

    }

    console.log(body)

 code to get signed url

    const response = await axios({
        method: 'post',
        url: 'http://ec2-15-206-153/admin/signed/url',
        headers:{
            Authorization: `Bearer ${accessToken}`
          },
        data: body
    })

 code to upload image with the signed url

    try{
        const result = await fetch(response.data.url, {
            method: "PUT",
            body: f,
          });

    }
    catch(e){
        console.log("error",e)
    }

I try to upload image to aws s3 with axios in react but i get the failed to fetch error.


问:
Shaka Player not playing video in Tizen
The Shaka player is showing, but it is not playing. It works fine in VS CODE and even in Tizen Studio with the watch. I have tried the following troubleshooting steps: cleaning the project, updating and installing all required modules from the package manager, using console.log (which did not work), reconfiguring the emulator, and giving internet permission in the config file.

Shaka player working on tizen tv

Title: Shaka Player not playing video in Tizen


问:
How to update the column in Sequelize Postgres DB for particular id with changing existing one using NodeJS
is there any possible way to update the data in a column for a particular id without changing the existing data, if it is possible to save it in DB, how to retrieve the data separately?

here I have used the concat method to save the data in a single column, is it the right way?

```<code>await stagesData.update(
      {
        stages_name: Sequelize.fn(
          "CONCAT",
          Sequelize.col("stages_name"),
          stages_name,
          ","
        ),
        stages_code: Sequelize.fn(
          "CONCAT",
          Sequelize.col("stages_code"),
          stages_code,
          ","
        ),
      },
      { where: { id: id } }
    );

</code>```

if it is the right way how to retrieve the data separately? [by using an array or any other methods]

Body:
is there any possible way to update the data in a column for a particular id without changing the existing data, if it is possible to save it in DB, how to retrieve the data separately?

here I have used the concat method to save the data in a single column, is it the right way?

await stagesData.update(
      {
        stages_name: Sequelize.fn(
          "CONCAT",
          Sequelize.col("stages_name"),
          stages_name,
          ","
        ),
        stages_code: Sequelize.fn(
          "CONCAT",
          Sequelize.col("stages_code"),
          stages_code,
          ","
        ),
      },
      { where: { id: id } }
    );

if it is the right way how to retrieve the data separately? [by using an array or any other methods]


问:
Owl carousel does not work with Alpine.js
Owl carousel does not work with Alpine.js in my project and I couldn't find any hook to initialize my carousel.

I'm trying to integrate owl.carousel.js in Alpine.js based project but, unfortunately, when I initialize the carousel, alpine code breaks and cannot find the referenced properties. Below is a snapshot of my code and the output error:

and this is the output error in the console

Anyone has a fix to this problem please I beg your help. T


问:
Implementation cuckoo search algorithm (TSPLIB, python
I am implementing an improved cuckoo search algorithm for research (link below). This algorithm should work very very well, however my implementation is approximately 1.5 times of the optimal on the test TSPLIB 'eil51.txt' while it should be close or optimal. If any of you guys has some feedback or improvements i would love to hear them.

```<code>import math
from random import randint
from random import uniform
import numpy as np
import pandas as pd

def levyFlight(u):
    return u/math.pow(1-u, 1.6)

def randF():
    return uniform(0.0001, 0.9999)

def calculateDistance(route, distanceMatrix):
    distance = 0
    for i in range(len(route)-1):
        j = i + 1
        distance += inputMatrix[route[i]][route[j]]
    distance+=inputMatrix[route[j]][route[1]]
    return distance

def swap(sequence, i, j):
    temp = sequence[i]
    sequence[i] = sequence[j]
    sequence[j] = temp
    return sequence

#returns the best direction of a given path
def bestDirection(path, distanceMatrix):
    temp = path.copy()
    temp.reverse()
    if(calculateDistance(path,distanceMatrix)>calculateDistance(temp,distanceMatrix)):
        return temp
    else:
        return path

#single two opt move
def simpleMove(nest, distanceMatrix):
    nest = nest[0][:]
    n = len(distanceMatrix)
    a, b = randint(0, n - 1), randint(0, n - 1)
    while a == b:
        a, b = randint(0, n - 1), randint(0, n - 1)
    temp = swap(nest, a, b)
    temp = bestDirection(temp, distanceMatrix)

    if calculateDistance(nest, distanceMatrix) > calculateDistance(temp, distanceMatrix):
        return (temp, calculateDistance(temp, distanceMatrix))
    else:
        return (nest, calculateDistance(nest, distanceMatrix))

#double bridge move
def doubleMove(nest, distanceMatrix):
    nest = nest[0][:]
    n = len(distanceMatrix)
    a, b, c, d = randint(0, n - 1), randint(0, n - 1), randint(0, n - 1), randint(0, n - 1)
    while (a == b) or (a == c) or (a == d) or (b == c) or b == d or (c == d):
        a, b, c, d = randint(0, n - 1), randint(0, n - 1), randint(0, n - 1), randint(0, n - 1)
    route = swap(nest, a, b)
    route = swap(route, c, d)
    route=bestDirection(route, distanceMatrix)
    if calculateDistance(nest, distanceMatrix) > calculateDistance(route, distanceMatrix):
        return (route, calculateDistance(route, distanceMatrix))
    else:
        return (nest, calculateDistance(nest, distanceMatrix))

#main
def cuckoo_search(distanceMatrix):
    numNests = 20
    pa = int(0.2 * numNests)
    pc = int(0.6 * numNests)

    maxGen = 750
    n = len(distanceMatrix)

    nests = []
    initPath = list(range(0, len(distanceMatrix)))
    print('distance initpath', calculateDistance(initPath, distanceMatrix))
    index = 0
    for i in range(numNests):
        if i != 0:
            if index == n - 1:
                index = 0
            initPath = swap(initPath, index, index + 1)
        index += 1
        nests.append((initPath[:], calculateDistance(initPath, distanceMatrix)))
    print(nests[0])
    nests.sort(key=lambda tup: tup[1])
    for t in range(maxGen):
        for k in range(numNests):
            levyRange = 0.2
            levy = levyFlight(randF())
            if ( levy <= levyRange):
                cuckooNest = doubleMove(nests[k], distanceMatrix)
            elif (levy <=levyRange*2):
                cuckooNest = doubleMove(nests[k], distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
            elif (levy <=levyRange*3):
                cuckooNest = doubleMove(nests[k], distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
            elif (levy <=levyRange*4):
                cuckooNest = doubleMove(nests[k], distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
            else:
                cuckooNest = simpleMove(nests[k], distanceMatrix)

            randomNestIndex = randint(0, numNests - 1)
            if (nests[randomNestIndex][1] > cuckooNest[1]):
                nests[randomNestIndex] = cuckooNest
            for i in range(numNests - pa, numNests):
                nests[i] = simpleMove(nests[i], distanceMatrix)
            nests.sort(key=lambda tup: tup[1])
    return nests[0][0], nests[0][1]

#only for eil51
def create_disMatrix(data):
    matrix = np.zeros((len(data), len(data)))
    for i in range(len(data)):
        a = data[i]
        for j in range(len(data)):
            b = data[j]
            dist = np.linalg.norm(a-b)
            matrix[i][j] = dist
    return matrix

if __name__ == '__main__':
    data = pd.read_csv('C:/.../eil51.txt', sep=" ", header=None)
    data = data.drop(0, axis=1)
    data = data.to_numpy()
    inputMatrix = create_disMatrix(data)
    distanceMatrix = inputMatrix.copy()

    route, distance = cuckoo_search(distanceMatrix)
    distance = calculateDistance(route, inputMatrix)
    print(route, distance)
</code>```

Paper Improved Cuckoo Search: https://link.springer.com/article/10.1007/s11042-022-12409-x

Body:
I am implementing an improved cuckoo search algorithm for research (link below). This algorithm should work very very well, however my implementation is approximately 1.5 times of the optimal on the test TSPLIB 'eil51.txt' while it should be close or optimal. If any of you guys has some feedback or improvements i would love to hear them.

import math
from random import randint
from random import uniform
import numpy as np
import pandas as pd

def levyFlight(u):
    return u/math.pow(1-u, 1.6)

def randF():
    return uniform(0.0001, 0.9999)

def calculateDistance(route, distanceMatrix):
    distance = 0
    for i in range(len(route)-1):
        j = i + 1
        distance += inputMatrix[route[i]][route[j]]
    distance+=inputMatrix[route[j]][route[1]]
    return distance

def swap(sequence, i, j):
    temp = sequence[i]
    sequence[i] = sequence[j]
    sequence[j] = temp
    return sequence

#returns the best direction of a given path
def bestDirection(path, distanceMatrix):
    temp = path.copy()
    temp.reverse()
    if(calculateDistance(path,distanceMatrix)>calculateDistance(temp,distanceMatrix)):
        return temp
    else:
        return path

#single two opt move
def simpleMove(nest, distanceMatrix):
    nest = nest[0][:]
    n = len(distanceMatrix)
    a, b = randint(0, n - 1), randint(0, n - 1)
    while a == b:
        a, b = randint(0, n - 1), randint(0, n - 1)
    temp = swap(nest, a, b)
    temp = bestDirection(temp, distanceMatrix)

    if calculateDistance(nest, distanceMatrix) > calculateDistance(temp, distanceMatrix):
        return (temp, calculateDistance(temp, distanceMatrix))
    else:
        return (nest, calculateDistance(nest, distanceMatrix))

#double bridge move
def doubleMove(nest, distanceMatrix):
    nest = nest[0][:]
    n = len(distanceMatrix)
    a, b, c, d = randint(0, n - 1), randint(0, n - 1), randint(0, n - 1), randint(0, n - 1)
    while (a == b) or (a == c) or (a == d) or (b == c) or b == d or (c == d):
        a, b, c, d = randint(0, n - 1), randint(0, n - 1), randint(0, n - 1), randint(0, n - 1)
    route = swap(nest, a, b)
    route = swap(route, c, d)
    route=bestDirection(route, distanceMatrix)
    if calculateDistance(nest, distanceMatrix) > calculateDistance(route, distanceMatrix):
        return (route, calculateDistance(route, distanceMatrix))
    else:
        return (nest, calculateDistance(nest, distanceMatrix))

#main
def cuckoo_search(distanceMatrix):
    numNests = 20
    pa = int(0.2 * numNests)
    pc = int(0.6 * numNests)

    maxGen = 750
    n = len(distanceMatrix)

    nests = []
    initPath = list(range(0, len(distanceMatrix)))
    print('distance initpath', calculateDistance(initPath, distanceMatrix))
    index = 0
    for i in range(numNests):
        if i != 0:
            if index == n - 1:
                index = 0
            initPath = swap(initPath, index, index + 1)
        index += 1
        nests.append((initPath[:], calculateDistance(initPath, distanceMatrix)))
    print(nests[0])
    nests.sort(key=lambda tup: tup[1])
    for t in range(maxGen):
        for k in range(numNests):
            levyRange = 0.2
            levy = levyFlight(randF())
            if ( levy <= levyRange):
                cuckooNest = doubleMove(nests[k], distanceMatrix)
            elif (levy <=levyRange*2):
                cuckooNest = doubleMove(nests[k], distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
            elif (levy <=levyRange*3):
                cuckooNest = doubleMove(nests[k], distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
            elif (levy <=levyRange*4):
                cuckooNest = doubleMove(nests[k], distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
                cuckooNest = doubleMove(cuckooNest, distanceMatrix)
            else:
                cuckooNest = simpleMove(nests[k], distanceMatrix)

            randomNestIndex = randint(0, numNests - 1)
            if (nests[randomNestIndex][1] > cuckooNest[1]):
                nests[randomNestIndex] = cuckooNest
            for i in range(numNests - pa, numNests):
                nests[i] = simpleMove(nests[i], distanceMatrix)
            nests.sort(key=lambda tup: tup[1])
    return nests[0][0], nests[0][1]

#only for eil51
def create_disMatrix(data):
    matrix = np.zeros((len(data), len(data)))
    for i in range(len(data)):
        a = data[i]
        for j in range(len(data)):
            b = data[j]
            dist = np.linalg.norm(a-b)
            matrix[i][j] = dist
    return matrix

if __name__ == '__main__':
    data = pd.read_csv('C:/.../eil51.txt', sep=" ", header=None)
    data = data.drop(0, axis=1)
    data = data.to_numpy()
    inputMatrix = create_disMatrix(data)
    distanceMatrix = inputMatrix.copy()

    route, distance = cuckoo_search(distanceMatrix)
    distance = calculateDistance(route, inputMatrix)
    print(route, distance)

Paper Improved Cuckoo Search: https://link.springer.com/article/10.1007/s11042-022-12409-x


问:
NSwag MSBuild Specification Generation in .Net Framework 4.8
I have a project built in .Net Framework 4.8, i have implemented NSwag, decorated postprocess with basic stuff, such as title, version, description, added few extensions, and made it serve openapi-v3 version(since it serves swagger 2.0  by default in .net 4.8). this is all great. but the problem arises when i want to produce open-api sppecification on build time with Nswag.MSBuild since it does not look at post-process at all.

Is there anyway to decorate openapi specification produced by NSwag.MSbuild?

I assume it could be done if I could reference DocumentProcessor into nswag.json, the documentation says that NSwag studio can generate "nswag.json" but I have not found a way.

Any help would be appreciated.


问:
Photo depth map information for iPhone or iPad with single camera or no TrueDepth camera
On iPhone or iPad devices with a back-facing dual camera or a front-facing TrueDepth camera, the capture system can record depth map information when taking photos:

https://developer.apple.com/documentation/avfoundation/additional_data_capture/capturing_photos_with_depth

However, for iPhone or iPad devices with a single camera or no front-facing TrueDepth camera, how can I obtain depth map information when taking photos?

I recall on those devices, iOS and iPadOS will use software to interpret the scene and create an estimate of the depth map information, but how do I access that depth map information?


问:
Cannot use imported Certificate in AWS Custom Domain
For my API Gateway I want to use a custom (sub) domain. I'm not using AWS as Domain Provider, but a different One. Therefore my plan was to:

Create a CNAM entry on my provider for subdomain.domain.com pointing to my API Gateway Invoke Url

Either create a subdomain certificate or use the existing wildcard and import them on AWS

Create a custom domain name for the API Gateway and use the certificate

Points 1 and 2 work so far. I have managed to import both the wildcard and the certificate containing the specific subdomain. Therefore I've specified the minimum requirements (private key, pem formatted public key) in the import settings.

Unfortunately, I cannot use one of those certificates. In the Domain name field I've specified the exact string as the Certificate is issued to (common name / fqdn).

If I create a new acm cert containing the same string it works but unfortunately my other provider cannot import any custom certificate so I have to go the other way.

Am i doing anything wrong or does this simply not work the way I think?


问:
How can I solve the "HTTPS not evaluated" problem in Google Search Console?
I noticed the following issue in Google Search Console, for the site I manage: "HTTPS not evaluated"
Using the "URL inspector" tool, also from Google Search Console, these links appear as: "Page is served over HTTPS"
No other Https errors appear in the report.
I noticed that the number of links increased from 1 to 6 on 18 Dec 2022, and today 28 Dec 2022 to 8. The site is one with thousands of links.
All 8 links in the report are "https://" links
I would also mention the fact that there is redirection in .htaccess from http to https functional, and the certificate is a valid one.
From what I've read, one of the causes could be receiving a 5xx page as a response (server error) or the bot discovered the link, but didn't have time to evaluate it as https.
Do you have any idea what could be the cause of these problems, how can I detect and fix it?
Thank you!

Using the "URL inspector" tool, also from Google Search Console, these links appear as: "Page is served over HTTPS"
No other Https errors appear in the report.


问:
Parallelising Transformer model inference due to large batch sizes
I have trained a text classification model using the HuggingFace library. The task is to classify bank transaction descriptions into one of 16 categories.

During training, my batch size was 32. However, now at inference time, all transactions for a single bank account must be classified at a time. Some accounts have thousands of transactions, meaning at inference, the model is recieiving batches much larger than it did during training (1000s as opposed to 32). This is making inference much slower than we would like (~15s per 1000 transactions). To make matters worse, right now I cannot deploy the service on a GPU instance due to cost constraints, so the model is only running on CPU(s).

Are there any options for improving inference time? Is it possible to split each bank accounts' transactions into smaller batches and pass each batch to copies of the model in parallel?


问:
Verify Simple-Matrix-Bot-Lib's session
I'm using Simple-Matrix-Bot-Lib to build a Matrix bot. It works but if I login to my bot's account via element, element says that the device/session "Bot Client using Simple-Matrix-Bot-Lib" is unverified.

So I clicked on "Verify" and then element says "To proceed, please accept the verification request on your other device.". Nothing appears in the terminal. The bot only recognizes, if I cancel the verification.

Does anyone have an idea to verify this session? Or does anyone know, how to set the recovery key in Simple-Matrix-Bot-Lib to verify by rec. key?

Title: Verify Simple-Matrix-Bot-Lib's session


问:
Authentication via WebView in Security and trust in Pre-Launch report on Google Play Console
I'm using LinkedIn login via WebView and it's working fine, in Pre-Launch report on Play Store showing this error. Once I was informed to App Access>Policy then it was resolved but in next release app showing again, Can anyone suggest what I've to do ?

In my build.gradle declare as:-
compileSdkVersion 33
buildToolsVersion "30.0.3"
minSdkVersion 21
targetSdkVersion 33

Image of the Pre-launch report issue:-
Pre-launch report image

Reference link given in the image:-
this Google Help Centre article


问:
C# Excel Interop Object Using Data > From Picture
I am trying to read data from tables from PDF, Excel and Doc files.

When searching for solution I come across "Insert Data From Picture" feature in Excel which can help me achieve what I want.
https://support.microsoft.com/en-us/office/insert-data-from-picture-3c1bb58d-2c59-4bc0-b04a-a671a6868fd7#:~:text=How%20it%20works&text=Click%20Data%20%3E%20From%20Picture%20%3E%20Picture,If%20necessary%2C%20crop%20the%20image

The solution I have in mind now is to convert the PDF, Excel and Doc files into images first.

Then I will insert data into the sheet via "Insert Data From Picture" feature.

Lastly, search the table for the data that I need.

The question now is what method should I call to achieve the "Insert Data From Picture"?


问:
CMake include native library build as external project in Android library
I want to create a simple android library that only contains a shared native library, which is supposed to get loaded via System.loadLibrary at a later step.

However I'm not able to add my external project to the *.aar. For some reasons gradle doesn't even bother to build it. However, when I use cmake directly on the CMakeList, the external project and its resulting library is at least built correctly, but also not included in the cmake export/result.

My snippet looks like this:

```<code>ExternalProject_Add(
  spatialite
  URL https://www.gaia-gis.it/gaia-sins/libspatialite-5.0.1.tar.gz
  CONFIGURE_COMMAND ${CMAKE_COMMAND} -E env ${CMAKE_CURRENT_SOURCE_DIR}/build/spatialite-prefix/src/spatialite/configure
  BUILD_IN_SOURCE 1
  BUILD_BYPRODUCTS ${CMAKE_CURRENT_SOURCE_DIR}/build/spatialite-prefix/src/spatialite/src/.libs/mod_spatialite.so
)

add_library(mod_spatialite SHARED IMPORTED)
add_dependencies(mod_spatialite spatialite)

set_target_properties(mod_spatialite PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/build/spatialite-prefix/src/spatialite/src/.libs/mod_spatialite.so")

</code>```

The external project is built using make, not CMake.

The library of concern (mod_spatialite.so) is existing under the correct path above.

CMake doesnt give me any hints like warnings/information etc.

For testing reasons e.g. adding add_library(x SHARED dummy.c) will result in a new library called "libx.so" which is later on included in the *.aar file, which I'm trying to do with my external project too.

Body:
I want to create a simple android library that only contains a shared native library, which is supposed to get loaded via System.loadLibrary at a later step.

However I'm not able to add my external project to the *.aar. For some reasons gradle doesn't even bother to build it. However, when I use cmake directly on the CMakeList, the external project and its resulting library is at least built correctly, but also not included in the cmake export/result.

My snippet looks like this:

ExternalProject_Add(
  spatialite
  URL https://www.gaia-gis.it/gaia-sins/libspatialite-5.0.1.tar.gz
  CONFIGURE_COMMAND ${CMAKE_COMMAND} -E env ${CMAKE_CURRENT_SOURCE_DIR}/build/spatialite-prefix/src/spatialite/configure
  BUILD_IN_SOURCE 1
  BUILD_BYPRODUCTS ${CMAKE_CURRENT_SOURCE_DIR}/build/spatialite-prefix/src/spatialite/src/.libs/mod_spatialite.so
)

add_library(mod_spatialite SHARED IMPORTED)
add_dependencies(mod_spatialite spatialite)

set_target_properties(mod_spatialite PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/build/spatialite-prefix/src/spatialite/src/.libs/mod_spatialite.so")

The external project is built using make, not CMake.

The library of concern (mod_spatialite.so) is existing under the correct path above.

CMake doesnt give me any hints like warnings/information etc.

For testing reasons e.g. adding add_library(x SHARED dummy.c) will result in a new library called "libx.so" which is later on included in the *.aar file, which I'm trying to do with my external project too.


问:
Wordpress site /private directory functionality
In wordpress there is /private directory that has basic authentication.
I can't find anything about it online except in documentation docs.wpvip.com.
But my site does not use wpvip.
Is it a wordpress plugin thing?
Or perhaps other unique case like created manually by administrator?

Can someone explain the purpose of this directory and point to right plugin if it is ?

Thanks,

I googled, searched wordpress codex for information.


问:
DocFx - Invalid return type
I am working on static site documentation with docfx. I am facing a issue regarding the return type

Method in a controller, In which I have a two produce response type for success and badrequest respectively.
`

///
        /// Endpoint used for weather forecast
        ///
        /// <remarks>
        /// Sample request:
        /// No sample need for this endpoint
        /// </remarks>
        /// <returns>List of 15 days weather forecast</returns>
        /// <response code="200">Request for weather forecast is successfull</response>
        /// <response code="400">If something went wrong</response>
        [HttpGet(Name = "GetWeatherForecast")]
        [ProducesResponseType(typeof(IEnumerable<WeatherForecast>), StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
        public IActionResult Get()
        {
            try
            {
                return Ok(Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = Random.Shared.Next(-20, 55),
                    Summary = Summaries[Random.Shared.Next(Summaries.Length)]
                })
                .ToArray());
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
```

Image shows the return type as IActionResult but I need IEnumerable and string in the return table

Help me to resolve this issue

I tried many things from the google and other website but no luck

Title: DocFx - Invalid return type

Body:
I am working on static site documentation with docfx. I am facing a issue regarding the return type

Method in a controller, In which I have a two produce response type for success and badrequest respectively.
`

///
        /// Endpoint used for weather forecast
        ///
        /// <remarks>
        /// Sample request:
        /// No sample need for this endpoint
        /// </remarks>
        /// <returns>List of 15 days weather forecast</returns>
        /// <response code="200">Request for weather forecast is successfull</response>
        /// <response code="400">If something went wrong</response>
        [HttpGet(Name = "GetWeatherForecast")]
        [ProducesResponseType(typeof(IEnumerable<WeatherForecast>), StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
        public IActionResult Get()
        {
            try
            {
                return Ok(Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = Random.Shared.Next(-20, 55),
                    Summary = Summaries[Random.Shared.Next(Summaries.Length)]
                })
                .ToArray());
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

Image shows the return type as IActionResult but I need IEnumerable and string in the return table

Help me to resolve this issue

I tried many things from the google and other website but no luck


问:
Changing Win32 UI code from GDI/GDI+ to Direct2D
In my Win32/C++ application I have some UI elements that are drawn using GDI+, its using typical commands such as draw an image (from resources), lines, paths, fills etc

I want to change this to use Direct2D to make it a bit snappier and potentially take advantage of effects like blurs/shadows.

I've got most things working using a ID2D1HwndRenderTarget and changed my code to keep things like brushes and pens unless the target needs to be re-created. So far I'm pretty pleased with the results, not only does it seem to perform better but also things like text and rounded rectangles are better quality.

I've got a bit of an issue using a ID2D1Bitmap though. The images I use for buttons are stored in my apps resources as a strip of images, the code indexes into this strip to draw the correct images for the button.

I'm using some MSDN code MSDN to load the resource into a ID2D1Bitmap, I've noticed though that on some of the buttons the neighbouring images seems to spill over. Its almost like the image has been scaled up and then scaled down leaving some artifacts. The loaded ID2D1Bitmap is reporting as the correct size though.

My application is per monitor DPI aware and all the UI code scales correctly, I create my ID2D1HwndRenderTarget using 96 x 96 DPI though as my code is already scaling the geometry of the buttons etc. So if the display is 150% DPI I'm loading images of 48 x 48 (a a strip) and drawing them as 48 x 48.

Secondly I want to draw the bitmap grey scaled when the element is disabled, It seems I can easily draw the image with transparency by changing the opacity but I can't see how to draw it grey scaled. My searching has found there are Direct2D effects but this uses a completely different drawing system (ID2D1DeviceContext) which seems over kill for what I want to do.

Any help appreciated.
Rob

To check the ID2D1Bitmap was the correct size I tried saving it as a PNG but I couldn't figure the code out to do that :(


问:
App Build is not appearing on App Store Connect
My App has been successfully uploaded through Xcode but the Build doesn’t appear in my App Connect Build section as you can see here https://snipboard.io/g64b5q.jpg
And I have waited more than 3 days but it still not appear
Has anyone here faced this kind of problem before? How did you solve?

after I waited more than 3 days I deleted from app connect and I upload it again but I still have the same problem.


问:
nginx: worker process is shutting down

What would be the reason for this nginx process not being killed for many days, I guess this is causing a lot of memory usage.

Note: I am using nginx and nginx tcp load balancing.

Title: nginx: worker process is shutting down


问:
how to highcharts code new for local to set the values for stacked column
how to highcharts code new for local to set the values for stacked columnhow to highcharts code new for local to set the values for stacked column how to highcharts code new for local to set the values for stacked column how to highcharts code new for local to set the values for stacked column how to highcharts code new for local to set the values for stacked column</p>
```<code>public options: any = {
    title: {
        text: 'Sales of petroleum products March, Norway',
        align: 'left'
    },
    xAxis: {
        categories: ['Jet fuel', 'Duty-free diesel', 'Petrol', 'Diesel', 'Gas oil']
    },
    yAxis: {
        title: {
            text: 'Million liter'
        }
    },
    labels: {
        items: [{
            html: 'Total liter',
            style: {
                left: '50px',
                top: '18px',
                color: ( // theme
                    Highcharts.defaultOptions.title.style &&
                    Highcharts.defaultOptions.title.style.color
                ) || 'black'
            }
        }]
    },
    plotOptions: {
      column: {
          stacking: 'percent' // normal or percent
      },
      series: {
        cursor: 'pointer',
        point: {
            events: {
                click: function () {
                    alert('Category: ' + this.category + ', value: ' + this.y);
                }
            }
        }
    }
    },
    series: [{
        type: 'column',
        name: '2020',
        data: [59, 83, 65, 228, 184]
    }, {
        type: 'column',
        name: '2021',
        data: [24, 79, 72, 240, 167]
    }, {
        type: 'column',
        name: '2022',
        data: [58, 88, 75, 250, 176]
    }, {
        type: 'spline',
        name: 'Average',
        data: [47, 83.33, 70.66, 239.33, 175.66],
        marker: {
            lineWidth: 2,
            lineColor: Highcharts.getOptions().colors[3],
            fillColor: 'white'
        }
    }]
  };

  public options1: any = {
    chart: {
        zoomType: 'xy'
    },
    colors: ['#7cb5ec', '#91e8e1', '#90ed7d'],

    title: {
        text: 'Something '
    },
    subtitle: {
        text: 'subsomething'
    },
    xAxis: [{
        categories: ['1/1','2/1','3/1','4/1', '5/1', '6/1','7/1','8/1','9/1','10/1','11/1', '12/1', '13/1', '14/1', '15/1']
                    }],
    yAxis: [{ // Primary yAxis
        labels: {
            format: '{value} %',
            style: {
                color: Highcharts.getOptions().colors[1]
            }
        },
        min: 0,
        max:100,
        title: {
            text: 'Percent',
            style: {
                color: Highcharts.getOptions().colors[1]
            }
        }
    }, { // Secondary yAxis
        title: {
            text: 'sample',
            style: {
                color: Highcharts.getOptions().colors[0]
            }
        },
        min: 0,
        max: 100,
        labels: {
            format: '{value} %',
            style: {
                color: Highcharts.getOptions().colors[0],
                display:'none'
            }
        },
        opposite: true
    }],
    tooltip: {
        shared: false
    },
    legend: {
        layout: 'vertical',
        align: 'center',
        x: -0,
        verticalAlign: 'top',
        y: 400,
        floating: true,
        // backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
    },
    plotOptions: {
        column: {
            stacking: 'percent'
        }
    },
    series: [
        {
        name: 'suff1',
        type: 'column',

        yAxis: 1,
        data: [10, 25, 10,30,80, 20, 25, 10,30,80, 20, 25, 10,30,80],
        tooltip: {
            valueSuffix: ' %'
        }

    },
      {
          name: 'suff2',
        type: 'column',

        yAxis: 1,
       tooltip: {
            valueSuffix: ' %'
        },
        data: [20, 50, 30,30,10, 30, 50, 30,30,10, 30, 50, 30,30,10]
    }, {
        name: 'suff3',
        yAxis: 1,
        type: 'column',
        tooltip: {
            valueSuffix: ' %'
        },
        data: [30,5, 60, 40, 10, 50,25, 60, 40, 10, 50,25, 60, 40, 10]
    },
      {
        name: 'NS',
        type: 'spline',
        data: [45,55,74,85,81, 45,55,74,85,81, 45,55,74,85,81],
        tooltip: {
            valueSuffix: '%'
        }
    }]

 };
</code>```
```<code>Highcharts.chart('container-nps', this.options);
</code>```
```<code>import * as Highcharts from 'highcharts';
</code>```
```<code><div id="container-nps"></div>
</code>```

Body:
how to highcharts code new for local to set the values for stacked columnhow to highcharts code new for local to set the values for stacked column how to highcharts code new for local to set the values for stacked column how to highcharts code new for local to set the values for stacked column how to highcharts code new for local to set the values for stacked column

public options: any = {
    title: {
        text: 'Sales of petroleum products March, Norway',
        align: 'left'
    },
    xAxis: {
        categories: ['Jet fuel', 'Duty-free diesel', 'Petrol', 'Diesel', 'Gas oil']
    },
    yAxis: {
        title: {
            text: 'Million liter'
        }
    },
    labels: {
        items: [{
            html: 'Total liter',
            style: {
                left: '50px',
                top: '18px',
                color: ( // theme
                    Highcharts.defaultOptions.title.style &&
                    Highcharts.defaultOptions.title.style.color
                ) || 'black'
            }
        }]
    },
    plotOptions: {
      column: {
          stacking: 'percent' // normal or percent
      },
      series: {
        cursor: 'pointer',
        point: {
            events: {
                click: function () {
                    alert('Category: ' + this.category + ', value: ' + this.y);
                }
            }
        }
    }
    },
    series: [{
        type: 'column',
        name: '2020',
        data: [59, 83, 65, 228, 184]
    }, {
        type: 'column',
        name: '2021',
        data: [24, 79, 72, 240, 167]
    }, {
        type: 'column',
        name: '2022',
        data: [58, 88, 75, 250, 176]
    }, {
        type: 'spline',
        name: 'Average',
        data: [47, 83.33, 70.66, 239.33, 175.66],
        marker: {
            lineWidth: 2,
            lineColor: Highcharts.getOptions().colors[3],
            fillColor: 'white'
        }
    }]
  };

  public options1: any = {
    chart: {
        zoomType: 'xy'
    },
    colors: ['#7cb5ec', '#91e8e1', '#90ed7d'],

    title: {
        text: 'Something '
    },
    subtitle: {
        text: 'subsomething'
    },
    xAxis: [{
        categories: ['1/1','2/1','3/1','4/1', '5/1', '6/1','7/1','8/1','9/1','10/1','11/1', '12/1', '13/1', '14/1', '15/1']
                    }],
    yAxis: [{ // Primary yAxis
        labels: {
            format: '{value} %',
            style: {
                color: Highcharts.getOptions().colors[1]
            }
        },
        min: 0,
        max:100,
        title: {
            text: 'Percent',
            style: {
                color: Highcharts.getOptions().colors[1]
            }
        }
    }, { // Secondary yAxis
        title: {
            text: 'sample',
            style: {
                color: Highcharts.getOptions().colors[0]
            }
        },
        min: 0,
        max: 100,
        labels: {
            format: '{value} %',
            style: {
                color: Highcharts.getOptions().colors[0],
                display:'none'
            }
        },
        opposite: true
    }],
    tooltip: {
        shared: false
    },
    legend: {
        layout: 'vertical',
        align: 'center',
        x: -0,
        verticalAlign: 'top',
        y: 400,
        floating: true,
        // backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
    },
    plotOptions: {
        column: {
            stacking: 'percent'
        }
    },
    series: [
        {
        name: 'suff1',
        type: 'column',

        yAxis: 1,
        data: [10, 25, 10,30,80, 20, 25, 10,30,80, 20, 25, 10,30,80],
        tooltip: {
            valueSuffix: ' %'
        }

    },
      {
          name: 'suff2',
        type: 'column',

        yAxis: 1,
       tooltip: {
            valueSuffix: ' %'
        },
        data: [20, 50, 30,30,10, 30, 50, 30,30,10, 30, 50, 30,30,10]
    }, {
        name: 'suff3',
        yAxis: 1,
        type: 'column',
        tooltip: {
            valueSuffix: ' %'
        },
        data: [30,5, 60, 40, 10, 50,25, 60, 40, 10, 50,25, 60, 40, 10]
    },
      {
        name: 'NS',
        type: 'spline',
        data: [45,55,74,85,81, 45,55,74,85,81, 45,55,74,85,81],
        tooltip: {
            valueSuffix: '%'
        }
    }]

 };

Highcharts.chart('container-nps', this.options);

import * as Highcharts from 'highcharts';


问:
ERROR Error: NG0901: Cannot find a differ supporting object '[object Object]' of type 'object'; Cannot read properties of undefined (reading 'diff')
While trying to display the data in the table which is from the angular material these two errors mentioned in the heading is showing in the browser console and not in the IDE terminal it runs fine.I dont have an idea what is causing this error to appear on the browser console.Any help would be much appreciated.

Past-training.html

```<code> <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    <ng-container matColumnDef="date">
      <th mat-header-cell *matHeaderCellDef> date </th>
      <td mat-cell *matCellDef="let element"> {{element.date | date}} </td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> name </th>
      <td mat-cell *matCellDef="let element" > {{element.name}} </td>
    </ng-container>

    <ng-container matColumnDef="calories">
      <th mat-header-cell *matHeaderCellDef> calories </th>
      <td mat-cell *matCellDef="let element"> {{element.calories | number}} </td>
    </ng-container>

    <ng-container matColumnDef="duration">
      <th mat-header-cell *matHeaderCellDef>duration</th>
      <td mat-cell *matCellDef="let element"> {{element.duration | number}} </td>
    </ng-container>
    <ng-container matColumnDef="state">
        <th mat-header-cell *matHeaderCellDef>State</th>
        <td mat-cell *matCellDef="let element"> {{element.state }} </td>
      </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row;columns: displayedColumns;"></tr>
    <td mat-footer-cell *matFooterCellDef > </td >

  </table>

</code>```

Past-trianing.ts

```<code>import { Component, OnInit } from '@angular/core';
import { MatTable, MatTableDataSource } from '@angular/material/table';
import { exerciseTypes } from '../data.services';
import { exercise } from '../models/exercise-interface';
@Component({
  selector: 'app-past-training',
  templateUrl: './past-training.component.html',
  styleUrls: ['./past-training.component.css']
})
export class PastTrainingComponent implements OnInit{

  dataSource: string[] =['date','name','calories','duration','state'];
  displayedColumns = new MatTableDataSource<exercise>()

constructor(private dataService:exerciseTypes){}

ngOnInit(): void {
  this.displayedColumns.data=this.dataService.getExerciseForTable()
}
}
</code>```

data.services.ts

```<code>import { Injectable } from "@angular/core";
import { exercise } from "./models/exercise-interface";
import { Subject } from 'rxjs';

@Injectable({
    providedIn:'root'
})
export class exerciseTypes {
    sub:Subject<exercise | null>=new Subject<exercise |null>();
    newSub:any;
   private exerciseList:exercise[]=[
    { id: 'crunches', name: 'Crunches', duration: 30, calories: 8 },
    { id: 'touch-toes', name: 'Touch Toes', duration: 180, calories: 15 },
    { id: 'side-lunges', name: 'Side Lunges', duration: 120, calories: 18 },
    { id: 'burpees', name: 'Burpees', duration: 60, calories: 8 }
    ]
    private exerciseid!: exercise | null;
     exerciseFinalisation: exercise  []=[];

    getExercise(){
       return this.exerciseList.slice()
    }
     retrieveSubject(id:string| null){//checking if the id exist on the db
     this.exerciseid=this.exerciseList.find(exId=>exId.id==id) as exercise
     console.log(id,"id")
    //  if(!this.exerciseid){
    //   console.log("undefined")
    //   return
    //  }
     this.newSub=this.sub.next({ ...this.exerciseid })
      console.log(this.newSub,"newSub")
     }
    userSelectedExercise(){
        return {
            ...this.exerciseid
        }
    }
    completeTraining(){
    this.exerciseFinalisation.push({
        ...this.exerciseid!,
        date:new Date(),
        state:'completed',
    })
        this.exerciseid = null;
        this.sub.next(null);
    }
    cancelledTraining(currentVal:number){
        this.exerciseFinalisation.push({
            ...this.exerciseid!,
            date:new Date(),
            duration:this.exerciseid!.duration * (currentVal / 100),
            calories:this.exerciseid!.calories * (currentVal / 100),
            state:'cancelled'
        })
        this.exerciseid = null
        this.sub.next(null);
    }
  getExerciseForTable(){
  return this.exerciseFinalisation.slice()
  }
}

</code>```

Body:
While trying to display the data in the table which is from the angular material these two errors mentioned in the heading is showing in the browser console and not in the IDE terminal it runs fine.I dont have an idea what is causing this error to appear on the browser console.Any help would be much appreciated.

Past-training.html

    <ng-container matColumnDef="date">
       date
       {{element.date | date}}
    </ng-container>

    <ng-container matColumnDef="name">
       name
       {{element.name}}
    </ng-container>

    <ng-container matColumnDef="calories">
       calories
       {{element.calories | number}}
    </ng-container>

    <ng-container matColumnDef="duration">
      duration
       {{element.duration | number}}
    </ng-container>
    <ng-container matColumnDef="state">
        State
         {{element.state }}
      </ng-container>

Past-trianing.ts

import { Component, OnInit } from '@angular/core';
import { MatTable, MatTableDataSource } from '@angular/material/table';
import { exerciseTypes } from '../data.services';
import { exercise } from '../models/exercise-interface';
@Component({
  selector: 'app-past-training',
  templateUrl: './past-training.component.html',
  styleUrls: ['./past-training.component.css']
})
export class PastTrainingComponent implements OnInit{

  dataSource: string[] =['date','name','calories','duration','state'];
  displayedColumns = new MatTableDataSource<exercise>()

constructor(private dataService:exerciseTypes){}

ngOnInit(): void {
  this.displayedColumns.data=this.dataService.getExerciseForTable()
}
}

data.services.ts

import { Injectable } from "@angular/core";
import { exercise } from "./models/exercise-interface";
import { Subject } from 'rxjs';

@Injectable({
    providedIn:'root'
})
export class exerciseTypes {
    sub:Subject<exercise | null>=new Subject<exercise |null>();
    newSub:any;
   private exerciseList:exercise[]=[
    { id: 'crunches', name: 'Crunches', duration: 30, calories: 8 },
    { id: 'touch-toes', name: 'Touch Toes', duration: 180, calories: 15 },
    { id: 'side-lunges', name: 'Side Lunges', duration: 120, calories: 18 },
    { id: 'burpees', name: 'Burpees', duration: 60, calories: 8 }
    ]
    private exerciseid!: exercise | null;
     exerciseFinalisation: exercise  []=[];

    getExercise(){
       return this.exerciseList.slice()
    }
     retrieveSubject(id:string| null){//checking if the id exist on the db
     this.exerciseid=this.exerciseList.find(exId=>exId.id==id) as exercise
     console.log(id,"id")
    //  if(!this.exerciseid){
    //   console.log("undefined")
    //   return
    //  }
     this.newSub=this.sub.next({ ...this.exerciseid })
      console.log(this.newSub,"newSub")
     }
    userSelectedExercise(){
        return {
            ...this.exerciseid
        }
    }
    completeTraining(){
    this.exerciseFinalisation.push({
        ...this.exerciseid!,
        date:new Date(),
        state:'completed',
    })
        this.exerciseid = null;
        this.sub.next(null);
    }
    cancelledTraining(currentVal:number){
        this.exerciseFinalisation.push({
            ...this.exerciseid!,
            date:new Date(),
            duration:this.exerciseid!.duration * (currentVal / 100),
            calories:this.exerciseid!.calories * (currentVal / 100),
            state:'cancelled'
        })
        this.exerciseid = null
        this.sub.next(null);
    }
  getExerciseForTable(){
  return this.exerciseFinalisation.slice()
  }
}


问:
Strange printing of R code using visual studio code
Using R within VSCode leads to strange printing of the R code. I see strange characters where there should be spaces (I think). For example here is the output of loading the tidyverse library:

```<code>> library("tidyverse")
-- ←[1mAttaching packages←[22m -------------------------------------------------- tidyverse 1.3.2 --
←[32mv←[39m ←[34mggplot2←[39m 3.4.0      ←[32mv←[39m ←[34mpurrr  ←[39m 1.0.0
←[32mv←[39m ←[34mtibble ←[39m 3.1.8      ←[32mv←[39m ←[34mdplyr  ←[39m 1.0.10
←[32mv←[39m ←[34mtidyr  ←[39m 1.2.1      ←[32mv←[39m ←[34mstringr←[39m 1.5.0
←[32mv←[39m ←[34mreadr  ←[39m 2.1.3      ←[32mv←[39m ←[34mforcats←[39m 0.5.2
-- ←[1mConflicts←[22m ----------------------------------------------------- tidyverse_conflicts() --
←[31mx←[39m ←[34mdplyr←[39m::←[32mfilter()←[39m masks ←[34mstats←[39m::filter()
←[31mx←[39m ←[34mdplyr←[39m::←[32mlag()←[39m    masks ←[34mstats←[39m::lag()
</code>```

Here is my user settings json file:

```<code>{
    "r.rterm.windows": "C:\\Program Files\\R\\R-4.2.2\\bin\\R.exe",
    "editor.suggestSelection": "first",
    "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
    "python.jediEnabled": false,
    "window.zoomLevel": 0,
    "python.languageServer": "Microsoft",
    "editor.fontFamily": "Fira Code Retina",
    "editor.fontLigatures": true,
    "editor.minimap.enabled": false,
    "r.bracketedPaste": true,
    "r.lsp.path": "C:\\Program Files\\R\\R-4.2.2\\bin\\R.exe",
    "r.lsp.debug": true,
    "r.lsp.diagnostics": true
}
</code>```

Now here is my sessionInfo()

```<code>> sessionInfo()
R version 4.2.2 (2022-10-31 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows Server 2012 R2 x64 (build 9600)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
  LC_MONETARY=English_United States.1252 LC_NUMERIC=C
LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] forcats_0.5.2   stringr_1.5.0   dplyr_1.0.10    purrr_1.0.0     readr_2.1.3
    tidyr_1.2.1     tibble_3.1.8    ggplot2_3.4.0   tidyverse_1.3.2

loaded via a namespace (and not attached):
 [1] pillar_1.8.1        compiler_4.2.2      cellranger_1.1.0    dbplyr_2.2.1
     tools_4.2.2         timechange_0.1.1    lubridate_1.9.0     jsonlite_1.8.4
     googledrive_2.0.0
[10] lifecycle_1.0.3     gargle_1.2.1        gtable_0.3.1        pkgconfig_2.0.3
     rlang_1.0.6         reprex_2.0.2        DBI_1.1.3           cli_3.5.0
     haven_2.5.1
[19] xml2_1.3.3          withr_2.5.0         httr_1.4.4          generics_0.1.3
     vctrs_0.5.1         fs_1.5.2            hms_1.1.2           googlesheets4_1
.0.1 grid_4.2.2
[28] tidyselect_1.2.0    glue_1.6.2          R6_2.5.1            fansi_1.0.3
     readxl_1.4.1        tzdb_0.3.0          modelr_0.1.10       magrittr_2.0.3
     backports_1.4.1
[37] scales_1.2.1        ellipsis_0.3.2      rvest_1.0.3         assertthat_0.2.
1    colorspace_2.0-3    utf8_1.2.2          stringi_1.7.8       munsell_0.5.0
     broom_1.0.2
[46] crayon_1.5.2
</code>```

Any ideas on how to fix would be appreciated. Thanks.

Body:
Using R within VSCode leads to strange printing of the R code. I see strange characters where there should be spaces (I think). For example here is the output of loading the tidyverse library:

> library("tidyverse")
-- ←[1mAttaching packages←[22m -------------------------------------------------- tidyverse 1.3.2 --
←[32mv←[39m ←[34mggplot2←[39m 3.4.0      ←[32mv←[39m ←[34mpurrr  ←[39m 1.0.0
←[32mv←[39m ←[34mtibble ←[39m 3.1.8      ←[32mv←[39m ←[34mdplyr  ←[39m 1.0.10
←[32mv←[39m ←[34mtidyr  ←[39m 1.2.1      ←[32mv←[39m ←[34mstringr←[39m 1.5.0
←[32mv←[39m ←[34mreadr  ←[39m 2.1.3      ←[32mv←[39m ←[34mforcats←[39m 0.5.2
-- ←[1mConflicts←[22m ----------------------------------------------------- tidyverse_conflicts() --
←[31mx←[39m ←[34mdplyr←[39m::←[32mfilter()←[39m masks ←[34mstats←[39m::filter()
←[31mx←[39m ←[34mdplyr←[39m::←[32mlag()←[39m    masks ←[34mstats←[39m::lag()

Here is my user settings json file:

{
    "r.rterm.windows": "C:\\Program Files\\R\\R-4.2.2\\bin\\R.exe",
    "editor.suggestSelection": "first",
    "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
    "python.jediEnabled": false,
    "window.zoomLevel": 0,
    "python.languageServer": "Microsoft",
    "editor.fontFamily": "Fira Code Retina",
    "editor.fontLigatures": true,
    "editor.minimap.enabled": false,
    "r.bracketedPaste": true,
    "r.lsp.path": "C:\\Program Files\\R\\R-4.2.2\\bin\\R.exe",
    "r.lsp.debug": true,
    "r.lsp.diagnostics": true
}

Now here is my sessionInfo()

> sessionInfo()
R version 4.2.2 (2022-10-31 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows Server 2012 R2 x64 (build 9600)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
  LC_MONETARY=English_United States.1252 LC_NUMERIC=C
LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] forcats_0.5.2   stringr_1.5.0   dplyr_1.0.10    purrr_1.0.0     readr_2.1.3
    tidyr_1.2.1     tibble_3.1.8    ggplot2_3.4.0   tidyverse_1.3.2

loaded via a namespace (and not attached):
 [1] pillar_1.8.1        compiler_4.2.2      cellranger_1.1.0    dbplyr_2.2.1
     tools_4.2.2         timechange_0.1.1    lubridate_1.9.0     jsonlite_1.8.4
     googledrive_2.0.0
[10] lifecycle_1.0.3     gargle_1.2.1        gtable_0.3.1        pkgconfig_2.0.3
     rlang_1.0.6         reprex_2.0.2        DBI_1.1.3           cli_3.5.0
     haven_2.5.1
[19] xml2_1.3.3          withr_2.5.0         httr_1.4.4          generics_0.1.3
     vctrs_0.5.1         fs_1.5.2            hms_1.1.2           googlesheets4_1
.0.1 grid_4.2.2
[28] tidyselect_1.2.0    glue_1.6.2          R6_2.5.1            fansi_1.0.3
     readxl_1.4.1        tzdb_0.3.0          modelr_0.1.10       magrittr_2.0.3
     backports_1.4.1
[37] scales_1.2.1        ellipsis_0.3.2      rvest_1.0.3         assertthat_0.2.
1    colorspace_2.0-3    utf8_1.2.2          stringi_1.7.8       munsell_0.5.0
     broom_1.0.2
[46] crayon_1.5.2

Any ideas on how to fix would be appreciated. Thanks.


问:
Difference in saving nodes in Memgraph
Is there a difference between saving a node, which is an instance of a class that inherits Node class, with save method and saving a node using the query builder in GQLAlchemy?

Also, is there any difference between node.save(db) and db.save_node(node)?

Title: Difference in saving nodes in Memgraph


问:
How can Torch profiler show that an operation is not on the GPU while all of its tensors are on the GPU?
I am using torch NMS as part of Detecron2, though for some reason I see that it runs on the CPU (as can be seen in the attached image of the profiling). Though when I debug it, I see that both the inputs and the outputs of the NMS are on the GPU so it is unclear why in the profiling it looks like it is on the CPU.
I'll appreciate any help in the matter.
Thanks!

Profling

I made sure the tensors are on the GPU but still it looks like it is on the CPU in the profiling.


问:
Problem with plotting regression line from spline in ggplot2
I have a dataset where I have bacterial carriage by age group. I used the bs spline function to model bacterial carriage by age.

```<code>fit2 <- lm(percentage ~ bs(Age_midpoint, knots = c(0.177, 1, 1.460, 2.585, 5, 8.75, 37.45)), data = Complete_data)
fit2
age <-range(Complete_data$Age_midpoint)
Age_grid <- seq(from=min(age), to = max(age))
pred2 <-predict(fit2, newdata = list(Age_midpoint = Age_grid), se = T)
se_bands = with(pred2, cbind("upper" = fit+2*se.fit, "lower" = fit-2*se.fit))
</code>```

I now want to plot the line that describes fit2 in the following plot:

```<code>Fig1 <- ggplot(Complete_data, aes(x= Age_midpoint, y = percentage)) + geom_point(shape=1, aes( size = denominator)) + xlab("Average age") + ylab("Pneumococcal Carriage") + theme_light()
</code>```

I am able to plot the line by itself using this:`

```<code>ggplot() + geom_line(aes(x = Age_midpoint.grid, y=pred2$fit), color = "red") +
  geom_ribbon(aes(x = Age_midpoint.grid, ymin=se_bands[, "lower"], ymax = se_bands[, "upper"]), alpha = 0.3) + xlim(age)
</code>```

But when I try to plot the line in the scatterplot I get a warning

```<code> Fig1 + geom_line(aes(x = Age_midpoint.grid, y=pred2$fit), color = "red") +
 geom_ribbon(aes(x = Age_midpoint.grid, ymin=se_bands[, "lower"], ymax = se_bands[, "upper"]), alpha = 0.3) + xlim(age)

 Error in geom_line(aes(x = Age_midpoint.grid, y = pred2$fit), color = "red") :
ℹ Error occurred in the 2nd layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (403)
✖ Fix the following mappings: `x` and `y`
</code>```

How can I plot the line in my scatterplot?

I looked online for solution, but I only found information about histograms.

Body:
I have a dataset where I have bacterial carriage by age group. I used the bs spline function to model bacterial carriage by age.

fit2 <- lm(percentage ~ bs(Age_midpoint, knots = c(0.177, 1, 1.460, 2.585, 5, 8.75, 37.45)), data = Complete_data)
fit2
age <-range(Complete_data$Age_midpoint)
Age_grid <- seq(from=min(age), to = max(age))
pred2 <-predict(fit2, newdata = list(Age_midpoint = Age_grid), se = T)
se_bands = with(pred2, cbind("upper" = fit+2*se.fit, "lower" = fit-2*se.fit))

I now want to plot the line that describes fit2 in the following plot:

Fig1 <- ggplot(Complete_data, aes(x= Age_midpoint, y = percentage)) + geom_point(shape=1, aes( size = denominator)) + xlab("Average age") + ylab("Pneumococcal Carriage") + theme_light()

I am able to plot the line by itself using this:`

ggplot() + geom_line(aes(x = Age_midpoint.grid, y=pred2$fit), color = "red") +
  geom_ribbon(aes(x = Age_midpoint.grid, ymin=se_bands[, "lower"], ymax = se_bands[, "upper"]), alpha = 0.3) + xlim(age)

But when I try to plot the line in the scatterplot I get a warning

 Fig1 + geom_line(aes(x = Age_midpoint.grid, y=pred2$fit), color = "red") +
 geom_ribbon(aes(x = Age_midpoint.grid, ymin=se_bands[, "lower"], ymax = se_bands[, "upper"]), alpha = 0.3) + xlim(age)

 Error in geom_line(aes(x = Age_midpoint.grid, y = pred2$fit), color = "red") :
ℹ Error occurred in the 2nd layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (403)
✖ Fix the following mappings: `x` and `y`

How can I plot the line in my scatterplot?

I looked online for solution, but I only found information about histograms.


问:
MDM Operational server getting partially stared
I recently installed IBM MDM 11.5, DB2 and IBM WebSphere on my system. For some reason the Asset in MDM-operational-server is stopped and isn't getting started. I'm new to this and don't know what is causing the problem.

Business-level applications

MDM-operational-server-EBA-E001

If anything is required from my side then please let me know.

I tried restarting the server multiple times, tried running 'Madconfig redeploy_EBA' and even reinstalled the whole thing again but still after completion it's in the same state. If tried to execute any OOTB transactions, it's throwing the following error:

Error: Service bean could not be looked up on server iiop://localhost:2809 and provider url com/dwl/base/requestHandler/beans/DWLServiceController
com.ibm.mdm.tools.metadata.common.exceptions.MetadataException: javax.naming.NameNotFoundException: Context: INLEN8520069636Node01Cell/nodes/INLEN8520069636Node01/servers/server1, name: com/dwl/base/requestHandler/beans/DWLServiceController: First component in name requestHandler/beans/DWLServiceController not found. [Root exception is org.omg.CosNaming.NamingContextPackage.NotFound: IDL:omg.org/CosNaming/NamingContext/NotFound:1.0]


问:
How can I trace back "EPROTONOSUPPORT: protocol not supported :::3000" in node.js?
I am more than clueless at the moment. I am trying to start a keystonejs-6 app in production mode and the the app throws this error:

```<code>Starting Keystone
node:events:505
      throw er; // Unhandled 'error' event
      ^

Error: listen EPROTONOSUPPORT: protocol not supported :::3000
    at Server.setupListenHandle [as _listen2] (node:net:1355:21)
    at listenInCluster (node:net:1420:12)
    at doListen (node:net:1559:7)
    at processTicksAndRejections (node:internal/process/task_queues:84:21)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1399:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EPROTONOSUPPORT',
  errno: -43,
  syscall: 'listen',
  address: '::',
  port: 3000
}
</code>```

I have no way to trace back, at which point of the keystonejs application code the error originated. As it seems, keystonejs provides practically no logging on the application code itself.

Is there a way to find out, what kind of protocol is meant by this error message?

Body:
I am more than clueless at the moment. I am trying to start a keystonejs-6 app in production mode and the the app throws this error:

Starting Keystone
node:events:505
      throw er; // Unhandled 'error' event
      ^

Error: listen EPROTONOSUPPORT: protocol not supported :::3000
    at Server.setupListenHandle [as _listen2] (node:net:1355:21)
    at listenInCluster (node:net:1420:12)
    at doListen (node:net:1559:7)
    at processTicksAndRejections (node:internal/process/task_queues:84:21)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1399:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EPROTONOSUPPORT',
  errno: -43,
  syscall: 'listen',
  address: '::',
  port: 3000
}

I have no way to trace back, at which point of the keystonejs application code the error originated. As it seems, keystonejs provides practically no logging on the application code itself.

Is there a way to find out, what kind of protocol is meant by this error message?


问:
Display WP plugins in choosen place
I have done a tutorial about writing WordPress plugins but this tutorial was bad. The teacher said about creating widgets and shortcodes (adding an option to that) but a lot of plugins can display it's options in other places. For example - the Yoast plugin can display it's an option on the page to create a new page. I don't know even how to find information about that. Could you give me a link or said me how can I find that?</p>

Title: Display WP plugins in choosen place


问:
Django form with Jstree checkbox ( Jquery Array)
I try to use Jstree checkbox in a Django form, but Jquery array is stopped by form is_valid() method :
La valeur « 584a6392-8958-40c8-b318-77c1d2df623d,a9f2deec-eda2-4c43-a080-cd070e9ff25f » n’est pas un UUID valide.
This code run if i choose only a checkbox

HTML

```<code> <input type="hidden" name="regroupements" id="regroupements" value="">

 <div id="kt_docs_jstree_basic">
    <ul>
             <li value="584a6392-8958-40c8-b318-77c1d2df623d"> Groupe 1 </li>
             <li value="a9f2deec-eda2-4c43-a080-cd070e9ff25f"> Groupe 2 </li>
    </ul>
 </div>
</code>```

JS

```<code>$(function () {
    $('#kt_docs_jstree_basic').jstree();
    $("#kt_docs_jstree_basic").on("select_node.jstree", function(e){
              var selected_regroupements = [];
              var selectedIndexes = $("#kt_docs_jstree_basic").jstree("get_selected", true);
              $.each(selectedIndexes,function () {
                  selected_regroupements.push(this['li_attr'].value);
              });
              $("#regroupements").val(selected_regroupements)
          }
      );
    });
</code>```

ViEWS.PY

```<code> def post(self, request,  **kwargs):
        context = super().get_context_data(**kwargs)
        context = KTLayout.init(context)
        form = forms.UtilisateursAddUpdate(request.POST, request.FILES)

        choices = request.POST.getlist("regroupements")

        if form.is_valid():

            instance = form.save(commit=False)

            ...

            instance.save()

            for item in choices:
                instance.regroupements.add(item)
</code>```

I don't understand why this code run with one checkbox "checked" but not with more.
How should i change my code ?

Body:
I try to use Jstree checkbox in a Django form, but Jquery array is stopped by form is_valid() method :
La valeur « 584a6392-8958-40c8-b318-77c1d2df623d,a9f2deec-eda2-4c43-a080-cd070e9ff25f » n’est pas un UUID valide.
This code run if i choose only a checkbox

HTML

 <input type="hidden" name="regroupements" id="regroupements" value="">

 Groupe 1

 Groupe 2

JS

$(function () {
    $('#kt_docs_jstree_basic').jstree();
    $("#kt_docs_jstree_basic").on("select_node.jstree", function(e){
              var selected_regroupements = [];
              var selectedIndexes = $("#kt_docs_jstree_basic").jstree("get_selected", true);
              $.each(selectedIndexes,function () {
                  selected_regroupements.push(this['li_attr'].value);
              });
              $("#regroupements").val(selected_regroupements)
          }
      );
    });

ViEWS.PY

 def post(self, request,  **kwargs):
        context = super().get_context_data(**kwargs)
        context = KTLayout.init(context)
        form = forms.UtilisateursAddUpdate(request.POST, request.FILES)

        choices = request.POST.getlist("regroupements")

        if form.is_valid():

            instance = form.save(commit=False)

            ...

            instance.save()

            for item in choices:
                instance.regroupements.add(item)

I don't understand why this code run with one checkbox "checked" but not with more.
How should i change my code ?


问:
Does Google-MLKit face detection use a MTCNN model?
Does Google-MLKit face detection use MTCNN, I'm using a FaceNet model that was trained on images from an MTCNN model, however google MLKit face detection seems to work well for aligning the face, I'm wondering if this would be a clean substitute.</p>


问:
Cannot run Python3.6 in debugging mode in Visual Studio
I am trying to run my Python program in debugging mode under Python3.6 environment in VS, yet everytime I endup with the error below:

enter image description here

Which also generates the following message in the Output window:

The program 'python.exe' has exited with code 4294967295 (0xffffffff).

I have tried almost everything, from reinstalling VS and Python3.6 together, adding Python3.6 environemnt manually from VS, checking the contents of the registry files in regedit. None of them worked!

The issue does not occurr for other versions of Python. I was able to successfully install and run in Debug mode Pythons 3.9 and 3.11.1.

Does anyone have any idea what could have caused the problem?

Thanks!

I have tried almost everything, from reinstalling VS and Python3.6 together, adding Python3.6 environemnt manually from VS, checking the contents of the registry files in regedit. None of them worked!


问:
Multivariate LSTM for Timeseries Forecatsing
I am working on a project that involves multivariate forecasting of weather. I have utilized Jason Brownlee's Blog for this purpose. But in a series to supervised conversion, I am unable to crack the working of this function. Moreover, Jason's other Blog which is about how to convert time series to supervised learning as:

```<code>from pandas import DataFrame
from pandas import concat

def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
    n_vars = 1 if type(data) is list else data.shape[1]
    df = DataFrame(data)
    cols, names = list(), list()
    # input sequence (t-n, ... t-1)
    for i in range(n_in, 0, -1):
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
    # forecast sequence (t, t+1, ... t+n)
    for i in range(0, n_out):
        cols.append(df.shift(-i))
        if i == 0:
            names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
        else:
            names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
    # put it all together
    agg = concat(cols, axis=1)
    agg.columns = names
    # drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    return agg

raw = DataFrame()
raw['ob1'] = [x for x in range(10)]
raw['ob2'] = [x for x in range(50, 60)]
values = raw.values
data = series_to_supervised(values)
print(data)`
</code>```

As mentioned I have a time series weather data which involves, Temperature, Wind speed, Humidity, and GHI and I have to forecast all of them one by one by taking all of the mentioned parameters. The problem is occurring in last lines

```<code>raw = DataFrame()
    raw['ob1'] = [x for x in range(10)]
    raw['ob2'] = [x for x in range(50, 60)]
    values = raw.values
    data = series_to_supervised(values)
    print(data)
</code>```

How to frame these lines for the mentioned problem?

Body:
I am working on a project that involves multivariate forecasting of weather. I have utilized Jason Brownlee's Blog for this purpose. But in a series to supervised conversion, I am unable to crack the working of this function. Moreover, Jason's other Blog which is about how to convert time series to supervised learning as:

from pandas import DataFrame
from pandas import concat

def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
    n_vars = 1 if type(data) is list else data.shape[1]
    df = DataFrame(data)
    cols, names = list(), list()
    # input sequence (t-n, ... t-1)
    for i in range(n_in, 0, -1):
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
    # forecast sequence (t, t+1, ... t+n)
    for i in range(0, n_out):
        cols.append(df.shift(-i))
        if i == 0:
            names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
        else:
            names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
    # put it all together
    agg = concat(cols, axis=1)
    agg.columns = names
    # drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    return agg

raw = DataFrame()
raw['ob1'] = [x for x in range(10)]
raw['ob2'] = [x for x in range(50, 60)]
values = raw.values
data = series_to_supervised(values)
print(data)`

As mentioned I have a time series weather data which involves, Temperature, Wind speed, Humidity, and GHI and I have to forecast all of them one by one by taking all of the mentioned parameters. The problem is occurring in last lines

raw = DataFrame()
    raw['ob1'] = [x for x in range(10)]
    raw['ob2'] = [x for x in range(50, 60)]
    values = raw.values
    data = series_to_supervised(values)
    print(data)

How to frame these lines for the mentioned problem?


问:
result.current.data is undefined when I declare renderHook into the test closure but works when it is defined outside of it
I'm trying to test a custom hook but for some reason I can't render the hook inside the test closure "it".

This code works (I must use the rerender methods otherwise the result.current.data remains undefined) :

describe('useGet hook', () => {

  const { result, rerender, unmount } = renderHook(
    () => useGet<IApplication>(getApplication),
    {
      wrapper: ({ children }) => (
        <AuthProvider {...oidcConfig}>{children}</AuthProvider>
      ),
    }
  );

  it('should make a GET request and return the data', async () => {
    rerender()
    console.log(result)

  });

```
<p>This code does not work :</p>
<pre class="lang-js prettyprint-override"><code>  it('should make a GET request and return the data', async () => {

    const { result, rerender, unmount } = renderHook(
      () => useGet<IApplication>(getApplication),
      {
        wrapper: ({ children }) => (
          <AuthProvider {...oidcConfig}>{children}</AuthProvider>
        ),
      }
    );
    rerender()
    console.log(result)
  });
</code>```

In both cases I can see that the loader state has changed (false to true) but the data remains undefined

```<code>   {
      current: {
        data: undefined,
        error: null,
        isLoading: true,
        refetch: [Function: executeCallback]
      }
    }
</code>```

Here is my customhook :

 const useGet = <T,>(
  callbackFn: () => Promise<T | null>,
  onPersist?: (data: T | null) => void,
  onError?: (error: ConnectError | null) => void
): useGetResponseType<T> => {
  const [data, setData] = useState<T | null>();
  const [error, setError] = useState<ConnectError | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const { userData } = useAuth();

  const executeCallback = () => {
    if (!callbackFn) {
      return Promise.resolve(null);
    }

    setIsLoading(true);

    return callbackFn()
      .then((dataResponse: T | null) => {
        setData(dataResponse);

        if (onPersist) {
          onPersist(dataResponse);
        }

        return dataResponse;
      })
      .catch((errorResponse: AxiosError<ConnectError>) => {
        setError(errorResponse?.response?.data || null);

        if (onError) {
          onError(errorResponse?.response?.data || null);
        }

        return null;
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  useEffect(() => {
    if (isLoading || !userData) {
      return;
    }

    executeCallback();
  }, [userData]);

  return {
    data,
    error,
    isLoading,
    refetch: executeCallback,
  };
};
```

Body:
I'm trying to test a custom hook but for some reason I can't render the hook inside the test closure "it".

This code works (I must use the rerender methods otherwise the result.current.data remains undefined) :

describe('useGet hook', () => {

  const { result, rerender, unmount } = renderHook(
    () => useGet<IApplication>(getApplication),
    {
      wrapper: ({ children }) => (
        <AuthProvider {...oidcConfig}>{children}</AuthProvider>
      ),
    }
  );

  it('should make a GET request and return the data', async () => {
    rerender()
    console.log(result)

  });

This code does not work :

  it('should make a GET request and return the data', async () => {

    const { result, rerender, unmount } = renderHook(
      () => useGet<IApplication>(getApplication),
      {
        wrapper: ({ children }) => (
          <AuthProvider {...oidcConfig}>{children}</AuthProvider>
        ),
      }
    );
    rerender()
    console.log(result)
  });

In both cases I can see that the loader state has changed (false to true) but the data remains undefined

   {
      current: {
        data: undefined,
        error: null,
        isLoading: true,
        refetch: [Function: executeCallback]
      }
    }

Here is my customhook :

 const useGet = <T,>(
  callbackFn: () => Promise<T | null>,
  onPersist?: (data: T | null) => void,
  onError?: (error: ConnectError | null) => void
): useGetResponseType<T> => {
  const [data, setData] = useState<T | null>();
  const [error, setError] = useState<ConnectError | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const { userData } = useAuth();

  const executeCallback = () => {
    if (!callbackFn) {
      return Promise.resolve(null);
    }

    setIsLoading(true);

    return callbackFn()
      .then((dataResponse: T | null) => {
        setData(dataResponse);

        if (onPersist) {
          onPersist(dataResponse);
        }

        return dataResponse;
      })
      .catch((errorResponse: AxiosError<ConnectError>) => {
        setError(errorResponse?.response?.data || null);

        if (onError) {
          onError(errorResponse?.response?.data || null);
        }

        return null;
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  useEffect(() => {
    if (isLoading || !userData) {
      return;
    }

    executeCallback();
  }, [userData]);

  return {
    data,
    error,
    isLoading,
    refetch: executeCallback,
  };
};