问:
Can't use apt-get when docker-compose on a php container
I am trying to setup a container that is pulling php:8.1-fpm through docker-compose, but I need to a some libs from apt-get that I require apt-get install -y php8.1-gmp

docker-compose

version: '3'
services:
  php:
    image: php:8.1-fpm
    depends_on:
      - mysql
    command: bash -c "apt-get update && apt-get install -y php8.1-gmp"
    volumes:
      - ./:/var/www/html:rw,cached
  mysql:
    image: mysql:debian
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: database
      MYSQL_USER: user
      MYSQL_PASSWORD: password
  nginx:
    depends_on:
      - php
    image: nginx:1.19
    ports:
      - 80:80
    volumes:
      - ./:/var/www/html
      - ./nginx.conf:/etc/nginx/conf.d/default.conf
```
<p>but when I docker-compose I get an error</p>
<pre class="lang-bash prettyprint-override"><code>php_1    | Reading package lists...
php_1    | Reading package lists...
php_1    | Building dependency tree...
php_1    | Reading state information...
php_1    | E: Unable to locate package php8.1-gmp
php_1    | E: Couldn't find any package by glob 'php8.1-gmp'
php_1    | E: Couldn't find any package by regex 'php8.1-gmp'

</code>```

if I remove the command: line it works fine but if I exec into php container and run the same command it gives me the same error.

Body:
I am trying to setup a container that is pulling php:8.1-fpm through docker-compose, but I need to a some libs from apt-get that I require apt-get install -y php8.1-gmp

docker-compose

version: '3'
services:
  php:
    image: php:8.1-fpm
    depends_on:
      - mysql
    command: bash -c "apt-get update && apt-get install -y php8.1-gmp"
    volumes:
      - ./:/var/www/html:rw,cached
  mysql:
    image: mysql:debian
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: database
      MYSQL_USER: user
      MYSQL_PASSWORD: password
  nginx:
    depends_on:
      - php
    image: nginx:1.19
    ports:
      - 80:80
    volumes:
      - ./:/var/www/html
      - ./nginx.conf:/etc/nginx/conf.d/default.conf

but when I docker-compose I get an error

php_1    | Reading package lists...
php_1    | Reading package lists...
php_1    | Building dependency tree...
php_1    | Reading state information...
php_1    | E: Unable to locate package php8.1-gmp
php_1    | E: Couldn't find any package by glob 'php8.1-gmp'
php_1    | E: Couldn't find any package by regex 'php8.1-gmp'

if I remove the command: line it works fine but if I exec into php container and run the same command it gives me the same error.


来源: stackexchange

问:
Error: Files must have consistent column names: * File 1 column 5 is: 1 * File 2 column 5 is: 0
Note: all of the datasets and scripts referenced here can be easily found in my
GitHub Repository for this research project. The code referenced and reprinted both in this question and the one linked to in the previous question should be in the script called "Both BE & FS script(40) - prepped for Antony" (Dr. Antony Davies is the principle researcher on this project).

This question is technically a follow up on a previous question, which itself was a follow up of a question before that. I firmly believe that the proposed answer in the previous question which can be found in the link would work in most cases, but my datasets have an unusual characteristic, they have no headers, and their top rows are not the variable names, the 3rd rows contain the variable names. Instead, their top rows contain which variables were selected by a variable selection algorithm (LASSO, Backward Stepwise, or Forward Stepwise) denoted as binary indicators, basically dummy variables as can be seen in the screenshot below:

This peculiar feature of these datasets I am loading into R and storing in a list/dataframe object I call 'datasets' means that when I ran the proposed solution to the previous question, I got this back in the Console:

```<code>all_data <- vroom(list.files(pattern = 'csv'), id = 'source_file')
Error: Files must have consistent column names: * File 1 column 5 is: 1 * File 2 column 5 is: 0
</code>```

I can clearly see what the problem is here, but I don't know how to fix it without asking my collaborator on this research project to edit part of the custom Excel Macro he wrote which he used to generate the 260,000 synthetic datasets we are running his new algorithm and the several Benchmark Algorithms on and then have him run it again on his second computer for half a week or more just so I can avoid this error at this very last step in measuring the performance of the Benchmark Methods!

p.s. 1 - Just to make myself clearer here, the best format I could have after transforming their current state would be for the top row to be what the 2nd row currently is, except with Xs in front of ever number, or equivalently, what is in the 3rd row starting with column #2, and what is currently in the 1st row right below that proper 1st row or header. I already know exactly how to write functions to score the selections if I can get the output in that format!

p.s. 2 - Again, the way that I got here in case it is too much trouble for you to quickly toggle between two tabs or between two tabs and an Rscript, I use the following code to get to where my issue is:

```<code>setwd("/datasets folder's location on my laptop")
filepaths_list <- list.files(path = filepath, full.names = TRUE, recursive = TRUE)
# reformat the names of each of the csv file formatted datasets
DS_names_list <- basename(filepaths_list)
DS_names_list <- tools::file_path_sans_ext(DS_names_list)

datasets <- lapply(filepaths_list, read.csv, header = FALSE)

True_IVs <- lapply(datasets, function(j) {j[1, -1]})

datasets <- lapply(datasets, function(i) {i[-1:-3, ]})
datasets <- lapply(datasets, \(X) { lapply(X, as.numeric) })
datasets <- lapply(datasets, function(i) { as.data.frame(i) })
# the line below won't run without the line above it having been run 1st
datasets <- lapply(datasets, \(X) { round(X, 3) })

# fit all of the Backward Stepwise Regressions
set.seed(11)      # for reproducibility
system.time(BE.fits <- parLapply(CL, datasets, \(X) {
    full_models <- lm(X$V1 ~ ., X)
    back <- step(full_models, scope = formula(full_models),
                    direction = 'back', trace = FALSE) }) )
# extract their fitted coefficients
BE_Coeffs <- lapply(seq_along(BE.fits), function(i) coef(BE.fits[[i]]))

# extract just the candidate variables they select by name
# this is one of the two components needed for performance measurment
IVs_Selected_by_BE <- lapply(seq_along(BE.fits),
                             \(i) names(coef(BE.fits[[i]])[-1]))

# this is the other component needed for performance measurement
True_Regressors <- lapply(True_IVs, function(i){names(i)[i == 1]})

</code>```

ContentLicense: CC BY-SA 4.0

Body:
Note: all of the datasets and scripts referenced here can be easily found in my
GitHub Repository for this research project. The code referenced and reprinted both in this question and the one linked to in the previous question should be in the script called "Both BE & FS script(40) - prepped for Antony" (Dr. Antony Davies is the principle researcher on this project).

This question is technically a follow up on a previous question, which itself was a follow up of a question before that. I firmly believe that the proposed answer in the previous question which can be found in the link would work in most cases, but my datasets have an unusual characteristic, they have no headers, and their top rows are not the variable names, the 3rd rows contain the variable names. Instead, their top rows contain which variables were selected by a variable selection algorithm (LASSO, Backward Stepwise, or Forward Stepwise) denoted as binary indicators, basically dummy variables as can be seen in the screenshot below:

This peculiar feature of these datasets I am loading into R and storing in a list/dataframe object I call 'datasets' means that when I ran the proposed solution to the previous question, I got this back in the Console:

all_data <- vroom(list.files(pattern = 'csv'), id = 'source_file')
Error: Files must have consistent column names: * File 1 column 5 is: 1 * File 2 column 5 is: 0

I can clearly see what the problem is here, but I don't know how to fix it without asking my collaborator on this research project to edit part of the custom Excel Macro he wrote which he used to generate the 260,000 synthetic datasets we are running his new algorithm and the several Benchmark Algorithms on and then have him run it again on his second computer for half a week or more just so I can avoid this error at this very last step in measuring the performance of the Benchmark Methods!

p.s. 1 - Just to make myself clearer here, the best format I could have after transforming their current state would be for the top row to be what the 2nd row currently is, except with Xs in front of ever number, or equivalently, what is in the 3rd row starting with column #2, and what is currently in the 1st row right below that proper 1st row or header. I already know exactly how to write functions to score the selections if I can get the output in that format!

p.s. 2 - Again, the way that I got here in case it is too much trouble for you to quickly toggle between two tabs or between two tabs and an Rscript, I use the following code to get to where my issue is:

setwd("/datasets folder's location on my laptop")
filepaths_list <- list.files(path = filepath, full.names = TRUE, recursive = TRUE)
# reformat the names of each of the csv file formatted datasets
DS_names_list <- basename(filepaths_list)
DS_names_list <- tools::file_path_sans_ext(DS_names_list)

datasets <- lapply(filepaths_list, read.csv, header = FALSE)

True_IVs <- lapply(datasets, function(j) {j[1, -1]})

datasets <- lapply(datasets, function(i) {i[-1:-3, ]})
datasets <- lapply(datasets, \(X) { lapply(X, as.numeric) })
datasets <- lapply(datasets, function(i) { as.data.frame(i) })
# the line below won't run without the line above it having been run 1st
datasets <- lapply(datasets, \(X) { round(X, 3) })

# fit all of the Backward Stepwise Regressions
set.seed(11)      # for reproducibility
system.time(BE.fits <- parLapply(CL, datasets, \(X) {
    full_models <- lm(X$V1 ~ ., X)
    back <- step(full_models, scope = formula(full_models),
                    direction = 'back', trace = FALSE) }) )
# extract their fitted coefficients
BE_Coeffs <- lapply(seq_along(BE.fits), function(i) coef(BE.fits[[i]]))

# extract just the candidate variables they select by name
# this is one of the two components needed for performance measurment
IVs_Selected_by_BE <- lapply(seq_along(BE.fits),
                             \(i) names(coef(BE.fits[[i]])[-1]))

# this is the other component needed for performance measurement
True_Regressors <- lapply(True_IVs, function(i){names(i)[i == 1]})


问:
What is the output of FIT() in KNeighborsClassifier
For OLS, I can extract the coefficients on train and apply them on test data to get y_hat.
For KNN, I thought we pick K observation close to a test observation to make the decision on label and therefore there is no need to fit within the train data.
So what is the role of knn.fit(train_data, train_labels) and what does it produce?
Can anyone please help enlightening me?
HHC</p>
```<code># Create and fit a nearest-neighbor classifier
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(train_data, train_labels)

predicted = knn.predict(test_data)
</code>```

