问:
Blueprint with step_naomit in R
I want to run the following recipe in Caret:

```<code>data_recipe_naomit <- recipe(MSRP ~ ., data = data_train) %>%
  step_naomit(all_predictors()) %>%
  step_BoxCox(matches("MSRP|highway.MPG|city.mpg|Popularity|Engine.HP")) %>%
  step_other(Make, threshold = 0.01,
             other = "Other") %>%
  step_other(Engine.Fuel.Type, threshold = 0.01,
             other = "Other") %>%
  step_other(Market.Category, threshold = 0.005,
             other = "Other") %>%
  step_other(Vehicle.Style, threshold = 0.02,
             other = "Other") %>%
  step_center(all_numeric(), -all_outcomes()) %>%
  step_scale(all_numeric(), -all_outcomes()) %>%
  step_dummy(all_nominal(), one_hot = FALSE)

prepare_na_omit <- prep(data_recipe_naomit, training = data_train)

baked_train_naomit <- bake(prepare_na_omit, new_data = data_train)
baked_test_naomit <- bake(prepare_na_omit, new_data = data_test)
</code>```

But when I bake it, I get the following error:

Error in if (any(x <= 0)) { : missing value where TRUE/FALSE needed

Does someone know how to fix this?

I tried with:
step_naomit(is.na(all_predictors()))

But that gives the following error, when prepping:

Error in as_indices_impl():
! Must subset columns with a valid subscript vector.
✖ Subscript has the wrong type logical.
ℹ It must be numeric or character.

Title: Blueprint with step_naomit in R

Body:
I want to run the following recipe in Caret:

data_recipe_naomit <- recipe(MSRP ~ ., data = data_train) %>%
  step_naomit(all_predictors()) %>%
  step_BoxCox(matches("MSRP|highway.MPG|city.mpg|Popularity|Engine.HP")) %>%
  step_other(Make, threshold = 0.01,
             other = "Other") %>%
  step_other(Engine.Fuel.Type, threshold = 0.01,
             other = "Other") %>%
  step_other(Market.Category, threshold = 0.005,
             other = "Other") %>%
  step_other(Vehicle.Style, threshold = 0.02,
             other = "Other") %>%
  step_center(all_numeric(), -all_outcomes()) %>%
  step_scale(all_numeric(), -all_outcomes()) %>%
  step_dummy(all_nominal(), one_hot = FALSE)

prepare_na_omit <- prep(data_recipe_naomit, training = data_train)

baked_train_naomit <- bake(prepare_na_omit, new_data = data_train)
baked_test_naomit <- bake(prepare_na_omit, new_data = data_test)

But when I bake it, I get the following error:

Error in if (any(x <= 0)) { : missing value where TRUE/FALSE needed

Does someone know how to fix this?

I tried with:
step_naomit(is.na(all_predictors()))

But that gives the following error, when prepping:

Error in as_indices_impl():
! Must subset columns with a valid subscript vector.
✖ Subscript has the wrong type logical.
ℹ It must be numeric or character.


来源: stackexchange

问:
UI5 OData - Filter automatic READ call after Create
Hi have developed an App with Planninng Calendar.

This is an example of my oData call when starting the App. Here I set some filters.

```<code>EmployeeSet?$skip=0&$top=1000&$filter=substringof(%2799999999%27,orgId)%20and%20startDate%20le%20datetime%272022-12-01T10%3a59%3a14%27%20and%20endDate%20ge%20datetime%272022-12-31T11%3a59%3a14%27&$expand=EmployeeToAppointment%2cEmployeeToSpecialDates
</code>```

My poblem comes, after I add a new Appointment with method Create, the Calendar is refreshed  and the READ method is called, but there is no filter, so all the data is read, without filtering. Is there any possibility to filter this automatic READ call?

Below is an example of the automatic READ call

```<code>GET EmployeeSet('00002889')/EmployeeToAppointment?$skip=0&$top=1000
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi have developed an App with Planninng Calendar.

This is an example of my oData call when starting the App. Here I set some filters.

EmployeeSet?$skip=0&$top=1000&$filter=substringof(%2799999999%27,orgId)%20and%20startDate%20le%20datetime%272022-12-01T10%3a59%3a14%27%20and%20endDate%20ge%20datetime%272022-12-31T11%3a59%3a14%27&$expand=EmployeeToAppointment%2cEmployeeToSpecialDates

My poblem comes, after I add a new Appointment with method Create, the Calendar is refreshed  and the READ method is called, but there is no filter, so all the data is read, without filtering. Is there any possibility to filter this automatic READ call?

Below is an example of the automatic READ call

GET EmployeeSet('00002889')/EmployeeToAppointment?$skip=0&$top=1000


问:
IntelliJ plugin: How to show multiline inline text
I want to show multiline inline text inside the IntelliJ editors and I have no clue how to implement it and there is no good documentation or examples in the wild.

I try to use the EditorCustomElementRenderer Interface.

I use the InlayModel.addBlockElement to add/show them.

I can display an inline string just fine, but I want the string to automatically use multiple lines if it is too long.

I try to use a JBTextArea to do it, but the problem is that I have no idea how to paint the textArea, in the paint function below you can see that I use drawString, but I need to draw the whole textArea.

Is this somehow achievable?

My class:

```<code>public class MyClass implements EditorCustomElementRenderer {

    private JBTextArea textArea;
    private Color color;
    public MyClass(final String problemMessage, Color color) {
        textArea = new JBTextArea(problemMessage);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        this.color = color;
    }

    @Override
    public void paint(@NotNull Inlay inlay, @NotNull Graphics graphics, @NotNull Rectangle targetRegion, @NotNull TextAttributes textAttributes) {
        Editor editor = inlay.getEditor();
        EditorColorsScheme colorsScheme = editor.getColorsScheme();

        graphics.setFont(colorsScheme.getFont(EditorFontType.PLAIN));
        graphics.setColor(color);

        // todo how to draw the textArea instead of the string?
        graphics.drawString(textArea.getText(), targetRegion.x, targetRegion.y + editor.getAscent());
    }
</code>```

I tried to find a solution in the "documentation" of the IntelliJ platform and I searched the code for all implementations of EditorCustomElementRenderer but that did not help.

Body:
I want to show multiline inline text inside the IntelliJ editors and I have no clue how to implement it and there is no good documentation or examples in the wild.

I try to use the EditorCustomElementRenderer Interface.

I use the InlayModel.addBlockElement to add/show them.

I can display an inline string just fine, but I want the string to automatically use multiple lines if it is too long.

I try to use a JBTextArea to do it, but the problem is that I have no idea how to paint the textArea, in the paint function below you can see that I use drawString, but I need to draw the whole textArea.

Is this somehow achievable?

My class:

public class MyClass implements EditorCustomElementRenderer {

    private JBTextArea textArea;
    private Color color;
    public MyClass(final String problemMessage, Color color) {
        textArea = new JBTextArea(problemMessage);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        this.color = color;
    }

    @Override
    public void paint(@NotNull Inlay inlay, @NotNull Graphics graphics, @NotNull Rectangle targetRegion, @NotNull TextAttributes textAttributes) {
        Editor editor = inlay.getEditor();
        EditorColorsScheme colorsScheme = editor.getColorsScheme();

        graphics.setFont(colorsScheme.getFont(EditorFontType.PLAIN));
        graphics.setColor(color);

        // todo how to draw the textArea instead of the string?
        graphics.drawString(textArea.getText(), targetRegion.x, targetRegion.y + editor.getAscent());
    }

I tried to find a solution in the "documentation" of the IntelliJ platform and I searched the code for all implementations of EditorCustomElementRenderer but that did not help.


问:
How to make Python language server in Neovim to work with conda enviromnments?
I am trying to make the language server to use a particular Python 3 executable in a particular conda environment. Now it works with a global Anaconda python, and it's not convenient at all. How do I set this up?

Thank you!


问:
how to insert and update using PDO prepared method
.

Is the following a good method to insert/update SQL data ?

Connection

```<code>try{
    $pdo = new PDO("mysql:host=localhost;dbname=5243c5435", "235v456234c5", "$23#4%34#54^");
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
</code>```

Insert Query

```<code>try{
    // Prepare an insert statement
   $sql = "INSERT INTO members (name, email) VALUES (:name, :email)";
   $stmt = $pdo->prepare($sql);

   // Bind parameters to statement
   $stmt->bindParam(':name', $name, PDO::PARAM_STR);
   $stmt->bindParam(':email', $email, PDO::PARAM_STR);

   $name = "Hermione";
   $email = "hermionegranger@mail.com";
   $stmt->execute();
</code>```

Update Query

```<code>try{
    // Prepare an insert statement
    $sql = "UPDATE members SET name=:name, email=:email WHERE phone = :phone" or die("Prepare Error");
    $stmt = $pdo->prepare($sql);

    // Bind parameters to statement
    $stmt->bindParam(':name', $name, PDO::PARAM_STR);
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->bindParam(':phone', $whatsapp, PDO::PARAM_STR);

    $phone="1234567890";
    $name = "Hermione";
    $email = "hermionegranger@mail.com";
    $stmt->execute();
</code>```

I need suggestions from experts, is it efficient and safe to use above to codes ?

Body:
.

Is the following a good method to insert/update SQL data ?

Connection

try{
    $pdo = new PDO("mysql:host=localhost;dbname=5243c5435", "235v456234c5", "$23#4%34#54^");
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}

Insert Query

try{
    // Prepare an insert statement
   $sql = "INSERT INTO members (name, email) VALUES (:name, :email)";
   $stmt = $pdo->prepare($sql);

   // Bind parameters to statement
   $stmt->bindParam(':name', $name, PDO::PARAM_STR);
   $stmt->bindParam(':email', $email, PDO::PARAM_STR);

   $name = "Hermione";
   $email = "hermionegranger@mail.com";
   $stmt->execute();

Update Query

try{
    // Prepare an insert statement
    $sql = "UPDATE members SET name=:name, email=:email WHERE phone = :phone" or die("Prepare Error");
    $stmt = $pdo->prepare($sql);

    // Bind parameters to statement
    $stmt->bindParam(':name', $name, PDO::PARAM_STR);
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->bindParam(':phone', $whatsapp, PDO::PARAM_STR);

    $phone="1234567890";
    $name = "Hermione";
    $email = "hermionegranger@mail.com";
    $stmt->execute();

I need suggestions from experts, is it efficient and safe to use above to codes ?


问:
MenuItem single check box in unity
I already know how to use MenuItem to extend the unity menu and we can use checkmark to let the item marked.
My question is if we can let the whole menu or sub-menu only have one checked item? Such as the single check box may be available by some unity component rather than writing code to cancel checked and check a new item?

I have tried Menu Item setting and PreEditor setting but none of APIs or class can do the single checkmark.

Title: MenuItem single check box in unity


问:
Firebase - copy document to a new collection and update a field
I have a Firebase database with a list of entries. Now, on click, I want to copy a certain document from this database to a user database (create new document in user DB) while at the same time updating one of the fields.
I figured out how to copy the document, but I have problems with updating the field. I think I'm simply using a wrong syntax, but couldn't find this example in Firebase documentation.

This is how the original document looks like: (https://i.stack.imgur.com/ux18x.png)]

And this is how it's copied into the user database: (https://i.stack.imgur.com/QsBVy.png)]

I use this code to make the copy:
setDoc(doc(userSentencesRef, newSentenceIDText), ...newSentence)

And I tried many ways to update the "Level" field, but none of them works:

setDoc(doc(userSentencesRef, newSentenceIDText), ...newSentence, {data: {LEVEL: "exclude"}})

setDoc(doc(userSentencesRef, newSentenceIDText), ...newSentence, {LEVEL: "exclude"})

setDoc(doc(userSentencesRef, newSentenceIDText), {...newSentence, LEVEL: "exclude"})

(the first two do nothing, the last one adds a separate level field).

I also wouldn't want to list every single field that needs to be added { EN: data.EN, DE: data.DE }, etc, because I want to make sure it works even if the other fields change in future.

I will really appreciate your help.


问:
How to set cookie from local subdomain?
I have an .NET API and a Blazor WASM app. They will be deployed on same domain but different subdomain (api.o.com and dashboard.o.com). In order to simulate this locally I mapped local IP address 127.0.0.2 to api.o.com and 127.0.0.3 to dashboard.o.com in my hosts file.

```<code>127.0.0.2 api.o.com
127.0.0.3 dashboard.o.com
</code>```

Both apps run just fine, but I cannot get them to share cookies. When I call an API from swagger the set-cookie in response sets the cookie for api.o.com but when I call an API from dashboard.o.com the set-cookie response header refuses to set the cookie.

Cookie is set on API with code

```<code>    Response.Cookies.Append("cookie-name", "cookie-value", new CookieOptions
    {
        HttpOnly = true,
        Domain = "o.com",
        Expires = DateTime.Now.AddMonths(1),
        Secure = true
    });
</code>```

My understanding was that the Domain value "o.com" on cookie would allow me to share cookies across subdomains. How do I share cookies across subdomains?

Title: How to set cookie from local subdomain?

Body:
I have an .NET API and a Blazor WASM app. They will be deployed on same domain but different subdomain (api.o.com and dashboard.o.com). In order to simulate this locally I mapped local IP address 127.0.0.2 to api.o.com and 127.0.0.3 to dashboard.o.com in my hosts file.

127.0.0.2 api.o.com
127.0.0.3 dashboard.o.com

Both apps run just fine, but I cannot get them to share cookies. When I call an API from swagger the set-cookie in response sets the cookie for api.o.com but when I call an API from dashboard.o.com the set-cookie response header refuses to set the cookie.

Cookie is set on API with code

    Response.Cookies.Append("cookie-name", "cookie-value", new CookieOptions
    {
        HttpOnly = true,
        Domain = "o.com",
        Expires = DateTime.Now.AddMonths(1),
        Secure = true
    });

My understanding was that the Domain value "o.com" on cookie would allow me to share cookies across subdomains. How do I share cookies across subdomains?


问:
CreateProcess() with I/O redirection: setting lpEnvironment disables redirection?
I am trying to port muon (a C99 implementation of meson) to Windows, and I am having a problem with one of its unit tests. This unit test calls python3 which launches a python script. I use I/O redirection to get the result. The python script, called get-version.py, is:

#!/usr/bin/env python3

print('1.2')

```
<p>If I call <code>CreateProcess()</code> with <code>lpEnvironment</code> being <code>NULL</code>, no problem, I correctly retrieve the version.</p>
<p>But, the unit test is also setting several environment variables for the child process. If I set <code>lpEnvironment</code>, I can't retrieve the version anymore.</p>
<p>Note that the code is not setting <code>UNICODE</code> (so I use the ANSI API).</p>
<p>The relevant code, from a test code you can find here (see lines 154 and 155), is:</p>
<pre class="lang-c prettyprint-override"><code>char *env = "MUON_VAR=FOO\0"; // last nul byte necessary
res = CreateProcess("C:\\Documents\\msys2\\mingw64\\bin/python3.exe",
                    "\"-c\" \"C:\\Documents\\msys2\\home\\vincent.torri\\gitroot_64\\muon_gh\\mon_test/get-version.py\"",
                    NULL, NULL, TRUE, CREATE_SUSPENDED, env, chdir, &si, &pi);
</code>```

Does someone see what the problem is?

Body:
I am trying to port muon (a C99 implementation of meson) to Windows, and I am having a problem with one of its unit tests. This unit test calls python3 which launches a python script. I use I/O redirection to get the result. The python script, called get-version.py, is:

#!/usr/bin/env python3

print('1.2')

If I call CreateProcess() with lpEnvironment being NULL, no problem, I correctly retrieve the version.

But, the unit test is also setting several environment variables for the child process. If I set lpEnvironment, I can't retrieve the version anymore.

Note that the code is not setting UNICODE (so I use the ANSI API).

The relevant code, from a test code you can find here (see lines 154 and 155), is:

char *env = "MUON_VAR=FOO\0"; // last nul byte necessary
res = CreateProcess("C:\\Documents\\msys2\\mingw64\\bin/python3.exe",
                    "\"-c\" \"C:\\Documents\\msys2\\home\\vincent.torri\\gitroot_64\\muon_gh\\mon_test/get-version.py\"",
                    NULL, NULL, TRUE, CREATE_SUSPENDED, env, chdir, &si, &pi);

Does someone see what the problem is?


问:
docker-compose: override / redirect internet request to local service?
Is it possible to redirect a http request targeted a public internet service executed from within a container to a mock service defined in docker-compose?

I have an image that makes a http request to a hard-coded address, let's say https://www.google.com/. For testing purposes, I would like to change this so that it targets a mock service defined in my docker-compose.yml file instead.

One attempt was to use extra_hosts, and provider the hostname google-mock as that is identical to the container name according to the Docker Compose networking documentation. However, that does not work since google-mock is not a valid IP address:

version: '3.3'

services:
  # a service that makes requests to hard-coded https://www.google.com
  some-service:
    image: some/image
    extra_hosts:
      - "www.google.com:google-mock"

  # the service that I would like the request to end up to instead of Google
  google-mock:
    image: http/mock
    ports:
      - 443:5050
```
<p>Replacing the <code>google-mock</code> service with an IP address works in the sense that the request does not hit Google's servers. However it does solve my problem because the request does not hit the <code>google-mock</code> service:</p>
<pre class="lang-yaml prettyprint-override"><code>version: '3.3'

services:
  some-service:
    image: some/image
    extra_hosts:
      - "www.google.com:127.0.0.1"

  google-mock:
    image: http/mock
    ports:
      - 443:5050
</code>```

Another idea was to add domainname to my config but still no success:

version: '3.3'

services:
  some-service:
    image: some/image

  google-mock:
    image: http/mock
    domainname: www.google.com
    ports:
      - 443:5050
```

Body:
Is it possible to redirect a http request targeted a public internet service executed from within a container to a mock service defined in docker-compose?

I have an image that makes a http request to a hard-coded address, let's say https://www.google.com/. For testing purposes, I would like to change this so that it targets a mock service defined in my docker-compose.yml file instead.

One attempt was to use extra_hosts, and provider the hostname google-mock as that is identical to the container name according to the Docker Compose networking documentation. However, that does not work since google-mock is not a valid IP address:

version: '3.3'

services:
  # a service that makes requests to hard-coded https://www.google.com
  some-service:
    image: some/image
    extra_hosts:
      - "www.google.com:google-mock"

  # the service that I would like the request to end up to instead of Google
  google-mock:
    image: http/mock
    ports:
      - 443:5050

Replacing the google-mock service with an IP address works in the sense that the request does not hit Google's servers. However it does solve my problem because the request does not hit the google-mock service:

version: '3.3'

services:
  some-service:
    image: some/image
    extra_hosts:
      - "www.google.com:127.0.0.1"

  google-mock:
    image: http/mock
    ports:
      - 443:5050

Another idea was to add domainname to my config but still no success:

version: '3.3'

services:
  some-service:
    image: some/image

  google-mock:
    image: http/mock
    domainname: www.google.com
    ports:
      - 443:5050


问:
Failed to pull image on EKS created by Terraform
I created EKS using Terraform, then I am trying to install aws-load-balancer using helm
it gives me this error

"Failed to pull image "602401143452.dkr.ecr.us-west-2.amazonaws.com/amazon/aws-load-balancer-controller:v2.4.5": rpc error: code = Unknown desc = Error response from daemon: Head "https://602401143452.dkr.ecr.us-west-2.amazonaws.com/v2/amazon/aws-load-balancer-controller/manifests/v2.4.5": no basic auth credentials"

why there is no basic auth credentials ?
How to make it pull the image from another region? my EKS is in Asia not us-west-2 ?

Note:
EKS is in a private subnet, I am using AWS CodeBuild to run Terraform and deploy EKS, in the last step of CodeBuild I run a simple HELM command to deploy

```<code> # Install AWS LoadBalancer Controller
resource "helm_release" "aws-lb-controller" {
  name       = "aws-load-balancer-controller"
  chart      = "eks/aws-load-balancer-controller"
  repository =  "https://aws.github.io/eks-charts"

  values = []

  set {
    name  = "region"
    value = "ap-southeast-1"
  }
  set {
    name  = "image.repository"
    value = "public.ecr.aws/eks/aws-load-balancer-controller"
  }
  set {
    name  = "image.tag"
    value = "v2.4.5"
  }
  set {
    name  = "namespace"
    value = "kube-system"
  }
  set {
    name  = "serviceAccount.create"
    value = "false"
  }
  set {
    name  = "serviceAccount.name"
    value = "aws-load-balancer-controller"
  }
  set {
    name  = "ingress-class"
    value = "alb"
  }
  set {
    name  = "controller.admissionWebhooks.enabled"
    value = "false"
  }
}
</code>```

Why EKS failed to pull the image ?

Body:
I created EKS using Terraform, then I am trying to install aws-load-balancer using helm
it gives me this error

"Failed to pull image "602401143452.dkr.ecr.us-west-2.amazonaws.com/amazon/aws-load-balancer-controller:v2.4.5": rpc error: code = Unknown desc = Error response from daemon: Head "https://602401143452.dkr.ecr.us-west-2.amazonaws.com/v2/amazon/aws-load-balancer-controller/manifests/v2.4.5": no basic auth credentials"

why there is no basic auth credentials ?
How to make it pull the image from another region? my EKS is in Asia not us-west-2 ?

Note:
EKS is in a private subnet, I am using AWS CodeBuild to run Terraform and deploy EKS, in the last step of CodeBuild I run a simple HELM command to deploy

 # Install AWS LoadBalancer Controller
resource "helm_release" "aws-lb-controller" {
  name       = "aws-load-balancer-controller"
  chart      = "eks/aws-load-balancer-controller"
  repository =  "https://aws.github.io/eks-charts"

  values = []

  set {
    name  = "region"
    value = "ap-southeast-1"
  }
  set {
    name  = "image.repository"
    value = "public.ecr.aws/eks/aws-load-balancer-controller"
  }
  set {
    name  = "image.tag"
    value = "v2.4.5"
  }
  set {
    name  = "namespace"
    value = "kube-system"
  }
  set {
    name  = "serviceAccount.create"
    value = "false"
  }
  set {
    name  = "serviceAccount.name"
    value = "aws-load-balancer-controller"
  }
  set {
    name  = "ingress-class"
    value = "alb"
  }
  set {
    name  = "controller.admissionWebhooks.enabled"
    value = "false"
  }
}

Why EKS failed to pull the image ?


问:
Is there a way to trigger another PR to a different branch when a PR is approved?
I have submitted PR to branch A. Once this approved, I need another PR to be automatically submitted to branch B. Is there a way to achieve this?</p>


问:
Error C++: 'BIO_ADDR' does not name a type
I'm a C++ developer. I'm using OpenSSL to make my data secure.

In this code:

#include <openssl/bio.h>

typedef struct contextt {
  SSL_CTX *ctx;
  SSL *ssl;
  HMAC_CTX *cookie_hmac;
  BIO_METHOD *meth;
  BIO_ADDR *bio_addr;
} contextt;
```
<p>I get these errors:</p>
<pre class="lang-none prettyprint-override"><code>error: 'BIO_ADDR' does not name a type
error: 'BIO_set_init' was not declared in this scope
error: 'BIO_set_data' was not declared in this scope
</code>```

BIO_ADDR is declared in bio.h with BIO_set_init(), and openssl/bio.h is under /usr/include.

I included the bio.h in the code, and I gave the path, but I don't know what the real problem is.

I think maybe a problem in the library or the makefile, but I don't know how to resolve it.

Body:
I'm a C++ developer. I'm using OpenSSL to make my data secure.

In this code:

#include <openssl/bio.h>

typedef struct contextt {
  SSL_CTX *ctx;
  SSL *ssl;
  HMAC_CTX *cookie_hmac;
  BIO_METHOD *meth;
  BIO_ADDR *bio_addr;
} contextt;

I get these errors:

error: 'BIO_ADDR' does not name a type
error: 'BIO_set_init' was not declared in this scope
error: 'BIO_set_data' was not declared in this scope

BIO_ADDR is declared in bio.h with BIO_set_init(), and openssl/bio.h is under /usr/include.

I included the bio.h in the code, and I gave the path, but I don't know what the real problem is.

I think maybe a problem in the library or the makefile, but I don't know how to resolve it.


问:
Why there are twice “query rollback” every time when I query
sql.log

```<code>2022-12-09T10:46:30.814252Z   877 Query SELECT flag.id AS flag_id, flag.code AS flag_code, flag.isused AS flag_isused, flag.user_id AS flag_user_id
FROM flag
WHERE flag.code = '000027'
LIMIT 1
2022-12-09T10:46:30.815296Z   877 Query ROLLBACK
2022-12-09T10:46:30.815512Z   877 Query ROLLBACK
</code>```

code

def exchange_code():
    code =  request.json.get('code')
    flag = db.session.query(Flag).filter_by(code=code).first()
    return flag.id
```

I'm using SQLAlchemy==1.4.44 and Flask-SQLAlchemy==2.5.1

i just want figure out why there twice "Query  ROLLBACK" every time i query.

Body:
sql.log

2022-12-09T10:46:30.814252Z   877 Query SELECT flag.id AS flag_id, flag.code AS flag_code, flag.isused AS flag_isused, flag.user_id AS flag_user_id
FROM flag
WHERE flag.code = '000027'
LIMIT 1
2022-12-09T10:46:30.815296Z   877 Query ROLLBACK
2022-12-09T10:46:30.815512Z   877 Query ROLLBACK

code

def exchange_code():
    code =  request.json.get('code')
    flag = db.session.query(Flag).filter_by(code=code).first()
    return flag.id

I'm using SQLAlchemy==1.4.44 and Flask-SQLAlchemy==2.5.1

i just want figure out why there twice "Query  ROLLBACK" every time i query.


问:
Does a JS ES6 block creates a new Execution Context?
So I understand how Execution Contexts && Activation Object work in ES5, no problem.
I also understand that ES6 is basically syntactic sugar over ES5, so most likely a block-scoped code does also create an Execution Context, just like function scopes.

However, I haven't found any documentation on this matter.

Imagine the following code:

```<code>var a = 50
{
  a = 51;
  let b = 100;

}
</code>```

The activation objects abstraction would be something like:

```<code>globalActivationObject {
    scope-chain: Global,
    this: this.globalExcutionContext,
    var a: 50
}

blockActivationObject {
    scope-chain: parentContext(aka Global),
    this: globalEC,
    a: 51,
    let b = 100;
}
</code>```

Is any of this correct? Is there any good source where I can read more about it?

Body:
So I understand how Execution Contexts && Activation Object work in ES5, no problem.
I also understand that ES6 is basically syntactic sugar over ES5, so most likely a block-scoped code does also create an Execution Context, just like function scopes.

However, I haven't found any documentation on this matter.

Imagine the following code:

var a = 50
{
  a = 51;
  let b = 100;

}

The activation objects abstraction would be something like:

globalActivationObject {
    scope-chain: Global,
    this: this.globalExcutionContext,
    var a: 50
}

blockActivationObject {
    scope-chain: parentContext(aka Global),
    this: globalEC,
    a: 51,
    let b = 100;
}

Is any of this correct? Is there any good source where I can read more about it?


问:
ERROR: "int() argument must be a string, a bytes-like object or a number, not 'KeyboardModifier'" while using matplotlib in pyside6 GUI application
I am coding a Pyside6 based GUI program to show wav/mp3 wavform figure with librosa, add import list as following,

```<code>#import lib
import librosa
import librosa.display

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

#code in WavformShow.py

        fig = Figure(figsize=(5, 2))
        librosa.display.waveshow(data,sample_rate,offset=0.0)
</code>```

However, when I run the script, an error message is,

```<code>Traceback (most recent call last):
  File "MainFrame_v8.py", line 8, in <module>
    from ClassicAudio.WavformShow import *
  File "E:\Code\Qt-proj\Pyside6UI\ClassicAudio\WavformShow.py", line 11, in <module>
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
  File "C:\Users\rui\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 7, in <module>
    from .backend_qtagg import (    # noqa: F401, E402 # pylint: disable=W0611
  File "C:\Users\rui\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\backends\backend_qtagg.py", line 12, in <module>
    from .backend_qt import (
  File "C:\Users\rui\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\backends\backend_qt.py", line 73, in <module>
    _MODIFIER_KEYS = [
  File "C:\Users\rui\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\backends\backend_qt.py", line 74, in <listcomp>
    (_to_int(getattr(_enum("QtCore.Qt.KeyboardModifier"), mod)),
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyboardModifier'
</code>```

plus,

I have tried 'import matplotlib.pyplot as plt', but same issue happened;

also, tried with 'matplotlib.use('tkagg')', which may choose tkagg backend, and tigger a independent show window, which is not my expectation(a picutre show in a wrapper).

Body:
I am coding a Pyside6 based GUI program to show wav/mp3 wavform figure with librosa, add import list as following,

#import lib
import librosa
import librosa.display

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

#code in WavformShow.py

        fig = Figure(figsize=(5, 2))
        librosa.display.waveshow(data,sample_rate,offset=0.0)

However, when I run the script, an error message is,

Traceback (most recent call last):
  File "MainFrame_v8.py", line 8, in <module>
    from ClassicAudio.WavformShow import *
  File "E:\Code\Qt-proj\Pyside6UI\ClassicAudio\WavformShow.py", line 11, in <module>
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
  File "C:\Users\rui\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 7, in <module>
    from .backend_qtagg import (    # noqa: F401, E402 # pylint: disable=W0611
  File "C:\Users\rui\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\backends\backend_qtagg.py", line 12, in <module>
    from .backend_qt import (
  File "C:\Users\rui\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\backends\backend_qt.py", line 73, in <module>
    _MODIFIER_KEYS = [
  File "C:\Users\rui\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\backends\backend_qt.py", line 74, in <listcomp>
    (_to_int(getattr(_enum("QtCore.Qt.KeyboardModifier"), mod)),
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyboardModifier'

plus,

I have tried 'import matplotlib.pyplot as plt', but same issue happened;

also, tried with 'matplotlib.use('tkagg')', which may choose tkagg backend, and tigger a independent show window, which is not my expectation(a picutre show in a wrapper).


问:
loop to go between two dates and output dates in unix format?
I have two dates:
2022-11-11
and
2022-12-12

How can I loop all of the days between these dates and output every day in unixtimestamp format?

Thanks.

I searched a lot online but all the solutions return dates in string format i.e.

Thursday 2022-12-08 00:00:00


问:
Mocha just stops recursively finding tests
So I've got a setup where I want to test preact components using mocha seperately to library/utils/helper tests. My structure is like below

```<code>--src/script/
  --component/
    --ExampleComponent/
      --ExampleComponent.ts
      --ExampleComponent.test.ts
      --ExampleSubComponent/
        --ExampleSubComponent.ts
        --ExampleSubComponent.test.ts
  --lib/
    --util/
      --index.ts
      --exampleUtil/
        --exampleUtil.ts
        --exampleUtil.test.ts
</code>```

Now

```<code>ts-mocha --paths -p ./src/tsconfig.json ./src/script/lib/**/*.test.ts
</code>```

runs src/script/lib/exampleUtil/exampleUtil.test.ts as expected but

```<code>ts-mocha --paths -p ./src/tsconfig.json -r ignore-styles ./src/script/Component/**/*.test.ts
</code>```

Only runs src/script/component/ExampleComponent/ExampleComponent.test.ts

but not src/script/component/ExampleComponent/ExampleSubComponent/ExampleSubComponent.test.ts

The same can also be said if src/script/lib/exampleUtil/subUtil/subUtil.test.ts existed.

However if I run

```<code>ts-mocha --paths -p ./src/tsconfig.json -r ignore-styles ./src/script/**/*.test.ts
</code>```

then every single test is ran as expected.

Body:
So I've got a setup where I want to test preact components using mocha seperately to library/utils/helper tests. My structure is like below

--src/script/
  --component/
    --ExampleComponent/
      --ExampleComponent.ts
      --ExampleComponent.test.ts
      --ExampleSubComponent/
        --ExampleSubComponent.ts
        --ExampleSubComponent.test.ts
  --lib/
    --util/
      --index.ts
      --exampleUtil/
        --exampleUtil.ts
        --exampleUtil.test.ts

Now

ts-mocha --paths -p ./src/tsconfig.json ./src/script/lib/**/*.test.ts

runs src/script/lib/exampleUtil/exampleUtil.test.ts as expected but

ts-mocha --paths -p ./src/tsconfig.json -r ignore-styles ./src/script/Component/**/*.test.ts

Only runs src/script/component/ExampleComponent/ExampleComponent.test.ts

but not src/script/component/ExampleComponent/ExampleSubComponent/ExampleSubComponent.test.ts

The same can also be said if src/script/lib/exampleUtil/subUtil/subUtil.test.ts existed.

However if I run

ts-mocha --paths -p ./src/tsconfig.json -r ignore-styles ./src/script/**/*.test.ts

then every single test is ran as expected.


问:
my variable "Player" isn't equal to my object key
I the types are the same, the array is the same but the final result that is the alert doesn't work.</p>
```<code>let player = [1, 2, 3];
let dark = [
  {
    name: [5, 2, 7]
  },
  {
    name: [6, 3, 5]
  },
  {
    name: [1, 2, 3]
  }
]

for (let i = 0; i < dark.length; i++) {
  if (dark[i].name == player) {
    alert("Something")
    break;
  }
}
</code>```

Body:
I the types are the same, the array is the same but the final result that is the alert doesn't work.

let player = [1, 2, 3];
let dark = [
  {
    name: [5, 2, 7]
  },
  {
    name: [6, 3, 5]
  },
  {
    name: [1, 2, 3]
  }
]

for (let i = 0; i < dark.length; i++) {
  if (dark[i].name == player) {
    alert("Something")
    break;
  }
}


问:
Can't export nested namespaces
I'm trying to make the code cleaner by creating namespaces in different directories and then exporting them all through one namespace.

Here's what I'm doing that works:

export namespace Main {
    export namespace Foo { // <-- this works

    }
}
```
<p>But importing Foo from another file and exporting it to Main does not work: ie</p>
<pre class="lang-js prettyprint-override"><code>// foo.ts
export namespace Foo {
}

// main.ts
import { Foo } from './foo.ts'
export namespace Main {
    export namespace Foo = Foo; // <- invalid syntax
}
</code>```

I've googled so much and I just can't find the syntax how do I export Foo if it exists in another file.

Thank you in advance.

Title: Can't export nested namespaces

Body:
I'm trying to make the code cleaner by creating namespaces in different directories and then exporting them all through one namespace.

Here's what I'm doing that works:

export namespace Main {
    export namespace Foo { // <-- this works

    }
}

But importing Foo from another file and exporting it to Main does not work: ie

// foo.ts
export namespace Foo {
}

// main.ts
import { Foo } from './foo.ts'
export namespace Main {
    export namespace Foo = Foo; // <- invalid syntax
}

I've googled so much and I just can't find the syntax how do I export Foo if it exists in another file.

Thank you in advance.


问:
Google Cloud GPU Instances not available (even if I have the quota)?
I just cannot bring up GPU optimized instances on GCP. Tried couple of different types/zones but always get rejected  Unavailable with the following explanation.

Does anybody else experienced this? Is it possible that the instance-types are not available whole day?

I tried to configure different timezones, increasing/decreasing the instance size and tried to use a VPN when accessing GCP.


问:
Error in eval(substitute(expr), data, enclos = parent.frame()) : Grouping factor must have 3 or more levels
I'm running an ordinal regression model on the following data (hope this is sufficient):

```<code>structure(list(ID = c(5508110, 5508215, 5508276, 5508318, 5508318,
5508343), gender = c("Woman", "Man", "Man", "Woman", "Woman",
"Woman"), ethnicity = structure(c(1L, 1L, 1L, 1L, 1L, 5L), levels = c("White",
"Asian / Asian British", "Black / African / Caribbean / Black British",
"Mixed / Multiple ethnic groups", "Other ethnic group"), class = "factor"),
    age.group = structure(c(1L, 1L, 1L, 3L, 3L, 1L), levels = c("young",
    "middle aged", "old"), class = "factor"), stimulus.pitch = structure(c(3L,
    3L, 3L, 2L, 2L, 1L), levels = c("medium", "low", "high"), class = "factor"),
    stimulus.accent = structure(c(3L, 1L, 1L, 3L, 2L, 2L), levels = c("SSBE",
    "Belfast", "Liverpool"), class = "factor"), uk.area = structure(c(1L,
    1L, 5L, 9L, 9L, 5L), levels = c("South East England", "East Midlands",
    "East of England", "London", "North East England", "North West England",
    "Northern Ireland", "Scotland", "South West England", "Wales",
    "West Midlands", "Yorkshire and the Humber"), class = "factor"),
    response.scale = structure(c(1L, 1L, 3L, 3L, 3L, 1L), levels = c("disagree",
    "neutral", "agree"), class = c("ordered", "factor"))), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

I'm receiving this error when creating a null model to test my ordinal regression model (using package ordinal), with the following code:

```<code>mg.null<-clmm2(response.scale~1, random=ID,
                data = mgm, Hess=TRUE)
</code>```

response.scale has three levels, 'disagree', 'neutral' and 'agree', so I don't understand why I'm getting this error - can anyone help? TIA!

Body:
I'm running an ordinal regression model on the following data (hope this is sufficient):

structure(list(ID = c(5508110, 5508215, 5508276, 5508318, 5508318,
5508343), gender = c("Woman", "Man", "Man", "Woman", "Woman",
"Woman"), ethnicity = structure(c(1L, 1L, 1L, 1L, 1L, 5L), levels = c("White",
"Asian / Asian British", "Black / African / Caribbean / Black British",
"Mixed / Multiple ethnic groups", "Other ethnic group"), class = "factor"),
    age.group = structure(c(1L, 1L, 1L, 3L, 3L, 1L), levels = c("young",
    "middle aged", "old"), class = "factor"), stimulus.pitch = structure(c(3L,
    3L, 3L, 2L, 2L, 1L), levels = c("medium", "low", "high"), class = "factor"),
    stimulus.accent = structure(c(3L, 1L, 1L, 3L, 2L, 2L), levels = c("SSBE",
    "Belfast", "Liverpool"), class = "factor"), uk.area = structure(c(1L,
    1L, 5L, 9L, 9L, 5L), levels = c("South East England", "East Midlands",
    "East of England", "London", "North East England", "North West England",
    "Northern Ireland", "Scotland", "South West England", "Wales",
    "West Midlands", "Yorkshire and the Humber"), class = "factor"),
    response.scale = structure(c(1L, 1L, 3L, 3L, 3L, 1L), levels = c("disagree",
    "neutral", "agree"), class = c("ordered", "factor"))), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))

I'm receiving this error when creating a null model to test my ordinal regression model (using package ordinal), with the following code:

mg.null<-clmm2(response.scale~1, random=ID,
                data = mgm, Hess=TRUE)

response.scale has three levels, 'disagree', 'neutral' and 'agree', so I don't understand why I'm getting this error - can anyone help? TIA!


问:
Why Java application is not working when VM size is increased?
We have a riemann JVM that currently runs between 50 and 65% that has increased over time gradually thanks to increasing load. Occasionally now though it spikes once is a while to around 90 ~ 95%. The VM is a 48 core 192GB machine. In terms of memory it does not consume more than 80GB.

We were hoping to scale it to the next larger VM of 64 CPU and 256GB memory. Strangely though the moment the BIGGER VM is added, the JVM constantly stays at 100% with a system load close to 100. The JVM process becomes unresponsive. (Bot the VMs are the same M5 types)

We had to scale down to the 48CPU machine.

The main question here is on a smaller VM (48 CPU (both m5 and c5)), the application is stable with CPU consumption at 40-65% and on switching(Scale UP) the VM to a 72 CPU machine, the application becomes unusable with 100% CPU. Switching back to the smaller VM makes everything stable again.

The use case is for a tool named riemann

Additional pointers:

OpenJDK 64-Bit Server VM version 17.0.3.0.1+7-LTS

Thread Dump: https://fastthread.io/my-thread-report.jsp?p=c2hhcmVkLzIwMjIvMTIvMjQvdGhyZWFkX2R1bXBfNF81M19wbS50ZHVtcC0tNS00MC0zOQ==&

configuration:

```<code>    MAX_HEAP=$(awk '/MemTotal/ { printf "%.0f", $2/1024*0.75 }' /proc/meminfo)
    HALF_MAX_HEAP=`expr $MAX_HEAP / 2`
    exec chpst -u vcap:vcap java \
      -XX:+UseParallelGC \
      -XX:+ExitOnOutOfMemoryError \
      -Xms"$HALF_MAX_HEAP"m \
      -Xmx"$MAX_HEAP"m \
      -Djava.io.tmpdir="$TMP_DIR" \
      -jar /var/vcap/packages/riemann/riemann.jar \
      "$CONFIG_DIR"/clojure/riemann.config \
      1>>"$LOG_DIR"/"$JOB_NAME".stdout.log \
      2>>"$LOG_DIR"/"$JOB_NAME".stderr.log &
</code>```

Body:
We have a riemann JVM that currently runs between 50 and 65% that has increased over time gradually thanks to increasing load. Occasionally now though it spikes once is a while to around 90 ~ 95%. The VM is a 48 core 192GB machine. In terms of memory it does not consume more than 80GB.

We were hoping to scale it to the next larger VM of 64 CPU and 256GB memory. Strangely though the moment the BIGGER VM is added, the JVM constantly stays at 100% with a system load close to 100. The JVM process becomes unresponsive. (Bot the VMs are the same M5 types)

We had to scale down to the 48CPU machine.

The main question here is on a smaller VM (48 CPU (both m5 and c5)), the application is stable with CPU consumption at 40-65% and on switching(Scale UP) the VM to a 72 CPU machine, the application becomes unusable with 100% CPU. Switching back to the smaller VM makes everything stable again.

The use case is for a tool named riemann

Additional pointers:

OpenJDK 64-Bit Server VM version 17.0.3.0.1+7-LTS

Thread Dump: https://fastthread.io/my-thread-report.jsp?p=c2hhcmVkLzIwMjIvMTIvMjQvdGhyZWFkX2R1bXBfNF81M19wbS50ZHVtcC0tNS00MC0zOQ==&

configuration:

    MAX_HEAP=$(awk '/MemTotal/ { printf "%.0f", $2/1024*0.75 }' /proc/meminfo)
    HALF_MAX_HEAP=`expr $MAX_HEAP / 2`
    exec chpst -u vcap:vcap java \
      -XX:+UseParallelGC \
      -XX:+ExitOnOutOfMemoryError \
      -Xms"$HALF_MAX_HEAP"m \
      -Xmx"$MAX_HEAP"m \
      -Djava.io.tmpdir="$TMP_DIR" \
      -jar /var/vcap/packages/riemann/riemann.jar \
      "$CONFIG_DIR"/clojure/riemann.config \
      1>>"$LOG_DIR"/"$JOB_NAME".stdout.log \
      2>>"$LOG_DIR"/"$JOB_NAME".stderr.log &


问:
Show backend pdf url in React app (Route)
I am facing one issue i try to solve it for long while but i can't so i decided to ask you all. come to my question is there is any way to open backend url (http://localhost:5000/files/demo.pdf) in react app using react routing e.g(http://localhost:3000/document/demo.pdf).

because when i click my url it opens in new tab and the url which shows is backend url so i want to replace it with react route url in react.

http://localhost:3000/document/demo.pdf
in same react app.
i tried with file system like stored it in folder and used as static but iam dealing with dynamic api so kinly help me with my condition.


问:
Is there a way to train a neuronal network (LSTM model) with multiple datasets in order to do time series forecasting?
I want to do predictions with a LSTM model, but the dataset isn't a single file, it's composed with multiple files (for example 3 Excels).

I've already checked that if you want to deal with a time series forecasting problem you have to prepare your data like (number of samples, number of time steps, number of features) and it works well if I implement this for a single Excel.

The problem consists in training with the three Excels at the same time, in this case the input tensor for the LSTM layer has the shape: (n_files, n_samples, n_timesteps, n_features), with dim = 4. This doesn't work because LSTM layers only admits input tensors with dim = 3.

My files have the same amount of data. It's collected from a device and the data has 1 value for each minute along the duration of the experiment. All the experiments have the same duration too.

I've tried to concatenate the files in order to have 1, and choosing the batch_size as the number of samples in one Excel (because I can't mix the different experiments) but it doesn't produce a good result (at least as good as the results from predicting with 1 experiment).

```<code>def build_model():
  model = keras.Sequential([
    layers.Masking(mask_value = 0.0, input_shape=[1,1]),
    layers.LSTM(50, return_sequences=True),
    layers.Dense(1)
  ])

  optimizer = tf.keras.optimizers.Adam(0.001)

  model.compile(loss='mse',
                optimizer=optimizer,
                metrics=['mae','RootMeanSquaredError'])
  return model

model_pred = build_model()
model_pred.fit(Xchopped_train, ychopped_train, batch_size = 252,
               epochs=500, verbose=1)

</code>```

Where Xchopped_train and ychopped_train are the concatenated data from the 3 Excel.

Another thing I've tried is to train the model within a loop, and changing the Excel:

```<code>for i in range(len(Xtrain)):
    model_pred.fit(Xtrain[i], Ytrain[i], epochs=167, verbose=1)
</code>```

Where Xtrain is (3,252,1,1) and the first index refers to the number of Excel.

And by far this is my best approach but it feels like this isn't a good solution since I don't know what's happening with the NN weights or which loss function is minimizing...

Is there a more efficient way to do this? Thanks!

Body:
I want to do predictions with a LSTM model, but the dataset isn't a single file, it's composed with multiple files (for example 3 Excels).

I've already checked that if you want to deal with a time series forecasting problem you have to prepare your data like (number of samples, number of time steps, number of features) and it works well if I implement this for a single Excel.

The problem consists in training with the three Excels at the same time, in this case the input tensor for the LSTM layer has the shape: (n_files, n_samples, n_timesteps, n_features), with dim = 4. This doesn't work because LSTM layers only admits input tensors with dim = 3.

My files have the same amount of data. It's collected from a device and the data has 1 value for each minute along the duration of the experiment. All the experiments have the same duration too.

I've tried to concatenate the files in order to have 1, and choosing the batch_size as the number of samples in one Excel (because I can't mix the different experiments) but it doesn't produce a good result (at least as good as the results from predicting with 1 experiment).

def build_model():
  model = keras.Sequential([
    layers.Masking(mask_value = 0.0, input_shape=[1,1]),
    layers.LSTM(50, return_sequences=True),
    layers.Dense(1)
  ])

  optimizer = tf.keras.optimizers.Adam(0.001)

  model.compile(loss='mse',
                optimizer=optimizer,
                metrics=['mae','RootMeanSquaredError'])
  return model

model_pred = build_model()
model_pred.fit(Xchopped_train, ychopped_train, batch_size = 252,
               epochs=500, verbose=1)

Where Xchopped_train and ychopped_train are the concatenated data from the 3 Excel.

Another thing I've tried is to train the model within a loop, and changing the Excel:

for i in range(len(Xtrain)):
    model_pred.fit(Xtrain[i], Ytrain[i], epochs=167, verbose=1)

Where Xtrain is (3,252,1,1) and the first index refers to the number of Excel.

And by far this is my best approach but it feels like this isn't a good solution since I don't know what's happening with the NN weights or which loss function is minimizing...

Is there a more efficient way to do this? Thanks!


问:
alert runs on loop when selecting a cell that has onfocusout event from another cell that has onfocusout event
There is a table that has multiple rows and columns and for some cells the input will be validated and alerts the users if its incorrect. Now what happens is that if I'm in a cell that validates the input and I select a cell that also need to validate the input, the browser throws an alert for the previous cell first and then shows an alert for the selected cell and when clicking on OK it shows the same alert and it loops infinitely.

So what I think is happening is that when I select the second cell the onfocusout event is triggered and it sends an alert and this alert triggered the onfocusout event for the selected cell and sends alert and this process repeats.

Below is an example of the problem

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text"  onfocusout="myFunction()">
    <input type="text"  onfocusout="myFunction()">
    <script>
        function myFunction(){
            alert("Hello");
        }
    </script>
</body>
</html>
</code>```

How do I fix this?

Body:
There is a table that has multiple rows and columns and for some cells the input will be validated and alerts the users if its incorrect. Now what happens is that if I'm in a cell that validates the input and I select a cell that also need to validate the input, the browser throws an alert for the previous cell first and then shows an alert for the selected cell and when clicking on OK it shows the same alert and it loops infinitely.

So what I think is happening is that when I select the second cell the onfocusout event is triggered and it sends an alert and this alert triggered the onfocusout event for the selected cell and sends alert and this process repeats.

Below is an example of the problem

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <input type="text"  onfocusout="myFunction()">
    <input type="text"  onfocusout="myFunction()">

How do I fix this?


问:
96 duplicate symbols for architecture x86_64 after pod install
I am using react native version 0.70.6, My project was running fine util I added pod for camera permission using react-native-permissions.After adding path for camera permission in my pod file i am getting this error

duplicate symbols for architecture x86_64

I have deleted my pods and regenerated and also deleted derived folder but none of the solutions worked.

My pod file looks as following:

```<code>require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '12.4'
install! 'cocoapods', :deterministic_uuids => false

target 'JDB_App' do
  config = use_native_modules!

  # Flags change depending on the env values.
  flags = get_default_flags()
  pod 'Firebase', :modular_headers => true
  pod 'FirebaseCore', :modular_headers => true
  pod 'GoogleUtilities', :modular_headers => true
  $RNFirebaseAsStaticFramework = true
  permissions_path = '../node_modules/react-native-permissions/ios'
  pod 'Permission-Camera', :path => "#{permissions_path}/Camera"

  use_react_native!(
    :path => config[:reactNativePath],
    # Hermes is now enabled by default. Disable by setting this flag to false.
    # Upcoming versions of React Native may rely on get_default_flags(), but
    # we make it explicit here to aid in the React Native upgrade process.
    :hermes_enabled => true,
    :fabric_enabled => flags[:fabric_enabled],
    # Enables Flipper.
    #
    # Note that if you have use_frameworks! enabled, Flipper will not work and
    # you should disable the next line.
    :flipper_configuration => FlipperConfiguration.enabled,
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 'JDB_AppTests' do
    inherit! :complete
    # Pods for testing
  end

  post_install do |installer|
    react_native_post_install(
      installer,
      # Set `mac_catalyst_enabled` to `true` in order to apply patches
      # necessary for Mac Catalyst builds
      :mac_catalyst_enabled => false
    )
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end

</code>```

Body:
I am using react native version 0.70.6, My project was running fine util I added pod for camera permission using react-native-permissions.After adding path for camera permission in my pod file i am getting this error

duplicate symbols for architecture x86_64

I have deleted my pods and regenerated and also deleted derived folder but none of the solutions worked.

My pod file looks as following:

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '12.4'
install! 'cocoapods', :deterministic_uuids => false

target 'JDB_App' do
  config = use_native_modules!

  # Flags change depending on the env values.
  flags = get_default_flags()
  pod 'Firebase', :modular_headers => true
  pod 'FirebaseCore', :modular_headers => true
  pod 'GoogleUtilities', :modular_headers => true
  $RNFirebaseAsStaticFramework = true
  permissions_path = '../node_modules/react-native-permissions/ios'
  pod 'Permission-Camera', :path => "#{permissions_path}/Camera"

  use_react_native!(
    :path => config[:reactNativePath],
    # Hermes is now enabled by default. Disable by setting this flag to false.
    # Upcoming versions of React Native may rely on get_default_flags(), but
    # we make it explicit here to aid in the React Native upgrade process.
    :hermes_enabled => true,
    :fabric_enabled => flags[:fabric_enabled],
    # Enables Flipper.
    #
    # Note that if you have use_frameworks! enabled, Flipper will not work and
    # you should disable the next line.
    :flipper_configuration => FlipperConfiguration.enabled,
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 'JDB_AppTests' do
    inherit! :complete
    # Pods for testing
  end

  post_install do |installer|
    react_native_post_install(
      installer,
      # Set `mac_catalyst_enabled` to `true` in order to apply patches
      # necessary for Mac Catalyst builds
      :mac_catalyst_enabled => false
    )
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end


问:
react-native-pager-view how to know to which direction the user is swiping?
i need to know to which direction the user is swiping, left or right. my initial thought was to save prev and current index with useRef hook and update them on each swipe using the onPageSelected callback. then i'd compare them to figure out which direction, but that just has its problems and is quite naive approach..

what can i do to figure this out?

current code goes like this

```<code>func component({stuff}){
    const currentIndex = useRef(null);
    const prevIndex = useRef(null);
    return <PagerView style={{ flex: 1 }}
        initialPage={currentPageNumber >= 1 ? 0 : 1}
        layoutDirection={"rtl"}
        onPageSelected={(PageSelectedEvent) => {
            prevIndex.current = currentIndex.current;
            currentIndex.current = PageSelectedEvent.nativeEvent.position;
            if (prevIndex.current > currentIndex.current) {
                if (currentPageNumber - 1 <= 0) {
                    setCurrentPageNumber(0);
                } else {
                    setCurrentPageNumber(currentPageNumber - 1);
                }
            } else if (prevIndex.current < currentIndex.current) {
                if (currentPageNumber + 1 >= 500) {
                    setCurrentPageNumber(500);
                } else {
                    setCurrentPageNumber(currentPageNumber + 1);
                }
            }
        }}
    >
        {pageComponents.map(page => {
            return page;
        })}
    </PagerView>

}
</code>```

Body:
i need to know to which direction the user is swiping, left or right. my initial thought was to save prev and current index with useRef hook and update them on each swipe using the onPageSelected callback. then i'd compare them to figure out which direction, but that just has its problems and is quite naive approach..

what can i do to figure this out?

current code goes like this

func component({stuff}){
    const currentIndex = useRef(null);
    const prevIndex = useRef(null);
    return <PagerView style={{ flex: 1 }}
        initialPage={currentPageNumber >= 1 ? 0 : 1}
        layoutDirection={"rtl"}
        onPageSelected={(PageSelectedEvent) => {
            prevIndex.current = currentIndex.current;
            currentIndex.current = PageSelectedEvent.nativeEvent.position;
            if (prevIndex.current > currentIndex.current) {
                if (currentPageNumber - 1 <= 0) {
                    setCurrentPageNumber(0);
                } else {
                    setCurrentPageNumber(currentPageNumber - 1);
                }
            } else if (prevIndex.current < currentIndex.current) {
                if (currentPageNumber + 1 >= 500) {
                    setCurrentPageNumber(500);
                } else {
                    setCurrentPageNumber(currentPageNumber + 1);
                }
            }
        }}
    >
        {pageComponents.map(page => {
            return page;
        })}
    </PagerView>

}


问:
How change docker log length limit to more than 16k
I am running docker swarm on engine version 20.10.17. I find out, some application making long logs (more than 16k) and in Loki, as my logging stack, I cannot parse JSON logs, because docker split logs by 16k strings and insert date in the middle of the log message.

I implement python script, that generates string based on string length and this is my findings (I'll replace repeating character to make it readable).

I message length is 16383:

```<code>2022-12-09T11:11:45.750162015Z xxxxxxxxx........xxxxx
</code>```

I message length is 16384 - this is the limit:

```<code>2022-12-09T11:13:15.903855127Z xxxxxxxxx........xxxxx2022-12-09T11:13:15.903855127Z
</code>```

the date 2022-12-09T11:13:15.903855127Z is the same at the beginning and at the end of message.

I message length is 16385:

```<code>2022-12-09T11:14:46.061048967Z xxxxxxxxx........xxxxx2022-12-09T11:14:46.061048967Z x
</code>```

This is my configuration of docker daemon:

{
  "storage-driver": "overlay2",
  "storage-opts": [
    "overlay2.override_kernel_check=true"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "5m",
    "max-file": "5"
  }
}
```

Is there a way how to change the configuration of length of log line? From docs I did not find this option and from source code it looks like its hardcoded. What is the best way how to parse logs properly?

In Loki, I can see whole log as one peace of log, but with dates (e.g. 2022-12-09T11:19:56.575690222Z ) in the middle of the log file (multiple times, based on the length of log line). This is quiet complicated way how to solve it, because that means, I have to check every log processed by Promtail.

Body:
I am running docker swarm on engine version 20.10.17. I find out, some application making long logs (more than 16k) and in Loki, as my logging stack, I cannot parse JSON logs, because docker split logs by 16k strings and insert date in the middle of the log message.

I implement python script, that generates string based on string length and this is my findings (I'll replace repeating character to make it readable).

I message length is 16383:

2022-12-09T11:11:45.750162015Z xxxxxxxxx........xxxxx

I message length is 16384 - this is the limit:

2022-12-09T11:13:15.903855127Z xxxxxxxxx........xxxxx2022-12-09T11:13:15.903855127Z

the date 2022-12-09T11:13:15.903855127Z is the same at the beginning and at the end of message.

I message length is 16385:

2022-12-09T11:14:46.061048967Z xxxxxxxxx........xxxxx2022-12-09T11:14:46.061048967Z x

This is my configuration of docker daemon:

{
  "storage-driver": "overlay2",
  "storage-opts": [
    "overlay2.override_kernel_check=true"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "5m",
    "max-file": "5"
  }
}

Is there a way how to change the configuration of length of log line? From docs I did not find this option and from source code it looks like its hardcoded. What is the best way how to parse logs properly?

In Loki, I can see whole log as one peace of log, but with dates (e.g. 2022-12-09T11:19:56.575690222Z ) in the middle of the log file (multiple times, based on the length of log line). This is quiet complicated way how to solve it, because that means, I have to check every log processed by Promtail.


问:
Tracking User properties on GA is not working
I'm trying to log events and set user id/properties in Google Analytics for my angular 13 application working with @angular/fire 7.3.0.

In my Google Analytics dashboard, I can see the my event just fine, but nothing regarding User ID or User Properties.

Here is my app.module.ts :

```<code>import { AngularFireAnalyticsModule, ScreenTrackingService, UserTrackingService, CONFIG } from '@angular/fire/compat/analytics';

@NgModule({
  declarations: [AppComponent],
  imports: [
    AngularFireModule.initializeApp(conf),
    AngularFireAnalyticsModule,
    // ...
  ],
  providers: [
    ScreenTrackingService,
    UserTrackingService,
    { provide: CONFIG, useValue: { send_page_view: false, allow_ad_personalization_signals: false, anonymize_ip: true} },
    // ...

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Here is the code I use to report Log and to set property

```<code>testID(){
    this.analytics.setUserId("test_id");
  }

  testProperties(value: string) {
    this.analytics.setUserProperties({ property: "property_test_value" });
  }

  testLog(){
    this.analytics.logEvent("event_test");
  }
</code>```

Any idea on why I cannot see my properties / user ID ?

Body:
I'm trying to log events and set user id/properties in Google Analytics for my angular 13 application working with @angular/fire 7.3.0.

In my Google Analytics dashboard, I can see the my event just fine, but nothing regarding User ID or User Properties.

Here is my app.module.ts :

import { AngularFireAnalyticsModule, ScreenTrackingService, UserTrackingService, CONFIG } from '@angular/fire/compat/analytics';

@NgModule({
  declarations: [AppComponent],
  imports: [
    AngularFireModule.initializeApp(conf),
    AngularFireAnalyticsModule,
    // ...
  ],
  providers: [
    ScreenTrackingService,
    UserTrackingService,
    { provide: CONFIG, useValue: { send_page_view: false, allow_ad_personalization_signals: false, anonymize_ip: true} },
    // ...

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here is the code I use to report Log and to set property

testID(){
    this.analytics.setUserId("test_id");
  }

  testProperties(value: string) {
    this.analytics.setUserProperties({ property: "property_test_value" });
  }

  testLog(){
    this.analytics.logEvent("event_test");
  }

Any idea on why I cannot see my properties / user ID ?


问:
Mocha: Permission denied error occured in Jenkins while Integrating Playwrigh_Mocha with Jenkins via GItHub
I am trying to run Playwright_Mocha through Jenkins, so I have created a Repository in Git Hub and the same is given in Jenkins Configuration (Source Code Management).

I have given the Build Step, to run my automation script which executes as shell command "npm run aboutPage"
In which aboutPage has the script as below in package.json file.

```<code> "scripts": {
"aboutPage": "mocha --timeout 800000 --config= ./.mocharc.js ./test/aboutPage.spec.js"
}
</code>```

below are the dependencies which I have installed in my project.

```<code>{
  "dependencies": {
    "@supercharge/fs": "^3.4.0",
    "allure-commandline": "^2.18.1",
    "allure-mocha": "^2.0.0-beta.19",
    "chai": "^4.3.6",
    "chai-dom": "^1.11.0",
    "chai-jquery": "^2.1.0",
    "chai-visible": "^0.1.5",
    "fs-extra": "^10.1.0",
    "mocha": "^10.0.0",
    "mocha-allure-reporter": "^1.4.0",
    "mochawesome-report-generator": "^6.2.0",
    "mochawesome-screenshots": "^1.7.3",
    "mysql": "^2.18.1",
    "node-localstorage": "^2.2.1",
    "node-sessionstorage": "^1.0.0",
    "playwright": "^1.27.0",
    "prettier": "^2.7.1",
    "read-excel-file": "^5.5.3",
    "sessionstorage": "^0.1.0",
    "winston": "^3.8.2",
    "winston-daily-rotate-file": "^4.7.1"
  },
  "devDependencies": {
    "mochawesome": "^7.1.3"
  }
}
</code>```

When I build Jenkins, below is the error displayed in the Console Output:

```<code> npm run aboutPage

> playwright_mocha@1.0.0 aboutPage /home/qabot/data/jenkins_home/workspace/TestDemo_QA_Automation_QATAR
> mocha --timeout 800000 --config= ./.mocharc.js ./test/aboutPage.spec.js

sh: 1: mocha: Permission denied

npm ERR! Linux 4.15.0-1113-azure
npm ERR! argv "/home/qabot/.nvm/versions/node/v4.3.2/bin/node" "/home/qabot/.nvm/versions/node/v4.3.2/bin/npm" "run" "aboutPage"
npm ERR! node v4.3.2
npm ERR! npm  v2.14.12
npm ERR! code ELIFECYCLE
npm ERR! playwright_mocha@1.0.0 aboutPage: `mocha --timeout 800000 --config= ./.mocharc.js ./test/aboutPage.spec.js`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the playwright_mocha@1.0.0 aboutPage script 'mocha --timeout 800000 --config= ./.mocharc.js ./test/aboutPage.spec.js'.
npm ERR! This is most likely a problem with the playwright_mocha package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     mocha --timeout 800000 --config= ./.mocharc.js ./test/aboutPage.spec.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls playwright_mocha
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/qabot/data/jenkins_home/workspace/TestDemo_QA_Automation_QATAR/npm-debug.log
Build step 'Execute shell' marked build as failure
Finished: FAILURE.
</code>```

Please let me know what and where I am doing wrong.

Thanks in advance

Body:
I am trying to run Playwright_Mocha through Jenkins, so I have created a Repository in Git Hub and the same is given in Jenkins Configuration (Source Code Management).

I have given the Build Step, to run my automation script which executes as shell command "npm run aboutPage"
In which aboutPage has the script as below in package.json file.

 "scripts": {
"aboutPage": "mocha --timeout 800000 --config= ./.mocharc.js ./test/aboutPage.spec.js"
}

below are the dependencies which I have installed in my project.

{
  "dependencies": {
    "@supercharge/fs": "^3.4.0",
    "allure-commandline": "^2.18.1",
    "allure-mocha": "^2.0.0-beta.19",
    "chai": "^4.3.6",
    "chai-dom": "^1.11.0",
    "chai-jquery": "^2.1.0",
    "chai-visible": "^0.1.5",
    "fs-extra": "^10.1.0",
    "mocha": "^10.0.0",
    "mocha-allure-reporter": "^1.4.0",
    "mochawesome-report-generator": "^6.2.0",
    "mochawesome-screenshots": "^1.7.3",
    "mysql": "^2.18.1",
    "node-localstorage": "^2.2.1",
    "node-sessionstorage": "^1.0.0",
    "playwright": "^1.27.0",
    "prettier": "^2.7.1",
    "read-excel-file": "^5.5.3",
    "sessionstorage": "^0.1.0",
    "winston": "^3.8.2",
    "winston-daily-rotate-file": "^4.7.1"
  },
  "devDependencies": {
    "mochawesome": "^7.1.3"
  }
}

When I build Jenkins, below is the error displayed in the Console Output:

 npm run aboutPage

> playwright_mocha@1.0.0 aboutPage /home/qabot/data/jenkins_home/workspace/TestDemo_QA_Automation_QATAR
> mocha --timeout 800000 --config= ./.mocharc.js ./test/aboutPage.spec.js

sh: 1: mocha: Permission denied

npm ERR! Linux 4.15.0-1113-azure
npm ERR! argv "/home/qabot/.nvm/versions/node/v4.3.2/bin/node" "/home/qabot/.nvm/versions/node/v4.3.2/bin/npm" "run" "aboutPage"
npm ERR! node v4.3.2
npm ERR! npm  v2.14.12
npm ERR! code ELIFECYCLE
npm ERR! playwright_mocha@1.0.0 aboutPage: `mocha --timeout 800000 --config= ./.mocharc.js ./test/aboutPage.spec.js`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the playwright_mocha@1.0.0 aboutPage script 'mocha --timeout 800000 --config= ./.mocharc.js ./test/aboutPage.spec.js'.
npm ERR! This is most likely a problem with the playwright_mocha package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     mocha --timeout 800000 --config= ./.mocharc.js ./test/aboutPage.spec.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls playwright_mocha
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/qabot/data/jenkins_home/workspace/TestDemo_QA_Automation_QATAR/npm-debug.log
Build step 'Execute shell' marked build as failure
Finished: FAILURE.

Please let me know what and where I am doing wrong.

Thanks in advance


问:
Dayjs relative time thresholds don't work
I've got a problem with thresholds and rounding using Dayjs relativeTime. I've set thresholds and extend dayjs, but it still use default options and I have no idea why.

```<code>import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

const thresholds = [
    { l: 's', r: 1 },
    { l: 'm', r: 1 },
    { l: 'mm', r: 59, d: 'minute' },
    { l: 'h', r: 1 },
    { l: 'hh', r: 23, d: 'hour' },
    { l: 'd', r: 1 },
    { l: 'dd', r: 29, d: 'day' },
    { l: 'M', r: 1 },
    { l: 'MM', r: 11, d: 'month' },
    { l: 'y' },
    { l: 'yy', d: 'year' },
];
const rounding = Math.floor;
const config = { thresholds, rounding };
dayjs.extend(relativeTime, config);
</code>```

Based on code above, with input dayjs('2022-01-01').to(dayjs('2022-01-28')) it should output 28 days, but the actual output is 1 month. It happens with number of days above 25, which is default value.

Body:
I've got a problem with thresholds and rounding using Dayjs relativeTime. I've set thresholds and extend dayjs, but it still use default options and I have no idea why.

import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

const thresholds = [
    { l: 's', r: 1 },
    { l: 'm', r: 1 },
    { l: 'mm', r: 59, d: 'minute' },
    { l: 'h', r: 1 },
    { l: 'hh', r: 23, d: 'hour' },
    { l: 'd', r: 1 },
    { l: 'dd', r: 29, d: 'day' },
    { l: 'M', r: 1 },
    { l: 'MM', r: 11, d: 'month' },
    { l: 'y' },
    { l: 'yy', d: 'year' },
];
const rounding = Math.floor;
const config = { thresholds, rounding };
dayjs.extend(relativeTime, config);

Based on code above, with input dayjs('2022-01-01').to(dayjs('2022-01-28')) it should output 28 days, but the actual output is 1 month. It happens with number of days above 25, which is default value.


问:
Python Pandas. How do I keep the values within the GroupBy clause?
I have the following code;

```<code>df = df_pivot.groupby(["Customer_ID","Code_Product"])["Customer_ID","Code_Product", "Order_Amount"].sum()
df.head(20)
</code>```

Which produces the following results;

The missing values for the Customer_ID can be found on the previous line. I would like my GroupBy command to populate the Customer_ID, how do I do this?

Body:
I have the following code;

df = df_pivot.groupby(["Customer_ID","Code_Product"])["Customer_ID","Code_Product", "Order_Amount"].sum()
df.head(20)

Which produces the following results;

The missing values for the Customer_ID can be found on the previous line. I would like my GroupBy command to populate the Customer_ID, how do I do this?


问:
How to organize multithreading
I have code, comes up WARNING: QApplication was not created in the main() thread, but the code runs, but 1 time, when it starts to run 2 times the site dies, how can I arrange multi-threading that it would not crash?

```<code>from .forms import UserForm
from bs4 import BeautifulSoup
from django import forms
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEnginePage
import sys
import time
import re
import requests

regex = r"price_85d2b9c\s+\w+\D+(?P<price>\d+\s+\d+)"

class Client(QWebEnginePage):
    def __init__(self,url):
        global app
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.html = ""
        self.loadFinished.connect(self.on_load_finished)
        self.load(QUrl(url))
        self.app.exec_()

    def on_load_finished(self):
        self.html = self.toHtml(self.Callable)
        print("Load Finished")

    def Callable(self,data):
        self.html = data
        self.app.quit()

def index(request):
    submitbutton= request.POST.get("submit")

    From=''
    To=''
    url=''
    prices = []

    form= UserForm(request.POST or None)
    if form.is_valid():
        From = (form.cleaned_data.get("From")).partition(", ")[2]
        To = (form.cleaned_data.get("To")).partition(", ")[2]

        regex = r"price_85d2b9c\s+\w+\D+(?P<price>\d+\s+\d+)|price_85d2b9c\D+(?P<pric>\d+\s+\d+)"
        url = "https://www.aviasales.ru/search/"+From+"1012"+To+"23121?request_source=search_form&expected_price_currency=rub&expected_price_source=calendar"
        print(url)
        client_response = Client(url)
        #print(client_response.html)

        test_str = client_response.html

        matches = re.finditer(regex, test_str, re.MULTILINE)

        for matchNum, match in enumerate(matches, start=1):
            print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

            for groupNum in range(0, len(match.groups())):
                groupNum = groupNum + 1
                print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
                prices.append("{group}".format(group = match.group(groupNum)))

    context= ({'form': form, 'From': From,
              'To': To, 'submitbutton': submitbutton,'prices': prices})

    return render(request, "index3.html", context)
</code>```

I tried using the QThreadPool Class, but it didn't work correctly. What can I do to make the code handle links and not crash.

Title: How to organize multithreading

Body:
I have code, comes up WARNING: QApplication was not created in the main() thread, but the code runs, but 1 time, when it starts to run 2 times the site dies, how can I arrange multi-threading that it would not crash?

from .forms import UserForm
from bs4 import BeautifulSoup
from django import forms
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEnginePage
import sys
import time
import re
import requests

regex = r"price_85d2b9c\s+\w+\D+(?P<price>\d+\s+\d+)"

class Client(QWebEnginePage):
    def __init__(self,url):
        global app
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.html = ""
        self.loadFinished.connect(self.on_load_finished)
        self.load(QUrl(url))
        self.app.exec_()

    def on_load_finished(self):
        self.html = self.toHtml(self.Callable)
        print("Load Finished")

    def Callable(self,data):
        self.html = data
        self.app.quit()

def index(request):
    submitbutton= request.POST.get("submit")

    From=''
    To=''
    url=''
    prices = []

    form= UserForm(request.POST or None)
    if form.is_valid():
        From = (form.cleaned_data.get("From")).partition(", ")[2]
        To = (form.cleaned_data.get("To")).partition(", ")[2]

        regex = r"price_85d2b9c\s+\w+\D+(?P<price>\d+\s+\d+)|price_85d2b9c\D+(?P<pric>\d+\s+\d+)"
        url = "https://www.aviasales.ru/search/"+From+"1012"+To+"23121?request_source=search_form&expected_price_currency=rub&expected_price_source=calendar"
        print(url)
        client_response = Client(url)
        #print(client_response.html)

        test_str = client_response.html

        matches = re.finditer(regex, test_str, re.MULTILINE)

        for matchNum, match in enumerate(matches, start=1):
            print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

            for groupNum in range(0, len(match.groups())):
                groupNum = groupNum + 1
                print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
                prices.append("{group}".format(group = match.group(groupNum)))

    context= ({'form': form, 'From': From,
              'To': To, 'submitbutton': submitbutton,'prices': prices})

    return render(request, "index3.html", context)

I tried using the QThreadPool Class, but it didn't work correctly. What can I do to make the code handle links and not crash.


问:
How to compare equality of values in a single object to the values in an array of objects?
I'm new to Javascript and I'm working on a project but am stuck.

I have a singular object that has been user generated based on a questionnaire and I now want to compare the value data to the data in the matching keys in multiple objects that's in an array.

ie user object is

```<code>var userObject = {
destination:"Lake",
expertise: "Expert",
hire:"No",
lessons:"Yes",
};
</code>```

then compare all the values to the corresponding keys in the objects in the array below, checking for equality. -

```<code>let locationArry = [
{ name :'Joss Bay Surf School',
  destination :'sea',
  hire: 'yes',
  lessons :'yes',
  expertise : 'beginner',
  website : 'https://www.jossbay.co.uk/'},

{ name :'Canoe Wild',
  destination :'lake',
  hire: 'yes',
  lessons :'yes',
  expertise : 'beginner',
  website : 'https://www.canoewild.co.uk/courses-lessons'},

  { name :'Paddleboarding London',
  destination :'lake',
  hire: 'yes',
  lessons :'yes',
  expertise : 'beginner',
  website : 'https://paddleboardinglondon.co.uk/'},
  ]
</code>```

finally returning the name value of the objects that have equality in destination, hire, lessons and expertise.

I've tried a few methods.

the latest which i think is still way off is

```<code>let userResult = locationArry.filter(destName=>{
if (locationArry.destination === resultObject.destination &&
locationArry.hire === resultObject.hire &&
locationArry.lessons === resultObject.lessons &&
locationArry.expertise === resultObject.expertise);
return destName.name;
})
</code>```

My gut is some sort of loop using filter()... but im at a bit of a loss.  I've not found a similar question specifically covering this so hoping someone can help me.

Body:
I'm new to Javascript and I'm working on a project but am stuck.

I have a singular object that has been user generated based on a questionnaire and I now want to compare the value data to the data in the matching keys in multiple objects that's in an array.

ie user object is

var userObject = {
destination:"Lake",
expertise: "Expert",
hire:"No",
lessons:"Yes",
};

then compare all the values to the corresponding keys in the objects in the array below, checking for equality. -

let locationArry = [
{ name :'Joss Bay Surf School',
  destination :'sea',
  hire: 'yes',
  lessons :'yes',
  expertise : 'beginner',
  website : 'https://www.jossbay.co.uk/'},

{ name :'Canoe Wild',
  destination :'lake',
  hire: 'yes',
  lessons :'yes',
  expertise : 'beginner',
  website : 'https://www.canoewild.co.uk/courses-lessons'},

  { name :'Paddleboarding London',
  destination :'lake',
  hire: 'yes',
  lessons :'yes',
  expertise : 'beginner',
  website : 'https://paddleboardinglondon.co.uk/'},
  ]

finally returning the name value of the objects that have equality in destination, hire, lessons and expertise.

I've tried a few methods.

the latest which i think is still way off is

let userResult = locationArry.filter(destName=>{
if (locationArry.destination === resultObject.destination &&
locationArry.hire === resultObject.hire &&
locationArry.lessons === resultObject.lessons &&
locationArry.expertise === resultObject.expertise);
return destName.name;
})

My gut is some sort of loop using filter()... but im at a bit of a loss.  I've not found a similar question specifically covering this so hoping someone can help me.


问:
How do I filter data using radio buttons on a Folium Map?
I was wondering how to add radio buttons to only select specific data to appear on a Folium Graph (basically be able to filter by the 'key' column in the data frame).

Here's what I currently have:

```<code>
!pip install geopandas
import numpy as np
import pandas as pd
import geopandas as gpd
!pip install folium
import folium
from folium import plugins
import datetime
import geopy

from IPython.display import HTML, display

from folium.plugins import TimestampedGeoJson

###Importing the data as Pandas DataFrame

fp = '/content/query.csv'
eartt1=pd.read_csv(fp)

Changing time to datetime
eartt1['time']=eartt1['time'], dayfirst=True)
eartt1['time']=pd.to_datetime(eartt1['time'])
###Time as the data frame's index
###Create a new column called "type" to help us in the pivoting

eartt1=eartt1.set_index('time')
eartt1['type']= 'ss'
eartt1.head(1)
###List number of earquakes by place, time, location, key

start = eartt1.pivot_table('id',
                          index = ['place', 'time',
                                   'latitude',
                                   'longitude',
                                   'key'
                                   ],
                          columns = 'type',
                          aggfunc='count').reset_index()

###Extract the hour from time_hour
start['time_hh']=start['time'].dt.hour

def create_geojson_features(df):
    features = []

    for _, row in df.iterrows():
        feature = {
            'type': 'Feature',
            'geometry': {
                'type':'Point',
                'coordinates':[row['longitude'],row['latitude']]
            },
            'properties': {
                'key': row['key'],
                'time': pd.to_datetime(row['time_hh'], unit='h').__str__(),
                'style': {'color' : ''},
                'icon': 'circle',
                'iconstyle':{
                    'fillColor': row['fillcolor'],
                    'fillOpacity': 0.8,
                    'stroke': 'true',
                }
            }
        }
        features.append(feature)
    return features

###Calling the Function create_geojson_features and using it in our data frame and get the geojson
start_geojson = create_geojson_features(start)

EQ_map = folium.Map(location = [2, -2],
                    tiles = "CartoDB Positron",
                    zoom_start = 2)
plugins.ScrollZoomToggler().add_to(EQ_map)

plugins.Fullscreen(
    position="topright",
    title="Expand me",
    title_cancel="Exit me",
    force_separate_button=True,
).add_to(EQ_map)

TimestampedGeoJson(start_geojson,
                  period = 'PT1H',
                  duration = 'PT1H',
                  transition_time = 1000,
                  auto_play = True).add_to(EQ_map)

EQ_map

</code>```

The original data frame resembles something like this:

```<code>    time.                 latitude.    longitude.    key.
    2022-11-07 09:30:03.  39.2345.     58.12942.     762346734
    2022-11-12 09:12:04.  32.1233.     45.28182.     612376322
    2022-11-15 09:19:40.  36.1287.     56.21387.     762346734
</code>```

I want the values in the key column to be displayed as radio buttons on the Map, so that I can filter by them, note that there are duplicate keys in the data.

I have come across FeatureGroup however I cannot figure out how to apply it to my current code.

Thanks

Body:
I was wondering how to add radio buttons to only select specific data to appear on a Folium Graph (basically be able to filter by the 'key' column in the data frame).

Here's what I currently have:

!pip install geopandas
import numpy as np
import pandas as pd
import geopandas as gpd
!pip install folium
import folium
from folium import plugins
import datetime
import geopy

from IPython.display import HTML, display

from folium.plugins import TimestampedGeoJson

###Importing the data as Pandas DataFrame

fp = '/content/query.csv'
eartt1=pd.read_csv(fp)

Changing time to datetime
eartt1['time']=eartt1['time'], dayfirst=True)
eartt1['time']=pd.to_datetime(eartt1['time'])
###Time as the data frame's index
###Create a new column called "type" to help us in the pivoting

eartt1=eartt1.set_index('time')
eartt1['type']= 'ss'
eartt1.head(1)
###List number of earquakes by place, time, location, key

start = eartt1.pivot_table('id',
                          index = ['place', 'time',
                                   'latitude',
                                   'longitude',
                                   'key'
                                   ],
                          columns = 'type',
                          aggfunc='count').reset_index()

###Extract the hour from time_hour
start['time_hh']=start['time'].dt.hour

def create_geojson_features(df):
    features = []

    for _, row in df.iterrows():
        feature = {
            'type': 'Feature',
            'geometry': {
                'type':'Point',
                'coordinates':[row['longitude'],row['latitude']]
            },
            'properties': {
                'key': row['key'],
                'time': pd.to_datetime(row['time_hh'], unit='h').__str__(),
                'style': {'color' : ''},
                'icon': 'circle',
                'iconstyle':{
                    'fillColor': row['fillcolor'],
                    'fillOpacity': 0.8,
                    'stroke': 'true',
                }
            }
        }
        features.append(feature)
    return features

###Calling the Function create_geojson_features and using it in our data frame and get the geojson
start_geojson = create_geojson_features(start)

EQ_map = folium.Map(location = [2, -2],
                    tiles = "CartoDB Positron",
                    zoom_start = 2)
plugins.ScrollZoomToggler().add_to(EQ_map)

plugins.Fullscreen(
    position="topright",
    title="Expand me",
    title_cancel="Exit me",
    force_separate_button=True,
).add_to(EQ_map)

TimestampedGeoJson(start_geojson,
                  period = 'PT1H',
                  duration = 'PT1H',
                  transition_time = 1000,
                  auto_play = True).add_to(EQ_map)

EQ_map

The original data frame resembles something like this:

    time.                 latitude.    longitude.    key.
    2022-11-07 09:30:03.  39.2345.     58.12942.     762346734
    2022-11-12 09:12:04.  32.1233.     45.28182.     612376322
    2022-11-15 09:19:40.  36.1287.     56.21387.     762346734

I want the values in the key column to be displayed as radio buttons on the Map, so that I can filter by them, note that there are duplicate keys in the data.

I have come across FeatureGroup however I cannot figure out how to apply it to my current code.

Thanks


问:
How to fix "The Rename refactoring cannot be applied in this context" with CPP in Netbeans
is there a solution to refactor CPP code using Apache NetBeans IDE 16 with MacOS ?
Right now if I select a variable then "Rename" from the "Refactor" menu I get this message:  "The Rename refactoring cannot be applied in this context", whatever kind of variable (local or global).

I'm a Netbeans user for years now with java, that's why I'm testing the tool for C++, but if that refactoring feature is not available for c++ I will change my mind for another IDE. Any suggestion ?  (I code for Arduino, and the Arduino IDE also does not provide refactoring).

Thanks


问:
Environment variables show undefined in React App
I have seen all posts on StackOverflow related to my problem statement. But none of them worked for me.
The following is my folder structure:

I have a variable named REACT_APP_API_URL=some value in the config.env file. In the App.js file I am trying to print out the variable console.log(process.env.REACT_APP_API_URL). But it continues to show undefined.