问:
Is there a way to consistently find ends of the Solidity functions in the corresponding EVM assembly?
I've been working on a project that analyzes EVM-assembly of Solidity smart contracts. Currently I am stuck with the problem of finding the endings of all the contract functions in the assembly. There is a bruteforce approach with simulating the EVM and simply tracking at what line the execution reaches the finish, but producing a complete EVM simulator is, I am afraid, well beyond my capabilities. I am searching for a simpler solution if there is one.

So far I've managed to (almost) consistenly find beginnings of the functions (corresponding JUMPDESTs) in the assembly assuming that I have access to the contract's ABI. The idea there is quite simple. At the top of the EVM assembly file there are multiple blocks looking as such:

```<code>PUSH4 0x8ac28d5a
GT
PUSH2 0x191
JUMPI
DUP1
</code>```

and also as such:

```<code>PUSH4 0xfeaf968c
EQ
PUSH2 0xc82
JUMPI
PUSH2 0x2f4
JUMP
JUMPDEST
DUP1
</code>```

Let's call them "header blocks" (if there is an official name, I am sorry for my illeteracy :) ). Each header block compares the hash of the method signature that came in the calldata and decides whether to jump on the JUMPDEST that corresponds to the beginning of the desired function. But there is a catch. As you can see, there is a GT at the top of the first header block. Why would we compare hashes with less/greater? So the header blocks do not perform a linear search over all the signatures. Instead, they do some kind of a logarithmic search as I deduced (please correct me if I am wrong). And, as we can see in the second header block, in some cases they can decide to unconditionally proceed somewhere else seemingly in the middle of the search process. But in reality, they just have enough information at that moment to infer that there is no function in this assembly that has the required hash of the signature. So we can deduce that those "else" JUMPs jump right to the fallback.

So this is the context of what I have done so far. I am able to obtain the list of the beginnings of all the functions including the fallback. Obtaining the list of the ends of the functions is what I am currently struggling with. So far I've had a hypothesis that I can split the whole assembly file by JUMPDESTs of the beginnings of functions (and the dispatch part with header blocks) and each part except the first will correspond to each Solidity function. Unfortunately, it can be easily disproven by looking at what is the assembly of a basic contract with only a couple of functions. You can experiment yourself at godbolt.org (a little example here). There will be a number of auxiliary "functions" created by the Solidity compiler. So my approach is not viable here. Are there any approaches of finding the endings of the functions without simulating the EVM?

Body:
I've been working on a project that analyzes EVM-assembly of Solidity smart contracts. Currently I am stuck with the problem of finding the endings of all the contract functions in the assembly. There is a bruteforce approach with simulating the EVM and simply tracking at what line the execution reaches the finish, but producing a complete EVM simulator is, I am afraid, well beyond my capabilities. I am searching for a simpler solution if there is one.

So far I've managed to (almost) consistenly find beginnings of the functions (corresponding JUMPDESTs) in the assembly assuming that I have access to the contract's ABI. The idea there is quite simple. At the top of the EVM assembly file there are multiple blocks looking as such:

PUSH4 0x8ac28d5a
GT
PUSH2 0x191
JUMPI
DUP1

and also as such:

PUSH4 0xfeaf968c
EQ
PUSH2 0xc82
JUMPI
PUSH2 0x2f4
JUMP
JUMPDEST
DUP1

Let's call them "header blocks" (if there is an official name, I am sorry for my illeteracy :) ). Each header block compares the hash of the method signature that came in the calldata and decides whether to jump on the JUMPDEST that corresponds to the beginning of the desired function. But there is a catch. As you can see, there is a GT at the top of the first header block. Why would we compare hashes with less/greater? So the header blocks do not perform a linear search over all the signatures. Instead, they do some kind of a logarithmic search as I deduced (please correct me if I am wrong). And, as we can see in the second header block, in some cases they can decide to unconditionally proceed somewhere else seemingly in the middle of the search process. But in reality, they just have enough information at that moment to infer that there is no function in this assembly that has the required hash of the signature. So we can deduce that those "else" JUMPs jump right to the fallback.

So this is the context of what I have done so far. I am able to obtain the list of the beginnings of all the functions including the fallback. Obtaining the list of the ends of the functions is what I am currently struggling with. So far I've had a hypothesis that I can split the whole assembly file by JUMPDESTs of the beginnings of functions (and the dispatch part with header blocks) and each part except the first will correspond to each Solidity function. Unfortunately, it can be easily disproven by looking at what is the assembly of a basic contract with only a couple of functions. You can experiment yourself at godbolt.org (a little example here). There will be a number of auxiliary "functions" created by the Solidity compiler. So my approach is not viable here. Are there any approaches of finding the endings of the functions without simulating the EVM?


来源: stackexchange

问:
Changing User Password PhpMyAdmin
I am unable to change my user password in phpMyAdmin. It appears to be hashed, but even when using a hash generator, the new password does not take.

After jumping into this in detail, I have discovered that (as of now) I am unable to change my user password. I have tried several different settings in the drop down menu next to the password field.

Has anyone run into this issue or have a solution?
enter image description here

ContentLicense: CC BY-SA 4.0

Title: Changing User Password PhpMyAdmin


问:
Why would a Python call to an sqllite3 database crash with only 'Killed' as an output
I'm trying to run some 3rd party code that attempts to read a database it has created. However, when I run this code, it crashes and only gives me the word Killed as output.

I inserted

```<code>import pdb
pdb_set_trace()
</code>```

Before the relevant section of the code:

```<code>db_name = mod_path / 'data/ais.db'
with sqlite3.connect(str(db_name)) as conn:
    c = conn.cursor()
    c.execute("SELECT name FROM sqlite_master "+
              "WHERE type='table' AND name='meta'")
</code>```

Which produced this output:

```<code>> /media/me/Fortress/bb/src/bb/data.py(316)download_data()
-> db_name = mod_path / 'data/ais.db'
(Pdb) n
> /media/me/Fortress/bb/src/bb/data.py(317)download_data()
-> with sqlite3.connect(str(db_name)) as conn:
(Pdb) n
> /media/me/Fortress/bb/src/bb/data.py(318)download_data()
-> c = conn.cursor()
(Pdb) conn
<sqlite3.Connection object at 0x7fa2f1e9d840>
(Pdb) n
> /media/me/Fortress/bb/src/bb/data.py(319)download_data()
-> c.execute("SELECT name FROM sqlite_master "+
(Pdb) c
Killed
</code>```

So, I know the issue is with the SELECT stmt, but I don't know much about datbases, so don't know what the next debugging step I should take is. Is there a problem I should check for in the database? Or something wrong with the SELECT stmt? Or something else entirely?

Body:
I'm trying to run some 3rd party code that attempts to read a database it has created. However, when I run this code, it crashes and only gives me the word Killed as output.

I inserted

import pdb
pdb_set_trace()

Before the relevant section of the code:

db_name = mod_path / 'data/ais.db'
with sqlite3.connect(str(db_name)) as conn:
    c = conn.cursor()
    c.execute("SELECT name FROM sqlite_master "+
              "WHERE type='table' AND name='meta'")

Which produced this output:

