问:
How to make clangd recognize gcc header files under macOS
I'm trying to use vscode-clangd plugin to complete my code. I've tried to use--query-driver and other parameters. Neither of them can recognize g+++ 12's header file properly, but clions that are also clangd based can recognize gcc's header file properly. Is this a bug? How should I fix it?

I tried to open the same CMake project with two compilers. These are their differences

This is the header directory given by vscode.
screenshot

settings.json

```<code>{
"C_Cpp.intelliSenseEngine": "Disabled",
"clangd.arguments": [
"-log=verbose",
"--query-driver=/usr/local/Cellar/gcc/12.2.0/bin/x86_64-apple-darwin22-g++-12,/usr/local/Cellar/gcc/12.2.0/bin/g++-12",
"--compile-commands-dir=/Users/season/Projects/cplusplus/Projects/acm_cmake/cmake-build-debug/compile_commands.json"
],
"cmake.configureOnOpen": true,
"cmake.configureArgs": [
"-D CMAKE_CXX_COMPILER=/usr/local/Cellar/gcc/12.2.0/bin/g++-12",
"-DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
]
}
</code>```

Compile_commands.json

```<code>[
{
"directory": "/Users/season/Projects/cplusplus/Projects/acm_cmake/cmake-build-debug",
"command": "/usr/local/Cellar/gcc/12.2.0/bin/g++-12 -g -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX13.0.sdk -fdiagnostics-color=always -std=gnu++14 -o CMakeFiles/acm_cmake.dir/main.cpp.o -c /Users/season/Projects/cplusplus/Projects/acm_cmake/main.cpp",
"file": "/Users/season/Projects/cplusplus/Projects/acm_cmake/main.cpp"
}
]
</code>```

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.23)
project(acm_cmake)

set(CMAKE_CXX_STANDARD 14)
#set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

add_executable(acm_cmake main.cpp)
</code>```

This is the header directory given by Clion.
screenshot

Clion's CMake options

screenshot

```<code>-D CMAKE_CXX_COMPILER=/usr/local/Cellar/gcc/12.2.0/bin/g++-12 -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
</code>```

Detail Logs

https://pastebin.com/nqCsVAuQ

System information

$ clangd --version

Homebrew clangd version 15.0.6

Features: mac+xpc

Platform: x86_64-apple-darwin22.1.0

clangd extension version:

clangd v0.1.15

Operating system:

macOS Ventura 13.0.1 (22A400)

I tried to use - I fallback arguments to specify the directory of the header file, but clangd will give many error prompts.

```<code>"clangd.fallbackFlags": [
        "-I/usr/local/Cellar/gcc/12.2.0/include/c++/12",
        "-I/usr/local/Cellar/gcc/12.2.0/include/c++/12/x86_64-apple-darwin22"
    ],
</code>```

screenshot

And I searched for similar problems on google, and I didn't find.

Body:
I'm trying to use vscode-clangd plugin to complete my code. I've tried to use--query-driver and other parameters. Neither of them can recognize g+++ 12's header file properly, but clions that are also clangd based can recognize gcc's header file properly. Is this a bug? How should I fix it?

I tried to open the same CMake project with two compilers. These are their differences

This is the header directory given by vscode.
screenshot

settings.json

{
"C_Cpp.intelliSenseEngine": "Disabled",
"clangd.arguments": [
"-log=verbose",
"--query-driver=/usr/local/Cellar/gcc/12.2.0/bin/x86_64-apple-darwin22-g++-12,/usr/local/Cellar/gcc/12.2.0/bin/g++-12",
"--compile-commands-dir=/Users/season/Projects/cplusplus/Projects/acm_cmake/cmake-build-debug/compile_commands.json"
],
"cmake.configureOnOpen": true,
"cmake.configureArgs": [
"-D CMAKE_CXX_COMPILER=/usr/local/Cellar/gcc/12.2.0/bin/g++-12",
"-DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
]
}

Compile_commands.json

[
{
"directory": "/Users/season/Projects/cplusplus/Projects/acm_cmake/cmake-build-debug",
"command": "/usr/local/Cellar/gcc/12.2.0/bin/g++-12 -g -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX13.0.sdk -fdiagnostics-color=always -std=gnu++14 -o CMakeFiles/acm_cmake.dir/main.cpp.o -c /Users/season/Projects/cplusplus/Projects/acm_cmake/main.cpp",
"file": "/Users/season/Projects/cplusplus/Projects/acm_cmake/main.cpp"
}
]

CMakeLists.txt

cmake_minimum_required(VERSION 3.23)
project(acm_cmake)

set(CMAKE_CXX_STANDARD 14)
#set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

add_executable(acm_cmake main.cpp)

This is the header directory given by Clion.
screenshot

Clion's CMake options

screenshot

-D CMAKE_CXX_COMPILER=/usr/local/Cellar/gcc/12.2.0/bin/g++-12 -DCMAKE_EXPORT_COMPILE_COMMANDS=ON

Detail Logs

https://pastebin.com/nqCsVAuQ

System information

$ clangd --version

Homebrew clangd version 15.0.6

Features: mac+xpc

Platform: x86_64-apple-darwin22.1.0

clangd extension version:

clangd v0.1.15

Operating system:

macOS Ventura 13.0.1 (22A400)

I tried to use - I fallback arguments to specify the directory of the header file, but clangd will give many error prompts.

"clangd.fallbackFlags": [
        "-I/usr/local/Cellar/gcc/12.2.0/include/c++/12",
        "-I/usr/local/Cellar/gcc/12.2.0/include/c++/12/x86_64-apple-darwin22"
    ],

screenshot

And I searched for similar problems on google, and I didn't find.


来源: stackexchange

问:
Is it possible to make a recursive tree-like tuple in TypeScript?

How to make a recursive tree-like tuple?

I have a function for recursively getting the value of an object's property:

function getValue(obj: object, ...keys: string[]): any
```
<p>and here is what it does given an object:</p>
<pre class="lang-js prettyprint-override"><code>const testObject = {
  hello: {
    world: "Hello world!",
    user: "Hello user!"
  },
  first: {
    second: 2
  },
  shallow: {
    deep: true
  }
}
console.log(getValue(testObject, "first")); // { second: 2 }
console.log(getValue(testObject, "hello", "world")); // Hello world!
console.log(getValue(testObject, "shallow", "deep")); // true
</code>```

My goal is adding autocomplete into the function parameters:

function getValueTyped<T extends object>(obj: T, ...keys: TreeKeys<T>): any
```
<h3><strong>Please note</strong> that this function should be able to work with <strong>any given object type!</strong></h3>
<p>and the concept is (with the same object as above):</p>
<pre class="lang-js prettyprint-override"><code>getValueTyped<typeof testObject>(
  testObject,
  "hello", // This parameter shows as a union: ("hello" | "first" | "shallow")
  "world" // IF the previous parameter is "hello", than this one is ("world" | "user")
);
getValueTyped<typeof testObject>(
  testObject,
  "first", // This parameter shows as a union: ("hello" | "first" | "shallow")
  "second" // IF the previous parameter is "first", than this one is only "second"
);

</code>```

While trying to solve this, I came up with a few things. The type of the keys argument should be a tuple with generics, something like this:

type TreeKeys<T extends object, K extends keyof T = keyof T> = [
  K, // The first property
  ...(K extends object ? TreeKeys<T[K], keyof T[K]> : [])
];
```

but it obviously didn't work. I think using infer might help, but I am not sure in how to implement this or if this is even possible.
If this is still not possible but there is a proposal, I would like to take a look at it.

Any help would be appreciated!

ContentLicense: CC BY-SA 4.0

Body:
How to make a recursive tree-like tuple?

I have a function for recursively getting the value of an object's property:

function getValue(obj: object, ...keys: string[]): any

and here is what it does given an object:

const testObject = {
  hello: {
    world: "Hello world!",
    user: "Hello user!"
  },
  first: {
    second: 2
  },
  shallow: {
    deep: true
  }
}
console.log(getValue(testObject, "first")); // { second: 2 }
console.log(getValue(testObject, "hello", "world")); // Hello world!
console.log(getValue(testObject, "shallow", "deep")); // true

My goal is adding autocomplete into the function parameters:

function getValueTyped<T extends object>(obj: T, ...keys: TreeKeys<T>): any

Please note that this function should be able to work with any given object type!

and the concept is (with the same object as above):

getValueTyped<typeof testObject>(
  testObject,
  "hello", // This parameter shows as a union: ("hello" | "first" | "shallow")
  "world" // IF the previous parameter is "hello", than this one is ("world" | "user")
);
getValueTyped<typeof testObject>(
  testObject,
  "first", // This parameter shows as a union: ("hello" | "first" | "shallow")
  "second" // IF the previous parameter is "first", than this one is only "second"
);

While trying to solve this, I came up with a few things. The type of the keys argument should be a tuple with generics, something like this:

type TreeKeys<T extends object, K extends keyof T = keyof T> = [
  K, // The first property
  ...(K extends object ? TreeKeys<T[K], keyof T[K]> : [])
];

but it obviously didn't work. I think using infer might help, but I am not sure in how to implement this or if this is even possible.
If this is still not possible but there is a proposal, I would like to take a look at it.

Any help would be appreciated!


问:
VBA Code works with button but doesn't work with shortcut
I have an Excel Sheet (destination.xlsm) where I want to import data from another sheet (source.xlsm).

I let the user select the source file using GetOpenFilenames.

I open the file selected

I copy some range from the selected file and paste it to the destination file (in which there is a module where this code is stored.)

Issue:

Code works when I call the Sub using F5 or Run button inside the VBA editor. Code also works if I create a button and assign this macro to the button on the worksheet. However, when I assign the macro a keyboard shortcut from Macro Manager in Excel, then the code stops after opening the source file. All operations after that are not done.

Again if I debug the code and run it in steps (F8), then again everything works fine.

Sample Code:

```<code>Sub sample_code()

Dim file as Variant
file = Application.GetOpenFilename("Excel Files(*.xlsm*),*.xlsm*")
Dim oBook as Workbook
Set oBook = Application.Workbooks.Open(file)
Dim oSheet as Worksheet
Set oSheet = oBook.Worksheets("List")

'*Code to copy some range from oSheet and paste it to a sheet in ThisWorkbook.Worksheet("ConsolidatedList")*

End Sub
</code>```

What could be the issue here? How should I proceed with this issue?

Body:
I have an Excel Sheet (destination.xlsm) where I want to import data from another sheet (source.xlsm).

I let the user select the source file using GetOpenFilenames.

I open the file selected

I copy some range from the selected file and paste it to the destination file (in which there is a module where this code is stored.)

Issue:

Code works when I call the Sub using F5 or Run button inside the VBA editor. Code also works if I create a button and assign this macro to the button on the worksheet. However, when I assign the macro a keyboard shortcut from Macro Manager in Excel, then the code stops after opening the source file. All operations after that are not done.

Again if I debug the code and run it in steps (F8), then again everything works fine.

Sample Code:

Sub sample_code()

Dim file as Variant
file = Application.GetOpenFilename("Excel Files(*.xlsm*),*.xlsm*")
Dim oBook as Workbook
Set oBook = Application.Workbooks.Open(file)
Dim oSheet as Worksheet
Set oSheet = oBook.Worksheets("List")

'*Code to copy some range from oSheet and paste it to a sheet in ThisWorkbook.Worksheet("ConsolidatedList")*

End Sub

What could be the issue here? How should I proceed with this issue?