Body:
For OLS, I can extract the coefficients on train and apply them on test data to get y_hat.
For KNN, I thought we pick K observation close to a test observation to make the decision on label and therefore there is no need to fit within the train data.
So what is the role of knn.fit(train_data, train_labels) and what does it produce?
Can anyone please help enlightening me?
HHC

# Create and fit a nearest-neighbor classifier
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(train_data, train_labels)

predicted = knn.predict(test_data)


问:
Possible to making telegram bot for interacting to smart contract?
If possible please give me an example of the script, I have searched but only found a telegram bot that can only read the blockchain

Maybe can use web3py?


问:
i cannot install mediapipe in pycharm and mine is 64 bit and python version is 3.11.1
ERROR: Could not find a version that satisfies the requirement mediapipe (from versions: none)
ERROR: No matching distribution found for mediapipe
enter image description here

i tried using "pip install mediapipe" and "py pip install mediapipe" but didn't work.
Also tried using a specific version and went down all the way to 0.8.9 of it in pycharm but the same error pops up


问:
STM32CubeIDE unable to connect to STM32f103c6t6 board, first upload was successful, but after several uploads i got this issue
Error in final launch sequence:

Failed to execute MI command:
target extended-remote localhost:3333

Error message from debugger back end:
localhost:3333: The system tried to join a drive to a directory on a joined drive.
Failed to execute MI command:
target extended-remote localhost:3333

Error message from debugger back end:
localhost:3333: The system tried to join a drive to a directory on a joined drive.
localhost:3333: The system tried to join a drive to a directory on a joined drive.

I uploaded the code first time and it was successful, now after several uploads this issue popped up, although I didn't unplug the device.


问:
Handling Multiple Changes To Different Objects In An Array Using Mongoose
I am creating a Discord Bot using discord.js and typescript. I am creating a leveling system where you get XP for sending messages.

I am using mongoose to interact with my database, hosted by MongoDB.

Here is the code for my schema:

```<code>import { Schema, model } from "mongoose";

interface IGuildProfiles {
    guildid: number;
    levels: {
        userid: number;
        totalXp: number;
        level: number;
        levelXp: number;
        levelXpNeeded: number;
        obtained: { level: number; date: number }[];
    }[];
}

const guildProfiles = new Schema<IGuildProfiles>(
    {
        guildid: {type: Number, required: true},
        levels: [
            {
                userid: {type: Number, required: true},
                totalXp: {type: Number, required: true},
                level: {type: Number, required: true},
                levelXp: {type: Number, required: true},
                levelXpNeeded: {type: Number, required: true},
                obtained: [{ level: {type: Number, required: true}, date: {type: Number, required: true} }],
            },
        ],
    },
    { timestamps: true }
);

export default model("GuildProfiles", guildProfiles);
</code>```

This creates a document containing a guild ID, and an array of information regarding the level of each user in the guild.

There is nothing wrong with this, but on the event that the bot makes multiple writes to the same guild document at the same time, would this have an unintended side effect of skipping XP sometimes, or is there nothing to worry about?

What I'm worried about:

```<code>// First Write (Around the same time as other writes)
const data = getDataSomeHow() // {id: 123, example:[]}
writeDataSomeHow() // writes {id:123, example: [{exampleString:"THIS IS THE FIRST WRITE"}]}

// Second Write (Around the same time as other writes)
const data = getDataSomeHow() // {id: 123, example:[]}
writeDataSomeHow() // writes {id:123, example: [{exampleString:"THIS IS THE SECOND WRITE"}]}

// Third Write (Around the same time as other writes)
const data = getDataSomeHow() // {id: 123, example:[]}
writeDataSomeHow() // writes {id:123, example: [{exampleString:"THIS IS THE THIRD WRITE"}]}

// Checking the written data
const data = getDataSomeHow()
/* What I think the data will be because of the side effect:
{id:123, example: [{exampleString:"THIS IS THE THIRD WRITE"}]}

What I want the data to be:
{id:123, example: [{exampleString:"THIS IS THE FIRST WRITE"}, {exampleString:"THIS IS THE SECOND WRITE"}, {exampleString:"THIS IS THE THIRD WRITE"}]}
*/
</code>```

Is this bound to happen, or am I wrong? If it is going to happen, how can I avoid it?

Body:
I am creating a Discord Bot using discord.js and typescript. I am creating a leveling system where you get XP for sending messages.

I am using mongoose to interact with my database, hosted by MongoDB.

Here is the code for my schema:

import { Schema, model } from "mongoose";

interface IGuildProfiles {
    guildid: number;
    levels: {
        userid: number;
        totalXp: number;
        level: number;
        levelXp: number;
        levelXpNeeded: number;
        obtained: { level: number; date: number }[];
    }[];
}

const guildProfiles = new Schema<IGuildProfiles>(
    {
        guildid: {type: Number, required: true},
        levels: [
            {
                userid: {type: Number, required: true},
                totalXp: {type: Number, required: true},
                level: {type: Number, required: true},
                levelXp: {type: Number, required: true},
                levelXpNeeded: {type: Number, required: true},
                obtained: [{ level: {type: Number, required: true}, date: {type: Number, required: true} }],
            },
        ],
    },
    { timestamps: true }
);

export default model("GuildProfiles", guildProfiles);

This creates a document containing a guild ID, and an array of information regarding the level of each user in the guild.

There is nothing wrong with this, but on the event that the bot makes multiple writes to the same guild document at the same time, would this have an unintended side effect of skipping XP sometimes, or is there nothing to worry about?

What I'm worried about:

// First Write (Around the same time as other writes)
const data = getDataSomeHow() // {id: 123, example:[]}
writeDataSomeHow() // writes {id:123, example: [{exampleString:"THIS IS THE FIRST WRITE"}]}

// Second Write (Around the same time as other writes)
const data = getDataSomeHow() // {id: 123, example:[]}
writeDataSomeHow() // writes {id:123, example: [{exampleString:"THIS IS THE SECOND WRITE"}]}

// Third Write (Around the same time as other writes)
const data = getDataSomeHow() // {id: 123, example:[]}
writeDataSomeHow() // writes {id:123, example: [{exampleString:"THIS IS THE THIRD WRITE"}]}

// Checking the written data
const data = getDataSomeHow()
/* What I think the data will be because of the side effect:
{id:123, example: [{exampleString:"THIS IS THE THIRD WRITE"}]}

What I want the data to be:
{id:123, example: [{exampleString:"THIS IS THE FIRST WRITE"}, {exampleString:"THIS IS THE SECOND WRITE"}, {exampleString:"THIS IS THE THIRD WRITE"}]}
*/

Is this bound to happen, or am I wrong? If it is going to happen, how can I avoid it?


问:
How to write query sql for oracle properly in this case the else statement doesn't working
i still looking for how to write sql in oracle properly. My goals is display name(NAMA) based on NIK. and if the NIK data not match with the database then else statement executed. right now the else statement not working.

This is my database

NIK
NAMA

94878
Alfian U

98345
Galeh S

Postman response when NIK data match with database

```<code>[{"NAMA":"Galeh S"}]
</code>```

But when NIK not match with database, else statement doesn't work. Postman response like this

```<code>[]
</code>```

PHP file.

```<code><?php
include ("koneksi.php");

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $NIK = $_POST["NIK"];
    $query = "SELECT NAMA FROM MASTER_KRY WHERE NIK = '$NIK'";
    $eksekusi = oci_parse($conn, $query);
    $cek = oci_execute($eksekusi);

    if($cek > 0){
        $response = array();
        while($ambil = oci_fetch_object($eksekusi)){
            $F["NAMA"] = $ambil->NAMA;
            array_push($response, $F);
        }
        } else {
            $response = "Data not available";
        }
}
else{
    $response = "Response Error";
}
echo json_encode($response);
oci_close($conn);
?>
</code>```

Body:
i still looking for how to write sql in oracle properly. My goals is display name(NAMA) based on NIK. and if the NIK data not match with the database then else statement executed. right now the else statement not working.

This is my database

NIK
NAMA

94878
Alfian U

98345
Galeh S

Postman response when NIK data match with database

[{"NAMA":"Galeh S"}]

But when NIK not match with database, else statement doesn't work. Postman response like this

[]

PHP file.

<?php
include ("koneksi.php");

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $NIK = $_POST["NIK"];
    $query = "SELECT NAMA FROM MASTER_KRY WHERE NIK = '$NIK'";
    $eksekusi = oci_parse($conn, $query);
    $cek = oci_execute($eksekusi);

    if($cek > 0){
        $response = array();
        while($ambil = oci_fetch_object($eksekusi)){
            $F["NAMA"] = $ambil->NAMA;
            array_push($response, $F);
        }
        } else {
            $response = "Data not available";
        }
}
else{
    $response = "Response Error";
}
echo json_encode($response);
oci_close($conn);
?>


问:
Why is my Gap property in SCSS not working?
I'm trying to put a gap on these icons to look appealing however it does not work. Which line did I go wrong with it? I've tried putting gap:20px; on both navlinks and icon divs still no changes.

Here's my SCSS

```<code>.navbar-container{
    background-color:$color--navyblue;
    width: 105px;
    height: 100vh;
    border-right: solid white 2px;
}
.SysDev-Logo{
    margin: 0;
    padding: 20px 25px;
}
.navlinks{
    margin: 0;
    justify-items: center;
    align-items: center;
    padding: 0px 25px;

    .icon{
        list-style: none;
        cursor: pointer;
        }
}
</code>```

And my nextjs

```<code><div className={styles['navbar-container']}>
            <div className="container-wrapper">
                <div className="Logo-wrapper">
                    <div className={styles['SysDev-Logo']}>
                        <Image
                            src="/img/SysDev LogoType.png"
                            width="50"
                            height="45"
                            objectFit="contain"
                            draggable="false"
                        />
                    </div>
                </div>
                <ul className={styles['navlinks']}>
                    <li className={[styles['icon'], styles['icon--home']].join(' ')}>
                        <Image
                            src="/img/home.svg"
                            width="50"
                            height="50"
                            objectFit="contain"
                            draggable="false"
                        />
                    </li>
</div>
</code>```

Body:
I'm trying to put a gap on these icons to look appealing however it does not work. Which line did I go wrong with it? I've tried putting gap:20px; on both navlinks and icon divs still no changes.

Here's my SCSS

.navbar-container{
    background-color:$color--navyblue;
    width: 105px;
    height: 100vh;
    border-right: solid white 2px;
}
.SysDev-Logo{
    margin: 0;
    padding: 20px 25px;
}
.navlinks{
    margin: 0;
    justify-items: center;
    align-items: center;
    padding: 0px 25px;

    .icon{
        list-style: none;
        cursor: pointer;
        }
}