> /media/me/Fortress/bb/src/bb/data.py(316)download_data()
-> db_name = mod_path / 'data/ais.db'
(Pdb) n
> /media/me/Fortress/bb/src/bb/data.py(317)download_data()
-> with sqlite3.connect(str(db_name)) as conn:
(Pdb) n
> /media/me/Fortress/bb/src/bb/data.py(318)download_data()
-> c = conn.cursor()
(Pdb) conn
<sqlite3.Connection object at 0x7fa2f1e9d840>
(Pdb) n
> /media/me/Fortress/bb/src/bb/data.py(319)download_data()
-> c.execute("SELECT name FROM sqlite_master "+
(Pdb) c
Killed

So, I know the issue is with the SELECT stmt, but I don't know much about datbases, so don't know what the next debugging step I should take is. Is there a problem I should check for in the database? Or something wrong with the SELECT stmt? Or something else entirely?


问:
network issue during deploy with gitlab CI/CD pipeline
We have a Linux machine where the GitLab runner was installed. The GitLab pipeline itself is working fine, but the issue is with the deployment stage in the pipeline. After building the project inside the docker container, we then attempt to publish the build into a Nexus repository. But the Docker container is unable to resolve the Nexus repository URL. However, the Linux machine(where the Docker-Container/GitLab-runner running on) is able to resolve the nexus URL. The docker container is able to ping the Linux machine just fine.

How can I publish the build to the Nexus repository from the docker container?

Note: I currently don't have access to the GitLab runner configurations, so I'm unable to provide that info

Here is my gitlab-ci.yml look like

```<code>image: xxx/image:v2

before_script:
  - python --version

stages:
  - Static Analysis
  - build
  - deploy

pylint:
  stage: Static Analysis
  script:
  - pylint *.py
  only:
    - merge_requests
    - master
run build:
  stage: build
  only:
    - master
  script:
    - chmod +X package.sh && sh package.sh
  cache:
    untracked: true
    paths:
      - build/
run deploy:
  stage: deploy
  only:
    - master
  before_script:
    - echo 10.89.xx.xxx nexusxxx.com >> /etc/hosts
  script:
    - mvn --s settings.xml -Dsettings.security=settings-security.xml clean deploy -X
  cache:
    untracked: true

</code>```

Body:
We have a Linux machine where the GitLab runner was installed. The GitLab pipeline itself is working fine, but the issue is with the deployment stage in the pipeline. After building the project inside the docker container, we then attempt to publish the build into a Nexus repository. But the Docker container is unable to resolve the Nexus repository URL. However, the Linux machine(where the Docker-Container/GitLab-runner running on) is able to resolve the nexus URL. The docker container is able to ping the Linux machine just fine.

How can I publish the build to the Nexus repository from the docker container?

Note: I currently don't have access to the GitLab runner configurations, so I'm unable to provide that info

Here is my gitlab-ci.yml look like

image: xxx/image:v2

before_script:
  - python --version

stages:
  - Static Analysis
  - build
  - deploy

pylint:
  stage: Static Analysis
  script:
  - pylint *.py
  only:
    - merge_requests
    - master
run build:
  stage: build
  only:
    - master
  script:
    - chmod +X package.sh && sh package.sh
  cache:
    untracked: true
    paths:
      - build/
run deploy:
  stage: deploy
  only:
    - master
  before_script:
    - echo 10.89.xx.xxx nexusxxx.com >> /etc/hosts
  script:
    - mvn --s settings.xml -Dsettings.security=settings-security.xml clean deploy -X
  cache:
    untracked: true


问:
Can Encryption Scope be set for an Azure Storage Account using Java API
I am trying to encrypt Azure containers using dedicated keys from Key Vaults.
For example:

Storage Account -> Encryption Scope 1, Encryption Scope 2

Storage Account -> Container 1 (encrypted by Encryption Scope 1)

```<code>               Container 2 (encrypted by Encryption Scope 2)
</code>```

The encryption scope themselves are mapped to distinct key vault keys

I would need to implement this using the Azure Java API and have a sample code as follows:

```<code>    BlobContainerEncryptionScope encryptionScope = new BlobContainerEncryptionScope();
    encryptionScope.setDefaultEncryptionScope("datalakeencscope");

    BlobContainerClient blobContainerClient = blobContainerClientBuilder
            .connectionString(storageConnectString)
            .blobContainerEncryptionScope(encryptionScope)
            .containerName("data-lake-enc-container")
            .buildClient();
    blobContainerClient.create();
</code>```

What I am unable to figure out, is how to assign the encryption scope to the storage account using the Java API. Any code snippets or API reference would be greatly appreciated.

Body:
I am trying to encrypt Azure containers using dedicated keys from Key Vaults.
For example:

Storage Account -> Encryption Scope 1, Encryption Scope 2

Storage Account -> Container 1 (encrypted by Encryption Scope 1)

               Container 2 (encrypted by Encryption Scope 2)

The encryption scope themselves are mapped to distinct key vault keys

I would need to implement this using the Azure Java API and have a sample code as follows:

    BlobContainerEncryptionScope encryptionScope = new BlobContainerEncryptionScope();
    encryptionScope.setDefaultEncryptionScope("datalakeencscope");

    BlobContainerClient blobContainerClient = blobContainerClientBuilder
            .connectionString(storageConnectString)
            .blobContainerEncryptionScope(encryptionScope)
            .containerName("data-lake-enc-container")
            .buildClient();
    blobContainerClient.create();

What I am unable to figure out, is how to assign the encryption scope to the storage account using the Java API. Any code snippets or API reference would be greatly appreciated.


问:
Connecting to existing in-memory H2 from different application/process
I have a simple Quarkus application that uses an in-memory H2 database. The JDBC connection string has some custom settings: jdbc:h2:mem:quarkus_db;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1;MODE=MariaDB.

I'm trying to connect to the exact same database from a database manager — say DataGrip. After following the documentation, several answers from StackOverflow, and some blog posts, I'm still unable to connect to the same instance and query for any existing data using SQL.

There is something I don't fully understand from the examples. I've seen that initially using a connection like this in the application: jdbc:h2:mem:quarkus_db, and while the same it's up and running, then on the other application/process (DataGrip in my case) using jdbc:h2:tcp://localhost/mem:quarkus_db should work, but I fail to see how the first scheme will create a TCP server.

My goal is to verify some data while the application is running. I understand that when using something like jdbc:h2:mem:*, everything will be lost after the application stops.


问:
Customized kernal always dies in sagemaker jupyter lab?
I was able to create a customized kernel by using

conda create -n myenv python=3.8 -y

and the customized env myenv works fine in sagemaker terminal. However, when trying to use kernel myenv within a sagemaker notebook, the kernal was there but will almost always die (more than 90% of the time and by luck it will work) and returns to showing no kernel. This happens for whatever simple python command I tried to run in a notebook cell. WTF is sagemaker doing that can't even work with such a trivial functionality?


问:
LocalizedStringResource with Formatter in AppIntent
I am trying to use DateComponentsFormatter() with my AppIntent, but I can not find a way to localize the formatter string with the same language that LocalizedStringResource use...

Example (My App: Arabic, Device: English, Siri: English)

```<code>let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .full
    formatter.maximumUnitCount = 2
    formatter.allowedUnits = [.hour, .minute]
    formatter.includesTimeRemainingPhrase = true

let relativeDate = formatter.string(from: .now, to: nextEvent.date) ?? ""

     return .result(
            value: value,
            dialog: "intent_current_event\(relativeDate)"
          )
</code>```

The result is: Next event  متبقي 4 ساعات و 5 دقائق

The relativeDate is in Arabic (App Language) and the "intent_current_event%@" localized in English (Siri Language)

Can anyone please help me to use the Formatter and get it to localized the same local as LocalizedStringResource.

Body:
I am trying to use DateComponentsFormatter() with my AppIntent, but I can not find a way to localize the formatter string with the same language that LocalizedStringResource use...

Example (My App: Arabic, Device: English, Siri: English)

let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .full
    formatter.maximumUnitCount = 2
    formatter.allowedUnits = [.hour, .minute]
    formatter.includesTimeRemainingPhrase = true

let relativeDate = formatter.string(from: .now, to: nextEvent.date) ?? ""

     return .result(
            value: value,
            dialog: "intent_current_event\(relativeDate)"
          )

The result is: Next event  متبقي 4 ساعات و 5 دقائق

The relativeDate is in Arabic (App Language) and the "intent_current_event%@" localized in English (Siri Language)

Can anyone please help me to use the Formatter and get it to localized the same local as LocalizedStringResource.


问:
How to implement style based recalibration module (SRM) - Attention mechanism
I am using pre-trained VGG16 and applying style based recalibration module (SRM) after the last-fully connected layer, but it doesn't work. Could you please explain to me what I'm not doing right? I've attached my code below for reference:

```<code>import tensorflow as tf
def SRM_block(x, channels, use_bias=False, is_training=True, scope='srm_block'):
    with tf.compat.v1.variable_scope(scope) :
        bs, h, w, c = x.get_shape().as_list() # c = channels

        x = tf.reshape(x, shape=[bs, -1, c]) # [bs, h*w, c]

        x_mean, x_var = tf.nn.moments(x, axes=1, keep_dims=True) # [bs, 1, c]
        x_std = tf.sqrt(x_var + 1e-5)

        t = tf.concat([x_mean, x_std], axis=1) # [bs, 2, c]

        z = tf.layers.conv1d(t, channels, kernel_size=2, strides=1, use_bias=use_bias)
        z = tf.layers.batch_normalization(z, momentum=0.9, epsilon=1e-05, center=True, scale=True,        training=is_training, name=scope)
        z = tf.contrib.layers.batch_norm(z, decay=0.9, epsilon=1e-05, center=True, scale=True, updates_collections=None, is_training=is_training, scope=scope)

        g = tf.sigmoid(z)

        x = tf.reshape(x * g, shape=[bs, h, w, c])

        return x
</code>```

Pretrained Model

```<code>vgg16_model = VGG16(include_top=False, input_shape=(SIZE,SIZE,3), weights='imagenet')
vgg16_model.trainable = False # Freeze the Weights
</code>```

Adding custom Layers

```<code>x = vgg16_model.output
x = SRM_block (x,512)
x = GlobalAveragePooling2D()(x)
x = Dense(256, activation="relu")(x)
x = Dropout(0.2)(x)
predictions = Dense(NUM_CLASSES, activation="softmax")(x)
</code>```

The error:

```<code>TypeError: Exception encountered when calling layer "tf.reshape" (type TFOpLambda).

Failed to convert elements of \[None, -1, 512\] to Tensor. Consider casting elements to a supported type. See https://www.tensorflow.org/api_docs/python/tf/dtypes for supported TF dtypes.

Call arguments received by layer `"tf.reshape" (type TFOpLambda): • tensor=tf.Tensor(shape=(None, 7, 7, 512), dtype=float32) • shape=\['None', '-1', '512'\] • name=None`
</code>```

Body:
I am using pre-trained VGG16 and applying style based recalibration module (SRM) after the last-fully connected layer, but it doesn't work. Could you please explain to me what I'm not doing right? I've attached my code below for reference:

import tensorflow as tf
def SRM_block(x, channels, use_bias=False, is_training=True, scope='srm_block'):
    with tf.compat.v1.variable_scope(scope) :
        bs, h, w, c = x.get_shape().as_list() # c = channels

        x = tf.reshape(x, shape=[bs, -1, c]) # [bs, h*w, c]

        x_mean, x_var = tf.nn.moments(x, axes=1, keep_dims=True) # [bs, 1, c]
        x_std = tf.sqrt(x_var + 1e-5)

        t = tf.concat([x_mean, x_std], axis=1) # [bs, 2, c]

        z = tf.layers.conv1d(t, channels, kernel_size=2, strides=1, use_bias=use_bias)
        z = tf.layers.batch_normalization(z, momentum=0.9, epsilon=1e-05, center=True, scale=True,        training=is_training, name=scope)
        z = tf.contrib.layers.batch_norm(z, decay=0.9, epsilon=1e-05, center=True, scale=True, updates_collections=None, is_training=is_training, scope=scope)

        g = tf.sigmoid(z)

        x = tf.reshape(x * g, shape=[bs, h, w, c])

        return x

Pretrained Model

vgg16_model = VGG16(include_top=False, input_shape=(SIZE,SIZE,3), weights='imagenet')
vgg16_model.trainable = False # Freeze the Weights

Adding custom Layers

x = vgg16_model.output
x = SRM_block (x,512)
x = GlobalAveragePooling2D()(x)
x = Dense(256, activation="relu")(x)
x = Dropout(0.2)(x)
predictions = Dense(NUM_CLASSES, activation="softmax")(x)

The error:

TypeError: Exception encountered when calling layer "tf.reshape" (type TFOpLambda).

Failed to convert elements of \[None, -1, 512\] to Tensor. Consider casting elements to a supported type. See https://www.tensorflow.org/api_docs/python/tf/dtypes for supported TF dtypes.

Call arguments received by layer `"tf.reshape" (type TFOpLambda): • tensor=tf.Tensor(shape=(None, 7, 7, 512), dtype=float32) • shape=\['None', '-1', '512'\] • name=None`


问:
R processes xml, if a node is missing then NA
Example input xml file is here

For each input file, there is at least 1 primary (<primary_outcome>) and secondary outcome (<secondary_outcome>).

For each primary or secondary outcome, there are 3 components: (1) <measure>, (2) <time_frame>, and (3) <description>.

My goal is to extract these 3 components for each primary and secondary outcome, then assemble them to make a dataframe and then output as an Excel file. My R code is:

```<code>library(xml2)
library(XML)
library(tidyverse)
library(stringr)

x <- "path/NCT04494256.xml"
y <- read_xml(x)

## Primary outcomes
    pri_out_measure = xml_text(xml_find_all(y, "./primary_outcome/measure"))

    pri_out_time = xml_text(xml_find_all(y, "./primary_outcome/time_frame"))

    pri_out_desc = xml_text(xml_find_all(y, "./primary_outcome/description"))

## Secondary outcomes
    sec_out_measure = xml_text(xml_find_all(y, "./secondary_outcome/measure"))

    sec_out_time = xml_text(xml_find_all(y, "./secondary_outcome/time_frame"))

    sec_out_desc = xml_text(xml_find_all(y, "./secondary_outcome/description"))

data = cbind(pri_out_measure,
             pri_out_time,
             pri_out_desc,

             sec_out_measure,
             sec_out_time,
             sec_out_desc) %>% as.data.frame()
</code>```

The problem is that in this example input xml file, only 3 of the 17 secondary outcomes have descriptions (here is the webpage corresponding to this example xml file, and you can see that under Secondary Outcome Measures, only #13, 14, 15 have descriptions).

As a result, the dataframe that I created looks like this:

```<code>secondary_outcome_1  secondary_outcome_1_time_frame  secondary_outcome_13_description
secondary_outcome_2  secondary_outcome_2_time_frame  secondary_outcome_14_description
secondary_outcome_3  secondary_outcome_3_time_frame  secondary_outcome_15_description
secondary_outcome_4  secondary_outcome_4_time_frame  NA
</code>```

While in reality, I would like to have a dataframe that looks like this:

```<code>secondary_outcome_1  secondary_outcome_1_time_frame  NA
secondary_outcome_2  secondary_outcome_2_time_frame  NA
secondary_outcome_3  secondary_outcome_3_time_frame  NA
.
.
.
secondary_outcome_13  secondary_outcome_13_time_frame  secondary_outcome_13_description
secondary_outcome_14  secondary_outcome_14_time_frame  secondary_outcome_14_description
secondary_outcome_15  secondary_outcome_15_time_frame  secondary_outcome_15_description
secondary_outcome_16  secondary_outcome_16_time_frame  NA
secondary_outcome_17  secondary_outcome_17_time_frame  NA
</code>```

Body:
Example input xml file is here

For each input file, there is at least 1 primary (<primary_outcome>) and secondary outcome (<secondary_outcome>).

For each primary or secondary outcome, there are 3 components: (1) <measure>, (2) <time_frame>, and (3) <description>.

My goal is to extract these 3 components for each primary and secondary outcome, then assemble them to make a dataframe and then output as an Excel file. My R code is:

library(xml2)
library(XML)
library(tidyverse)
library(stringr)

x <- "path/NCT04494256.xml"
y <- read_xml(x)

## Primary outcomes
    pri_out_measure = xml_text(xml_find_all(y, "./primary_outcome/measure"))

    pri_out_time = xml_text(xml_find_all(y, "./primary_outcome/time_frame"))

    pri_out_desc = xml_text(xml_find_all(y, "./primary_outcome/description"))

## Secondary outcomes
    sec_out_measure = xml_text(xml_find_all(y, "./secondary_outcome/measure"))

    sec_out_time = xml_text(xml_find_all(y, "./secondary_outcome/time_frame"))

    sec_out_desc = xml_text(xml_find_all(y, "./secondary_outcome/description"))

data = cbind(pri_out_measure,
             pri_out_time,
             pri_out_desc,

             sec_out_measure,
             sec_out_time,
             sec_out_desc) %>% as.data.frame()

The problem is that in this example input xml file, only 3 of the 17 secondary outcomes have descriptions (here is the webpage corresponding to this example xml file, and you can see that under Secondary Outcome Measures, only #13, 14, 15 have descriptions).

As a result, the dataframe that I created looks like this:

secondary_outcome_1  secondary_outcome_1_time_frame  secondary_outcome_13_description
secondary_outcome_2  secondary_outcome_2_time_frame  secondary_outcome_14_description
secondary_outcome_3  secondary_outcome_3_time_frame  secondary_outcome_15_description
secondary_outcome_4  secondary_outcome_4_time_frame  NA

While in reality, I would like to have a dataframe that looks like this:

secondary_outcome_1  secondary_outcome_1_time_frame  NA
secondary_outcome_2  secondary_outcome_2_time_frame  NA
secondary_outcome_3  secondary_outcome_3_time_frame  NA
.
.
.
secondary_outcome_13  secondary_outcome_13_time_frame  secondary_outcome_13_description
secondary_outcome_14  secondary_outcome_14_time_frame  secondary_outcome_14_description
secondary_outcome_15  secondary_outcome_15_time_frame  secondary_outcome_15_description
secondary_outcome_16  secondary_outcome_16_time_frame  NA
secondary_outcome_17  secondary_outcome_17_time_frame  NA


问:
Get user input for categorical data for predictive modeling
I am building a predictive regression model that will predict movie revenue based on different features of the film. I have trained the model but I now need to get user input for the different features which will then be put into the model to return a predicted revenue. Most of these features are categorical so I used one hot encoding when training it. My question is: How do I intake categorical data from the user and apply one hot encoding on that. This is what I've done so far:

```<code>notOver = True
while(notOver):
    user_movie = input("Enter the name of your movie: ")
    user_genre = input("What is the genre of your movie? ")
    user_budget = input("What is your movie's budget? ")
    user_runtime = input("What is your movie's runtime? ")
    user_studio = input("Who is your studio partner? ")
    user_director = input("Who is the director of your movie? ")
    user_writer = input("Who is your movie's writer? ")
    user_rating = input("What is your movie's rating?")

    user_ohe = ["user_genre", "user_studio", "user_director", "user_writer"]
    user_ohe = np.array(user_ohe)
    transformer_ohe = OneHotEncoder(handle_unknown="ignore")
    user_num = ["user_budget", "user_runtime"]
    user_num = np.array(user_num)

    preprocessor = ColumnTransformer(transformers=[("cat", transformer_ohe, user_ohe)])

    steps = Pipeline(steps = [('preprocessor',preprocessor), ('classifier',Ridge())])
    steps.fit(user_ohe.reshape(-1,1), user_num.reshape(-1,1))
    notOver = False
</code>```

However, this doesn't work since while it might one hot encode each input, it doesn't have information about the others in that category. For example when training, there are thousands of studio partners. If the input is "A24", it'll set is_A24 = 1, but how will it know to set the other studios = 0?

I was told maybe pandas series might help but I've never used that so I'm not sure how to do it.

This is what the data I trained on looks like:

Body:
I am building a predictive regression model that will predict movie revenue based on different features of the film. I have trained the model but I now need to get user input for the different features which will then be put into the model to return a predicted revenue. Most of these features are categorical so I used one hot encoding when training it. My question is: How do I intake categorical data from the user and apply one hot encoding on that. This is what I've done so far:

notOver = True
while(notOver):
    user_movie = input("Enter the name of your movie: ")
    user_genre = input("What is the genre of your movie? ")
    user_budget = input("What is your movie's budget? ")
    user_runtime = input("What is your movie's runtime? ")
    user_studio = input("Who is your studio partner? ")
    user_director = input("Who is the director of your movie? ")
    user_writer = input("Who is your movie's writer? ")
    user_rating = input("What is your movie's rating?")

    user_ohe = ["user_genre", "user_studio", "user_director", "user_writer"]
    user_ohe = np.array(user_ohe)
    transformer_ohe = OneHotEncoder(handle_unknown="ignore")
    user_num = ["user_budget", "user_runtime"]
    user_num = np.array(user_num)

    preprocessor = ColumnTransformer(transformers=[("cat", transformer_ohe, user_ohe)])

    steps = Pipeline(steps = [('preprocessor',preprocessor), ('classifier',Ridge())])
    steps.fit(user_ohe.reshape(-1,1), user_num.reshape(-1,1))
    notOver = False

However, this doesn't work since while it might one hot encode each input, it doesn't have information about the others in that category. For example when training, there are thousands of studio partners. If the input is "A24", it'll set is_A24 = 1, but how will it know to set the other studios = 0?

I was told maybe pandas series might help but I've never used that so I'm not sure how to do it.

This is what the data I trained on looks like:


问:
Is there a hardcoded Avalonia UI Grid.Row max?
A student of mine is using Avalonia UI for a C# project.  I don't have access to the actual code yet, but have read over it with them.

The code uses

```<code><Grid>
     <TextBlock Grid.Row=0>1</TextBlock>
     <TextBlock Grid.Row=1>2</TextBlock>
     <TextBlock Grid.Row=2>3</TextBlock>
     <TextBlock Grid.Row=3>4</TextBlock>
</Grid>
</code>```

At grid row 3 it says the max is 0-2. Is there a place to change this?  I can't find it in the API or anyone asking about this online.

Looked through the guides and API documentation.  I didn't see anything specific on this.  Except that all of the examples we find are for only 3 rows.
Avalonia Docs - Grid

Body:
A student of mine is using Avalonia UI for a C# project.  I don't have access to the actual code yet, but have read over it with them.

The code uses

<Grid>
     <TextBlock Grid.Row=0>1</TextBlock>
     <TextBlock Grid.Row=1>2</TextBlock>
     <TextBlock Grid.Row=2>3</TextBlock>
     <TextBlock Grid.Row=3>4</TextBlock>
</Grid>

At grid row 3 it says the max is 0-2. Is there a place to change this?  I can't find it in the API or anyone asking about this online.

Looked through the guides and API documentation.  I didn't see anything specific on this.  Except that all of the examples we find are for only 3 rows.
Avalonia Docs - Grid


问:
css grid: centerin column/row
I'm trying to create a simple css grid using the native CSS Grid properties.

I really don't understand why this doesn't go in the middle (main axis) on the display.
What is wrong with it? Does anyone have any ideas?
Thanks

```<code><body>
    <div class="container">
        <div class="pic">pic</div>
        <div class="headline">headline</div>
        <div class="text">text</div>
    </div>

</body>
</code>```

```<code>* {
    margin: 2px;
    padding: 0px;
    box-sizing: border-box;
}

body {
    background-color: antiquewhite;
}

.container {
    height: 100vh auto;
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: auto 1fr 1fr;
    justify-content: center;
    place-items: center;
    gap: 3px;
}

.pic {
    border: 2px sandybrown solid;
    background-color: #fff;
}
.headline {
    border: 2px sandybrown solid;
    background-color: #fff;
}
.text {
    border: 2px sandybrown solid;
    background-color: #fff;
}
</code>```

type here

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

Title: css grid: centerin column/row

Body:
I'm trying to create a simple css grid using the native CSS Grid properties.

I really don't understand why this doesn't go in the middle (main axis) on the display.
What is wrong with it? Does anyone have any ideas?
Thanks

pic

headline

text

* {
    margin: 2px;
    padding: 0px;
    box-sizing: border-box;
}

body {
    background-color: antiquewhite;
}

.container {
    height: 100vh auto;
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: auto 1fr 1fr;
    justify-content: center;
    place-items: center;
    gap: 3px;
}

.pic {
    border: 2px sandybrown solid;
    background-color: #fff;
}
.headline {
    border: 2px sandybrown solid;
    background-color: #fff;
}
.text {
    border: 2px sandybrown solid;
    background-color: #fff;
}

type here


问:
Is this approach secure enough to store OAuth tokens?
I'm building a Node app utilizing the Twitch OAuth API and I need to store the user's access and refresh tokens. I did some Google research and mostly followed the Nest.js docs (since I'm using Nest).

This is the code to encrypt the tokens. IV and salt are created beforehand (using crypto.randomBytes(16)) and passed as parameters.

const key = (await promisify(scrypt)(process.env['CRYPT_PW'], salt, 32)) as Buffer,
    cipher = createCipheriv('aes-256-ctr', key, iv);

return Buffer.concat([
    cipher.update(token),
    cipher.final(),
]);
```

The CRYPT_PW is stored in an environment variable, IV and salt are stored alongside with the respective users keys in the DB. Is this secure enough to store OAuth tokens? If not, what do I need to change? Thanks!

Body:
I'm building a Node app utilizing the Twitch OAuth API and I need to store the user's access and refresh tokens. I did some Google research and mostly followed the Nest.js docs (since I'm using Nest).

This is the code to encrypt the tokens. IV and salt are created beforehand (using crypto.randomBytes(16)) and passed as parameters.

const key = (await promisify(scrypt)(process.env['CRYPT_PW'], salt, 32)) as Buffer,
    cipher = createCipheriv('aes-256-ctr', key, iv);

return Buffer.concat([
    cipher.update(token),
    cipher.final(),
]);

The CRYPT_PW is stored in an environment variable, IV and salt are stored alongside with the respective users keys in the DB. Is this secure enough to store OAuth tokens? If not, what do I need to change? Thanks!


问:
Youtube Data API 403 forbidden after numerous successful thumbnails.set() calls
```<code>def update_thumbnail_on_youtube(video, path):
    try:
        request = youtube.thumbnails().set(videoId=video['id'], alt="media", media_body=MediaFileUpload(path))
        response = request.execute()
        print(response)
    except Exception as e:
        raise(e)
    finally:
        os.remove(path)
</code>```

this works fine. i'll give a list of videos from my own youtube playlist, auth, and path is a local image file. after a hundred if these updates it'll throw 403

typically wait a day and it fixes? maybe? doesnt say what the deal is in the documentation.

403 is as follows

```<code>b'{\n "error": {\n "code": 403,\n "message": "The caller does not have permission",\n "errors": [\n {\n "message": "The caller does not have permission",\n "domain": "global",\n "reason": "forbidden"\n }\n ],\n "status": "PERMISSION_DENIED"\n }\n}\n'
</code>```

edit: it does start working after around 24 hours. guys at youtube/google, bros, just let me know i'm being limited instead of having me pull my f8ckin hair out. imagine a world...

Body:
def update_thumbnail_on_youtube(video, path):
    try:
        request = youtube.thumbnails().set(videoId=video['id'], alt="media", media_body=MediaFileUpload(path))
        response = request.execute()
        print(response)
    except Exception as e:
        raise(e)
    finally:
        os.remove(path)

this works fine. i'll give a list of videos from my own youtube playlist, auth, and path is a local image file. after a hundred if these updates it'll throw 403

typically wait a day and it fixes? maybe? doesnt say what the deal is in the documentation.

403 is as follows

b'{\n "error": {\n "code": 403,\n "message": "The caller does not have permission",\n "errors": [\n {\n "message": "The caller does not have permission",\n "domain": "global",\n "reason": "forbidden"\n }\n ],\n "status": "PERMISSION_DENIED"\n }\n}\n'

edit: it does start working after around 24 hours. guys at youtube/google, bros, just let me know i'm being limited instead of having me pull my f8ckin hair out. imagine a world...


问:
How to calculate centrality with weight using igraph in Python
I'm using igraph to calcualate centrality measures for a large undirected network. I have a set of vertices with weights added as an attribute.

G.vs["weight"] = weight_list

I'd like to calculate centrality scores with weights.
To calculate the betweenness score, I used the below function:

```<code>G.betweenness(directed = False,  weights = 'weight')
</code>```

However, I got this error:

Could anyone kindly help?

Body:
I'm using igraph to calcualate centrality measures for a large undirected network. I have a set of vertices with weights added as an attribute.

G.vs["weight"] = weight_list

I'd like to calculate centrality scores with weights.
To calculate the betweenness score, I used the below function:

G.betweenness(directed = False,  weights = 'weight')

However, I got this error:

Could anyone kindly help?


问:
After removing DOM element from child component when refreshing props gets error
CODE

https://github.com/bostonmacosx/MTBCRM/tree/main/mtbcrm_react/src/components

PARENT COMPONENT: MainScreen

Child Components: Userlist on the left and People next to it.

I have a list which when clicked sends the information to the child components.

When I then click on the X I run a javascript routine in the child component which removes the phone number from the database which works fine....

When I go to click on one of the names in the List....which run the get userDetails in the MainScreen component and updates the props for the people component I get

Not sure why the react app is erroring out at this piont. It was fine until I removed the phone number DIV with javascript after clicking the "X"

Not sure why.


问:
Sample Xamarin.Forms Project Without Using XAML
Late to the party and new to Xamarin.Forms.  I'm looking for an example Xamarin.Forms app (sample code) which does not use any XAML, or, as little as possible.  This is because I'm translating from an existing C# project where all of the user interface elements are built in code.

The existing project has two what would be called "forms": a splash form, and an application form.  The structure of the application form changes dynamically - for example, depending on the GPS coordinates of the user at start-up, hence the dynamic building of the form.

The two "forms" exist as independent classes extending ContentPage and using AbsoluteLayout.  My difficulty boils down to how to get the splash screen to display at start-up, and then, after determining what my application form should look like and establishing its structure, hiding the splash form and showing the application form.

The building of the splash and application interfaces already take into account scaling for display size and orientation.

We have googled around a fair bit on this end but apparently we're not googling the right thing.


问:
send array list of objects as part in multipart
I want to send the arraylist of objects answer with multipart request,
this is the form data that i should send :

```<code>{
    "title"        : "title",
    "description"  : "description",
    "file"         : "0",
    "type"         : 0,
    "question"     : "question",
    "points_number": 3,
    "exam_id"      : 3,
    "answers"      : [
         {
        "title"    : "title",
        "status"   : 0
    },
     {
        "title"    : "title2",
        "status"   : 1
    }
    ]
}
</code>```

this my retrofit request

```<code>@Multipart
@JvmSuppressWildcards
@POST("teacher/exams/questions/store-question")
suspend fun storeQuestionTeacher(
    @Header("Authorization") Authorization: String,
    @Header("lang") lang: String,
    @Part("answers[]") answers: ArrayList<Map<String,Any>>,
    @PartMap createQuestionBody: Map<String, RequestBody>,
    @Part file: MultipartBody.Part,
): Response<TeacherMainResponse<Any>>
</code>```

this what i send with this request

I want send the answers array in multipart request
as shown above.

Body:
I want to send the arraylist of objects answer with multipart request,
this is the form data that i should send :

{
    "title"        : "title",
    "description"  : "description",
    "file"         : "0",
    "type"         : 0,
    "question"     : "question",
    "points_number": 3,
    "exam_id"      : 3,
    "answers"      : [
         {
        "title"    : "title",
        "status"   : 0
    },
     {
        "title"    : "title2",
        "status"   : 1
    }
    ]
}

this my retrofit request

@Multipart
@JvmSuppressWildcards
@POST("teacher/exams/questions/store-question")
suspend fun storeQuestionTeacher(
    @Header("Authorization") Authorization: String,
    @Header("lang") lang: String,
    @Part("answers[]") answers: ArrayList<Map<String,Any>>,
    @PartMap createQuestionBody: Map<String, RequestBody>,
    @Part file: MultipartBody.Part,
): Response<TeacherMainResponse<Any>>

this what i send with this request

I want send the answers array in multipart request
as shown above.


问:
Javascript API connection to Notion database not right
I'm not a developer but am trying to connect data entered into a Notion database with an Equals spreadsheet. I've written a preliminary connection by using help from Chat GPT 3 but something's not right. Can someone please help?

Here is what I have:

```<code>const equals = require("equals");
const axios = require("axios");

const API_KEY = equals.getSecret("notion_api_key"); // Replace with your Notion API key
const TABLE_ID = equals.getSecret("notion_table_id"); // Replace with the ID of your Notion table

const getRecords = async () => {
  const resp = await axios({
    method: "post",
    url: "https://api.notion.com/v3/query",
    data: {
      query: `{
        table(id: "${TABLE_ID}") {
          name
          columns {
            name
            type
          }
          rows {
            id
            cells {
              value {
                ... on Text {
                  text
                }
                ... on RichText {
                  text
                }
                ... on Checkbox {
                  checked
                }
                ... on MultiSelect {
                  options {
                    text
                  }
                }
                ... on Date {
                  start
                }
              }
            }
          }
        }
      }`,
    },
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
  });
  return resp.data.results[0].table.rows;
};

const records = await getRecords();

// Add the table column names as headers
const headers = records[0].cells.map((cell) => cell.value.name);
equals.addHeaders(headers);

// Add the table rows as rows in the Equals sheet
for (const record of records) {
  const row = record.cells.map((cell) => {
    switch (cell.value.type) {
      case "text":
        return cell.value.text;
      case "rich_text":
        return cell.value.text;
      case "checkbox":
        return cell.value.checked;
      case "multi_select":
        return cell.value.options.map((option) => option.text).join(", ");
      case "date":
        return cell.value.start;
      default:
        return null;
    }
  });
  equals.addRow(row);
}
</code>```

I also wanted to include a quick example I wrote that brings data from Airtable into Equals, just as a comparison:

```<code>const equals = require("equals");
const axios = require("axios");

const API_KEY = equals.getSecret("airtable_api_key");
const BASE_ID = equals.getSecret("airtable_base_id");
const TABLE_NAME = "Issues";
const MAX_RECORDS = 100;

const getRecords = async () => {
  const resp = await axios({
    method: "get",
    url: `https://api.airtable.com/v0/${BASE_ID}/${TABLE_NAME}`,
    params: {
      maxRecords: MAX_RECORDS,
      view: "Grid view"
    },
    headers: {
      Authorization: `Bearer ${API_KEY}`
    }
  });
  return resp.data.records;
}

const records = await getRecords();

equals.addHeaders(["number", "title", "user", "state", "closed at", "created at"]);

for(const record of records) {
  equals.addRow([
    record.fields.number,
    record.fields.title,
    record.fields.user,
    record.fields.state,
    record.fields.closed_at,
    record.fields.created_at
  ])
}
</code>```

I would love to see the data from my Notion table appear in my Equals spreadsheet, so that I can make a more complex analysis off of the inputs in my Notion board.

Body:
I'm not a developer but am trying to connect data entered into a Notion database with an Equals spreadsheet. I've written a preliminary connection by using help from Chat GPT 3 but something's not right. Can someone please help?

Here is what I have:

const equals = require("equals");
const axios = require("axios");

const API_KEY = equals.getSecret("notion_api_key"); // Replace with your Notion API key
const TABLE_ID = equals.getSecret("notion_table_id"); // Replace with the ID of your Notion table

const getRecords = async () => {
  const resp = await axios({
    method: "post",
    url: "https://api.notion.com/v3/query",
    data: {
      query: `{
        table(id: "${TABLE_ID}") {
          name
          columns {
            name
            type
          }
          rows {
            id
            cells {
              value {
                ... on Text {
                  text
                }
                ... on RichText {
                  text
                }
                ... on Checkbox {
                  checked
                }
                ... on MultiSelect {
                  options {
                    text
                  }
                }
                ... on Date {
                  start
                }
              }
            }
          }
        }
      }`,
    },
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
  });
  return resp.data.results[0].table.rows;
};

const records = await getRecords();

// Add the table column names as headers
const headers = records[0].cells.map((cell) => cell.value.name);
equals.addHeaders(headers);

// Add the table rows as rows in the Equals sheet
for (const record of records) {
  const row = record.cells.map((cell) => {
    switch (cell.value.type) {
      case "text":
        return cell.value.text;
      case "rich_text":
        return cell.value.text;
      case "checkbox":
        return cell.value.checked;
      case "multi_select":
        return cell.value.options.map((option) => option.text).join(", ");
      case "date":
        return cell.value.start;
      default:
        return null;
    }
  });
  equals.addRow(row);
}

I also wanted to include a quick example I wrote that brings data from Airtable into Equals, just as a comparison:

const equals = require("equals");
const axios = require("axios");

const API_KEY = equals.getSecret("airtable_api_key");
const BASE_ID = equals.getSecret("airtable_base_id");
const TABLE_NAME = "Issues";
const MAX_RECORDS = 100;

const getRecords = async () => {
  const resp = await axios({
    method: "get",
    url: `https://api.airtable.com/v0/${BASE_ID}/${TABLE_NAME}`,
    params: {
      maxRecords: MAX_RECORDS,
      view: "Grid view"
    },
    headers: {
      Authorization: `Bearer ${API_KEY}`
    }
  });
  return resp.data.records;
}

const records = await getRecords();

equals.addHeaders(["number", "title", "user", "state", "closed at", "created at"]);

for(const record of records) {
  equals.addRow([
    record.fields.number,
    record.fields.title,
    record.fields.user,
    record.fields.state,
    record.fields.closed_at,
    record.fields.created_at
  ])
}

I would love to see the data from my Notion table appear in my Equals spreadsheet, so that I can make a more complex analysis off of the inputs in my Notion board.


问:
range-v3: can range::remove be made to work on a view::chunk?
It appears ranges::remove cannot operate on a ranges::views::chunk.

#include "range/v3/algorithm/remove.hpp"
#include <iostream>
#include <range/v3/view/chunk.hpp>
#include <vector>

int main() {

    std::vector<int> v{
        1, 2, 3, 4,
        5, 6, 7, 8,
        9, 10, 11, 12,
        13, 14, 15, 16
    };

    auto a = ranges::views::chunk(v, 4);
    for (const auto& e: a) std::cout << e[0] << "\n";

    auto it = ranges::remove(a, 9, [](const auto& e) { return e[0]; });

    // expected result  (xx means unspecified)

    // std::vector<int> v{
    //     1, 2, 3, 4,
    //     5, 6, 7, 8,
    //     13, 14, 15, 16,
    //     xx, xx, xx, xx
    // };

}

```
<p>Errors are "does not satisfy" a chain of concepts: permutable, forward_iterator, etc..</p>
```      constraints not satisfied [with I = ranges::chunk_view<ranges::ref_view<std::vector<int>>>, S = int, T = (lambda at
      /home/oliver/c/physicssim/app/parremove.cpp:19:36), P = ranges::identity]
        constexpr I RANGES_FUNC(remove)(I first, S last, T const & val, P proj = P{})
                    ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/detail/config.hpp:633:27: note: expanded from macro
      'RANGES_FUNC'
#define RANGES_FUNC(NAME) operator() RANGES_FUNC_CONST_ /**/
                          ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/algorithm/remove.hpp:42:22: note: because
      'ranges::chunk_view<ranges::ref_view<std::vector<int>>>' does not satisfy 'permutable'
            requires permutable AND sentinel_for<S, I> AND
                     ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/detail/prologue.hpp:35:26: note: expanded from macro
      'template'
    template<__VA_ARGS__ CPP_TEMPLATE_AUX_                                      \
                         ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/iterator/concepts.hpp:841:9: note: because
      'ranges::chunk_view<ranges::ref_view<std::vector<int>>>' does not satisfy 'forward_iterator'
        forward_iterator &&
        ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/iterator/concepts.hpp:371:9: note: because
      'ranges::chunk_view<ranges::ref_view<std::vector<int>>>' does not satisfy 'input_iterator'
        input_iterator &&
        ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/iterator/concepts.hpp:363:9: note: because
      'ranges::chunk_view<ranges::ref_view<std::vector<int>>>' does not satisfy 'input_or_output_iterator'
        input_or_output_iterator &&
        ^
....

```

I can see why this would be non-trivial, but think it should be hypothetically possible?

Assuming I am not making an obvious mistake, is there any alternative, or solution/workaround?

Body:
It appears ranges::remove cannot operate on a ranges::views::chunk.

#include "range/v3/algorithm/remove.hpp"
#include <iostream>
#include <range/v3/view/chunk.hpp>
#include <vector>

int main() {

    std::vector<int> v{
        1, 2, 3, 4,
        5, 6, 7, 8,
        9, 10, 11, 12,
        13, 14, 15, 16
    };

    auto a = ranges::views::chunk(v, 4);
    for (const auto& e: a) std::cout << e[0] << "\n";

    auto it = ranges::remove(a, 9, [](const auto& e) { return e[0]; });

    // expected result  (xx means unspecified)

    // std::vector<int> v{
    //     1, 2, 3, 4,
    //     5, 6, 7, 8,
    //     13, 14, 15, 16,
    //     xx, xx, xx, xx
    // };

}

Errors are "does not satisfy" a chain of concepts: permutable, forward_iterator, etc..

      constraints not satisfied [with I = ranges::chunk_view<ranges::ref_view<std::vector<int>>>, S = int, T = (lambda at
      /home/oliver/c/physicssim/app/parremove.cpp:19:36), P = ranges::identity]
        constexpr I RANGES_FUNC(remove)(I first, S last, T const & val, P proj = P{})
                    ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/detail/config.hpp:633:27: note: expanded from macro
      'RANGES_FUNC'
#define RANGES_FUNC(NAME) operator() RANGES_FUNC_CONST_ /**/
                          ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/algorithm/remove.hpp:42:22: note: because
      'ranges::chunk_view<ranges::ref_view<std::vector<int>>>' does not satisfy 'permutable'
            requires permutable AND sentinel_for<S, I> AND
                     ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/detail/prologue.hpp:35:26: note: expanded from macro
      'template'
    template<__VA_ARGS__ CPP_TEMPLATE_AUX_                                      \
                         ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/iterator/concepts.hpp:841:9: note: because
      'ranges::chunk_view<ranges::ref_view<std::vector<int>>>' does not satisfy 'forward_iterator'
        forward_iterator &&
        ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/iterator/concepts.hpp:371:9: note: because
      'ranges::chunk_view<ranges::ref_view<std::vector<int>>>' does not satisfy 'input_iterator'
        input_iterator &&
        ^
/home/oliver/c/physicssim/ext/range-v3/include/range/v3/iterator/concepts.hpp:363:9: note: because
      'ranges::chunk_view<ranges::ref_view<std::vector<int>>>' does not satisfy 'input_or_output_iterator'
        input_or_output_iterator &&
        ^
....

I can see why this would be non-trivial, but think it should be hypothetically possible?

Assuming I am not making an obvious mistake, is there any alternative, or solution/workaround?


问:
How to combine STM32 HAL library with CMake, as it need file from project it linked to
For ones who dont know STM32 library structure.
The library is not projected to cmake use (or any another build system as i think).

It have a bunch of source\headers files

```<code>  stm32_hal.c
  stm32_hal.h
</code>```

They are provided with git repository, as example https://github.com/STMicroelectronics/STM32CubeF4
This files is depended by user provided stm32_hal_conf.h

The structure of project is looked like.

```<code>\ Repository
\--- HAL submodule library
\------ stm32_hal.c
\------ stm32_hal.h
\--- User library
\------ lib.c
\------ lib.h
\--- Project sources (depended from HAL)
\------ main.c
\------ main.h
\------ stm32_hal_conf.h (file, HAL library depended by)
</code>```

The main question - HOW?
Obiviusly compilation HAL as generic add_library() would fail, as HAL library doesnt have access and even dont know about stm32_hal_conf.h

There is a repository, where this problem seems solved, but there is too much high level CMake code-mess, i cant even make it works.
https://github.com/ahessling/STM32F4Template

I dont want to hard copy HAL to project and dont want to include files as lists.

The code samples:

HAL FindPackage()

```<code>function(FindCmsisSTM32F4)
    set(CMSIS_LIBRARY_NAME "LIB_CMSIS")
    set(CMSIS_PATH ./submodules/stm32cubef4/Drivers/CMSIS)
    list(APPEND CMSIS_INCLUDE
        ${CMSIS_PATH}/Device/ST/STM32F4xx/Include
        ${CMSIS_PATH}/Core/Include)
    set(CMSIS_STM32_INCLUDE_PATH ${CMSIS_PATH}/Device/ST/STM32F4xx/include)
    add_library(${CMSIS_LIBRARY_NAME} INTERFACE)
    target_include_directories(${CMSIS_LIBRARY_NAME} INTERFACE ${CMSIS_INCLUDE})

endfunction(FindCmsisSTM32F4)

FindCmsisSTM32F4()
set(LIB_CMSIS "LIB_CMSIS")
</code>```

Project CMakeLists.txt

```<code>find_package(STM32F4_CMSIS)

# Add sources to elf file
add_executable(${elf_file} ${sources})

# Link Generic stm32 libraries to project
target_include_directories(${elf_file} PUBLIC ./src) # hal_conf.h inclusion
target_link_libraries(${elf_file} PRIVATE ${LIB_HAL})
</code>```

Body:
For ones who dont know STM32 library structure.
The library is not projected to cmake use (or any another build system as i think).

It have a bunch of source\headers files

  stm32_hal.c
  stm32_hal.h

They are provided with git repository, as example https://github.com/STMicroelectronics/STM32CubeF4
This files is depended by user provided stm32_hal_conf.h

The structure of project is looked like.

\ Repository
\--- HAL submodule library
\------ stm32_hal.c
\------ stm32_hal.h
\--- User library
\------ lib.c
\------ lib.h
\--- Project sources (depended from HAL)
\------ main.c
\------ main.h
\------ stm32_hal_conf.h (file, HAL library depended by)

The main question - HOW?
Obiviusly compilation HAL as generic add_library() would fail, as HAL library doesnt have access and even dont know about stm32_hal_conf.h

There is a repository, where this problem seems solved, but there is too much high level CMake code-mess, i cant even make it works.
https://github.com/ahessling/STM32F4Template

I dont want to hard copy HAL to project and dont want to include files as lists.

The code samples:

HAL FindPackage()

function(FindCmsisSTM32F4)
    set(CMSIS_LIBRARY_NAME "LIB_CMSIS")
    set(CMSIS_PATH ./submodules/stm32cubef4/Drivers/CMSIS)
    list(APPEND CMSIS_INCLUDE
        ${CMSIS_PATH}/Device/ST/STM32F4xx/Include
        ${CMSIS_PATH}/Core/Include)
    set(CMSIS_STM32_INCLUDE_PATH ${CMSIS_PATH}/Device/ST/STM32F4xx/include)
    add_library(${CMSIS_LIBRARY_NAME} INTERFACE)
    target_include_directories(${CMSIS_LIBRARY_NAME} INTERFACE ${CMSIS_INCLUDE})

endfunction(FindCmsisSTM32F4)

FindCmsisSTM32F4()
set(LIB_CMSIS "LIB_CMSIS")

Project CMakeLists.txt

find_package(STM32F4_CMSIS)

# Add sources to elf file
add_executable(${elf_file} ${sources})

# Link Generic stm32 libraries to project
target_include_directories(${elf_file} PUBLIC ./src) # hal_conf.h inclusion
target_link_libraries(${elf_file} PRIVATE ${LIB_HAL})


问:
Is there a way to zoom out all screen on Visual Studio 2022?
zoom out shortcuts for vs code such as ctrl+shift+- does not work for vs 2022. Is there any way to zoom out specifically in vs 2022 as not only for the editor side in it but for the all screen?

I tried ctrl+shift+- or ctrl+- but those all does not work for vs 2022.


问:
Nx typescript error on custom build script
I would like to create a custom build script that compile multiple files from a single app but I always get compilation errors with nx. Here is a dummy project reproducing the error:

Create a new monorepo: npx create-nx-workspace test-error

Change nx.json workspaceLayout's property and set appsDir to apps instead of packages

Add the npm package to make a new node application: npm i -D @nrwl/node

Create a new application: npx nx g @nrwl/node:application test-app

Create two files ready to be compiles: Copy/paste main.ts and name it main2.ts

Add this to tsconfig.json to remove the error that should have popped:

  "compilerOptions": {
    "composite": true,
    "declaration": true
  },
```
<ul>
<li>Add this dummy script to compile the two files</li>
</ul>
<pre class="lang-js prettyprint-override"><code>    "ts-build": {
      "executor": "nx:run-commands",
      "options": {
        "commands": [
          "tsc apps/test-app/src/main.ts",
          "tsc apps/test-app/src/main2.ts"
        ],
        "outputPath": "dist/apps/test-app"
      }
    },
</code>```

Compile the app: npx nx ts-build test-app

This will throw this error but still output the two files in the same directory (not in the dist folder as planned).

```<code>npx nx ts-build test-app

> nx run test-app:ts-build

node_modules/@types/jsdom/base.d.ts(5,10): error TS2305: Module '"parse5"' has no exported member 'ElementLocation'.
node_modules/@types/jsdom/base.d.ts(5,10): error TS2305: Module '"parse5"' has no exported member 'ElementLocation'.
Warning: run-commands command "tsc apps/test-app/src/main.ts" exited with non-zero status codeWarning: run-commands command "tsc apps/test-app/src/main2.ts" exited with non-zero status code
</code>```

I don't understand why it show an error message but seems to compile successfully (the main files should have only a console.log line of code). And also why it doesn't output the files in the specified dist directory.

Body:
I would like to create a custom build script that compile multiple files from a single app but I always get compilation errors with nx. Here is a dummy project reproducing the error:

Create a new monorepo: npx create-nx-workspace test-error

Change nx.json workspaceLayout's property and set appsDir to apps instead of packages

Add the npm package to make a new node application: npm i -D @nrwl/node

Create a new application: npx nx g @nrwl/node:application test-app

Create two files ready to be compiles: Copy/paste main.ts and name it main2.ts

Add this to tsconfig.json to remove the error that should have popped:

  "compilerOptions": {
    "composite": true,
    "declaration": true
  },

Add this dummy script to compile the two files

    "ts-build": {
      "executor": "nx:run-commands",
      "options": {
        "commands": [
          "tsc apps/test-app/src/main.ts",
          "tsc apps/test-app/src/main2.ts"
        ],
        "outputPath": "dist/apps/test-app"
      }
    },

Compile the app: npx nx ts-build test-app

This will throw this error but still output the two files in the same directory (not in the dist folder as planned).

npx nx ts-build test-app

> nx run test-app:ts-build

node_modules/@types/jsdom/base.d.ts(5,10): error TS2305: Module '"parse5"' has no exported member 'ElementLocation'.
node_modules/@types/jsdom/base.d.ts(5,10): error TS2305: Module '"parse5"' has no exported member 'ElementLocation'.
Warning: run-commands command "tsc apps/test-app/src/main.ts" exited with non-zero status codeWarning: run-commands command "tsc apps/test-app/src/main2.ts" exited with non-zero status code

I don't understand why it show an error message but seems to compile successfully (the main files should have only a console.log line of code). And also why it doesn't output the files in the specified dist directory.


问:
How to show mysql data in html using python
I was given a task to create a database and display the information there in a simple html page, with the help of python. Can you help me understand how it is done?

I tried to write py-script in html, but then import mysql.connector doesn't work. Besides py-script, are there any other options to do the task?


问:
Why am I unable to achieve the desired aspect-ratio using TailwindCSS?
I am trying to achieve an 1:1 aspect ratio for the React component EventPreview under the parent component EventPreviewCarousel using TailwindCSS.

From TailwindCSS' official docs:

The aspect-{ratio} utilities use the native aspect-ratio CSS property, which was not supported in Safari until version 15. Until Safari 15 is popularized, Tailwind’s aspect-ratio plugin is a good alternative.

I'll further quote the docs for @tailwindcss/aspect-ratio:

Note that due to the way this currently needs to be implemented (the old padding-bottom trick) you need to assign the aspect ratio to a parent element, and make the actual element you are trying to size the only child of that parent.

I installed @tailwind/aspect-ratio and below is my code after the necessary revisions:

tailwind.config.js

const defaultTheme = require("tailwindcss/defaultTheme")

module.exports = {
    content: ["./src/**/*.{js,jsx,ts,tsx}"],
    theme: {
        fontSize: {
            ...defaultTheme.fontSize,
            base: "0.9375rem",
        },
        fontFamily: {
            sans: ["Archivo", ...defaultTheme.fontFamily.sans],
            serif: ["Lora", ...defaultTheme.fontFamily.serif],
            "ev-p-d": ["Quantico"],
            "ev-p-n": ["Epilogue"],
            "tl-ev-y": ["Cabin"],
        },
        aspectRatio: {
            auto: "auto",
            square: "1 / 1",
            video: "16 / 9",
            1: "1",
            2: "2",
            3: "3",
            4: "4",
            5: "5",
            6: "6",
            7: "7",
            8: "8",
            9: "9",
            10: "10",
            11: "11",
            12: "12",
            13: "13",
            14: "14",
            15: "15",
            16: "16",
        },
        extend: {
            colors: {
                primary: "#0066FF",
            },
        },
    },
    corePlugins: {
        aspectRatio: false,
    },
    plugins: [
        require("@tailwindcss/aspect-ratio")
    ]
}
```
<p><code>EventPreview.js</code></p>
<pre class="lang-js prettyprint-override"><code>const EventPreview = (props) => {
    const formattingOptions = {
        year: "numeric",
        month: "short",
        day: "2-digit"
    }

    const formattedDate = props.date.toLocaleDateString("en-US", formattingOptions)

    return (
        <div className="w-3/4 aspect-square">
            <div
                className={`${props.className} grid grid-cols-1 content-between p-3 bg-gradient-to-b from-gray-50 to-gray-200 rounded border border-gray-400`}
            >
                <div className="flex justify-between items-center">
                    <span className="font-ev-p-d text-sm">{props.category}</span>
                    <span className="font-ev-p-d text-sm">{formattedDate}</span>
                </div>

                <span className="font-ev-p-n lowercase leading-tight">
                    {props.name}
                </span>
            </div>
        </div>
    )
}

export default EventPreview
</code>```

EventPreviewCarousel.js

import Carousel from "../UI/Carousel"
import EventPreview from './EventPreview'

const EventPreviewCarousel = props => {
    const carouselOptions = {
        cellAlign: "left",
        contain: true,
        selectedAttraction: 0.2,
        friction: 0.8
    }

    return (
        <Carousel options={carouselOptions}>
            {props.events.map(event => {
                return <EventPreview
                    className="mr-6"
                    key={event.id}
                    name={event.name}
                    date={event.date}
                    category={event.category}
                />
            })}
        </Carousel>
    )
}

export default EventPreviewCarousel
```

Here's a screenshot of my code running on the current Safari version on an iPhone 13 with iOS 16.0. It also looks the same on this device on Firefox 108.0.

What am I doing incorrectly? Any advice would be greatly appreciated. Thank you!

Body:
I am trying to achieve an 1:1 aspect ratio for the React component EventPreview under the parent component EventPreviewCarousel using TailwindCSS.

From TailwindCSS' official docs:

The aspect-{ratio} utilities use the native aspect-ratio CSS property, which was not supported in Safari until version 15. Until Safari 15 is popularized, Tailwind’s aspect-ratio plugin is a good alternative.

I'll further quote the docs for @tailwindcss/aspect-ratio:

Note that due to the way this currently needs to be implemented (the old padding-bottom trick) you need to assign the aspect ratio to a parent element, and make the actual element you are trying to size the only child of that parent.

I installed @tailwind/aspect-ratio and below is my code after the necessary revisions:

tailwind.config.js

const defaultTheme = require("tailwindcss/defaultTheme")

module.exports = {
    content: ["./src/**/*.{js,jsx,ts,tsx}"],
    theme: {
        fontSize: {
            ...defaultTheme.fontSize,
            base: "0.9375rem",
        },
        fontFamily: {
            sans: ["Archivo", ...defaultTheme.fontFamily.sans],
            serif: ["Lora", ...defaultTheme.fontFamily.serif],
            "ev-p-d": ["Quantico"],
            "ev-p-n": ["Epilogue"],
            "tl-ev-y": ["Cabin"],
        },
        aspectRatio: {
            auto: "auto",
            square: "1 / 1",
            video: "16 / 9",
            1: "1",
            2: "2",
            3: "3",
            4: "4",
            5: "5",
            6: "6",
            7: "7",
            8: "8",
            9: "9",
            10: "10",
            11: "11",
            12: "12",
            13: "13",
            14: "14",
            15: "15",
            16: "16",
        },
        extend: {
            colors: {
                primary: "#0066FF",
            },
        },
    },
    corePlugins: {
        aspectRatio: false,
    },
    plugins: [
        require("@tailwindcss/aspect-ratio")
    ]
}

EventPreview.js

const EventPreview = (props) => {
    const formattingOptions = {
        year: "numeric",
        month: "short",
        day: "2-digit"
    }

    const formattedDate = props.date.toLocaleDateString("en-US", formattingOptions)

    return (

            <div
                className={`${props.className} grid grid-cols-1 content-between p-3 bg-gradient-to-b from-gray-50 to-gray-200 rounded border border-gray-400`}
            >

                    {props.category}
                    {formattedDate}

                    {props.name}

    )
}

export default EventPreview

EventPreviewCarousel.js

import Carousel from "../UI/Carousel"
import EventPreview from './EventPreview'

const EventPreviewCarousel = props => {
    const carouselOptions = {
        cellAlign: "left",
        contain: true,
        selectedAttraction: 0.2,
        friction: 0.8
    }

    return (
        <Carousel options={carouselOptions}>
            {props.events.map(event => {
                return <EventPreview
                    className="mr-6"
                    key={event.id}
                    name={event.name}
                    date={event.date}
                    category={event.category}
                />
            })}
        </Carousel>
    )
}

export default EventPreviewCarousel

Here's a screenshot of my code running on the current Safari version on an iPhone 13 with iOS 16.0. It also looks the same on this device on Firefox 108.0.

What am I doing incorrectly? Any advice would be greatly appreciated. Thank you!


问:
How to add two floats in NASM?
I started to learn NASM a few days ago so there are many things that I don't know about NASM. I am trying to add two floats, from user input.

I found a code in this question that prints the result but I want to store it. As I read from here, the result is stored in ST0, I don't understand where actually it is, but I can't assign the result to a variable. The code I found from the question :

```<code>sub esp, 8
mov dword [esp], 2
fild dword [esp]
mov dword [esp], __float32__(3.25) ;
fadd dword [esp]
</code>```

And I tried :

```<code>mov eax, dword [esp]
mov dword [res], eax
</code>```

But it didn't produce any output.

How can I do that on NASM?

Title: How to add two floats in NASM?

Body:
I started to learn NASM a few days ago so there are many things that I don't know about NASM. I am trying to add two floats, from user input.

I found a code in this question that prints the result but I want to store it. As I read from here, the result is stored in ST0, I don't understand where actually it is, but I can't assign the result to a variable. The code I found from the question :

sub esp, 8
mov dword [esp], 2
fild dword [esp]
mov dword [esp], __float32__(3.25) ;
fadd dword [esp]

And I tried :

mov eax, dword [esp]
mov dword [res], eax

But it didn't produce any output.

How can I do that on NASM?


问:
Find close up corner with python and opencv
So I'm trying to find the corner of a painted plexiglas. The background and the corner itself is rough and textured. Here are two sample images:

Since the corner is a bit rounded, I think the best way to find the pixel coordinates of the corner is to interpolate the edges and find their intersection. The goal is to reliably find the pixel coordinates of the corner in a live webcam feed.

I did try to use the Canny edge detection and then HoughLinesP

```<code>import cv2
import numpy as np

image = cv2.imread(filename)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (9, 9), 0)
edges = cv2.Canny(blur, 150, 10)

rho = 1
theta = np.pi / 180
threshold = 45
min_line_length = 15
max_line_gap = 200
lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]),
                        min_line_length, max_line_gap)

for line in lines:
    for x1, y1, x2, y2 in line:
        cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 1)

cv2.imshow('Corners', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

I was tweaking all the parameters randomly until I found something I was looking for:

My next step would be to cluster all those lines into groups and fit a single line to approximate the edges. I think my procedure is probably ugly and unreliable once I put it to a live webcam feed of these corners. Does someone have a better idea, or am I on a good track here?

Body:
So I'm trying to find the corner of a painted plexiglas. The background and the corner itself is rough and textured. Here are two sample images:

Since the corner is a bit rounded, I think the best way to find the pixel coordinates of the corner is to interpolate the edges and find their intersection. The goal is to reliably find the pixel coordinates of the corner in a live webcam feed.

I did try to use the Canny edge detection and then HoughLinesP

import cv2
import numpy as np

image = cv2.imread(filename)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (9, 9), 0)
edges = cv2.Canny(blur, 150, 10)

rho = 1
theta = np.pi / 180
threshold = 45
min_line_length = 15
max_line_gap = 200
lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]),
                        min_line_length, max_line_gap)

for line in lines:
    for x1, y1, x2, y2 in line:
        cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 1)

cv2.imshow('Corners', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

I was tweaking all the parameters randomly until I found something I was looking for:

My next step would be to cluster all those lines into groups and fit a single line to approximate the edges. I think my procedure is probably ugly and unreliable once I put it to a live webcam feed of these corners. Does someone have a better idea, or am I on a good track here?


问:
Every other celery task fails; it seems to be "unregistered"
I'm using celery to run a task called 'filter'.

I'm having a weird error whereby every other task call seems to result in a celery.exceptions.NotRegistered exception.

By every other call, I mean:

I call it once, it works

I call it again, it fails (with the error below)

I call it for the third time, it works again.

I call it for a fourth time, it fails (same error) message

I'm calling it using send_task like this, storing the task_id so I can pool it later.

```<code>async_result1 = celery_app.send_task("filter", kwargs=data.dict())

output = {"task_id": async_result1.task_id}
</code>```

Then I poll the app every few seconds to get the status of the task like this:

```<code>result=AsyncResult(task_id)

(if status is not success, keep polling until it's successful)
</code>```

The weird thing is that the code works once but when I call again it fails.

I've ssh'ed into the worker container and when I run celery result passing a failed task Id like this celery -A app.name result -t filter  880df2ee-0a25-455f-93fb-50af3d5980e5, this is the output I get (the last line shows the error I mentioned above)

```<code>Traceback (most recent call last):
  File "/usr/local/bin/celery", line 8, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.7/site-packages/celery/__main__.py", line 16, in main
    _main()
  File "/usr/local/lib/python3.7/site-packages/celery/bin/celery.py", line 322, in main
    cmd.execute_from_commandline(argv)
  File "/usr/local/lib/python3.7/site-packages/celery/bin/celery.py", line 495, in execute_from_commandline
    super(CeleryCommand, self).execute_from_commandline(argv)))
  File "/usr/local/lib/python3.7/site-packages/celery/bin/base.py", line 305, in execute_from_commandline
    return self.handle_argv(self.prog_name, argv[1:])
  File "/usr/local/lib/python3.7/site-packages/celery/bin/celery.py", line 487, in handle_argv
    return self.execute(command, argv)
  File "/usr/local/lib/python3.7/site-packages/celery/bin/celery.py", line 419, in execute
    ).run_from_argv(self.prog_name, argv[1:], command=argv[0])
  File "/usr/local/lib/python3.7/site-packages/celery/bin/base.py", line 309, in run_from_argv
    sys.argv if argv is None else argv, command)
  File "/usr/local/lib/python3.7/site-packages/celery/bin/base.py", line 393, in handle_argv
    return self(*args, **options)
  File "/usr/local/lib/python3.7/site-packages/celery/bin/base.py", line 253, in __call__
    ret = self.run(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/celery/bin/result.py", line 41, in run
    value = task_result.get()
  File "/usr/local/lib/python3.7/site-packages/celery/result.py", line 228, in get
    on_message=on_message,
  File "/usr/local/lib/python3.7/site-packages/celery/backends/asynchronous.py", line 195, in wait_for_pending
    return result.maybe_throw(callback=callback, propagate=propagate)
  File "/usr/local/lib/python3.7/site-packages/celery/result.py", line 333, in maybe_throw
    self.throw(value, self._to_remote_traceback(tb))
  File "/usr/local/lib/python3.7/site-packages/celery/result.py", line 326, in throw
    self.on_ready.throw(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/vine/promises.py", line 244, in throw
    reraise(type(exc), exc, tb)
  File "/usr/local/lib/python3.7/site-packages/vine/five.py", line 195, in reraise
    raise value
celery.exceptions.NotRegistered: 'filter'
</code>```

Any idea of what could be happening here? I feel like there's something I'm missing, maybe I need to flush/restart the queue somehow?

I'm using docker-compose and this is how the worker container is being started:

celery worker -A app.name -P threads --loglevel=DEBUG

One curiosity here: I started off passing --queues parameter to the celery worker **no call whatsoever worked**. When I removed the --queues` parameter, it started behaving like it is now. Every other call fails.

When I run celery inspect to view the worker state, I notice that only the tasks that end up successful are added to the queue

```<code>root@604dce1e1dda:/workers# celery -A app.name inspect active
-> celery@76089a886b04: OK
  - empty -
-> celery@604dce1e1dda: OK
  * {'id': '4d35d0bf-e3b4-4a6b-9a2e-4b23e12c98b1', 'name': 'filter', 'args': [], 'kwargs': {'foo': 'bar'}, 'type': 'filter', 'hostname': 'celery@604dce1e1dda', 'time_start': 1671406221.0351112, 'acknowledged': True, 'delivery_info': {'exchange': '', 'routing_key': 'celery', 'priority': 0, 'redelivered': False}, 'worker_pid': 1}
</code>```

The task is properly registered (but only the one that ends in 1dda, it seems)

```<code>root@604dce1e1dda:/workers# celery -A app.name inspect registered
-> celery@76089a886b04: OK
   * model
-> celery@604dce1e1dda: OK
   * filter
</code>```

PS. : I'm running celery 4.4.0 (cliffs) on python 3.7.16

Body:
I'm using celery to run a task called 'filter'.

I'm having a weird error whereby every other task call seems to result in a celery.exceptions.NotRegistered exception.

By every other call, I mean:

I call it once, it works

I call it again, it fails (with the error below)

I call it for the third time, it works again.

I call it for a fourth time, it fails (same error) message

I'm calling it using send_task like this, storing the task_id so I can pool it later.

async_result1 = celery_app.send_task("filter", kwargs=data.dict())

output = {"task_id": async_result1.task_id}

Then I poll the app every few seconds to get the status of the task like this:

result=AsyncResult(task_id)

(if status is not success, keep polling until it's successful)

The weird thing is that the code works once but when I call again it fails.

I've ssh'ed into the worker container and when I run celery result passing a failed task Id like this celery -A app.name result -t filter  880df2ee-0a25-455f-93fb-50af3d5980e5, this is the output I get (the last line shows the error I mentioned above)

Traceback (most recent call last):
  File "/usr/local/bin/celery", line 8, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.7/site-packages/celery/__main__.py", line 16, in main
    _main()
  File "/usr/local/lib/python3.7/site-packages/celery/bin/celery.py", line 322, in main
    cmd.execute_from_commandline(argv)
  File "/usr/local/lib/python3.7/site-packages/celery/bin/celery.py", line 495, in execute_from_commandline
    super(CeleryCommand, self).execute_from_commandline(argv)))
  File "/usr/local/lib/python3.7/site-packages/celery/bin/base.py", line 305, in execute_from_commandline
    return self.handle_argv(self.prog_name, argv[1:])
  File "/usr/local/lib/python3.7/site-packages/celery/bin/celery.py", line 487, in handle_argv
    return self.execute(command, argv)
  File "/usr/local/lib/python3.7/site-packages/celery/bin/celery.py", line 419, in execute
    ).run_from_argv(self.prog_name, argv[1:], command=argv[0])
  File "/usr/local/lib/python3.7/site-packages/celery/bin/base.py", line 309, in run_from_argv
    sys.argv if argv is None else argv, command)
  File "/usr/local/lib/python3.7/site-packages/celery/bin/base.py", line 393, in handle_argv
    return self(*args, **options)
  File "/usr/local/lib/python3.7/site-packages/celery/bin/base.py", line 253, in __call__
    ret = self.run(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/celery/bin/result.py", line 41, in run
    value = task_result.get()
  File "/usr/local/lib/python3.7/site-packages/celery/result.py", line 228, in get
    on_message=on_message,
  File "/usr/local/lib/python3.7/site-packages/celery/backends/asynchronous.py", line 195, in wait_for_pending
    return result.maybe_throw(callback=callback, propagate=propagate)
  File "/usr/local/lib/python3.7/site-packages/celery/result.py", line 333, in maybe_throw
    self.throw(value, self._to_remote_traceback(tb))
  File "/usr/local/lib/python3.7/site-packages/celery/result.py", line 326, in throw
    self.on_ready.throw(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/vine/promises.py", line 244, in throw
    reraise(type(exc), exc, tb)
  File "/usr/local/lib/python3.7/site-packages/vine/five.py", line 195, in reraise
    raise value
celery.exceptions.NotRegistered: 'filter'

Any idea of what could be happening here? I feel like there's something I'm missing, maybe I need to flush/restart the queue somehow?

I'm using docker-compose and this is how the worker container is being started:

celery worker -A app.name -P threads --loglevel=DEBUG

One curiosity here: I started off passing --queues parameter to the celery worker **no call whatsoever worked**. When I removed the --queues` parameter, it started behaving like it is now. Every other call fails.

When I run celery inspect to view the worker state, I notice that only the tasks that end up successful are added to the queue

root@604dce1e1dda:/workers# celery -A app.name inspect active
-> celery@76089a886b04: OK
  - empty -
-> celery@604dce1e1dda: OK
  * {'id': '4d35d0bf-e3b4-4a6b-9a2e-4b23e12c98b1', 'name': 'filter', 'args': [], 'kwargs': {'foo': 'bar'}, 'type': 'filter', 'hostname': 'celery@604dce1e1dda', 'time_start': 1671406221.0351112, 'acknowledged': True, 'delivery_info': {'exchange': '', 'routing_key': 'celery', 'priority': 0, 'redelivered': False}, 'worker_pid': 1}

The task is properly registered (but only the one that ends in 1dda, it seems)

root@604dce1e1dda:/workers# celery -A app.name inspect registered
-> celery@76089a886b04: OK
   * model
-> celery@604dce1e1dda: OK
   * filter

PS. : I'm running celery 4.4.0 (cliffs) on python 3.7.16


问:
DsGetDcName failing for Domain Controller
I have added two additional Windows Server 2012 domain controllers to my domain. When running dcdiag /v I receive a failure:

Doing primary tests

Testing server: Default-First-Site-Name\NEWDC
Starting test: Advertising
Warning: DsGetDcName returned information for
\SVR.mydomain.local, when we were trying to reach NEWDC.
SERVER IS NOT RESPONDING or IS NOT CONSIDERED SUITABLE.
......................... NEWDC failed test Advertising

It seems odd that the server "NEWDC" returns information for our original primary DC "SVR".  Any ideas where to start troubleshooting?

Ran dcdiag /v  and errors above noted.

Ran repladmin /showrepl  and it shows successful replication.


问:
Maintaining state when Dynamically building components
I'm trying to implement a dynamic component builder, however I'm struggling to find an optimal way to do so:

```<code>export interface InputDetailMetadata {
  detailMetadata: DetailMetadata,
  stateResolvers: DetailStateResolver[]
}

export interface DetailStateResolver {
  currentValue: any,
  onValueChange: (value: any) => void
}
</code>```

I'm trying to dynamically resolving a component based on its type, I have a detail component that handles iterating over a list of data and generating components like so:

```<code>detail.detailMetadata.type === DetailField.ADDRESS ? (
  <AddressInput key={key} label={t`${detail.detailMetadata.label}`} value={detail.stateResolvers[0].currentValue} onChange={detail.stateResolvers[0].onValueChange} />
) :
detail.detailMetadata.type === DetailField.Numeric ? (
   <NumericInputPanel key={key} label={t`${detail.detailMetadata.label}`} value={detail.stateResolvers[0].currentValue} onChange={detail.stateResolvers[0].onValueChange} />
) :
null
</code>```

Each one of these components require maintaining state of one or many values, in the past I had the states hard coded for each component:

```<code>const [toAddressValue, setToAddressValue] = useState('')
const handleToAddressInput = useCallback(
  (toAddress: string) => {
    setToAddressValue(toAddress)
  },
  [setToAddressValue]
)
</code>```

Now I need to store this dynamically for an array, however some of these components may require multiple callbacks/states, and on top of that hook limitations will prevent me from using a switch case on the details.

```<code>const stateResolvers: InputDetailMetadata[] = details.map(detail => {
  const result = { detailMetadata: detail };
  if (detail.type === ProposalActionDetailField.ADDRESS) {
    const [toValue, setValue] = useState('')
    const onValueChange = useCallback((value: any) => setValue(value), [setValue]);
    result.stateResolvers = [{
      currentValue: toValue,
      onValueChange
    }]
  }
  // handle other types which may require multiple states and callbacks
})
</code>```

My solution won't work for a few reasons of conditional hooks, and I'm skeptical whether I won't need to nest them later.

How can I store state for a dynamic component?

Body:
I'm trying to implement a dynamic component builder, however I'm struggling to find an optimal way to do so:

export interface InputDetailMetadata {
  detailMetadata: DetailMetadata,
  stateResolvers: DetailStateResolver[]
}

export interface DetailStateResolver {
  currentValue: any,
  onValueChange: (value: any) => void
}

I'm trying to dynamically resolving a component based on its type, I have a detail component that handles iterating over a list of data and generating components like so:

detail.detailMetadata.type === DetailField.ADDRESS ? (
  <AddressInput key={key} label={t`${detail.detailMetadata.label}`} value={detail.stateResolvers[0].currentValue} onChange={detail.stateResolvers[0].onValueChange} />
) :
detail.detailMetadata.type === DetailField.Numeric ? (
   <NumericInputPanel key={key} label={t`${detail.detailMetadata.label}`} value={detail.stateResolvers[0].currentValue} onChange={detail.stateResolvers[0].onValueChange} />
) :
null

Each one of these components require maintaining state of one or many values, in the past I had the states hard coded for each component:

const [toAddressValue, setToAddressValue] = useState('')
const handleToAddressInput = useCallback(
  (toAddress: string) => {
    setToAddressValue(toAddress)
  },
  [setToAddressValue]
)

Now I need to store this dynamically for an array, however some of these components may require multiple callbacks/states, and on top of that hook limitations will prevent me from using a switch case on the details.

const stateResolvers: InputDetailMetadata[] = details.map(detail => {
  const result = { detailMetadata: detail };
  if (detail.type === ProposalActionDetailField.ADDRESS) {
    const [toValue, setValue] = useState('')
    const onValueChange = useCallback((value: any) => setValue(value), [setValue]);
    result.stateResolvers = [{
      currentValue: toValue,
      onValueChange
    }]
  }
  // handle other types which may require multiple states and callbacks
})

My solution won't work for a few reasons of conditional hooks, and I'm skeptical whether I won't need to nest them later.

How can I store state for a dynamic component?