问:
diffierent behavour of file io by fgetc/fputc in C
I have learnt that, In C, I can read and write to a file when I open a file with "r+" mode.

But the behaviour of my program in different platform is different.

My source code is:

```<code>#include <stdio.h>

int main(void)
{
    FILE* filePtr = fopen("text.txt", "r+");
    char c;
    if(filePtr == NULL)
        printf("Error on opening file.");
    printf("feof = %d\n", feof(filePtr));
    while(!feof(filePtr))
    {
        c = fgetc(filePtr);
        fputc('$', filePtr);
    }
    fclose(filePtr);
    return 0;
}
</code>```

I just want to test the "r+" mode.

The content in "text.txt" is abcdefghijklmnopqrstuvwxyz.

I execute this code in two platform:

Env_0:

Ubuntu 18.04

gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0

After executing, the content of "text.txt" became "a$c$e$g$i$k$m$o$q$s$u$w$y$.$$" (same as I predicted)

Env_1:

Windows 11 x64

gcc 4.9.2 64-bit (in Dev-cpp 5.11)

The program can not even terminal by itself. and the result is in a mess.
It like `abcdefghijklmnopqrstuvwxyz.$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$... and some garbage character in it.

I try to execute it in different platform.

Body:
I have learnt that, In C, I can read and write to a file when I open a file with "r+" mode.

But the behaviour of my program in different platform is different.

My source code is:

#include <stdio.h>

int main(void)
{
    FILE* filePtr = fopen("text.txt", "r+");
    char c;
    if(filePtr == NULL)
        printf("Error on opening file.");
    printf("feof = %d\n", feof(filePtr));
    while(!feof(filePtr))
    {
        c = fgetc(filePtr);
        fputc('$', filePtr);
    }
    fclose(filePtr);
    return 0;
}

I just want to test the "r+" mode.

The content in "text.txt" is abcdefghijklmnopqrstuvwxyz.

I execute this code in two platform:

Env_0:

Ubuntu 18.04

gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0

After executing, the content of "text.txt" became "a$c$e$g$i$k$m$o$q$s$u$w$y$.$$" (same as I predicted)

Env_1:

Windows 11 x64

gcc 4.9.2 64-bit (in Dev-cpp 5.11)

The program can not even terminal by itself. and the result is in a mess.
It like `abcdefghijklmnopqrstuvwxyz.$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$... and some garbage character in it.

I try to execute it in different platform.


问:
How do I open Visual Studio NuGet Package Overview?
I wanted to get back into programming a discord bot. To do so I need to isntall the discord-api form the NuGet Package Manager. But when I try to open it up the button is not clickable.
NuGet Not Clickable

What might be the reason for that?

(It is checked in the version of Visual Studio that I am using)

-Visual Studio Community 2019

-Console Application


问:
Internal Server Error on cpannel in node js
i am kinda new in deployment of nodejs on c Pannel.
I installed node js on c pannel and upload my code to c pannel. Only the default router work like

```<code>`app.get('/', (req,res)=>{
  return res.status(200).json({
            status: true,
            res: "Api is working",
            data: null
        });

});`
</code>```

this route works only

```<code>`app.get('/', (req,res)=>{
  return res.status(200).json({
            status: true,
            res: "Api is working",
            data: null
        });

});`
</code>```

Only this route works, even if i user

```<code>`app.get('/check', (req,res)=>{
  return res.status(200).json({
            status: true,
            res: "Api is working",
            data: null
        });

});`
</code>```

it give me internal server error 500
and all other routes as well giving me Internal server error 500
// Auth Routes app.use('/api/auth', require('./Routes/Auth')); // Role Routes app.use('/api/role', require('./Routes/Roles'))

My Code Structure

Body:
i am kinda new in deployment of nodejs on c Pannel.
I installed node js on c pannel and upload my code to c pannel. Only the default router work like

`app.get('/', (req,res)=>{
  return res.status(200).json({
            status: true,
            res: "Api is working",
            data: null
        });

});`

this route works only

`app.get('/', (req,res)=>{
  return res.status(200).json({
            status: true,
            res: "Api is working",
            data: null
        });

});`

Only this route works, even if i user

`app.get('/check', (req,res)=>{
  return res.status(200).json({
            status: true,
            res: "Api is working",
            data: null
        });

});`

it give me internal server error 500
and all other routes as well giving me Internal server error 500
// Auth Routes app.use('/api/auth', require('./Routes/Auth')); // Role Routes app.use('/api/role', require('./Routes/Roles'))

My Code Structure


问:
Send data to PHP Class and post in in SQL database
I am quite new in PHP and all web development. I am wondering if someone could help me with data flow. I am trying to send form data to a PHP file and then call the function from the class to send data to the sql database. Right now, I don't have any PHP extensions in VS Code so I could debug it and see what is not working. And ofcourse in DOM there is only JS file and PHP which holds HTML code.
This is my code in JavaScript where it takes all user given data and sends it to php. But in form it consists of three static inputs, and then there is a switcher, which displays a user defined view.
`

```<code>    //Function check for correct input with .value() call
    //If it returns 'true' it proceedss with further validation of additional fields that change dynamically.
    //When all fields have passed validation function begins to POST FormData to PHP file for backend work.
    if(validate.test(sku) && validate.test(name) && validatePrice.test(price)){
        if(validateAdditional(this.switcher)){
            let xml = new XMLHttpRequest();
            xml.open("POST", "./backend/product.php", true);
            xml.onload = () => {
                if(xml.readyState == 4 && xml.status == 200){
                    let response = xml.response;
                    alert(response);
                    form.reset()
                    history.back();
                }
            };
            let formData = new FormData(form);
            xml.send(formData);
        }
    }else{
        alert("Please check if there is not any spaces or special characters added");
    }
}
</code>```

Then I created a class that will hold all of the network calls to post/read/edit/delete data from the sql database.

```<code>class DatabaseCalls{
    private $servername = "localhost";
    private $username = "root";
    private $password = "";
    private $dbname = "scandiweb";

    public function insertData($dataQuery){
        $connection = new mysqli($this->servername, $this->username, $this->password, $this->dbname);

        if(!$connection){
            return die("Connection failed" . $connection->connect_error);
        }

        if($connection->query($dataQuery)){
            return "Done";
        }else{
            echo "Error: " . $dataQuery . "<br>" . $connection->connect_error;
        }
        $connection->close();
    }
}
</code>```

And then where there are model call network functions to send it to sql. JS file post data to models file. And then procedurally create the Product object and call the first function where I populate the input data.

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

$sku = $_POST['sku'];
$name = $_POST['name'];
$price = $_POST['price'];
$memory = $_POST['dvd-memory'];

$dvdProduct = new Product($sku, $name, $price, $memory);
echo $dvdProduct->insertQuery();

class Product extends DatabaseCalls{
    private $sku;
    private $name;
    private $price;
    private $memory;

    public function __construct($sku, $name, $price, $memory){
        $this->sku = $sku;
        $this->name = $name;
        $this->price = $price;
        $this->memory = $memory;
    }

    public function insertQuery(){
        $sql = "INSERT INTO dvd (SKU, Name, Price, Memory)
        VALUES ('$sku', '$name', '$price', '$memory')";

        $response = $this->insertData($sql);
        return $response;
    }
}
</code>```

And for context I will all also HTML code.

```<code>    <form class="input" name="input">
        <div>
        <label for="sku">SKU:</label>
        <input id="sku" type="text" name="sku" placeholder="#SKU">
        </div>

        <div>
        <label for="name">Name:</label>
        <input id="name" type="text" name="name" placeholder="#name">
        </div>

        <div>
        <label for="price">Price ($):</label>
        <input id="price" type="text" name="price" placeholder="#price">
        </div>

        <div class="switcher">
            <h3>Type Switcher</h3>

            <select name="select" id="select">
                <option selected disabled>Choose a type</option>
                <option value="dvd">DVD</option>
                <option value="furniture">Furniture</option>
                <option value="book">Book</option>
            </select>
        </div>

        <div class="switchContent">

            <div class="dvd-mem", id="dvd">
                <p>DVD-disc</p>
                <label for="dvd-memory">Size(MB):</label>
                <input id="dvd-memory" type="text" name="dvd-memory" placeholder="Please enter MB amount here">
                <p>Please enter amount of disc memory in MB.</p>
            </div>

            <div class="furniture" id="furniture">
                <p>Furniture</p>

                <div>
                <label for="height">Height(CM):</label>
                <input id="height" type="text" name="height" placeholder="Enter height in here">
                </div>

                <div>
                <label for="width">Width(CM):</label>
                <input id="width" type="text" name="width" placeholder="Enter width in here">
                </div>

                <div>
                <label for="lenght">Height(CM):</label>
                <input id="lenght" type="text" name="lenght" placeholder="Enter lenght in here">
                </div>

                <p>Please enter all dimensions of furniture</p>
            </div>

            <div class="book" id="book">
                <p>Book</p>
                <label for="weight">Weight(KG):</label>
                <input id="weight" type="text" name="weight" placeholder="Please enter weight in KG">
                <p>Please enter weight of book</p>
            </div>

        </div>
    </form>
</code>```