And my nextjs

                        <Image
                            src="/img/SysDev LogoType.png"
                            width="50"
                            height="45"
                            objectFit="contain"
                            draggable="false"
                        />

                        <Image
                            src="/img/home.svg"
                            width="50"
                            height="50"
                            objectFit="contain"
                            draggable="false"
                        />


问:
Sequelize unkown column in field list error
I have a MySql DB and using sequelize.
I have a recipe and ingredients tables.

I want to pass the ingredients as an array to the api.
So I researched and discovered I can use get/set to achieve this.

But I get an "Unknown coumn 'ingredients' in 'field list'".

This is my model. The line

```<code>console.info("getDataValue...", this);
</code>```

never gets executed.

```<code>function model(sequelize) {
    const attributes = {
        recipeTitle: { type: DataTypes.STRING(255), allowNull: false },
        category: { type: DataTypes.STRING(30), allowNull: false },
        recipeSource: { type: DataTypes.STRING(100), allowNull: false },
        recipeSourceData: { type: DataTypes.TEXT(), allowNull: true },
        method: { type: DataTypes.TEXT(), allowNull: true },
        comments: { type: DataTypes.TEXT(), allowNull: true },
        prepTime: { type: DataTypes.STRING(10), allowNull: true },
        cookTime: { type: DataTypes.STRING(10), allowNull: true },
        rating: { type: DataTypes.FLOAT, allowNull: false },
        owner_id: { type: DataTypes.INTEGER, allowNull: false },
        ingredients: {
            type: DataTypes.TEXT,
            get() {
                console.info("getDataValue...", this);
                return JSON.parse(this.getDataValue("ingredients"));
            },
            set(val) {
                if (!Array.isArray(val)) {
                    throw new Error("ingredients must to be an array");
                }
                this.setDataValue("ingredients", JSON.stringify(val));
            },
        },
    };
</code>```

This is my validate-request middle ware and it does have the ingredients
when i console.info("valreq...").

So it seems its the schema.validate that fails??

```<code>function validateRequest(req, next, schema) {
    console.info("valreq...", req.body);
    const options = {
        abortEarly: false, // include all errors
        allowUnknown: true, // ignore unknown props
        stripUnknown: true, // remove unknown props
    };
    const { error, value } = schema.validate(req.body, options);

    if (error) {
        next(`Validation error: ${error.details.map((x) => x.message).join(", ")}`);
    } else {
        console.info("value...", value);
        req.body = value;
        next();
    }
}
</code>```

Body:
I have a MySql DB and using sequelize.
I have a recipe and ingredients tables.

I want to pass the ingredients as an array to the api.
So I researched and discovered I can use get/set to achieve this.

But I get an "Unknown coumn 'ingredients' in 'field list'".

This is my model. The line

console.info("getDataValue...", this);

never gets executed.