Body:
I am quite new in PHP and all web development. I am wondering if someone could help me with data flow. I am trying to send form data to a PHP file and then call the function from the class to send data to the sql database. Right now, I don't have any PHP extensions in VS Code so I could debug it and see what is not working. And ofcourse in DOM there is only JS file and PHP which holds HTML code.
This is my code in JavaScript where it takes all user given data and sends it to php. But in form it consists of three static inputs, and then there is a switcher, which displays a user defined view.
`

    //Function check for correct input with .value() call
    //If it returns 'true' it proceedss with further validation of additional fields that change dynamically.
    //When all fields have passed validation function begins to POST FormData to PHP file for backend work.
    if(validate.test(sku) && validate.test(name) && validatePrice.test(price)){
        if(validateAdditional(this.switcher)){
            let xml = new XMLHttpRequest();
            xml.open("POST", "./backend/product.php", true);
            xml.onload = () => {
                if(xml.readyState == 4 && xml.status == 200){
                    let response = xml.response;
                    alert(response);
                    form.reset()
                    history.back();
                }
            };
            let formData = new FormData(form);
            xml.send(formData);
        }
    }else{
        alert("Please check if there is not any spaces or special characters added");
    }
}

Then I created a class that will hold all of the network calls to post/read/edit/delete data from the sql database.

class DatabaseCalls{
    private $servername = "localhost";
    private $username = "root";
    private $password = "";
    private $dbname = "scandiweb";

    public function insertData($dataQuery){
        $connection = new mysqli($this->servername, $this->username, $this->password, $this->dbname);

        if(!$connection){
            return die("Connection failed" . $connection->connect_error);
        }

        if($connection->query($dataQuery)){
            return "Done";
        }else{
            echo "Error: " . $dataQuery . "
" . $connection->connect_error;
        }
        $connection->close();
    }
}

And then where there are model call network functions to send it to sql. JS file post data to models file. And then procedurally create the Product object and call the first function where I populate the input data.

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

$sku = $_POST['sku'];
$name = $_POST['name'];
$price = $_POST['price'];
$memory = $_POST['dvd-memory'];

$dvdProduct = new Product($sku, $name, $price, $memory);
echo $dvdProduct->insertQuery();

class Product extends DatabaseCalls{
    private $sku;
    private $name;
    private $price;
    private $memory;

    public function __construct($sku, $name, $price, $memory){
        $this->sku = $sku;
        $this->name = $name;
        $this->price = $price;
        $this->memory = $memory;
    }

    public function insertQuery(){
        $sql = "INSERT INTO dvd (SKU, Name, Price, Memory)
        VALUES ('$sku', '$name', '$price', '$memory')";

        $response = $this->insertData($sql);
        return $response;
    }
}

And for context I will all also HTML code.

    <form class="input" name="input">

        SKU:
        <input id="sku" type="text" name="sku" placeholder="#SKU">

        Name:
        <input id="name" type="text" name="name" placeholder="#name">

        Price ($):
        <input id="price" type="text" name="price" placeholder="#price">

Type Switcher

            <select name="select" id="select">
                <option selected disabled>Choose a type</option>
                <option value="dvd">DVD</option>
                <option value="furniture">Furniture</option>
                <option value="book">Book</option>
            </select>

DVD-disc

                Size(MB):
                <input id="dvd-memory" type="text" name="dvd-memory" placeholder="Please enter MB amount here">

Please enter amount of disc memory in MB.

Furniture

                Height(CM):
                <input id="height" type="text" name="height" placeholder="Enter height in here">

                Width(CM):
                <input id="width" type="text" name="width" placeholder="Enter width in here">

                Height(CM):
                <input id="lenght" type="text" name="lenght" placeholder="Enter lenght in here">

Please enter all dimensions of furniture

Book

                Weight(KG):
                <input id="weight" type="text" name="weight" placeholder="Please enter weight in KG">

Please enter weight of book

    </form>


问:
In Jira there is a Time Report what is the alternative in Azure and how to use it?
In Jira there is a Time Report where you could see how many hours spend on the task an employee, and for month report you could see all tasks together and total time spent day by day on the task and total sepent time to be able to report to the customer, about how much time spent each employee.

I could not find normal documentation for such feature, I am expected to get help, if there is such feature, how to use it and setup.


问:
Transposition using multiple merges (feedback wanted)
i have a solution in danfojs (codepen below) but would like some feedback on how to improve it, since im new to danfo, maybe the same result can be obtained more elegantly.

Essentially i want to do a transposition by merging around twenty Dataframes, but realized that the merge feature only allows to merge two single Dataframes, so i implemented a loop, but end up removing extra columns (played with joins but was the best i could get).

The input files (file1...file20) have the following structure:

```<code>╔═══╤══════════╤═══════════════════╤═══════════╗
║   │ tag_name │ ts_utc            │ tag_value ║
╟───┼──────────┼───────────────────┼───────────╢
║ 0 │ C1       │ Thu Sep 15 2022…  │ 1         ║
╟───┼──────────┼───────────────────┼───────────╢
║ 1 │ C1       │ Sat Sep 17 2022…  │ 10        ║
╟───┼──────────┼───────────────────┼───────────╢
║ 2 │ C1       │ Sat Sep 17 2022…  │ 11        ║
╚═══╧══════════╧═══════════════════╧═══════════╝
</code>```

...

```<code>╔═══╤══════════╤═══════════════════╤═══════════╗
║   │ tag_name │ ts_utc            │ tag_value ║
╟───┼──────────┼───────────────────┼───────────╢
║ 0 │ C3       │ Thu Sep 15 2022…  │ 3         ║
╟───┼──────────┼───────────────────┼───────────╢
║ 1 │ C3       │ Sat Sep 17 2022…  │ 30        ║
╟───┼──────────┼───────────────────┼───────────╢
║ 2 │ C3       │ Sat Sep 17 2022…  │ 31        ║
╚═══╧══════════╧═══════════════════╧═══════════╝
</code>```

And the desired result is:

tag_value header becomes the tag_name (C1,C2...)

Components are merged by date (ts_utc)

tag_name is replaced by constant "sourcetag"

```<code>╔═══╤═══════════════════╤═══════════╤═════╤════╤════╗
║   │ ts_utc            │ tag_name  │ C1  │ C2 │ C3 ║
╟───┼───────────────────┼───────────┼─────┼────┼────╢
║ 0 │ Thu Sep 15 2022…  │ sourceTag │ 1   │ 2  │ 3  ║
╟───┼───────────────────┼───────────┼─────┼────┼────╢
║ 1 │ Sat Sep 17 2022…  │ sourceTag │ 10  │ 20 │ 30 ║
╟───┼───────────────────┼───────────┼─────┼────┼────╢
║ 2 │ Sat Sep 17 2022…  │ sourceTag │ 11  │ 21 │ 31 ║
╚═══╧═══════════════════╧═══════════╧═════╧════╧════╝
</code>```

Sample code:
https://codepen.io/dotmindlabs/pen/xxJwMqZ?editors=1111

Thanks, any feedback is very appreciatted.

Body:
i have a solution in danfojs (codepen below) but would like some feedback on how to improve it, since im new to danfo, maybe the same result can be obtained more elegantly.

Essentially i want to do a transposition by merging around twenty Dataframes, but realized that the merge feature only allows to merge two single Dataframes, so i implemented a loop, but end up removing extra columns (played with joins but was the best i could get).

The input files (file1...file20) have the following structure:

╔═══╤══════════╤═══════════════════╤═══════════╗
║   │ tag_name │ ts_utc            │ tag_value ║
╟───┼──────────┼───────────────────┼───────────╢
║ 0 │ C1       │ Thu Sep 15 2022…  │ 1         ║
╟───┼──────────┼───────────────────┼───────────╢
║ 1 │ C1       │ Sat Sep 17 2022…  │ 10        ║
╟───┼──────────┼───────────────────┼───────────╢
║ 2 │ C1       │ Sat Sep 17 2022…  │ 11        ║
╚═══╧══════════╧═══════════════════╧═══════════╝

...

╔═══╤══════════╤═══════════════════╤═══════════╗
║   │ tag_name │ ts_utc            │ tag_value ║
╟───┼──────────┼───────────────────┼───────────╢
║ 0 │ C3       │ Thu Sep 15 2022…  │ 3         ║
╟───┼──────────┼───────────────────┼───────────╢
║ 1 │ C3       │ Sat Sep 17 2022…  │ 30        ║
╟───┼──────────┼───────────────────┼───────────╢
║ 2 │ C3       │ Sat Sep 17 2022…  │ 31        ║
╚═══╧══════════╧═══════════════════╧═══════════╝

And the desired result is:

tag_value header becomes the tag_name (C1,C2...)

Components are merged by date (ts_utc)

tag_name is replaced by constant "sourcetag"

╔═══╤═══════════════════╤═══════════╤═════╤════╤════╗
║   │ ts_utc            │ tag_name  │ C1  │ C2 │ C3 ║
╟───┼───────────────────┼───────────┼─────┼────┼────╢
║ 0 │ Thu Sep 15 2022…  │ sourceTag │ 1   │ 2  │ 3  ║
╟───┼───────────────────┼───────────┼─────┼────┼────╢
║ 1 │ Sat Sep 17 2022…  │ sourceTag │ 10  │ 20 │ 30 ║
╟───┼───────────────────┼───────────┼─────┼────┼────╢
║ 2 │ Sat Sep 17 2022…  │ sourceTag │ 11  │ 21 │ 31 ║
╚═══╧═══════════════════╧═══════════╧═════╧════╧════╝

Sample code:
https://codepen.io/dotmindlabs/pen/xxJwMqZ?editors=1111

Thanks, any feedback is very appreciatted.


问:
Why the request body is empty in Django when I send a request to it from Node JS?
I am writing an application using React Native for frontend, Node JS (express, axios) for backend and Python Django (v 4.1.4) for hosting a neural network. In this app I need to send a POST request containing some parameters in body, as well as a music file. This request goes from React to Node JS to Python server. The request is successfully processed on a Node JS server, however, when I send it to Python Django server from Node, I get an empty body in the python endpoint. Now, when Python server is hosted on amazon (I use Elastic Beanstalk), the request comes with populated body, it stops working once I try to host python server locally and send a request from node js to python django server.
You might ask: why bother, just use amazon hosting then? I can't because my neural network is too heavy for free tier hosting and it requires power to respond quickly.
The strangest thing is that requests comes to the Python server (it does not say something like CORS error) and the response is sent from Python server, but the request body is empty.

I have tried to use another IP for Django server (my local one, which is 192.168.1.x) and connect to it from Node: still no body in request.

I have tried to use static global IP for Django server (I hosted on 0.0.0.0 and it was accessible via my globally available static IP). Then I connected to Python server from Node using another network -- so the servers where not in the same LAN. Still the same thing: requests goes, but without a body.

I have tried to use fetch instead of axios -- the same problem.

I am using ALLOWED_HOSTS: "*" for Django hosts setting.

Here's the code on Node JS side:

```<code>const form = new FormData();
form.append('recording', fs.createReadStream(req.file.path), req.file.originalname);
form.append('tempo', req.body.tempo);

console.log('requesting', process.env.PYTHON_API);

try {
    const response = await axios.request({
        method: 'POST',
        url: 'http://83.24.143.208:8000/api/get-notes',
        headers: {
            "Content-Type": "multipart/form-data"
        },
        data: form,
    });
    console.log('response:', response)
    return res
        .status(200)
        .send(JSON.stringify(response.data));
} catch (error) {
    console.log(error);
    res
        .status(500)
        .send(JSON.stringify(error));
}
</code>```

And this is for Python:

```<code>@csrf_exempt
def generate_tabs(request):
    try:
        """ PROCESS INPUT DATA GOT FROM THE NODE SERVER """
        file: InMemoryUploadedFile = check_and_fetch(
            key='recording',
            _dict=request.FILES,
            error_msg=f'There is no file with filename = recording. Got the following set of files: {list(request.FILES.keys())}',
            status=404
        )

        tempo = int(check_and_fetch(
            key='tempo',
            _dict=request.POST,
            error_msg=f'Required parameter tempo was not found. Got the following set of keys: {list(request.POST.keys())}',
            status=404
        ))

        file_format = file.name.split('.')[-1]
        if file_format not in ALLOWED_FORMATS:
            raise ProcessingException(
                error_msg=f'File format is inappropriate — WAV and MP3 are supported only. Provided file format is: {file_format}',
                status=415)

        """ STORE PROVIDED FILE, TRANSCRIBE AND RESPOND """
        in_path, out_path, tmp_path = process_file(file, file_format)
        tab_onsets, song_duration = predict(in_path, out_path, tmp_path, predict_config)
        tabs, tacts = get_tabs_for_onsets(tab_onsets, song_duration, tempo, predict_config)
        response = finalize_response(tabs, tacts, song_duration, in_path, out_path)

    except ProcessingException as e:
        response = JsonResponse({"error": e.error_msg}, status=e.status)
    except Exception as e:
        response = JsonResponse({"error": f'There was an error while transcribing the file with the following error message: {e}'},
                            status=500)
    return response

def check_and_fetch(key, _dict, error_msg, status):
    if key not in _dict.keys():
        raise ProcessingException(error_msg=error_msg, status=status)
    return _dict[key]
</code>```

So don't really know what's left to do at all. So, if You have any suggestions/further questions, I will be very grateful for any help, thank You!

Body:
I am writing an application using React Native for frontend, Node JS (express, axios) for backend and Python Django (v 4.1.4) for hosting a neural network. In this app I need to send a POST request containing some parameters in body, as well as a music file. This request goes from React to Node JS to Python server. The request is successfully processed on a Node JS server, however, when I send it to Python Django server from Node, I get an empty body in the python endpoint. Now, when Python server is hosted on amazon (I use Elastic Beanstalk), the request comes with populated body, it stops working once I try to host python server locally and send a request from node js to python django server.
You might ask: why bother, just use amazon hosting then? I can't because my neural network is too heavy for free tier hosting and it requires power to respond quickly.
The strangest thing is that requests comes to the Python server (it does not say something like CORS error) and the response is sent from Python server, but the request body is empty.

I have tried to use another IP for Django server (my local one, which is 192.168.1.x) and connect to it from Node: still no body in request.

I have tried to use static global IP for Django server (I hosted on 0.0.0.0 and it was accessible via my globally available static IP). Then I connected to Python server from Node using another network -- so the servers where not in the same LAN. Still the same thing: requests goes, but without a body.

I have tried to use fetch instead of axios -- the same problem.

I am using ALLOWED_HOSTS: "*" for Django hosts setting.

Here's the code on Node JS side:

const form = new FormData();
form.append('recording', fs.createReadStream(req.file.path), req.file.originalname);
form.append('tempo', req.body.tempo);

console.log('requesting', process.env.PYTHON_API);

try {
    const response = await axios.request({
        method: 'POST',
        url: 'http://83.24.143.208:8000/api/get-notes',
        headers: {
            "Content-Type": "multipart/form-data"
        },
        data: form,
    });
    console.log('response:', response)
    return res
        .status(200)
        .send(JSON.stringify(response.data));
} catch (error) {
    console.log(error);
    res
        .status(500)
        .send(JSON.stringify(error));
}

And this is for Python:

@csrf_exempt
def generate_tabs(request):
    try:
        """ PROCESS INPUT DATA GOT FROM THE NODE SERVER """
        file: InMemoryUploadedFile = check_and_fetch(
            key='recording',
            _dict=request.FILES,
            error_msg=f'There is no file with filename = recording. Got the following set of files: {list(request.FILES.keys())}',
            status=404
        )

        tempo = int(check_and_fetch(
            key='tempo',
            _dict=request.POST,
            error_msg=f'Required parameter tempo was not found. Got the following set of keys: {list(request.POST.keys())}',
            status=404
        ))

        file_format = file.name.split('.')[-1]
        if file_format not in ALLOWED_FORMATS:
            raise ProcessingException(
                error_msg=f'File format is inappropriate — WAV and MP3 are supported only. Provided file format is: {file_format}',
                status=415)

        """ STORE PROVIDED FILE, TRANSCRIBE AND RESPOND """
        in_path, out_path, tmp_path = process_file(file, file_format)
        tab_onsets, song_duration = predict(in_path, out_path, tmp_path, predict_config)
        tabs, tacts = get_tabs_for_onsets(tab_onsets, song_duration, tempo, predict_config)
        response = finalize_response(tabs, tacts, song_duration, in_path, out_path)

    except ProcessingException as e:
        response = JsonResponse({"error": e.error_msg}, status=e.status)
    except Exception as e:
        response = JsonResponse({"error": f'There was an error while transcribing the file with the following error message: {e}'},
                            status=500)
    return response

def check_and_fetch(key, _dict, error_msg, status):
    if key not in _dict.keys():
        raise ProcessingException(error_msg=error_msg, status=status)
    return _dict[key]

So don't really know what's left to do at all. So, if You have any suggestions/further questions, I will be very grateful for any help, thank You!


问:
EfficientNet Failed to convert elements of SparseTensor
i'm trying to train my model using EfficientNetb0 but the error says failed to convert SparseTensor, honestly idk why im just following some tutorialenter image description here(https://i.stack.imgur.com/5a5az.png)enter image description hereenter image description here

how can i see what the required shape and what i have now, as far as i know the input already match but still could work


问:
SSLCertVerificationError in python pandas dataframe , M1 macos
I try to read CSV from URL of the pandas dataframe, but it shows an error "SSLCertVerificationError ", how to deal with it? My laptop is M1 macOS, I'm not sure why.
Here is my code:

```<code>import pandas as pd
path = "https://archive.ics.uci.edu/ml/machine-learning-databases/00523/Exasens.csv"
df = pd.read_csv(path, skiprows=3)
</code>```

Here is error detail:

```<code>SSLCertVerificationError                  Traceback (most recent call last)
File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:1348, in AbstractHTTPHandler.do_open(self, http_class, req, **http_conn_args)
   1347 try:
-> 1348     h.request(req.get_method(), req.selector, req.data, headers,
   1349               encode_chunked=req.has_header('Transfer-encoding'))
   1350 except OSError as err: # timeout error

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:1282, in HTTPConnection.request(self, method, url, body, headers, encode_chunked)
   1281 """Send a complete request to the server."""
-> 1282 self._send_request(method, url, body, headers, encode_chunked)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:1328, in HTTPConnection._send_request(self, method, url, body, headers, encode_chunked)
   1327     body = _encode(body, 'body')
-> 1328 self.endheaders(body, encode_chunked=encode_chunked)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:1277, in HTTPConnection.endheaders(self, message_body, encode_chunked)
   1276     raise CannotSendHeader()
-> 1277 self._send_output(message_body, encode_chunked=encode_chunked)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:1037, in HTTPConnection._send_output(self, message_body, encode_chunked)
   1036 del self._buffer[:]
-> 1037 self.send(msg)
   1039 if message_body is not None:
   1040
   1041     # create a consistent interface to message_body

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:975, in HTTPConnection.send(self, data)
    974 if self.auto_open:
--> 975     self.connect()
    976 else:

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:1454, in HTTPSConnection.connect(self)
   1452     server_hostname = self.host
-> 1454 self.sock = self._context.wrap_socket(self.sock,
   1455                                       server_hostname=server_hostname)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/ssl.py:513, in SSLContext.wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session)
    507 def wrap_socket(self, sock, server_side=False,
    508                 do_handshake_on_connect=True,
    509                 suppress_ragged_eofs=True,
    510                 server_hostname=None, session=None):
    511     # SSLSocket class handles server_hostname encoding before it calls
    512     # ctx._wrap_socket()
--> 513     return self.sslsocket_class._create(
    514         sock=sock,
    515         server_side=server_side,
    516         do_handshake_on_connect=do_handshake_on_connect,
    517         suppress_ragged_eofs=suppress_ragged_eofs,
    518         server_hostname=server_hostname,
    519         context=self,
    520         session=session
    521     )

</code>```

don't know how to solve it.

Body:
I try to read CSV from URL of the pandas dataframe, but it shows an error "SSLCertVerificationError ", how to deal with it? My laptop is M1 macOS, I'm not sure why.
Here is my code:

import pandas as pd
path = "https://archive.ics.uci.edu/ml/machine-learning-databases/00523/Exasens.csv"
df = pd.read_csv(path, skiprows=3)

Here is error detail:

SSLCertVerificationError                  Traceback (most recent call last)
File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py:1348, in AbstractHTTPHandler.do_open(self, http_class, req, **http_conn_args)
   1347 try:
-> 1348     h.request(req.get_method(), req.selector, req.data, headers,
   1349               encode_chunked=req.has_header('Transfer-encoding'))
   1350 except OSError as err: # timeout error

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:1282, in HTTPConnection.request(self, method, url, body, headers, encode_chunked)
   1281 """Send a complete request to the server."""
-> 1282 self._send_request(method, url, body, headers, encode_chunked)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:1328, in HTTPConnection._send_request(self, method, url, body, headers, encode_chunked)
   1327     body = _encode(body, 'body')
-> 1328 self.endheaders(body, encode_chunked=encode_chunked)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:1277, in HTTPConnection.endheaders(self, message_body, encode_chunked)
   1276     raise CannotSendHeader()
-> 1277 self._send_output(message_body, encode_chunked=encode_chunked)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:1037, in HTTPConnection._send_output(self, message_body, encode_chunked)
   1036 del self._buffer[:]
-> 1037 self.send(msg)
   1039 if message_body is not None:
   1040
   1041     # create a consistent interface to message_body

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:975, in HTTPConnection.send(self, data)
    974 if self.auto_open:
--> 975     self.connect()
    976 else:

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py:1454, in HTTPSConnection.connect(self)
   1452     server_hostname = self.host
-> 1454 self.sock = self._context.wrap_socket(self.sock,
   1455                                       server_hostname=server_hostname)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/ssl.py:513, in SSLContext.wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session)
    507 def wrap_socket(self, sock, server_side=False,
    508                 do_handshake_on_connect=True,
    509                 suppress_ragged_eofs=True,
    510                 server_hostname=None, session=None):
    511     # SSLSocket class handles server_hostname encoding before it calls
    512     # ctx._wrap_socket()
--> 513     return self.sslsocket_class._create(
    514         sock=sock,
    515         server_side=server_side,
    516         do_handshake_on_connect=do_handshake_on_connect,
    517         suppress_ragged_eofs=suppress_ragged_eofs,
    518         server_hostname=server_hostname,
    519         context=self,
    520         session=session
    521     )

don't know how to solve it.


问:
How can I save in different pdf by CPF, with Python?
How can I save in different pdf by CPF?
I need to split a pdf file into others, through the CPF and save in different files. using python
How could save in separate files?</p>
```<code>                print("GRAVAR ARQUIVO POR CPF/PESSOA",cpf_ant)
                print("PAGINA INICIAL",cpf_pag_ini)
                print("PAGINA FINAL",cpf_pag_fim)

                arquivo_novo = pyf.PdfFileWriter()
                arquivo_novo = "teste"

                paginas = range(cpf_pag_ini, cpf_pag_fim)
                for pagina in paginas:
                    arquivo_novo.addPage(pagina)

                with Path(f'paginas/Arquivo{p}.txt').open(mode='wb') as arquivo_final:
                    arquivo_novo.write(arquivo_final)
                    p += 1

                # Atualiza o controle por CPF e página inicial do mesmo
                cpf_pag_ini = i + 1

            cpf_ant = cpf

# Para separar as páginas
print()

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

Body:
How can I save in different pdf by CPF?
I need to split a pdf file into others, through the CPF and save in different files. using python
How could save in separate files?

                print("GRAVAR ARQUIVO POR CPF/PESSOA",cpf_ant)
                print("PAGINA INICIAL",cpf_pag_ini)
                print("PAGINA FINAL",cpf_pag_fim)

                arquivo_novo = pyf.PdfFileWriter()
                arquivo_novo = "teste"

                paginas = range(cpf_pag_ini, cpf_pag_fim)
                for pagina in paginas:
                    arquivo_novo.addPage(pagina)

                with Path(f'paginas/Arquivo{p}.txt').open(mode='wb') as arquivo_final:
                    arquivo_novo.write(arquivo_final)
                    p += 1

                # Atualiza o controle por CPF e página inicial do mesmo
                cpf_pag_ini = i + 1

            cpf_ant = cpf

# Para separar as páginas
print()


问:
Cannot find module '@ledgerhq/devices/hid-framing'
I'm getting the following error when I make yarn start (The npm packages were previously installed without any problem). I'm using es5. The full error consists of these three errors:

Uncaught Error: Cannot find module '@ledgerhq/devices/hid-framing'

Uncaught ReferenceError: process is not defined

index.js:1 ./node_modules/@ledgerhq/hw-transport-webhid/lib-es/TransportWebHID.js

As far as I know, none of my packages depend on the @ledgerhq/devices package.

I have found some possible solutions, but none of them have worked. Among them I have tried:

I have installed it using
npm install @ledgerhq/devices

I tried adding "alias": {"@ledgerhq/devices": "@ledgerhq/devices/lib-es" } in package.json