function model(sequelize) {
    const attributes = {
        recipeTitle: { type: DataTypes.STRING(255), allowNull: false },
        category: { type: DataTypes.STRING(30), allowNull: false },
        recipeSource: { type: DataTypes.STRING(100), allowNull: false },
        recipeSourceData: { type: DataTypes.TEXT(), allowNull: true },
        method: { type: DataTypes.TEXT(), allowNull: true },
        comments: { type: DataTypes.TEXT(), allowNull: true },
        prepTime: { type: DataTypes.STRING(10), allowNull: true },
        cookTime: { type: DataTypes.STRING(10), allowNull: true },
        rating: { type: DataTypes.FLOAT, allowNull: false },
        owner_id: { type: DataTypes.INTEGER, allowNull: false },
        ingredients: {
            type: DataTypes.TEXT,
            get() {
                console.info("getDataValue...", this);
                return JSON.parse(this.getDataValue("ingredients"));
            },
            set(val) {
                if (!Array.isArray(val)) {
                    throw new Error("ingredients must to be an array");
                }
                this.setDataValue("ingredients", JSON.stringify(val));
            },
        },
    };

This is my validate-request middle ware and it does have the ingredients
when i console.info("valreq...").

So it seems its the schema.validate that fails??

function validateRequest(req, next, schema) {
    console.info("valreq...", req.body);
    const options = {
        abortEarly: false, // include all errors
        allowUnknown: true, // ignore unknown props
        stripUnknown: true, // remove unknown props
    };
    const { error, value } = schema.validate(req.body, options);

    if (error) {
        next(`Validation error: ${error.details.map((x) => x.message).join(", ")}`);
    } else {
        console.info("value...", value);
        req.body = value;
        next();
    }
}


问:
Issue - Dockerfile - CentOS and Postfix - SMTP Relay SendGrid
Having issues to start a container that build using Dockerfile.

I am trying to simply run a CentOS image that has Postfix configured with SendGrid or any SMTP Relay service # KB # Integrate SendGrid with Postfix - SendGrid Documentation | SendGrid | Twilio

Dockerfile below:

FROM centos:7

# Update package repository and install postfix and SASL

RUN yum update -y && yum install -y postfix cyrus-sasl-plain

# Configure postfix to listen on all interfaces and enable SASL

RUN sed -i 's/inet_interfaces = localhost/inet_interfaces = all/' /etc/postfix/main.cf \

&& echo "broken_sasl_auth_clients = yes" >> /etc/postfix/main.cf \

&& echo "smtpd_sasl_auth_enable = yes" >> /etc/postfix/main.cf \

&& echo "smtpd_sasl_security_options = noanonymous" >> /etc/postfix/main.cf \

&& echo "smtp_sasl_tls_security_options = noanonymous" >> /etc/postfix/main.cf \

&& echo "smtp_tls_security_level = encrypt" >> /etc/postfix/main.cf \

&& echo "header_size_limit = 4096000" >> /etc/postfix/main.cf \

&& echo "relayhost = [smtp.sendgrid.net]:587" >> /etc/postfix/main.cf

# Expose the SMTP port (25)

EXPOSE 25

# Run a script to create a SASL password file for the specified user with the specified password

CMD ["/bin/bash", "-c", "echo $USERNAME $PASSWORD > /etc/postfix/sasl_passwd && chmod 600 /etc/postfix/sasl_passwd && echo 'smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd' >> /etc/postfix/main.cf && postfix start"]```
</div>
</div>
</p>
<p>Then I do a docker build</p>
```docker build -t user/centos-postfix-sendgrid . --no-cache=true --platform=linux/amd64
```
<p>Then docker run</p>
```docker run -itd --cap-add=NET_BIND_SERVICE -p 2513:25 -e USERNAME=apikey -e PASSWORD=passwordhere --name centos7_postfix_sendgrid user/centos-postfix-sendgrid
```

The container doesn’t start, not sure what issue is here. Any ideas?

Thanks

Body:
Having issues to start a container that build using Dockerfile.

I am trying to simply run a CentOS image that has Postfix configured with SendGrid or any SMTP Relay service # KB # Integrate SendGrid with Postfix - SendGrid Documentation | SendGrid | Twilio

Dockerfile below:

FROM centos:7

# Update package repository and install postfix and SASL

RUN yum update -y && yum install -y postfix cyrus-sasl-plain

# Configure postfix to listen on all interfaces and enable SASL

RUN sed -i 's/inet_interfaces = localhost/inet_interfaces = all/' /etc/postfix/main.cf \

&& echo "broken_sasl_auth_clients = yes" >> /etc/postfix/main.cf \

&& echo "smtpd_sasl_auth_enable = yes" >> /etc/postfix/main.cf \

&& echo "smtpd_sasl_security_options = noanonymous" >> /etc/postfix/main.cf \

&& echo "smtp_sasl_tls_security_options = noanonymous" >> /etc/postfix/main.cf \

&& echo "smtp_tls_security_level = encrypt" >> /etc/postfix/main.cf \

&& echo "header_size_limit = 4096000" >> /etc/postfix/main.cf \

&& echo "relayhost = [smtp.sendgrid.net]:587" >> /etc/postfix/main.cf

# Expose the SMTP port (25)

EXPOSE 25

# Run a script to create a SASL password file for the specified user with the specified password

CMD ["/bin/bash", "-c", "echo $USERNAME $PASSWORD > /etc/postfix/sasl_passwd && chmod 600 /etc/postfix/sasl_passwd && echo 'smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd' >> /etc/postfix/main.cf && postfix start"]

Then I do a docker build

docker build -t user/centos-postfix-sendgrid . --no-cache=true --platform=linux/amd64

Then docker run

docker run -itd --cap-add=NET_BIND_SERVICE -p 2513:25 -e USERNAME=apikey -e PASSWORD=passwordhere --name centos7_postfix_sendgrid user/centos-postfix-sendgrid

The container doesn’t start, not sure what issue is here. Any ideas?

Thanks


问:
Force php-curl to resolve with /etc/hosts configuration
i need to run an Nextcloud instance over an IPv6 Only Server.
(Web access will be accessable over IPv4 and IPv6 over an nginx reverse proxy).

Problem:
If i try to install an app to nextcloud, it tryt to curl it from https://github.com which is (what a shame today) not ipv6 compatible.

Error message:
cURL error 7: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://github.com/nextcloud-releases/calendar/releases/download/v4.2.0/calendar-v4.2.0.tar.gz

Setup:

Debian 11.6

Apache/2.4.54

PHP 8.1.13 (cli)

First approach:
I found public proxy services for github, that proxy the requests through an nginx, through edited entrys in the /etc/hosts file.
2a01:4f8:c010:d56::2 github.com 2a01:4f8:c010:d56::3 api.github.com 2a01:4f8:c010:d56::4 codeload.github.com 2a01:4f8:c010:d56::5 objects.githubusercontent.com

That solution works for me on console, but not for the nextcloud application.
It seems php-curl ignores the /etc/hosts file.

I also found "CURLOPT_RESOLVE" but it seems that something i need to put in the nextcloud code?
Is there anything similar i can put in the php.ini or something like that?

Question:
Is there any option to force php-curl to use the /etc/hosts file without touching the code of nextcloud?


问:
Firebase android: Getting invalid appcheck token error even though SHA 256 fingerprint is registered in console
I am trying to implement Firebase app check in my android app. I have followed all the steps as shown in the documentation page.

I am using Firebase BoM libraries as shown in the documentation page:

```<code>dependencies {
    implementation platform('com.google.firebase:firebase-bom:31.1.1')
    implementation 'com.google.firebase:firebase-appcheck-playintegrity'
}
</code>```

I got my SHA 256 fingerprint which I got from android studio after running this command in the terminal:

```<code>./gradlew signingReport
</code>```

I added the fingerprint in both PlayIntegrity and SafetyNet attestations (just in case PlayIntegrity doesn't work)

Inside all the activities in my app, I added this code:

```<code>FirebaseApp.initializeApp(activity_name.this);
FirebaseAppCheck firebaseAppCheck = FirebaseAppCheck.getInstance();
firebaseAppCheck.installAppCheckProviderFactory(
        PlayIntegrityAppCheckProviderFactory.getInstance());

FirebaseAuth mAuth = FirebaseAuth.getInstance();

mAuth.signInAnonymously()
        .addOnCompleteListener(record_viewer.this, (OnCompleteListener<AuthResult>) task -> {
            if (task.isSuccessful()) {

                FirebaseDatabase database = FirebaseDatabase.getInstance();

                //rest of the code here
            }
        });

</code>```

Every time I run my app on my physical device, I get these warnings in my console:

```<code> pc_0 - Detected invalid AppCheck token. Reconnecting (2 attempts remaining)
 pc_0 - Detected invalid AppCheck token. Reconnecting (1 attempts remaining)
 pc_0 - Detected invalid AppCheck token. Reconnecting (0 attempts remaining)
 pc_0 - Firebase Database connection was forcefully killed by the server. Will not attempt reconnect.   Reason: Invalid appcheck token
</code>```

How is my appcheck token invalid? I have tried regenerating and reattaching my SHA 256 fingerprint again and again into my Playintegrity attestation (thinking the key might be wrong), but this warning keeps on reappearing.
Where am I going wrong?

EDIT : Ok, I've noticed this line in the documentation page:

Currently, the built-in Play Integrity provider only supports Android apps distributed by Google Play. To use Play Integrity's off-Play features, or to use App Check with your own custom provider, see Implement a custom App Check provider.

Does this mean I have to publish the app in Google play store for the PlayIntegrity attestation to work?

Body:
I am trying to implement Firebase app check in my android app. I have followed all the steps as shown in the documentation page.

I am using Firebase BoM libraries as shown in the documentation page:

dependencies {
    implementation platform('com.google.firebase:firebase-bom:31.1.1')
    implementation 'com.google.firebase:firebase-appcheck-playintegrity'
}

I got my SHA 256 fingerprint which I got from android studio after running this command in the terminal:

./gradlew signingReport

I added the fingerprint in both PlayIntegrity and SafetyNet attestations (just in case PlayIntegrity doesn't work)

Inside all the activities in my app, I added this code:

FirebaseApp.initializeApp(activity_name.this);
FirebaseAppCheck firebaseAppCheck = FirebaseAppCheck.getInstance();
firebaseAppCheck.installAppCheckProviderFactory(
        PlayIntegrityAppCheckProviderFactory.getInstance());

FirebaseAuth mAuth = FirebaseAuth.getInstance();

mAuth.signInAnonymously()
        .addOnCompleteListener(record_viewer.this, (OnCompleteListener<AuthResult>) task -> {
            if (task.isSuccessful()) {

                FirebaseDatabase database = FirebaseDatabase.getInstance();

                //rest of the code here
            }
        });

Every time I run my app on my physical device, I get these warnings in my console:

 pc_0 - Detected invalid AppCheck token. Reconnecting (2 attempts remaining)
 pc_0 - Detected invalid AppCheck token. Reconnecting (1 attempts remaining)
 pc_0 - Detected invalid AppCheck token. Reconnecting (0 attempts remaining)
 pc_0 - Firebase Database connection was forcefully killed by the server. Will not attempt reconnect.   Reason: Invalid appcheck token

How is my appcheck token invalid? I have tried regenerating and reattaching my SHA 256 fingerprint again and again into my Playintegrity attestation (thinking the key might be wrong), but this warning keeps on reappearing.
Where am I going wrong?

EDIT : Ok, I've noticed this line in the documentation page:

Currently, the built-in Play Integrity provider only supports Android apps distributed by Google Play. To use Play Integrity's off-Play features, or to use App Check with your own custom provider, see Implement a custom App Check provider.

Does this mean I have to publish the app in Google play store for the PlayIntegrity attestation to work?


问:
setting a cookie in playwright but unable to retrieve it in application

Edit

Further fact finding, it appears that this is an issue ONLY appearing in React v16, but i dont know why?

not appearing in React v18, or Vue v2.6.10

in my playwright test im setting a cookie in the browser context like this:

test.beforeEach(async ({ page, browser }) => {
  const context = await browser.newContext()
  await context.addCookies([
    {
      name: AUTHTKN,
      value: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzI1NDUyMzh9.AN93Ms3qkL_mkY2_bF_-mI3MvhXVKbrsV4BRPLLF5hs',
      domain: 'localhost',
      path: '/',
      expires: moment().add(24, 'hours')
    }
  ])

  const cookies = await context.cookies()
  console.log(JSON.stringify(cookies, null, 2))

  await page.goto('/')
})
```
<p>using console.log i can see the output</p>
<p>I suspect this is an issue caused by playwright which seems to automatically inject <code>sameSite</code>, but not sure since this is a representation of the cookie and I have no ability (that i know of) how I could view it in browser to be sure</p>
<pre class="lang-js prettyprint-override"><code>[
  {
    "name": "AUTHTKN",
    "value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzI1NDUyMzh9.AN93Ms3qkL_mkY2_bF_-mI3MvhXVKbrsV4BRPLLF5hs",
    "domain": "localhost",
    "path": "/",
    "expires": 7776000,
    "httpOnly": false,
    "secure": false,
    "sameSite": "Lax"
  }
]
</code>```

in my application code, it fails to find the cookie, I load cookies from memory like this

const getAll = () => {
  const pairs = document.cookie.split(';')
  const cookies = {}
  for (let i = 0; i < pairs.length; i++) {
    var pair = pairs[i].split('=')
    cookies[(pair[0] + '').trim()] = unescape(pair.slice(1).join('='))
  }
  return cookies
}

getAll()['AUTHTKN']
// => undefined
```
<p>within my app in real scenarios, i can set the cookie in my application goes like this, and when done this way my app can find the cookie, but mocking it within playwright is whats not seeming to work</p>
<pre class="lang-js prettyprint-override"><code>const set = (key, value, seconds, domain) => {
  // ...
  let string = `${key}=${value}`
  if (seconds) string += `; max-age=${seconds}`
  if (domain) string += `; domain=${domain}`
  string += `; path=/`
  document.cookie = string
}
const NINETYDAYSASSECONDS = 90 * 86400
cont token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzI1NDUyMzh9.AN93Ms3qkL_mkY2_bF_-mI3MvhXVKbrsV4BRPLLF5hs'
set('AUTHTKN', token, NINETYDAYSASSECONDS, null)
getAll()['AUTHTKN']
// => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzI1NDUyMzh9.AN93Ms3qkL_mkY2_bF_-mI3MvhXVKbrsV4BRPLLF5hs'
</code>```

I believe it has something to do with the domain as the issue or sameSite, but cant be sure

Body:
Edit

Further fact finding, it appears that this is an issue ONLY appearing in React v16, but i dont know why?

not appearing in React v18, or Vue v2.6.10

in my playwright test im setting a cookie in the browser context like this:

test.beforeEach(async ({ page, browser }) => {
  const context = await browser.newContext()
  await context.addCookies([
    {
      name: AUTHTKN,
      value: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzI1NDUyMzh9.AN93Ms3qkL_mkY2_bF_-mI3MvhXVKbrsV4BRPLLF5hs',
      domain: 'localhost',
      path: '/',
      expires: moment().add(24, 'hours')
    }
  ])

  const cookies = await context.cookies()
  console.log(JSON.stringify(cookies, null, 2))

  await page.goto('/')
})

using console.log i can see the output

I suspect this is an issue caused by playwright which seems to automatically inject sameSite, but not sure since this is a representation of the cookie and I have no ability (that i know of) how I could view it in browser to be sure

[
  {
    "name": "AUTHTKN",
    "value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzI1NDUyMzh9.AN93Ms3qkL_mkY2_bF_-mI3MvhXVKbrsV4BRPLLF5hs",
    "domain": "localhost",
    "path": "/",
    "expires": 7776000,
    "httpOnly": false,
    "secure": false,
    "sameSite": "Lax"
  }
]

in my application code, it fails to find the cookie, I load cookies from memory like this

const getAll = () => {
  const pairs = document.cookie.split(';')
  const cookies = {}
  for (let i = 0; i < pairs.length; i++) {
    var pair = pairs[i].split('=')
    cookies[(pair[0] + '').trim()] = unescape(pair.slice(1).join('='))
  }
  return cookies
}

getAll()['AUTHTKN']
// => undefined

within my app in real scenarios, i can set the cookie in my application goes like this, and when done this way my app can find the cookie, but mocking it within playwright is whats not seeming to work

const set = (key, value, seconds, domain) => {
  // ...
  let string = `${key}=${value}`
  if (seconds) string += `; max-age=${seconds}`
  if (domain) string += `; domain=${domain}`
  string += `; path=/`
  document.cookie = string
}
const NINETYDAYSASSECONDS = 90 * 86400
cont token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzI1NDUyMzh9.AN93Ms3qkL_mkY2_bF_-mI3MvhXVKbrsV4BRPLLF5hs'
set('AUTHTKN', token, NINETYDAYSASSECONDS, null)
getAll()['AUTHTKN']
// => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzI1NDUyMzh9.AN93Ms3qkL_mkY2_bF_-mI3MvhXVKbrsV4BRPLLF5hs'

I believe it has something to do with the domain as the issue or sameSite, but cant be sure


问:
How can I get these variables to output together?
I can't seem to get $d1 and $d2 to print together. Would like to include all columns in one output. (UID, HDate, Email and Office)

```<code>$txt1 = "C:\Users\Alex\Downloads\New folder\datafile01.txt"
$txt2 = "C:\Users\Alex\Downloads\New folder\datafile02.txt"
$newtxt = "C:\Users\Alex\Downloads\New folder\new.txt"

$d1 = Import-Csv $txt1 -Delimiter `t -Header "UID", "HDate"| Select-Object -Property *
$d2 = Import-Csv $txt2 -Delimiter `t -Header "UID", "Email", "Office" | Select-Object -Property "Email", "Office"

#$d1
$d2
</code>```

Can't figure out how to output d1 + d2 together, like concatenate them but while keeping their respective columns.

Body:
I can't seem to get $d1 and $d2 to print together. Would like to include all columns in one output. (UID, HDate, Email and Office)

$txt1 = "C:\Users\Alex\Downloads\New folder\datafile01.txt"
$txt2 = "C:\Users\Alex\Downloads\New folder\datafile02.txt"
$newtxt = "C:\Users\Alex\Downloads\New folder\new.txt"

$d1 = Import-Csv $txt1 -Delimiter `t -Header "UID", "HDate"| Select-Object -Property *
$d2 = Import-Csv $txt2 -Delimiter `t -Header "UID", "Email", "Office" | Select-Object -Property "Email", "Office"

#$d1
$d2

Can't figure out how to output d1 + d2 together, like concatenate them but while keeping their respective columns.


问:
How to get more font weights from Google Fonts than what they provide (or, how does Figma do it)?
Looking at the Lato Google Font...

They provide font weights of 300, 400, 700 and 900.

If I use the provided links/stylesheet or attach the font files directly, I can only use those sizes. If I try something like:

```<code>.text {
    font-weight: 500;  // Weight not provided by GF
}
</code>```

it displays the same as 400. And if I try with 600 it displays the same as 700.

But using the exact same font files, I have much more granularity when doing my design in Figma. They are using the file that I provided to them, with only the limited set of weights. But I can switch through a dozen different sizes (thin, x-light, light... ) and each one has a distinctly different weight than the others.

Figma runs in the browser, so there is clearly a way to emulate the in-between weights somehow.

So, to the point: How does Figma do it? How can I get the in-between weights that I used in my (browser-based) design in Figma, but can't seem to do via CSS?

Body:
Looking at the Lato Google Font...

They provide font weights of 300, 400, 700 and 900.

If I use the provided links/stylesheet or attach the font files directly, I can only use those sizes. If I try something like:

.text {
    font-weight: 500;  // Weight not provided by GF
}

it displays the same as 400. And if I try with 600 it displays the same as 700.

But using the exact same font files, I have much more granularity when doing my design in Figma. They are using the file that I provided to them, with only the limited set of weights. But I can switch through a dozen different sizes (thin, x-light, light... ) and each one has a distinctly different weight than the others.

Figma runs in the browser, so there is clearly a way to emulate the in-between weights somehow.

So, to the point: How does Figma do it? How can I get the in-between weights that I used in my (browser-based) design in Figma, but can't seem to do via CSS?


问:
How do I attach my email to the "send message" button?
I'm trying to create my own website using this HTML5 template. I have no background in HTML.

I'm trying to make the last section, Contact Me, send a message directly from the website. The code that I think is relevant from the link above (again, no background in HTML) is:

```<code><section id="Contact">
    <div class="container">
        <h3>Contact Me</h3>
        <p>Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer non. Adipiscing cubilia elementum integer. Integer eu ante ornare amet commetus.</p>
        <form method="post" action="#">
            <div class="row gtr-uniform">
                <div class="col-6 col-12-xsmall"><input type="text" name="name" id="name" placeholder="Name" /></div>
                <div class="col-6 col-12-xsmall"><input type="email" name="email" id="email" placeholder="Email" /></div>
                <div class="col-12"><input type="text" name="subject" id="subject" placeholder="Subject" /></div>
                <div class="col-12"><textarea name="message" id="message" placeholder="Message" rows="6"></textarea></div>
                <div class="col-12">
                    <ul class="actions">
                        <li><input type="submit" class="primary" value="Send Message" /></li>
                        <li><input type="reset" value="Reset Form" /></li>
                    </ul>
                </div>
            </div>
        </form>
    </div>
</section>
</code>```

I was trying to understand which part of it I need to change to make this happen. From this SO question I understand that the relevant line might be <form method="post" action="#">. I changed it to be <form method="post" action="mailto:my_email@gmail.com">, but it opens the user's outlook email instead of directly sending from the website, and the message in the outlook is also messed up: name=some_name&email=some_email_test&subject=test&message=some+message

Body:
I'm trying to create my own website using this HTML5 template. I have no background in HTML.

I'm trying to make the last section, Contact Me, send a message directly from the website. The code that I think is relevant from the link above (again, no background in HTML) is:

Contact Me

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer non. Adipiscing cubilia elementum integer. Integer eu ante ornare amet commetus.

        <form method="post" action="#">

<input type="text" name="name" id="name" placeholder="Name" />

<input type="email" name="email" id="email" placeholder="Email" />

<input type="text" name="subject" id="subject" placeholder="Subject" />

<textarea name="message" id="message" placeholder="Message" rows="6"></textarea>

<input type="submit" class="primary" value="Send Message" />

<input type="reset" value="Reset Form" />

        </form>

I was trying to understand which part of it I need to change to make this happen. From this SO question I understand that the relevant line might be <form method="post" action="#">. I changed it to be <form method="post" action="mailto:my_email@gmail.com">, but it opens the user's outlook email instead of directly sending from the website, and the message in the outlook is also messed up: name=some_name&email=some_email_test&subject=test&message=some+message


问:
Can not create project and debugging code on visual code
I has just installed Microsoft Visual Studio 2022. But I can not create file in project, as a result Start debugging is disable.
How can I debug code in this case.


问:
try/except vs validate the data while inserting to avoid "Violation of UNIQUE KEY constraint"?
Which is the better option for performance?

Python try/except?

```<code>try:
    cursor.execute('INSERT INTO date (iyear, imonth, iday) VALUES (?,?,?)',year, month, day)
except Exception:
    pass
</code>```

or validate the data in database?

```<code>cursor.execute('IF NOT EXISTS (SELECT TOP 1 * FROM date where iyear = ? and imonth = ? and iday = ?) INSERT INTO date (iyear, imonth, iday) VALUES (?,?,?)',year, month, day,year, month, day)
</code>```

Actually I am not sure if using if not exists is the better option to validate the data. Is there any better way to do it?

Body:
Which is the better option for performance?

Python try/except?

try:
    cursor.execute('INSERT INTO date (iyear, imonth, iday) VALUES (?,?,?)',year, month, day)
except Exception:
    pass

or validate the data in database?

cursor.execute('IF NOT EXISTS (SELECT TOP 1 * FROM date where iyear = ? and imonth = ? and iday = ?) INSERT INTO date (iyear, imonth, iday) VALUES (?,?,?)',year, month, day,year, month, day)

Actually I am not sure if using if not exists is the better option to validate the data. Is there any better way to do it?


问:
Django: mysterious slow request before timing middleware kicks in
I'm using Django with Sentry to monitor errors and performance. There's one specific endpoint (this doesn't happen with other endpoints) that seems to stall for a few seconds before actually processing the request.

It's a very simple endpoint, but it does get called a lot.

It seems to do nothing for a few seconds and is waiting on the time before Django middleware is even called.

The actual logic that goes into rendering only takes a few hundred milliseconds: something is happening before the Django middleware that causes this to only happen for this view.

What could this mean? I don't often see the Django.db.close_old_connections call and I'm hoping someone might have a clue for what might be causing it when the stall is after that, with another stall in the same place towards the end right before close_old_connections is called again.


问:
Getting InflateException ("Error inflating class") when inflating AppCompatImageView
I'm working on a Xamarin app with an existing .aar lib. The lib was tested with a native Android demo application, and it works fine with the demo.

But when I invoke it through my Xamarin app, following InflateException was always thrown:

Android.Views.InflateException: 'Binary XML file line #1 in com.radaee.reader:layout/bar_cmd: Binary XML file line #1 in com.radaee.reader:layout/bar_cmd: Error inflating class androidx.appcompat.widget.AppCompatImageView'

Looks like some dependencies are missing from the Xamarin project, but I've added following dependencies from NuGet:

Xamarin.AndroidX.AppCompat

Xamarin.AndroidX.AppCompat.AppCompatResources

Xamarin.Android.Support.v4

Those are basically what the Android native application used.
And here is how the lib project basically using the AppCompatImageView:

```<code><androidx.appcompat.widget.AppCompatImageView
    android:id="@+id/btn_back"
    android:layout_width="@dimen/toolbar_icons_size"
    android:layout_height="@dimen/toolbar_icons_size"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginStart="15dp"
    android:layout_marginEnd="15dp"
    app:srcCompat="@drawable/ic_arrow_back"
    android:tint="@color/red"/>
</code>```

How does this issue come up, and how should I fix it?

Body:
I'm working on a Xamarin app with an existing .aar lib. The lib was tested with a native Android demo application, and it works fine with the demo.

But when I invoke it through my Xamarin app, following InflateException was always thrown:

Android.Views.InflateException: 'Binary XML file line #1 in com.radaee.reader:layout/bar_cmd: Binary XML file line #1 in com.radaee.reader:layout/bar_cmd: Error inflating class androidx.appcompat.widget.AppCompatImageView'

Looks like some dependencies are missing from the Xamarin project, but I've added following dependencies from NuGet:

Xamarin.AndroidX.AppCompat

Xamarin.AndroidX.AppCompat.AppCompatResources

Xamarin.Android.Support.v4

Those are basically what the Android native application used.
And here is how the lib project basically using the AppCompatImageView:

<androidx.appcompat.widget.AppCompatImageView
    android:id="@+id/btn_back"
    android:layout_width="@dimen/toolbar_icons_size"
    android:layout_height="@dimen/toolbar_icons_size"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginStart="15dp"
    android:layout_marginEnd="15dp"
    app:srcCompat="@drawable/ic_arrow_back"
    android:tint="@color/red"/>

How does this issue come up, and how should I fix it?


问:
Django Application CPanel Internal Server Error 500
I am getting a Internal Server Error in my Django Application hosted in Cpanel . I have tables with Links and sublinks associated with those links .

so the url is like https://[domain]/links/ and https://[domain]/links// . Everything works fine on local host but whenever i go to the Sublink in the live website I get 500 Error.

I am really lost as I dont know how to debug this . I dont know how to start to look at the error . I looked at the log file and this is the ouput .

Can anyone tell me how to start debug this error since its running properly on the localhost so I cant find anything .


问:
Federated Learning Local Clients Flucuating Accuracies
I am currently working on a personalized federated learning research. The current simulation structure is as follows:

Global model with with 5 global rounds

Local model with 10 clients and 4 local rounds

Model is CNN for 11 classes classification.

While the code is running, the local models have accuracies all over the place. Here is an example:

Is this normal for personalized federated learning? I can also observe this behavior in all datasets that I have tried so far.

I do want to share more details with you, but since this is an ongoing research, I am not sure how much details I can share.

I have not tried anything else yet since my knowledge about federated learning is very limited, and I am not sure if there is an actual issue in first place.


问:
Using scipy optimizer with a pandas DataFrame objective function
I am trying to create an optimizer that better fits the moving average with the time series data by shifting it backwards, but I am running into them problem:

```<code>only integer scalar arrays can be converted to a scalar index.
</code>```

My objective function to minimize is:

```<code>def mse(shift, prices, d=5):
    ma = prices.rolling(d).mean().shift(-shift)
    return ((prices - ma)**2).sum()
</code>```

and the optimizer function is:

```<code>def reduce_MSE(prices: pd.Series, d: int) -> int:
    init_value = 1
    shift = minimize(mse, x0=init_value, args=(prices,d), options={'maxiter':10000}, bounds=((0.0, 10.0),))
    return shift
</code>```

I tried changing the objective function and saw the the line of code responsible for the error is

```<code>ma = prices.rolling(d).mean().shift(-shift)
</code>```

The optimizer worked fine if I removed this part of code. Also, my mse objective function works if I use it outside the optimizer.

My question is if it is not possible to use some pandas functions as objective functions for the optimizer or if I am doing it the wrong way.

Thanks

Body:
I am trying to create an optimizer that better fits the moving average with the time series data by shifting it backwards, but I am running into them problem:

only integer scalar arrays can be converted to a scalar index.

My objective function to minimize is:

def mse(shift, prices, d=5):
    ma = prices.rolling(d).mean().shift(-shift)
    return ((prices - ma)**2).sum()

and the optimizer function is:

def reduce_MSE(prices: pd.Series, d: int) -> int:
    init_value = 1
    shift = minimize(mse, x0=init_value, args=(prices,d), options={'maxiter':10000}, bounds=((0.0, 10.0),))
    return shift

I tried changing the objective function and saw the the line of code responsible for the error is

ma = prices.rolling(d).mean().shift(-shift)

The optimizer worked fine if I removed this part of code. Also, my mse objective function works if I use it outside the optimizer.

My question is if it is not possible to use some pandas functions as objective functions for the optimizer or if I am doing it the wrong way.

Thanks


问:
docker compose cannot detect the update after error
I try to use the docker-compose for mongodb and express which i know that there are some error on the mongodb part which remain unfix for the connection.But the there are error on server.js after when running docker-compose up.When i update the file , docker cannot detect the update which remain unchange with the same error message.

error message:

```<code> expressnew | ff
    expressnew | /usr/src/app/server.js:8
    expressnew | app.use(cors());
    expressnew |     ^
    expressnew |
    expressnew | ReferenceError: cors is not defined
    expressnew |     at Object.<anonymous> (/usr/src/app/server.js:8:5)
    expressnew |     at Module._compile (node:internal/modules/cjs/loader:1165:14)
    expressnew |     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1219:10)
    expressnew |     at Module.load (node:internal/modules/cjs/loader:1043:32)
    expressnew |     at Function.Module._load (node:internal/modules/cjs/loader:878:12)
    expressnew |     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    expressnew |     at node:internal/main/run_main_module:22:47