I also tried running it using npm start -- --reset-cache


问:
How to modify Engine's output on iOS AudioKit
I want to choose different sound effects to listen to when playing music
this is my code:

```<code>class EffectConductor: ObservableObject, ProcessesPlayerInput {
    var engine = AudioEngine()
    var player = AudioPlayer()
//    var dryWetMixer : DryWetMixer
    var isPlaying = false

    init(path:String) {
        let mediaUrl = URL.init(fileURLWithPath: path)
        let file = try! AVAudioFile(forReading: mediaUrl)
        try! player.load(file: file, buffered: true)
        engine.output = player
    }

    @Published var effectType: Int = 0 {
        didSet {
            var node : Node? = nil
            switch effectType {
            case 1:
                node = AutoPanner(player)
            case 2:
                node = AutoWah(player)
            case 3:
                node = Compressor(player)
            case 4:
                node = DynamicRangeCompressor(player)
            case 5:
                node = Expander(player)
            case 6:
                node = Phaser(player)
            case 7:
                node = StringResonator(player)
            default:
                node = nil
            }
            if node==nil
            {
                print("effect nil")
                engine.output = player
            }else{
                engine.output = DryWetMixer(player, node!)
            }
        }
    }
}
</code>```

when i call this code：

engine.start() player.start()
Can play music. but when i click a button and call this code:
effectType = 2(or ever value)
to change engine.output value
it's stop playing

i try this when i click a button

```<code>let progress = player.getCurrentTime()
if(isPlaying){
   player.stop()
}
self.effectType = 3
if(isPlaying){
   player.seek(time: progress)
   player.play()
}
</code>```

But there will be a pause in the playback process

how to solve this problem?

thanks everyone!

Body:
I want to choose different sound effects to listen to when playing music
this is my code:

class EffectConductor: ObservableObject, ProcessesPlayerInput {
    var engine = AudioEngine()
    var player = AudioPlayer()
//    var dryWetMixer : DryWetMixer
    var isPlaying = false

    init(path:String) {
        let mediaUrl = URL.init(fileURLWithPath: path)
        let file = try! AVAudioFile(forReading: mediaUrl)
        try! player.load(file: file, buffered: true)
        engine.output = player
    }

    @Published var effectType: Int = 0 {
        didSet {
            var node : Node? = nil
            switch effectType {
            case 1:
                node = AutoPanner(player)
            case 2:
                node = AutoWah(player)
            case 3:
                node = Compressor(player)
            case 4:
                node = DynamicRangeCompressor(player)
            case 5:
                node = Expander(player)
            case 6:
                node = Phaser(player)
            case 7:
                node = StringResonator(player)
            default:
                node = nil
            }
            if node==nil
            {
                print("effect nil")
                engine.output = player
            }else{
                engine.output = DryWetMixer(player, node!)
            }
        }
    }
}

when i call this code：

engine.start() player.start()
Can play music. but when i click a button and call this code:
effectType = 2(or ever value)
to change engine.output value
it's stop playing

i try this when i click a button

let progress = player.getCurrentTime()
if(isPlaying){
   player.stop()
}
self.effectType = 3
if(isPlaying){
   player.seek(time: progress)
   player.play()
}

But there will be a pause in the playback process

how to solve this problem?

thanks everyone!


问:
AES/GCM Encryption on C# and decryption on Java fails with error "Tag Mismatch"
I have been trying to send data effectively between two applications. One is implemented in C# (Sender) the other in Java (Receiver). The sender has to encrypt data using the transformation "AES/GCM/NOPadding" with a 32-byte key while the receiver has to decrypt using the same parameters. Here is the sender encryption function in C# (using bouncy castle)

```<code>public static string Encrypt(string plainText, string msgId)
        {
            const byte GcmTagSize = 16;

            byte[] hashKey;
            byte[] secretKey = Encoding.UTF8.GetBytes(msgId);

            Console.WriteLine(secretKey.Length);

            using (var hasher = SHA512.Create())
            {
                byte[] digestSeed = hasher.ComputeHash(secretKey);
                hashKey = new byte[16];
                Array.Copy(digestSeed, hashKey, hashKey.Length);
            }

            var keyParameter = new KeyParameter(hashKey);
            var keyParameters = new AeadParameters(keyParameter, GcmTagSize * 8, secretKey);

            var cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding");
            cipher.Init(true, keyParameters);

            var plainTextData = Encoding.ASCII.GetBytes(plainText);
            var cipherText = cipher.DoFinal(plainTextData); //bouncy castle

            return Convert.ToBase64String(cipherText);
        }
</code>```

Here is the receiver decryption function in java

```<code>private static byte[] decrypt(byte[] message, SecretKey key) throws NoSuchPaddingException, NoSuchAlgorithmException,
            IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeyException {

        Cipher cipher = Cipher.getInstance("AES/GCM/NOPadding"); //NoPadding

        byte[] nonce = Arrays.copyOfRange(message, message.length - cipher.getBlockSize(), message.length);
        byte[] encryptedKycData = Arrays.copyOf(message, message.length - cipher.getBlockSize());

        System.out.println(doEncode(nonce));

        System.out.println(doEncode(nonce));
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, nonce);
        cipher.init(Cipher.DECRYPT_MODE, key, gcmParameterSpec);

        byte[] decryptedValue=cipher.doFinal(encryptedKycData);

        return decryptedValue;

    }
</code>```

When I try to decrypt with the java decryption function I get the error

```<code>javax.crypto.AEADBadTagException: Tag mismatch
</code>```

Struggling with this issue and any help would be appreciated.

Body:
I have been trying to send data effectively between two applications. One is implemented in C# (Sender) the other in Java (Receiver). The sender has to encrypt data using the transformation "AES/GCM/NOPadding" with a 32-byte key while the receiver has to decrypt using the same parameters. Here is the sender encryption function in C# (using bouncy castle)

public static string Encrypt(string plainText, string msgId)
        {
            const byte GcmTagSize = 16;

            byte[] hashKey;
            byte[] secretKey = Encoding.UTF8.GetBytes(msgId);

            Console.WriteLine(secretKey.Length);

            using (var hasher = SHA512.Create())
            {
                byte[] digestSeed = hasher.ComputeHash(secretKey);
                hashKey = new byte[16];
                Array.Copy(digestSeed, hashKey, hashKey.Length);
            }

            var keyParameter = new KeyParameter(hashKey);
            var keyParameters = new AeadParameters(keyParameter, GcmTagSize * 8, secretKey);

            var cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding");
            cipher.Init(true, keyParameters);

            var plainTextData = Encoding.ASCII.GetBytes(plainText);
            var cipherText = cipher.DoFinal(plainTextData); //bouncy castle

            return Convert.ToBase64String(cipherText);
        }

Here is the receiver decryption function in java

private static byte[] decrypt(byte[] message, SecretKey key) throws NoSuchPaddingException, NoSuchAlgorithmException,
            IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeyException {

        Cipher cipher = Cipher.getInstance("AES/GCM/NOPadding"); //NoPadding

        byte[] nonce = Arrays.copyOfRange(message, message.length - cipher.getBlockSize(), message.length);
        byte[] encryptedKycData = Arrays.copyOf(message, message.length - cipher.getBlockSize());

        System.out.println(doEncode(nonce));

        System.out.println(doEncode(nonce));
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, nonce);
        cipher.init(Cipher.DECRYPT_MODE, key, gcmParameterSpec);

        byte[] decryptedValue=cipher.doFinal(encryptedKycData);

        return decryptedValue;

    }

When I try to decrypt with the java decryption function I get the error

javax.crypto.AEADBadTagException: Tag mismatch

Struggling with this issue and any help would be appreciated.


问:
How i want to write function when i click on button calculate order, it will show the ouput

The cleaning total I got is from total laundry.

I have written the function for calculate tax amount and total order amount. but I'm not sure which line got error. It's more confusing when I only can use one button (calculate order) for 2 function.

function calculateTaxAmount() {
  let cleaningTotal = document.getElementById("cleaningTotal");
  let tax = 5.75;
  let taxAmount = cleaningTotal * tax / 100;
  document.getElementById("taxAmount").value = taxAmount;
}