</code>```

my docker-compose.yml:

```<code>version: "3.8"

services:
  mongodb:
    container_name: mongo_ex
    image: mongo
    env_file: ./.env
    environment:
      - MONGO_INITDB_ROOT_USERNAME=Alexso0121
      - MONGO_INITDB_ROOT_PASSWORD=LR4135alex
    ports:
      - '27017:27017'
    volumes:
      - db:/data/db
  app:
    container_name: expressnew
    depends_on:
      - mongodb
    build: .
    env_file: ./.env
    ports:
      - '80:3000'
    environment:
      - DB_HOST=mongodb
      - DB_USER=alexso0121
      - DB_PASSWORD=LR4135alex
      - DB_NAME=
      - DB_PORT=$MONGODB_DOCKER_PORT
    stdin_open: true
    tty: true

volumes:
  db:
</code>```

server.js (after update):

```<code>const bodyParser = require('body-parser')
const express = require('express')
const app = express()
console.log("ff")
const mongoose=require('mongoose')
mongoose.set('strictQuery',false)
require('dotenv/config')

app.use(bodyParser.json());

const db=mongoose.connection
db.on('error',(error)=>console.error(error))
db.once('open',()=> console.log('connect to db'))

mongoose.connect(
    process.env.DB_CONNECTION
    ,{ useNewUrlParser:true })
app.use(logger)

//app.use(bodyParser.urlencoded({ extended: false }));

app.get('/',logger,(req,res)=>{
    console.log("ddd")
    //res.status(500)
    res.json({ username : "alex"})

})

const userRouter = require('./routes/users')

function logger(req,res,next){
    console.log(req.originalUrl)
    next()
}
app.use('/users',userRouter)
app.listen(3000)
</code>```

I have use docker-compose down but nothing happen which the container are not actually generated.I am wondering how to fix this.

Body:
I try to use the docker-compose for mongodb and express which i know that there are some error on the mongodb part which remain unfix for the connection.But the there are error on server.js after when running docker-compose up.When i update the file , docker cannot detect the update which remain unchange with the same error message.

error message:

 expressnew | ff
    expressnew | /usr/src/app/server.js:8
    expressnew | app.use(cors());
    expressnew |     ^
    expressnew |
    expressnew | ReferenceError: cors is not defined
    expressnew |     at Object.<anonymous> (/usr/src/app/server.js:8:5)
    expressnew |     at Module._compile (node:internal/modules/cjs/loader:1165:14)
    expressnew |     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1219:10)
    expressnew |     at Module.load (node:internal/modules/cjs/loader:1043:32)
    expressnew |     at Function.Module._load (node:internal/modules/cjs/loader:878:12)
    expressnew |     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    expressnew |     at node:internal/main/run_main_module:22:47

my docker-compose.yml:

version: "3.8"

services:
  mongodb:
    container_name: mongo_ex
    image: mongo
    env_file: ./.env
    environment:
      - MONGO_INITDB_ROOT_USERNAME=Alexso0121
      - MONGO_INITDB_ROOT_PASSWORD=LR4135alex
    ports:
      - '27017:27017'
    volumes:
      - db:/data/db
  app:
    container_name: expressnew
    depends_on:
      - mongodb
    build: .
    env_file: ./.env
    ports:
      - '80:3000'
    environment:
      - DB_HOST=mongodb
      - DB_USER=alexso0121
      - DB_PASSWORD=LR4135alex
      - DB_NAME=
      - DB_PORT=$MONGODB_DOCKER_PORT
    stdin_open: true
    tty: true

volumes:
  db:

server.js (after update):

const bodyParser = require('body-parser')
const express = require('express')
const app = express()
console.log("ff")
const mongoose=require('mongoose')
mongoose.set('strictQuery',false)
require('dotenv/config')

app.use(bodyParser.json());

const db=mongoose.connection
db.on('error',(error)=>console.error(error))
db.once('open',()=> console.log('connect to db'))

mongoose.connect(
    process.env.DB_CONNECTION
    ,{ useNewUrlParser:true })
app.use(logger)

//app.use(bodyParser.urlencoded({ extended: false }));

app.get('/',logger,(req,res)=>{
    console.log("ddd")
    //res.status(500)
    res.json({ username : "alex"})

})

const userRouter = require('./routes/users')

function logger(req,res,next){
    console.log(req.originalUrl)
    next()
}
app.use('/users',userRouter)
app.listen(3000)

I have use docker-compose down but nothing happen which the container are not actually generated.I am wondering how to fix this.


问:
IndexError is raised when trying to perform comparison in while loop
I am aware of indexError in python but I am unable to understand the logic behind my code throwing this error. I am not getting why the error is thrown for an existing list on using it as a condition in while loop.

```<code>def solve(A, B):
    cumsum = [A[0]] * len(A)
    for i in range(1,len(A)):
        cumsum[i] = cumsum[i-1] + A[i]
    final_arr = []
    for val in B:
        index = 0
        print(index, cumsum)
        print("INDEX Value:", cumsum[index])
        print(val)
        while (cumsum[index] <= val):
            index+=1
        final_arr.append(index)
    return final_arr

A = [3, 4, 4, 6]
B = [20, 4, 10, 2]
print(solve(A,B))
</code>```

The output I received on the online compiler is, as below

```<code>0 [3, 7, 11, 17]
INDEX Value: 3
20
Traceback (most recent call last):
  File "<string>", line 23, in <module>
File "<string>", line 14, in solve
IndexError: list index out of range
</code>```

The print function has no qualms in accessing the same index in the same list but as a while loop condition(Comparison) IndexError is thrown

Body:
I am aware of indexError in python but I am unable to understand the logic behind my code throwing this error. I am not getting why the error is thrown for an existing list on using it as a condition in while loop.

def solve(A, B):
    cumsum = [A[0]] * len(A)
    for i in range(1,len(A)):
        cumsum[i] = cumsum[i-1] + A[i]
    final_arr = []
    for val in B:
        index = 0
        print(index, cumsum)
        print("INDEX Value:", cumsum[index])
        print(val)
        while (cumsum[index] <= val):
            index+=1
        final_arr.append(index)
    return final_arr

A = [3, 4, 4, 6]
B = [20, 4, 10, 2]
print(solve(A,B))

The output I received on the online compiler is, as below

0 [3, 7, 11, 17]
INDEX Value: 3
20
Traceback (most recent call last):
  File "<string>", line 23, in <module>
File "<string>", line 14, in solve
IndexError: list index out of range

The print function has no qualms in accessing the same index in the same list but as a while loop condition(Comparison) IndexError is thrown


问:
SQL Server cannot connect to Visual Studio using Server Explorer
I'm a beginner developer, when I tried to connect database to Visual Studio by means of the Server Explorer, this error message pops up.

Does anyone know how to fix this?


问:
JB Rider 'Undo/redo Language Injection Configuration Update' with xaml.cs files instead of simple 'Undo/redo'
I'm using JB Rider to create WPF project. In editor for .xaml files there is usual Undo/Redo commands but in .xaml.cs Undo/Redo it is replaced by 'Undo/redo Language Injection Configuration Update' command and it is not working as usual Undo/Redo command.

Reviewed settings for xaml.cs files and Language injections settings but didn't find any useful options.

How to set Undo/Redo commands instead 'Undo/redo Language Injection Configuration Update' for .xaml.cs files?


问:
How can I make the gdb `disassemble` command use /s as a default option, through MI
I need to disassemble some C code, but I want to also show the source lines mixed in with the assembly code.  The issue I have is that I'm using gdb through the MI interface, which calls disassemble (or equivalent, perhaps -data-disassemble?), and I have no control over the options sent with the command.  If I did have access to the command, I could probably just use

-data-disassemble ... -- 1.

I've tried making a user-defined command, e.g.:

```<code>define dis
    disassemble /s