function processOrder() {
  var f1 = document.getElementById('sum').value;
  var f2 = document.getElementById('sumpants').value;
  var f3 = document.getElementById('sumItem1').value;
  var f4 = document.getElementById('sumItem2').value;
  var f5 = document.getElementById('sumItem3').value;
  var f6 = document.getElementById('sumItem4').value;

  if (f1 == "") f1 = 0;
  if (f2 == "") f2 = 0;
  if (f3 == "") f3 = 0;
  if (f4 == "") f4 = 0;
  if (f5 == "") f5 = 0;
  if (f6 == "") f6 = 0;

  var result = parseInt(f1) + parseInt(f2) + parseInt(f3) + parseInt(f4) + parseInt(f5) + parseInt(f6);
  if (!isNaN(result)) {
    document.getElementById('cleaningTotal').value = result;
  }
  var orderTotal = cleaningTotal + tax; {
    document.getElementById('orderTotal').value = result
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" value="Calculate Order" onclick="processOrder()"><br><br>
<label>Cleaning Total</label>
</td>
<td>
  <div>
    <input type="text" name="cleaningTotal" id="cleaningTotal" value="">
  </div>
</td>
<td> </td>
</tr>
<tr class="tbl-foot">
  <td colspan="3">
    <label>Tax Rate</label>
  </td>
  <td>
    <input type="text" name="taxRate" id="taxRate" value="5.75">%
  </td>
  <td> </td>
</tr>
<tr class="tbl-foot">
  <td colspan="3">
    <label>Tax Amount : </label>
  </td>
  <td>
    <div>
      <input type="text" name="taxAmount" id="taxAmount" onclick="processOrder()" value="">
    </div>
  </td>
  <td> </td>
</tr>
<tr class="tbl-foot">
  <td colspan="3">
    <label>Order Total : </label>
  </td>
  <td>
    <div>
      <input type="text" name="orderTotal" id="orderTotal" value="">
    </div>
  </td>
  <td> </td>
</tr></code>```

Body:
The cleaning total I got is from total laundry.

I have written the function for calculate tax amount and total order amount. but I'm not sure which line got error. It's more confusing when I only can use one button (calculate order) for 2 function.

function calculateTaxAmount() {
  let cleaningTotal = document.getElementById("cleaningTotal");
  let tax = 5.75;
  let taxAmount = cleaningTotal * tax / 100;
  document.getElementById("taxAmount").value = taxAmount;
}

function processOrder() {
  var f1 = document.getElementById('sum').value;
  var f2 = document.getElementById('sumpants').value;
  var f3 = document.getElementById('sumItem1').value;
  var f4 = document.getElementById('sumItem2').value;
  var f5 = document.getElementById('sumItem3').value;
  var f6 = document.getElementById('sumItem4').value;

  if (f1 == "") f1 = 0;
  if (f2 == "") f2 = 0;
  if (f3 == "") f3 = 0;
  if (f4 == "") f4 = 0;
  if (f5 == "") f5 = 0;
  if (f6 == "") f6 = 0;

  var result = parseInt(f1) + parseInt(f2) + parseInt(f3) + parseInt(f4) + parseInt(f5) + parseInt(f6);
  if (!isNaN(result)) {
    document.getElementById('cleaningTotal').value = result;
  }
  var orderTotal = cleaningTotal + tax; {
    document.getElementById('orderTotal').value = result
  }
}

<input type="button" value="Calculate Order" onclick="processOrder()">

Cleaning Total

    <input type="text" name="cleaningTotal" id="cleaningTotal" value="">

    Tax Rate

    <input type="text" name="taxRate" id="taxRate" value="5.75">%

    Tax Amount :

      <input type="text" name="taxAmount" id="taxAmount" onclick="processOrder()" value="">

    Order Total :

      <input type="text" name="orderTotal" id="orderTotal" value="">


问:
@Transaction method calling ReactiveCassandraRepository.insert with flux does not rollback all if one element fails

spring-data-cassandra version 3.4.6

spring-boot version 2.7.7

cassandra version 3.11

DataStax Java driver 3.10.0

We have a Controller method POST /all calling a service class with a transactional method inserting a Flux of simple versioned entities:

Controller

```<code>@PostMapping("/all")
@Operation(summary = "Create all data for the request account")
public Flux<SampleCassandraData> create(@RequestBody Flux<SampleCassandraData> datas,
                                        RequestContext context) {

    datas = datas.doOnNext(data -> data.setAccountId(context.getAccountId()));

    return service.create(datas);
}

</code>```

Service method

```<code>@Transactional
public Flux<SampleCassandraData> create(@NonNull Flux<SampleCassandraData> datas) {
    return repository.insert(datas);
}
</code>```

The entity:

```<code>@Table("sample_table")
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class SampleCassandraData {

    @PrimaryKeyColumn(name = "account_id", type = PARTITIONED)
    @EqualsAndHashCode.Include
    private String accountId;

    @PrimaryKeyColumn(name = "id", type = CLUSTERED, ordering = ASCENDING)
    @EqualsAndHashCode.Include
    private UUID id;

    @Column("content")
    private String content;

    @Version
    private Long version;
}
</code>```

We have an integration test using cassandra test container inserting an element and then sending an array of 2 elements including the existing one. The expected response status is 409 CONFLICT with an OptimisticLockingFailureException in the logs and no data inserted.

```<code>@Test
void when_POST_all_with_duplicated_in_1st_then_CONFLICT() {
    val existingData = given_single_created();
    datas.set(0, existingData);

    val newData = given_new_data();
    datas.set(1, newData);

    when_create_all(datas);

    then_error_json_returned(response, CONFLICT);

    then_data_not_saved(newData);
}

</code>```

Test results:

HttpStatus is 409 CONFLICT as expected

Response json body is our error response as expected

Service logs show the OptimisticLockingFailureException stacktrace as expected

Test fails: newData was saved in Cassandra when we expected the transaction to be fully rollbacked.

What are we doing wrong?
Is there a configuration, annotation field we must set to enable full rollback?
Or is it the reactive nature and we can't expect full rollback?

Thanks in advance

Body:
spring-data-cassandra version 3.4.6

spring-boot version 2.7.7

cassandra version 3.11

DataStax Java driver 3.10.0

We have a Controller method POST /all calling a service class with a transactional method inserting a Flux of simple versioned entities:

Controller

@PostMapping("/all")
@Operation(summary = "Create all data for the request account")
public Flux<SampleCassandraData> create(@RequestBody Flux<SampleCassandraData> datas,
                                        RequestContext context) {

    datas = datas.doOnNext(data -> data.setAccountId(context.getAccountId()));

    return service.create(datas);
}

Service method

@Transactional
public Flux<SampleCassandraData> create(@NonNull Flux<SampleCassandraData> datas) {
    return repository.insert(datas);
}

The entity:

@Table("sample_table")
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class SampleCassandraData {

    @PrimaryKeyColumn(name = "account_id", type = PARTITIONED)
    @EqualsAndHashCode.Include
    private String accountId;

    @PrimaryKeyColumn(name = "id", type = CLUSTERED, ordering = ASCENDING)
    @EqualsAndHashCode.Include
    private UUID id;

    @Column("content")
    private String content;

    @Version
    private Long version;
}

We have an integration test using cassandra test container inserting an element and then sending an array of 2 elements including the existing one. The expected response status is 409 CONFLICT with an OptimisticLockingFailureException in the logs and no data inserted.

@Test
void when_POST_all_with_duplicated_in_1st_then_CONFLICT() {
    val existingData = given_single_created();
    datas.set(0, existingData);

    val newData = given_new_data();
    datas.set(1, newData);

    when_create_all(datas);

    then_error_json_returned(response, CONFLICT);

    then_data_not_saved(newData);
}

Test results:

HttpStatus is 409 CONFLICT as expected

Response json body is our error response as expected

Service logs show the OptimisticLockingFailureException stacktrace as expected

Test fails: newData was saved in Cassandra when we expected the transaction to be fully rollbacked.

What are we doing wrong?
Is there a configuration, annotation field we must set to enable full rollback?
Or is it the reactive nature and we can't expect full rollback?

Thanks in advance


问:
ConnectionReset error message while receiving data through socket
I'm new to Rust and have implemented a network receiver thread where in I'm testing my implementation by sending data to the same socket address the receiver socket is bound to(making use of dynamic binding by binding the socket to port 0). But I'm getting thread 'google' panicked at 'Didn't receive data: Os { code: 10054, kind: ConnectionReset, message: "An existing connection was forcibly closed by the remote host." }', src\ethernet_interface.rs:62:42. This is my code

src/main.rs

```<code>mod ethernet_interface;
mod WWW_sim_interface;

use crate::WWW_sim_interface::WWWSimInterface;
use std::{thread, time};

fn main() {
    let www_sim_interface = WWWSimInterface::new(String::from("google"));
    let mut www_sim_interface_runnable = www_sim_interface.start();

    let two_seconds = time::Duration::from_secs(2);

    thread::sleep(two_seconds);

    www_sim_interface_runnable.terminate_WWW_sim();

    www_sim_interface_runnable.join_handle.join();
}
</code>```

src/WWW_sim_interface.rs

```<code>use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use std::thread;
use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    };
use std::mem;

use crate::ethernet_interface::EthernetInterface;

pub struct WWWSimInterface {
    target_ID: String,
    terminate_flag: AtomicBool,
    eth_interface: Option<EthernetInterface>,
}

pub struct RunningWWWSimInterface {
    pub join_handle: thread::JoinHandle<()>,
    WWW_sim_interface: Arc<WWWSimInterface>,
}

impl WWWSimInterface {

    pub fn new(target_ID: String) -> WWWSimInterface {
        let mut WWW_sim_interface = WWWSimInterface {
            target_ID: target_ID,
            terminate_flag: AtomicBool::new(false),
            eth_interface: Some(EthernetInterface::new()),
        };

        WWW_sim_interface.eth_interface.as_mut().expect("Error").setup_receiver(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0));

        WWW_sim_interface
    }

    pub fn start(self) -> RunningWWWSimInterface {
        let WWW_sim_interface = Arc::new(self);
        let join_handle = {
            let WWW_sim_interface = WWW_sim_interface.clone();
            thread::Builder::new().name(WWW_sim_interface.target_ID.clone()).spawn(move || WWW_sim_interface.run()).ok().unwrap()
        };

        RunningWWWSimInterface {
            join_handle,
            WWW_sim_interface,
        }
    }

    pub fn run(&self) {
        let mut buff: [u8; 2048] = [0; 2048];
        let mut msg_ID: u16;

        println!("started receiver thread");
        while !self.terminate_flag.load(Ordering::Relaxed) {
            let data_len = self.eth_interface.as_ref().expect("Error").recv_data(&mut buff);
            if data_len < 2 {
                continue;
            }

            let vec_buff = buff[..data_len].to_vec();

            let (int_bytes, rest) = buff.split_at(mem::size_of::<u16>());
            msg_ID = u16::from_be_bytes(int_bytes.try_into().unwrap());
            if msg_ID == 1234 {
                break;
            }
        }
    }
}

impl RunningWWW_simInterface {

    pub fn terminate_WWWSim(&mut self) {
        self.WWW_sim_interface.terminate_flag.store(true, Ordering::Relaxed);

        let msg_ID: u16 = 1234;

        // self.WWW_sim_interface.eth_interface.as_ref().expect("Error").send_data(&msg_ID.to_be_bytes());
        self.WWW_sim_interface.eth_interface.as_ref().expect("Error").send_self(&msg_ID.to_be_bytes());
    }
}
</code>```

src/ethernet_interface.rs

```<code>use std::net::{UdpSocket, SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr};
use std::net::IpAddr::V4;
use std::net::IpAddr::V6;

pub struct EthernetInterface {
    socket: Option<UdpSocket>,

    recv_IP_sock_addr: Option<SocketAddr>,
    send_IP_sock_addr: Option<SocketAddr>,
}

impl EthernetInterface {
    pub fn new() -> EthernetInterface {
        EthernetInterface {
            socket: None,
            recv_IP_sock_addr: None,
            send_IP_sock_addr: None,
        }
    }

    pub fn setup_receiver(&mut self, mut recv_IP_sock_addr: SocketAddr) {
        let ip_addr = recv_IP_sock_addr.ip();

        let first_octect: u8 = match ip_addr {
            V4(ip4_addr) => ip4_addr.octets().to_vec()[0],
            V6(ip6_addr) => ip6_addr.octets().to_vec()[0]
        };

        if first_octect > 223 && first_octect < 240 {
            match ip_addr {
                V4(ip4_addr) => recv_IP_sock_addr.set_ip(IpAddr::V4(Ipv4Addr::UNSPECIFIED)),
                V6(ip6_addr) => recv_IP_sock_addr.set_ip(IpAddr::V6(Ipv6Addr::UNSPECIFIED))
            };
        }
        self.recv_IP_sock_addr = Some(recv_IP_sock_addr);
        self.socket = Some(UdpSocket::bind(self.recv_IP_sock_addr.unwrap()).unwrap());

        if first_octect > 223 && first_octect < 240 {
            let ip_addr = self.recv_IP_sock_addr.unwrap().ip();
            match ip_addr {
                V4(ip4_addr) => self.socket.as_ref().unwrap().join_multicast_v4(&ip4_addr, &Ipv4Addr::UNSPECIFIED).ok(),
                V6(ip6_addr) => self.socket.as_ref().unwrap().join_multicast_v6(&ip6_addr, 0).ok()
            };
        }
    }

    pub fn setup_sender(&mut self, send_IP_sock_addr: SocketAddr) {
        let ip_addr = send_IP_sock_addr.ip();
        let first_octect = match ip_addr {
            V4(ip4_addr) => ip4_addr.octets().to_vec()[0],
            V6(ip6_addr) => ip6_addr.octets().to_vec()[0]
        };
        self.send_IP_sock_addr = Some(send_IP_sock_addr);
        if first_octect > 223 && first_octect < 240 {
            self.socket.as_ref().unwrap().set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
            self.socket.as_ref().unwrap().set_multicast_ttl_v4(8).expect("set_multicast_ttl_v4 call failed");
        }
    }

    pub fn recv_data(&self, buff: &mut [u8]) -> usize {
        let (number_of_bytes, src_addr) = self.socket.as_ref().unwrap().recv_from(buff)
                                        .expect("Didn't receive data");

        println!("recvd data");

        number_of_bytes
    }

    pub fn send_data(&self, buff: &[u8]) {
        self.socket.as_ref().unwrap().send_to(buff, self.send_IP_sock_addr.unwrap()).expect("couldn't send data");
    }

    pub fn get_host_bound_port(&self) -> u16 {
        self.socket.as_ref().unwrap().local_addr().unwrap().port()
    }