end
</code>```

but I don't know how to force using that command through gdb/mi.  I also tried making an alias, but it creates a naming conflict ("Alias disassemble is the name of an existing command") and probably wouldn't work anyway because of the MI connection.

I'd like to just add a line to my .gdbinit file that forces the /s option to be a default for disassemble, but I can't find any documentation that shows how this can be done.

As a side note, I'm trying to accomplish this in MSVC 2019, and I can sort of do it manually using the instructions from Microsoft's MIEngine custom command doc.  But this doesn't go through the usual gdb/mi interface, and just dumps text into the Command Window.  I was able to set disassembly-flavor intel, which works in changing the assembly into Intel format, so it seems like what I want to accomplish is at least plausible.

Body:
I need to disassemble some C code, but I want to also show the source lines mixed in with the assembly code.  The issue I have is that I'm using gdb through the MI interface, which calls disassemble (or equivalent, perhaps -data-disassemble?), and I have no control over the options sent with the command.  If I did have access to the command, I could probably just use

-data-disassemble ... -- 1.

I've tried making a user-defined command, e.g.:

define dis
    disassemble /s
end

but I don't know how to force using that command through gdb/mi.  I also tried making an alias, but it creates a naming conflict ("Alias disassemble is the name of an existing command") and probably wouldn't work anyway because of the MI connection.

I'd like to just add a line to my .gdbinit file that forces the /s option to be a default for disassemble, but I can't find any documentation that shows how this can be done.

As a side note, I'm trying to accomplish this in MSVC 2019, and I can sort of do it manually using the instructions from Microsoft's MIEngine custom command doc.  But this doesn't go through the usual gdb/mi interface, and just dumps text into the Command Window.  I was able to set disassembly-flavor intel, which works in changing the assembly into Intel format, so it seems like what I want to accomplish is at least plausible.


问:
react native webrtc replace video stream with new stream
I am implement screen captured inside my webrtc application, I successfull get mediaStream + get frame from Boardcast Extension, but I dont know why I can not replace the videotrack from localVideoTrack to screen captured video track, here is my code:


问:
Search bar is not being placed correctly, and footer is not responding to the CSS
I tried to make the search bar the same height as the navbar tags in the navbar but its just being blocked and placed weirdly. Second, my footer is not responding to the CSS as I want the
 to be under the icons and I want the footer thinner not huge and not wide enough from the sides.

footer {
  overflow: hidden;
  font-family: 'Times New Roman', Times, serif;
  min-width: 100%;
  /* Add this property */
  display: flex;
  justify-content: center;
  letter-spacing: 1px;
  font-size: 13px;
  padding: 10px 0;
}

.icon-container {
  display: flex;
}

.icon-container a {
  margin: 0 10px;
}

.icon-container i {
  font-size: 20px;
  /* Decrease from 30px */
  color: #333;
  border-radius: 50%;
  background: #fff;
  padding: 10px;
  transition: all 0.3s ease-out;
}

.icon-container i:hover {
  transform: scale(1.1);
  background: #333;
  color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div class="icon-container">
    <i class="fab fa-instagram"></i>
    <i class="fab fa-github"></i>
    <i class="fa fa-envelope"></i>
  </div>
  <br><br>
  <p>Developed with ❤ by Shahed &copy2022</p>
</footer></code>```

header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: rgba(51, 51, 51, 0.467);
  z-index: 1;
  /* Add this to make sure the navbar stays on top of other elements */
}

.navbar {
  overflow: hidden;
  background-color: rgba(43, 43, 45, 0.693);
  font-family: 'Times New Roman', Times, serif;
  width: 100%;
}