    pub fn get_src_addr(&mut self) {
        let mut buff: [u8; 2048] = [0; 2048];
        let (_, src_addr) = self.socket.as_ref().unwrap().recv_from(&mut buff)
                                        .expect("Didn't receive data");
        self.send_IP_sock_addr = Some(src_addr);
    }

    pub fn send_self(&self, buff: &[u8]) {
        self.socket.as_ref().unwrap().send_to(buff, self.recv_IP_sock_addr.unwrap()).expect("couldn't end self data");

        println!("sent data");
    }
}
</code>```

Body:
I'm new to Rust and have implemented a network receiver thread where in I'm testing my implementation by sending data to the same socket address the receiver socket is bound to(making use of dynamic binding by binding the socket to port 0). But I'm getting thread 'google' panicked at 'Didn't receive data: Os { code: 10054, kind: ConnectionReset, message: "An existing connection was forcibly closed by the remote host." }', src\ethernet_interface.rs:62:42. This is my code

src/main.rs

mod ethernet_interface;
mod WWW_sim_interface;

use crate::WWW_sim_interface::WWWSimInterface;
use std::{thread, time};

fn main() {
    let www_sim_interface = WWWSimInterface::new(String::from("google"));
    let mut www_sim_interface_runnable = www_sim_interface.start();

    let two_seconds = time::Duration::from_secs(2);

    thread::sleep(two_seconds);

    www_sim_interface_runnable.terminate_WWW_sim();

    www_sim_interface_runnable.join_handle.join();
}

src/WWW_sim_interface.rs

use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use std::thread;
use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    };
use std::mem;

use crate::ethernet_interface::EthernetInterface;

pub struct WWWSimInterface {
    target_ID: String,
    terminate_flag: AtomicBool,
    eth_interface: Option<EthernetInterface>,
}

pub struct RunningWWWSimInterface {
    pub join_handle: thread::JoinHandle<()>,
    WWW_sim_interface: Arc<WWWSimInterface>,
}

impl WWWSimInterface {

    pub fn new(target_ID: String) -> WWWSimInterface {
        let mut WWW_sim_interface = WWWSimInterface {
            target_ID: target_ID,
            terminate_flag: AtomicBool::new(false),
            eth_interface: Some(EthernetInterface::new()),
        };

        WWW_sim_interface.eth_interface.as_mut().expect("Error").setup_receiver(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0));

        WWW_sim_interface
    }

    pub fn start(self) -> RunningWWWSimInterface {
        let WWW_sim_interface = Arc::new(self);
        let join_handle = {
            let WWW_sim_interface = WWW_sim_interface.clone();
            thread::Builder::new().name(WWW_sim_interface.target_ID.clone()).spawn(move || WWW_sim_interface.run()).ok().unwrap()
        };

        RunningWWWSimInterface {
            join_handle,
            WWW_sim_interface,
        }
    }

    pub fn run(&self) {
        let mut buff: [u8; 2048] = [0; 2048];
        let mut msg_ID: u16;

        println!("started receiver thread");
        while !self.terminate_flag.load(Ordering::Relaxed) {
            let data_len = self.eth_interface.as_ref().expect("Error").recv_data(&mut buff);
            if data_len < 2 {
                continue;
            }

            let vec_buff = buff[..data_len].to_vec();

            let (int_bytes, rest) = buff.split_at(mem::size_of::<u16>());
            msg_ID = u16::from_be_bytes(int_bytes.try_into().unwrap());
            if msg_ID == 1234 {
                break;
            }
        }
    }
}

impl RunningWWW_simInterface {

    pub fn terminate_WWWSim(&mut self) {
        self.WWW_sim_interface.terminate_flag.store(true, Ordering::Relaxed);

        let msg_ID: u16 = 1234;

        // self.WWW_sim_interface.eth_interface.as_ref().expect("Error").send_data(&msg_ID.to_be_bytes());
        self.WWW_sim_interface.eth_interface.as_ref().expect("Error").send_self(&msg_ID.to_be_bytes());
    }
}

src/ethernet_interface.rs

use std::net::{UdpSocket, SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr};
use std::net::IpAddr::V4;
use std::net::IpAddr::V6;

pub struct EthernetInterface {
    socket: Option<UdpSocket>,

    recv_IP_sock_addr: Option<SocketAddr>,
    send_IP_sock_addr: Option<SocketAddr>,
}

impl EthernetInterface {
    pub fn new() -> EthernetInterface {
        EthernetInterface {
            socket: None,
            recv_IP_sock_addr: None,
            send_IP_sock_addr: None,
        }
    }

    pub fn setup_receiver(&mut self, mut recv_IP_sock_addr: SocketAddr) {
        let ip_addr = recv_IP_sock_addr.ip();

        let first_octect: u8 = match ip_addr {
            V4(ip4_addr) => ip4_addr.octets().to_vec()[0],
            V6(ip6_addr) => ip6_addr.octets().to_vec()[0]
        };

        if first_octect > 223 && first_octect < 240 {
            match ip_addr {
                V4(ip4_addr) => recv_IP_sock_addr.set_ip(IpAddr::V4(Ipv4Addr::UNSPECIFIED)),
                V6(ip6_addr) => recv_IP_sock_addr.set_ip(IpAddr::V6(Ipv6Addr::UNSPECIFIED))
            };
        }
        self.recv_IP_sock_addr = Some(recv_IP_sock_addr);
        self.socket = Some(UdpSocket::bind(self.recv_IP_sock_addr.unwrap()).unwrap());

        if first_octect > 223 && first_octect < 240 {
            let ip_addr = self.recv_IP_sock_addr.unwrap().ip();
            match ip_addr {
                V4(ip4_addr) => self.socket.as_ref().unwrap().join_multicast_v4(&ip4_addr, &Ipv4Addr::UNSPECIFIED).ok(),
                V6(ip6_addr) => self.socket.as_ref().unwrap().join_multicast_v6(&ip6_addr, 0).ok()
            };
        }
    }

    pub fn setup_sender(&mut self, send_IP_sock_addr: SocketAddr) {
        let ip_addr = send_IP_sock_addr.ip();
        let first_octect = match ip_addr {
            V4(ip4_addr) => ip4_addr.octets().to_vec()[0],
            V6(ip6_addr) => ip6_addr.octets().to_vec()[0]
        };
        self.send_IP_sock_addr = Some(send_IP_sock_addr);
        if first_octect > 223 && first_octect < 240 {
            self.socket.as_ref().unwrap().set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
            self.socket.as_ref().unwrap().set_multicast_ttl_v4(8).expect("set_multicast_ttl_v4 call failed");
        }
    }

    pub fn recv_data(&self, buff: &mut [u8]) -> usize {
        let (number_of_bytes, src_addr) = self.socket.as_ref().unwrap().recv_from(buff)
                                        .expect("Didn't receive data");

        println!("recvd data");

        number_of_bytes
    }

    pub fn send_data(&self, buff: &[u8]) {
        self.socket.as_ref().unwrap().send_to(buff, self.send_IP_sock_addr.unwrap()).expect("couldn't send data");
    }

    pub fn get_host_bound_port(&self) -> u16 {
        self.socket.as_ref().unwrap().local_addr().unwrap().port()
    }

    pub fn get_src_addr(&mut self) {
        let mut buff: [u8; 2048] = [0; 2048];
        let (_, src_addr) = self.socket.as_ref().unwrap().recv_from(&mut buff)
                                        .expect("Didn't receive data");
        self.send_IP_sock_addr = Some(src_addr);
    }

    pub fn send_self(&self, buff: &[u8]) {
        self.socket.as_ref().unwrap().send_to(buff, self.recv_IP_sock_addr.unwrap()).expect("couldn't end self data");

        println!("sent data");
    }
}


问:
eslint fails when using i18nOptions keyPrefix to prefix key from locale file
In vue component it is possible to use keyPrefix of i18n in order to use a shorter path to the translated key.

So, for example if my lang file looks like that:

```<code>{"a":{"b":{"c":{"placeholder": "my placeholder"}}}}
</code>```

and in my vue component, set i18nOptions like that:

```<code>export default {
i18nOptions: {
    keyPrefix: 'a.b.c',
},
</code>```

I am able to consume the key like that:

```<code>$t(`placeholder`)
</code>```

it works great! the problem is that eslint won't allow that (@intlify/vue-i18n/no-missing-keys)

I didn't find any way to teach eslint to handle that correctly...

did anyone manage to do it?

Body:
In vue component it is possible to use keyPrefix of i18n in order to use a shorter path to the translated key.

So, for example if my lang file looks like that:

{"a":{"b":{"c":{"placeholder": "my placeholder"}}}}

and in my vue component, set i18nOptions like that:

export default {
i18nOptions: {
    keyPrefix: 'a.b.c',
},

I am able to consume the key like that:

$t(`placeholder`)

it works great! the problem is that eslint won't allow that (@intlify/vue-i18n/no-missing-keys)

I didn't find any way to teach eslint to handle that correctly...

did anyone manage to do it?


问:
React Nodejs Express Server Cannot GET
I'm developing my first full-stack project. I developed the client side and server side. You can see the code down. When I run the client (Front end side ) it is working in localhost. Then when I ran the backend side I got a 'Cannot GET' message. Any idea about this?

Index.js

```<code>const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const authRoute = require("./routes/auth");
const userRoute = require("./routes/users");
const postRoute = require("./routes/posts");
const categoryRoute = require("./routes/categories");
const multer = require("multer");
const path = require("path");

dotenv.config();
app.use(express.json());
app.use("/images", express.static(path.join(__dirname, "/images")));

mongoose.connect(process.env.MONGO_URL).then(console.log('Connected to mongo')).catch(err=>console.log(err));

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "images");
  },
  filename: (req, file, cb) => {
    cb(null, req.body.name);
  },
});

const upload = multer({ storage: storage });
app.post("/api/upload", upload.single("file"), (req, res) => {
  res.status(200).json("File has been uploaded");
});

app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/posts", postRoute);
app.use("/api/categories", categoryRoute);

app.listen("3000", () => {
  console.log("Backend is running.");
});
</code>```

Home.jsx

```<code>import React from 'react'
import Header from '../../components/header/Header'
import Posts from '../../components/posts/Posts'
import Sidebar from '../../components/sidebar/Sidebar'
import axios from "axios";
import { useEffect, useState } from "react";