.navbar a {
  float: left;
  font-size: 18px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  cursor: pointer;
  font-size: 18px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.navbar a:hover,
.dropdown:hover .dropbtn,
.dropbtn:focus {
  background-color: rgba(189, 127, 137, 0.445);
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: rgba(189, 127, 137, 0.445);
  min-width: 142px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: white;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
  font-size: 15px;
}

.dropdown-content a:hover {
  background-color: rgba(189, 127, 137, 0.618);
}

.show {
  display: block;
  margin: 0 auto;
  /* add this line to center the chart horizontally */
}```

If you could please enlighten me and help me fix those errors I would appreciate it. Thanks in advance.

Body:
I tried to make the search bar the same height as the navbar tags in the navbar but its just being blocked and placed weirdly. Second, my footer is not responding to the CSS as I want the
 to be under the icons and I want the footer thinner not huge and not wide enough from the sides.

footer {
  overflow: hidden;
  font-family: 'Times New Roman', Times, serif;
  min-width: 100%;
  /* Add this property */
  display: flex;
  justify-content: center;
  letter-spacing: 1px;
  font-size: 13px;
  padding: 10px 0;
}

.icon-container {
  display: flex;
}

.icon-container a {
  margin: 0 10px;
}

.icon-container i {
  font-size: 20px;
  /* Decrease from 30px */
  color: #333;
  border-radius: 50%;
  background: #fff;
  padding: 10px;
  transition: all 0.3s ease-out;
}

.icon-container i:hover {
  transform: scale(1.1);
  background: #333;
  color: #fff;
}

Developed with ❤ by Shahed &copy2022

header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: rgba(51, 51, 51, 0.467);
  z-index: 1;
  /* Add this to make sure the navbar stays on top of other elements */
}

.navbar {
  overflow: hidden;
  background-color: rgba(43, 43, 45, 0.693);
  font-family: 'Times New Roman', Times, serif;
  width: 100%;
}

.navbar a {
  float: left;
  font-size: 18px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  cursor: pointer;
  font-size: 18px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.navbar a:hover,
.dropdown:hover .dropbtn,
.dropbtn:focus {
  background-color: rgba(189, 127, 137, 0.445);
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: rgba(189, 127, 137, 0.445);
  min-width: 142px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: white;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
  font-size: 15px;
}

.dropdown-content a:hover {
  background-color: rgba(189, 127, 137, 0.618);
}

.show {
  display: block;
  margin: 0 auto;
  /* add this line to center the chart horizontally */
}

If you could please enlighten me and help me fix those errors I would appreciate it. Thanks in advance.


问:
Want to be able to drag the things in the listbox into the workspace
I am trying to get the content in the listbox able to be dragged into the workspace as a block. Like scratch. I used OpenAi to give me ideas of how to do it, and it gave me that there is a draggable option I can put into the code as you can see, but when I try to drag the items in the listbox it wont let me.</p>
```<code>import PySimpleGUI as sg
from PIL import ImageGrab

# Create a list of Python code to display in the scroller
code_lines = [
    "variable",
    "loops",
    "types of variables"
]

# Create the window layout
layout = [  [sg.Column([[sg.Listbox(values=code_lines, size=(20, 10), key='Python Code', draggable = True)]]),
             sg.Column([[sg.Text('Workspace:', size=(20, 1)), sg.Multiline(size=(50, 30), key='workspace', background_color='dark gray')]])],
            [sg.Button('Close')] ]

# Create the window
window = sg.Window('PyDrop', layout)

# Event loop to process events
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Close':  # if user closes window or clicks close button
        break
    elif event == 'Python Code':  # if user clicks on an item in the listbox
        # stores the value of the clicked item in a variable
        dragged_item = values['Python Code'][0]
    elif event == sg.DRAG:  # if user moves the mouse while holding down the button
        # updates the value of the drop target
        print('Drag event triggered')
        window['drop_target'].update(dragged_item)

# Close the window
window.close()

</code>```

Body:
I am trying to get the content in the listbox able to be dragged into the workspace as a block. Like scratch. I used OpenAi to give me ideas of how to do it, and it gave me that there is a draggable option I can put into the code as you can see, but when I try to drag the items in the listbox it wont let me.

import PySimpleGUI as sg
from PIL import ImageGrab

# Create a list of Python code to display in the scroller
code_lines = [
    "variable",
    "loops",
    "types of variables"
]

# Create the window layout
layout = [  [sg.Column([[sg.Listbox(values=code_lines, size=(20, 10), key='Python Code', draggable = True)]]),
             sg.Column([[sg.Text('Workspace:', size=(20, 1)), sg.Multiline(size=(50, 30), key='workspace', background_color='dark gray')]])],
            [sg.Button('Close')] ]

# Create the window
window = sg.Window('PyDrop', layout)

# Event loop to process events
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Close':  # if user closes window or clicks close button
        break
    elif event == 'Python Code':  # if user clicks on an item in the listbox
        # stores the value of the clicked item in a variable
        dragged_item = values['Python Code'][0]
    elif event == sg.DRAG:  # if user moves the mouse while holding down the button
        # updates the value of the drop target
        print('Drag event triggered')
        window['drop_target'].update(dragged_item)

# Close the window
window.close()


问:
Python network scanner (host discovery tool) is telling me that my source and destination are the same when sending UDP datagrams
I'm following Black Hat Python (2ed.), in which I'm writing a network scanning tool. The tool is in theory supposed to send UDP packets out to a given subnet, and if a host is up on that subnet, the response packet is decoded, found to contain the message in the original datagram, and used to indicate the host is up. This seems to generally be working well to capture packets; I can go to a website, or ping another host, and the tool reliably provides the correct source and destination addresses for those cases.

Here is the meat of the code (I have not included the class creation, or the passing of the host argument for brevity, but the host is 192.168.10.85).

```<code>class IP:
    """layer 3 (IP) packet header decoder"""
    def __init__(self, buff=None):
        header = struct.unpack('<BBHHHBBH4s4s', buff)
        self.ver = header[0] >> 4
        self.ihl = header[0] & 0xF
        self.tos = header[1]
        self.len = header[2]
        self.id = header[3]
        self.offset = header[4]
        self.ttl = header[5]
        self.protocol_num = header[6]
        self.sum = header[7]
        self.src = header[8]
        self.dst = header[9]

        # make IP addrs human readable
        self.src_address = ipaddress.ip_address(self.src)
        self.dst_address = ipaddress.ip_address(self.dst)

        # the protocol_num is actually a code for the protocol name
        self.protocol_name = {1: 'ICMP', 6: 'TCP', 17: 'UDP'}

        # try to provide the human version of the protocol, otherwise just give the code
        try:
            self.protocol = self.protocol_name[self.protocol_num]
        except KeyError as error:
            self.protocol = self.protocol_num
            print(f'Protocol is unrecognized, try googling "IP protocol {self.protocol_num}"')

class ICMP:
    """layer 4 (ICMP) packet header decoder"""
    def __init__(self, buff):
        header = struct.unpack('<BBHHH', buff)
        self.type = header[0]
        self.code = header[1]
        self.checksum = header[2]
        self.ident = header[3]
        self.seq_num = header[4]

def udp_sender():
    # blasts udp packets into the network to solicit responses
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender:
        for ip in ipaddress.ip_network(SUBNET).hosts():
            # time.sleep(1)
            print(f'sending a test message to {ip}')
            # send our test message out to port 65212 on the destination
            sender.sendto(bytes(MESSAGE, 'utf8'), (str(ip), 65212))

class Scanner:
    def __init__(self, host):
        self.host = host
        # create raw socket, bind to public interface
        # if windows:
        if os.name == 'nt':
            socket_protocol = socket.IPPROTO_IP
        # if linux/mac:
        else:
            socket_protocol = socket.IPPROTO_ICMP
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
        self.socket.bind((host, 0))
        # socket options, include header
        self.socket.setsockopt(socket_protocol, socket.IP_HDRINCL, 1)
        # enable promiscuous mode for windows
        if os.name == 'nt':
            self.socket.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

    def sniff(self):
        # set of all hosts that are up (respond to our ICMP message)
        hosts_up = {f'{str(self.host)} *'}
        try:
            while True:
                # read a packet, and parse the IP header
                raw_buffer = self.socket.recvfrom(65535)[0]
                # create IP header from the first 20 bytes
                ip_header = IP(raw_buffer[0:20])
                # if the protocol is ICMP, do some additional things
                # print(f'src={ip_header.src_address}, dst={ip_header.dst_address}, prot_name={ip_header.protocol}')
                if ip_header.protocol == 'ICMP':
                    # calculate where the ICMP packet starts
                    offset = ip_header.ihl * 4
                    buf = raw_buffer[offset:offset + 8]
                    # create ICMP structure
                    icmp_header = ICMP(buf)
                    print(f'type: {icmp_header.type}, code: {icmp_header.code}')
                    print(f'src={ip_header.src_address}, dst={ip_header.dst_address}, prot_name={ip_header.protocol}')
                    if icmp_header.type == 3 and icmp_header.code == 3:
                        print(f'type: {icmp_header.type}, code: {icmp_header.code}')
                        print(f'src={ip_header.src_address}, dst={ip_header.dst_address}, prot_name={ip_header.protocol}')
                        if ipaddress.ip_address(ip_header.src_address) in ipaddress.IPv4Network(SUBNET):
                            # make sure the packet has our test message
                            if raw_buffer[len(raw_buffer) - len(MESSAGE):] == bytes(MESSAGE, 'utf8'):
                                tgt = str(ip_header.src_address)
                                if tgt != self.host and tgt not in hosts_up:
                                    hosts_up.add(str(ip_header.src_address))
                                    print(f'Host Up: {tgt}')
</code>```

However, when receiving the ICMP responses as a result of my datagram, the tool reports that the source and destination addresses are the same (my host, 192.168.10.85). Furthermore, while I should be receiving responses with Type 3 and Code 3 (destination unreachable, and port unreachable), but I am receiving (in my program) Type 3 and Code 1.

Here is an example of the output when I issue a ping command while the scanner is running, which seems correct:

src=192.168.10.85, dst=192.168.10.200, prot_name=ICMP type: 0, code: 0 src=192.168.10.200, dst=192.168.10.85, prot_name=ICMP type: 8, code: 0

Here is an example of the output to what I am assuming is the UDP packet response, which seems incorrect):
src=192.168.10.85, dst=192.168.10.85, prot_name=ICMP type: 3, code: 1

If I open wireshark while I'm running my code, I can correctly see the ICMP Type 3/Code 3 responses, so I know they are going through, here is a screen grab of one host on the target subnet as an example:

Why is my scanner not seeing these responses that are in wireshark?

I've tried running wireshark alongside my program, to see if the packets are being correctly decoded, and that the message in the UDP packet is properly in place. All signs indicate that the packets are going out to the hosts I'm trying to detect, and the correct responses are coming back, but my scanner refuses to find them.

Body:
I'm following Black Hat Python (2ed.), in which I'm writing a network scanning tool. The tool is in theory supposed to send UDP packets out to a given subnet, and if a host is up on that subnet, the response packet is decoded, found to contain the message in the original datagram, and used to indicate the host is up. This seems to generally be working well to capture packets; I can go to a website, or ping another host, and the tool reliably provides the correct source and destination addresses for those cases.

Here is the meat of the code (I have not included the class creation, or the passing of the host argument for brevity, but the host is 192.168.10.85).

class IP:
    """layer 3 (IP) packet header decoder"""
    def __init__(self, buff=None):
        header = struct.unpack('<BBHHHBBH4s4s', buff)
        self.ver = header[0] >> 4
        self.ihl = header[0] & 0xF
        self.tos = header[1]
        self.len = header[2]
        self.id = header[3]
        self.offset = header[4]
        self.ttl = header[5]
        self.protocol_num = header[6]
        self.sum = header[7]
        self.src = header[8]
        self.dst = header[9]

        # make IP addrs human readable
        self.src_address = ipaddress.ip_address(self.src)
        self.dst_address = ipaddress.ip_address(self.dst)

        # the protocol_num is actually a code for the protocol name
        self.protocol_name = {1: 'ICMP', 6: 'TCP', 17: 'UDP'}

        # try to provide the human version of the protocol, otherwise just give the code
        try:
            self.protocol = self.protocol_name[self.protocol_num]
        except KeyError as error:
            self.protocol = self.protocol_num
            print(f'Protocol is unrecognized, try googling "IP protocol {self.protocol_num}"')

class ICMP:
    """layer 4 (ICMP) packet header decoder"""
    def __init__(self, buff):
        header = struct.unpack('<BBHHH', buff)
        self.type = header[0]
        self.code = header[1]
        self.checksum = header[2]
        self.ident = header[3]
        self.seq_num = header[4]

def udp_sender():
    # blasts udp packets into the network to solicit responses
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender:
        for ip in ipaddress.ip_network(SUBNET).hosts():
            # time.sleep(1)
            print(f'sending a test message to {ip}')
            # send our test message out to port 65212 on the destination
            sender.sendto(bytes(MESSAGE, 'utf8'), (str(ip), 65212))

class Scanner:
    def __init__(self, host):
        self.host = host
        # create raw socket, bind to public interface
        # if windows:
        if os.name == 'nt':
            socket_protocol = socket.IPPROTO_IP
        # if linux/mac:
        else:
            socket_protocol = socket.IPPROTO_ICMP
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
        self.socket.bind((host, 0))
        # socket options, include header
        self.socket.setsockopt(socket_protocol, socket.IP_HDRINCL, 1)
        # enable promiscuous mode for windows
        if os.name == 'nt':
            self.socket.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

    def sniff(self):
        # set of all hosts that are up (respond to our ICMP message)
        hosts_up = {f'{str(self.host)} *'}
        try:
            while True:
                # read a packet, and parse the IP header
                raw_buffer = self.socket.recvfrom(65535)[0]
                # create IP header from the first 20 bytes
                ip_header = IP(raw_buffer[0:20])
                # if the protocol is ICMP, do some additional things
                # print(f'src={ip_header.src_address}, dst={ip_header.dst_address}, prot_name={ip_header.protocol}')
                if ip_header.protocol == 'ICMP':
                    # calculate where the ICMP packet starts
                    offset = ip_header.ihl * 4
                    buf = raw_buffer[offset:offset + 8]
                    # create ICMP structure
                    icmp_header = ICMP(buf)
                    print(f'type: {icmp_header.type}, code: {icmp_header.code}')
                    print(f'src={ip_header.src_address}, dst={ip_header.dst_address}, prot_name={ip_header.protocol}')
                    if icmp_header.type == 3 and icmp_header.code == 3:
                        print(f'type: {icmp_header.type}, code: {icmp_header.code}')
                        print(f'src={ip_header.src_address}, dst={ip_header.dst_address}, prot_name={ip_header.protocol}')
                        if ipaddress.ip_address(ip_header.src_address) in ipaddress.IPv4Network(SUBNET):
                            # make sure the packet has our test message
                            if raw_buffer[len(raw_buffer) - len(MESSAGE):] == bytes(MESSAGE, 'utf8'):
                                tgt = str(ip_header.src_address)
                                if tgt != self.host and tgt not in hosts_up:
                                    hosts_up.add(str(ip_header.src_address))
                                    print(f'Host Up: {tgt}')

However, when receiving the ICMP responses as a result of my datagram, the tool reports that the source and destination addresses are the same (my host, 192.168.10.85). Furthermore, while I should be receiving responses with Type 3 and Code 3 (destination unreachable, and port unreachable), but I am receiving (in my program) Type 3 and Code 1.

Here is an example of the output when I issue a ping command while the scanner is running, which seems correct:

src=192.168.10.85, dst=192.168.10.200, prot_name=ICMP type: 0, code: 0 src=192.168.10.200, dst=192.168.10.85, prot_name=ICMP type: 8, code: 0

Here is an example of the output to what I am assuming is the UDP packet response, which seems incorrect):
src=192.168.10.85, dst=192.168.10.85, prot_name=ICMP type: 3, code: 1

If I open wireshark while I'm running my code, I can correctly see the ICMP Type 3/Code 3 responses, so I know they are going through, here is a screen grab of one host on the target subnet as an example:

Why is my scanner not seeing these responses that are in wireshark?

I've tried running wireshark alongside my program, to see if the packets are being correctly decoded, and that the message in the UDP packet is properly in place. All signs indicate that the packets are going out to the hosts I'm trying to detect, and the correct responses are coming back, but my scanner refuses to find them.