export default function Home() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const fetchPosts = async () => {
      const res = await axios.get("/posts");
      console.log(res)
      setPosts(res.data);
    };
    fetchPosts();
  });
  return (
    <>
    <div className="mt-8">

    <Header/>
    </div>

    <div className="container">
      <div className="row mt-5">
        <div className="col-lg-4 col-md-4">
        <Posts posts={posts}/>
        </div>
        <div className="col-lg-4 col-md-4 ms-auto">
          <Sidebar/>
        </div>
      </div>
    </div>
    </>
  )
}
</code>```

I added proxy to package.json file. (Client side).

```<code> "proxy": "http://localhost:3000/api/",
</code>```

Title: React Nodejs Express Server Cannot GET

Body:
I'm developing my first full-stack project. I developed the client side and server side. You can see the code down. When I run the client (Front end side ) it is working in localhost. Then when I ran the backend side I got a 'Cannot GET' message. Any idea about this?

Index.js

const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const authRoute = require("./routes/auth");
const userRoute = require("./routes/users");
const postRoute = require("./routes/posts");
const categoryRoute = require("./routes/categories");
const multer = require("multer");
const path = require("path");

dotenv.config();
app.use(express.json());
app.use("/images", express.static(path.join(__dirname, "/images")));

mongoose.connect(process.env.MONGO_URL).then(console.log('Connected to mongo')).catch(err=>console.log(err));

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "images");
  },
  filename: (req, file, cb) => {
    cb(null, req.body.name);
  },
});

const upload = multer({ storage: storage });
app.post("/api/upload", upload.single("file"), (req, res) => {
  res.status(200).json("File has been uploaded");
});

app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/posts", postRoute);
app.use("/api/categories", categoryRoute);

app.listen("3000", () => {
  console.log("Backend is running.");
});

Home.jsx

import React from 'react'
import Header from '../../components/header/Header'
import Posts from '../../components/posts/Posts'
import Sidebar from '../../components/sidebar/Sidebar'
import axios from "axios";
import { useEffect, useState } from "react";

export default function Home() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const fetchPosts = async () => {
      const res = await axios.get("/posts");
      console.log(res)
      setPosts(res.data);
    };
    fetchPosts();
  });
  return (
    <>

        <Posts posts={posts}/>

          <Sidebar/>

    </>
  )
}

I added proxy to package.json file. (Client side).

 "proxy": "http://localhost:3000/api/",


问:
Simulate global variable access with Claripy
I need to simulate this decompiled line of code in a Python script using claripy as solver engine,

```<code>*(ulong *)(global_variable + (ulong)((uint)local_variable[local_inedx + 1] & 1) * 8)
</code>```

global_variable is basically an array cointaining a 0 and an integer and the local_variable is an array populated with 4 bytes symbolic variables that will be evaluated.

```<code>pwndbg> x/gx <global_variable address>
0x...70 <global_variable>:  0x0000000000000000
0x...78 <global_variable+8>:    0x000000009908b0df
</code>```

As I've understood, depending on the & between the local variable value and 1 the code is resolved with 0 or the integer stored in global_variable+8.

I thought I'd use the claripy.If operations as below, but there's no way to satisfy the solver constraint.

claripy.If(local_variable[local_inedx + 1] & 1 == 1, claripy.BVV(0x9908b0df,32), claripy.BVV(0, 32))
```

As far as there could be other reason that implies the unsatisfied constraint I would like to know if this is the correct way to simulate read access to the global variables using claripy or there are other ways.

Body:
I need to simulate this decompiled line of code in a Python script using claripy as solver engine,

*(ulong *)(global_variable + (ulong)((uint)local_variable[local_inedx + 1] & 1) * 8)

global_variable is basically an array cointaining a 0 and an integer and the local_variable is an array populated with 4 bytes symbolic variables that will be evaluated.

pwndbg> x/gx <global_variable address>
0x...70 <global_variable>:  0x0000000000000000
0x...78 <global_variable+8>:    0x000000009908b0df

As I've understood, depending on the & between the local variable value and 1 the code is resolved with 0 or the integer stored in global_variable+8.

I thought I'd use the claripy.If operations as below, but there's no way to satisfy the solver constraint.

claripy.If(local_variable[local_inedx + 1] & 1 == 1, claripy.BVV(0x9908b0df,32), claripy.BVV(0, 32))

As far as there could be other reason that implies the unsatisfied constraint I would like to know if this is the correct way to simulate read access to the global variables using claripy or there are other ways.


问:
Retrieve the OUT Parameter of SP Routine
Please, how do I retrieve an OUT parameter of MySQL Stored Procedure in NodeJS? I wanted to retrieve the 4 OUT parameter of Stored Procedure.

My Stored Procedure works fine, and it takes 6 IN parameters and return 4 OUT parameters. Below is my NodeJS code.

```<code> query = `SET @initiatorName = ''; @initiatorEmail = ''; @initiatorPhone = '';
    @initiatorWhatsApp = ''; CALL AcceptBookingInitiationRequest_SP(?, ?,?,?,?,?, @initiatorName, @initiatorEmail, @initiatorPhone, @initiatorWhatsApp); SELECT @initiatorName, @initiatorEmail, @initiatorPhone, @initiatorWhatsApp`;
`;

conn.query(query, [bookinginitiationrequest_ID, bookingInitiatedTo,
            beneficiary_ID, no_Of_Box_Allotted, loggedIP, recordAddedBy], function(err, results) {
                if(err) {
                   return "Could not add beneficiary to Slot.";
                }
                else{

                    const beneficiaryContactDetails = {
                        fullname: results[0],
                        email: "",
                        phone: "",
                        whatsapp: "",
                    }

                    return beneficiaryContactDetails;
                }
            });

</code>```

The above code returned no error, but my challenge is how to access the returned results of the OUT parameter to the object I created.

Body:
Please, how do I retrieve an OUT parameter of MySQL Stored Procedure in NodeJS? I wanted to retrieve the 4 OUT parameter of Stored Procedure.

My Stored Procedure works fine, and it takes 6 IN parameters and return 4 OUT parameters. Below is my NodeJS code.

 query = `SET @initiatorName = ''; @initiatorEmail = ''; @initiatorPhone = '';
    @initiatorWhatsApp = ''; CALL AcceptBookingInitiationRequest_SP(?, ?,?,?,?,?, @initiatorName, @initiatorEmail, @initiatorPhone, @initiatorWhatsApp); SELECT @initiatorName, @initiatorEmail, @initiatorPhone, @initiatorWhatsApp`;
`;

conn.query(query, [bookinginitiationrequest_ID, bookingInitiatedTo,
            beneficiary_ID, no_Of_Box_Allotted, loggedIP, recordAddedBy], function(err, results) {
                if(err) {
                   return "Could not add beneficiary to Slot.";
                }
                else{

                    const beneficiaryContactDetails = {
                        fullname: results[0],
                        email: "",
                        phone: "",
                        whatsapp: "",
                    }

                    return beneficiaryContactDetails;
                }
            });

The above code returned no error, but my challenge is how to access the returned results of the OUT parameter to the object I created.


问:
Add metadata via REST API Call in Alfresco Community
Is it possible to add different metadata to a document via rest call?

thank you

I tried to upload a document to alfresco using rest call but now i want to add some metadata to that document and search for it by its properties.


问:
spaCy version 3 cannot add 'negative' example, how can I resolve?
In spaCy 3, we now train our model with the configuration system, and we need to use DocBin.to_disk("any_name.spacy") to export the training data.

The problem is, we need to first create Span objects to store the entites in the text, and then assign them to doc.ents. During this process, if there are no entities marked in the text, doc.char_span(0,0,"LABEL") (0,0, because there is no entity) will return None, and this cannot be appended into the DocBin.

In simple terms, I cannot add any negative examples into my training data. Have anyone figure out a way to add negative example into their data?

I tried doc.char_span(0,0,"NO_ENTITY") as a place holder and see if it returns a span as "", not it doesn't work.


问:
Why do "align-items: flex-start" and "flex-wrap: wrap" mess with my elements?
I have a box (div.rack) in my application with icons.

Here's the rack style :

.rack {
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
}
```

(the rack has a fixed height)

This is driving me nuts but why are the wrapped icons not all at the top?

Body:
I have a box (div.rack) in my application with icons.

Here's the rack style :

.rack {
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
}

(the rack has a fixed height)

This is driving me nuts but why are the wrapped icons not all at the top?


问:
CSRF Violation with Oathkeeper/Kratos in AWS Cloud
Merry Christmas Everyone!

I am trying to set up Ory Kratos with Oathkeeper in a AWS Cloud.

My problem is that I can't get the CSRF validation to work properly.

I've spent days figuring out whats causing issues without any success.

Please refer to this github post

Any help is appreciated!

I've tried everything mentioned in the docs CSRF pitfalls


问:
Add a line graph to an HTML webpage using the data from a real-time database in Firebase
I am doing a project that requires me to add a line graph in an html webpage. The data that will be displayed on my graph comes from a sensor that I connected to a real-time database in Firebase.

So what would be the easiest way for me to create such line graph?

I have tried using a simple line graph example directly from Chart.js and that worked. But again the data of the actual graph needs to be updated in real-time as well since it should refer to the data coming thru my real-time database...


问:
Defining a generic method
I was wondering if I could create a method outside a class in Python.
For example, in this supposed method I wanted to create references to an integer number, and check whether or not it is prime.

The code I'd like to create would be something like this:

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

    for x in range(1, self):
        if self % x == 0:
            return False

    return True
</code>```

self is the integer number to which the method is applied.
So a theoretical use of this would be:

```<code>random_integer: int = 53

if random_integer.is_prime():
    print(f"{random_integer} is a prime number.")
else:
    print(f"{random_integer} is not prime.")
</code>```

A way I tried to implement this was by writing this code:

```<code>class Number(float):

    def __init__(self, num):
        self.__num = num

    def is_prime(self):
        root = round(self.__num**0.5)
        for x in range(2, root):
            if self.__num % x == 0 and x < root:
                return False
        return True

var = Number(54)
print(var.is_prime())  # --> returns False
</code>```

Is it possible to create generic methods (or methods that only apply to certain types - e.g. int, float, str) in Python?
Or are we 'stuck' with functions that only take them as parameters and don't use self?

I'm a beginner programmer, so please be clear with your answers :) and thanks in advance!

Title: Defining a generic method

Body:
I was wondering if I could create a method outside a class in Python.
For example, in this supposed method I wanted to create references to an integer number, and check whether or not it is prime.

The code I'd like to create would be something like this:

def is_prime(self):

    for x in range(1, self):
        if self % x == 0:
            return False

    return True

self is the integer number to which the method is applied.
So a theoretical use of this would be:

random_integer: int = 53

if random_integer.is_prime():
    print(f"{random_integer} is a prime number.")
else:
    print(f"{random_integer} is not prime.")

A way I tried to implement this was by writing this code:

class Number(float):

    def __init__(self, num):
        self.__num = num

    def is_prime(self):
        root = round(self.__num**0.5)
        for x in range(2, root):
            if self.__num % x == 0 and x < root:
                return False
        return True

var = Number(54)
print(var.is_prime())  # --> returns False

Is it possible to create generic methods (or methods that only apply to certain types - e.g. int, float, str) in Python?
Or are we 'stuck' with functions that only take them as parameters and don't use self?

I'm a beginner programmer, so please be clear with your answers :) and thanks in advance!


问:
Is there a way to make timestamp always unique?
let's say I have multiple lists of objects (representing log-like record) containing the property returning a timestamp when they were created (it's simple datetime.now() record). My idea was that after I join all these objects to a single list, I sort them chronologically just by their "timestamp". They're not created in parallel (but by multiple class instances recursively), so I expected everytime I call datetime.now(), the record would be unique and sortable. The problem is that it seems the objects are created faster than datetime resolution can be enough, and many of the objects ends with the same "timestamp".

I made a workaround by adding another property "index" to the objects and separate counter, but it increased overall code complexity, I must watch out many places now to not forget counting, had to convert some static functions to instantiable etc...
Is there a clean way to create timestamp that is unique for any call, sortable and possibly able to reformat on print output using string.format? Thank you!


问:
How to keep object not move outside of other object
I am using fabric js to building a image editor. My need is i need to keep parent object not move out side of child object. i found a way to do that but when the object get rotated then its not works properly.

I tried like this.

maxLeft = child.left
minLeft = parent.left - ( child.width - parent.width )
maxTop = child.top
minTop = parent.top - ( child.height - parent.height )
its helps me to control object movement but when that object got rotated this not works well